text
stringlengths
1
1.05M
import React from "react"; import EditablePage from "@/components/editablePage/editablePage"; import { GetServerSideProps } from "next"; import { Block } from "@/components/editablePage/editablePage.type"; type PageProps = { pid: string blocks: Block[] err: boolean } export default function IndexPage ({ pid, blocks, err }: PageProps) { return <EditablePage id={pid} fetchedBlocks={blocks} err={err}/> } export const getServerSideProps: GetServerSideProps = async (context) => { const blocks = [{ tag: 'p', html: '' }]; const res = context.res; const req = context.req; try { const requestHeaders: HeadersInit = new Headers(); requestHeaders.set('Content-Type', 'application/json'); req.headers.cookie && requestHeaders.set('Cookie', req.headers.cookie); const response = await fetch(`${process.env.NEXT_PUBLIC_API}/pages`, { method: 'POST', credentials: 'include', headers: requestHeaders, body: JSON.stringify({ blocks: blocks }) }); const data = await response.json(); const pageId = data.pageId; const creator = data.creator; const query = !creator ? '?public=true' : ''; // show notice res.writeHead(302, { Location: `/p/${pageId}${query}` }); res.end(); return { props: {} }; } catch (err) { console.log(err); return { props: { blocks: [], pid: err, err: true} }; } }
//Chapter 07 //Temp 06 //透视投影范围 // 共冶一炉: PorjMatrix * ViewMatrix * ModelMatrix // 多次绘制图形 drawArrays执行多次即可 //vertex shader var VSHADER_SOURCE = ` attribute vec4 a_Position; attribute vec4 a_Color; // uniform mat4 u_ModelMatrix; //模型矩阵 // uniform mat4 u_ViewMatrix; //视图矩阵 // uniform mat4 u_ProjMatrix; //盒状可视范围 uniform mat4 u_MVPMatrix; //js中计算的结果矩阵 varying vec4 v_Color; void main() { // gl_Position = u_ProjMatrix * u_ViewMatrix * u_ModelMatrix * a_Position; gl_Position = u_MVPMatrix * a_Position; v_Color = a_Color; } `; //fragment shader var FSHADER_SOURCE = ` precision mediump float; varying vec4 v_Color; void main() { gl_FragColor = v_Color; } `; //main ready(loadWEBGL); //主程序 function loadWEBGL () { var canvas = document.getElementById('webgl'); if ( !canvas ) { console.error('Failed to get canvas-element!'); return ; } var webgl = canvas.getContext('webgl'); if ( !webgl ) { console.error('Failed to get canvas context: webgl!'); return ; } if ( !initShaders(webgl, VSHADER_SOURCE, FSHADER_SOURCE) ) { console.error('Failed to init shaders!'); return ; } var n = initBuffer(webgl); if ( n < 0 ) { console.error('Failed to init buffer!'); return ; } var ex = 0.0, ey = 0.0, ez = 5.0; // setViewMatrix(webgl, ex, ey, ez); // setPersProjMatrix(webgl, fov, aspect, near, far); //视图矩阵 var viewMat = new Matrix4(); viewMat.setLookAt(ex, ey, ez, 0.0, 0.0, -100, 0.0, 1.0, 0.0); //范围矩阵 var fov = 30, aspect = canvas.width/canvas.height; var near = 1.0, far = 100.0; var projMat = new Matrix4(); projMat.setPerspective(fov, aspect, near, far); //模型矩阵 var modelMat = new Matrix4(); var tx = 0.75, ty = 0.0, tz = 0.0; modelMat.setTranslate(tx, ty, tz); // => 在shader中计算 // setUniMat(webgl, 'u_ViewMatrix', viewMat); // setUniMat(webgl, 'u_ProjMatrix', projMat); // setUniMat(webgl, 'u_ModelMatrix', modelMat); // => 在js中计算 避免性能浪费 var mvpMatrix = new Matrix4(); mvpMatrix.set(projMat).multiply(viewMat).multiply(modelMat); setUniMat(webgl, 'u_MVPMatrix', mvpMatrix); webgl.clearColor(0.0, 0.0, 0.0, 1.0); webgl.clear(webgl.COLOR_BUFFER_BIT); //绘制右边 webgl.drawArrays(webgl.TRIANGLES, 0, n); //绘制左边 modelMat.setTranslate(-tx, ty, tz); mvpMatrix.set(projMat).multiply(viewMat).multiply(modelMat); setUniMat(webgl, 'u_MVPMatrix', mvpMatrix); webgl.drawArrays(webgl.TRIANGLES, 0, n); } function initBuffer (webgl) { var vertexData = new Float32Array([ //顶点坐标颜色 0.0, 0.5, -4, 0.4, 1.0, 0.4, -0.5, -0.5, -4, 0.4, 1.0, 0.4, 0.5, -0.5, -4, 1.0, 0.4, 0.4, 0.0, 0.5, -2, 1.0, 0.4, 0.4, -0.5,-0.5, -2, 1.0, 1.0, 0.4, 0.5, -0.5, -2, 1.0, 1.0, 0.4, 0.0, 0.5, 0.0, 0.4, 0.4, 1.0, -0.5, -0.5, 0.0, 0.4, 0.4, 1.0, 0.5, -0.5, 0.0, 1.0, 0.4, 0.4 ]); var n = vertexData.length/6; var FSIZE = vertexData.BYTES_PER_ELEMENT; var a_Position = webgl.getAttribLocation(webgl.program, 'a_Position'); var a_Color = webgl.getAttribLocation(webgl.program, 'a_Color'); var buffer = webgl.createBuffer(); webgl.bindBuffer(webgl.ARRAY_BUFFER, buffer); webgl.bufferData(webgl.ARRAY_BUFFER, vertexData, webgl.STATIC_DRAW); webgl.vertexAttribPointer(a_Position, 3, webgl.FLOAT, false, FSIZE*6, 0); webgl.vertexAttribPointer(a_Color, 3, webgl.FLOAT, false, FSIZE*6, FSIZE*3); webgl.enableVertexAttribArray(a_Position); webgl.enableVertexAttribArray(a_Color); return n; } /* // 设置盒装可视范围矩阵 // function setBoxProjMatrix (webgl, near, far) { // var u_ProjMatrix = webgl.getUniformLocation(webgl.program, 'u_ProjMatrix'); // var projMatrix = new Matrix4(); // projMatrix.setOrtho(-1, 1, -1, 1, near, far); // webgl.uniformMatrix4fv(u_ProjMatrix, false, projMatrix.elements); // return (near, far) => { // projMatrix.setOrtho(-1, 1, -1, 1, near, far); // webgl.uniformMatrix4fv(u_ProjMatrix, false, projMatrix.elements); // }; // } // 设置投影可视范围矩阵 // function setPersProjMatrix (webgl, fov, aspect, near, far) { // var u_ProjMatrix = webgl.getUniformLocation(webgl.program, 'u_ProjMatrix'); // var projMatrix = new Matrix4(); // projMatrix.setPerspective(fov, aspect, near, far); // webgl.uniformMatrix4fv(u_ProjMatrix, false, projMatrix.elements); // return (near, far) => { // projMatrix.setPerspective(fov, aspect, near, far); // webgl.uniformMatrix4fv(u_ProjMatrix, false, projMatrix.elements); // }; // } // 设置视图矩阵 // function setViewMatrix (webgl, ex, ey, ez) { // var u_ViewMatrix = webgl.getUniformLocation(webgl.program, 'u_ViewMatrix'); // var viewMatrix = new Matrix4(); // viewMatrix.setLookAt(ex, ey, ez, 0.0, 0.0, -100, 0.0, 1.0, 0.0); // webgl.uniformMatrix4fv(u_ViewMatrix, false, viewMatrix.elements); // return (ex, ey, ez) => { // viewMatrix.setLookAt(ex, ey, ez, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); // webgl.uniformMatrix4fv(u_ViewMatrix, false, viewMatrix.elements); // }; // } // 设置模型矩阵 // function setTranslateMatrix (webgl, tx, ty, tz) { // var u_ModelMatrix = webgl.getUniformLocation(webgl.program, 'u_ModelMatrix'); // var modelMatrix = new Matrix4(); // modelMatrix.setTranslate(tx, ty, tz); // webgl.uniformMatrix4fv(u_ModelMatrix, false, modelMatrix.elements); // return (tx, ty, tz) => { // modelMatrix.setTranslate(tx, ty, tz); // webgl.uniformMatrix4fv(u_ModelMatrix, false, modelMatrix.elements); // }; // } */ // 优化代码 对指定着色器变量-矩阵赋值 function setUniMat ( webgl, name, mat ) { var uniformMat = webgl.getUniformLocation(webgl.program, name); webgl.uniformMatrix4fv(uniformMat, false, mat.elements); }
<gh_stars>0 #ifndef ASSESSMENTPAGE_H #define ASSESSMENTPAGE_H #include "assessment.h" #include "student.h" #include "course.h" #include "studentcourselink.h" #include "user.h" #include "vector" #include <QMainWindow> #include <QListWidgetItem> namespace Ui { class AssessmentPage; } class AssessmentPage : public QMainWindow { Q_OBJECT public: explicit AssessmentPage(QWidget *parent = nullptr); ~AssessmentPage(); void loadStudents(); void loadCourses(); void loadAssessments(); void loadFiles(); void clearAll(); public slots: void receiveStudent(Student s); void receiveEmployee(person::Employee e); private slots: void on_ListStudents_itemClicked(QListWidgetItem *item); void on_ListCourses_itemClicked(QListWidgetItem *item); void on_ListAssessments_itemClicked(QListWidgetItem *item); void on_BtnAssessment_clicked(); void on_BtnAddAssessment_clicked(); void on_BtnSave_clicked(); void on_BtnSubmission_clicked(); void on_BtnAssessmentUpload_clicked(); void on_BtnSubmissionUpload_clicked(); void on_BoxMarksSubmission_textChanged(const QString &arg1); void on_BtnSubmitMark_clicked(); void on_HomeButton_clicked(); void on_ResourcesButton_clicked(); void on_CourseButton_clicked(); void on_SignOutButton_clicked(); private: Ui::AssessmentPage *ui; Student currentStudent; person::Employee currentUser; size_t studentCount, count, degreeCount, courseCount, sdCount, scCount, aCount, subCount; std::vector<Student> students; std::vector<program::Course> course; std::vector<grade::Assessment> assessments; std::vector<grade::Submission> subs; slink::StudentDegreeLink sdlink[MAX_DEGREES]; slink::StudentCourseLink sclink[MAX_DEGREES]; Student* selectedStudent; program::Course *selectedCourse; grade::Assessment *selAssessment; grade::Submission *subSelected; }; #endif // ASSESSMENTPAGE_H
import Axios from 'axios' export const BASE_URL = 'http://localhost:5000/api' const Client = Axios.create({ baseURL: BASE_URL }) export default Client
from PyQt5 import QtCore from PyQt5.QtGui import QBrush, QColor, QFont, QFontMetrics, QPen from . import Drawer from ..themes import ThemeHolder class LineDrawer(Drawer): def __init__(self, painter) -> None: super().__init__(painter) def draw(self, data): vertex = data[0] pen = QPen(QColor(ThemeHolder.theme.currentPriceLineColor), 1, QtCore.Qt.DashLine) self.painter.setPen(pen) self.painter.drawLine( 0, self.getVerticalPosition(vertex.closePrice), self.width, self.getVerticalPosition(vertex.closePrice), ) text = str(vertex.closePrice) font = QFont("times", 12) fm = QFontMetrics(font) self.painter.setBrush(QBrush(QColor(ThemeHolder.theme.chartLineColor))) self.painter.drawRect( self.width - fm.width(text) - 5, self.getVerticalPosition(vertex.closePrice) - fm.height() / 2 - 2, fm.width(text) + 5, fm.height() + 1, ) pen = QPen(QColor(ThemeHolder.theme.textColor), 3) self.painter.setPen(pen) self.painter.setFont(font) self.painter.drawText(self.width - fm.width(text), (self.getVerticalPosition(vertex.closePrice) + fm.height() / 4), text)
<reponame>misakimichy/kombucha-bar import React, {Component} from 'react' import PropTypes from 'prop-types' import { Redirect } from 'react-router-dom' class EditKeg extends Component { state = { toHome: false } _name = React.createRef() _brand = React.createRef() _price = React.createRef() _flavor = React.createRef() handleEditForm = id => { this.props.onEditKeg(id, { name: this._name.value, brand: this._brand.value, price: parseInt(this._price.value), flavor: this._flavor.value, pints: 124 }) this.setState({ toHome: true }) } render() { const { toHome } = this.state if(toHome) return <Redirect to ='/' /> return( <main> <h1>Edit Keg</h1> <form onSubmit={this.handleEditForm}> <input id='kegName' name='kegName' type='text' placeholder={this.props.location.state.name} ref={input => {this._name = input}} /> <input id='kegBrand' name='kegBrand' type='text' placeholder={this.props.location.state.brand} ref={input => {this._brand = input}} /> <input id='kegPrice' name='kegPrice' type='number' min='0' placeholder={this.props.location.state.price} ref={input => {this._price = input}} /> <input id='kegFlavor' name='kegFlavor' type='text' placeholder={this.props.location.state.flavor} ref={input => {this._flavor = input}} /> <button type='submit'>Save the Change</button> </form> </main> ) } } EditKeg.propTypes = { id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, brand: PropTypes.string.isRequired, price: PropTypes.number.isRequired, flavor: PropTypes.string.isRequired, onEditKeg: PropTypes.func.isRequired } export default EditKeg
package weixin.popular.api; import java.nio.charset.Charset; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.entity.StringEntity; import weixin.popular.bean.BaseResult; import weixin.popular.bean.live.LiveAuditResult; import weixin.popular.bean.live.LiveGetApprovedGoodResult; import weixin.popular.bean.live.LiveGetGoodsWarehouseResult; import weixin.popular.bean.live.LiveGoodUpdateInfo; import weixin.popular.bean.live.LiveGoodsAddInfo; import weixin.popular.bean.live.LiveGoodsAddResult; import weixin.popular.bean.live.LiveGoodsIdArrayInfo; import weixin.popular.bean.live.LiveGoodsInfo; import weixin.popular.bean.live.LiveGoodsResetauditInfo; import weixin.popular.bean.live.LivePageInfo; import weixin.popular.bean.live.LiveRoomCreateInfo; import weixin.popular.bean.live.LiveRoomCreateResult; import weixin.popular.bean.live.LiveRoomGetInfoPage; import weixin.popular.bean.live.LiveRoomListInfo; import weixin.popular.bean.live.RoomAddGoodsInfo; import weixin.popular.client.LocalHttpClient; import weixin.popular.util.JsonUtil; public class LiveAPI extends BaseAPI{ /* * 小程序直播间创建接口 * add by wrs 20200731 * */ public static LiveRoomCreateResult room_create(String access_token, LiveRoomCreateInfo params) throws Exception{ String str = JsonUtil.toJSONString(params); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) .setUri(BASE_URI+"/wxaapi/broadcast/room/create") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .setEntity(new StringEntity(str,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,LiveRoomCreateResult.class); } /* * 删除直播间 * * */ public static BaseResult room_delete(Integer room_id, String access_token) throws Exception{ String paramJson = "{\"id\":"+room_id+"}"; HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) .setUri(BASE_URI+"/wxaapi/broadcast/room/deleteroom") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .setEntity(new StringEntity(paramJson,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,BaseResult.class); } /* * * 获取直播房间列表 * */ public static LiveRoomListInfo getliveinfo(String access_token, LiveRoomGetInfoPage params) throws Exception{ String str = JsonUtil.toJSONString(params); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) .setUri(BASE_URI+"/wxa/business/getliveinfo") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .setEntity(new StringEntity(str,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,LiveRoomListInfo.class); } /* * 往指定直播间导入已入库的商品 * * */ public static BaseResult room_add_goods(String access_token, RoomAddGoodsInfo params) throws Exception{ String str = JsonUtil.toJSONString(params); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) .setUri(BASE_URI+"/wxaapi/broadcast/room/addgoods") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .setEntity(new StringEntity(str,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,BaseResult.class); } /* * * 添加商品到直播商品库并审核 * * **/ public static LiveGoodsAddResult add_goods(String access_token, LiveGoodsAddInfo params) throws Exception{ String str = JsonUtil.toJSONString(params); String paramJson = "{\"goodsInfo\":"+str+"}"; HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) .setUri(BASE_URI+"/wxaapi/broadcast/goods/add") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .setEntity(new StringEntity(paramJson,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,LiveGoodsAddResult.class); } /* * 撤回直播商品的提审申请 * goods/resetaudit * */ public static BaseResult goods_resetaudit(String access_token, LiveGoodsResetauditInfo params) throws Exception{ String str = JsonUtil.toJSONString(params); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) .setUri(BASE_URI+"/wxaapi/broadcast/goods/resetaudit") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .setEntity(new StringEntity(str,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,BaseResult.class); } /* * 对已撤回提审的商品再次发起提审申请 * * * */ public static LiveAuditResult audit(String access_token, LiveGoodsInfo params) throws Exception{ String str = JsonUtil.toJSONString(params); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) .setUri(BASE_URI+"/wxaapi/broadcast/goods/audit") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .setEntity(new StringEntity(str,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,LiveAuditResult.class); } /* * * 删除【小程序直播】商品库中的商品,删除后直播间上架的该商品也将被同步删除,不可恢复; * */ public static BaseResult goods_delete(String access_token, LiveGoodsInfo params) throws Exception{ String str = JsonUtil.toJSONString(params); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) .setUri(BASE_URI+"/wxaapi/broadcast/goods/delete") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .setEntity(new StringEntity(str,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,BaseResult.class); } /* * * 更新商品 * 调用此接口可以更新商品信息,审核通过的商品仅允许更新价格类型与价格, * 审核中的商品不允许更新,未审核的商品允许更新所有字段, 只传入需要更新的字段。 * * */ public static BaseResult goods_update(String access_token, LiveGoodUpdateInfo params) throws Exception{ String str = JsonUtil.toJSONString(params); String paramJson = "{\"goodsInfo\":"+str+"}"; HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) .setUri(BASE_URI+"/wxaapi/broadcast/goods/update") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .setEntity(new StringEntity(paramJson,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,BaseResult.class); } /* * * 获取商品的信息与审核状态 * */ public static LiveGetGoodsWarehouseResult get_goods_warehouse(String access_token, LiveGoodsIdArrayInfo params) throws Exception{ String str = JsonUtil.toJSONString(params); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) .setUri(BASE_URI+"/wxa/business/getgoodswarehouse") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .setEntity(new StringEntity(str,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,LiveGetGoodsWarehouseResult.class); } /* * * 获取商品列表 * */ public static LiveGetApprovedGoodResult get_approved_goods(String access_token, LivePageInfo pageInfo) throws Exception{ HttpUriRequest httpUriRequest = RequestBuilder.get() .setHeader(jsonHeader) .setUri(BASE_URI+"/wxaapi/broadcast/goods/getapproved") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .addParameter("offset", String.valueOf(pageInfo.getOffset())) .addParameter("limit", String.valueOf(pageInfo.getLimit())) .addParameter("status", String.valueOf(pageInfo.getStatus())) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,LiveGetApprovedGoodResult.class); } }
#!/bin/bash [ -n "$TEMP" ] || export TEMP=/tmp export GOROOT="$HOME/go$GO_VERSION" export GOROOT_BOOTSTRAP="$HOME/gobootstrap$GO_VERSION" export GOPATH="$TEMP/gopath" export PATH="$GOROOT/bin:$PATH" env | grep -e ^GO -e ^PATH -e ^TRAVIS -e ^TEMP | sort [ -n "$TRAVIS_BUILD_DIR" ] || exit 2 [ -n "$TRAVIS_REPO_SLUG" ] || exit 3 [ -n "$GOOS" ] || exit 4 [ -n "$GOARCH" ] || exit 5 [ -d "$TEMP" ] || exit 1 [ -d "$GOROOT" ] || exit 6 [ -d "$GOROOT_BOOTSTRAP" ] || exit 7 which go go version || exit 8 # setup cross compile environment if [ "${GOOS}_${GOARCH}" != "$(go env GOHOSTOS)_$(go env GOHOSTARCH)" ]; then if [ ! -f "$GOROOT/bin/${GOOS}_${GOARCH}/go" ]; then ( cd "$GOROOT/src" ./make.bash || exit 1 ) || exit 9 fi fi # copy workspace files to GOPATH rm -rf "$GOPATH" mkdir -p "$GOPATH/src/github.com/$TRAVIS_REPO_SLUG" || exit 10 cp -R "$TRAVIS_BUILD_DIR" "$GOPATH/src/github.com/$TRAVIS_REPO_SLUG/.." || exit 11 # install dependencies if [ "$GOOS" = "linux" -o "$GOOS" = "freebsd" -o "$GOOS" = "openbsd" -o "$GOOS" = "netbsd" -o "$GOOS" = "solaris" ]; then go get github.com/BurntSushi/xgb || exit 12 elif [ "$GOOS" = "windows" ]; then go get github.com/lxn/win || exit 13 fi # build example/main.go ( cd "$GOPATH/src/github.com/$TRAVIS_REPO_SLUG" go build example/main.go || exit 1 echo "Built successfully" ls -la ) || exit 14
<reponame>belano/spring-boot-jersey-jwt-auth package com.example.security; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; /** * Returns a 401 error code (Unauthorized) to the client. */ @Component public class EntryPointUnauthorizedHandler implements AuthenticationEntryPoint { private static final Logger logger = LoggerFactory.getLogger(EntryPointUnauthorizedHandler.class); @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { logger.debug("AuthenticationException: {}", exception.getMessage()); response.setContentType("application/json;charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); try (PrintWriter out = response.getWriter()) { out.print("{\"message\":\"Full authentication is required to access this resource.\", \"access-denied\":true,\"cause\":\"NOT AUTHENTICATED\"}"); out.flush(); } catch (IOException e) { logger.warn("Unexpected IO exception", e); } } }
#! /bin/bash testerDirectory="/home/ssdavis/40/p3/Testing" if [ $# -ne 1 ]; then echo "usage Tester.sh: $testerDirectory/Tester.sh calendar.out_directory" 1>&2 exit fi if [[ $1 =~ Testing ]]; then # Use from this directory is not allowed echo "You may not use Testing as your own source directory!" 1>&2 exit fi if [[ ! -e $1/calendar.out ]]; then # calendar.out not found echo "calendar.out not found in $1!" 1>&2 exit fi cd $1 cp $testerDirectory/appts.csv ./appts.csv cp $testerDirectory/in*txt . fileNum=1 opScore=0 echo Operation testing: 1>&2 while [[ $fileNum -lt 10 ]]; do echo $fileNum 1>&2 echo "File#: $fileNum " >> operationsResults.txt rm -f out$fileNum.txt (calendar.out < $testerDirectory/in$fileNum.txt | tail -40 > out$fileNum.txt )& sleep 2 pkill calendar.out &> /dev/null rm core &> /dev/null if [[ -s out$fileNum.txt ]]; then diff out$fileNum.txt $testerDirectory/out$fileNum.txt > temp if [ -s temp ] ; then echo "Not OK" >> operationsResults.txt echo "Yours:" >> operationsResults.txt cat out$fileNum.txt >> operationsResults.txt echo -e "\n\nSean's:" >> operationsResults.txt cat $testerDirectory/out$fileNum.txt >> operationsResults.txt else echo "OK" >> operationsResults.txt (( opScore += 1 )) fi else echo "No output created so zero for operation." >> operationsResults.txt fi fileNum=$((fileNum + 1)) done # while less than 10 echo "Memory leak check (3 points):" >> operationsResults.txt rm -f out$fileNum.txt >& /dev/null (valgrind calendar.out < $testerDirectory/in9.txt >& out$fileNum.txt )& sleep 2 pkill calendar.out >& /dev/null rm core >& /dev/null rm vgcore* >& /dev/null if [[ -s out$fileNum.txt ]]; then if grep "lost.*[1-9]" out$fileNum.txt >& /dev/null ; then echo "Memory leak found." >> operationsResults.txt else echo "OK +2" >> operationsResults.txt (( opScore += 2 )) fi if ! grep "ERROR SUMMARY: 0 errors from 0 contexts" out$fileNum.txt >& /dev/null ; then echo "Memory error found." >> operationsResults.txt else echo "OK +1" >> operationsResults.txt (( opScore += 1 )) fi else echo "Program did not terminate normally so memory leak could not checked." >> operationsResults.txt fi if [ -e appts.csv.old ]; then mv appts.csv.old appts.csv fi echo $opScore # this is the only line that goes to stdout
package kr.co.gardener.admin.model.object.list; import kr.co.gardener.admin.model.object.Cert; import kr.co.gardener.util.CommonList; public class CertList extends CommonList<Cert>{ public CertList() { super("인증 관리"); this.addTh("인증ID","certId","none"); this.addTh("인증명","certName","text"); this.addTh("인증마크","certImage","file"); this.addTh("인증내용","certInfo","area"); this.addInsert("인증ID","certId","none"); this.addInsert("인증명","certName","text"); this.addInsert("인증마크","certImage","file"); this.addInsert("인증내용","certInfo","area"); setView(true); } }
/* * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.webkit.dom; import org.w3c.dom.html.HTMLAreaElement; public class HTMLAreaElementImpl extends HTMLElementImpl implements HTMLAreaElement { HTMLAreaElementImpl(long peer) { super(peer); } static HTMLAreaElement getImpl(long peer) { return (HTMLAreaElement)create(peer); } // Attributes public String getAlt() { return getAltImpl(getPeer()); } native static String getAltImpl(long peer); public void setAlt(String value) { setAltImpl(getPeer(), value); } native static void setAltImpl(long peer, String value); public String getCoords() { return getCoordsImpl(getPeer()); } native static String getCoordsImpl(long peer); public void setCoords(String value) { setCoordsImpl(getPeer(), value); } native static void setCoordsImpl(long peer, String value); public boolean getNoHref() { return getNoHrefImpl(getPeer()); } native static boolean getNoHrefImpl(long peer); public void setNoHref(boolean value) { setNoHrefImpl(getPeer(), value); } native static void setNoHrefImpl(long peer, boolean value); public String getPing() { return getPingImpl(getPeer()); } native static String getPingImpl(long peer); public void setPing(String value) { setPingImpl(getPeer(), value); } native static void setPingImpl(long peer, String value); public String getRel() { return getRelImpl(getPeer()); } native static String getRelImpl(long peer); public void setRel(String value) { setRelImpl(getPeer(), value); } native static void setRelImpl(long peer, String value); public String getShape() { return getShapeImpl(getPeer()); } native static String getShapeImpl(long peer); public void setShape(String value) { setShapeImpl(getPeer(), value); } native static void setShapeImpl(long peer, String value); public String getTarget() { return getTargetImpl(getPeer()); } native static String getTargetImpl(long peer); public void setTarget(String value) { setTargetImpl(getPeer(), value); } native static void setTargetImpl(long peer, String value); public String getAccessKey() { return getAccessKeyImpl(getPeer()); } native static String getAccessKeyImpl(long peer); public void setAccessKey(String value) { setAccessKeyImpl(getPeer(), value); } native static void setAccessKeyImpl(long peer, String value); public String getHref() { return getHrefImpl(getPeer()); } native static String getHrefImpl(long peer); public void setHref(String value) { setHrefImpl(getPeer(), value); } native static void setHrefImpl(long peer, String value); public String getOrigin() { return getOriginImpl(getPeer()); } native static String getOriginImpl(long peer); public String getProtocol() { return getProtocolImpl(getPeer()); } native static String getProtocolImpl(long peer); public void setProtocol(String value) { setProtocolImpl(getPeer(), value); } native static void setProtocolImpl(long peer, String value); public String getUsername() { return getUsernameImpl(getPeer()); } native static String getUsernameImpl(long peer); public void setUsername(String value) { setUsernameImpl(getPeer(), value); } native static void setUsernameImpl(long peer, String value); public String getPassword() { return getPasswordImpl(getPeer()); } native static String getPasswordImpl(long peer); public void setPassword(String value) { setPasswordImpl(getPeer(), value); } native static void setPasswordImpl(long peer, String value); public String getHost() { return getHostImpl(getPeer()); } native static String getHostImpl(long peer); public void setHost(String value) { setHostImpl(getPeer(), value); } native static void setHostImpl(long peer, String value); public String getHostname() { return getHostnameImpl(getPeer()); } native static String getHostnameImpl(long peer); public void setHostname(String value) { setHostnameImpl(getPeer(), value); } native static void setHostnameImpl(long peer, String value); public String getPort() { return getPortImpl(getPeer()); } native static String getPortImpl(long peer); public void setPort(String value) { setPortImpl(getPeer(), value); } native static void setPortImpl(long peer, String value); public String getPathname() { return getPathnameImpl(getPeer()); } native static String getPathnameImpl(long peer); public void setPathname(String value) { setPathnameImpl(getPeer(), value); } native static void setPathnameImpl(long peer, String value); public String getSearch() { return getSearchImpl(getPeer()); } native static String getSearchImpl(long peer); public void setSearch(String value) { setSearchImpl(getPeer(), value); } native static void setSearchImpl(long peer, String value); public String getHash() { return getHashImpl(getPeer()); } native static String getHashImpl(long peer); public void setHash(String value) { setHashImpl(getPeer(), value); } native static void setHashImpl(long peer, String value); }
#!/bin/bash # serve.sh start sh -c "serve dist"
#!/usr/bin/env python # -*- coding:UTF-8 -*- # # shutdownevt.py # # Example of a generator that uses an event to shut down import time def follow(thefile,shutdown=None): thefile.seek(0,2) while True: # 通过设置一个"全局"标志位,来关闭生成器 if shutdown and shutdown.isSet(): break # 从内部关闭 line = thefile.readline() if not line: time.sleep(0.1) continue yield line import threading shutdown_event = threading.Event() def run(): lines = follow(open("run/foo/access-log"),shutdown_event) for line in lines: print line, print "Done" # Run the above in a separate thread t = threading.Thread(target=run) t.start() # Wait a while then shut down time.sleep(60) print "Shutting down" shutdown_event.set()
class GeometricShape: def __init__(self, name, color): self.name = name self.color = color def __repr__(self): return f"Shape(name='{self.name}', color='{self.color}')" # Example usage shape1 = GeometricShape("Circle", "Red") print(repr(shape1)) # Output: Shape(name='Circle', color='Red')
setup() { docker history alpine:3.5 >/dev/null 2>&1 } @test "version is correct" { run docker run alpine:3.5 cat /etc/os-release [ $status -eq 0 ] [ "${lines[2]}" = "VERSION_ID=3.5.2" ] } @test "package installs cleanly" { run docker run alpine:3.5 apk add --no-cache libressl [ $status -eq 0 ] } @test "timezone" { run docker run alpine:3.5 date +%Z [ $status -eq 0 ] [ "$output" = "UTC" ] } @test "apk-install script should be missing" { run docker run alpine:3.5 which apk-install [ $status -eq 1 ] } @test "repository list is correct" { run docker run alpine:3.5 cat /etc/apk/repositories [ $status -eq 0 ] [ "${lines[0]}" = "http://dl-cdn.alpinelinux.org/alpine/v3.5/main" ] [ "${lines[1]}" = "http://dl-cdn.alpinelinux.org/alpine/v3.5/community" ] [ "${lines[2]}" = "" ] } @test "cache is empty" { run docker run alpine:3.5 sh -c "ls -1 /var/cache/apk | wc -l" [ $status -eq 0 ] [ "$output" = "0" ] } @test "root password is disabled" { run docker run --user nobody alpine:3.5 su [ $status -eq 1 ] }
<filename>painel/js/usuariosInserirCtrl.js angular.module('spa') .controller('usuariosInserirCtrl', [ '$scope', '$rootScope', '$routeParams', '$http', '$location', '$mdToast', function($scope, $rootScope,$routeParams, $http, $location, $mdToast){ $scope.name = 'Usuários > Inserir novo usuario'; $scope.statusList = [ {status: 0, value: "Inativo"}, {status: 1, value: "Ativo"} ]; $scope.adminList = [ {admin: 0, value: "Colaborador"}, {admin: 1, value: "Gerente"} ]; $scope.cancelar = function(){ $location.path('usuarios').search({}); }; $scope.inserir = function(){ var token = sessionStorage.getItem("user_session") || localStorage.getItem("user_session"); if(token) { $http({ url: $rootScope.api + '/usuario', dataType: 'json', method:'POST', headers: {'Authorization': token,'Content-Type': 'application/x-www-form-urlencoded'}, data: $.param ({ 'nome': $scope.usuario.nome, 'usuario': $scope.usuario.usuario, 'senha': $scope.usuario.senha, 'status': $scope.usuario.status, 'admin': $scope.usuario.admin }) }).success(function (response) { $mdToast.show($mdToast.simple() .content(response.message) .hideDelay(3000)); $location.path('usuarios').search({}); }).error(function (response) { $mdToast.show($mdToast.simple() .content(response.message) .hideDelay(3000)); console.log(response); if (response.status == 2) window.location = "/#/login"; }); }else{ alert("sem token"); window.location = "/#/login"; } }; } ]);
using TrainsOnline.Application.Interfaces.Repository; public interface IPKPAppDbUnitOfWork : IGenericUnitOfWork { IRoutesRepository RoutesRepository { get; } IStationsRepository StationsRepository { get; } ITicketsRepository TicketsRepository { get; } IUsersRepository UsersRepository { get; } }
<reponame>renankalfa/Curso_em_Video from d115.visuais import * from d115.tratamento import * from d115.bancodedados import * while True: menu('Pessoas cadastradas', 'Cadastrar Pessoa', 'Encerrar Programa') option = testaoption(input('\033[33mSua opção: \033[m')) if option == 1: mostrarcadastradas() if option == 2: armazenar() if option == 3: encerrar() break
import Vue from 'vue' import App from './App' import store from './store/index' Vue.prototype.$store = store; Vue.config.productionTip = false App.mpType = 'app' const app = new Vue(App) app.$mount()
/****************************************************************************** Copyright (c) 2015, Intel Corporation Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ var B = require("hope-base"); function Trace(workflow, config) { this.workflow = workflow; this.id = B.unique_id("HOPE/TRACE_"); this.trace = []; this.config = config || {}; // by default, only capture 100 records if (!this.config.max_records || this.config.max_records < 0) { this.config.max_records = 1000; } } Trace.prototype.start = function(clean_first) { if (clean_first) { this.clean(); } this.is_started = true; }; Trace.prototype.stop = function() { this.is_started = false; }; Trace.prototype.clean = function() { this.trace = []; }; Trace.prototype.sweep = function() { while (this.trace.length > this.config.max_records) { this.trace.shift(); } }; // General Trace for Execution function ExecutionTrace(workflow, config) { Trace.call(this, workflow, config); this.workflow.event.on("node", this.on_node_event.bind(this)); this.workflow.event.on("edge", this.on_edge_event.bind(this)); } B.type.inherit(ExecutionTrace, Trace); ExecutionTrace.prototype.on_node_event = function(data) { if (!this.is_started) { return; } if (data.event === "kernel") { this.trace.push({ time: data.time, nodes: [{ id: data.node_id, data: data.data }] }); this.sweep(); } }; ExecutionTrace.prototype.on_edge_event = function(data) { if (!this.is_started) { return; } if (data.event === "dispatch") { this.trace.push({ time: data.time, edges: [{ id: data.edge_id, data: data.data }] }); this.sweep(); } }; function DebugTrace(workflow, config) { Trace.call(this, workflow, config); this.workflow.event.on("debug", this.on_debug_event.bind(this)); } B.type.inherit(DebugTrace, Trace); DebugTrace.prototype.on_debug_event = function(data) { if (!this.is_started) { return; } this.trace.push(data); this.sweep(); }; module.exports = { ExecutionTrace: ExecutionTrace, DebugTrace: DebugTrace };
<reponame>smagill/opensphere-desktop package io.opensphere.core.util.time; import java.util.function.Supplier; import io.opensphere.core.model.time.TimeInstant; /** * Supplier of now. */ public class NowSupplier implements Supplier<TimeInstant> { /** Reusable instance of NowSupplier. */ public static final Supplier<TimeInstant> INSTANCE = new NowSupplier(); @Override public TimeInstant get() { return TimeInstant.get(); } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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. * */ //using System.ComponentModel.Composition; package com.quantconnect.lean.lean.engine; import java.io.Closeable; import com.quantconnect.lean.configuration.Config; import com.quantconnect.lean.lean.engine.datafeeds.IDataFeed; import com.quantconnect.lean.util.Composer; /** * Provides a container for the algorithm specific handlers */ public class LeanEngineAlgorithmHandlers implements Closeable { private final IDataFeed _dataFeed; private final ISetupHandler _setup; private final IResultHandler _results; private final IRealTimeHandler _realTime; private final ITransactionHandler _transactions; private final IHistoryProvider _historyProvider; private final ICommandQueueHandler _commandQueue; private final IMapFileProvider _mapFileProvider; private final IFactorFileProvider _factorFileProvider; /** * Gets the result handler used to communicate results from the algorithm */ public IResultHandler Results { get { return _results; } } /** * Gets the setup handler used to initialize the algorithm state */ public ISetupHandler Setup { get { return _setup; } } /** * Gets the data feed handler used to provide data to the algorithm */ public IDataFeed DataFeed { get { return _dataFeed; } } /** * Gets the transaction handler used to process orders from the algorithm */ public ITransactionHandler Transactions { get { return _transactions; } } /** * Gets the real time handler used to process real time events */ public IRealTimeHandler RealTime { get { return _realTime; } } /** * Gets the history provider used to process historical data requests within the algorithm */ public IHistoryProvider HistoryProvider { get { return _historyProvider; } } /** * Gets the command queue responsible for receiving external commands for the algorithm */ public ICommandQueueHandler CommandQueue { get { return _commandQueue; } } /** * Gets the map file provider used as a map file source for the data feed */ public IMapFileProvider MapFileProvider { get { return _mapFileProvider; } } /** * Gets the map file provider used as a map file source for the data feed */ public IFactorFileProvider FactorFileProvider { get { return _factorFileProvider; } } /** * Initializes a new instance of the <see cref="LeanEngineAlgorithmHandlers"/> class from the specified handlers * @param results The result handler for communicating results from the algorithm * @param setup The setup handler used to initialize algorithm state * @param dataFeed The data feed handler used to pump data to the algorithm * @param transactions The transaction handler used to process orders from the algorithm * @param realTime The real time handler used to process real time events * @param historyProvider The history provider used to process historical data requests * @param commandQueue The command queue handler used to receive external commands for the algorithm * @param mapFileProvider The map file provider used to retrieve map files for the data feed */ public LeanEngineAlgorithmHandlers( final IResultHandler results, final ISetupHandler setup, final IDataFeed dataFeed, final ITransactionHandler transactions, final IRealTimeHandler realTime, final IHistoryProvider historyProvider, final ICommandQueueHandler commandQueue, final IMapFileProvider mapFileProvider, final IFactorFileProvider factorFileProvider ) { if( results == null ) { throw new NullPointerException( "results"); } if( setup == null ) { throw new NullPointerException( "setup"); } if( dataFeed == null ) { throw new NullPointerException( "dataFeed"); } if( transactions == null ) { throw new NullPointerException( "transactions"); } if( realTime == null ) { throw new NullPointerException( "realTime"); } if( historyProvider == null ) { throw new NullPointerException( "realTime"); } if( commandQueue == null ) { throw new NullPointerException( "commandQueue"); } if( mapFileProvider == null ) { throw new NullPointerException( "mapFileProvider"); } if( factorFileProvider == null ) { throw new NullPointerException( "factorFileProvider"); } _results = results; _setup = setup; _dataFeed = dataFeed; _transactions = transactions; _realTime = realTime; _historyProvider = historyProvider; _commandQueue = commandQueue; _mapFileProvider = mapFileProvider; _factorFileProvider = factorFileProvider; } /** * Creates a new instance of the <see cref="LeanEngineAlgorithmHandlers"/> class from the specified composer using type names from configuration * @param composer The composer instance to obtain implementations from * @returns A fully hydrates <see cref="LeanEngineSystemHandlers"/> instance. * @throws Exception Throws a CompositionException during failure to load */ public static LeanEngineAlgorithmHandlers fromConfiguration( final Composer composer ) { final String setupHandlerTypeName = Config.get( "setup-handler", "ConsoleSetupHandler"); final String transactionHandlerTypeName = Config.get( "transaction-handler", "BacktestingTransactionHandler"); final String realTimeHandlerTypeName = Config.get( "real-time-handler", "BacktestingRealTimeHandler"); final String dataFeedHandlerTypeName = Config.get( "data-feed-handler", "FileSystemDataFeed"); final String resultHandlerTypeName = Config.get( "result-handler", "BacktestingResultHandler"); final String historyProviderTypeName = Config.get( "history-provider", "SubscriptionDataReaderHistoryProvider"); final String commandQueueHandlerTypeName = Config.get( "command-queue-handler", "EmptyCommandQueueHandler"); final String mapFileProviderTypeName = Config.get( "map-file-provider", "LocalDiskMapFileProvider"); final String factorFileProviderTypeName = Config.get( "factor-file-provider", "LocalDiskFactorFileProvider"); return new LeanEngineAlgorithmHandlers( composer.<IResultHandler>getExportedValueByTypeName( resultHandlerTypeName ), composer.<ISetupHandler>getExportedValueByTypeName(setupHandlerTypeName), composer.<IDataFeed>getExportedValueByTypeName(dataFeedHandlerTypeName), composer.<ITransactionHandler>getExportedValueByTypeName(transactionHandlerTypeName), composer.<IRealTimeHandler>getExportedValueByTypeName(realTimeHandlerTypeName), composer.<IHistoryProvider>getExportedValueByTypeName(historyProviderTypeName), composer.<ICommandQueueHandler>getExportedValueByTypeName(commandQueueHandlerTypeName), composer.<IMapFileProvider>getExportedValueByTypeName(mapFileProviderTypeName), composer.<IFactorFileProvider>getExportedValueByTypeName(factorFileProviderTypeName) ); } /** * Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. */ @Override public void close() { Setup.Dispose(); CommandQueue.Dispose(); } }
from django.db.models import Q from .grammar import FieldExpr, OperationAnd, OperationNot, OperationOr, SearchTerm class BaseSearchSet: search_fields = None filters = {} def get_term_condition(self, term): if not self.search_fields: raise NotImplementedError( "search_fields or get_term_match must be overridden" ) condition = Q() for field_name in self.search_fields: condition = condition | Q(**{f"{field_name}__icontains": term}) return condition def get_field_condition(self, term): filters = self.get_filters() if term.field not in filters: raise NotImplementedError(f"Unknown field {term.field}") return filters[term.field](term.value) def get_filters(self): return self.filters def get_condition(self, result): if isinstance(result, SearchTerm): return self.get_term_condition(result.term) elif isinstance(result, OperationAnd): return self.get_condition(result.operands[0]) & self.get_condition( result.operands[1] ) elif isinstance(result, OperationOr): return self.get_condition(result.operands[0]) | self.get_condition( result.operands[1] ) elif isinstance(result, OperationNot): return ~self.get_condition(result.operands) elif isinstance(result, FieldExpr): return self.get_field_condition(result) raise RuntimeError(f"Unknown operation {result.__class__.__name__}") def create_searchset(search_fields, filters): searchset = BaseSearchSet() searchset.search_fields = search_fields searchset.filters = filters return searchset
RSpec.describe Message do describe '#send_message' do it 'sends a payment confirmation text message' do subject(:message) { Message.new } allow(message).to receive(:send_message) expect(message).to receive(:send_message).with("Thank you for your order: £20.93") takeaway.complete_order(20.93) end end end
<filename>eiseg/inference/evaluation.py from time import time import numpy as np import paddle from .utils import * from inference.clicker import Clicker from tqdm import tqdm import scipy.misc as sm import os def evaluate_dataset(dataset, predictor, oracle_eval=False, **kwargs): all_ious = [] start_time = time() for index in tqdm(range(len(dataset)), leave=False): sample = dataset.get_sample(index) _, sample_ious, _ = evaluate_sample(sample.image, sample.gt_mask, predictor, sample_id=index, **kwargs) all_ious.append(sample_ious) end_time = time() elapsed_time = end_time - start_time return all_ious, elapsed_time def evaluate_sample(image, gt_mask, predictor, max_iou_thr, pred_thr=0.49, min_clicks=1, max_clicks=20, sample_id=None, callback=None): clicker = Clicker(gt_mask=gt_mask) pred_mask = np.zeros_like(gt_mask) ious_list = [] predictor.set_input_image(image) pred_probs = None for click_indx in range(max_clicks): clicker.make_next_click(pred_mask) pred_probs = predictor.get_prediction(clicker) pred_mask = pred_probs > pred_thr if callback is not None: callback(image, gt_mask, pred_probs, sample_id, click_indx, clicker.clicks_list) iou = get_iou(gt_mask, pred_mask) ious_list.append(iou) if iou >= max_iou_thr and click_indx + 1 >= min_clicks: # image_name = str(time()) + '.png' # sm.imsave(os.path.join('result', image_name), pred_probs) break return clicker.clicks_list, np.array(ious_list, dtype=np.float32), pred_probs
package stringboot_demo.dso; /** * @author noear 2020/12/29 created */ public interface HelloService { String hello(String name); }
package com.smartalgorithms.getit.Place; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.animation.OvershootInterpolator; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.gms.maps.model.LatLng; import com.rd.PageIndicatorView; import com.smartalgorithms.getit.GetitApplication; import com.smartalgorithms.getit.Helpers.GeneralHelper; import com.smartalgorithms.getit.Helpers.LoggingHelper; import com.smartalgorithms.getit.Models.Database.PlaceInfo; import com.smartalgorithms.getit.R; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import at.blogc.android.views.ExpandableTextView; import butterknife.BindView; import butterknife.ButterKnife; /** * Contact <EMAIL> * Created by <NAME> on 2017/12/06. * Updated by <NAME> on 2017/12/06. */ public class PlaceActivity extends AppCompatActivity implements PlaceContract.UIListener { private static final String TAG = PlaceActivity.class.getSimpleName(); @BindView(R.id.tv_place_title) TextView tv_place_title; @BindView(R.id.etv_description) ExpandableTextView etv_description; @BindView(R.id.iv_desc_toogle) ImageView iv_desc_toogle; @BindView(R.id.llyt_place_details) LinearLayout llyt_place_details; @BindView(R.id.tv_address) TextView tv_address; @BindView(R.id.tv_place_link) TextView tv_place_link; @BindView(R.id.tv_place_checkins) TextView tv_place_checkins; @BindView(R.id.iv_directions) ImageView iv_directions; @BindView(R.id.llyt_location) LinearLayout llyt_location; @BindView(R.id.piv_image_indicator) PageIndicatorView piv_image_indicator; @BindView(R.id.vp_image_swipe) ViewPager vp_image_swipe; @BindView(R.id.iv_back) ImageView iv_back; private PlacePresenter placePresenter; View.OnClickListener clickListener = view -> { switch (view.getId()) { case R.id.llyt_place_details: iv_desc_toogle.setImageDrawable(etv_description.isExpanded() ? GeneralHelper.getDrawable(R.drawable.expand_button) : GeneralHelper.getDrawable(R.drawable.dexpand_button)); etv_description.toggle(); break; case R.id.tv_place_link: //TODO open link on browser if available (Or open phone dialer) break; case R.id.iv_directions: placePresenter.goToPlace(); break; case R.id.iv_back: onBackPressed(); break; } }; private LatLng coordinates; private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); coordinates = new LatLng(bundle.getDouble("lat"), bundle.getDouble("lng")); LoggingHelper.i("Broadcast receiver", "lat: " + coordinates.latitude + " lang: " + coordinates.longitude); } }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_place); setupUI(); LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("com.smartalgorithms.getit")); } private void setupUI() { ButterKnife.bind(this); etv_description.setInterpolator(new OvershootInterpolator()); llyt_place_details.setOnClickListener(clickListener); tv_place_link.setOnClickListener(clickListener); iv_directions.setOnClickListener(clickListener); iv_back.setOnClickListener(clickListener); vp_image_swipe.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {/*empty*/} @Override public void onPageSelected(int position) { piv_image_indicator.setSelection(position); } @Override public void onPageScrollStateChanged(int state) {/*empty*/} }); } @Override public void onAdapterCreated(PlaceImageAdapter placeImageAdapter) { LoggingHelper.i(TAG, "Images: " + placeImageAdapter.getImages().toString()); piv_image_indicator.setCount(placeImageAdapter.getImages().size()); piv_image_indicator.setSelected(0); vp_image_swipe.setAdapter(placeImageAdapter); } @Override public void updateUI(String title, String info, String link_phone, String checkins) { tv_place_title.setText(title); etv_description.setText(info); tv_place_link.setText(link_phone); tv_place_checkins.setText(checkins); } @Override public void showMessage(String title, String message, DialogInterface.OnClickListener ok_listener, DialogInterface.OnClickListener cancel_listener, boolean has_cancel, String positive_text, String negative_text) { GeneralHelper.displayDialog(PlaceActivity.this, title, message, ok_listener, cancel_listener, has_cancel, positive_text, negative_text); } @Override protected void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override protected void onStop() { super.onStop(); EventBus.getDefault().unregister(this); } @Override protected void onResume() { super.onResume(); startService(GetitApplication.getLocationIntent()); LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("com.smartalgorithms.getit")); } @Override protected void onPause() { super.onPause(); stopService(GetitApplication.getLocationIntent()); LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); } @Override protected void onDestroy() { stopService(GetitApplication.getLocationIntent()); super.onDestroy(); } @Override public void onBackPressed() { PlaceActivity.this.finish(); super.onBackPressed(); } @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) public void recieveImageList(PlaceInfo placeInfo) { placePresenter = new PlacePresenter(PlaceActivity.this, PlaceActivity.this, placeInfo); } @Override public void onAddressRecieved(String formatted_address) { tv_address.setText(formatted_address); } }
#!/bin/bash HIDE_WARNINGS=1 source "./scripts/variables.sh" for i in 1 2; do for j in 0 1 2; do echo CLUSTER $i HOST $j; ./generated/ssh_mapr_cluster_${i}_host_${j}.sh "sudo cat /opt/mapr/conf/mapruserticket" done done
<filename>pecado-commons/pecado-commons-sentinel/src/main/java/me/batizhao/common/sentinel/feign/PecadoSentinelFeignAutoConfiguration.java package me.batizhao.common.sentinel.feign; import com.alibaba.cloud.sentinel.feign.SentinelFeignAutoConfiguration; import feign.Feign; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; /** * 暂时使用 PecadoSentinelFeign 覆盖 Sentinel 中的配置,等待 Alibaba 升级 * @author batizhao * @date 2021/1/6 */ @Configuration(proxyBeanMethods = false) @AutoConfigureBefore(SentinelFeignAutoConfiguration.class) public class PecadoSentinelFeignAutoConfiguration { @Bean @Scope("prototype") @ConditionalOnMissingBean @ConditionalOnProperty(name = "feign.sentinel.enabled") public Feign.Builder feignSentinelBuilder() { return PecadoSentinelFeign.builder(); } }
package information; public class PersonalInfo implements Information{ private PhoneNumber number; private EmailAddress email; public PersonalInfo() { } public PersonalInfo(PhoneNumber number, EmailAddress email) { this.number = number; this.email = email; } public void setPhoneNumber(PhoneNumber number) { this.number = number; } public void setEmailAddress(EmailAddress email) { this.email = email; } public long getPhoneNumber() { return this.number.getNumber(); } public String getEmailAddress() { return this.email.getEmailAddress(); } public String toString() { return String.valueOf(this.number) + "," + String.valueOf(this.email); } @Override public void setEmailAddress(String email) { // TODO Auto-generated method stub } }
#!/bin/bash . ./storm_env.sh # The following is needed only if we use DBToaster operators # On Linux machines, we need to install Scala (at least 2.10) # wget http://www.scala-lang.org/files/archive/scala-2.10.4.deb # sudo dpkg -i scala-2.10.4.deb # sudo apt-get update # sudo apt-get install scala # Downloading Storm and putting it to the right place echo "Downloading and extracting $STORMNAME ..." wget http://mirror.easyname.ch/apache/storm/$STORMNAME/$STORMNAME.tar.gz tar -xzf $STORMNAME.tar.gz mv $STORMNAME .. rm $STORMNAME.tar.gz # Compiling Squall and generating dependencies echo "Compiling Squall and generating dependencies ..." CURR_DIR=`pwd` cd .. sbt package sbt assemblyPackageDependency cd $CURR_DIR # The following is used only for the Cluster Mode cp ../squall-core/target/squall-dependencies-0.2.0.jar ../$STORMNAME/lib/
#!/bin/bash # Installs Hadoop BigQuery and/or Spark BigQuery connectors # onto a Cloud Dataproc cluster. set -euxo pipefail readonly VM_CONNECTORS_HADOOP_DIR=/usr/lib/hadoop/lib readonly VM_CONNECTORS_DATAPROC_DIR=/usr/local/share/google/dataproc/lib declare -A MIN_CONNECTOR_VERSIONS MIN_CONNECTOR_VERSIONS=( ["bigquery"]="1.0.0" ["spark-bigquery"]="0.17.0") readonly BIGQUERY_CONNECTOR_VERSION=$(/usr/share/google/get_metadata_value attributes/bigquery-connector-version || true) readonly SPARK_BIGQUERY_CONNECTOR_VERSION=$(/usr/share/google/get_metadata_value attributes/spark-bigquery-connector-version || true) readonly BIGQUERY_CONNECTOR_URL=$(/usr/share/google/get_metadata_value attributes/bigquery-connector-url || true) readonly SPARK_BIGQUERY_CONNECTOR_URL=$(/usr/share/google/get_metadata_value attributes/spark-bigquery-connector-url || true) is_worker() { local role role="$(/usr/share/google/get_metadata_value attributes/dataproc-role)" if [[ $role != Master ]]; then return 0 fi return 1 } min_version() { echo -e "$1\n$2" | sort -r -t'.' -n -k1,1 -k2,2 -k3,3 | tail -n1 } get_connector_url() { # Hadoop BigQuery connector: # gs://hadoop-lib/bigquery-connector/bigquery-connector-hadoop{hadoop_version}-${version}.jar # # Spark BigQuery connector: # gs://spark-lib/bigquery/spark-bigquery-connector-with-dependencies_${scala_version}-${version}.jar local -r name=$1 local -r version=$2 if [[ $name == spark-bigquery ]]; then # DATAPROC_VERSION is an environment variable set on the cluster. # We will use this to determine the appropriate connector to use # based on the scala version. if [[ $(min_version "$DATAPROC_VERSION" 1.5) == 1.5 ]]; then local -r scala_version=2.12 else local -r scala_version=2.11 fi local -r jar_name="spark-bigquery-with-dependencies_${scala_version}-${version}.jar" echo "gs://spark-lib/bigquery/${jar_name}" return fi if [[ $(min_version "$DATAPROC_VERSION" 2.0) == 2.0 ]]; then local -r hadoop_version_suffix=hadoop3 else local -r hadoop_version_suffix=hadoop2 fi local -r jar_name="${name}-connector-${hadoop_version_suffix}-${version}.jar" echo "gs://hadoop-lib/${name}/${jar_name}" } validate_version() { local name=$1 # connector name: "bigquery" or "spark-bigquery" local version=$2 # connector version local min_valid_version=${MIN_CONNECTOR_VERSIONS[$name]} if [[ "$(min_version "$min_valid_version" "$version")" != "$min_valid_version" ]]; then echo "ERROR: ${name}-connector version should be greater than or equal to $min_valid_version, but was $version" return 1 fi } update_connector_url() { local -r name=$1 local -r url=$2 if [[ -d ${VM_CONNECTORS_DATAPROC_DIR} ]]; then local vm_connectors_dir=${VM_CONNECTORS_DATAPROC_DIR} else local vm_connectors_dir=${VM_CONNECTORS_HADOOP_DIR} fi # Remove old connector if exists if [[ $name == spark-bigquery ]]; then find "${vm_connectors_dir}/" -name "${name}*.jar" -delete else find "${vm_connectors_dir}/" -name "${name}-connector-*.jar" -delete fi gsutil cp "${url}" "${vm_connectors_dir}/" local -r jar_name=${url##*/} # Update or create version-less connector link ln -s -f "${vm_connectors_dir}/${jar_name}" "${vm_connectors_dir}/${name}-connector.jar" } update_connector_version() { local -r name=$1 # connector name: "bigquery" or "spark-bigquery" local -r version=$2 # connector version # validate new connector version validate_version "$name" "$version" local -r connector_url=$(get_connector_url "$name" "$version") update_connector_url "$name" "$connector_url" } update_connector() { local -r name=$1 local -r version=$2 local -r url=$3 if [[ -n $version && -n $url ]]; then echo "ERROR: Both, connector version and URL are specified for the same connector" exit 1 fi if [[ -n $version ]]; then update_connector_version "$name" "$version" fi if [[ -n $url ]]; then update_connector_url "$name" "$url" fi } if [[ -z $BIGQUERY_CONNECTOR_VERSION && -z $BIGQUERY_CONNECTOR_URL ]] && [[ -z $SPARK_BIGQUERY_CONNECTOR_VERSION && -z $SPARK_BIGQUERY_CONNECTOR_URL ]]; then echo "ERROR: None of connector versions or URLs are specified" exit 1 fi update_connector "bigquery" "$BIGQUERY_CONNECTOR_VERSION" "$BIGQUERY_CONNECTOR_URL" update_connector "spark-bigquery" "$SPARK_BIGQUERY_CONNECTOR_VERSION" "$SPARK_BIGQUERY_CONNECTOR_URL"
<gh_stars>1-10 require 'caracal/core/models/bookmark_model' require 'caracal/errors' module Caracal module Core # This module encapsulates all the functionality related to adding # bookmarks to the document. # module Bookmarks def self.included(base) base.class_eval do #------------------------------------------------ # Public Methods #------------------------------------------------ def current_bookmark_id @current_bookmark_id ||= 1 end def next_bookmark_id @current_bookmark_id = current_bookmark_id + 1 end #========== BOOKMARKS =========================== def bookmark_start(*args, &block) options = Caracal::Utilities.extract_options!(args) options.merge!({ start: true, id: next_bookmark_id }) model = Caracal::Core::Models::BookmarkModel.new(options, &block) if model.valid? contents << model else raise Caracal::Errors::InvalidModelError, 'Bookmark starting tags require a name.' end model end def bookmark_end contents << Caracal::Core::Models::BookmarkModel.new(start: false, id: current_bookmark_id) end end end end end end
<reponame>Habens/cascade<gh_stars>10-100 package com.github.robindevilliers.welcometohell.wizard.parser; import com.github.robindevilliers.welcometohell.wizard.ElementParser; import com.github.robindevilliers.welcometohell.wizard.ParserUtilities; import com.github.robindevilliers.welcometohell.wizard.domain.TitleLarge; import org.springframework.stereotype.Component; import org.xml.sax.Attributes; import java.util.Stack; @Component public class TitleLargeParser implements ElementParser { @Override public boolean accepts(String name) { return "title-large".equals(name); } @Override public Object parse(Stack<Object> elements, Attributes attributes) { TitleLarge element = new TitleLarge(); ParserUtilities.assignAttributes(element, attributes); linkToParent(elements.peek(), element); return element; } }
<filename>dynamic_programming/max_subarray.py<gh_stars>0 """ 53. Maximum Subarray https://leetcode.com/problems/maximum-subarray/ Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. """ # Runtime: 100ms (11.40%) class Solution: def maxSubArray(self, nums: List[int]) -> int: max_sum = nums[0] curr_sum = max_sum for i in range(1, len(nums)): curr_sum = max(nums[i] + curr_sum, nums[i]) max_sum = max(curr_sum, max_sum) return max_sum
#!/bin/bash -neu # Copyright 2021 Alin Mr. <almr.oss@outlook.com>. Licensed under the MIT license (https://opensource.org/licenses/MIT). # Minimally viable bash associative array-based argparser # @k9s0ke bashaap __k9s0ke_bashaap_chkver() { local __k9s0ke_BASHAAP_VERSION=2.1.0 # MAJOR.minor.patch [[ ${BASH_VERSINFO[0]} -gt 4 ]] || [[ ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -ge 4 ]] || { echo 1>&2 "bash too old"; return 1; } [[ $1 = '----v'* ]] || return 1 local v=${1#----v}; [[ $v = [0-9]* ]] || # required by user, string { echo 1>&2 "Bad bashaap args: $*"; return 1; } local vpat='^([^.]+)\.([^.+])' # regex for MAJOR.minor [[ $__k9s0ke_BASHAAP_VERSION =~ $vpat ]] || return 1; local pv=( "${BASH_REMATCH[@]}" ) # provided version [[ $v =~ $vpat ]] || return 1; local rv=( "${BASH_REMATCH[@]}" ) # required version [[ ${rv[1]} -eq ${pv[1]} && ${rv[2]} -le ${pv[2]} ]] || # provided MAJOR = required, minor >= required { echo 1>&2 "ERROR: mismatched bashaap version (need $v, got $__k9s0ke_BASHAAP_VERSION)"; return 1; } return 0 } __k9s0ke_bashaap_chkver "$@" # --- x8 --- start here to embed script --- # embedded bashaaparse; see https://gitlab.com/kstr0k/bashaaparse __k9s0ke_amember() { local h ndl=$1; shift for h; do test "$ndl" = "$h" && return 0; done return 1 } __k9s0ke_aappend() { test _f = "$1" || local -n _f=$1; shift test _t = "$1" || local -n _t=$1; shift local k; for k in "${!_f[@]}"; do _t[$k]=${_f[$k]}; done } __k9s0ke_on_switch() { test _n = "$1" || local -n _n=$1; shift; _n=0 case "$1" in -h|--help) __k9s0ke_print_help; exit 0 ;; esac local s=${1#--} if __k9s0ke_amember "$s" "${!CLI_OPTS_bool[@]}"; then # TODO: --arg=val _n=1; CLI_OPTS_bool["$s"]=y elif __k9s0ke_amember "${s#no-}" "${!CLI_OPTS_bool[@]}"; then _n=1; CLI_OPTS_bool["${s#no-}"]= elif __k9s0ke_amember "$s" "${!CLI_OPTS[@]}"; then _n=2; CLI_OPTS["$s"]="$2" else return 1 fi; return 0 } __k9s0ke_print_help() { local s cat <<EOF Usage: ${_USAGE:-$(basename "$0") [<option> ...] [...]} Options: --help EOF for s in "${!CLI_OPTS[@]}"; do cat <<EOF --$s <$s> EOF done for s in "${!CLI_OPTS_bool[@]}"; do cat <<EOF --$s --no-$s EOF done } __k9s0ke_argloop() { test 'ARGV' = "$1" || local -n ARGV=$1; shift local NSHIFT while test ${#ARGV[@]} -gt 0; do local arg="${ARGV[0]}"; ARGV=( "${ARGV[@]:1}" ); case "$arg" in --) break ;; -v) ARGV=( '--verbose' "${ARGV[@]}" ) ;; -*) if __k9s0ke_on_switch NSHIFT "$arg" "${ARGV[@]}"; then ARGV=( "${ARGV[@]:$(( NSHIFT - 1 ))}" ) else echo 1>&2 "Bad args: $arg"; exit 1 fi ;; *) ARGV=( "$arg" "${ARGV[@]}" ); break ;; esac; done __k9s0ke_aappend CLI_OPTS_bool CLI_OPTS #; declare 1>&2 -p CLI_OPTS CLI_OPTS_bool } __k9s0ke_read_cfg() { test -r "$1" || return 1 local kv _n while IFS= read -r kv; do __k9s0ke_on_switch _n "${kv%%=*}" "${kv#*=}" done <"$1" } # @k9s0ke: end bashaap # vim: set ft=bash:
<filename>src/com/thaura/gaming/ID.java package com.thaura.gaming; public enum ID { Player(); Enemy(); }
import peewee class StockInfo(peewee.Model): id = peewee.CharField(primary_key=True, max_length=64) name = peewee.CharField(max_length=64) class meta: table_name = "stock_information" class StockMarket(peewee.Model): date = peewee.DateField(index=True) category = peewee.IntegerField() stock = peewee.ForeignKeyField(StockInfo) open = peewee.FloatField(null=True) high = peewee.FloatField(null=True) low = peewee.FloatField(null=True) close = peewee.FloatField(null=True) capacity = peewee.BigIntegerField(null=True) transaction = peewee.BigIntegerField(null=True) turnover = peewee.BigIntegerField(null=True) foreign_dealers_buy = peewee.BigIntegerField(null=True) foreign_dealers_sell = peewee.BigIntegerField(null=True) foreign_dealers_total = peewee.BigIntegerField(null=True) investment_trust_buy = peewee.BigIntegerField(null=True) investment_trust_sell = peewee.BigIntegerField(null=True) investment_trust_total = peewee.BigIntegerField(null=True) dealer_buy = peewee.BigIntegerField(null=True) dealer_sell = peewee.BigIntegerField(null=True) dealer_total = peewee.BigIntegerField(null=True) institutional_investors_total = peewee.BigIntegerField(null=True) margin_purchase = peewee.BigIntegerField(null=True) margin_sales = peewee.BigIntegerField(null=True) margin_cash_redemption = peewee.BigIntegerField(null=True) margin_today_balance = peewee.BigIntegerField(null=True) margin_quota = peewee.BigIntegerField(null=True) short_covering = peewee.BigIntegerField(null=True) short_sale = peewee.BigIntegerField(null=True) short_stock_redemption = peewee.BigIntegerField(null=True) short_today_balance = peewee.BigIntegerField(null=True) short_quota = peewee.BigIntegerField(null=True) offsetting_margin_short = peewee.BigIntegerField(null=True) note = peewee.BigIntegerField(null=True) class meta: table_name = "stock_market"
#!/usr/bin/env bash set -o errexit set -o nounset # Ensure that we have a valid OTHER_LDFLAGS environment variable OTHER_LDFLAGS=${OTHER_LDFLAGS:=""} # Ensure that we have a valid CocoaDebug_FILENAME environment variable CocoaDebug_FILENAME=${CocoaDebug_FILENAME:="CocoaDebug.framework"} # Ensure that we have a valid CocoaDebug_PATH environment variable CocoaDebug_PATH=${CocoaDebug_PATH:="${SRCROOT}/${CocoaDebug_FILENAME}"} # The path to copy the framework to app_frameworks_dir="${CODESIGNING_FOLDER_PATH}/Frameworks" copy_library() { mkdir -p "$app_frameworks_dir" cp -vRf "$CocoaDebug_PATH" "${app_frameworks_dir}/${CocoaDebug_FILENAME}" } codesign_library() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" ]; then codesign -fs "${EXPANDED_CODE_SIGN_IDENTITY}" "${app_frameworks_dir}/${CocoaDebug_FILENAME}" fi } main() { if [[ $OTHER_LDFLAGS =~ "CocoaDebug" ]]; then if [ -e "$CocoaDebug_PATH" ]; then copy_library codesign_library echo "${CocoaDebug_FILENAME} is included in this build, and has been copied to $CODESIGNING_FOLDER_PATH" else echo "${CocoaDebug_FILENAME} is not included in this build, as it could not be found at $CocoaDebug_PATH" fi else echo "${CocoaDebug_FILENAME} is not included in this build because CocoaDebug was not present in the OTHER_LDFLAGS environment variable." fi } main
<reponame>tetreum/Vuindows function God (game, x, y) { // call Phaser.Sprite constructor Phaser.Sprite.call(this, game, x, y, 'god') this.anchor.set(0.5, 0.5) this.animations.add('left', [0]); this.animations.add('right', [1]); this.facing = 'left' this.game.physics.enable(this) this.body.collideWorldBounds = true // this.doTween() } // inherit from Phaser.Sprite God.prototype = Object.create(Phaser.Sprite.prototype) God.prototype.constructor = God God.prototype.float = function (x, y) { this.x += x * 5 this.y += y * 5 } God.prototype.doTween = function () { this.floatTween = this.game.add.tween(this).to({ y: this.position.y - 50 }, 1500, Phaser.Easing.Linear.None, true, 0, 0, true).loop(true) } God.prototype._getAnimationName = function () { if (this.facing === 'right') { return 'right' } else { return 'left' } return name; }; God.prototype.update = function () { const animationName = this._getAnimationName(); if (this.animations.name !== animationName) { this.animations.play(animationName); } }; module.exports = God
# frozen_string_literal: true require 'rails_helper' describe ImageUploader do subject { described_class.new(:store) } describe 'upload_options plugin' do let(:store_lambda) { subject.opts[:upload_options][:store] } context 'when original version' do let(:acl) { store_lambda.call(double, derivative: nil)[:acl] } it 'returns private acl' do expect(acl).to eq('private') end end context 'when other versions' do let(:acl) { store_lambda.call(double, derivative: :other)[:acl] } it 'returns public-read acl' do expect(acl).to eq('public-read') end end end end
package cmu.xprize.robotutor.startup.configuration; import java.util.HashMap; public class ConfigurationClassMap { static public HashMap<String, Class> classMap = new HashMap<>(); static { classMap.put("ConfigurationItems", ConfigurationItems.class); classMap.put("string", String.class); classMap.put("bool", Boolean.class); classMap.put("int", Integer.class); classMap.put("float", Float.class); classMap.put("byte", Byte.class); classMap.put("long", Long.class); classMap.put("short", Short.class); classMap.put("object", Object.class); } }
def generate_license_plate(registration_input): # Defining a dictionary to map the first letter # Of each vehicle brand to a prefix prefix_map = { 'H': 'ABC', 'T': 'XYZ', 'M': 'QRS' } # Initializing an empty list to store the license plates license_plates = [] # Iterating through the input list for brand, number in registration_input: # Getting the first letter of the brand name first_letter = brand[0].upper() # Checking if the first letter of the brand is present in the prefix map if first_letter in prefix_map: # Appending the prefix + number to the license plates list license_plates.append(prefix_map[first_letter] + number) # Returning the list of license plates return license_plates
package br.etec.sebrae.portal.dtos; import java.io.Serializable; import java.util.Date; public class SolicitacoesDto implements Serializable{ /** * */ private static final long serialVersionUID = -6541520440241118272L; private long id; private int status; private Date data_solicitacao ; private String documento; private String aluno; public long getId() { return id; } public void setId(long id) { this.id = id; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Date getData_solicitacao() { return data_solicitacao; } public void setData_solicitacao(Date data_solicitacao) { this.data_solicitacao = data_solicitacao; } public String getDocumento() { return documento; } public void setDocumento(String documento) { this.documento = documento; } public String getAluno() { return aluno; } public void setAluno(String aluno) { this.aluno = aluno; } }
<gh_stars>1-10 'use strict'; angular.module('ffffngAdmin').config(function(NgAdminConfigurationProvider, RestangularProvider, Constraints, config) { RestangularProvider.addFullRequestInterceptor(function(element, operation, what, url, headers, params) { if (operation === 'getList') { if (params._filters) { // flatten filter query params for (var filter in params._filters) { params[filter] = params._filters[filter]; } delete params._filters; } } return { params: params }; }); function nullable(value) { return value ? value : 'N/A'; } function formatMoment(unix) { return unix ? moment.unix(unix).fromNow() : 'N/A'; } function formatDuration(duration) { return typeof duration === 'number' ? moment.duration(duration).humanize() : 'N/A'; } function nodeConstraint(field) { var constraint = Constraints.node[field]; var result = { required: !constraint.optional }; if (constraint.type === 'string') { result.pattern = constraint.regex; } return result; } var nga = NgAdminConfigurationProvider; var title = 'Knotenverwaltung - ' + config.community.name + ' - Admin-Panel'; var admin = nga.application(title); document.title = title; var pathPrefix = config.rootPath === '/' ? '' : config.rootPath; var siteChoices = []; for (var i = 0; i < config.community.sites.length; i++) { var site = config.community.sites[i]; siteChoices.push({ label: site, value: site }); } var domainChoices = []; for (var i = 0; i < config.community.domains.length; i++) { var domain = config.community.domains[i]; domainChoices.push({ label: domain, value: domain }); } var header = '<div class="navbar-header">' + '<a class="navbar-brand" href="#" ng-click="appController.displayHome()">' + title + ' ' + '<small style="font-size: 0.7em;">(<fa-version></fa-version>)</small>' + '</a>' + '</div>'; if (config.legal.imprintUrl) { header += '<p class="navbar-text navbar-right">' + '<a href="' + config.legal.imprintUrl + '" target="_blank">' + 'Imprint' + '</a>' + '</p>'; } if (config.legal.privacyUrl) { header += '<p class="navbar-text navbar-right">' + '<a href="' + config.legal.privacyUrl + '" target="_blank">' + 'Privacy' + '</a>' + '</p>'; } header += '<p class="navbar-text navbar-right">' + '<a href="https://github.com/freifunkhamburg/ffffng/issues" target="_blank">' + '<i class="fa fa-bug" aria-hidden="true"></i> Report Error' + '</a>' + '</p>' + '<p class="navbar-text navbar-right">' + '<a href="https://github.com/freifunkhamburg/ffffng" target="_blank">' + '<i class="fa fa-code" aria-hidden="true"></i> Source Code' + '</a>' + '</p>' + '<p class="navbar-text navbar-right">' + '<a href="' + pathPrefix + '/" target="_blank">' + '<i class="fa fa-external-link" aria-hidden="true"></i> Frontend' + '</a>' + '</p>'; admin .header(header) .baseApiUrl(pathPrefix + '/internal/api/') .debug(true); function nodeClasses(node) { if (!node) { return; } switch (node.values.onlineState) { case 'ONLINE': return 'node-online'; case 'OFFLINE': return 'node-offline'; default: return; } } var nodes = nga.entity('nodes').label('Nodes').identifier(nga.field('token')); nodes .listView() .title('Nodes') .perPage(30) .sortDir('ASC') .sortField('hostname') .actions([]) .batchActions([]) .exportFields([]) .fields([ nga.field('hostname').cssClasses(nodeClasses), nga.field('nickname').cssClasses(nodeClasses), nga.field('email').cssClasses(nodeClasses), nga.field('token').cssClasses(nodeClasses), nga.field('mac').cssClasses(nodeClasses), nga.field('key').label('VPN').cssClasses(nodeClasses).template(function (node) { return node.values.key ? '<i class="fa fa-lock vpn-key-set" aria-hidden="true" title="VPN key set"></i>' : '<i class="fa fa-times vpn-key-unset" aria-hidden="true" title="no VPN key"></i>'; }), nga.field('site').map(nullable).cssClasses(nodeClasses), nga.field('domain').map(nullable).cssClasses(nodeClasses), nga.field('coords').label('GPS').cssClasses(nodeClasses).template(function (node) { return node.values.coords ? '<i class="fa fa-map-marker coords-set" aria-hidden="true" title="coordinates set"></i>' : '<i class="fa fa-times coords-unset" aria-hidden="true" title="no coordinates"></i>'; }), nga.field('onlineState').map(nullable).cssClasses(nodeClasses), nga.field('monitoringState').cssClasses(nodeClasses).template(function (node) { switch (node.values.monitoringState) { case 'active': return '<i class="fa fa-heartbeat monitoring-active" title="active"></i>'; case 'pending': return '<i class="fa fa-envelope monitoring-confirmation-pending" title="confirmation pending"></i>'; default: return '<i class="fa fa-times monitoring-disabled" title="disabled"></i>'; } }) ]) .filters([ nga.field('q', 'template') .label('') .pinned(true) .template( '<div class="input-group">' + '<input type="text" ng-model="value" placeholder="Search" class="form-control"></input>' + '<span class="input-group-addon"><i class="fa fa-search"></i></span></div>'), nga.field('site', 'choice') .label('Site') .pinned(false) .choices(siteChoices), nga.field('domain', 'choice') .label('Domäne') .pinned(false) .choices(domainChoices), nga.field('hasKey', 'choice') .label('VPN key') .pinned(false) .choices([ { label: 'VPN key set', value: true }, { label: 'no VPN key', value: false } ]), nga.field('hasCoords', 'choice') .label('GPS coordinates') .pinned(false) .choices([ { label: 'coordinates set', value: true }, { label: 'no coordinates', value: false } ]), nga.field('onlineState', 'choice') .label('Online state') .pinned(false) .choices([ { label: 'online', value: 'ONLINE' }, { label: 'offline', value: 'OFFLINE' } ]), nga.field('monitoringState', 'choice') .label('Monitoring') .pinned(false) .choices([ { label: 'pending', value: 'pending' }, { label: 'active', value: 'active' }, { label: 'disabled', value: 'disabled' } ]) ]) .actions(['<ma-filter-button filters="filters()" enabled-filters="enabledFilters" enable-filter="enableFilter()"></ma-filter-button>']) .listActions( '<ma-edit-button entry="entry" entity="entity" size="sm"></ma-edit-button> ' + '<ma-delete-button entry="entry" entity="entity" size="sm"></ma-delete-button> ' + '<form style="display: inline-block" action="' + pathPrefix + '/#/update" method="POST" target="_blank">' + '<input type="hidden" name="token" value="{{entry.values.token}}"/>' + '<button class="btn btn-primary btn-sm" type="submit"><i class="fa fa-external-link"></i> Open</button>' + '</form> ' + '<a class="btn btn-success btn-sm" href="' + config.map.mapUrl + '/#!v:m;n:{{entry.values.mapId}}" target="_blank"><i class="fa fa-map-o"></i> Map</a>' ) ; nodes .editionView() .title('Edit node') .actions(['list', 'delete']) .addField(nga.field('token').editable(false)) .addField(nga.field('hostname').label('Name').validation(nodeConstraint('hostname'))) .addField(nga.field('key').label('Key').validation(nodeConstraint('key'))) .addField(nga.field('mac').label('MAC').validation(nodeConstraint('mac'))) .addField(nga.field('coords').label('GPS').validation(nodeConstraint('coords'))) .addField(nga.field('nickname').validation(nodeConstraint('nickname'))) .addField(nga.field('email').validation(nodeConstraint('email'))) .addField(nga.field('monitoring', 'boolean').validation(nodeConstraint('monitoring'))) .addField(nga.field('monitoringConfirmed').label('Monitoring confirmation').editable(false).map( function (monitoringConfirmed, node) { if (!node.monitoring) { return 'N/A'; } return monitoringConfirmed ? 'confirmed' : 'pending'; } )) ; admin.addEntity(nodes); function monitoringStateClasses(monitoringState) { if (!monitoringState) { return; } switch (monitoringState.values.state) { case 'ONLINE': return 'monitoring-state-online'; case 'OFFLINE': return 'monitoring-state-offline'; default: return; } } var monitoringStates = nga.entity('monitoring').label('Monitoring'); monitoringStates .listView() .title('Monitoring') .perPage(30) .sortDir('ASC') .sortField('id') .actions([]) .batchActions([]) .exportFields([]) .fields([ nga.field('id').cssClasses(monitoringStateClasses), nga.field('hostname').cssClasses(monitoringStateClasses), nga.field('mac').cssClasses(monitoringStateClasses), nga.field('site').map(nullable).cssClasses(monitoringStateClasses), nga.field('domain').map(nullable).cssClasses(monitoringStateClasses), nga.field('monitoring_state').cssClasses(monitoringStateClasses).template(function (monitoringState) { switch (monitoringState.values.monitoring_state) { case 'active': return '<i class="fa fa-heartbeat monitoring-active" title="active"></i>'; case 'pending': return '<i class="fa fa-envelope monitoring-confirmation-pending" title="confirmation pending"></i>'; default: return '<i class="fa fa-times monitoring-disabled" title="disabled"></i>'; } }), nga.field('state').cssClasses(monitoringStateClasses), nga.field('last_seen').map(formatMoment).cssClasses(monitoringStateClasses), nga.field('import_timestamp').label('Imported').map(formatMoment).cssClasses(monitoringStateClasses), nga.field('last_status_mail_type').map(nullable).cssClasses(monitoringStateClasses), nga.field('last_status_mail_sent').map(formatMoment).cssClasses(monitoringStateClasses), nga.field('created_at').map(formatMoment).cssClasses(monitoringStateClasses), nga.field('modified_at').map(formatMoment).cssClasses(monitoringStateClasses) ]) .filters([ nga.field('q') .label('') .pinned(true) .template( '<div class="input-group">' + '<input type="text" ng-model="value" placeholder="Search" class="form-control"></input>' + '<span class="input-group-addon"><i class="fa fa-search"></i></span></div>'), ]) .listActions( '<a class="btn btn-success btn-sm" href="' + config.map.mapUrl + '/#!v:m;n:{{entry.values.mapId}}" target="_blank"><i class="fa fa-map-o"></i> Map</a>' ) ; admin.addEntity(monitoringStates); function mailClasses(mail) { if (!mail) { return; } var failures = mail.values.failures; if (failures === 0) { return 'mails-pending'; } if (failures >= 5) { return 'mails-failed-max'; } return 'mails-failed'; } var mails = nga.entity('mails').label('Mail-Queue'); mails .listView() .title('Mail-Queue') .perPage(30) .sortDir('ASC') .sortField('id') .actions([]) .batchActions([]) .exportFields([]) .fields([ nga.field('id').cssClasses(mailClasses), nga.field('failures').cssClasses(mailClasses), nga.field('sender').cssClasses(mailClasses), nga.field('recipient').cssClasses(mailClasses), nga.field('email').cssClasses(mailClasses), nga.field('created_at').map(formatMoment).cssClasses(mailClasses), nga.field('modified_at').map(formatMoment).cssClasses(mailClasses) ]) .filters([ nga.field('q') .label('') .pinned(true) .template( '<div class="input-group">' + '<input type="text" ng-model="value" placeholder="Search" class="form-control"></input>' + '<span class="input-group-addon"><i class="fa fa-search"></i></span></div>'), ]) .listActions( '<fa-mail-action-button disabled="entry.values.failures === 0" action="reset" icon="refresh" label="Retry" mail="entry" button="success" label="run" size="sm"></fa-mail-action-button> ' + '<ma-delete-button entry="entry" entity="entity" size="sm"></ma-delete-button>' ) ; admin.addEntity(mails); function taskClasses(field) { return function(task) { if (!task) { return; } return 'task-' + field + ' ' + (task.values.enabled ? 'task-enabled' : 'task-disabled') + ' ' + 'task-state-' + task.values.state + ' ' + 'task-result-' + (task.values.result ? task.values.result : 'none'); }; } var tasks = nga.entity('tasks').label('Background-Jobs'); tasks .listView() .title('Background-Jobs') .perPage(30) .sortDir('ASC') .sortField('id') .actions([]) .batchActions([]) .exportFields([]) .fields([ nga.field('id').cssClasses(taskClasses('id')), nga.field('name').cssClasses(taskClasses('name')), nga.field('description').cssClasses(taskClasses('description')), nga.field('schedule').cssClasses(taskClasses('schedule')), nga.field('state').cssClasses(taskClasses('state')), nga.field('message').cssClasses(taskClasses('message')), nga.field('runningSince').map(formatMoment).cssClasses(taskClasses('runningSince')), nga.field('lastRunStarted').map(formatMoment).cssClasses(taskClasses('lastRunStarted')), nga.field('lastRunDuration').map(formatDuration).cssClasses(taskClasses('lastRunDuration')) ]) .filters([ nga.field('q') .label('') .pinned(true) .template( '<div class="input-group">' + '<input type="text" ng-model="value" placeholder="Search" class="form-control"></input>' + '<span class="input-group-addon"><i class="fa fa-search"></i></span></div>'), ]) .listActions( '<fa-task-action-button action="run" task="entry" button="primary" label="run" size="sm"></fa-task-action-button> ' + '<fa-task-action-button ng-if="!entry.values.enabled" button="success" action="enable" icon="power-off" task="entry" label="enable" size="sm"></fa-task-action-button> ' + '<fa-task-action-button ng-if="entry.values.enabled" button="warning" action="disable" icon="power-off" task="entry" label="disable" size="sm"></fa-task-action-button>' ) ; admin.addEntity(tasks); admin.menu( nga.menu() .addChild(nga .menu() .template( '<a href="' + pathPrefix + '/internal/admin">' + '<span class="fa fa-dashboard"></span> Dashboard / Statistics' + '</a>' ) ) .addChild(nga .menu(nodes) .icon('<i class="fa fa-dot-circle-o"></i>') ) .addChild(nga .menu(monitoringStates) .icon('<span class="fa fa-heartbeat"></span>') ) .addChild(nga .menu(mails) .icon('<span class="fa fa-envelope"></span>') ) .addChild(nga .menu(tasks) .icon('<span class="fa fa-cog"></span>') ) .addChild(nga .menu() .template( '<a href="' + pathPrefix + '/internal/logs" target="_blank">' + '<span class="fa fa-list"></span> Logs' + '</a>' ) ) ); admin.dashboard(nga.dashboard() .template( '<div class="row dashboard-starter"></div>' + '<fa-dashboard-stats></fa-dashboard-stats>' + '<div class="row dashboard-content">' + '<div class="col-lg-6">' + '<div class="panel panel-default" ng-repeat="collection in dashboardController.collections | orderElement" ng-if="$even">' + '<ma-dashboard-panel collection="collection" entries="dashboardController.entries[collection.name()]"></ma-dashboard-panel>' + '</div>' + '</div>' + '</div>' ) ); nga.configure(admin); });
import * as tg from "generic-type-guard"; export declare const isDataLayerEvent: tg.TypeGuard<object & { data: object; }>; /** * A message sent from the game to the iFrame when the data of the layers change after the iFrame send a message to the game that it want to listen to the data of the layers */ export declare type DataLayerEvent = tg.GuardedType<typeof isDataLayerEvent>;
package me.aleiv.modeltool.events; import lombok.Getter; import me.aleiv.modeltool.core.EntityModel; import org.bukkit.entity.Entity; public class EntityModelDeathEvent extends EntityModelEvent { @Getter private final Entity killer; public EntityModelDeathEvent(EntityModel entityModel, Entity killer) { super(entityModel); this.killer = killer; } }
#!/usr/bin/env bash # # Copyright 2020-2021 by Vegard IT GmbH, Germany, https://vegardit.com # SPDX-License-Identifier: Apache-2.0 # # Author: Sebastian Thomschke, Vegard IT GmbH set -eu if ! hash native-image 2>/dev/null; then /usr/bin/env bash "$(dirname ${BASH_SOURCE[0]})/run-in-docker.sh" bash tools/build-native-image.sh exit $? fi cd "$(dirname ${BASH_SOURCE[0]})/../target/" input_jar=copycat-*-fat.jar output_binary=copycat-snapshot-linux-amd64 native-image \ -H:ReflectionConfigurationFiles=picocli-reflections.json \ -H:+ReportExceptionStackTraces \ -H:+RemoveUnusedSymbols \ --allow-incomplete-classpath \ --no-fallback \ --no-server \ --verbose \ -H:+StaticExecutableWithDynamicLibC `#https://www.graalvm.org/reference-manual/native-image/StaticImages/#build-a-mostly-static-native-image` \ -Dfile.encoding=UTF-8 \ --initialize-at-build-time=org.slf4j \ --initialize-at-build-time=net.sf.jstuff.core.collection.WeakIdentityHashMap \ --initialize-at-build-time=net.sf.jstuff.core.logging \ --initialize-at-build-time=net.sf.jstuff.core.reflection.StackTrace \ --initialize-at-build-time=com.vegardit.copycat.command.sync.AbstractSyncCommand \ --initialize-at-build-time=com.vegardit.copycat.command.watch.WatchCommand \ -Dnet.sf.jstuff.core.logging.Logger.preferSLF4J=false \ --class-path $input_jar \ com.vegardit.copycat.CopyCatMain \ $output_binary ls -l $output_binary strip --strip-unneeded $output_binary ls -l $output_binary chmod u+x $output_binary ./$output_binary --help ./$output_binary sync --help ./$output_binary watch --help ./$output_binary --version
<reponame>v55448330/cattle<filename>code/framework/java-server/src/main/java/io/github/ibuildthecloud/gdapi/json/JacksonMapper.java package io.github.ibuildthecloud.gdapi.json; import io.github.ibuildthecloud.gdapi.model.Field; import io.github.ibuildthecloud.gdapi.model.Resource; import io.github.ibuildthecloud.gdapi.model.Schema; import io.github.ibuildthecloud.gdapi.model.SchemaCollection; import io.github.ibuildthecloud.gdapi.model.impl.FieldImpl; import io.github.ibuildthecloud.gdapi.model.impl.SchemaImpl; import io.github.ibuildthecloud.gdapi.util.DateUtils; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.List; import java.util.Map; import java.util.TimeZone; import javax.annotation.PostConstruct; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; public class JacksonMapper implements JsonMapper { ObjectMapper mapper; boolean escapeForwardSlashes; @PostConstruct public void init() { SimpleModule module = new SimpleModule(); module.setMixInAnnotation(Resource.class, ResourceMix.class); module.setMixInAnnotation(SchemaCollection.class, SchemaCollectionMixin.class); module.setMixInAnnotation(SchemaImpl.class, SchemaImplMixin.class); SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_FORMAT); df.setTimeZone(TimeZone.getTimeZone("GMT")); mapper = new ObjectMapper(); mapper.setDateFormat(df); mapper.registerModule(new JaxbAnnotationModule()); mapper.registerModule(module); mapper.getFactory().configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); if (escapeForwardSlashes) { mapper.getFactory().setCharacterEscapes(new EscapeForwardSlash()); } } @Override public <T> T readValue(byte[] content, Class<T> type) throws IOException { return mapper.readValue(content, type); } @Override public Object readValue(byte[] content) throws IOException { return mapper.readValue(content, Object.class); } @Override public void writeValue(OutputStream os, Object object) throws IOException { mapper.writeValue(os, object); } @Override public <T> T convertValue(Object fromValue, Class<T> toValueType) { return mapper.convertValue(fromValue, toValueType); } public static interface ResourceMix { @JsonAnyGetter Map<String, Object> getFields(); } public static interface SchemaCollectionMixin { @JsonDeserialize(as = List.class, contentAs = SchemaImpl.class) List<Schema> getData(); } public static interface SchemaImplMixin { @JsonDeserialize(as = Map.class, contentAs = FieldImpl.class) Map<String, Field> getResourceFields(); } public static interface ResourceMixin { @JsonAnyGetter Map<String, Object> getFields(); } public boolean isEscapeForwardSlashes() { return escapeForwardSlashes; } public void setEscapeForwardSlashes(boolean escapeForwardSlashes) { this.escapeForwardSlashes = escapeForwardSlashes; } }
<reponame>dmitrievanthony/decision-tree-prototype /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dmitrievanthony.tree.core.distributed.criteria; import com.dmitrievanthony.tree.utils.Utils; import java.util.Arrays; /** * Step function described by {@code x} and {@code y} points. * * @param <T> */ public class StepFunction<T extends ImpurityMeasure<T>> { /** Argument of every steps start. Should be ascendingly sorted all the time. */ private final double[] x; /** Value of every step. */ private final T[] y; /** * Constructs a new instance of step function. * * @param x Argument of every steps start. * @param y Value of every step. */ public StepFunction(double[] x, T[] y) { if (x.length != y.length) throw new IllegalArgumentException("Argument and value arrays have to be the same length"); this.x = x; this.y = y; Utils.quickSort(x, y); } /** * Adds the given step function to this. * * @param b Another step function. * @return Sum of this and the given function. */ public StepFunction<T> add(StepFunction<T> b) { int resSize = 0, leftPtr = 0, rightPtr = 0; double previousPnt = 0; while (leftPtr < x.length || rightPtr < b.x.length) { if (rightPtr >= b.x.length || (leftPtr < x.length && x[leftPtr] < b.x[rightPtr])) { if (resSize == 0 || x[leftPtr] != previousPnt) { previousPnt = x[leftPtr]; resSize++; } leftPtr++; } else { if (resSize == 0 || b.x[rightPtr] != previousPnt) { previousPnt = b.x[rightPtr]; resSize++; } rightPtr++; } } double[] resX = new double[resSize]; T[] resY = Arrays.copyOf(y, resSize); leftPtr = 0; rightPtr = 0; for (int i = 0; leftPtr < x.length || rightPtr < b.x.length; i++) { if (rightPtr >= b.x.length || (leftPtr < x.length && x[leftPtr] < b.x[rightPtr])) { boolean override = i > 0 && x[leftPtr] == resX[i - 1]; int target = override ? i - 1 : i; resY[target] = override ? resY[target] : null; resY[target] = i > 0 ? resY[i - 1] : null; resY[target] = resY[target] == null ? y[leftPtr] : resY[target].add(y[leftPtr]); if (leftPtr > 0) resY[target] = resY[target].subtract(y[leftPtr - 1]); resX[target] = x[leftPtr]; i = target; leftPtr++; } else { boolean override = i > 0 && b.x[rightPtr] == resX[i - 1]; int target = override ? i - 1 : i; resY[target] = override ? resY[target] : null; resY[target] = i > 0 ? resY[i - 1] : null; resY[target] = resY[target] == null ? b.y[rightPtr] : resY[target].add(b.y[rightPtr]); if (rightPtr > 0) resY[target] = resY[target].subtract(b.y[rightPtr - 1]); resX[target] = b.x[rightPtr]; i = target; rightPtr++; } } return new StepFunction<>(resX, resY); } /** */ public double[] getX() { return x; } /** */ public T[] getY() { return y; } }
#!/bin/bash -X STORAGEDIR="/opt/extility/skyline/war/storage/" DATE=$(date "+%Y-%m-%dT%H:%M:%S") echo touch $STORAGEDIR/Cluster1.csv #touch $STORAGEDIRCluster1.csv # if ! grep -q 'DATE,Used Bytes' $STORAGEDIR/Cluster1.csv ; then # # sed -i -e '1iDATE,Used Bytes' $STORAGEDIR/Cluster1.csv; # fi # # STORAGE1=$(ssh -i /etc/extility/sshkeys/id_extility admin@10.158.208.2 /sbin/zfs get -o name,value -Hp used rpool0/sd1 | awk '{print $2}') # # echo $DATE,$STORAGE1 >> $STORAGEDIR/Cluster1.csv if ! grep -q 'DATE,Used Bytes,Available' $STORAGEDIR/Cluster1.csv ; then sed -i -e '1iDATE,Used Bytes,Available' $STORAGEDIR/Cluster1.csv; fi STORAGE1KB=$(ceph df -f json-pretty | grep total_used | awk '{print $2}' | sed -e 's/,//g') STORAGE1=$(echo $STORAGE1KB*1024 | bc) AVAILABLESTORAGE1KB=$(ceph df -f json-pretty | grep total_avail | awk '{print $2}' | sed -e 's/,//g' | sed -e 's/}//g') AVAILABLESTORAGE1=$(echo $AVAILABLESTORAGE1KB*1024 | bc) echo $DATE,$STORAGE1,$AVAILABLESTORAGE1 >> $STORAGEDIR/Cluster1.csv touch $STORAGEDIR/Cluster2.csv if ! grep -q 'DATE,Used Bytes,Available' $STORAGEDIR/Cluster2.csv ; then sed -i -e '1iDATE,Used Bytes,Available' $STORAGEDIR/Cluster2.csv; fi STORAGE2KB=$(sshe 10.0.0.1 ceph df -f json-pretty | grep total_used | awk '{print $2}' | sed -e 's/,//g') STORAGE2=$(echo $STORAGE2KB*1024 | bc) AVAILABLESTORAGE2KB=$(sshe 10.0.0.1 ceph df -f json-pretty | grep total_avail | awk '{print $2}' | sed -e 's/,//g' | sed -e 's/}//g') AVAILABLESTORAGE2=$(echo $AVAILABLESTORAGE2KB*1024 | bc) echo $DATE,$STORAGE2,$AVAILABLESTORAGE2 >> $STORAGEDIR/Cluster2.csv
/* * Copyright (C) 2014 Square, Inc. * Copyright (C) 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.oriley.epoxy; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.JsonReader; import android.util.JsonToken; import android.util.JsonWriter; import java.io.IOException; /** * Converts Java values to JSON, and JSON values to Java. */ @SuppressWarnings("WeakerAccess") public abstract class JsonAdapter<T> { static final String ERROR_FORMAT = "Expected %s but was %s in %s"; static final String CLASS_SUFFIX = "$$JsonAdapter"; @Nullable public abstract T fromJson(@NonNull Epoxy epoxy, @NonNull JsonReader reader) throws IOException; public abstract void toJson(@NonNull Epoxy epoxy, @NonNull JsonWriter writer, @Nullable T value) throws IOException; /** * Returns a JSON adapter equal to this JSON adapter, but with support for reading and writing * nulls. */ public final JsonAdapter<T> nullSafe() { final JsonAdapter<T> delegate = this; return new JsonAdapter<T>() { @Override @Nullable public T fromJson(@NonNull Epoxy epoxy, @NonNull JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } else { return delegate.fromJson(epoxy, reader); } } @Override public void toJson(@NonNull Epoxy epoxy, @NonNull JsonWriter writer, @Nullable T value) throws IOException { if (value == null) { writer.nullValue(); } else { delegate.toJson(epoxy, writer, value); } } @Override public String toString() { return delegate + ".nullSafe()"; } }; } protected static int rangeCheckNextInt(@NonNull JsonReader reader, @NonNull String typeMessage, int min, int max) throws IOException { int value = reader.nextInt(); if (value < min || value > max) { throw new JsonException(String.format(ERROR_FORMAT, typeMessage, value, reader.toString())); } return value; } protected static char lengthCheckNextChar(@NonNull JsonReader reader) throws IOException { String value = reader.nextString(); if (value.length() > 1) { throw new JsonException(String.format(ERROR_FORMAT, "a char", '"' + value + '"', reader.toString())); } return value.charAt(0); } protected static boolean handleNull(@NonNull JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return true; } else { return false; } } }
declare const _default: (req: any, res: any) => Promise<void>; /** * @oas [post] /gift-cards * operationId: "PostGiftCards" * summary: "Create a Gift Card" * description: "Creates a Gift Card that can redeemed by its unique code. The Gift Card is only valid within 1 region." * x-authenticated: true * requestBody: * content: * application/json: * schema: * properties: * value: * type: integer * description: The value (excluding VAT) that the Gift Card should represent. * is_disabled: * type: boolean * description: Whether the Gift Card is disabled on creation. You will have to enable it later to make it available to Customers. * ends_at: * type: string * format: date-time * description: The time at which the Gift Card should no longer be available. * region_id: * description: The id of the Region in which the Gift Card can be used. * type: array * items: * type: string * metadata: * description: An optional set of key-value pairs to hold additional information. * type: object * tags: * - Gift Card * responses: * 200: * description: OK * content: * application/json: * schema: * properties: * gift_card: * $ref: "#/components/schemas/gift_card" */ export default _default; export declare class AdminPostGiftCardsReq { value?: number; ends_at?: Date; is_disabled?: boolean; region_id?: string; metadata?: object; }
SELECT * FROM tableName WHERE phoneNumber = 'XXXXXXXXXX';
#!/bin/sh echo "This is command2";
#!/bin/sh set -e if [ "$RUN_E2E_TESTS" != "true" ]; then echo "Skipping end to end tests." else echo "Running end to end tests..." wget https://github.com/segmentio/library-e2e-tester/releases/download/0.3.2/tester_linux_amd64 -O tester chmod +x tester ./tester -path='./cli.js' -concurrency=3 echo "End to end tests completed!" fi
def fibonacci(n): fib_list = [0, 1] if(n < 2): return fib_list[n] while(n > 1): next_fib = fib_list[-1] + fib_list[-2] fib_list.append(next_fib) n -= 1 return fib_list n = int(input("Enter number: ")) fibonacci = fibonacci(n) print(fibonacci)
#!/usr/bin/env bash set -xe SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" SRC=$SCRIPT_DIR/../src LIB=$SCRIPT_DIR/../lib npm run babel # Produce the bundled ES5 into /dist npm run build:gh-client # Copy the LESS assets out into /lib # cd to src so it doesn't appear in the find output cd $SRC ASSET_FILES=$(find . -name \*.css) for FILE in $ASSET_FILES; do DIR_PATH=$(dirname $FILE) sudo mkdir -p $LIB/$DIR_PATH sudo cp $FILE $LIB/$FILE sudo mkdir -p $ESM/$DIR_PATH sudo cp $FILE $ESM/$FILE done
Two possible ways to encrypt the data stored in `data.csv` are: (1) using Advanced Encryption Standard (AES) and (2) using a cryptographic hash function. AES is an established, reliable algorithm for symmetric key encryption, which means the same key is used for both encryption and decryption. A cryptographic hash function is a secure one-way function which takes an arbitrary block of data and produces a unique, fixed-length output. It is effective in that the same data will always result in the same hash, making it very difficult to tamper with the data without the recipient being able to detect the change.
<gh_stars>0 /****************************************************************************** Copyright (c) 2015, Intel Corporation Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ var gulp = require("gulp"); var nib = require("nib"); var _ = require("lodash"); var browserify = require("browserify"); var watchify = require("watchify"); var babel = require("babelify"); // load plugins var $ = require("gulp-load-plugins")(); var wiredep = require("wiredep").stream; var RELEASE = process.env.NODE_ENV === "production"; var DEBUG = !RELEASE; gulp.task("hope_css", function () { gulp.src("ui/styles/hope.styl") .pipe($.plumber()) .pipe($.if(DEBUG, $.sourcemaps.init())) .pipe($.stylus({use: nib(), import: ["nib"]})) .pipe($.plumber.stop()) .pipe($.if(DEBUG, $.sourcemaps.write("."))) .pipe(gulp.dest("public/css")); }); function make_bundle(watch) { // add custom browserify options here var customOpts = { entries: "./ui/js/index.js", debug: DEBUG }; var opts = _.assign({}, watchify.args, customOpts); var _bundle = browserify(opts).transform(babel.configure({ sourceMap: RELEASE ? false : "inline", optional: ["es7.classProperties"] })); if (watch) { _bundle = watchify(_bundle); } var f = function() { $.util.log("Starting browserify"); var source = require("vinyl-source-stream"); var buffer = require("vinyl-buffer"); return _bundle.bundle() .on("error", function (err) { console.log(err); }) .pipe($.plumber()) .pipe(source("hope.js")) .pipe(buffer()) .pipe($.if(DEBUG, $.sourcemaps.init({loadMaps: true}))) // Add transformation tasks to the pipeline here. .pipe($.if(RELEASE, $.uglify())) .on("error", $.util.log) .pipe($.plumber.stop()) .pipe($.if(DEBUG, $.sourcemaps.write("."))) .pipe(gulp.dest("public/js")); }; if (watch) { _bundle.on("update", f); } return f; } gulp.task("hope_js", make_bundle(false)); // all 3rd party files into ui/*.html gulp.task("wire_html", function() { return gulp.src("ui/*.html") .pipe($.plumber()) .pipe(wiredep({ directory: "ui/bower_components" })) .pipe($.plumber.stop()) .pipe(gulp.dest("ui")); }); // NOTE that this would result in vendor.js / vendor.css gulp.task("hope_html", ["wire_html"], function () { return gulp.src("ui/*.html") .pipe($.plumber()) .pipe($.useref({searchPath: [".tmp", "ui"]})) .pipe($.if("*.js", $.uglify())) .pipe($.if("*.css", $.csso())) .pipe($.plumber.stop()) .pipe(gulp.dest("public")); }); gulp.task("hope_image", function() { return gulp.src("ui/images/**/*") .pipe(gulp.dest("public/images")); }); gulp.task("fonts", function () { return gulp.src(["ui/bower_components/bootstrap/fonts/*", "ui/bower_components/font-awesome/fonts/*"]) .pipe($.flatten()) .pipe(gulp.dest("public/fonts")); }); gulp.task("clean", function () { return gulp.src(["public/*", ".tmp"], { read: false }).pipe($.rimraf()); }); gulp.task("build", ["hope_css", "hope_js", "hope_html", "hope_image", "fonts"], function() { }); gulp.task("start", function () { require("opn")("http://localhost:8080"); }); gulp.task("watch_js", make_bundle(true)); // rebundle in case any dep changed gulp.task("watch", ["watch_js"], function () { gulp.watch("ui/images/**/*", ["hope_image"]); gulp.watch(["ui/styles/**/*.styl"], ["hope_css"]); gulp.watch("ui/*.html", ["hope_html"]); gulp.watch("bower.json", ["hope_html"]); });
/* * delay.c * * Created on: Jan 11, 2021 * Author: linhao */ #include "delay.h" #include "stm32f1xx_hal.h" //void delay_us(uint32_t us) { // uint32_t delay = (HAL_RCC_GetHCLKFreq() / 4000000 * us); // while (delay--) { // ; // } //} uint32_t DWT_Init(void) { if (!(CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA_Msk)) { CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; } /* Reset the clock cycle counter value */ DWT->CYCCNT = 0; /* Enable clock cycle counter */ DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; for (int i = 0; i < 5; ++i) { __NOP(); } /* Check if clock cycle counter has started */ return (DWT->CYCCNT) ? 0 : 1; } void DWT_DelayUs(volatile uint32_t us) { uint32_t startTick = DWT->CYCCNT; uint32_t delayTicks = us * (SystemCoreClock / 1000000); while (DWT->CYCCNT - startTick < delayTicks) ; } void DWT_DelayMs(uint32_t ms) { DWT_DelayUs(1000 * ms); }
<reponame>Farhaan900/boiler-plate-all-services-2<gh_stars>0 package com.stackroute.playerservice.exceptions; /** * Custom Exception to handle conditions where players were not found */ public class PlayerNotFoundException extends Exception { public PlayerNotFoundException(String s) { super(s); } }
<reponame>sagarchauhan005/serverless-screen-grab-service<filename>index.js let response; const validUrl = require('valid-url'); const chromium = require('chrome-aws-lambda'); const { v4: uuidv4 } = require('uuid'); const AWS = require('aws-sdk') const fs = require("fs"); AWS.config.update({ region: 'ap-south-1' }) const bucketName = process.env.UploadBucket; const s3 = new AWS.S3({ bucketName: bucketName }); let browser = null; let buffer = null; // overall constants const screenWidth = 1920; const screenHeight = 1080; const prefix = 'screenshots/'; /** * @param {T|string} targetUrl * @param {string} image_path_prefix */ const getScreenshot = async (targetUrl, image_path_prefix) => { try{ browser = await chromium.puppeteer.launch({ args: chromium.args, defaultViewport: chromium.defaultViewport, executablePath: await chromium.executablePath, headless: chromium.headless, ignoreHTTPSErrors: true, }); const page = await browser.newPage(); const image_name = image_path_prefix+uuidv4()+"-"+new Date().getTime()+'.png'; await page.setViewport({ width: screenWidth, height: screenHeight, deviceScaleFactor: 1, }); await page.goto(targetUrl, { waitUntil: 'networkidle0', }); buffer = await page.screenshot(); return { 'name': image_name, 'buffer': buffer, }; } catch (error) { console.log("Something went wrong during getScreenshot"); console.log(error) } finally { if (browser !== null) { await browser.close(); } } }; async function uploadToS3(name, buffer, image_path_prefix) { let upload = null; const params = { Bucket: process.env.UploadBucket, Key: name, Body: buffer, ContentType: 'image/png', }; upload = await s3.upload(params).promise(); console.log("uploaded filed response",upload); return upload; } /** * * @param {Object} event - API Gateway Lambda Proxy Input Format * @param {Object} context * @returns {Object} object - API Gateway Lambda Proxy Output Format * */ exports.handler = async (event, context) => { console.log(event); const targetUrl = event.queryStringParameters.url || "https://www.google.com"; // check if the given url is valid if (!validUrl.isUri(targetUrl)) { response = { 'statusCode': 422, 'body': JSON.stringify({ message: "Invalid Url: Please provide a valid url, not:"+targetUrl, }) } } try { let response = await getScreenshot(targetUrl, prefix); let getUploadedFile = await uploadToS3(response.name, response.buffer, prefix); response = { 'statusCode': 200, "headers": { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers":"*" }, 'body': JSON.stringify({ message: { "response" : "Screenshot successfully taken for your domain", "image_key": getUploadedFile.Key, "image_path": getUploadedFile.Location }, }) } //console.log("response", response); return response } catch (err) { console.log(err) response = { 'statusCode': 500, 'body': JSON.stringify({ message: 'RenderingFailed : Unable to generate screenshot. Please contact administrator', }) } } return response };
#!/bin/bash # Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ echo "==============================================================================================================" echo "Please run the scipt as: " echo "bash run_standalone_pretrain_ascend.sh DEVICE_ID EPOCH_SIZE" echo "for example: bash run_standalone_pretrain_ascend.sh 0 350" echo "==============================================================================================================" DEVICE_ID=$1 EPOCH_SIZE=$2 mkdir -p ms_log PROJECT_DIR=$(cd "$(dirname "$0")" || exit; pwd) CUR_DIR=`pwd` export GLOG_log_dir=${CUR_DIR}/ms_log export GLOG_logtostderr=0 python ${PROJECT_DIR}/../train.py \ --distribute=false \ --need_profiler=false \ --profiler_path=./profiler \ --epoch_size=$EPOCH_SIZE \ --device_id=$DEVICE_ID \ --enable_save_ckpt=true \ --do_shuffle=true \ --enable_data_sink=true \ --data_sink_steps=50 \ --load_checkpoint_path="" \ --save_checkpoint_steps=10000 \ --save_checkpoint_num=1 \ --mindrecord_dir="" \ --mindrecord_prefix="coco_hp.train.mind" \ --visual_image=false \ --save_result_dir="" > training_log.txt 2>&1 &
<reponame>ernestyalumni/CompPhys /** * @file : Groups.h * @author : <NAME> * @email : <EMAIL> * @brief : Groups as an abstract type. * @details A group * @ref : 3.2.1.2 A Container, Ch. 3 A Tour of C++: Abstraction * Mechanisms. Bjarne Stroustrup, The C++ Programming Language, 4th Ed. * * If you find this code useful, feel free to donate directly and easily at this direct PayPal link: * * https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=ernestsaveschristmas%2bpaypal%40gmail%2ecom&lc=US&item_name=ernestyalumni&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted * * which won't go through a 3rd. party such as indiegogo, kickstarter, patreon. * Otherwise, I receive emails and messages on how all my (free) material on physics, math, and engineering have * helped students with their studies, and I know what it's like to not have money as a student, but love physics * (or math, sciences, etc.), so I am committed to keeping all my material open-source and free, whether or not * sufficiently crowdfunded, under the open-source MIT license: * feel free to copy, edit, paste, make your own versions, share, use as you wish. * Peace out, never give up! -EY * * COMPILATION TIPS: * g++ -std=c++14 Groups.cpp Groups_main.cpp -o Groups_main * */ #ifndef _GROUPS_H_ #define _GROUPS_H_ namespace Groups { //------------------------------------------------------------------------------ /// \brief Group /// \details Use CRTP pattern. /// \ref https://stackoverflow.com/questions/27180342/pure-virtual-function-in-abstract-class-with-return-type-of-base-derived-type //------------------------------------------------------------------------------ template <class Object> class Group { public: Group() = default; Group(const Group&) = delete; Group& operator=(const Group&) = delete; Group(Group&&) = delete; Group& operator=(Group&&) = delete; virtual Object& operator*=(const Object& g) = 0; // pure virtual function template <class Obj> friend Obj operator*(Obj g, const Obj& h); virtual Object identity() const = 0; // pure virtual function virtual Object inverse() const = 0; // pure virtual function virtual ~Group() {} }; template <class Object> class AbelianGroup { public: AbelianGroup() = default; // copy constructor needed for binary addition AbelianGroup(const AbelianGroup&) = default; AbelianGroup& operator=(const AbelianGroup&) = delete; // move constructor needed because in derived classes, identity will need it AbelianGroup(AbelianGroup&&) = delete; AbelianGroup& operator=(AbelianGroup&&) = delete; virtual Object& operator+=(const Object& g) = 0; template <class Obj> friend Obj operator+(Obj g, const Obj& h); virtual Object identity() const = 0; // pure virtual function virtual Object inverse() const = 0; virtual ~AbelianGroup() {} }; } // namespace Groups #endif // _GROUPS_H_
class ComplexNumber { constructor(real, imaginary) { this.real = real; this.imaginary = imaginary; } }
<reponame>m-nakagawa/sample<filename>jena-3.0.1/jena-core/src/main/java/org/apache/jena/reasoner/rulesys/GenericRuleReasonerFactory.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.reasoner.rulesys; import org.apache.jena.rdf.model.* ; import org.apache.jena.reasoner.* ; import org.apache.jena.vocabulary.ReasonerVocabulary ; /** * Factory object for creating general rule reasoner instances. The * specific rule set and mode confriguration can be set either be method * calls to the created reasoner or though parameters in the configuration Model. */ public class GenericRuleReasonerFactory implements ReasonerFactory { /** Single global instance of this factory */ private static GenericRuleReasonerFactory theInstance = new GenericRuleReasonerFactory(); /** Static URI for this reasoner type */ public static final String URI = "http://jena.hpl.hp.com/2003/GenericRuleReasoner"; /** Cache of the capabilities description */ protected Model capabilities; /** * Return the single global instance of this factory */ public static GenericRuleReasonerFactory theInstance() { return theInstance; } /** * Constructor method that builds an instance of the associated Reasoner * @param configuration a set of arbitrary configuration information to be * passed the reasoner, encoded as RDF properties of a base configuration resource, * can be null in no custom configuration is required. */ @Override public Reasoner create( Resource configuration ) { return new GenericRuleReasoner( this, configuration ); } /** * Return a description of the capabilities of this reasoner encoded in * RDF. This method is normally called by the ReasonerRegistry which caches * the resulting information so dynamically creating here is not really an overhead. */ @Override public Model getCapabilities() { if (capabilities == null) { capabilities = ModelFactory.createDefaultModel(); Resource base = capabilities.createResource(getURI()); base.addProperty(ReasonerVocabulary.nameP, "Generic Rule Reasoner") .addProperty(ReasonerVocabulary.descriptionP, "Generic rule reasoner, configurable") .addProperty(ReasonerVocabulary.versionP, "0.1"); } return capabilities; } /** * Return the URI labelling this type of reasoner */ @Override public String getURI() { return URI; } }
def tokenize(s): tokens = [] current_token = "" for c in s: if c.isspace(): tokens.append(current_token) current_token = "" else: current_token += c if current_token: tokens.append(current_token) return tokens
// Define the custom plugin const enforceSyncGettersPlugin = store => { const { getters } = store._modules.root.context Object.keys(getters).forEach(getterName => { const getterFn = getters[getterName] if (getterFn.constructor.name === "AsyncFunction") { throw new Error(`Asynchronous function detected in getter: ${getterName}`) } }) } // Create the Vuex store with the custom plugin const store = new Vuex.Store({ // ... other store configurations plugins: [enforceSyncGettersPlugin] })
gcc main.c myfactory.c -ldl gcc -shared parrot.c -o parrot.so -fPIC gcc -shared tiger.c -o tiger.so -fPIC ./a.out
/** * Author: thegoldenmule */ var main = (function() { "use strict"; var canvas, renderer, engine = new Engine(), scene = engine.getScene(); var runTests = (function() { var index = 0; return function(suite) { if (suite.tests.length > index) { suite.tests[index++](); setTimeout(runTests, 2000, suite); } }; })(); return function() { var that = this; ////////////// // boilerplate canvas = document.getElementById('stage'); renderer = new WebGLRenderer(canvas); engine.initialize(renderer); setupDebugEnvironment(engine); // end boilerplate ////////////////// var displayObjects = []; [ new Color(1, 0, 0), new Color(0.75, 0.25, 0), new Color(0.5, 0.5, 0), new Color(0.25, 0.75, 0.5), new Color(0, 1, 0), new Color(0, 0.75, 0.25), new Color(0, 0.5, 0.5), new Color(0, 0.25, 0.75), new Color(0, 0, 1), new Color(0, 0, 0) ].forEach(function(item, index, array) { var shape = new Shape({ width: Math.pow(2, array.length - index), height: Math.pow(2, array.length - index), tint: item }); engine.getScene().root.addChild(shape); displayObjects.push(shape); }); runTests(new TestSuite(displayObjects)); }; function setupDebugEnvironment(engine) { window.isTwoDeeDebug = true; // stats var stats = new Stats(); stats.setMode(0); stats.domElement.style.position = 'absolute'; stats.domElement.style.left = '0px'; stats.domElement.style.top = '0px'; document.body.appendChild(stats.domElement); // update stats engine.onPreUpdate.add(stats.begin); engine.onPostUpdate.add(stats.end); $(document).keydown(function(event) { if (13 === event.which) { engine.paused = !engine.paused; } }); } })(); var TestSuite = (function() { "use strict"; return function(displayObjects) { this.tests = [ parentTest, colorTest, colorRootTest, anchorPointTest, anchorPointRotationTest ]; function parentTest() { for (var i = 1, len = displayObjects.length; i < len; i++) { displayObjects[i - 1].addChild(displayObjects[i]); displayObjects[i].transform.position.x = displayObjects[i - 1].getWidth() / 2 - displayObjects[i].getWidth() / 2; displayObjects[i].transform.position.y = displayObjects[i - 1].getHeight() / 2 - displayObjects[i].getHeight() / 2; displayObjects[i - 1].transform.rotationInRadians = Math.PI / 12; } } function colorTest() { displayObjects[0].transform.rotationInRadians = 0; for (var i = 1, len = displayObjects.length; i < len; i++) { displayObjects[0].addChild(displayObjects[i]); displayObjects[i].transform.position.x = displayObjects[i - 1].getWidth() / 2 - displayObjects[i].getWidth() / 2; displayObjects[i].transform.position.y = displayObjects[i - 1].getHeight() / 2 - displayObjects[i].getHeight() / 2; displayObjects[i].transform.rotationInRadians = 0; } } function colorRootTest() { for (var i = 1, len = displayObjects.length; i < len; i++) { displayObjects[0].getParent().addChild(displayObjects[i]); displayObjects[i].transform.position.x = displayObjects[i - 1].getWidth() / 2 - displayObjects[i].getWidth() / 2; displayObjects[i].transform.position.y = displayObjects[i - 1].getHeight() / 2 - displayObjects[i].getHeight() / 2; displayObjects[i].transform.rotationInRadians = 0; } } function anchorPointTest() { for (var i = 1, len = displayObjects.length; i < len; i++) { displayObjects[0].getParent().addChild(displayObjects[i]); displayObjects[i].transform.anchorPoint.x = displayObjects[i].getWidth() / 2; displayObjects[i].transform.anchorPoint.y = displayObjects[i].getHeight() / 2; displayObjects[i].transform.position.x = displayObjects[0].getWidth() / 2; displayObjects[i].transform.position.y = displayObjects[0].getHeight() / 2; displayObjects[i].transform.rotationInRadians = 0; } } function anchorPointRotationTest() { for (var i = 1, len = displayObjects.length; i < len; i++) { displayObjects[0].getParent().addChild(displayObjects[i]); displayObjects[i].transform.anchorPoint.x = displayObjects[i].getWidth() / 2; displayObjects[i].transform.anchorPoint.y = displayObjects[i].getHeight() / 2; displayObjects[i].transform.position.x = displayObjects[0].getWidth() / 2; displayObjects[i].transform.position.y = displayObjects[0].getHeight() / 2; displayObjects[i].transform.rotationInRadians = (2 * Math.PI / len) * i; } } }; })();
#include <stdio.h> void printPascal(int n) { for (int line = 0; line < n; line++) { int C = 1; // used to represent C(line, i) for (int i = 1; i <= line; i++) { printf("%d ", C); C = C * (line - i) / i; } printf("\n"); } } int main() { int n = 10; printPascal(n); return 0; }
@RestController @RequestMapping("/users") public class UserController { private List<User> users; public UserController() { this.users = Arrays.asList( new User(1, "John", 25), new User(2, "Paul", 30) ); } @GetMapping("/{id}") public User getUser(@PathVariable("id") int id) { return this.users.stream() .filter(user -> user.getId() == id) .findFirst() .orElse(null); } }
<reponame>RayFantasyStudio/blog<gh_stars>0 package models import ( "time" "github.com/astaxie/beego/orm" ) type Category struct { Id int64 Name string Created time.Time`orm:"index"` ArticleCount int64`orm:"index"` } //分类字段过滤器 const ( Filter_Category_Create = "created" Filter_Category_ArticleCount = "article_count" ) func GetCategories(order_key string,inverted bool) ([]*Category, error) { o := orm.NewOrm() qs := o.QueryTable("category") categoryList := make([]*Category, 0) var err error switch order_key { case Filter_Category_Create: if inverted{ _, err = qs.OrderBy("-" + Filter_Category_Create).All(&categoryList) }else { _, err = qs.OrderBy(Filter_Category_Create).All(&categoryList) } case Filter_Category_ArticleCount: if inverted{ _, err = qs.OrderBy("-" + Filter_Category_ArticleCount).All(&categoryList) }else { _, err = qs.OrderBy(Filter_Category_ArticleCount).All(&categoryList) } } return categoryList, err } func AddCategory(category Category) error { o := orm.NewOrm() category.Created = time.Now() _, err := o.Insert(&category) return err } func DeleteCategory(Id int64, name string) error { o := orm.NewOrm() category := new(Category) var err error //按照id删除(优先) if Id > -1 { category.Id = Id _, err = o.Delete(category) if err != nil { return err } } //按照名称(name)删除 if len(name) > 0 { category.Name = name _, err = o.Delete(name) if err != nil { return err } } return err } func ModifyCategory(former_category, category_name string) error { o := orm.NewOrm() qs := o.QueryTable("category").Filter("name",former_category) category_tmp := Category{} err := qs.One(&category_tmp) category_tmp.Name = category_name category_tmp.Created = time.Now() _,err = o.Update(&category_tmp) articles := make([]Article,0) qs_article := o.QueryTable("article").Filter("category",former_category) _,err = qs_article.All(&articles) for _,x := range articles{ x.Category = category_name _,err = o.Update(&x) } return err }
<gh_stars>10-100 require 'spec_helper' describe SparkPostRails::DeliveryMethod do before(:each) do SparkPostRails.configuration.set_defaults @delivery_method = SparkPostRails::DeliveryMethod.new end context "Campaign ID" do it "handles campaign id in the configuration" do SparkPostRails.configure do |c| c.campaign_id = "ABCD1234" end test_email = Mailer.test_email @delivery_method.deliver!(test_email) expect(@delivery_method.data[:campaign_id]).to eq("ABCD1234") end it "handles campaign id on an individual message" do test_email = Mailer.test_email sparkpost_data: {campaign_id: "My Campaign"} @delivery_method.deliver!(test_email) expect(@delivery_method.data[:campaign_id]).to eq("My Campaign") end it "handles the value on an individual message overriding configuration" do SparkPostRails.configure do |c| c.campaign_id = "ABCD1234" end test_email = Mailer.test_email sparkpost_data: {campaign_id: "My Campaign"} @delivery_method.deliver!(test_email) expect(@delivery_method.data[:campaign_id]).to eq("My Campaign") end it "handles the value on an individual message of nil overriding configuration" do SparkPostRails.configure do |c| c.campaign_id = "ABCD1234" end test_email = Mailer.test_email sparkpost_data: {campaign_id: nil} @delivery_method.deliver!(test_email) expect(@delivery_method.data.has_key?(:campaign_id)).to eq(false) end it "handles a default setting of none" do test_email = Mailer.test_email @delivery_method.deliver!(test_email) expect(@delivery_method.data.has_key?(:campaign_id)).to eq(false) end end end
#!/usr/bin/env bash PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH #================================================= # System Required: CentOS/Debian/Ubuntu # Description: tinyPortMapper # Version: 1.0.2 # Author: Toyo # Blog: https://doub.io/wlzy-36/ #================================================= sh_ver="1.0.2" Folder="/usr/local/tinyPortMapper" File="/usr/local/tinyPortMapper/tinymapper" LOG_File="/tmp/tinymapper.log" Green_font_prefix="\033[32m" && Red_font_prefix="\033[31m" && Green_background_prefix="\033[42;37m" && Red_background_prefix="\033[41;37m" && Font_color_suffix="\033[0m" Info="${Green_font_prefix}[信息]${Font_color_suffix}" && Error="${Red_font_prefix}[错误]${Font_color_suffix}" && Tip="${Green_font_prefix}[注意]${Font_color_suffix}" Get_IP(){ ip=$(wget -qO- -t1 -T2 ipinfo.io/ip) if [[ -z "${ip}" ]]; then ip=$(wget -qO- -t1 -T2 api.ip.sb/ip) if [[ -z "${ip}" ]]; then ip=$(wget -qO- -t1 -T2 members.3322.org/dyndns/getip) if [[ -z "${ip}" ]]; then ip="VPS_IP" fi fi fi } Add_iptables(){ iptables_Type=$1 if [[ ! -z "${local_Port}" ]]; then if [[ ${iptables_Type} == "tcp" ]]; then iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport ${local_Port} -j ACCEPT elif [[ ${iptables_Type} == "udp" ]]; then iptables -I INPUT -m state --state NEW -m udp -p udp --dport ${local_Port} -j ACCEPT elif [[ ${iptables_Type} == "all" ]]; then iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport ${local_Port} -j ACCEPT iptables -I INPUT -m state --state NEW -m udp -p udp --dport ${local_Port} -j ACCEPT fi fi } Del_iptables(){ iptables_Type=$1 if [[ ! -z "${port}" ]]; then if [[ ${iptables_Type} == "tcp" ]]; then iptables -D INPUT -m state --state NEW -m tcp -p tcp --dport ${port} -j ACCEPT elif [[ ${iptables_Type} == "udp" ]]; then iptables -D INPUT -m state --state NEW -m udp -p udp --dport ${port} -j ACCEPT elif [[ ${iptables_Type} == "all" ]]; then iptables -D INPUT -m state --state NEW -m tcp -p tcp --dport ${port} -j ACCEPT iptables -D INPUT -m state --state NEW -m udp -p udp --dport ${port} -j ACCEPT fi fi } Save_iptables(){ iptables-save > /etc/iptables.up.rules } Set_iptables(){ iptables-save > /etc/iptables.up.rules echo -e '#!/bin/bash\n/sbin/iptables-restore < /etc/iptables.up.rules' > /etc/network/if-pre-up.d/iptables chmod +x /etc/network/if-pre-up.d/iptables } check_tinyPortMapper(){ [[ ! -e ${File} ]] && echo -e "${Error} 没有安装 tinyPortMapper , 请检查 !" && exit 1 } check_sys(){ if [[ -f /etc/redhat-release ]]; then release="centos" elif cat /etc/issue | grep -q -E -i "debian"; then release="debian" elif cat /etc/issue | grep -q -E -i "ubuntu"; then release="ubuntu" elif cat /etc/issue | grep -q -E -i "centos|red hat|redhat"; then release="centos" elif cat /proc/version | grep -q -E -i "debian"; then release="debian" elif cat /proc/version | grep -q -E -i "ubuntu"; then release="ubuntu" elif cat /proc/version | grep -q -E -i "centos|red hat|redhat"; then release="centos" fi bit=`uname -m` } check_new_ver(){ tinymapper_new_ver=$(wget --no-check-certificate -qO- https://api.github.com/repos/wangyu-/tinyPortMapper/releases | grep -o '"tag_name": ".*"' |grep -v '20180620.0'|head -n 1| sed 's/"//g;s/v//g' | sed 's/tag_name: //g') if [[ -z ${tinymapper_new_ver} ]]; then echo -e "${Error} tinyPortMapper 最新版本获取失败,请手动获取最新版本号[ https://github.com/wangyu-/tinyPortMapper/releases ]" read -e -p "请输入版本号 [ 格式是日期 , 如 20180224.0 ] :" tinymapper_new_ver [[ -z "${tinymapper_new_ver}" ]] && echo "取消..." && exit 1 else echo -e "${Info} 检测到 tinyPortMapper 最新版本为 [ ${tinymapper_new_ver} ]" fi } Download_tinyPortMapper(){ cd ${Folder} wget -N --no-check-certificate "https://github.com/wangyu-/tinyPortMapper/releases/download/${tinymapper_new_ver}/tinymapper_binaries.tar.gz" [[ ! -e "tinymapper_binaries.tar.gz" ]] && echo -e "${Error} tinyPortMapper 压缩包下载失败 !" && exit 1 tar -xzf tinymapper_binaries.tar.gz if [[ ${bit} == "x86_64" ]]; then [[ ! -e "tinymapper_amd64" ]] && echo -e "${Error} tinyPortMapper 解压失败 !" && exit 1 mv tinymapper_amd64 tinymapper else [[ ! -e "tinymapper_x86" ]] && echo -e "${Error} tinyPortMapper 解压失败 !" && exit 1 mv tinymapper_x86 tinymapper fi [[ ! -e "tinymapper" ]] && echo -e "${Error} tinyPortMapper 重命名失败 !" && exit 1 chmod +x tinymapper rm -rf version.txt rm -rf tinymapper_* rm -rf tinymapper_binaries.tar.gz } Install_tinyPortMapper(){ [[ -e ${File} ]] && echo -e "${Error} 已经安装 tinyPortMapper , 请检查 !" && exit 1 mkdir ${Folder} check_new_ver Download_tinyPortMapper Set_iptables echo -e "${Info} tinyPortMapper 安装完成!" } Uninstall_tinyPortMapper(){ check_tinyPortMapper echo "确定要 卸载 tinyPortMapper?[y/N]" && echo read -e -p "(默认: n):" unyn [[ -z ${unyn} ]] && unyn="n" if [[ ${unyn} == [Yy] ]]; then Uninstall_forwarding "Uninstall" rm -rf ${Folder} echo && echo " tinyPortMapper 卸载完成 !" && echo else echo && echo " 卸载已取消..." && echo fi } Uninstall_forwarding(){ Uninstall_forwarding_Type=$1 check_tinyPortMapper tinymapper_Total=$(ps -ef | grep tinymapper | grep -v grep | grep -v "tinymapper.sh" | wc -l) if [[ ${tinymapper_Total} != "0" ]]; then for((integer = 1; integer <= ${tinymapper_Total}; integer++)) do Uninstall_all=$(ps -ef | grep tinymapper | grep -v grep | grep -v "tinymapper.sh") Uninstall_pid=$(echo -e "${Uninstall_all}"| sed -n "1p"| awk '{print $2}') Uninstall_listen=$(echo -e "${Uninstall_all}"| sed -n "1p"| awk '{print $10}'| awk -F ':' '{print $NF}') Uninstall_type_tcp=$(echo -e "${Uninstall_all}"| sed -n "1p"| awk '{print $13}') if [[ ${Uninstall_type_tcp} == "-t" ]]; then Uninstall_type_udp=$(echo -e "${Uninstall_all}"| sed -n "1p"| awk '{print $14}') if [[ ${Uninstall_type_udp} == "-u" ]]; then Uninstall_type="all" else Uninstall_type="tcp" fi else Uninstall_type="udp" fi kill -9 "${Uninstall_pid}" Del_iptables "${Uninstall_type}" sleep 1s done fi if [[ ${Uninstall_forwarding_Type} != "Uninstall" ]]; then tinymapper_Total=$(ps -ef | grep tinymapper | grep -v grep | grep -v "tinymapper.sh" | wc -l) if [[ ${tinymapper_Total} == "0" ]]; then echo -e "${Info} tinyPortMapper 所有端口转发已清空!" else echo -e "${Error} tinyPortMapper 所有端口转发清空失败!" fi fi } Add_forwarding(){ check_tinyPortMapper Set_local_Port Set_Mapper_Port Set_Mapper_IP Set_Mapper_Type Mapper_Type_1=${Mapper_Type} [[ ${Mapper_Type_1} == "ALL" ]] && Mapper_Type_1="TCP+UDP" echo -e "\n—————————————————————————————— 请检查 tinyPortMapper 配置是否有误 !\n 本地监听端口\t : ${Red_background_prefix} ${local_Port} ${Font_color_suffix} 远程转发 IP\t : ${Red_background_prefix} ${Mapper_IP} ${Font_color_suffix} 远程转发端口\t : ${Red_background_prefix} ${Mapper_Port} ${Font_color_suffix} 转发类型\t : ${Red_background_prefix} ${Mapper_Type_1} ${Font_color_suffix} ——————————————————————————————\n" read -e -p "请按任意键继续,如有配置错误请使用 Ctrl+C 退出。" var Start_tinyPortMapper Get_IP clear echo -e "\n—————————————————————————————— tinyPortMapper 已启动 !\n 本地监听 IP\t : ${Red_background_prefix} ${ip} ${Font_color_suffix} 本地监听端口\t : ${Red_background_prefix} ${local_Port} ${Font_color_suffix}\n 远程转发 IP\t : ${Red_background_prefix} ${Mapper_IP} ${Font_color_suffix} 远程转发端口\t : ${Red_background_prefix} ${Mapper_Port} ${Font_color_suffix} 转发类型\t : ${Red_background_prefix} ${Mapper_Type_1} ${Font_color_suffix} ——————————————————————————————\n" } Set_local_Port(){ while true do echo -e "请输入 tinyPortMapper 的 本地监听端口 [1-65535]" read -e -p "(默认回车取消):" local_Port [[ -z "${local_Port}" ]] && echo "已取消..." && exit 1 echo $((${local_Port}+0)) &>/dev/null if [[ $? -eq 0 ]]; then if [[ ${local_Port} -ge 1 ]] && [[ ${local_Port} -le 65535 ]]; then echo echo "——————————————————————————————" echo -e " 本地监听端口 : ${Red_background_prefix} ${local_Port} ${Font_color_suffix}" echo "——————————————————————————————" echo break else echo -e "${Error} 请输入正确的数字 !" fi else echo -e "${Error} 请输入正确的数字 !" fi done } Set_Mapper_Port(){ while true do echo -e "请输入 tinyPortMapper 远程被转发 端口 [1-65535](就是被中转服务器的端口)" read -e -p "(默认同本地监听端口: ${local_Port}):" Mapper_Port [[ -z "${Mapper_Port}" ]] && Mapper_Port=${local_Port} echo $((${Mapper_Port}+0)) &>/dev/null if [[ $? -eq 0 ]]; then if [[ ${Mapper_Port} -ge 1 ]] && [[ ${Mapper_Port} -le 65535 ]]; then echo echo "——————————————————————————————" echo -e " 远程转发端口 : ${Red_background_prefix} ${Mapper_Port} ${Font_color_suffix}" echo "——————————————————————————————" echo break else echo -e "${Error} 请输入正确的数字 !" fi else echo -e "${Error} 请输入正确的数字 !" fi done } Set_Mapper_IP(){ echo -e "请输入 tinyPortMapper 远程被转发 IP(就是被中转服务器的外网IP)" read -e -p "(默认回车取消):" Mapper_IP [[ -z "${Mapper_IP}" ]] && echo "已取消..." && exit 1 echo echo "——————————————————————————————" echo -e " 远程转发 IP : ${Red_background_prefix} ${Mapper_IP} ${Font_color_suffix}" echo "——————————————————————————————" echo } Set_Mapper_Type(){ echo -e "请输入数字 来选择 tinyPortMapper 转发类型:" echo -e " 1. TCP\n 2. UDP\n 3. TCP+UDP(ALL)\n" read -e -p "(默认: TCP+UDP):" Mapper_Type_num [[ -z "${Mapper_Type_num}" ]] && Mapper_Type_num="3" if [[ ${Mapper_Type_num} = "1" ]]; then Mapper_Type="TCP" elif [[ ${Mapper_Type_num} = "2" ]]; then Mapper_Type="UDP" elif [[ ${Mapper_Type_num} = "3" ]]; then Mapper_Type="ALL" else Mapper_Type="ALL" fi } Start_tinyPortMapper(){ cd ${Folder} if [[ ${Mapper_Type} = "TCP" ]]; then Run_tinyPortMapper "-t" sleep 2s PID=$(ps -ef | grep "./tinymapper -l 0.0.0.0:${local_Port}" | grep -v grep | awk '{print $2}') [[ -z ${PID} ]] && echo -e "${Error} tinyPortMapper TCP 启动失败 !" && exit 1 Add_iptables "tcp" elif [[ ${Mapper_Type} = "UDP" ]]; then Run_tinyPortMapper "-u" sleep 2s PID=$(ps -ef | grep "./tinymapper -l 0.0.0.0:${local_Port}" | grep -v grep | awk '{print $2}') [[ -z ${PID} ]] && echo -e "${Error} tinyPortMapper UDP 启动失败 !" && exit 1 Add_iptables "udp" elif [[ ${Mapper_Type} = "ALL" ]]; then Run_tinyPortMapper "-t -u" sleep 2s PID=$(ps -ef | grep "./tinymapper -l 0.0.0.0:${local_Port}" | grep -v grep | awk '{print $2}') [[ -z ${PID} ]] && echo -e "${Error} tinyPortMapper TCP+UDP 启动失败 !" && exit 1 Add_iptables "all" fi Save_iptables } Run_tinyPortMapper(){ nohup ./tinymapper -l 0.0.0.0:${local_Port} -r ${Mapper_IP}:${Mapper_Port} $1 > ${LOG_File} 2>&1 & } View_forwarding(){ check_tinyPortMapper tinymapper_Total=$(ps -ef | grep tinymapper | grep -v grep | grep -v "tinymapper.sh" | wc -l) if [[ ${tinymapper_Total} = "0" ]]; then echo -e "${Error} 没有发现 tinyPortMapper 进程运行,请检查 !" && exit 1 fi tinymapper_list_all="" for((integer = 1; integer <= ${tinymapper_Total}; integer++)) do tinymapper_all=$(ps -ef | grep tinymapper | grep -v grep | grep -v "tinymapper.sh") tinymapper_pid=$(echo -e "${tinymapper_all}"| sed -n "${integer}p"| awk '{print $2}') tinymapper_listen=$(echo -e "${tinymapper_all}"| sed -n "${integer}p"| awk '{print $10}'| awk -F ':' '{print $NF}') tinymapper_fork=$(echo -e "${tinymapper_all}"| sed -n "${integer}p"| awk '{print $12}') tinymapper_type_tcp=$(echo -e "${tinymapper_all}"| sed -n "${integer}p"| awk '{print $13}') if [[ ${tinymapper_type_tcp} == "-t" ]]; then tinymapper_type_udp=$(echo -e "${tinymapper_all}"| sed -n "${integer}p"| awk '{print $14}') if [[ ${tinymapper_type_udp} == "-u" ]]; then tinymapper_type="TCP+UDP" else tinymapper_type="TCP" fi else tinymapper_type="UDP" fi tinymapper_list_all=${tinymapper_list_all}"进程PID: ${Red_font_prefix}"${tinymapper_pid}"${Font_color_suffix} 类型: ${Red_font_prefix}"${tinymapper_type}"${Font_color_suffix} 监听端口: ${Green_font_prefix}"${tinymapper_listen}"${Font_color_suffix} 转发IP和端口: ${Green_font_prefix}"${tinymapper_fork}"${Font_color_suffix}\n" done echo echo -e "当前有${Green_background_prefix}" ${tinymapper_Total} "${Font_color_suffix}个 tinyPortMapper 端口转发进程。" echo -e "${tinymapper_list_all}" } Del_forwarding(){ check_tinyPortMapper PID=$(ps -ef | grep tinymapper | grep -v grep | grep -v "tinymapper.sh" | awk '{print $2}') [[ -z $PID ]] && echo -e "${Error} 没有发现 tinyPortMapper 进程运行,请检查 !" && exit 1 while true do View_forwarding read -e -p "请输入你要终止的 tinyPortMapper 本地监听端口:" Del_forwarding_port [[ -z "${Del_forwarding_port}" ]] && echo "已取消..." && exit 0 Del_port=$(echo -e "${tinymapper_list_all}"|grep ${Del_forwarding_port}) if [[ ! -z ${Del_port} ]]; then port=${Del_forwarding_port} Del_all=$(ps -ef | grep tinymapper | grep -v grep | grep -v "tinymapper.sh") pid=$(echo -e "${Del_all}"| grep "./tinymapper -l 0.0.0.0:${Del_forwarding_port}"| awk '{print $2}') Del_type_tcp=$(echo -e "${Del_all}"| grep "./tinymapper -l 0.0.0.0:${Del_forwarding_port}"| awk '{print $13}') if [[ ${Del_type_tcp} == "-t" ]]; then Del_type_udp=$(echo -e "${Del_all}"| grep "./tinymapper -l 0.0.0.0:${Del_forwarding_port}"| awk '{print $14}') if [[ ${Del_type_udp} == "-u" ]]; then Del_type="all" else Del_type="tcp" fi else Del_type="udp" fi kill -9 ${pid} sleep 2s pid=$(ps -ef | grep tinymapper | grep -v grep | grep -v "tinymapper.sh"| grep "./tinymapper -l 0.0.0.0:${Del_forwarding_port}"| awk '{print $2}') if [[ -z ${pid} ]]; then echo -e "${Info} tinyPortMapper [${Del_forwarding_port}] 终止成功!" Del_iptables "${Del_type}" else echo -e "${Error} tinyPortMapper [${Del_forwarding_port}] 终止失败!" && exit 1 fi break else echo -e "${Error} 请输入正确的端口 !" fi done } # 查看日志 View_Log(){ [[ ! -e ${LOG_File} ]] && echo -e "${Error} tinyPortMapper 日志文件不存在 !" && exit 1 echo && echo -e "${Tip} 按 ${Red_font_prefix}Ctrl+C${Font_color_suffix} 终止查看日志" && echo -e "如果需要查看完整日志内容,请用 ${Red_font_prefix}cat ${LOG_File}${Font_color_suffix} 命令。" && echo tail -f ${LOG_File} } Update_Shell(){ sh_new_ver=$(wget --no-check-certificate -qO- -t1 -T3 "https://raw.githubusercontent.com/xianyuss/doubi/master/tinymapper.sh"|grep 'sh_ver="'|awk -F "=" '{print $NF}'|sed 's/\"//g'|head -1) && sh_new_type="github" [[ -z ${sh_new_ver} ]] && echo -e "${Error} 无法链接到 Github !" && exit 0 wget -N --no-check-certificate "https://raw.githubusercontent.com/xianyuss/doubi/master/tinymapper.sh" && chmod +x tinymapper.sh echo -e "脚本已更新为最新版本[ ${sh_new_ver} ] !(注意:因为更新方式为直接覆盖当前运行的脚本,所以可能下面会提示一些报错,无视即可)" && exit 0 } check_sys [[ ${release} != "centos" ]] && [[ ${release} != "debian" ]] && [[ ${release} != "ubuntu" ]] && echo -e "${Error} 本脚本不支持当前系统 ${release} !" && exit 1 echo && echo -e " tinyPortMapper 端口转发一键管理脚本 ${Red_font_prefix}[v${sh_ver}]${Font_color_suffix} -- Toyo | doub.io/wlzy-36 -- ${Green_font_prefix}0.${Font_color_suffix} 升级脚本 ———————————— ${Green_font_prefix}1.${Font_color_suffix} 安装 tinyPortMapper ${Green_font_prefix}2.${Font_color_suffix} 卸载 tinyPortMapper ${Green_font_prefix}3.${Font_color_suffix} 清空 tinyPortMapper 端口转发 ———————————— ${Green_font_prefix}4.${Font_color_suffix} 查看 tinyPortMapper 端口转发 ${Green_font_prefix}5.${Font_color_suffix} 添加 tinyPortMapper 端口转发 ${Green_font_prefix}6.${Font_color_suffix} 删除 tinyPortMapper 端口转发 ———————————— ${Green_font_prefix}7.${Font_color_suffix} 查看 tinyPortMapper 输出日志" && echo read -e -p " 请输入数字 [0-7]:" num case "$num" in 0) Update_Shell ;; 1) Install_tinyPortMapper ;; 2) Uninstall_tinyPortMapper ;; 3) Uninstall_forwarding ;; 4) View_forwarding ;; 5) Add_forwarding ;; 6) Del_forwarding ;; 7) View_Log ;; *) echo "请输入正确数字 [0-7]" ;; esac
#!/usr/bin/env bash # Copyright (c) 2014 The Bitcoin Core developers # Copyright (c) 2014-2015 The Dash developers # Copyright (c) 2018 The Thrill developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # Functions used by more than one test function echoerr { echo "$@" 1>&2; } # Usage: ExtractKey <key> "<json_object_string>" # Warning: this will only work for the very-well-behaved # JSON produced by thrilld, do NOT use it to try to # parse arbitrary/nested/etc JSON. function ExtractKey { echo $2 | tr -d ' "{}\n' | awk -v RS=',' -F: "\$1 ~ /$1/ { print \$2}" } function CreateDataDir { DIR=$1 mkdir -p $DIR CONF=$DIR/thrill.conf echo "regtest=1" >> $CONF echo "keypool=2" >> $CONF echo "rpcuser=rt" >> $CONF echo "rpcpassword=rt" >> $CONF echo "rpcwait=1" >> $CONF echo "walletnotify=${SENDANDWAIT} -STOP" >> $CONF shift while (( "$#" )); do echo $1 >> $CONF shift done } function AssertEqual { if (( $( echo "$1 == $2" | bc ) == 0 )) then echoerr "AssertEqual: $1 != $2" declare -f CleanUp > /dev/null 2>&1 if [[ $? -eq 0 ]] ; then CleanUp fi exit 1 fi } # CheckBalance -datadir=... amount account minconf function CheckBalance { declare -i EXPECT="$2" B=$( $CLI $1 getbalance $3 $4 ) if (( $( echo "$B == $EXPECT" | bc ) == 0 )) then echoerr "bad balance: $B (expected $2)" declare -f CleanUp > /dev/null 2>&1 if [[ $? -eq 0 ]] ; then CleanUp fi exit 1 fi } # Use: Address <datadir> [account] function Address { $CLI $1 getnewaddress $2 } # Send from to amount function Send { from=$1 to=$2 amount=$3 address=$(Address $to) txid=$( ${SENDANDWAIT} $CLI $from sendtoaddress $address $amount ) } # Use: Unspent <datadir> <n'th-last-unspent> <var> function Unspent { local r=$( $CLI $1 listunspent | awk -F'[ |:,"]+' "\$2 ~ /$3/ { print \$3 }" | tail -n $2 | head -n 1) echo $r } # Use: CreateTxn1 <datadir> <n'th-last-unspent> <destaddress> # produces hex from signrawtransaction function CreateTxn1 { TXID=$(Unspent $1 $2 txid) AMOUNT=$(Unspent $1 $2 amount) VOUT=$(Unspent $1 $2 vout) RAWTXN=$( $CLI $1 createrawtransaction "[{\"txid\":\"$TXID\",\"vout\":$VOUT}]" "{\"$3\":$AMOUNT}") ExtractKey hex "$( $CLI $1 signrawtransaction $RAWTXN )" } # Use: SendRawTxn <datadir> <hex_txn_data> function SendRawTxn { ${SENDANDWAIT} $CLI $1 sendrawtransaction $2 } # Use: GetBlocks <datadir> # returns number of blocks from getinfo function GetBlocks { $CLI $1 getblockcount }
// https://cses.fi/problemset/task/1621/ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int n, s = 1; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; sort(a.begin(), a.end()); for (int i = 1; i < n; i++) if (a[i] != a[i - 1]) s++; cout << s << "\n"; }
<reponame>sambouguerra/mljs module.exports = [ "-0.38076,0.91886,0", "-0.50749,0.90424,0", "-0.54781,0.70687,0", "0.10311,0.77997,0", "0.057028,0.91886,0", "-0.10426,0.99196,0", "-0.081221,1.1089,0", "0.28744,1.087,0", "0.39689,0.82383,0", "0.20104,-0.60161,1", "0.46601,-0.53582,1", "0.67339,-0.53582,1", "-0.13882,0.54605,1", "-0.29435,0.77997,1", "-0.26555,0.96272,1", "-0.16187,0.8019,1", "-0.17339,0.64839,1", "-0.28283,0.47295,1", ]
package stack import ( "context" "fmt" "github.com/shurcooL/graphql" "github.com/urfave/cli/v2" "github.com/spacelift-io/spacectl/client/structs" "github.com/spacelift-io/spacectl/internal/cmd/authenticated" ) func runTrigger(spaceliftType, humanType string) cli.ActionFunc { return func(cliCtx *cli.Context) error { stackID := cliCtx.String(flagStackID.Name) var mutation struct { RunTrigger struct { ID string `grapqhl:"id"` } `graphql:"runTrigger(stack: $stack, commitSha: $sha, runType: $type)"` } variables := map[string]interface{}{ "stack": graphql.ID(stackID), "sha": (*graphql.String)(nil), "type": structs.NewRunType(spaceliftType), } if cliCtx.IsSet(flagCommitSHA.Name) { variables["sha"] = graphql.NewString(graphql.String(cliCtx.String(flagCommitSHA.Name))) } ctx := context.Background() var requestOpts []graphql.RequestOption if cliCtx.IsSet(flagRunMetadata.Name) { requestOpts = append(requestOpts, graphql.WithHeader(UserProvidedRunMetadataHeader, cliCtx.String(flagRunMetadata.Name))) } if err := authenticated.Client.Mutate(ctx, &mutation, variables, requestOpts...); err != nil { return err } fmt.Println("You have successfully created a", humanType) fmt.Println("The live run can be visited at", authenticated.Client.URL( "/stack/%s/run/%s", stackID, mutation.RunTrigger.ID, )) if !cliCtx.Bool(flagTail.Name) { return nil } terminal, err := runLogs(ctx, stackID, mutation.RunTrigger.ID) if err != nil { return err } return terminal.Error() } }
# frozen_string_literal: true class ApplicationController < ActionController::Base include Knock::Authenticable end
package ru.job4j.user; import java.util.*; /** * SortUser - class sorting collections of User objects * * @author <NAME> (<EMAIL>) * @version $Id$ * @since 0.1 */ public class SortUser { /** * The method sorting the list of Users according to the used comparator. * @return sorted TreeSet produced from User List. */ public Set<User> sort(List<User> users) { return new TreeSet<User>(users); } /** * The method sorting the List of Users by the name length from short to long names. * @return - sorted users List. */ public List<User> sortNameLength(List<User> users) { users.sort(new Comparator<User>() { @Override public int compare(User o1, User o2) { return Integer.compare(o1.getName().length(), o2.getName().length()); } }); return users; } /** * The method sorting the List of Users at first by the name length (from short to long names) * and then by the age (from young to old). * @return - sorted users List. */ public List<User> sortByAllFields(List<User> users) { users.sort(new Comparator<User>() { @Override public int compare(User o1, User o2) { return o1.getName().length() > o2.getName().length() ? 1 : o1.getName().length() < o2.getName().length() ? -1 : Integer.compare(o1.getAge(), o2.getAge()); } }); return users; } }
import { Injectable } from '@angular/core'; import { Actions, createEffect, ofType } from '@ngrx/effects'; import { select, Store } from '@ngrx/store'; import { fetch } from '@nrwl/angular'; import { ID_DOMAIN_BLUE, ID_DOMAIN_RED } from '@taormina/shared-constants'; import { ResourceCount, RESOURCE_COUNTS } from '@taormina/shared-models'; import { forkJoin, Observable, of } from 'rxjs'; import { catchError, concatMap, map, take, withLatestFrom, } from 'rxjs/operators'; import { v4 as uuidv4 } from 'uuid'; import * as DomainsCardsActions from './domains-cards.actions'; import { createDomainsCardsEntity, createInitialDomainsCards, DomainsCardsEntity, } from './domains-cards.models'; import * as DomainsCardsFeature from './domains-cards.reducer'; import * as DomainsCardsSelectors from './domains-cards.selectors'; @Injectable() export class DomainsCardsEffects { initNewGame$ = createEffect(() => this.actions$.pipe( ofType(DomainsCardsActions.initDomainsCardsNewGame), map(() => DomainsCardsActions.setDomainsCardsInitialized({ domainsCards: createInitialDomainsCards(), }) ) ) ); initSavedGame$ = createEffect(() => this.actions$.pipe( ofType(DomainsCardsActions.initDomainsCardsSavedGame), fetch({ run: () => { // Your custom service 'load' logic goes here. For now just return a success action... return DomainsCardsActions.loadDomainsCardsSuccess({ domainsCards: [], }); }, onError: (_action, error) => { console.error('Error', error); return DomainsCardsActions.loadDomainsCardsFailure({ error }); }, }) ) ); increaseResourcesForDie$ = createEffect(() => this.actions$.pipe( ofType(DomainsCardsActions.increaseAvailableResourcesForDie), concatMap((action) => { return forkJoin({ increaseOne: this.domainsCardsStore.pipe( select( DomainsCardsSelectors.getLandCardsPivotsIncreaseOneProduction, { die: action.die, } ), take(1) ), increaseTwo: this.domainsCardsStore.pipe( select( DomainsCardsSelectors.getLandCardsPivotsIncreaseTwoProduction, { die: action.die, } ), take(1) ), }); }), map(({ increaseOne, increaseTwo }) => { const updatesOne = this.updatesAvailableResources(increaseOne, 1); // eslint-disable-next-line no-magic-numbers const updatesTwo = this.updatesAvailableResources(increaseTwo, 2); return DomainsCardsActions.updateDomainsCards({ updates: [...updatesOne, ...updatesTwo], }); }) ) ); increaseResourcesAuspiciousYear$ = createEffect(() => this.actions$.pipe( ofType(DomainsCardsActions.increaseAvailableResourcesForAuspiciousYear), withLatestFrom( this.domainsCardsStore.select( DomainsCardsSelectors.getLandCardsPivotsIncreaseAuspiciousYear, { count: 1 } ), this.domainsCardsStore.select( DomainsCardsSelectors.getLandCardsPivotsIncreaseAuspiciousYear, { count: 2 } ), this.domainsCardsStore.select( DomainsCardsSelectors.getLandCardsPivotsIncreaseAuspiciousYear, { count: 3 } ), this.domainsCardsStore.select( DomainsCardsSelectors.getLandCardsPivotsIncreaseAuspiciousYear, { count: 4 } ) ), map( // eslint-disable-next-line @typescript-eslint/no-unused-vars ([_action, increaseOne, increaseTwo, increaseThree, increaseFour]) => { const updatesOne = this.updatesAvailableResources(increaseOne, 1); /* eslint-disable no-magic-numbers */ const updatesTwo = this.updatesAvailableResources(increaseTwo, 2); const updatesThree = this.updatesAvailableResources(increaseThree, 3); const updatesFour = this.updatesAvailableResources(increaseFour, 4); /* eslint-enable no-magic-numbers */ return DomainsCardsActions.updateDomainsCards({ updates: [ ...updatesOne, ...updatesTwo, ...updatesThree, ...updatesFour, ], }); } ) ) ); lockResource$ = createEffect(() => this.actions$.pipe( ofType(DomainsCardsActions.lockResource), concatMap((action) => this.takeOneDefinedPivotOrThrow(action.id).pipe( map((pivot) => { if (pivot.availableResources === 0) { throw new Error( `Can't lock unavailable resource for pivot ${pivot.id}.` ); } if (pivot.lockedResources === Math.max(...RESOURCE_COUNTS)) { throw new Error( `Can't lock more resources for pivot ${pivot.id}.` ); } const update = { id: pivot.id, changes: { // prettier-ignore availableResources: (pivot.availableResources - 1) as ResourceCount, // prettier-ignore lockedResources: (pivot.lockedResources + 1) as ResourceCount, }, }; return DomainsCardsActions.updateDomainCard({ update }); }), catchError((error) => of( DomainsCardsActions.setDomainsCardsError({ error: error.message }) ) ) ) ) ) ); unlockResources$ = createEffect(() => this.actions$.pipe( ofType(DomainsCardsActions.unlockResources), concatMap((action) => this.takeOneDefinedPivotOrThrow(action.id).pipe( map((pivot) => { if ( pivot.availableResources + pivot.lockedResources > Math.max(...RESOURCE_COUNTS) ) { throw new Error( `Shouldn't have been able to lock so many resources for pivot ${pivot.id}.` ); } const update = { id: pivot.id, changes: { availableResources: (pivot.availableResources + pivot.lockedResources) as ResourceCount, lockedResources: 0 as ResourceCount, }, }; return DomainsCardsActions.updateDomainCard({ update }); }), catchError((error) => of( DomainsCardsActions.setDomainsCardsError({ error: error.message }) ) ) ) ) ) ); useLockedResources$ = createEffect(() => this.actions$.pipe( ofType(DomainsCardsActions.useLockedResources), withLatestFrom( this.domainsCardsStore.select( DomainsCardsSelectors.getLandCardPivotWithLockedResources ) ), // eslint-disable-next-line @typescript-eslint/no-unused-vars map(([_action, pivots]) => { const updates = pivots.map((pivot) => { return { id: pivot.id, changes: { lockedResources: 0 as ResourceCount, }, }; }); return DomainsCardsActions.updateDomainsCards({ updates }); }) ) ); increaseResources$ = createEffect(() => this.actions$.pipe( ofType(DomainsCardsActions.increaseAvailableResources), concatMap((action) => this.takeOneDefinedPivotOrThrow(action.id).pipe( map((pivot) => { if (pivot.availableResources === Math.max(...RESOURCE_COUNTS)) { throw new Error( `Can't increase available resources beyond maximum for pivot ${pivot.id}.` ); } const update = { id: pivot.id, changes: { // prettier-ignore availableResources: (pivot.availableResources + 1) as ResourceCount, }, }; return DomainsCardsActions.updateDomainCard({ update }); }), catchError((error) => of( DomainsCardsActions.setDomainsCardsError({ error: error.message }) ) ) ) ) ) ); putCardInPivot$ = createEffect(() => this.actions$.pipe( ofType(DomainsCardsActions.putCardInPivot), map((action) => { const update = { id: action.id, changes: { cardType: action.cardType, cardId: action.cardId, }, }; return DomainsCardsActions.updateDomainCard({ update }); }) ) ); createCard$ = createEffect(() => this.actions$.pipe( ofType(DomainsCardsActions.createDomainCard), map(({ domainId, cardType, cardId, col, row }) => { const domainCard = createDomainsCardsEntity( uuidv4(), domainId, cardType, cardId, col, row ); return DomainsCardsActions.addDomainCard({ domainCard }); }) ) ); countStealResources$ = createEffect(() => this.actions$.pipe( ofType(DomainsCardsActions.countAndStealUnprotectedGoldAndWool), withLatestFrom( this.domainsCardsStore.select( DomainsCardsSelectors.getDomainResourceCountSeenByThieves, { domainId: ID_DOMAIN_RED } ), this.domainsCardsStore.select( DomainsCardsSelectors.getDomainResourceCountSeenByThieves, { domainId: ID_DOMAIN_BLUE } ), this.domainsCardsStore.select( DomainsCardsSelectors.getDomainUnprotectedGoldMinesAndPastures, { domainId: ID_DOMAIN_RED } ), this.domainsCardsStore.select( DomainsCardsSelectors.getDomainUnprotectedGoldMinesAndPastures, { domainId: ID_DOMAIN_BLUE } ) ), map( ([ // eslint-disable-next-line @typescript-eslint/no-unused-vars _action, redResourceCount, blueResourceCount, redGoldMinesAndPastures, blueGoldMinesAndPastures, ]) => { const thievesResourceCountThreshold = 7; let pivots: DomainsCardsEntity[] = []; if (redResourceCount > thievesResourceCountThreshold) { pivots = [...pivots, ...redGoldMinesAndPastures]; } if (blueResourceCount > thievesResourceCountThreshold) { pivots = [...pivots, ...blueGoldMinesAndPastures]; } return pivots; } ), map((pivots) => { const updates = pivots.map((pivot) => { return { id: pivot.id, changes: { availableResources: 0 as ResourceCount, }, }; }); return DomainsCardsActions.updateDomainsCards({ updates }); }) ) ); constructor( private actions$: Actions, private domainsCardsStore: Store<DomainsCardsFeature.DomainsCardsPartialState> ) {} private takeOneDefinedPivotOrThrow( id: string ): Observable<DomainsCardsEntity> { return this.domainsCardsStore.pipe( select(DomainsCardsSelectors.getLandCardPivotById, { id, }), map((pivot) => { if (pivot === undefined) { throw new Error(`Couldn't find land card pivot for id.`); } return pivot; }), take(1) ); } private updatesAvailableResources = ( domainsCards: DomainsCardsEntity[], resourceIncrement: number ): { id: string; changes: { availableResources: ResourceCount; }; }[] => { const belowMax = domainsCards .filter( (pivot) => pivot.availableResources < Math.max(...RESOURCE_COUNTS) - resourceIncrement ) .map((pivot) => { return { id: pivot.id, changes: { availableResources: (pivot.availableResources + resourceIncrement) as ResourceCount, }, }; }); const atMax = domainsCards .filter( (pivot) => pivot.availableResources >= Math.max(...RESOURCE_COUNTS) - resourceIncrement && pivot.availableResources < Math.max(...RESOURCE_COUNTS) ) .map((pivot) => { return { id: pivot.id, changes: { availableResources: Math.max(...RESOURCE_COUNTS) as ResourceCount, }, }; }); return [...belowMax, ...atMax]; }; }
<reponame>fenlgy/olyd<filename>src/components/utils/index.js /** * Created by Administrator on 2017/4/14. */ // 如果变量有值则输出本身,没值则不输出 // 等式输出用于class,之类的html类标签属性 function IF(variable, equ) { if (!variable || variable === 'undefined') { return '' } return equ ? `${equ}="${variable}"` : variable } function arrayDel(arr, val) { var index = $.inArray(val, arr) if (index > -1) { arr.splice(index, 1) } return arr } // 返回索引 // @param arr 数组或数组对象 // @param opts function inArray(arr, opts) { const isObject = $.isPlainObject(opts); const key = isObject && Object.keys(opts)[0] function getIndex(arr, opts, i = -1) { arr.forEach((_arr, index) => { if (isObject) { if (_arr[key] === opts[key]) { i = index } } else { if (_arr === opts) { i = index } } }) return i } return getIndex(arr, opts) } const strToJson = function (str) { const json = (new Function("return " + str))(); return json; }; // 返回指定索引的数组中的值, // 返回类型也是数组 // @param index 数组或者可以转换为number的数字 function getArrFromIndex(arr,index) { let ret=[]; if($.isArray(index)){ index.forEach( item => { ret.push(arr[item]) }) } if($.isNumeric(index)){ ret = arr[index] } return ret; } function installExtensions() { } module.exports = { IF, arrayDel, inArray, strToJson, getArrFromIndex, installExtensions, // uniq:require('lodash.uniq'), uniq:$.unique, cloneDeep:require('lodash.clonedeep'), isEqual:require('lodash.isequal'), keycode: require('./keycode'), classnames: require('classnames'), moment: require('moment'), }
package com.packtpub.springrest.client.auth; import org.apache.http.HttpHost; import org.apache.http.client.AuthCache; import org.apache.http.client.HttpClient; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.auth.DigestScheme; import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.springframework.http.HttpMethod; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import java.net.URI; public class DigestAuthHttpRequestFactory extends HttpComponentsClientHttpRequestFactory { private final HttpHost host; public DigestAuthHttpRequestFactory(HttpHost host, HttpClient client) { super(client); this.host = host; } @Override protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { AuthCache authCache = new BasicAuthCache(); authCache.put(host, new DigestScheme()); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); return localcontext; } }
function makeData() { "use strict"; return [makeRandomData(20), makeRandomData(20)]; } function run(div, data, Plottable) { "use strict"; var svg = div.append("svg").attr("height", 500); var doAnimate = true; var circleRenderer; var xScale = new Plottable.Scale.Linear(); var xAxis = new Plottable.Axis.Numeric(xScale, "bottom"); var yScale = new Plottable.Scale.Linear(); var yAxis = new Plottable.Axis.Numeric(yScale, "left"); var d1 = new Plottable.Dataset(data[0]); var d2 = new Plottable.Dataset(data[1]); circleRenderer = new Plottable.Plot.Scatter(xScale, yScale) .addDataset(d1) .addDataset(d2) .attr("r", 8) .attr("opacity", 0.75) .animate(doAnimate); var circleChart = new Plottable.Component.Table([[yAxis, circleRenderer], [null, xAxis]]); circleChart.renderTo(svg); var cb = function(x, y){ var tmp = d1.data(); d1.data(d2.data()); d2.data(tmp); }; circleRenderer.registerInteraction( new Plottable.Interaction.Click(circleRenderer).callback(cb) ); }
std::unordered_map<Texture*, size_t> CountUniqueTexturesAndTransforms(const std::unordered_map<std::pair<int, Texture*>, std::vector<Matrix>>& textureTransforms, Texture* currentTexture) { std::unordered_map<Texture*, size_t> uniqueTexturesCount; for (auto it = textureTransforms.begin(); it != textureTransforms.end(); ++it) { Texture *texture = it->first.second; Matrix *transforms = &it->second[0]; size_t numTransforms = it->second.size(); if (numTransforms == 0) { continue; } if (texture != currentTexture) { uniqueTexturesCount[texture]++; } } return uniqueTexturesCount; }
<filename>src/EndpointServiceMVCExtensions.ts import { decorate, injectable } from 'inversify'; import { Controller } from '@telar/mvc'; import { IServiceCollection } from '@telar/core/IServiceCollection'; declare module '@telar/core/IServiceCollection' { /** * Constains extensions for configuring routing */ export interface IServiceCollection { /** * Add the routing middleware */ addMVC(): IServiceCollection; } } IServiceCollection.prototype.addMVC = function () { try { decorate(injectable(), Controller); } catch (error) { // FIXME: should fix this error // eslint-disable-next-line no-console console.log('[WARN] Cannot apply @injectable decorator multiple times.'); } return this; };
def longestIncreasingSubsequence(sequence): n = len(sequence) lis = [1]*n for i in range (1 , n): for j in range(0 , i): if sequence[i] > sequence[j] and lis[i]< lis[j] + 1 : lis[i] = lis[j]+1 maximum = 0 for i in range(n): maximum = max(maximum , lis[i]) return maximum
var jsdirectives = Npm.require('jsdirectives')
<reponame>davidbstein/eavesdrop-spotify """ Creates a series of FileNode objects from an input unbundled pack see the `browser-unpack` npm module to generate an input file unbundled.json must contain a list of { id: unique ID of file source: raw source code deps: a dictionary of relative path to ID entry: (optional) a boolean set to true if this was the entry point for the build } """ from unbundler.file_node import FileNode import json def parse_file(file_target="unbundled.json"): """ returns acn immutabile dictionary of FileNodes keyed on ID """ with open(file_target) as f: content = json.loads(f.read()) nodes = { raw_file_node['id']: FileNode(**raw_file_node) for raw_file_node in content } for ref_id, node in nodes.items(): if node._dup_id: # undo the dedup webpack optimization node._source = nodes[node._dup_id].source # add dependency paths for dep_id, path in node.deps.items(): nodes[dep_id].set_ref(ref_id, path) return nodes
// Normalize Carousel Heights - pass in Bootstrap Carousel items. $.fn.carouselHeights = function() { var items = $(this), //grab all slides heights = [], //create empty array to store height values tallest; //create variable to make note of the tallest slide var normalizeHeights = function() { items.each(function() { //add heights to array heights.push($(this).height()); }); tallest = Math.max.apply(null, heights); //cache largest value items.each(function() { $(this).css('min-height',tallest + 'px'); }); }; normalizeHeights(); $(window).on('resize orientationchange', function () { //reset vars tallest = 0; heights.length = 0; items.each(function() { $(this).css('min-height','0'); //reset min-height }); normalizeHeights(); //run it again }); }; jQuery(function($){ $(window).on('load', function(){ $('#carousel .item').carouselHeights(); }); });
import { Test } from '@nestjs/testing'; import { getRepositoryToken } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { Episode } from './entities/episode.entity'; import { Podcast } from './entities/podcast.entity'; import { PodcastsService } from './podcasts.service'; const mockRespository = () => ({ find: jest.fn(), save: jest.fn(), create: jest.fn(), findOne: jest.fn(), delete: jest.fn(), }); type MockRepository<T = any> = Partial< Record<keyof Repository<Podcast>, jest.Mock> >; describe('PodcastsService', () => { let service: PodcastsService; let podcastsRepository: MockRepository<Podcast>; let episodesRepository: MockRepository<Episode>; beforeEach(async () => { const module = await Test.createTestingModule({ providers: [ PodcastsService, { provide: getRepositoryToken(Podcast), useValue: mockRespository(), }, { provide: getRepositoryToken(Episode), useValue: mockRespository(), }, ], }).compile(); service = module.get<PodcastsService>(PodcastsService); podcastsRepository = module.get(getRepositoryToken(Podcast)); episodesRepository = module.get(getRepositoryToken(Episode)); }); it('Should be defined', () => { expect(service).toBeDefined(); }); describe('allPodcasts', () => { it('should find allPodcasts', async () => { const Podcast = { id: 1, title: 'testPodcast', }; podcastsRepository.find.mockResolvedValue([Podcast]); const result = await service.allPodcasts(); expect(result).toEqual({ ok: true, result: [Podcast], }); }); // it('should error on exception', async () => { // podcastsRepository.find.mockResolvedValue(new Error()); // const result = await service.allPodcasts(); // expect(result).toEqual({ // ok: false, // error: 'Could not find podcasts', // }); // }); }); describe('createPodcast', () => { it('should create podcast', async () => { const creaatePodcastArgs = { title: 'testTitle', rating: 10, category: 'testCategory', }; podcastsRepository.create.mockReturnValue(creaatePodcastArgs); const result = await service.createPodcast(creaatePodcastArgs); expect(podcastsRepository.create).toHaveBeenCalledTimes(1); expect(podcastsRepository.create).toHaveBeenCalledWith( creaatePodcastArgs, ); expect(podcastsRepository.save).toHaveBeenCalledWith(creaatePodcastArgs); expect(result).toEqual({ ok: true }); }); }); describe('findPodcastById', () => { it('should fail if no podcast if found ', async () => { podcastsRepository.findOne.mockResolvedValue(null); const result = await service.findPodcastById({ id: 1 }); expect(result).toEqual({ ok: false, error: 'Podcast not found' }); }); it('should find podcast by id', async () => { const findByIdArgs = { id: 1, }; podcastsRepository.findOne.mockResolvedValue(findByIdArgs); const result = await service.findPodcastById(findByIdArgs); expect(result).toEqual({ ok: true, podcast: findByIdArgs }); }); }); describe('editPodcast', () => { const editPodcastArgs = { podcastId: 1, title: 'newtitle', rating: 10, category: 'newCategory', }; it('should fail if no podcast if found', async () => { podcastsRepository.findOne.mockResolvedValue(undefined); const result = await service.editPodcast(editPodcastArgs); expect(result).toEqual({ ok: false, error: 'Podcast not found', }); }); it('should edit podcast', async () => { const oldPodcast = { title: 'oldTitle', rating: 9, }; podcastsRepository.findOne.mockResolvedValue(oldPodcast); await service.editPodcast(editPodcastArgs); expect(podcastsRepository.findOne).toHaveBeenCalledWith( expect.any(Number), ); expect(podcastsRepository.save).toHaveBeenCalledWith({ id: editPodcastArgs.podcastId, ...editPodcastArgs, }); }); }); describe('deletePodcast', () => { it('should fail if no podcast if found ', async () => { podcastsRepository.findOne.mockResolvedValue(null); const result = await service.findPodcastById({ id: 1 }); expect(result).toEqual({ ok: false, error: 'Podcast not found' }); }); it('should delete podcast', async () => { podcastsRepository.findOne.mockResolvedValue({ id: 1 }); const result = await service.deletePodcast({ podcastId: 1 }); expect(podcastsRepository.delete).toHaveBeenCalledWith(1); expect(result).toEqual({ ok: true }); }); }); it.todo('allEpisodes'); it.todo('createEpisode'); it.todo('deleteEpisode'); it.todo('editEpisode'); });
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+0+512-ST/13-model --tokenizer_name model-configs/1024-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+0+512-ST/13-512+0+512-pad-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function truncate_and_pad_first_half_quarter --eval_function last_quarter_eval
class WebDriver { // Assume the WebDriver class and its methods are defined } class Condition<T> { constructor(private text: string, private fn: (driver: WebDriver) => Promise<T>) {} async apply(driver: WebDriver): Promise<T> { return await this.fn(driver); } } function waitForCondition(driver: WebDriver): ( text: string, fn: (driver: WebDriver) => Promise<boolean>, timeout: number ) => Promise<boolean> { return async function( text: string, fn: (driver: WebDriver) => Promise<boolean>, timeout: number ): Promise<boolean> { return await driver.wait(new Condition<boolean>(text, fn), timeout); }; }
#!/usr/bin/env bash set -euo pipefail # Builds vscode into lib/vscode/out-vscode. # MINIFY controls whether a minified version of vscode is built. MINIFY=${MINIFY-true} main() { cd "$(dirname "${0}")/../.." cd lib/vscode # Any platform works since we have our own packaging step (for now). yarn gulp "vscode-reh-web-linux-x64${MINIFY:+-min}" } main "$@"
<filename>JSIMWebrtcOverMQTT/ConfigSet.h // // ConfigSet.h // JSIMWebrtcOverMQTT // // Created by WHC on 15/9/18. // Copyright (c) 2015年 weaver software. All rights reserved. // #ifndef JSIMWebrtcOverMQTT_ConfigSet_h #define JSIMWebrtcOverMQTT_ConfigSet_h #endif #define UserAliceName @"JSIMUser/Alice" #define UserBobName @"JSIMUser/Bob" //server name #define SERVERNAME_IPTEL @"iptel server" #define SERVERNAME_SOFTJOYS @"softjoys server" #define SERVERNAME_IBM @"ibm server" #define SERVERNAME_MOSQUITTOR @"mosquitto server" #define SERVERNAME_OTHER @"other server" //mqtt server config #define MQTTSERVER_IBMHOST @"messagesight.demos.ibm.com" #define MQTTSERVER_IBMPORT @"1883" #define MQTTSERVER_MOSQUITTOHOST @"test.mosquitto.org" #define MQTTSERVER_MOSQUITTOPORT @"1883" //ice #define ICESERVER_IPTEL_STUN_HOST @"stun:stun.iptel.org" #define ICESERVER_IPTEL_STUN_PORT @"" #define ICESERVER_IPTEL_TURN_HOST @"stun:stun.iptel.org" #define ICESERVER_IPTEL_TURN_PORT @"" #define ICESERVER_IPTEL_TURN_USERNAME @"" #define ICESERVER_IPTEL_TURN_CREDENTIAL @"" #define ICESERVER_SOFTJOYS_STUN_HOST @"stun:stun.softjoys.com" #define ICESERVER_SOFTJOYS_STUN_PORT @"" #define ICESERVER_SOFTJOYS_TURN_HOST @"stun:stun.softjoys.com" #define ICESERVER_SOFTJOYS_TURN_PORT @"" #define ICESERVER_SOFTJOYS_TURN_USERNAME @"" #define ICESERVER_SOFTJOYS_TURN_CREDENTIAL @"" #define JSIMRTCLOG #ifdef JSIMRTCLOG #define JSIMRTCLOG(format, ...) NSLog(format, ## __VA_ARGS__) #else #define JSIMRTCLOG(format, ...) #endif
package com.amaljoyc.patterns.behavioural.chainofresponsibility; /** * Created by achemparathy on 29.07.18. */ public abstract class Logger { public static final int INFO = 1; public static final int DEBUG = 2; public static final int ERROR = 3; protected int level; private Logger nextLogger; protected void setNextLogger(Logger nextLogger) { this.nextLogger = nextLogger; } protected void logMessage(int level, String message) { if (this.level <= level) { write(message); } if (nextLogger != null) { nextLogger.logMessage(level, message); } } abstract void write(String message); }
/* * Copyright (c) 2021-2021. https://playio.cloud/ * 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 * * All rights reserved. */ import { isFunction } from './checker'; // FIXME: must notify to global error state then show error model in frontend instead of using `alert` // eslint-disable-next-line @typescript-eslint/no-unused-vars function logError(error, ...args: any[]) { console.error(error); // if (isFunction(window.alert)) { // // eslint-disable-next-line no-alert // alert(error.toString()); // } else { // throw error; // } } export const ErrorHandler = (target: any, propertyKey: string, descriptor: any) => { const fn = descriptor.value!; descriptor.value = function DescriptorValue(...args: any[]) { try { return fn.apply(this, args); } catch (error) { logError(error, ...args); } }; return descriptor; }; export const ErrorCallbackHandler = (errHandler: any) => (target: any, propertyKey: string, descriptor: any) => { const fn = descriptor.value!; descriptor.value = function DescriptorValue(...args: any[]) { try { return fn.apply(this, args); } catch (error) { logError(error, ...args); if (isFunction(errHandler)) { return errHandler(error, args); } } }; return descriptor; };