identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/IBM-Security/ibmsecurity/blob/master/ibmsecurity/isam/base/system_alerts/logdb.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
ibmsecurity
|
IBM-Security
|
Python
|
Code
| 375
| 1,427
|
import logging
import ibmsecurity.utilities.tools
logger = logging.getLogger(__name__)
def get_all(isamAppliance, check_mode=False, force=False):
"""
Get all logdb objects
"""
return isamAppliance.invoke_get("Get all logdb objects",
"/core/rsp_logdb_objs")
def get(isamAppliance, uuid, check_mode=False, force=False):
"""
Get a specific logdb object
"""
return isamAppliance.invoke_get("Get a specific logdb object",
"/core/rsp_logdb_objs/{0}".format(uuid))
def add(isamAppliance, name, aclEventsAllocation, ipsEventsAllocation, sysEventsAllocation, objType='logdb',
comment='', check_mode=False, force=False):
"""
Add a logdb object
NOTE: This function does not work!
"""
if force is True or _check(isamAppliance, None, name, comment, aclEventsAllocation, ipsEventsAllocation,
sysEventsAllocation) is False:
if check_mode is True:
return isamAppliance.create_return_object(changed=True)
else:
return isamAppliance.invoke_post(
"Add a logdb object",
"/core/rsp_logdb_objs/",
{
'name': name,
'objType': objType,
'comment': comment,
'aclEventsAllocation': aclEventsAllocation,
'ipsEventsAllocation': ipsEventsAllocation,
'sysEventsAllocation': sysEventsAllocation
})
return isamAppliance.create_return_object()
def update(isamAppliance, name, uuid, aclEventsAllocation, ipsEventsAllocation, sysEventsAllocation, objType='logdb',
comment='', check_mode=False, force=False):
"""
Update a specific logdb object
"""
if force is True or (
_exists(isamAppliance, uuid) is True and _check(isamAppliance, uuid, name, comment, aclEventsAllocation,
ipsEventsAllocation, sysEventsAllocation) is False):
if check_mode is True:
return isamAppliance.create_return_object(changed=True)
else:
return isamAppliance.invoke_put(
"Update a specific logdb object",
"/core/rsp_logdb_objs/{0}".format(uuid),
{
'name': name,
'uuid': uuid,
'objType': objType,
'comment': comment,
'aclEventsAllocation': aclEventsAllocation,
'ipsEventsAllocation': ipsEventsAllocation,
'sysEventsAllocation': sysEventsAllocation
})
return isamAppliance.create_return_object()
def delete(isamAppliance, uuid, check_mode=False, force=False):
"""
Delete a logdb object
NOTE: This function does not work!
"""
if force is True or _exists(isamAppliance, uuid) is True:
if check_mode is True:
return isamAppliance.create_return_object(changed=True)
else:
return isamAppliance.invoke_delete(
"Delete a logdb object",
"/core/rsp_logdb_objs/{0}".format(uuid))
return isamAppliance.create_return_object()
def _exists(isamAppliance, uuid):
"""
Check if an uuid object exists
:param isamAppliance:
:param uuid:
:return:
"""
exists = False
ret_obj = get_all(isamAppliance)
for snmp in ret_obj['data']['logdbObjects']:
if snmp['uuid'] == uuid:
exists = True
break
return exists
def _check(isamAppliance, uuid, name, comment, aclEventsAllocation, ipsEventsAllocation, sysEventsAllocation):
"""
Check if the logdb object exists and is the same - uuid=None means add versus delete
NOTE: if UUID is not found that will be same as no match!!!
"""
set_value = {
'name': name,
'comment': comment,
'objType': 'logdb',
'uuid': uuid,
'aclEventsAllocation': aclEventsAllocation,
'ipsEventsAllocation': ipsEventsAllocation,
'sysEventsAllocation': sysEventsAllocation
}
set_value = ibmsecurity.utilities.tools.json_sort(set_value)
ret_obj = get_all(isamAppliance)
for obj in ret_obj['data']['logdbObjects']:
if uuid is None and obj['name'] == name:
return True
elif ibmsecurity.utilities.tools.json_sort(obj) == set_value:
return True
return False
def compare(isamAppliance1, isamAppliance2):
"""
Compare logdb objects between two appliances
"""
ret_obj1 = get_all(isamAppliance1)
ret_obj2 = get_all(isamAppliance2)
for obj in ret_obj1['data']['logdbObjects']:
del obj['uuid']
for obj in ret_obj2['data']['logdbObjects']:
del obj['uuid']
return ibmsecurity.utilities.tools.json_compare(ret_obj1, ret_obj2, deleted_keys=['uuid'])
| 9,358
|
https://github.com/06danielsms/api-cce/blob/master/src/inventory/inventory.service.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
api-cce
|
06danielsms
|
TypeScript
|
Code
| 72
| 227
|
import { Injectable } from '@nestjs/common';
import { CreateInventoryDto } from './dto/create-inventory.dto';
import { UpdateInventoryDto } from './dto/update-inventory.dto';
import { Inventory, InventoryDocument } from './schemas/inventory.schema';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
@Injectable()
export class InventoryService {
constructor (
@InjectModel('Inventory') private readonly inventoryModel: Model<InventoryDocument>
) {}
async create(createInventoryDto: CreateInventoryDto): Promise<Inventory> {
const createProduct = new this.inventoryModel(createInventoryDto);
return createProduct.save()
}
async findAll() {
return this.inventoryModel.find({state: true});
}
}
| 27,905
|
https://github.com/konduruvijaykumar/ibm-iot-examples/blob/master/ibmiot-device-client-demo/src/main/java/org/pjay/ibm/iot/DeviceCommandCallbackSubscriber.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
ibm-iot-examples
|
konduruvijaykumar
|
Java
|
Code
| 271
| 833
|
/**
*
*/
package org.pjay.ibm.iot;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.eclipse.paho.client.mqttv3.MqttException;
import com.ibm.iotf.client.device.Command;
import com.ibm.iotf.client.device.CommandCallback;
import com.ibm.iotf.client.device.DeviceClient;
/**
* @author Vijay Konduru
*
* Note:
* With the latest java library for Watson IoT Platform, a DeviceClient can only subscribe to CommandCallbacks and not EventCallbacks.
* However, an ApplicationClient can publish Events and Commands both. publishEvent method will not trigger the CommandCallback
*
*/
public class DeviceCommandCallbackSubscriber {
private final static String PROPERTIES_FILE_NAME = "/device.properties";
//private final static String PROPERTIES_FILE_NAME = "C:\\JavaIoT\\ibm-iot-properties\\app.properties";
/**
* @param args
* @throws MqttException
*/
public static void main(String[] args) throws MqttException {
/**
* Load device properties
*/
Properties props = new Properties();
//props = ApplicationClient.parsePropertiesFile(new File("C:\\JavaIoT\\ibm-iot-properties\\app1.properties"));
DeviceClient myClient = null;
//ApplicationClient appClient = null;
try {
//Instantiate the class by passing the properties file
// Does not have method other setting command callback, hence trying Application client
//myClient = new DeviceClient(props);
props.load(DeviceCommandCallbackSubscriber.class.getResourceAsStream(PROPERTIES_FILE_NAME));
myClient = new DeviceClient(props);
//appClient = new ApplicationClient(props);
} catch (Exception e) {
e.printStackTrace();
}
//Pass the implemented CommandCallback as an argument to this device client
CommandCallbackSubscriber commandCallbackSubscriber = new CommandCallbackSubscriber();
Thread t1 = new Thread(commandCallbackSubscriber);
t1.start();
//myClient.setCommandCallback(eventCallbackSubscriber);
myClient.setCommandCallback(commandCallbackSubscriber);
// Connect to the IBM Watson IoT Platform
myClient.connect();
}
}
class CommandCallbackSubscriber implements CommandCallback, Runnable {
private BlockingQueue<Command> commandQueue = new LinkedBlockingQueue<Command>();
private Command command = null;
@Override
public void processCommand(Command cmd) {
try {
commandQueue.put(cmd);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(true){
try {
// Command related
command = commandQueue.take();
System.out.println("Command :: " + command.getCommand() + "\t Payload :: " + command.getData());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| 34,372
|
https://github.com/apache/netbeans/blob/master/webcommon/javascript2.editor/test/unit/data/testfiles/with/issue234637A.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
netbeans
|
apache
|
JavaScript
|
Code
| 11
| 34
|
to234637 = {
$bindings: {
xProperty: "",
xyProperty: 1
}
}
| 31,650
|
https://github.com/rdkmaster/jigsaw/blob/master/src/app/for-internal/demo/pc/chart-icon/with-button/demo.module.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
jigsaw
|
rdkmaster
|
TypeScript
|
Code
| 40
| 185
|
import {NgModule} from "@angular/core";
import {JigsawButtonModule, JigsawHeaderModule, JigsawCheckBoxModule, JigsawChartIconModule} from "jigsaw/public_api";
import {JigsawDemoDescriptionModule} from "app/for-internal/description/demo-description";
import {ChartIconButtonDemoComponent} from "./demo.component";
@NgModule({
declarations: [ChartIconButtonDemoComponent],
exports: [ ChartIconButtonDemoComponent ],
imports: [
JigsawChartIconModule, JigsawButtonModule, JigsawDemoDescriptionModule, JigsawHeaderModule,
JigsawCheckBoxModule
]
})
export class ChartIconButtonDemoModule {
}
| 27,205
|
https://github.com/makese/Server/blob/master/src/responses/weather.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Server
|
makese
|
JavaScript
|
Code
| 17
| 66
|
"use strict";
function getWeather(url, info, sessionID) {
return json.stringify({"err": 0, "errmsg": null, "data": weather_f.generate()});
}
router.addStaticRoute("/client/weather", getWeather);
| 45,363
|
https://github.com/jsdelivrbot/365_programs/blob/master/2017-05-31/global.d.ts
|
Github Open Source
|
Open Source
|
Unlicense
| null |
365_programs
|
jsdelivrbot
|
TypeScript
|
Code
| 8
| 18
|
declare function require(path: string): any;
declare var module:any;
| 20,386
|
https://github.com/rnjava/signoz/blob/master/frontend/src/components/Spiner.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
signoz
|
rnjava
|
TSX
|
Code
| 90
| 255
|
import React from 'react';
import { Spin } from 'antd';
import styled from "styled-components";
import { LoadingOutlined } from '@ant-design/icons';
const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;
const SpinerStyle = styled.div`
position: fixed;
z-index: 999;
height: 4em;
// width: 4em;
overflow: visible;
margin: auto;
top: 0;
left: 50%;
bottom: 0;
right: 0;
`;
export const CustomSpinner = ({
size,
tip,
}:{
size:string,
tip:string,
})=>{
return(
<>
<SpinerStyle>
<Spin size={size} tip={tip} indicator={antIcon}/>
</SpinerStyle>
</>
)
}
export const DefaultSpinner = ()=>{
return(
<>
<Spin indicator={antIcon}/>
</>
)
}
| 33,381
|
https://github.com/romajs/react-calendar/blob/master/src/features/calendar/calendarSelectors.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
react-calendar
|
romajs
|
JavaScript
|
Code
| 28
| 74
|
import * as R from 'ramda';
import { createSelector } from 'reselect';
const getCalendar = R.prop('calendar');
export const monthSelector = createSelector([getCalendar], R.prop('month'));
export const yearSelector = createSelector([getCalendar], R.prop('year'));
| 44,016
|
https://github.com/dingxing123/fivestar/blob/master/Unity/Assets/Hotfix/GameGather/CardFiveStar/Handler/Actor_FiveStar_MaiMaHandler.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
fivestar
|
dingxing123
|
C#
|
Code
| 55
| 237
|
using System;
using System.Collections.Generic;
using System.Linq;
using ETModel;
namespace ETHotfix
{
[MessageHandler]
public class Actor_FiveStar_MaiMaHandler : AMHandler<Actor_FiveStar_MaiMa>
{
public static bool _IsMaima = false;
public static int _MaiMaScore = 0;
protected override async void Run(ETModel.Session session, Actor_FiveStar_MaiMa message)
{
_IsMaima = true;
_MaiMaScore = message.Score;
await UIComponent.GetUiView<MaiMaPanelComponent>().ShowMaiMaCard(message.Card, message.Score);
UIComponent.GetUiView<FiveStarSmallResultPanelComponent>().ShowSmallResult(Actor_FiveStar_SmallResultHandler.samllResultMessag);
_IsMaima = false;
}
}
}
| 47,748
|
https://github.com/arunantoney/Android-Kotlin-MVVM/blob/master/app/src/main/java/com/applab/ktmvvm/util/SchedulerProvider.kt
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
Android-Kotlin-MVVM
|
arunantoney
|
Kotlin
|
Code
| 15
| 40
|
package com.applab.ktmvvm.util
/**
* Created by Arun Antoney on 29-07-2018.
*/
class SchedulerProvider {
}
| 983
|
https://github.com/TArora238/atdlogistics/blob/master/src/views/LandingPage/Sections/SolutionsSection.js
|
Github Open Source
|
Open Source
|
MIT
| null |
atdlogistics
|
TArora238
|
JavaScript
|
Code
| 218
| 701
|
import React from "react";
// @material-ui/core components
import { makeStyles } from "@material-ui/core/styles";
import ContactSupport from "@material-ui/icons/ContactSupport";
import Description from "@material-ui/icons/Description";
import AccountBalanceWallet from "@material-ui/icons/AccountBalanceWallet";
import CreditCard from "@material-ui/icons/CreditCard";
// core components
import GridContainer from "components/Grid/GridContainer.js";
import GridItem from "components/Grid/GridItem.js";
import styles from "assets/jss/material-kit-react/views/landingPageSections/solutionsStyle.js";
import InfoArea from "components/InfoArea/InfoArea";
const useStyles = makeStyles(styles);
export default function SolutionsSection() {
const classes = useStyles();
return (
<div className={classes.section}>
<div className={classes.requestQuote}>
<GridContainer justify="center">
<GridItem xs={12} sm={12} md={12} lg={12}>
<h1 className={classes.title}>
Solutions That Take The Stress Out Of The Move
</h1>
</GridItem>
<GridItem
xs={12}
sm={12}
md={12}
lg={12}
className={classes.infoSection}
>
<div className={classes.infoBox}>
<InfoArea
title="24*7 Dispatching"
description="Our dispatching services include finding the top paying loads, conducting credit checks, negotiating rates, handling all emails, contracts, and billing."
icon={ContactSupport}
iconColor="info"
vertical={false}
horizontal
/>
</div>
<div className={classes.infoBox}>
<InfoArea
title="Accounting"
description="Our accounting team handles all the requirements including, carrier packets, broker setups, and all aspects of paperwork."
icon={Description}
iconColor="info"
vertical={false}
horizontal
/>
</div>
<div className={classes.infoBox}>
<InfoArea
title="Factoring"
description="Our factoring solutions help you obtain fuel cards and cash for on-the-road expenses besides ensuring on-time payments for your freight bills."
icon={AccountBalanceWallet}
iconColor="info"
horizontal
vertical={false}
/>
</div>
<div className={classes.infoBox}>
<InfoArea
title="Billing & Invoicing"
description="We submit your invoices to your factoring company so that you get timely payments for your loads."
icon={CreditCard}
iconColor="info"
horizontal
vertical={false}
/>
</div>
</GridItem>
</GridContainer>
</div>
</div>
);
}
| 3,053
|
https://github.com/RayRoestenburg/akka-in-action/blob/master/chapter-cluster/src/main/scala/aia/cluster/words/ReceptionistRouterLookup.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
akka-in-action
|
RayRoestenburg
|
Scala
|
Code
| 41
| 145
|
package aia.cluster
package words
import akka.actor._
import akka.cluster.routing._
import akka.routing._
trait ReceptionistRouterLookup { this: Actor =>
def receptionistRouter = context.actorOf(
ClusterRouterGroup(
BroadcastGroup(Nil),
ClusterRouterGroupSettings(
totalInstances = 100,
routeesPaths = List("/user/receptionist"),
allowLocalRoutees = true,
useRole = Some("master")
)
).props(),
name = "receptionist-router")
}
| 39,406
|
https://github.com/TimTheToad/CrazyCanvas/blob/master/LambdaEngine/Include/Rendering/AARenderer.h
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
CrazyCanvas
|
TimTheToad
|
C++
|
Code
| 269
| 1,327
|
#pragma once
#include "Rendering/CustomRenderer.h"
#include "Rendering/Core/API/CommandList.h"
#include "Rendering/Core/API/CommandAllocator.h"
#include "Rendering/Core/API/DescriptorHeap.h"
#include "Rendering/Core/API/DescriptorSet.h"
#include "Rendering/Core/API/PipelineLayout.h"
#include "Application/API/Events/WindowEvents.h"
#include "Application/API/Events/KeyEvents.h"
namespace LambdaEngine
{
enum class EAAMode
{
AAMODE_NONE = 0,
AAMODE_FXAA = 1,
AAMODE_TAA = 2,
};
/*
* AARenderer
*/
class AARenderer : public CustomRenderer
{
public:
AARenderer();
~AARenderer();
virtual bool Init() override final;
virtual bool RenderGraphInit(const CustomRendererRenderGraphInitDesc* pPreInitDesc) override final;
virtual void UpdateTextureResource(
const String& resourceName,
const TextureView* const* ppPerImageTextureViews,
const TextureView* const* ppPerSubImageTextureViews,
const Sampler* const* ppPerImageSamplers,
uint32 imageCount,
uint32 subImageCount,
bool backBufferBound) override final;
virtual void UpdateBufferResource(
const String& resourceName,
const Buffer* const* ppBuffers,
uint64* pOffsets,
uint64* pSizesInBytes,
uint32 count,
bool backBufferBound) override final;
virtual void Render(
uint32 modFrameIndex,
uint32 backBufferIndex,
CommandList** ppFirstExecutionStage,
CommandList** ppSecondaryExecutionStage,
bool sleeping) override final;
FORCEINLINE virtual FPipelineStageFlag GetFirstPipelineStage() const override final
{
return FPipelineStageFlag::PIPELINE_STAGE_FLAG_VERTEX_SHADER;
}
FORCEINLINE virtual FPipelineStageFlag GetLastPipelineStage() const override final
{
return FPipelineStageFlag::PIPELINE_STAGE_FLAG_PIXEL_SHADER;
}
FORCEINLINE virtual const String& GetName() const override final
{
static String name = "AA_RENDERER";
return name;
}
FORCEINLINE void SetAAMode(EAAMode aaMode)
{
m_AAMode = aaMode;
}
FORCEINLINE EAAMode GetAAMode() const
{
return m_AAMode;
}
public:
static FORCEINLINE AARenderer* GetInstance()
{
return s_pInstance;
}
private:
inline static AARenderer* s_pInstance = 0;
private:
TSharedRef<const Buffer> m_PerFrameBuffer;
TSharedRef<const Texture> m_IntermediateOutput;
TSharedRef<const TextureView> m_IntermediateOutputView;
TSharedRef<const Texture> m_Velocity;
TSharedRef<const TextureView> m_VelocityView;
TSharedRef<const Texture> m_Depth;
TSharedRef<const TextureView> m_DepthView;
TArray<TSharedRef<Texture>> m_BackBuffers;
TArray<TSharedRef<TextureView>> m_BackBufferViews;
TArray<TSharedRef<const Texture>> m_TAAHistory;
TArray<TSharedRef<const TextureView>> m_TAAHistoryViews;
uint32 m_Width;
uint32 m_Height;
uint64 m_Tick = 0;
bool m_NeedsUpdate = true;
EAAMode m_AAMode;
TSharedRef<Sampler> m_Sampler;
TArray<TSharedRef<CommandList>> m_CommandLists;
TArray<TSharedRef<CommandAllocator>> m_CommandAllocators;
uint64 m_BlitState;
TSharedRef<RenderPass> m_RenderPass;
TSharedRef<RenderPass> m_TAARenderPass;
uint64 m_TAAState;
TSharedRef<PipelineLayout> m_TAALayout;
uint64 m_FXAAState;
TSharedRef<PipelineLayout> m_FXAALayout;
TSharedRef<DescriptorHeap> m_DescriptorHeap;
TArray<TSharedRef<DescriptorSet>> m_TAATextureDescriptorSets;
TArray<TSharedRef<DescriptorSet>> m_TAABufferDescriptorSets;
TArray<TSharedRef<DescriptorSet>> m_FXAADescriptorSets;
};
}
| 32,394
|
https://github.com/G00dBye/YYMS/blob/master/scripts/field/achieve_davy.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
YYMS
|
G00dBye
|
Python
|
Code
| 29
| 78
|
# Maps in Lord PiratePQ | Used in the Lord Pirate PQ
if sm.getFieldID() == 925100500 and not sm.hasMobsInField():
sm.spawnMob(9300119, 566, 238, False) # Spawns Captain Davy John
sm.dispose()
| 46,742
|
https://github.com/base33/GlobalManifesto/blob/master/src/GlobalManifesto.Demo/Views/ContentPageLeftNav.cshtml
|
Github Open Source
|
Open Source
|
MIT
| null |
GlobalManifesto
|
base33
|
C#
|
Code
| 86
| 307
|
@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
Layout = "Global.cshtml";
}
@section headContent {}
@section Content {
<div class="content-page-left-nav">
<div id="side-container">
@Html.Container(new Container()
{
Classes = "aside-container",
Name = "asideContainer",
Tag = "aside",
WysiwygClass = "wysiwyg",
Blocks = new List<WebBlocks.Interfaces.IBlock>
{
new ContentBlock(1139)
}
})
</div>
@Html.Container(new Container()
{
Attributes = new Dictionary<string, string> { { "id", "main-container" } },
Classes = "main-container",
Name = "mainContainer",
Tag = "main",
WysiwygClass = "wysiwyg",
Blocks = new List<WebBlocks.Interfaces.IBlock>
{
new ContentBlock(1103),
new WysiwygBlock { Id = 100 }
}
})
</div>
}
| 47,484
|
https://github.com/musishui/u3d-loader/blob/master/dist/index.js
|
Github Open Source
|
Open Source
|
MIT
| null |
u3d-loader
|
musishui
|
JavaScript
|
Code
| 185
| 724
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = loader;
var _path = _interopRequireDefault(require("path"));
var _loaderUtils = _interopRequireDefault(require("loader-utils"));
var _lib = require("./lib");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
async function loader() {
var callback = this.async();
const options = _loaderUtils.default.getOptions(this);
const sourcePath = _path.default.dirname(this.resourcePath);
const modelName = _path.default.basename(sourcePath);
let jsUrl = _path.default.posix.join(modelName, 'Build', 'UnityLoader.js');
let jsonUrl = _path.default.posix.join(modelName, 'Build', 'builds.json');
if (options.outputPath) {
jsUrl = _path.default.posix.join(options.outputPath, jsUrl);
jsonUrl = _path.default.posix.join(options.outputPath, jsonUrl);
}
jsUrl = `__webpack_public_path__ + ${JSON.stringify(jsUrl)}`;
jsonUrl = `__webpack_public_path__ + ${JSON.stringify(jsonUrl)}`;
if (options.publicPath) {
jsUrl = `${options.publicPath.trimEnd('/')}/${jsUrl}`;
jsonUrl = `${options.publicPath.trimEnd('/')}/${jsonUrl}`;
jsUrl = Json.stringify(jsUrl);
jsonUrl = JSON.stringify(jsonUrl);
}
if (options.postTransformPublicPath) {
jsUrl = options.postTransformPublicPath(jsUrl);
jsonUrl = options.postTransformPublicPath(jsonUrl);
}
const prefix = _path.default.posix.join(options.outputPath || '', modelName);
const allFiles = (0, _lib.getAllFiles)(sourcePath);
allFiles.forEach(file => {
let rpath = _path.default.posix.join(prefix, _path.default.relative(sourcePath, file));
this.emitFile(rpath, (0, _lib.readFile)(file));
});
const esModule = typeof options.esModule !== 'undefined' ? options.esModule : false;
const importPath = _loaderUtils.default.stringifyRequest(this, `!${_path.default.join(__dirname, 'runtime/index.js')}`);
const rtn = `loadModel(${jsUrl}, ${jsonUrl})`;
const res = esModule ? `import loadModel from ${importPath}; export default ${rtn};` : `var loadModel = require(${importPath});module.exports=${rtn};`;
callback(null, res);
}
| 46,754
|
https://github.com/Ivanov-Stiliqn/OnlineShop/blob/master/Models/User.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
OnlineShop
|
Ivanov-Stiliqn
|
C#
|
Code
| 144
| 356
|
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
namespace Models
{
// Add profile data for application users by adding properties to the User class
public class User : IdentityUser
{
public User()
{
this.MyProducts = new List<Product>();
this.Reports = new List<Report>();
this.ReportsGiven = new List<Report>();
this.Reviews = new List<Review>();
this.PurchaseOrders = new List<Order>();
this.SellOrders = new List<Order>();
this.MessagesSent = new List<Message>();
this.MessagesReceived = new List<Message>();
}
public ICollection<Product> MyProducts { get; set; }
public bool IsRestricted { get; set; }
public string Whishlist { get; set; }
public UserInfo UserInfo { get; set; }
public ICollection<Report> Reports { get; set; }
public ICollection<Report> ReportsGiven { get; set; }
public ICollection<Review> Reviews { get; set; }
public ICollection<Order> PurchaseOrders { get; set; }
public ICollection<Order> SellOrders { get; set; }
public ICollection<Message> MessagesSent { get; set; }
public ICollection<Message> MessagesReceived { get; set; }
}
}
| 34,356
|
https://github.com/emredalkiran/store-finder/blob/master/src/server.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
store-finder
|
emredalkiran
|
TypeScript
|
Code
| 95
| 272
|
import env from 'dotenv'
import http from 'http'
import MongoConnection from './utils/database'
import App from './app'
import { Container } from 'winston'
import ServiceContainer from './service-container'
async function init() {
env.config()
const connectionURL = `mongodb://${process.env.URL}`
const port = process.env.PORT || 3000
const databaseConnection = new MongoConnection()
const app = new App()
try {
const db = await databaseConnection.connect(connectionURL, process.env.DATABASE_NAME!)
console.log(`Connected to ${process.env.DATABASE_NAME} database `)
console.log('Starting server...')
const serviceContainer = new ServiceContainer(db)
app.configureApp(serviceContainer)
const server = http.createServer(app.instance)
server.listen({host: 'localhost', port: port},()=> console.log(`Server listening on port ${port} at localhost`))
} catch (err) {
console.log(err)
}
}
init()
| 15,859
|
https://github.com/ezefranca/LogiKiD-Allegro5-Game/blob/master/doc/Doxygen/html/fase4_8h.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
LogiKiD-Allegro5-Game
|
ezefranca
|
JavaScript
|
Code
| 40
| 295
|
var fase4_8h =
[
[ "LevelQuatro", "struct_level_quatro.html", "struct_level_quatro" ],
[ "createLevelQuatro", "fase4_8h.html#a2e3f32a21095be47141c672563cda050", null ],
[ "destroyLevelQuatro", "fase4_8h.html#ab3270bd2db01c24e1aa639cc8c917363", null ],
[ "drawLevelQuatro", "fase4_8h.html#a46038b8242aecb210c6b3230f28c9612", null ],
[ "drawLogicLevelQuatro", "fase4_8h.html#a5047e57ff397b8288800c55544466e0e", null ],
[ "initDrawGatesLevelQuatro", "fase4_8h.html#a60b48ac5a9adef285e49f4b22b7a4158", null ],
[ "logicLevelQuatro", "fase4_8h.html#a1963ba9636812c08e8d0bd4e7ef4f6bf", null ]
];
| 29,038
|
https://github.com/BabakMahmoudi/parOdoo/blob/master/addons/odoo/addons/web/static/src/js/views/control_panel/control_panel_renderer.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
parOdoo
|
BabakMahmoudi
|
JavaScript
|
Code
| 1,169
| 3,505
|
odoo.define('web.ControlPanelRenderer', function (require) {
"use strict";
var config = require('web.config');
var data = require('web.data');
var FavoriteMenu = require('web.FavoriteMenu');
var FilterMenu = require('web.FilterMenu');
var GroupByMenu = require('web.GroupByMenu');
var mvc = require('web.mvc');
var SearchBar = require('web.SearchBar');
var TimeRangeMenu = require('web.TimeRangeMenu');
var Renderer = mvc.Renderer;
var ControlPanelRenderer = Renderer.extend({
template: 'ControlPanel',
custom_events: {
get_action_info: '_onGetActionInfo',
},
events: _.extend({}, Renderer.prototype.events, {
'click .o_searchview_more': '_onMore',
}),
/**
* @override
* @param {Object} [params.action] current action if any
* @param {Object} [params.context]
* @param {Object[]} [params.breadcrumbs=[]] list of breadcrumbs elements
* @param {boolean} [params.withBreadcrumbs=false] if false, breadcrumbs
* won't be rendered
* @param {boolean} [params.withSearchBar=false] if false, no search bar
* is rendered
* @param {string[]} [params.searchMenuTypes=[]] determines the search menus
* that are displayed.
* @param {String} [params.template] the QWeb template to render the
* ControlPanel. By default, the template 'ControlPanel' will be used.
* @param {string} [params.title=''] the title visible in control panel
*/
init: function (parent, state, params) {
this._super.apply(this, arguments);
this._breadcrumbs = params.breadcrumbs || [];
this._title = params.title || '';
this.withBreadcrumbs = params.withBreadcrumbs;
this.withSearchBar = params.withSearchBar;
if (params.template) {
this.template = params.template;
}
this.context = params.context;
this.$subMenus = null;
this.action = params.action;
this.displaySearchMenu = true;
this.isMobile = config.device.isMobile;
this.menusSetup = false;
this.searchMenuTypes = params.searchMenuTypes || [];
this.subMenus = {};
},
/**
* Render the control panel and create a dictionnary of its exposed elements.
*
* @override
*/
start: function () {
var self = this;
// exposed jQuery nodesets
this.nodes = {
$buttons: this.$('.o_cp_buttons'),
$pager: this.$('.o_cp_pager'),
$sidebar: this.$('.o_cp_sidebar'),
$switch_buttons: this.$('.o_cp_switch_buttons'),
};
// if we don't use the default search bar and buttons, we expose the
// corresponding areas for custom content
if (!this.withSearchBar) {
this.nodes.$searchview = this.$('.o_cp_searchview');
}
if (this.searchMenuTypes.length === 0) {
this.nodes.$searchview_buttons = this.$('.o_search_options');
}
if (this.withBreadcrumbs) {
this._renderBreadcrumbs();
}
var superDef = this._super.apply(this, arguments);
var searchDef = this._renderSearch();
return Promise.all([superDef, searchDef]).then(function () {
self._setSearchMenusVisibility();
});
},
/**
* @override
*/
on_attach_callback: function () {
this._focusSearchInput();
},
/**
* @override
*/
on_detach_callback: function () {
},
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* @returns {Object|undefined}
*/
getLastFacet: function () {
return this.state.facets.slice(-1)[0];
},
/**
* This function is called when actions call 'updateControlPanel' with
* custom contents to insert in the exposed areas.
*
* @param {Object} status
* @param {Object} [status.cp_content] dictionnary containing the jQuery
* elements to insert in the exposed areas
* @param {string} [status.breadcrumbs] the breadcrumbs to display before
* the current controller
* @param {string} [status.title] the title of the current controller, to
* display at the end of the breadcrumbs
* @param {Object} [options]
* @param {Boolean} [options.clear=true] set to false to keep control panel
* elements that are not in status.cp_content (useful for partial updates)
*/
updateContents: function (status, options) {
var new_cp_content = status.cp_content || {};
var clear = 'clear' in (options || {}) ? options.clear : true;
if (this.withBreadcrumbs) {
this._breadcrumbs = status.breadcrumbs || this._breadcrumbs;
this._title = status.title || this._title;
this._renderBreadcrumbs();
}
if (clear) {
this._detachContent(this.nodes);
} else {
this._detachContent(_.pick(this.nodes, _.keys(new_cp_content)));
}
this._attachContent(new_cp_content);
},
/**
* Update the state of the renderer state. It retriggers a full rerendering.
*
* @param {Object} state
* @returns {Promise}
*/
updateState: function (state) {
this.state = state;
return this._renderSearch();
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* @private
* @param {Object} content dictionnary of jQuery elements to attach, whose
* keys are jQuery nodes identifiers in this.nodes
*/
_attachContent: function (content) {
for (var $element in content) {
var $nodeset = content[$element];
if ($nodeset && this.nodes[$element]) {
this.nodes[$element].append($nodeset);
}
}
},
/**
* @private
* @param {Object} content subset of this.nodes to detach
*/
_detachContent: function (content) {
for (var $element in content) {
content[$element].contents().detach();
}
},
/**
* @private
*/
_focusSearchInput: function () {
if (this.withSearchBar && !config.device.isMobile) {
// in mobile mode, we would rather not focus manually the
// input, because it opens up the integrated keyboard, which is
// not what you expect when you just selected a filter.
this.searchBar.focus();
}
},
/**
* @private
* @param {string} menuType
* @returns {Objects[]} menuItems
*/
_getMenuItems: function (menuType) {
var menuItems;
if (menuType === 'filter') {
menuItems = this.state.filters;
}
if (menuType === 'groupBy') {
menuItems = this.state.groupBys;
}
if (menuType === 'timeRange') {
menuItems = this.state.timeRanges;
}
if (menuType === 'favorite') {
menuItems = this.state.favorites;
}
return menuItems;
},
/**
* @private
* @returns {jQueryElement}
*/
_getSubMenusPlace: function () {
return $('<div>').appendTo(this.$('.o_search_options'));
},
/**
* @private
*/
_renderBreadcrumbs: function () {
var self = this;
var breadcrumbsDescriptors = this._breadcrumbs.concat({title: this._title});
var breadcrumbs = breadcrumbsDescriptors.map(function (bc, index) {
return self._renderBreadcrumbsItem(bc, index, breadcrumbsDescriptors.length);
});
this.$('.breadcrumb').html(breadcrumbs);
},
/**
* Render a breadcrumbs' li jQuery element.
*
* @private
* @param {Object} bc
* @param {string} bc.title
* @param {string} bc.controllerID
* @param {integer} index
* @param {integer} length
* @returns {jQueryElement} $bc
*/
_renderBreadcrumbsItem: function (bc, index, length) {
var self = this;
var is_last = (index === length-1);
var li_content = bc.title && _.escape(bc.title.trim()) || data.noDisplayContent;
var $bc = $('<li>', {class: 'breadcrumb-item'})
.append(is_last ? li_content : $('<a>', {href: '#'}).html(li_content))
.toggleClass('active', is_last);
if (!is_last) {
$bc.click(function (ev) {
ev.preventDefault();
self.trigger_up('breadcrumb_clicked', {controllerID: bc.controllerID});
});
}
var secondLast = index === length - 2;
if (secondLast) {
$bc.attr('accessKey', 'b');
}
return $bc;
},
/**
* Renderer the search bar and the search menus
*
* @private
* @returns {Promise}
*/
_renderSearch: function () {
var defs = [];
if (this.menusSetup) {
this._updateMenus();
} else {
this.menusSetup = true;
defs = defs.concat(this._setupMenus());
}
if (this.withSearchBar) {
defs.push(this._renderSearchBar());
}
return Promise.all(defs).then(this._focusSearchInput.bind(this));
},
/**
* @private
* @returns {Promise}
*/
_renderSearchBar: function () {
// TODO: might need a reload instead of a destroy/instantiate
var oldSearchBar = this.searchBar;
this.searchBar = new SearchBar(this, {
context: this.context,
facets: this.state.facets,
fields: this.state.fields,
filterFields: this.state.filterFields,
});
return this.searchBar.appendTo(this.$('.o_searchview')).then(function () {
if (oldSearchBar) {
oldSearchBar.destroy();
}
});
},
/**
* Hide or show the search menus according to this.displaySearchMenu.
*
* @private
*/
_setSearchMenusVisibility: function () {
this.$('.o_searchview_more')
.toggleClass('fa-search-plus', !this.displaySearchMenu)
.toggleClass('fa-search-minus', this.displaySearchMenu);
this.$('.o_search_options')
.toggleClass('o_hidden', !this.displaySearchMenu);
},
/**
* Create a new menu of the given type and append it to this.$subMenus.
* This menu is also added to this.subMenus.
*
* @private
* @param {string} menuType
* @returns {Promise}
*/
_setupMenu: function (menuType) {
var Menu;
var menu;
if (menuType === 'filter') {
Menu = FilterMenu;
}
if (menuType === 'groupBy') {
Menu = GroupByMenu;
}
if (menuType === 'timeRange') {
Menu = TimeRangeMenu;
}
if (menuType === 'favorite') {
Menu = FavoriteMenu;
}
if (_.contains(['filter', 'groupBy', 'timeRange'], menuType)) {
menu = new Menu(this, this._getMenuItems(menuType), this.state.fields);
}
if (menuType === 'favorite') {
menu = new Menu(this, this._getMenuItems(menuType), this.action);
}
this.subMenus[menuType] = menu;
return menu.appendTo(this.$subMenus);
},
/**
* Instantiate the search menu determined by this.searchMenuTypes.
*
* @private
* @returns {Promise[]}
*/
_setupMenus: function () {
this.$subMenus = this._getSubMenusPlace();
return this.searchMenuTypes.map(this._setupMenu.bind(this));
},
/**
* Update the search menus.
*
* @private
*/
_updateMenus: function () {
var self = this;
this.searchMenuTypes.forEach(function (menuType) {
self.subMenus[menuType].update(self._getMenuItems(menuType));
});
},
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* Toggle the search menus visibility.
*
* @private
*/
_onMore: function () {
this.displaySearchMenu = !this.displaySearchMenu;
this._setSearchMenusVisibility();
},
});
return ControlPanelRenderer;
});
| 28,666
|
https://github.com/lukasz-golebiewski/mantis/blob/master/src/test/scala/io/iohk/ethereum/jsonrpc/CheckpointingServiceSpec.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
mantis
|
lukasz-golebiewski
|
Scala
|
Code
| 661
| 2,247
|
package io.iohk.ethereum.jsonrpc
import akka.actor.ActorSystem
import akka.testkit.{TestKit, TestProbe}
import io.iohk.ethereum.blockchain.sync.regular.RegularSync.NewCheckpoint
import io.iohk.ethereum.consensus.blocks.CheckpointBlockGenerator
import io.iohk.ethereum.domain.{Block, BlockBody, BlockchainImpl, Checkpoint}
import io.iohk.ethereum.jsonrpc.CheckpointingService._
import io.iohk.ethereum.ledger.Ledger
import io.iohk.ethereum.{Fixtures, NormalPatience, WithActorSystemShutDown}
import monix.execution.Scheduler.Implicits.global
import org.scalacheck.Gen
import org.scalamock.scalatest.MockFactory
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.flatspec.AnyFlatSpecLike
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
class CheckpointingServiceSpec
extends TestKit(ActorSystem("CheckpointingServiceSpec_System"))
with AnyFlatSpecLike
with WithActorSystemShutDown
with MockFactory
with ScalaFutures
with NormalPatience
with ScalaCheckPropertyChecks
with Matchers {
"CheckpointService" should "get latest block (at a correct checkpointing interval) from Blockchain" in new TestSetup {
val nums = for {
k <- Gen.choose[Int](1, 10) // checkpointing interval
m <- Gen.choose(0, 1000) // number of checkpoints in the chain
n <- Gen.choose(0, k - 1) // distance from best block to checkpointed block
} yield (k, m, n)
forAll(nums) { case (k, m, n) =>
val checkpointedBlockNum: BigInt = k * m
val bestBlockNum: BigInt = checkpointedBlockNum + n
val block = Block(Fixtures.Blocks.ValidBlock.header.copy(number = checkpointedBlockNum), BlockBody.empty)
val request = GetLatestBlockRequest(k, None)
val expectedResponse = GetLatestBlockResponse(Some(BlockInfo(block.hash, block.number)))
(blockchain.getBestBlockNumber _).expects().returning(bestBlockNum)
(blockchain.getBlockByNumber _).expects(checkpointedBlockNum).returning(Some(block))
val result = service.getLatestBlock(request)
result.runSyncUnsafe() shouldEqual Right(expectedResponse)
}
}
it should "get latest block that is a descendant of the passed parent checkpoint block" in new TestSetup {
val nums = for {
k <- Gen.choose[Int](1, 10) // checkpointing interval
m <- Gen.choose(0, 1000) // number of checkpoints in the chain
n <- Gen.choose(0, k - 1) // distance from best block to checkpointed block
} yield (k, m, n)
val previousCheckpoint = Fixtures.Blocks.Block3125369.block
val hash = previousCheckpoint.hash
forAll(nums) { case (k, m, n) =>
val checkpointedBlockNum: BigInt = k * m
val bestBlockNum: BigInt = checkpointedBlockNum + n
val block = Block(Fixtures.Blocks.ValidBlock.header.copy(number = checkpointedBlockNum), BlockBody.empty)
val request = GetLatestBlockRequest(k, Some(hash))
val expectedResponse = GetLatestBlockResponse(Some(BlockInfo(block.hash, block.number)))
(blockchain.getBestBlockNumber _).expects().returning(bestBlockNum)
(blockchain.getBlockHeaderByHash _).expects(hash).returning(Some(previousCheckpoint.header.copy(number = 0)))
(blockchain.getBlockByNumber _).expects(checkpointedBlockNum).returning(Some(block))
val result = service.getLatestBlock(request)
result.runSyncUnsafe() shouldEqual Right(expectedResponse)
}
}
it should "not return a block that is at the same height as the passed parent checkpoint block" in new TestSetup {
val nums = for {
k <- Gen.choose[Int](1, 10) // checkpointing interval
m <- Gen.choose(0, 1000) // number of checkpoints in the chain
n <- Gen.choose(0, k - 1) // distance from best block to checkpointed block
} yield (k, m, n)
val previousCheckpoint = Fixtures.Blocks.ValidBlock.block
val hash = previousCheckpoint.hash
forAll(nums) { case (k, m, n) =>
val checkpointedBlockNum: BigInt = k * m
val bestBlockNum: BigInt = checkpointedBlockNum + n
val request = GetLatestBlockRequest(k, Some(hash))
val expectedResponse = GetLatestBlockResponse(None)
(blockchain.getBestBlockNumber _).expects().returning(bestBlockNum)
(blockchain.getBlockHeaderByHash _)
.expects(hash)
.returning(Some(previousCheckpoint.header.copy(number = bestBlockNum)))
(blockchain.getBlockByNumber _).expects(*).returning(Some(previousCheckpoint))
val result = service.getLatestBlock(request)
result.runSyncUnsafe() shouldEqual Right(expectedResponse)
}
}
it should "return an empty response if the descendant is not a part of a local blockchain" in new TestSetup {
val nums = for {
k <- Gen.choose[Int](1, 10) // checkpointing interval
m <- Gen.choose(0, 1000) // number of checkpoints in the chain
n <- Gen.choose(0, k - 1) // distance from best block to checkpointed block
} yield (k, m, n)
val previousCheckpoint = Fixtures.Blocks.ValidBlock.block
val hash = previousCheckpoint.hash
forAll(nums) { case (k, m, n) =>
val checkpointedBlockNum: BigInt = k * m
val bestBlockNum: BigInt = checkpointedBlockNum + n
val block = Block(Fixtures.Blocks.ValidBlock.header.copy(number = checkpointedBlockNum), BlockBody.empty)
val request = GetLatestBlockRequest(k, Some(hash))
val expectedResponse = GetLatestBlockResponse(None)
(blockchain.getBestBlockNumber _).expects().returning(bestBlockNum)
(blockchain.getBlockHeaderByHash _).expects(hash).returning(None)
(blockchain.getBlockByNumber _).expects(checkpointedBlockNum).returning(Some(block))
val result = service.getLatestBlock(request)
result.runSyncUnsafe() shouldEqual Right(expectedResponse)
}
}
it should "send new checkpoint to Sync" in new TestSetup {
val parentBlock = Fixtures.Blocks.ValidBlock.block
val hash = parentBlock.hash
val signatures = Nil
val request = PushCheckpointRequest(hash, signatures)
val expectedResponse = PushCheckpointResponse()
(ledger.getBlockByHash _).expects(hash).returning(Some(parentBlock)).once()
val result = service.pushCheckpoint(request).runSyncUnsafe()
val checkpointBlock = checkpointBlockGenerator.generate(parentBlock, Checkpoint(signatures))
syncController.expectMsg(NewCheckpoint(checkpointBlock))
result shouldEqual Right(expectedResponse)
}
it should "get latest block in case of blockchain re-org" in new TestSetup {
val block = Fixtures.Blocks.ValidBlock.block
val expectedResponse = GetLatestBlockResponse(Some(BlockInfo(block.hash, block.number)))
(blockchain.getBestBlockNumber _)
.expects()
.returning(7)
(blockchain.getBlockByNumber _)
.expects(BigInt(4))
.returning(None)
(blockchain.getBestBlockNumber _)
.expects()
.returning(7)
(blockchain.getBlockByNumber _)
.expects(BigInt(4))
.returning(Some(block))
val result = service.getLatestBlock(GetLatestBlockRequest(4, None))
result.runSyncUnsafe() shouldEqual Right(expectedResponse)
}
trait TestSetup {
val blockchain = mock[BlockchainImpl]
val ledger = mock[Ledger]
val syncController = TestProbe()
val checkpointBlockGenerator: CheckpointBlockGenerator = new CheckpointBlockGenerator()
val service = new CheckpointingService(blockchain, ledger, checkpointBlockGenerator, syncController.ref)
}
}
| 28,844
|
https://github.com/healtheloper/JS-Array-Challenge/blob/master/Challenge/uhj1993/forEachMap/solve.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
JS-Array-Challenge
|
healtheloper
|
JavaScript
|
Code
| 21
| 51
|
const inputArray = [100, 10, 20, 40];
// write your codes
const arr = [];
inputArray.forEach((item) => arr.push(item + "%"));
console.log(arr);
| 32,797
|
https://github.com/tektoncd/operator/blob/master/pkg/apis/operator/v1alpha1/tektoninstallerset_lifecycle_test.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
operator
|
tektoncd
|
Go
|
Code
| 347
| 1,438
|
/*
Copyright 2021 The Tekton Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
"testing"
"k8s.io/apimachinery/pkg/runtime/schema"
apistest "knative.dev/pkg/apis/testing"
)
func TestTektonInstallerSetGroupVersionKind(t *testing.T) {
r := &TektonInstallerSet{}
want := schema.GroupVersionKind{
Group: GroupName,
Version: SchemaVersion,
Kind: KindTektonInstallerSet,
}
if got := r.GetGroupVersionKind(); got != want {
t.Errorf("got: %v, want: %v", got, want)
}
}
func TestTektonInstallerSetHappyPath(t *testing.T) {
tis := &TektonInstallerSetStatus{}
tis.InitializeConditions()
apistest.CheckConditionOngoing(tis, CrdInstalled, t)
apistest.CheckConditionOngoing(tis, ClustersScoped, t)
apistest.CheckConditionOngoing(tis, NamespaceScoped, t)
apistest.CheckConditionOngoing(tis, DeploymentsAvailable, t)
apistest.CheckConditionOngoing(tis, WebhookReady, t)
apistest.CheckConditionOngoing(tis, ControllerReady, t)
apistest.CheckConditionOngoing(tis, AllDeploymentsReady, t)
// Install succeeds.
tis.MarkCRDsInstalled()
apistest.CheckConditionSucceeded(tis, CrdInstalled, t)
tis.MarkClustersScopedResourcesInstalled()
apistest.CheckConditionSucceeded(tis, ClustersScoped, t)
tis.MarkNamespaceScopedResourcesInstalled()
apistest.CheckConditionSucceeded(tis, NamespaceScoped, t)
tis.MarkDeploymentsAvailable()
apistest.CheckConditionSucceeded(tis, DeploymentsAvailable, t)
// Initially Webhook will not be available
tis.MarkWebhookNotReady("waiting for pods")
apistest.CheckConditionFailed(tis, WebhookReady, t)
tis.MarkWebhookReady()
apistest.CheckConditionSucceeded(tis, WebhookReady, t)
tis.MarkControllerReady()
apistest.CheckConditionSucceeded(tis, ControllerReady, t)
tis.MarkAllDeploymentsReady()
apistest.CheckConditionSucceeded(tis, AllDeploymentsReady, t)
if ready := tis.IsReady(); !ready {
t.Errorf("tt.IsReady() = %v, want true", ready)
}
}
func TestTektonInstallerSetErrorPath(t *testing.T) {
tis := &TektonInstallerSetStatus{}
tis.InitializeConditions()
apistest.CheckConditionOngoing(tis, CrdInstalled, t)
apistest.CheckConditionOngoing(tis, ClustersScoped, t)
apistest.CheckConditionOngoing(tis, NamespaceScoped, t)
apistest.CheckConditionOngoing(tis, DeploymentsAvailable, t)
apistest.CheckConditionOngoing(tis, WebhookReady, t)
apistest.CheckConditionOngoing(tis, ControllerReady, t)
apistest.CheckConditionOngoing(tis, AllDeploymentsReady, t)
// CrdsInstall succeeds
tis.MarkCRDsInstalled()
apistest.CheckConditionSucceeded(tis, CrdInstalled, t)
// ClustersScopedResources Install succeeds
tis.MarkClustersScopedResourcesInstalled()
apistest.CheckConditionSucceeded(tis, ClustersScoped, t)
// NamespaceScopedResources Install succeeds
tis.MarkNamespaceScopedResourcesInstalled()
apistest.CheckConditionSucceeded(tis, NamespaceScoped, t)
// DeploymentsAvailable succeeds
tis.MarkDeploymentsAvailable()
apistest.CheckConditionSucceeded(tis, DeploymentsAvailable, t)
// Initially Webhook will not be available
tis.MarkWebhookNotReady("waiting for pods")
apistest.CheckConditionFailed(tis, WebhookReady, t)
tis.MarkWebhookReady()
apistest.CheckConditionSucceeded(tis, WebhookReady, t)
tis.MarkControllerReady()
apistest.CheckConditionSucceeded(tis, ControllerReady, t)
tis.MarkAllDeploymentsReady()
apistest.CheckConditionSucceeded(tis, AllDeploymentsReady, t)
if ready := tis.IsReady(); !ready {
t.Errorf("tt.IsReady() = %v, want true", ready)
}
// Now in further reconciliation some error occurred in any of the
// condition
tis.MarkCRDsInstallationFailed("failed due to some error")
apistest.CheckConditionFailed(tis, CrdInstalled, t)
if ready := tis.IsReady(); ready {
t.Errorf("tt.IsReady() = %v, want false", ready)
}
}
| 11,031
|
https://github.com/gopalshendge18/Practice-Question/blob/master/Day 17/Q.1]/Ravi.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Practice-Question
|
gopalshendge18
|
C++
|
Code
| 92
| 451
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t=1;
// cin>>t;
while(t--)
{
ll n;
cin>>n;
ll arr[n];
ll sum[n]={0};
for(ll i=0;i<n;i++)
{
cin>>arr[i];
if(i!=0)
sum[i] = sum[i-1] + arr[i];
else sum[i] = arr[i];
}
ll sorted[n];
for(ll i=0;i<n;i++) sorted[i] = arr[i];
sort(sorted,sorted+n);
ll sum2[n];
for(ll i=0;i<n;i++)
{
if(i!=0)
sum2[i] = sum2[i-1] + sorted[i];
else sum2[i] = sorted[i];
}
ll m;
cin>>m;
while(m--)
{
ll type,l,r;
cin>>type>>l>>r;
if(type==1)
{
if(l!=1)
cout<<sum[r-1]-sum[l-2]<<endl;
else
cout<<sum[r-1]<<endl;
}
else
{
if(l!=1)
cout<<sum2[r-1]-sum2[l-2]<<endl;
else
cout<<sum2[r-1]<<endl;
}
}
}
return 0;
}
| 15,240
|
https://github.com/mvirenius/ptv-1.7/blob/master/src/PTV.Application.Web/wwwroot/js/app/Routes/GeneralDescription/components/GeneralDescriptionForm/GeneralDescriptionForm.js
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
ptv-1.7
|
mvirenius
|
JavaScript
|
Code
| 570
| 1,703
|
/**
* The MIT License
* Copyright (c) 2016 Population Register Centre (VRK)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import React from 'react'
import PropTypes from 'prop-types'
import { compose } from 'redux'
import { connect } from 'react-redux'
import { reduxForm } from 'redux-form/immutable'
import GeneralDescriptionBasic from '../GeneralDescriptionBasic'
import GeneralDescriptionClassificationAndKeywords from '../GeneralDescriptionClassificationAndKeywords'
import { generalDescriptionBasicTransformer } from 'Routes/GeneralDescription/components/generalDescriptionTransformers'
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'
import { Accordion } from 'appComponents/Accordion'
import {
withEntityHeader,
withBubbling,
withEntityButtons,
withFormStates,
withEntityTitle,
withNotification,
withPublishingDialog,
withConnectionStep,
withPreviewDialog
} from 'util/redux-form/HOC'
import {
LanguageComparisonSelect,
ValidationMessages
} from 'appComponents'
import { handleOnSubmit, handleOnSubmitSuccess } from 'util/redux-form/util'
import { getGeneralDescription } from 'Routes/GeneralDescription/selectors'
import { EntitySelectors } from 'selectors'
import { getIsFormLoading } from 'selectors/formStates'
import { Label } from 'sema-ui-components'
import { EntitySchemas } from 'schemas'
import { formTypesEnum } from 'enums'
import { messages as commonFormMessages } from 'Routes/messages'
import { getGeneralDescription as getGeneralDescriptionAction } from 'Routes/GeneralDescription/actions'
import cx from 'classnames'
import styles from './styles.scss'
import { validateForPublish } from 'util/redux-form/syncValidation/publishing'
export const messages = defineMessages({
entityTitleNew: {
id: 'Containers.GeneralDescription.Add.Header.Title',
defaultMessage: 'Lisää pohjakuvaus'
},
formTitle: {
id: 'Containers.GeneralDescription.Add.Step1.Header.Title',
defaultMessage: 'Perustiedot'
},
formTitle2: {
id: 'Containers.GeneralDescription.Step2.Title',
defaultMessage: 'Luokittelu ja asiasanat'
},
formTitle2InfoText: {
id: 'Routes.GeneralDescription.GeneralDescriptionForm.Section2.InfoText',
defaultMessage: 'Tämän osion tiedot eivät näy loppukäyttäjille.'
}
})
const GeneralDescriptionForm = ({ handleSubmit, form, intl: { formatMessage }, isCompareMode }) => {
const formClass = cx(
styles.form,
{
[styles.compareMode]: isCompareMode
}
)
return (
<form onSubmit={handleSubmit} className={formClass}>
<LanguageComparisonSelect />
<Accordion>
<Accordion.Title
title={formatMessage(messages.formTitle)}
validateFields={[
'name', 'organization'
]}
/>
<div className='row'>
<div className='col-lg-12'>
<ValidationMessages form={form} top />
</div>
</div>
<Accordion.Content>
<GeneralDescriptionBasic />
</Accordion.Content>
</Accordion>
<Accordion>
<Accordion.Title title={formatMessage(messages.formTitle2)}>
<Label infoLabel labelText={formatMessage(messages.formTitle2InfoText)} />
</Accordion.Title>
<Accordion.Content>
<GeneralDescriptionClassificationAndKeywords />
</Accordion.Content>
</Accordion>
<div className='row'>
<div className='col-lg-12'>
<ValidationMessages form={form} />
</div>
</div>
</form>
)
}
GeneralDescriptionForm.propTypes = {
handleSubmit: PropTypes.func.isRequired,
form: PropTypes.string.isRequired,
intl: PropTypes.object.isRequired,
isCompareMode: PropTypes.bool
}
const onSubmit = handleOnSubmit({
url: 'generalDescription/SaveGeneralDescription',
transformers: [
generalDescriptionBasicTransformer
],
schema: EntitySchemas.GENERAL_DESCRIPTION
})
const onSubmitFail = (values, x1, x2, x4) => console.log('values:\n', values, x2, x4)
const onSubmitSuccess = (props, dispatch) => {
handleOnSubmitSuccess(props, dispatch, formTypesEnum.GENERALDESCRIPTIONFORM, getGeneralDescription)
}
const getIsLoading = getIsFormLoading(formTypesEnum.GENERALDESCRIPTIONFORM)
export default compose(
injectIntl,
connect((state, ownProps) => ({
initialValues: getGeneralDescription(state, ownProps),
isLoading: EntitySelectors.generalDescriptions.getEntityIsFetching(state) || getIsLoading(state)
})),
reduxForm({
form: formTypesEnum.GENERALDESCRIPTIONFORM,
enableReinitialize: true,
onSubmit,
onSubmitFail,
onSubmitSuccess,
warn: validateForPublish
}),
withBubbling,
withNotification,
withFormStates,
withEntityTitle({
newEntityTitle: <FormattedMessage {...messages.entityTitleNew} />,
newLanguageVersionTitle: <FormattedMessage {...commonFormMessages.languageVersionTitleNew} />
}),
withConnectionStep,
withEntityButtons({
formNameToSubmit: formTypesEnum.GENERALDESCRIPTIONFORM
}),
withEntityHeader({
entityId: null,
getEndpoint: getGeneralDescriptionAction
}),
withPublishingDialog(),
withPreviewDialog
)(GeneralDescriptionForm)
| 14,395
|
https://github.com/seyuf/magento-actions-sample/blob/master/magento/dev/tests/api-functional/testsuite/Magento/GraphQl/Quote/Customer/PlaceOrderTest.php
|
Github Open Source
|
Open Source
|
MIT, OSL-3.0, LicenseRef-scancode-unknown-license-reference, AFL-2.1, AFL-3.0
| 2,023
|
magento-actions-sample
|
seyuf
|
PHP
|
Code
| 943
| 5,002
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\GraphQl\Quote\Customer;
use Exception;
use Magento\Framework\Registry;
use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId;
use Magento\Integration\Api\CustomerTokenServiceInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;
/**
* Test for placing an order for customer
*/
class PlaceOrderTest extends GraphQlAbstract
{
/**
* @var CustomerTokenServiceInterface
*/
private $customerTokenService;
/**
* @var GetMaskedQuoteIdByReservedOrderId
*/
private $getMaskedQuoteIdByReservedOrderId;
/**
* @var CollectionFactory
*/
private $orderCollectionFactory;
/**
* @var OrderRepositoryInterface
*/
private $orderRepository;
/**
* @var Registry
*/
private $registry;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class);
$this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class);
$this->orderCollectionFactory = $objectManager->get(CollectionFactory::class);
$this->orderRepository = $objectManager->get(OrderRepositoryInterface::class);
$this->registry = Bootstrap::getObjectManager()->get(Registry::class);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
* @magentoConfigFixture default_store carriers/flatrate/active 1
* @magentoConfigFixture default_store carriers/tablerate/active 1
* @magentoConfigFixture default_store carriers/freeshipping/active 1
* @magentoConfigFixture default_store payment/banktransfer/active 1
* @magentoConfigFixture default_store payment/cashondelivery/active 1
* @magentoConfigFixture default_store payment/checkmo/active 1
* @magentoConfigFixture default_store payment/purchaseorder/active 1
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_checkmo_payment_method.php
*/
public function testPlaceOrder()
{
$reservedOrderId = 'test_quote';
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId);
$query = $this->getQuery($maskedQuoteId);
$response = $this->graphQlMutation($query, [], '', $this->getHeaderMap());
self::assertArrayHasKey('placeOrder', $response);
self::assertArrayHasKey('order_number', $response['placeOrder']['order']);
self::assertEquals($reservedOrderId, $response['placeOrder']['order']['order_number']);
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
*/
public function testPlaceOrderIfCartIdIsEmpty()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Required parameter "cart_id" is missing');
$maskedQuoteId = '';
$query = $this->getQuery($maskedQuoteId);
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
*/
public function testPlaceOrderWithNoItemsInCart()
{
$reservedOrderId = 'test_quote';
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId);
$query = $this->getQuery($maskedQuoteId);
self::expectExceptionMessage(
'Unable to place order: A server error stopped your order from being placed. ' .
'Please try to place your order again'
);
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php
*/
public function testPlaceOrderWithNoShippingAddress()
{
$reservedOrderId = 'test_quote';
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId);
$query = $this->getQuery($maskedQuoteId);
self::expectExceptionMessage(
'Unable to place order: Some addresses can\'t be used due to the configurations for specific countries'
);
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php
*/
public function testPlaceOrderWithNoShippingMethod()
{
$reservedOrderId = 'test_quote';
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId);
$query = $this->getQuery($maskedQuoteId);
self::expectExceptionMessage(
'Unable to place order: The shipping method is missing. Select the shipping method and try again'
);
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
* @magentoConfigFixture default_store carriers/flatrate/active 1
* @magentoConfigFixture default_store carriers/tablerate/active 1
* @magentoConfigFixture default_store carriers/freeshipping/active 1
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php
*/
public function testPlaceOrderWithNoBillingAddress()
{
$reservedOrderId = 'test_quote';
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId);
$query = $this->getQuery($maskedQuoteId);
self::expectExceptionMessageMatches(
'/Unable to place order: Please check the billing address information*/'
);
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
/**
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
* @magentoConfigFixture default_store carriers/flatrate/active 1
* @magentoConfigFixture default_store carriers/tablerate/active 1
* @magentoConfigFixture default_store carriers/freeshipping/active 1
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php
*/
public function testPlaceOrderWithNoPaymentMethod()
{
$reservedOrderId = 'test_quote';
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId);
$query = $this->getQuery($maskedQuoteId);
self::expectExceptionMessage('Unable to place order: Enter a valid payment method and try again');
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
/**
* @magentoConfigFixture cataloginventory/options/enable_inventory_check 1
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
* @magentoConfigFixture default_store carriers/flatrate/active 1
* @magentoConfigFixture default_store carriers/tablerate/active 1
* @magentoConfigFixture default_store carriers/freeshipping/active 1
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/set_simple_product_out_of_stock.php
*/
public function testPlaceOrderWithOutOfStockProduct()
{
$reservedOrderId = 'test_quote';
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId);
$query = $this->getQuery($maskedQuoteId);
self::expectExceptionMessage('Unable to place order: Some of the products are out of stock');
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
/**
* @magentoConfigFixture cataloginventory/options/enable_inventory_check 0
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
* @magentoConfigFixture default_store carriers/flatrate/active 1
* @magentoConfigFixture default_store carriers/tablerate/active 1
* @magentoConfigFixture default_store carriers/freeshipping/active 1
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/set_simple_product_out_of_stock.php
*/
public function testPlaceOrderWithOutOfStockProductWithDisabledInventoryCheck()
{
$reservedOrderId = 'test_quote';
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId);
$query = $this->getQuery($maskedQuoteId);
self::expectExceptionMessage('Unable to place order: Enter a valid payment method and try again.');
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
/**
* _security
* @magentoApiDataFixture Magento/Customer/_files/customer.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
* @magentoConfigFixture default_store carriers/flatrate/active 1
* @magentoConfigFixture default_store carriers/tablerate/active 1
* @magentoConfigFixture default_store carriers/freeshipping/active 1
* @magentoConfigFixture default_store payment/banktransfer/active 1
* @magentoConfigFixture default_store payment/cashondelivery/active 1
* @magentoConfigFixture default_store payment/checkmo/active 1
* @magentoConfigFixture default_store payment/purchaseorder/active 1
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_checkmo_payment_method.php
*/
public function testPlaceOrderOfGuestCart()
{
$reservedOrderId = 'test_quote';
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId);
$query = $this->getQuery($maskedQuoteId);
self::expectExceptionMessageMatches('/The current user cannot perform operations on cart*/');
$this->graphQlMutation($query, [], '', $this->getHeaderMap());
}
/**
* _security
* @magentoApiDataFixture Magento/Customer/_files/three_customers.php
* @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php
* @magentoConfigFixture default_store carriers/flatrate/active 1
* @magentoConfigFixture default_store carriers/tablerate/active 1
* @magentoConfigFixture default_store carriers/freeshipping/active 1
* @magentoConfigFixture default_store payment/banktransfer/active 1
* @magentoConfigFixture default_store payment/cashondelivery/active 1
* @magentoConfigFixture default_store payment/checkmo/active 1
* @magentoConfigFixture default_store payment/purchaseorder/active 1
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php
* @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_checkmo_payment_method.php
*/
public function testPlaceOrderOfAnotherCustomerCart()
{
$reservedOrderId = 'test_quote';
$maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId);
$query = $this->getQuery($maskedQuoteId);
self::expectExceptionMessageMatches('/The current user cannot perform operations on cart*/');
$this->graphQlMutation($query, [], '', $this->getHeaderMap('customer3@search.example.com'));
}
/**
* @param string $maskedQuoteId
* @return string
*/
private function getQuery(string $maskedQuoteId): string
{
return <<<QUERY
mutation {
placeOrder(input: {cart_id: "{$maskedQuoteId}"}) {
order {
order_number
}
}
}
QUERY;
}
/**
* @param string $username
* @param string $password
* @return array
* @throws \Magento\Framework\Exception\AuthenticationException
*/
private function getHeaderMap(string $username = 'customer@example.com', string $password = 'password'): array
{
$customerToken = $this->customerTokenService->createCustomerAccessToken($username, $password);
$headerMap = ['Authorization' => 'Bearer ' . $customerToken];
return $headerMap;
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', true);
$orderCollection = $this->orderCollectionFactory->create();
foreach ($orderCollection as $order) {
$this->orderRepository->delete($order);
}
$this->registry->unregister('isSecureArea');
$this->registry->register('isSecureArea', false);
parent::tearDown();
}
}
| 30,458
|
https://github.com/andredaprato/hlash/blob/master/frontend/src/Page/Game.purs
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
hlash
|
andredaprato
|
PureScript
|
Code
| 806
| 1,928
|
module Page.Game where
import Prelude
import Capability.Resource.Game (class ManageGame, submitAnswer)
import Component.Timer as Timer
import Data.Array (head, tail, (!!))
import Data.Const (Const(..))
import Data.Foldable (elem)
import Data.Game (Game, GameState(..), Round(..), Stage(..), checkRoundChanged, gameIsOver, getCurrentAnswers, getPlayerQuestions)
import Data.Map as M
import Data.Maybe (Maybe(..))
import Data.Newtype (class Newtype)
import Data.Profile (Profile)
import Data.Question (Question, toString)
import Data.RoomCode (removeRoomCode)
import Data.Set as S
import Data.Symbol (SProxy(..))
import Data.Tuple (fst, snd)
import Effect.Aff (Milliseconds(..), delay)
import Effect.Aff.Class (class MonadAff)
import Effect.Class.Console (log, logShow)
import Formless as F
import Halogen as H
import Halogen.HTML as HH
import Halogen.HTML.Events as HE
import Halogen.HTML.Properties as HP
import Lib.Page.DisplayAnswers as DisplayAnswers
import Page.DisplayMembers (renderMembers)
import Page.GameOver (renderGameOver)
import Socket.Types (MsgIn(..))
import UI.UI (column, css)
import UI.Form (control, field)
import UI.Form as Form
import UI.Validation (FieldError(..), maxLength, toText)
type State =
{
loading :: Boolean
, currentUser :: Profile
, game :: Game
, playerQuestions :: Array Question
, currentQuestion :: Maybe Question
, timer :: Int
}
data Query a = Action MsgIn a
data Action = Initialize | SubmitAnswer Answer | UpdateDuration Int
type ChildSlots = ( timer :: H.Slot (Const Void) Int Unit)
component :: forall m .
MonadAff m =>
ManageGame m =>
H.Component HH.HTML Query {currentUser :: Profile, game :: Game} Void m
component = H.mkComponent { initialState : initialState
, render
, eval : H.mkEval $ H.defaultEval { initialize = Just Initialize
, handleAction = handleAction
, handleQuery = handleQuery}
}
where
initialState = \ {currentUser, game} -> { loading : false
, game : game
, currentUser: currentUser
, playerQuestions : []
, currentQuestion : Nothing
, timer : 60
}
handleAction = case _ of
Initialize -> do
st <- H.get
modifyNextQuestion $ getPlayerQuestions st.currentUser st.game
pure unit
SubmitAnswer ans -> do
st <- H.get
case st.currentQuestion of
Nothing -> pure unit
Just q -> do
submitAnswer q ans.answer st.game.gameCode
modifyNextQuestion st.playerQuestions
UpdateDuration time -> H.modify_ _ {timer = time}
handleQuery :: forall a. Query a -> H.HalogenM State Action _ _ m (Maybe a)
handleQuery (Action msg a) = case msg of
NewGameState newGame -> do
st <- H.get
when (checkRoundChanged st.game newGame) $ do
modifyNextQuestion $ getPlayerQuestions st.currentUser newGame
H.modify_ _ { timer = 60 }
when (gameIsOver newGame.gameState) $ H.liftEffect removeRoomCode
H.modify_ _ {game = newGame}
pure (Just a)
_ -> pure (Just a)
render st =
HH.div [ css "section has-background-light" ]
[
HH.div [ css "columns" ]
[
column "is-9"
[
displayGame st
]
, HH.div [ css "columns is-multiline is-centered" ]
[
column "is-full"
[
renderMembers $ map Just st.game.members
]
, column "has-text-centered"
[
HH.slot (SProxy :: _ "timer") unit Timer.component st.timer (Just <<< UpdateDuration)
]
]
]
]
displayGame st =
case st.game.gameState of
GameState GameOver _ ->
renderGameOver st.game.membersScore
GameState _ AwaitingQuestion ->
case st.currentQuestion of
Nothing -> HH.h1 [ css "title has-text-centered "]
[
HH.text "Waiting for other players answers"
]
Just q -> renderCurrentQuestion q
GameState _ (Display ix) ->
case st.game.currentStageQuestions !! ix of
Nothing -> HH.text "error"
Just currentQuestion ->
HH.slot (SProxy :: _ "answerDisplay") unit DisplayAnswers.component displayAnswersInput (Just <<< UpdateDuration)
where displayAnswersInput = { question : currentQuestion
, answers : getCurrentAnswers st.game currentQuestion
, currentUser : st.currentUser
, gameCode : st.game.gameCode}
modifyNextQuestion pQuestions = H.modify_ _ { playerQuestions = case tail pQuestions of
Nothing -> []
Just xs -> xs
, currentQuestion = head pQuestions
}
renderCurrentQuestion q = HH.slot F._formless unit formComponent q (Just <<< SubmitAnswer)
type Answer = { answer :: String }
newtype AnswerForm r f = AnswerForm ( r
( answer :: f FieldError String String
)
)
derive instance newtypeAnswerForm :: Newtype (AnswerForm r f) _
prx = F.mkSProxies (F.FormProxy :: _ AnswerForm)
data FormAction = Receive Question
formComponent :: forall m . MonadAff m => F.Component AnswerForm Query () Question Answer m
formComponent = F.component formInput $ F.defaultSpec { render = renderFormless
, handleEvent = F.raiseResult
, receive = Just <<< Receive
, handleAction = handleAction
}
where
formInput q = { initialInputs : Nothing
, question : q
, validators : AnswerForm { answer : maxLength 20
}
}
renderFormless st@{form} =
HH.div [ css "container"]
[
HH.form_
[
field [
HH.div [ css "columns is-centered"]
[ column "is-half"
[
HH.div [ css "notification is-info"]
[
HH.p [ css " is-size-4 has-text-centered "]
[
HH.text $ toString st.question
]
]
]
]
, control $ Form.input prx.answer form [ css "input is-info is-large"
, HP.placeholder "Enter something clever"]
]
, field $
[
control $ HH.button
[ css "button is-info is-centered is-medium",
HE.onClick \_ -> Just F.submit,
HP.type_ HP.ButtonSubmit]
[ HH.text "Submit"]
]
, HH.text case F.getError prx.answer form of
Nothing -> ""
Just a -> toText a
]
]
handleAction :: FormAction -> H.HalogenM _ _ _ _ m Unit
handleAction = case _ of
Receive question -> H.modify_ _ { question = question
}
| 30,603
|
https://github.com/jrineck/sawtooth-core/blob/master/validator/gossip/token_bucket.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
sawtooth-core
|
jrineck
|
Python
|
Code
| 377
| 734
|
# Copyright 2016 Intel 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.
# ------------------------------------------------------------------------------
"""
This module implements the TokenBucket class for managing the average
rate of data transmission between nodes.
"""
import logging
import time
logger = logging.getLogger(__name__)
class TokenBucket(object):
"""The TokenBucket class allows for traffic shaping via an average
transmission rate (the drip rate) and a limit to 'burstiness' (via
the bucket capacity).
Attributes:
DefaultDripRate (int): The default number of tokens which are
added to the bucket per second.
DefaultCapacity (int): The default maximum number of tokens
which can fit in the bucket.
DripRate (int): The configured number of tokens added to the
bucket per second.
Capacity (int): The configured maximum number of tokens which
can fit in the bucket.
LastDrip (float): The time in seconds since the epoch.
Tokens (int): The number of tokens in the bucket.
"""
DefaultDripRate = 32000
DefaultCapacity = DefaultDripRate * 2
def __init__(self, rate=None, capacity=None):
"""Constructor for the TokenBucket class.
Args:
rate (int): the drip rate for the newly created bucket in
tokens per second.
capacity (int): the maximum number of tokens the newly
created bucket can hold.
"""
self.DripRate = rate or self.DefaultDripRate
self.Capacity = capacity or self.DefaultCapacity
self.LastDrip = time.time()
self.Tokens = 0
def drip(self):
"""Adds tokens to the bucket based on the configured drip rate
per second, up to the capacity of the bucket.
"""
now = time.time()
self.Tokens = min(self.Capacity,
self.Tokens + int(self.DripRate *
(now - self.LastDrip)))
self.LastDrip = now
def consume(self, amount):
"""Consumes tokens from the bucket.
Args:
amount (int): the number of tokens to consume from the bucket.
Returns:
bool: If more tokens are requested than are available, returns
False, otherwise subtracts the tokens and returns True.
"""
self.drip()
if amount > self.Tokens:
return False
self.Tokens -= amount
return True
| 9,082
|
https://github.com/TalHadad/yolov3_tf2/blob/master/yolov3.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
yolov3_tf2
|
TalHadad
|
Python
|
Code
| 798
| 2,105
|
# yolov3.py
from typing import List
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import BatchNormalization, \
Conv2D, \
Input, \
ZeroPadding2D, \
LeakyReLU, \
UpSampling2D
# print(tf.__version__)
# 2.0
def parse_cfg_file(cfg_file: str):
'''Read configuration file and parse it into list of blocks'''
lines = read_uncommented_lines(cfg_file)
blocks = parse_cfg_list(lines)
return blocks
def read_uncommented_lines(cfg_file: str) -> List:
'''Read file lines to list and remove unnecessary characters like ‘\n’ and ‘#’.'''
with open(cfg_file, 'r') as file:
lines = [line.rstrip('\n') for line in file if line != '\n' and line[0] != '#']
return lines
def parse_cfg_list(cfg_list: List) -> List:
'''Read attributes list and store them as key, value pairs in list blocks'''
holder = {}
blocks = []
for cfg_item in cfg_list:
if cfg_item[0] == '[':
cfg_item = 'type=' + cfg_item[1:-1].rstrip()
if len(holder) != 0:
blocks.append(holder)
holder = {}
key, value = cfg_item.split("=")
holder[key.rstrip()] = value.lstrip()
blocks.append(holder)
return blocks
def yolov3_net(cfg_file: str, model_size: int, num_classes: int):
blocks = parse_cfg_file(cfg_file)
outputs = {}
output_filters = []
filters = []
out_pred = []
scale = 0
inputs = input_image = Input(shape=model_size)
# normalize input to range of 0-1
inputs = inputs / 255.0
# YOLOv3 has 5 layers types:
# 1. convolutional layer
# 2. upsample layer
# 3. route layer
# 4. shortcut layer
# 5. yolo layer
for i, block in enumerate(blocks[1:]):
# 1. convolutional layer
if (block['type'] == 'convolutional'):
activation = block['activation']
filters = int(block['filters'])
kernel_size = int(block['size'])
strides = int(block['stride'])
if strides > 1:
inputs = ZeroPadding2D(((1, 0), (1, 0)))(inputs)
inputs = Conv2D(filters,
kernel_size,
strides=strides,
padding='valid' if strides > 1 else 'same',
name=f'conv_{str(i)}',
use_bias=False if ('batch_normalize' in block) else True)(inputs)
# there are 2 convolutional layer types, with and without batch normalization layer.
# The convolutional layer with batch normalization layer uses a leaky ReLU activation layer,
# otherwise, it uses the linear activation.
if 'batch_normalize' in block:
inputs = BatchNormalization(name=f'bnorm_{str(i)}')(inputs)
inputs = LeakyReLU(alpha=0.1, name=f'leaky_{str(i)}')(inputs)
# 2. Upsample Layer
# Upsample by a factor of stride
# e.g.: [upsample] stride=2
elif (block['type'] == 'upsample'):
stride = int(block['stride'])
inputs = UpSampling2D(stride)(inputs)
# 3. Route Layer
# e.g.: [route] layers = -4
# Backward -4 number of layers, then output the feature map from that layer.
# e.g.: [route] layers = -1, 61
# Concatenate the feature map from previous layer (-1) and the feature map from layer 61
elif (block['type'] == 'route'):
block['layers'] = block['layers'].split(',')
start = int(block['layers'][0])
if len(block['layers']) > 1:
end = int(block['layers'][1]) - i
filters = output_filters[i + start] + output_filters[end] # Index negatif :end - index
inputs = tf.concat([outputs[i + start], outputs[i + end]], axis=-1)
else:
filters = output_filters[i + start]
inputs = outputs[i + start]
# 4. Shortcut Layer
# e.g.: [shortcut] from=-3 activation=linear
# Backward 3 layers (-3), then add the feature map with the feature map of the previous layer
elif block['type'] == 'shortcut':
from_ = int(block['from'])
inputs = outputs[i - 1] + outputs[i + from_]
# 5. Yolo Layer
# Preform detection
elif block['type'] == 'yolo':
mask = block['mask'].split(',')
mask = [int(x) for x in mask]
anchors = block['anchors'].split(',')
anchors = [int(a) for a in anchors]
anchors = [(anchors[i], anchors[i + 1]) for i in range(0, len(anchors), 2)]
anchors = [anchors[i] for i in mask]
n_anchors = len(anchors)
# reshape output to [None, B * grid size * grid size, 5 + C]
# B = number of anchors, C = number of classes
out_shape = inputs.get_shape().as_list()
inputs = tf.reshape(inputs, [-1, n_anchors * out_shape[1] * out_shape[2], 5 + num_classes])
# access all boxes attributes
box_centers = inputs[:, :, 0:2]
box_shapes = inputs[:, :, 2:4]
confidence = inputs[:, :, 4:5]
classes = inputs[:, :, 5:num_classes + 5]
# refine bounding boxes prediction to right posisions and shapes.
# sigmoid to convert to 0-1 range
box_centers = tf.sigmoid(box_centers)
confidence = tf.sigmoid(confidence)
classes = tf.sigmoid(classes)
# convert box_shapes
anchors = tf.tile(anchors, [out_shape[1] * out_shape[2], 1])
box_shapes = tf.exp(box_shapes) * tf.cast(anchors, dtype=tf.float32)
# convert the relative positions of the center boxes into the real positions
x = tf.range(out_shape[1], dtype=tf.float32)
y = tf.range(out_shape[2], dtype=tf.float32)
cx, cy = tf.meshgrid(x, y)
cx = tf.reshape(cx, (-1, 1))
cy = tf.reshape(cy, (-1, 1))
cxy = tf.concat([cx, cy], axis=-1)
cxy = tf.tile(cxy, [1, n_anchors])
cxy = tf.reshape(cxy, [1, -1, 2])
strides = (input_image.shape[1] // out_shape[1], input_image.shape[2] // out_shape[2])
box_centers = (box_centers + cxy) * strides
# concatenate them all together
prediction = tf.concat([box_centers, box_shapes, confidence, classes], axis=-1)
# Yolov3 does 3 predictions across the scale.
# Take prediction result of each scale and concatenate it with the others.
if scale:
out_pred = tf.concat([out_pred, prediction], axis=1)
else:
out_pred = prediction
scale = 1
# Since the route and shortcut layers need output feature maps from previous layers,
# we keep track of feature maps and output filters in every iteration.
outputs[i] = inputs
output_filters.append(filters)
model = Model(input_image, out_pred)
model.summary()
return model
| 38,415
|
https://github.com/justincasey/devextreme-reactive/blob/master/packages/dx-react-grid/src/plugins/search-state.tsx
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
devextreme-reactive
|
justincasey
|
TypeScript
|
Code
| 158
| 471
|
import * as React from 'react';
import {
Getter, Action, Plugin, createStateHelper, ActionFn, Getters,
} from '@devexpress/dx-react-core';
import { changeSearchValue, searchFilterExpression } from '@devexpress/dx-grid-core';
import { SearchStateProps, SearchStateState } from '../types';
class SearchStateBase extends React.PureComponent<SearchStateProps, SearchStateState> {
static defaultProps = {
defaultValue: '',
};
changeValue: ActionFn<string>;
constructor(props) {
super(props);
this.state = {
value: props.value || props.defaultValue,
};
const stateHelper = createStateHelper(this, {
value: () => {
const { onValueChange } = this.props;
return onValueChange;
},
});
this.changeValue = stateHelper.applyFieldReducer
.bind(stateHelper, 'value', changeSearchValue);
}
static getDerivedStateFromProps(nextProps, prevState) {
const {
value = prevState.value,
} = nextProps;
return {
value,
};
}
render() {
const { value } = this.state;
const filterExpressionComputed = (
{ filterExpression, columns }: Getters,
) => searchFilterExpression(value, columns, filterExpression);
return (
<Plugin
name="SearchState"
>
<Getter name="filterExpression" computed={filterExpressionComputed} />
<Getter name="searchValue" value={value} />
<Action name="changeSearchValue" action={this.changeValue} />
</Plugin>
);
}
}
/** A plugin that manages the search state. */
export const SearchState: React.ComponentType<SearchStateProps> = SearchStateBase;
| 33,007
|
https://github.com/cnheider/home-slide-android/blob/master/feature-onboarding/src/main/java/fr/outadoc/homeslide/app/onboarding/OnboardingNavHostFragment.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
home-slide-android
|
cnheider
|
Kotlin
|
Code
| 123
| 315
|
/*
* Copyright 2020 Baptiste Candellier
*
* 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 fr.outadoc.homeslide.app.onboarding
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import fr.outadoc.homeslide.app.onboarding.navigation.CustomTabsNavigator
@Suppress("unused")
class OnboardingNavHostFragment : NavHostFragment() {
override fun onCreateNavController(navController: NavController) {
super.onCreateNavController(navController)
context?.let {
navController.navigatorProvider.addNavigator(CustomTabsNavigator(it))
}
}
}
| 36,862
|
https://github.com/threefoldtech/threefold-forums/blob/master/db/migrate/20130612200846_create_post_upload_join_table.rb
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
threefold-forums
|
threefoldtech
|
Ruby
|
Code
| 36
| 137
|
# frozen_string_literal: true
class CreatePostUploadJoinTable < ActiveRecord::Migration[4.2]
def change
create_table :posts_uploads, force: true, id: false do |t|
t.integer :post_id
t.integer :upload_id
end
add_index :posts_uploads, :post_id
add_index :posts_uploads, :upload_id
add_index :posts_uploads, [:post_id, :upload_id], unique: true
end
end
| 16,756
|
https://github.com/adrianiftode/Moq.ILogger/blob/master/tests/Moq.ILogger.Tests/VerifyLogUnexpectedExceptionTests.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
Moq.ILogger
|
adrianiftode
|
C#
|
Code
| 81
| 263
|
using System;
using FluentAssertions;
using Xunit;
// ReSharper disable once CheckNamespace
namespace Moq.Tests
{
public class VerifyLogUnexpectedExceptionTests
{
[Fact]
public void Ctor_DoesNotThrow()
{
Action act = () => new VerifyLogUnexpectedException();
act.Should().NotThrow();
}
[Fact]
public void Ctor_WhenMessage_DoesNotThrow()
{
Action act = () => new VerifyLogUnexpectedException("Some message");
act.Should().NotThrow();
}
[Fact]
public void Ctor_WhenInnerException_DoesNotThrow()
{
Action act = () => new VerifyLogUnexpectedException("Some message", new Exception());
act.Should().NotThrow();
}
[Fact]
public void Exception_ShouldBeBinarySerializable()
{
var sut = new VerifyLogUnexpectedException("Some message", new Exception());
sut.Should().BeBinarySerializable();
}
}
}
| 4,924
|
https://github.com/jeremiergz/rirekisho/blob/master/src/components/sections/Information/PersonalDetails/index.tsx
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
rirekisho
|
jeremiergz
|
TypeScript
|
Code
| 91
| 298
|
import Label from '@/components/common/Label';
import PersonalDetail from '@/models/PersonalDetail';
import clsx from 'clsx';
import React from 'react';
function PersonalDetails({ items }: PersonalDetailsProps): JSX.Element {
return (
<div
className={clsx(
'flex flex-1 flex-col justify-center order-2 md:order-1',
'h-full min-w-[224px] mb-2 mt-4 text-center md:text-left',
)}
>
{items
.sort((a, b) => a.sortOrder - b.sortOrder)
.map((item, index) => (
<div className={clsx('flex flex-col', index !== items.length - 1 && 'mb-6')} key={item.label}>
<Label title={item.label} />
<span className="font-extrabold leading-4 text-secondary dark:text-secondary-dark text-xl uppercase">
{item.value}
</span>
</div>
))}
</div>
);
}
export type PersonalDetailsProps = {
items: PersonalDetail[];
};
export default PersonalDetails;
| 6,675
|
https://github.com/divanvisagie/scala-EEPA/blob/master/example/fibonacci/src/main/scala/com/fibonacci/FibonacciService.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,016
|
scala-EEPA
|
divanvisagie
|
Scala
|
Code
| 29
| 115
|
package com.fibonacci
import com.eepa.consumer.Listener
object FibonacciService {
def main(args: Array[String]): Unit = {
val recursiveMath = RecursiveMath()
Listener().listen[InDomainMessage]("fibonacci", inMessage => {
val fibAnswer = recursiveMath.fibonacci(inMessage.number)
OutDomainMessage(fibAnswer)
})
}
}
| 6,577
|
https://github.com/CorentG/Pokecube-Issues-and-Wiki/blob/master/src/main/java/pokecube/mobs/abilities/r/Rattled.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Pokecube-Issues-and-Wiki
|
CorentG
|
Java
|
Code
| 61
| 277
|
package pokecube.mobs.abilities.r;
import pokecube.core.database.abilities.Ability;
import pokecube.core.interfaces.IMoveConstants;
import pokecube.core.interfaces.IPokemob;
import pokecube.core.interfaces.pokemob.moves.MovePacket;
import pokecube.core.moves.MovesUtils;
import pokecube.core.utils.PokeType;
public class Rattled extends Ability
{
private boolean isCorrectType(PokeType type)
{
return type == PokeType.getType("dark") || type == PokeType.getType("bug") || type == PokeType.getType("ghost");
}
@Override
public void onMoveUse(IPokemob mob, MovePacket move)
{
if (mob == move.attacked && !move.pre && this.isCorrectType(move.attackType)) MovesUtils.handleStats2(mob, mob
.getEntity(), IMoveConstants.VIT, IMoveConstants.RAISE);
}
}
| 34,621
|
https://github.com/JamesCalleja/python/blob/master/fucktions/if_statements.py
|
Github Open Source
|
Open Source
|
MIT
| null |
python
|
JamesCalleja
|
Python
|
Code
| 65
| 183
|
is_male = False
is_tall = True
if is_male:
print("yep")
else:
print("nope")
if is_male and is_tall: #and or
print("both are true")
elif is_tall and not(is_male):
print("you are a female")
else:
print("this is the else")
def max_mum (num1, num2,num3):
if num1 >= num2 and num1 >= mun3: # == != <=
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print(max_mum(24,645453,325))
| 19,918
|
https://github.com/pchanumolu/dotfiles/blob/master/fish/functions/gi.fish
|
Github Open Source
|
Open Source
|
WTFPL
| 2,018
|
dotfiles
|
pchanumolu
|
Fish
|
Code
| 6
| 14
|
function gi
grep -i $argv
end
| 15,797
|
https://github.com/lxiaoli/calc/blob/master/Clac/src/com/lxl/clac/Controller.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
calc
|
lxiaoli
|
Java
|
Code
| 147
| 612
|
package com.lxl.clac;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JLabel;
/**
* 按钮点击的监听器事件
* @author lxl
*
*/
public class Controller implements ActionListener{
/**
* 计算器的核心部分
*/
private CalcModel calcModel;
private CalcFrame frame;
private JLabel labelResult;
private StringBuilder input = new StringBuilder();
// private CalcCallback callback;
//
// public void setCallback(CalcCallback callback) {
// this.callback = callback;
// }
/**
* 控制器的构造方法
*/
public Controller() {
// super();
// this.calcModel = calcModel;
}
/**
* 设置控制器依赖的模型
* @param model
*/
public void setModel(CalcModel model) {
this.calcModel=model;
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
// System.out.println(command);
switch(command){
case "←":
String text;
if(!input.toString().equals("0.0")){
text = input.toString();
text = text.substring(0, text.length()-1);
input.setLength(0);
input.append(text);
calcModel.setInput(input.toString());
}
break;
case "C":
calcModel.clear();
input.setLength(0);
break;
case "=":
calcModel.setInput(input.toString());
text = input.toString();
calculate c = new calculate(text);
input.setLength(0);
input.append(c.getNumStack());
calcModel.setInput(input.toString());
break;
default:
input.append(command);
calcModel.setInput(input.toString());
}
}
}
| 32,054
|
https://github.com/mojiito/mojito-backup/blob/master/dist/core/zone/zone.d.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
mojito-backup
|
mojiito
|
TypeScript
|
Code
| 454
| 980
|
import { EventEmitter } from '../async/events';
export declare class ZoneWrapper {
private _innerZone;
private _outerZone;
private _onEnter;
private _onLeave;
private _onError;
private _setMicrotask;
private _setMacrotask;
constructor({onEnter, onLeave, setMicrotask, setMacrotask, onError}: {
onEnter: () => void;
onLeave: () => void;
setMicrotask: (hasMicrotasks: boolean) => void;
setMacrotask: (hasMacrotasks: boolean) => void;
onError: (error: Error) => void;
});
runInner(fn: () => any): any;
runInnerGuarded(fn: () => any): any;
runOuter(fn: () => any): any;
}
export declare class ZoneService {
private _zoneWrapper;
private _nestedLevel;
private _hasPendingMicrotasks;
private _hasPendingMacrotasks;
private _isStable;
private _onUnstable;
private _onMicrotaskEmpty;
private _onStable;
private _onErrorEvents;
constructor();
private _checkStable();
/**
* Notifies when code enters Mojito Zone. This gets fired first on VM Turn.
*/
onUnstable: EventEmitter<any>;
/**
* Notifies when there is no more microtasks enqueue in the current VM Turn.
* This is a hint for Mojito to do change detection, which may enqueue more microtasks.
* For this reason this event can fire multiple times per VM Turn.
*/
onMicrotaskEmpty: EventEmitter<any>;
/**
* Notifies when the last `onMicrotaskEmpty` has run and there are no more microtasks, which
* implies we are about to relinquish VM turn.
* This event gets called just once.
*/
onStable: EventEmitter<any>;
/**
* Notify that an error has been delivered.
*/
onError: EventEmitter<any>;
/**
* Whether there are no outstanding microtasks or microtasks.
*/
isStable: boolean;
/**
* Whether there are any outstanding microtasks.
*/
hasPendingMicrotasks: boolean;
/**
* Whether there are any outstanding microtasks.
*/
hasPendingMacrotasks: boolean;
/**
* Executes the `fn` function synchronously within the Mojito zone and returns value returned by
* the function.
*
* Running functions via `run` allows you to reenter Mojito zone from a task that was executed
* outside of the Mojito zone (typically started via {@link #runOutsideMojito}).
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* within the Mojito zone.
*
* If a synchronous error happens it will be rethrown and not reported via `onError`.
*/
run(fn: () => any): any;
/**
* Same as #run, except that synchronous errors are caught and forwarded
* via `onError` and not rethrown.
*/
runGuarded(fn: () => any): any;
/**
* Executes the `fn` function synchronously in Mojito's parent zone and returns value returned by
* the function.
*
* Running functions via `runOutsideMojito` allows you to escape Mojito's zone and do work that
* doesn't trigger Mojito change-detection or is subject to Mojito's error handling.
*
* Any future tasks or microtasks scheduled from within this function will continue executing from
* outside of the Mojito zone.
*
* Use {@link #run} to reenter the Mojito zone and do work that updates the application model.
*/
runOutsideMojito(fn: () => any): any;
}
| 29,200
|
https://github.com/9988123/SlinkyTyped/blob/master/d/devexpress-web/src/main/scala/typingsSlinky/devexpressWeb/global/ASPxClientPivotCustomization.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
SlinkyTyped
|
9988123
|
Scala
|
Code
| 25
| 121
|
package typingsSlinky.devexpressWeb.global
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation._
/**
* A client-side equivalent of the ASPxPivotCustomizationControl control.
*/
@JSGlobal("ASPxClientPivotCustomization")
@js.native
class ASPxClientPivotCustomization ()
extends typingsSlinky.devexpressWeb.ASPxClientPivotCustomization
| 27,449
|
https://github.com/darki73/Mekanism/blob/master/src/main/java/mekanism/common/tile/TileEntityPressurizedReactionChamber.java
|
Github Open Source
|
Open Source
|
MIT
| null |
Mekanism
|
darki73
|
Java
|
Code
| 573
| 2,927
|
package mekanism.common.tile;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import mekanism.api.RelativeSide;
import mekanism.api.Upgrade;
import mekanism.api.annotations.NonNull;
import mekanism.api.chemical.gas.BasicGasTank;
import mekanism.api.chemical.gas.Gas;
import mekanism.api.chemical.gas.GasStack;
import mekanism.api.chemical.gas.IGasTank;
import mekanism.api.recipes.PressurizedReactionRecipe;
import mekanism.api.recipes.cache.CachedRecipe;
import mekanism.api.recipes.cache.PressurizedReactionCachedRecipe;
import mekanism.api.recipes.inputs.IInputHandler;
import mekanism.api.recipes.inputs.InputHelper;
import mekanism.api.recipes.outputs.IOutputHandler;
import mekanism.api.recipes.outputs.OutputHelper;
import mekanism.api.transmitters.TransmissionType;
import mekanism.common.capabilities.energy.PRCEnergyContainer;
import mekanism.common.capabilities.fluid.BasicFluidTank;
import mekanism.common.capabilities.holder.chemical.ChemicalTankHelper;
import mekanism.common.capabilities.holder.chemical.IChemicalTankHolder;
import mekanism.common.capabilities.holder.energy.EnergyContainerHelper;
import mekanism.common.capabilities.holder.energy.IEnergyContainerHolder;
import mekanism.common.capabilities.holder.fluid.FluidTankHelper;
import mekanism.common.capabilities.holder.fluid.IFluidTankHolder;
import mekanism.common.capabilities.holder.slot.IInventorySlotHolder;
import mekanism.common.capabilities.holder.slot.InventorySlotHelper;
import mekanism.common.inventory.slot.EnergyInventorySlot;
import mekanism.common.inventory.slot.InputInventorySlot;
import mekanism.common.inventory.slot.OutputInventorySlot;
import mekanism.common.recipe.MekanismRecipeType;
import mekanism.common.registries.MekanismBlocks;
import mekanism.common.tile.component.TileComponentConfig;
import mekanism.common.tile.component.TileComponentEjector;
import mekanism.common.tile.component.config.ConfigInfo;
import mekanism.common.tile.component.config.DataType;
import mekanism.common.tile.component.config.slot.EnergySlotInfo;
import mekanism.common.tile.component.config.slot.FluidSlotInfo;
import mekanism.common.tile.component.config.slot.GasSlotInfo;
import mekanism.common.tile.component.config.slot.InventorySlotInfo;
import mekanism.common.tile.prefab.TileEntityBasicMachine;
import mekanism.common.util.MekanismUtils;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import org.apache.commons.lang3.tuple.Pair;
public class TileEntityPressurizedReactionChamber extends TileEntityBasicMachine<PressurizedReactionRecipe> {
private static final int BASE_DURATION = 100;
private static final long MAX_GAS = 10_000;
public BasicFluidTank inputFluidTank;
public BasicGasTank inputGasTank;
public BasicGasTank outputGasTank;
private final IOutputHandler<@NonNull Pair<@NonNull ItemStack, @NonNull GasStack>> outputHandler;
private final IInputHandler<@NonNull ItemStack> itemInputHandler;
private final IInputHandler<@NonNull FluidStack> fluidInputHandler;
private final IInputHandler<@NonNull GasStack> gasInputHandler;
private PRCEnergyContainer energyContainer;
private InputInventorySlot inputSlot;
private OutputInventorySlot outputSlot;
private EnergyInventorySlot energySlot;
public TileEntityPressurizedReactionChamber() {
super(MekanismBlocks.PRESSURIZED_REACTION_CHAMBER, BASE_DURATION);
configComponent = new TileComponentConfig(this, TransmissionType.ITEM, TransmissionType.ENERGY, TransmissionType.FLUID, TransmissionType.GAS);
ConfigInfo itemConfig = configComponent.getConfig(TransmissionType.ITEM);
if (itemConfig != null) {
itemConfig.addSlotInfo(DataType.INPUT, new InventorySlotInfo(true, false, inputSlot));
itemConfig.addSlotInfo(DataType.OUTPUT, new InventorySlotInfo(false, true, outputSlot));
itemConfig.addSlotInfo(DataType.ENERGY, new InventorySlotInfo(true, true, energySlot));
//Set default config directions
itemConfig.setDataType(RelativeSide.TOP, DataType.INPUT);
itemConfig.setDataType(RelativeSide.RIGHT, DataType.OUTPUT);
itemConfig.setDataType(RelativeSide.BOTTOM, DataType.ENERGY);
}
ConfigInfo fluidConfig = configComponent.getConfig(TransmissionType.FLUID);
if (fluidConfig != null) {
fluidConfig.addSlotInfo(DataType.INPUT, new FluidSlotInfo(true, false, inputFluidTank));
//Set default config directions
fluidConfig.setDataType(RelativeSide.BACK, DataType.INPUT);
fluidConfig.setCanEject(false);
}
ConfigInfo gasConfig = configComponent.getConfig(TransmissionType.GAS);
if (gasConfig != null) {
gasConfig.addSlotInfo(DataType.INPUT, new GasSlotInfo(true, false, inputGasTank));
gasConfig.addSlotInfo(DataType.OUTPUT, new GasSlotInfo(false, true, outputGasTank));
//Set default config directions
gasConfig.setDataType(RelativeSide.LEFT, DataType.INPUT);
gasConfig.setDataType(RelativeSide.RIGHT, DataType.OUTPUT);
}
ConfigInfo energyConfig = configComponent.getConfig(TransmissionType.ENERGY);
if (energyConfig != null) {
energyConfig.addSlotInfo(DataType.INPUT, new EnergySlotInfo(true, false, energyContainer));
energyConfig.fill(DataType.INPUT);
energyConfig.setCanEject(false);
}
ejectorComponent = new TileComponentEjector(this);
ejectorComponent.setOutputData(TransmissionType.ITEM, itemConfig);
ejectorComponent.setOutputData(TransmissionType.GAS, gasConfig);
itemInputHandler = InputHelper.getInputHandler(inputSlot);
fluidInputHandler = InputHelper.getInputHandler(inputFluidTank);
gasInputHandler = InputHelper.getInputHandler(inputGasTank);
outputHandler = OutputHelper.getOutputHandler(outputGasTank, outputSlot);
}
@Nonnull
@Override
protected IChemicalTankHolder<Gas, GasStack, IGasTank> getInitialGasTanks() {
ChemicalTankHelper<Gas, GasStack, IGasTank> builder = ChemicalTankHelper.forSideGasWithConfig(this::getDirection, this::getConfig);
builder.addTank(inputGasTank = BasicGasTank.input(MAX_GAS, gas -> containsRecipe(recipe -> recipe.getInputGas().testType(gas)), this));
builder.addTank(outputGasTank = BasicGasTank.output(MAX_GAS, this));
return builder.build();
}
@Nonnull
@Override
protected IFluidTankHolder getInitialFluidTanks() {
FluidTankHelper builder = FluidTankHelper.forSideWithConfig(this::getDirection, this::getConfig);
builder.addTank(inputFluidTank = BasicFluidTank.input(10_000, fluid -> containsRecipe(recipe -> recipe.getInputFluid().testType(fluid)), this));
return builder.build();
}
@Nonnull
@Override
protected IEnergyContainerHolder getInitialEnergyContainers() {
EnergyContainerHelper builder = EnergyContainerHelper.forSideWithConfig(this::getDirection, this::getConfig);
builder.addContainer(energyContainer = PRCEnergyContainer.input(this));
return builder.build();
}
@Nonnull
@Override
protected IInventorySlotHolder getInitialInventory() {
InventorySlotHelper builder = InventorySlotHelper.forSideWithConfig(this::getDirection, this::getConfig);
builder.addSlot(inputSlot = InputInventorySlot.at(item -> containsRecipe(recipe -> recipe.getInputSolid().testType(item)), this, 54, 35));
builder.addSlot(outputSlot = OutputInventorySlot.at(this, 116, 35));
builder.addSlot(energySlot = EnergyInventorySlot.fillOrConvert(energyContainer, this::getWorld, this, 141, 19));
return builder.build();
}
@Override
protected void onUpdateServer() {
super.onUpdateServer();
energySlot.fillContainerOrConvert();
CachedRecipe<PressurizedReactionRecipe> oldCache = this.cachedRecipe;
cachedRecipe = getUpdatedCache(0);
if (oldCache != cachedRecipe) {
//If it is not the same literal object
int recipeDuration = cachedRecipe == null ? BASE_DURATION : cachedRecipe.getRecipe().getDuration();
boolean update = BASE_TICKS_REQUIRED != recipeDuration;
BASE_TICKS_REQUIRED = recipeDuration;
if (update) {
recalculateUpgrades(Upgrade.SPEED);
}
//Ensure we take our recipe's energy per tick into account
energyContainer.updateEnergyPerTick();
}
if (cachedRecipe != null) {
cachedRecipe.process();
}
}
@Nonnull
@Override
public MekanismRecipeType<PressurizedReactionRecipe> getRecipeType() {
return MekanismRecipeType.REACTION;
}
@Nullable
@Override
public CachedRecipe<PressurizedReactionRecipe> getCachedRecipe(int cacheIndex) {
return cachedRecipe;
}
@Nullable
@Override
public PressurizedReactionRecipe getRecipe(int cacheIndex) {
ItemStack stack = itemInputHandler.getInput();
if (stack.isEmpty()) {
return null;
}
FluidStack fluid = fluidInputHandler.getInput();
if (fluid.isEmpty()) {
return null;
}
GasStack gas = gasInputHandler.getInput();
if (gas.isEmpty()) {
return null;
}
return findFirstRecipe(recipe -> recipe.test(stack, fluid, gas));
}
@Nullable
@Override
public CachedRecipe<PressurizedReactionRecipe> createNewCachedRecipe(@Nonnull PressurizedReactionRecipe recipe, int cacheIndex) {
return new PressurizedReactionCachedRecipe(recipe, itemInputHandler, fluidInputHandler, gasInputHandler, outputHandler)
.setCanHolderFunction(() -> MekanismUtils.canFunction(this))
.setActive(this::setActive)
.setEnergyRequirements(energyContainer::getEnergyPerTick, energyContainer)
.setRequiredTicks(() -> ticksRequired)
.setOnFinish(() -> markDirty(false))
.setOperatingTicksChanged(this::setOperatingTicks);
}
public PRCEnergyContainer getEnergyContainer() {
return energyContainer;
}
}
| 32,306
|
https://github.com/Azadeh82/game_world/blob/master/resources/views/admin/promotion.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
game_world
|
Azadeh82
|
PHP
|
Code
| 148
| 634
|
@extends('layouts.app')
@section('title')
Admin
@endsection
@section('content')
<div class="container">
<div class="row">
<div class="col-12 bg-white w-50 p-5 mx-auto">
<h3 class="text-center" style="color:#427eff;">Modifier l'article :<br>{{ $promotion->nom }}</h3>
<form action="{{ route('promotion.update', $promotion) }}" method="post">
@csrf
@method('PUT')
<div class="mb-3">
<label for="nom" class="form-label">Nom : </label>
<input type="text" class="form-control" id="nom" name="nom" value="{{ $promotion->nom }}">
</div>
<div class="mb-3">
<label for="reduction" class="form-label">Réduction : </label>
<input type="text" class="form-control" id="reduction" name="reduction"
value="{{ $promotion->reduction }}">
</div>
<div class="mb-3">
<label for="debut" class="form-label">Date du début : </label>
<input type="date" class="form-control" id="debut" name="date_debut"
value="{{ $promotion->date_debut }}">
</div>
<div class="mb-3">
<label for="fin" class="form-label">Date de la fin : </label>
<input type="date" class="form-control" id="fin" name="date_fin"
value="{{ $promotion->date_fin }}">
</div>
@foreach ($articles as $article)
<div class="custom-control custom-checkbox">
<input type="checkbox"
class="custom-control-input" name="article{{ $article->id }}"
value="{{ $article->id }}" id="article{{ $article->id }}"
@foreach ($promotion->articles as $article_en_promotion)
@if ($article->id == $article_en_promotion->id)
checked
@break
@endIf
@endforeach>
<label class="custom-control-label" for="article{{ $article->id }}">{{ $article->nom }}</label>
</div>
@endforeach
<input type="submit" class="button-25" value="Modifier">
</form>
</div>
</div>
</div>
@endsection
| 18,715
|
https://github.com/adk9/openmpmpibench-C/blob/master/pt_to_pt_pingping.c
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
openmpmpibench-C
|
adk9
|
C
|
Code
| 1,527
| 4,213
|
/*****************************************************************************
* *
* Mixed-mode OpenMP/MPI MicroBenchmark Suite - Version 1.0 *
* *
* produced by *
* *
* Mark Bull, Jim Enright and Fiona Reid *
* *
* at *
* *
* Edinburgh Parallel Computing Centre *
* *
* email: markb@epcc.ed.ac.uk, fiona@epcc.ed.ac.uk *
* *
* *
* Copyright 2012, The University of Edinburgh *
* *
* *
* 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. *
* *
****************************************************************************/
/*-----------------------------------------------------------*/
/* Contains the point-to-point pingping mixed mode */
/* OpenMP/MPI benchmarks. */
/* This includes: -masteronly pingping */
/* -funnelled pingping */
/* -multiple pingping */
/*-----------------------------------------------------------*/
#include "pt_to_pt_pingping.h"
/*-----------------------------------------------------------*/
/* pingPing */
/* */
/* Driver subroutine for the pingping benchmark. */
/*-----------------------------------------------------------*/
int pingPing(int benchmarkType){
int dataSizeIter;
int sameNode;
pingRankA = PPRanks[0];
pingRankB = PPRanks[1];
/* Check if pingRankA and pingRankB are on the same node */
sameNode = compareProcNames(pingRankA, pingRankB);
if (myMPIRank == 0){
/* print message saying if benchmark is inter or intra node */
printNodeReport(sameNode,pingRankA,pingRankB);
/* then print report column headings. */
printBenchHeader();
}
/* initialise repsToDo to defaultReps at start of benchmark */
repsToDo = defaultReps;
/* Loop over data sizes */
dataSizeIter = minDataSize; /* initialise dataSizeIter to minDataSize */
while (dataSizeIter <= maxDataSize){
/* set sizeofBuffer */
sizeofBuffer = dataSizeIter * numThreads;
/* Allocate space for main data arrays */
allocatePingpingData(sizeofBuffer);
/* warm-up for benchmarkType */
if (benchmarkType == MASTERONLY){
/* Masteronly warmp sweep */
masteronlyPingping(warmUpIters, dataSizeIter);
}
else if (benchmarkType == FUNNELLED){
/* perform funnelled warm-up sweep */
funnelledPingping(warmUpIters, dataSizeIter);
}
else if (benchmarkType == MULTIPLE){
multiplePingping(warmUpIters, dataSizeIter);
}
/* perform verification test for the pingping */
testPingping(sizeofBuffer, dataSizeIter);
/* Initialise benchmark */
benchComplete = FALSE;
/* keep executing benchmark until target time is reached */
while (benchComplete != TRUE){
/* Start the timer...MPI_Barrier to synchronise */
MPI_Barrier(comm);
startTime = MPI_Wtime();
if (benchmarkType == MASTERONLY){
/* execute for repsToDo repetitions */
masteronlyPingping(repsToDo, dataSizeIter);
}
else if (benchmarkType == FUNNELLED){
funnelledPingping(repsToDo, dataSizeIter);
}
else if (benchmarkType == MULTIPLE){
multiplePingping(repsToDo, dataSizeIter);
}
/* Stop the timer...MPI_Barrier to synchronise processes */
MPI_Barrier(comm);
finishTime = MPI_Wtime();
totalTime = finishTime - startTime;
/* Call repTimeCheck function to test if target time is reached */
if (myMPIRank==0){
benchComplete = repTimeCheck(totalTime, repsToDo);
}
/* Ensure all procs have the same value of benchComplete */
/* and repsToDo */
MPI_Bcast(&benchComplete, 1, MPI_INT, 0, comm);
MPI_Bcast(&repsToDo, 1, MPI_INT, 0, comm);
}
/* Master process sets benchmark results */
if (myMPIRank == 0){
setReportParams(dataSizeIter, repsToDo, totalTime);
printReport();
}
/* Free the allocated space for the main data arrays */
freePingpingData();
/* Update dataSize before the next iteration */
dataSizeIter = dataSizeIter * 2; /* double data size */
}
return 0;
}
/*-----------------------------------------------------------*/
/* masteronlyPingping */
/* */
/* Two processes send a message to each other using the */
/* MPI_Isend, MPI_Recv and MPI_Wait routines. */
/* Inter-process communication takes place outside of the */
/* parallel region. */
/*-----------------------------------------------------------*/
int masteronlyPingping(int totalReps, int dataSize){
int repIter, i;
int destRank;
/* set destRank to ID of other process */
if (myMPIRank == pingRankA){
destRank = pingRankB;
}
else if (myMPIRank == pingRankB){
destRank = pingRankA;
}
for (repIter = 0; repIter < totalReps; repIter++){
if (myMPIRank == pingRankA || myMPIRank == pingRankB){
/* Each thread writes its globalID to pingSendBuf
* using a PARALLEL DO directive.
*/
#pragma omp parallel for default(none) \
private(i) \
shared(pingSendBuf,dataSize,sizeofBuffer,globalIDarray) \
schedule(static,dataSize)
for (i=0; i<sizeofBuffer; i++){
pingSendBuf[i] = globalIDarray[myThreadID];
}
/* Process calls non-bloacking send to start transfer of pingSendBuf
* to other process.
*/
MPI_Isend(pingSendBuf, sizeofBuffer, MPI_INT, destRank, \
TAG, comm, &requestID);
/* Process then waits for message from other process. */
MPI_Recv(pingRecvBuf, sizeofBuffer, MPI_INT, destRank, \
TAG, comm, &status);
/* Finish the Send operation with an MPI_Wait */
MPI_Wait(&requestID, &status);
/* Each thread under the MPI process now reads its part of the
* received buffer.
*/
#pragma omp parallel for default(none) \
private(i) \
shared(finalRecvBuf,dataSize,sizeofBuffer,pingRecvBuf) \
schedule(static,dataSize)
for (i=0; i<sizeofBuffer; i++){
finalRecvBuf[i] = pingRecvBuf[i];
}
}
}
return 0;
}
/*-----------------------------------------------------------*/
/* funnelledPingPing */
/* */
/* Two processes send a message to each other using the */
/* MPI_Isend, MPI_Recv and MPI_Wait routines. */
/* Inter-process communication takes place inside the */
/* OpenMP parallel region. */
/*-----------------------------------------------------------*/
int funnelledPingping(int totalReps, int dataSize){
int repIter, i;
int destRank;
/* set destRank to ID of other process */
if (myMPIRank == pingRankA){
destRank = pingRankB;
}
else if (myMPIRank == pingRankB){
destRank = pingRankA;
}
/* Open the parallel region */
#pragma omp parallel \
private(i, repIter) \
shared(dataSize,sizeofBuffer,pingSendBuf,globalIDarray) \
shared(pingRecvBuf,finalRecvBuf,status,requestID) \
shared(destRank,comm,myMPIRank,pingRankA,pingRankB,totalReps)
for (repIter = 0; repIter < totalReps; repIter++){
if (myMPIRank == pingRankA || myMPIRank == pingRankB){
/* Each thread writes its globalID to its part of
* pingSendBuf.
*/
#pragma omp for schedule(static,dataSize)
for (i=0; i<sizeofBuffer; i++){
pingSendBuf[i] = globalIDarray[myThreadID];
}
/* Implicit barrier here takes care of necessary synchronisation */
#pragma omp master
{
/* Master thread starts send of buffer */
MPI_Isend(pingSendBuf, sizeofBuffer, MPI_INT, destRank, \
TAG, comm, &requestID);
/* then waits for message from other process */
MPI_Recv(pingRecvBuf, sizeofBuffer, MPI_INT, destRank, \
TAG, comm, &status);
/* Master thread then completes send using an MPI_Wait */
MPI_Wait(&requestID, &status);
}
/* Barrier needed to ensure master thread has completed transfer */
#pragma omp barrier
/* Each thread reads its part of the received buffer */
#pragma omp for schedule(static,dataSize)
for (i=0; i<sizeofBuffer; i++){
finalRecvBuf[i] = pingRecvBuf[i];
}
}
}
return 0;
}
/*-----------------------------------------------------------*/
/* multiplePingping */
/* */
/* With this algorithm multiple threads take place in the */
/* communication and computation. */
/* Each thread sends its portion of the pingSendBuf to the */
/* other process using MPI_Isend/ MPI_Recv/ MPI_Wait */
/* routines. */
/*-----------------------------------------------------------*/
int multiplePingping(int totalReps, int dataSize){
int repIter, i;
int destRank;
int lBound;
/* set destRank to ID of other process */
if (myMPIRank == pingRankA){
destRank = pingRankB;
}
else if (myMPIRank == pingRankB){
destRank = pingRankA;
}
/* Open parallel region */
#pragma omp parallel \
private(i,lBound,requestID,status,repIter) \
shared(pingSendBuf,pingRecvBuf,finalRecvBuf,sizeofBuffer) \
shared(destRank,myMPIRank,pingRankA,pingRankB,totalReps) \
shared(dataSize,globalIDarray,comm)
{
for (repIter = 0; repIter < totalReps; repIter++){
if (myMPIRank == pingRankA || myMPIRank == pingRankB){
/* Calculate the lower bound of each threads
* portion of the data arrays.
*/
lBound = (myThreadID * dataSize);
/* Each thread writes to its part of pingSendBuf */
#pragma omp for nowait schedule(static,dataSize)
for (i=0; i<sizeofBuffer; i++){
pingSendBuf[i] = globalIDarray[myThreadID];
}
/* Each thread starts send of dataSize items of
* pingSendBuf to process with rank = destRank.
*/
MPI_Isend(&pingSendBuf[lBound], dataSize, MPI_INT, destRank, \
myThreadID, comm, &requestID);
/* Thread then waits for message from destRank with
* tag equal to it thread id.
*/
MPI_Recv(&pingRecvBuf[lBound], dataSize, MPI_INT, destRank, \
myThreadID, comm, &status);
/* Thread completes send using MPI_Wait */
MPI_Wait(&requestID, &status);
/* Each thread reads its part of received buffer. */
#pragma omp for nowait schedule(static,dataSize)
for (i=0; i<sizeofBuffer; i++){
finalRecvBuf[i] = pingRecvBuf[i];
}
}
}
}
return 0;
}
/*-----------------------------------------------------------*/
/* allocatePingpingData */
/* */
/* Allocates space for the main data arrays. */
/* Size of each array is specified by subroutine argument. */
/*-----------------------------------------------------------*/
int allocatePingpingData(int sizeofBuffer){
pingSendBuf = (int *)malloc(sizeofBuffer * sizeof(int));
pingRecvBuf = (int *)malloc(sizeofBuffer * sizeof(int));
finalRecvBuf = (int *)malloc(sizeofBuffer * sizeof(int));
return 0;
}
/*-----------------------------------------------------------*/
/* freePingpingData */
/* */
/* Deallocates the storage space for the main data arrays. */
/*-----------------------------------------------------------*/
int freePingpingData(){
free(pingSendBuf);
free(pingRecvBuf);
free(finalRecvBuf);
return 0;
}
/*-----------------------------------------------------------*/
/* testPingping */
/* */
/* Verifies that the PingPing benchmark worked correctly. */
/*-----------------------------------------------------------*/
int testPingping(int sizeofBuffer,int dataSize){
int otherPingRank, i, testFlag, reduceFlag;
int *testBuf;
/* initialise testFlag to true (test passed) */
testFlag = TRUE;
/* Testing only needs to be done by pingRankA & pingRankB */
if (myMPIRank == pingRankA || myMPIRank == pingRankB){
/* allocate space for testBuf */
testBuf = (int *)malloc(sizeofBuffer * sizeof(int));
/* set the ID of other pingRank */
if (myMPIRank == pingRankA){
otherPingRank = pingRankB;
}
else if (myMPIRank == pingRankB){
otherPingRank = pingRankA;
}
/* construct testBuf array with correct values.
* These are the values that should be in finalRecvBuf.
*/
#pragma omp parallel for default(none) \
private(i) \
shared(otherPingRank,numThreads,testBuf,dataSize,sizeofBuffer) \
schedule(static,dataSize)
for (i=0; i<sizeofBuffer; i++){
/* calculate globalID of thread expected in finalRecvBuf
* This is done by using otherPingRank
*/
testBuf[i] = (otherPingRank * numThreads) + myThreadID;
}
/* compare each element of testBuf and finalRecvBuf */
for (i=0; i<sizeofBuffer; i++){
if (testBuf[i] != finalRecvBuf[i]){
testFlag = FALSE;
}
}
/* free space for testBuf */
free(testBuf);
}
MPI_Reduce(&testFlag, &reduceFlag, 1, MPI_INT, MPI_LAND, 0, comm);
/* Master process sets the testOutcome using testFlag. */
if (myMPIRank == 0){
setTestOutcome(reduceFlag);
}
return 0;
}
| 46,022
|
https://github.com/MiggieNRG/microsoft-authentication-library-for-dotnet/blob/master/src/client/Microsoft.Identity.Client/Utils/ITimeService.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
microsoft-authentication-library-for-dotnet
|
MiggieNRG
|
C#
|
Code
| 27
| 63
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
namespace Microsoft.Identity.Client.Utils
{
internal interface ITimeService
{
DateTime GetUtcNow();
}
}
| 38,322
|
https://github.com/daviwil/gambit/blob/master/tests/unit-tests/03-number/divide.scm
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
gambit
|
daviwil
|
Scheme
|
Code
| 8
| 29
|
(include "#.scm")
(check-eqv? (denominator (/ -12 -10)) 5)
| 14,475
|
https://github.com/ahmad-fauzan458/TarungLabDDP1/blob/master/lab/09/template_09_a.py
|
Github Open Source
|
Open Source
|
MIT
| null |
TarungLabDDP1
|
ahmad-fauzan458
|
Python
|
Code
| 144
| 487
|
'''
Template untuk solusi Lab 09 kelas A.
'''
class Bangunan:
def __init__(self, nama, lama_sewa, harga_sewa):
self.nama = nama
self.lama_sewa = lama_sewa
self.harga_sewa = harga_sewa
def getHargaSewa(self):
return self.harga_sewa
class Restoran(Bangunan):
def __init__(self, nama, lama_sewa):
Bangunan.__init__(self, nama, lama_sewa, 30000000)
# Silahkan ditambahkan class-class lainnya atau jika ingin memodifikasi
daftar_bangunan = None
while True:
masukan = input().split()
if (masukan[0] == "BANGUN"):
# dapatkan nilai ini dari masukan_split sesuai indexnya
nama = None
jenis_bangunan = None
# lakukan selection untuk menentukan tipe Pegawai
if (jenis_bangunan == "HOTEL"):
bangunan = Hotel(nama) # instansiasi objek
elif (jenis_bangunan == "RESTORAN"):
bangunan = None
elif (jenis_bangunan == "RUMAHSAKIT"):
bangunan = None
# masukan bangunan yang sudah dibuat ke dalam dictionary
# cetak pesan sesuai format
elif (masukan[0] == "INFO"):
pass
elif (masukan[0] == "JUALMAKANAN"):
pass
elif (masukan[0] == "TERIMATAMU"):
pass
elif (masukan[0] == "OBATIPASIEN"):
pass
elif (masukan[0] == "HITUNGUANG"):
pass
| 3,754
|
https://github.com/solidate/closed-domain-faq/blob/master/server.py
|
Github Open Source
|
Open Source
|
MIT
| null |
closed-domain-faq
|
solidate
|
Python
|
Code
| 155
| 709
|
from fastapi import FastAPI,Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from haystack.document_store.memory import InMemoryDocumentStore
from haystack.retriever.dense import EmbeddingRetriever
from haystack.utils import print_answers
from haystack.pipeline import FAQPipeline
from fastapi.staticfiles import StaticFiles
import pandas as pd
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="./static/")
global store,retr,pipe
class Item(BaseModel):
query : str
def _document_store(similarity="cosine",index="document",
embedding_field="question_emb",
embedding_dim=768):
document_store = InMemoryDocumentStore(similarity=similarity,index=index,
embedding_field=embedding_field,
embedding_dim=embedding_dim)
return document_store
def _document_retriever(document_store=None,embedding_model=None):
retriever = EmbeddingRetriever(document_store=document_store,
embedding_model=embedding_model)
return retriever
def _faq_pipeline(retriever=None):
pipeline = FAQPipeline(retriever=retriever)
return pipeline
@app.on_event("startup")
def startup_event():
global store,retr,pipe
store = _document_store()
retr = _document_retriever(document_store=store, embedding_model="sentence-transformers/paraphrase-albert-small-v2")
pipe = _faq_pipeline(retriever=retr)
df = pd.read_csv('Data/faq.csv')
questions = list(df["question"].values)
df["question_emb"] = retr.embed_queries(texts=questions)
df = df.rename(columns={"question": "text"})
docs_to_index = df.to_dict(orient="records")
store.write_documents(docs_to_index)
@app.get('/', response_class=HTMLResponse)
def home(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
# return 'Go to /docs'
@app.post('/search/')
def search(item: Item):
item = item.dict()
query = item['query']
global pipe
prediction = pipe.run(query=query, params={"Retriever": {"top_k": 10}})
prediction = prediction['answers'][0]['answer']
return {'answer':prediction}
| 39,457
|
https://github.com/jf248/scrape-the-plate/blob/master/frontend/src/components/common/EditResourceDialog/EditResourceDialog.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
scrape-the-plate
|
jf248
|
JavaScript
|
Code
| 143
| 435
|
import React from 'react';
import { Compose } from 'lib/react-powerplug';
import { RecordForm } from 'controllers/record-form';
import { Modal } from 'controllers/modal';
import EditResourceDialogPres from './EditResourceDialogPres';
function EditResourceDialog({
name,
component,
resource,
resourceName,
...rest
}) {
const renderFunc = (modal, recordForm) => {
const {
isOpen,
modalProps: { id },
onClose,
} = modal;
const {
getInputProps,
getRootProps,
getSubmitProps,
resetForm,
} = recordForm;
const isCreate = !id;
const onExit = () => resetForm();
return (
<EditResourceDialogPres
{...{
getInputProps,
getRootProps,
getSubmitProps,
isCreate,
isOpen,
onClose,
onExit,
component,
resourceName,
}}
/>
);
};
return (
/* eslint-disable react/jsx-key */
<Compose
components={[
<Modal provider name={name} />,
(render, { modalProps: { id } }) => (
<RecordForm
{...{
id,
meta: {
onSuccess: {
snackbar: {},
closeModal: { name },
},
},
render,
resource,
...rest,
}}
/>
),
]}
render={renderFunc}
/>
/* eslint-enable react/jsx-key */
);
}
export default EditResourceDialog;
| 45,124
|
https://github.com/ClearMelody/ds_manager/blob/master/ds-web/.eslintrc.js
|
Github Open Source
|
Open Source
|
MIT
| null |
ds_manager
|
ClearMelody
|
JavaScript
|
Code
| 466
| 2,695
|
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint',
},
env: {
browser: true,
},
extends: [
// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
'plugin:vue/essential',
// https://github.com/standard/standard/blob/master/docs/RULES-en.md
'standard'
],
// required to lint *.vue files
plugins: [
'vue'
],
// add your custom rules here
rules: {
/**
* 不需要
*/
// 强制在 function的左括号之前使用一致的空格
"space-before-function-paren": 0,
"spaced-comment": 0,
"indent": [0, 2],
'vue/script-indent': [2, 2, {'baseIndent': 1}],
"prefer-promise-reject-errors": 1,
"no-trailing-spaces": 0,
// 文件末尾强制换行
"eol-last": 0,
// 使用 === 替代 == allow-null允许null和undefined==
"eqeqeq": 0,
// 强制函数中的变量要么一起声明要么分开声明
"one-var": 0,
// 禁用未声明的变量,除非它们在 /*global */ 注释中被提到
"no-undef": 0,
// 要求箭头函数的参数使用圆括号
"arrow-parens": 0,
// 强制 generator 函数中 * 号周围使用一致的空格
"generator-star-spacing": 0,
// 禁用指定的通过 require 加载的模块
"no-return-assign": 0,
// 禁止在注释中使用特定的警告术语
"no-warning-comments": 0,
// 禁止出现未使用过的变量
"no-unused-vars": 0,
// 禁止 if 语句中有 return 之后有 else
"no-else-return": 0,
// 强制使用有效的 JSDoc 注释
"valid-jsdoc": [0, {
"requireParamDescription": true,
"requireReturnDescription": true
}],
// 强制在对象字面量的属性中键和值之间使用一致的间距
"key-spacing": [0, {
"beforeColon": false,
"afterColon": true
}],
// 限制圈复杂度,也就是类似if else能连续接多少个
"complexity": 0,
// 禁止出现未使用过的表达式
"no-unused-expressions": 0,
// 禁止自身比较
"no-self-compare": 0,
// 禁用逗号操作符
"no-sequences": 0,
// 强制把变量的使用限制在其定义的作用域范围内
"block-scoped-var": 0,
"no-useless-escape": 0,
// 禁止扩展原生类型
"no-extend-native": 0,
// 禁止使用 var 多次声明同一变量
"no-redeclare": 0,
"block-spacing": 0,
// 允许 es6模板字符
"no-template-curly-in-string": 0,
// 强制花括号内换行符的一致性
"object-curly-newline":0,
// 强制在花括号中使用一致的空格
"object-curly-spacing": 0,
// 强制将对象的属性放在不同的行上
"object-property-newline":0,
// 表达式可以使用布尔值
"no-unneeded-ternary": 0,
// 禁止不必要的括号 //(a * b) + c;//报错
"no-extra-parens": 0,
// 允许使用 new Object
"no-new-object": 0,
"comma-spacing": 0,
"quotes": 0,
/**
* 警告
*/
// 禁止不必要的布尔转换
"no-extra-boolean-cast": 1,
// 禁止空语句块
"no-empty": 0,
// 不允许在变量定义之前使用它们
"no-use-before-define": [0, "nofunc"],
/**
* 错误
*/
// 数组和对象键值对最后一个逗号, never参数:不能带末尾的逗号, always参数:必须带末尾的逗号,
// always-multiline:多行模式必须带逗号,单行模式不能带逗号
"comma-dangle": [0, "never"],
// 禁止在条件中使用常量表达式
// if (false) {
// doSomethingUnfinished();
// } //cuowu
"no-constant-condition": 2,
// 禁止 function 定义中出现重名参数
"no-dupe-args": 2,
// 禁止对 Function 对象使用 new 操作符
"no-new-func": 2,
// 禁止重复的 case 标签
"no-duplicate-case": 2,
// 禁止对象字面量中出现重复的 key
"no-dupe-keys": 2,
// 禁止在正则表达式中使用空字符集 (/^abc[]/)
"no-empty-character-class": 2,
// 禁止 RegExp 构造函数中无效的正则表达式字符串
"no-invalid-regexp": 2,
// 禁止对 function 声明重新赋值
"no-func-assign": 0,
// 强制 typeof 表达式与有效的字符串进行比较
// typeof foo === "undefimed" 错误
"valid-typeof": 2,
// 禁止在return、throw、continue 和 break语句之后出现不可达代码
/*
function foo() {
return true;
console.log("done");
}//错误
*/
"no-unreachable": 2,
// 禁止出现令人困惑的多行表达式
"no-unexpected-multiline": 2,
// 禁用稀疏数组
"no-sparse-arrays": 2,
// 禁止覆盖受限制的标识符
"no-shadow-restricted-names": 2,
// 禁止条件表达式中出现赋值操作符
"no-cond-assign": 2,
// 禁止对原生对象赋值
"no-native-reassign": 2,
"no-debugger": process.env.NODE_ENV === "production" ? 2 : 0,
/**
* 代码风格
*/
// 禁止使用多个空格
"no-multi-spaces": 0,
// 要求 return 语句要么总是指定返回的值,要么不指定
"consistent-return": 0,
// 定义对象的set存取器属性时,强制定义get
"accessor-pairs": 2,
// 强制object.key 中 . 的位置,参数:
// property,"."号应与属性在同一行
// object, "." 号应与对象名在同一行
"dot-location": [2, "property"],
// 禁用不必要的嵌套块
"no-lone-blocks": 2,
// 禁用标签语句
"no-labels": 2,
// 禁止数字字面量中使用前导和末尾小数点
"no-floating-decimal": 2,
// 禁止在循环中出现 function 声明和表达式
"no-loop-func": 2,
// 禁止不必要的分号
"no-extra-semi": 2,
// 要求或禁止使用分号而不是 ASI(这个才是控制行尾部分号的,)
"semi": 0,
// 禁止抛出非异常字面量
"no-throw-literal": 2,
// 禁止不必要的 .call() 和 .apply()
"no-useless-call": 2,
// 禁止不必要的字符串字面量或模板字面量的连接
"no-useless-concat": 2,
// 禁用 void 操作符
"no-void": 2,
// 禁用 with 语句
"no-with": 2,
// 要求操作符周围有空格
"space-infix-ops": 2,
// 强制所有控制语句使用一致的括号风格
"curly": 1
}
}
| 37,553
|
https://github.com/refraction-ray/qop/blob/master/qop/boson.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
qop
|
refraction-ray
|
Python
|
Code
| 44
| 157
|
import sys
import numpy as np
from .particle import ParticleOperator, ParticleOperatorString
from .utils import repr_short
thismodule = sys.modules[__name__]
class BosonOperator(ParticleOperator):
def strfy(self):
return BosonOperatorString.from_op(self)
b = BosonOperator
class BosonOperatorString(ParticleOperatorString):
pass
for i in range(10):
setattr(thismodule, "b" + str(i), b(i, name="b", repr_=repr_short))
BOS = BosonOperatorString
| 46,689
|
https://github.com/shelby-yao/CommonPods/blob/master/Example/Pods/JKNetwork/JKNetworking/JKNetworkingKit/JKNetworking/NSURLSession+JKCategory.m
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
CommonPods
|
shelby-yao
|
Objective-C
|
Code
| 106
| 455
|
//
// NSURLSession+JKCategory.m
// JKNetwork
//
// Created by Jekin on 2019/11/14.
//
#import "NSURLSession+JKCategory.h"
#import <objc/runtime.h>
void swizzing(Class class, SEL originalSelector, SEL swizzledSelector)
{
Method originalMethod = class_getClassMethod(class, originalSelector);
Method swizzledMethod = class_getClassMethod(class, swizzledSelector);
method_exchangeImplementations(originalMethod, swizzledMethod);
}
@implementation NSURLSession (JKCategory)
+ (void)load{
#if DEBUG
#else
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [NSURLSession class];
swizzing(class, @selector(sessionWithConfiguration:), @selector(jk_sessionWithConfiguration:));
swizzing(class, @selector(sessionWithConfiguration:delegate:delegateQueue:),
@selector(jk_sessionWithConfiguration:delegate:delegateQueue:));
});
#endif
}
+ (NSURLSession *)jk_sessionWithConfiguration:(NSURLSessionConfiguration *)configuration
delegate:(nullable id<NSURLSessionDelegate>)delegate
delegateQueue:(nullable NSOperationQueue *)queue{
if (!configuration){
configuration = [[NSURLSessionConfiguration alloc] init];
}
configuration.connectionProxyDictionary = @{};
return [self jk_sessionWithConfiguration:configuration delegate:delegate delegateQueue:queue];
}
+ (NSURLSession *)jk_sessionWithConfiguration:(NSURLSessionConfiguration *)configuration{
if (configuration){
configuration.connectionProxyDictionary = @{};
}
return [self jk_sessionWithConfiguration:configuration];
}
@end
| 5,037
|
https://github.com/Sreejithpin/odata.net/blob/master/test/FunctionalTests/Taupo/Source/Taupo.Astoria/Contracts/LinqToAstoria/IAstoriaQueryVerifierCapabilityInspector.cs
|
Github Open Source
|
Open Source
|
CC-BY-3.0
| 2,022
|
odata.net
|
Sreejithpin
|
C#
|
Code
| 109
| 286
|
//---------------------------------------------------------------------
// <copyright file="IAstoriaQueryVerifierCapabilityInspector.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.Test.Taupo.Astoria.Contracts.LinqToAstoria
{
using Microsoft.Test.Taupo.Common;
/// <summary>
/// Inspects the QueryVerifier to understand what level of capability it has
/// </summary>
[ImplementationSelector("AstoriaQueryVerifierCapabilityInspector", DefaultImplementation = "Default")]
public interface IAstoriaQueryVerifierCapabilityInspector
{
/// <summary>
/// Indicates the QueryVerifier runs on the client
/// </summary>
/// <returns>True if it executes on the client</returns>
bool ExecutesOnDataServicesClient();
/// <summary>
/// Indicates that this query execution method supports projection when the keys aren't specified
/// </summary>
/// <returns>returns true if the executor supports projections with out keys</returns>
bool SupportsProjectionWithoutKeys();
}
}
| 5,614
|
https://github.com/robertojnior/tompero/blob/master/src/app/clients/RecipePuppyClient/baseClient.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
tompero
|
robertojnior
|
TypeScript
|
Code
| 19
| 65
|
import axios from 'axios'
import dotenv from 'dotenv'
dotenv.config()
const baseClient = axios.create({
baseURL: process.env.RECIPE_PUPPY_BASE_URL
})
export default baseClient
| 6,490
|
https://github.com/qvik/go-cloudlogging/blob/master/stackdriver.go
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
go-cloudlogging
|
qvik
|
Go
|
Code
| 155
| 552
|
package cloudlogging
import (
"context"
"fmt"
stdlog "log"
stackdriver "cloud.google.com/go/logging"
"google.golang.org/api/option"
)
var (
levelToStackdriverSeverityMap map[Level]stackdriver.Severity
)
// createStackdriverLogger creates a new Stackdriver logging client and a logger
func createStackdriverLogger(opts options) (*stackdriver.Client,
*stackdriver.Logger, error) {
ctx := context.Background()
o := []option.ClientOption{}
if opts.credentialsFilePath != "" {
//TODO use WriteScope here too
o = append(o, option.WithCredentialsFile(opts.credentialsFilePath))
}
// See: https://godoc.org/cloud.google.com/go/logging#NewClient
parent := fmt.Sprintf("projects/%v", opts.gcpProjectID)
client, err := stackdriver.NewClient(ctx, parent, o...)
if err != nil {
return nil, nil, fmt.Errorf("failed to create stackdriver client: %v", err)
}
// Install an error handler
client.OnError = func(err error) {
stdlog.Printf("Stackdriver error: %v", err)
}
loggeropts := []stackdriver.LoggerOption{}
if opts.stackDriverMonitoredResource != nil {
loggeropts = append(loggeropts,
stackdriver.CommonResource(opts.stackDriverMonitoredResource))
}
logger := client.Logger(opts.stackdriverLogID, loggeropts...)
// Emit a log entry for testing
logger.Log(stackdriver.Entry{
Payload: "Stackdriver logger created",
Severity: stackdriver.Info,
})
return client, logger, nil
}
func init() {
levelToStackdriverSeverityMap = map[Level]stackdriver.Severity{
Debug: stackdriver.Debug,
Info: stackdriver.Info,
Warning: stackdriver.Warning,
Error: stackdriver.Error,
Fatal: stackdriver.Critical,
}
}
| 9,225
|
https://github.com/onezens/SmartQQ/blob/master/qqtw/qqheaders7.2/CFT_FF14467.h
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
SmartQQ
|
onezens
|
Objective-C
|
Code
| 281
| 1,422
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "CFT_UICustomNaviBarViewController.h"
#import "MulMemSelBusiProcessDelegate.h"
#import "UIScrollViewDelegate.h"
#import "UISegmentViewDelegate.h"
#import "UITextFieldDelegate.h"
@class CFT_RedGiftView, NSMutableDictionary, NSString, UIImage, UIView;
@interface CFT_FF14467 : CFT_UICustomNaviBarViewController <UISegmentViewDelegate, MulMemSelBusiProcessDelegate, UITextFieldDelegate, UIScrollViewDelegate>
{
int _redgiftType;
_Bool _memoTextToChange;
unsigned long long _lastMemoTextLength;
_Bool _navbarReloaded;
_Bool _isOne2One;
_Bool _conf_show_vipshop;
_Bool _isTmpChat;
_Bool _isLbsAr;
NSMutableDictionary *_RedGiftparam;
NSString *_comefrom;
NSString *_uin;
NSString *_skey;
NSString *_skey_type;
NSString *_appinfo;
NSString *_nick;
UIImage *_superviewNaviBgImage;
NSString *_hideWishing;
CFT_RedGiftView *_normalView;
CFT_RedGiftView *_randomView;
CFT_RedGiftView *_commandView;
CFT_RedGiftView *_one2oneView;
UIView *_contentView;
}
@property(retain, nonatomic) NSMutableDictionary *RedGiftparam; // @synthesize RedGiftparam=_RedGiftparam;
@property(retain, nonatomic) NSString *appinfo; // @synthesize appinfo=_appinfo;
- (void)bannerTipViewDidClick:(id)arg1;
- (void)changeNextBtnEnable:(_Bool)arg1;
- (void)changeProcessFlag:(_Bool)arg1;
- (void)changeToOrientedRedgiftClick:(id)arg1;
@property(retain, nonatomic) NSString *comefrom; // @synthesize comefrom=_comefrom;
@property(retain, nonatomic) CFT_RedGiftView *commandView; // @synthesize commandView=_commandView;
@property(retain, nonatomic) UIView *contentView; // @synthesize contentView=_contentView;
- (void)controlBecomeFirstResponder;
- (id)currentRedGiftView;
- (void)dealloc;
- (id)getRedGiftViewByType:(int)arg1;
@property(retain, nonatomic) NSString *hideWishing; // @synthesize hideWishing=_hideWishing;
- (void)leftButtonClick:(id)arg1;
- (void)nextStep:(id)arg1;
@property(retain, nonatomic) NSString *nick; // @synthesize nick=_nick;
@property(retain, nonatomic) CFT_RedGiftView *normalView; // @synthesize normalView=_normalView;
- (void)onBusinessProcessWithSelectedMems:(id)arg1 currentViewControllerClass:(id)arg2 currentViewController:(id)arg3;
- (void)onPersonalRedbagDownloadSuccess;
@property(retain, nonatomic) CFT_RedGiftView *one2oneView; // @synthesize one2oneView=_one2oneView;
- (void)qpay_hb_pack;
- (void)qpay_hb_zone_pack;
@property(retain, nonatomic) CFT_RedGiftView *randomView; // @synthesize randomView=_randomView;
- (id)redgiftChannel;
- (double)redgiftTotalMoney;
- (int)redgiftTotalNum;
- (int)redgiftTotalNum:(id)arg1;
- (void)resetControlContentState;
- (void)resetNextButtonState;
- (void)resetRedGiftViewFileldFromState:(int)arg1 ToState:(int)arg2;
- (void)rightButtonClick:(id)arg1;
- (void)segmentSelectionChange:(id)arg1 selection:(long long)arg2;
- (void)selectOrientedMemberClick:(id)arg1;
@property(retain, nonatomic) NSString *skey; // @synthesize skey=_skey;
@property(retain, nonatomic) NSString *skey_type; // @synthesize skey_type=_skey_type;
@property(retain, nonatomic) UIImage *superviewNaviBgImage; // @synthesize superviewNaviBgImage=_superviewNaviBgImage;
@property(retain, nonatomic) NSString *uin; // @synthesize uin=_uin;
- (void)showHuanFuPreview;
- (void)textFieldDidChange:(id)arg1;
- (void)textFiledReturnEditing:(id)arg1;
- (void)updateHuanFuBtn;
- (void)updateHuanFuPreviewWithColor:(id)arg1 img:(id)arg2;
- (void)viewDidAppear:(_Bool)arg1;
- (void)viewDidLoad;
- (void)viewWillAppear:(_Bool)arg1;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 3,024
|
https://github.com/keithpij/python-blueprints/blob/master/blueprints/loggers/basic_logger_old.py
|
Github Open Source
|
Open Source
|
MIT
| null |
python-blueprints
|
keithpij
|
Python
|
Code
| 384
| 943
|
'''
A Basic Python Logging Blueprint.
'''
import argparse
import logging
from blueprints.loggers import logging_utils as lu
def create_basic_logger(logger_name, logging_level, propagate_message=True):
'''
Creates a logger with a StreamHandler that sends messages to stdout. The logging level of
the logger itself is set to NOTSET. The logging level of the handler is set to the value
passed in via the logging_level parameter.
The logging level must numeric. Typically it is one of the contants found in the logging
module (ex. logging.INFO) but it can be any number. As an example, setting it to
logging.CRITICAL + 1 will turn off the handler.
Setting propagate_message to True will cause messages to be sent to parent loggers where
the messages will be sent to the parents handlers regardless of the level of the logger.
When this parameter is false the logger will behave like a root logger.
IMPORTANT: If the logger is set to NOTSET then the logger will propagate to the parent
regardless of how the propagate property is set.
'''
# Create and configure the logger.
basic_logger = logging.getLogger(logger_name)
basic_logger.setLevel(logging_level)
#basic_logger.parent = None
basic_logger.propagate = propagate_message
# Create the handler and set the logging level.
stdout_handler = lu.create_stdout_handler(logging_level)
# Create and add the formatter to the handler.
stdout_handler.setFormatter(lu.create_formatter())
# Add the handler to the logger.
basic_logger.addHandler(stdout_handler)
return basic_logger
if __name__ == '__main__':
# Setup all the CLI arguments for this module.
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--logger_name',
help='Specify the name of your logger.')
parser.add_argument('-l', '--logging_level',
help='Specify a logging level (NOTSET, DEBUG, INFO, WARNING, ERROR, or CRITICAL) for the basic logger.')
parser.add_argument('-pl', '--print_levels',
help='Print all log levels and their numeric values.',
action='store_true')
parser.add_argument('-ph', '--print_handlers',
help='Print all handlers within the logger that is created.',
action='store_true')
parser.add_argument('-pal', '--print_all_loggers',
help='Print all loggers.',
action='store_true')
# Parse what was passed in. This will also check the arguments for you and produce
# a help message is something is wrong.
args = parser.parse_args()
# Get the name of the logger.
if args.logger_name:
NAME = args.logger_name
else:
NAME = __name__
# get the level to be used for the logger's handler.
if args.logging_level:
LEVEL = lu.convert_logging_level(args.logging_level)
else:
LEVEL = logging.INFO
print('The current level is : ' + str(LEVEL))
LOGGER = create_microservice_logger(NAME, LEVEL, False)
lu.log_sample_messages(LOGGER)
# Print all handlers
if args.print_handlers:
lu.print_handlers(LOGGER)
# Print logging levels.
if args.print_levels:
lu.print_logging_levels()
# Print all loggers.
if args.print_all_loggers:
lu.print_all_loggers()
| 7,864
|
https://github.com/EVODelavega/gp-scripts/blob/master/rrn.js
|
Github Open Source
|
Open Source
|
MIT
| null |
gp-scripts
|
EVODelavega
|
JavaScript
|
Code
| 672
| 2,270
|
/**
* Basic RRN (SSN) number checker/generator/validator
*/
var RRMod = (function()
{
var modMax = 1000,
modBase = 997,
checkBase = 97,
module = {},
str2date = function(str)
{
var parts = str.split(/[^\d]+/);
if (parts.length != 3)
return false;
if (parts[2].length === 4)
parts = parts.reverse;//reverse dd mm YYYY
//assume YYYY-mm-dd
if (parts[0].length === 4)
return new Date(parts.join('/'));//works fine
//all parts are 2 long?
if (+(parts[0]) > 12)
parts = parts.reverse();
return new Date(parts.join('-'));
},
randMod = function (mod, max, odd)
{
var r;
mod = mod || modBase;
max = max || modMax;
odd = odd || 1;
do
{
r = Math.round(Math.random()*max + 1)%mod
} while (r%2 !== odd);
return r || modMax + 1;//max even is 998
},
bd2rr = function(date, sex)
{
var year, month, day, count;
if (!date instanceof Date)
date = str2date(date);
//day-count:
sex = sex.toLowerCase() === 'f' ? 0 : 1;
count = ('0000' + randMod(modBase, modMax, sex)).substr(-1*(''+modMax).length);
year = ('00' + (date.getFullYear()%100)).substr(-2);//get last 2 digits
month = ('00' + (date.getMonth()+1)).substr(-2);//months are zero indexed
day = ('00' + date.getDate()).substr(-2);
return year+month+day+count;
},
rrn = function(rrnString)
{
var num, base = (rrnString.replace(/[^0-9]/g,'')).substr(0,9)
if (base.length != 9)
return false;
num = parseInt(base, 10);//use parseInt to avoid octals in case of leading zeroes
num = ('0000' + (checkBase - (num%checkBase))).substr(-1 * (''+checkBase).length);
return base.replace(/^(\d{2})(\d{2})(\d{2})(\d{3})/,'$1.$2.$3-$4-' + num);
},
usSsn = function()
{
var k,
check,
bases = [900,100,10000],
groups =[
(Math.round(Math.random()*1000)+111)%bases[0],
(Math.round(Math.random()*100)+1)%bases[1],
(Math.round(Math.random()*10000)+1)%bases[2]
];
for (k=0;k<groups.length;++k)
if (!groups[k])
groups[k] = Math.round(Math.random()*bases[k]);
while (groups[0] === 666 || groups[0] > 900)
groups[0] = (Math.round(Math.random()*1000)+111)%900;
if (groups[0] === 987 && groups[1] === 65)
while(groups[2] > 4319 && groups[2] < 4330)
groups[2] = (Math.round(Math.random()*10000)+1)%10000;
//the Woolworth SSN: 078-05-1120
if (groups[0] === 78 && groups[1] === 5 && groups[2] === 1120)
{
k = (Math.round(Math.random()*10))%3;
check = groups[k];
while (groups[k] === check)
groups[k] = Math.round(Math.random()*bases[k]);
//small chance, but dirty fix to avoid prohibited SSN's from being generated here.
if (groups[k] === 666) groups[k]++;
else if (groups[k] === 0) groups[k]++;
else if (groups[k] === 65) groups[k]++;
}
for (k = 0;k<groups.length;++k)
groups[k] = ('0000' + groups[k]).substr( k === 2 ? -4 : (k -3));
return groups.join('-');
};
Object.defineProperties(module, {
modMax: {
set: function(max)
{
modMax = Math.abs(+(max) || modMax);
},
get: function()
{
return modMax;
}
},
modBase: {
set: function(newB)
{
modBase = +(newB) || modBase;
},
get: function()
{
return modBase;
}
},
checkBase: {
set: function(newCB)
{
checkBase = Math.abs(+(newCB) || checkBase);
},
get: function()
{
return checkBase;
}
},
addValidator: {
value: rrn,
writable: false
},
date2baseRR: {
value: bd2rr,
writable: false
},
validate: {
value: function (nr)
{
return (nr.substr(-3) === rrn(nr).substr(-3));
},
writable: false
},
generateRandom: {
value: function(minAge, sex)
{
var date = new Date();
sex = (sex || 'm').toLowerCase() === 'f' ? 'f' : 'm';
minAge = minAge || 0;
if (minAge)
minAge = (minAge+Math.floor(Math.random()*100))%100 || minAge;
date.setFullYear(date.getFullYear() - minAge);
date.setMonth(Math.round(Math.random()*100)%12);
date.setDate(Math.round(Math.random()*100)%32);
return rrn(bd2rr(date, sex));
},
writable: false
},
generateRandomBetween: {
value: function(min, max, sex)
{
var date = new Date(),
age,
mod = 12;
if (typeof max !== 'number')
{
sex = max;
max = 100;
}
//age -> random between min and max age
age = Math.floor(Math.random() * (max - min) + min);
if (age === min)
mod = date.getMonth();//not in future months
date.setFullYear(date.getFullYear() - age);
date.setMonth(Math.round(Math.random()*100)%mod);
mod=32;//day modulo
if (date.getMonth() === 1)
{//feb -> date modulo needs to change
mod -= 2;//29 or 28 days
if (date.getFullYear()%4)
{//if year not divisible by 4, mod needs to be 29 (for 28 days)
--mod;
}
}
date.setDate(Math.round(Math.random()*100)%mod);
return rrn(bd2rr(date, sex));
},
writable: false
},
generateRR: {
value: function(d, s, full)
{
full = typeof full === 'undefined' ? true : full;
if (full)
return rrn(bd2rr(d,s));
return bd2rr(d,s);
},
writable: false
},
generateUSSSN: {
value: usSsn,
writable: false
}
});
return module;
}());
/*
console.log(RRMod.modBase);
console.log(RRMod.generateRandom(18));
console.log(RRMod.generateRR(new Date(), 'f'));
console.log(RRMod.generateRR(new Date(), 'm', false));
console.log(RRMod.addValidator('99.01.01-009-??'));
(function(i)
{
console.log('10 RRNs 21+, male: ');
for (i=0;i<10;++i)
console.log(RRMod.generateRandom(21, 'm'));
console.log('10 RRNs, 21+, female: ');
for (i=0;i<10;++i)
console.log(RRMod.generateRandom(21, 'f'));
console.log('5 RRNs 18+ male: ');
for (i=0;i<5;++i)
console.log(RRMod.generateRandomBetween(18, 21, 'm'));
}());
*/
| 805
|
https://github.com/cmitchell/jooby/blob/master/docs/asciidoc/modules/rocker.adoc
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
jooby
|
cmitchell
|
AsciiDoc
|
Code
| 266
| 938
|
== Rocker
https://github.com/fizzed/rocker[Rocker] is a Java 8 optimized, memory efficient, speedy template
engine producing statically typed, plain java objects.
=== Usage
1) Add the dependency:
[dependency, artifactId="jooby-rocker"]
.
2) Configure code generator
.Maven
[source,xml,role="primary",subs="verbatim,attributes"]
----
<plugin>
<groupId>com.fizzed</groupId>
<artifactId>rocker-maven-plugin</artifactId>
<version>{rockerVersion}</version>
<configuration>
<templateDirectory>src/rocker</templateDirectory>
</configuration>
<executions>
<execution>
<id>generate-rocker-templates</id>
<phase>generate-sources</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
----
.Gradle
[source,groovy,role="secondary",subs="verbatim,attributes"]
----
plugins {
id "com.fizzed.rocker" version "{rockerVersion}"
}
sourceSets {
main {
rocker {
srcDir('src/rocker')
}
}
}
----
NOTE: Complete code generator options are https://github.com/fizzed/rocker#integrate-parsergenerator-in-build-tool[available here]
3) Write your templates inside the `src/rocker/views` folder
.src/rocker/views/index.rocker.html
[source, html]
----
@args (String message)
<p>Hello @message!</p>
----
4) Install and use rocker templates
.Java
[source, java, role="primary"]
----
import io.jooby.rocker.RockerModule;
{
install(new RockerModule()); <1>
get("/", ctx -> {
return views.index.template("Rocker"); <2>
});
}
----
.Kotlin
[source, kt, role="secondary"]
----
import io.jooby.rocker.RockerModule
{
install(RockerModule()) <1>
get("/") {
views.index.template("Rocker") <2>
}
}
----
<1> Install Rocker
<2> Returns a rocker view
=== Options
Rocker uses a byte buffer to render a view. Default byte buffer size is `4k`. To change the buffer size:
.Java
[source, java, role="primary"]
----
import io.jooby.rocker.RockerModule;
{
install(new RockerModule().bufferSize(1024));
}
----
.Kotlin
[source, kt, role="secondary"]
----
import io.jooby.rocker.RockerModule
{
install(RockerModule().bufferSize(1024)
}
----
You can reuse/recycle the buffer using a thread-local approach by setting `reuseBuffer(true)`:
.Java
[source, java, role="primary"]
----
import io.jooby.rocker.RockerModule;
{
install(new RockerModule().reuseBuffer(true));
}
----
.Kotlin
[source, kt, role="secondary"]
----
import io.jooby.rocker.RockerModule
{
install(RockerModule().reuseBuffer(true)
}
----
CAUTION: Use with caution due it creates a buffer per thread memory consumption might be high.
This technique works when the number of available threads is low enough
(like the number of available processors).
| 47,318
|
https://github.com/DevscoreTeam/Bitnomi/blob/master/table.js
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
Bitnomi
|
DevscoreTeam
|
JavaScript
|
Code
| 199
| 613
|
import React, { Component } from 'react';
import Table from 'antd/lib/table';
import './App.css';
class OrderTable extends Component {
render() {
const columns = [
{
title: "No.",
dataIndex: "No.",
key: "No.",
},
{
title: "Type",
dataIndex: "Type",
key: "Type",
},
{
title: "Amount",
dataIndex: "Amount",
key: "Amount",
},
{
title: "Price",
dataIndex: "Price",
key: "Price",
},
{
title: "Fee",
dataIndex: "Fee",
key: "Fee",
},{
title: "Time",
dataIndex: "Time",
key: "Time",
},
{
title: "Status",
dataIndex: "Status",
key: "Status"
},
{
title: "Conterparty",
dataIndex: "Conterparty",
key: "Conterparty"
}
];
const data = [
{
key: "1",
Status: "Closed",
age: 32,
address: "New York No. 1 Lake Park"
},
{
key: "2",
name: "Jim Green",
Status: "Closed",
address: "London No. 1 Lake Park"
},
{
key: "3",
name: "Joe Black",
Status: "Closed",
address: "Sidney No. 1 Lake Park"
}
,
{
key: "3",
name: "Joe Black",
Status: "Canceled",
address: "Sidney No. 1 Lake Park"
},
{
key: "3",
name: "Joe Black",
Status: "Closed",
address: "Sidney No. 1 Lake Park"
},
{
key: "3",
name: "Joe Black",
Status: "Canceled",
address: "Sidney No. 1 Lake Park"
}
];
return (
<div className="table">
<Table columns={columns} dataSource={data} />
</div>
);
}
}
export default OrderTable;
| 21,195
|
https://github.com/V-Fib/FlurryClone/blob/master/MMOCoreORB/bin/scripts/object/custom_content/draft_schematic/dance_prop/prop_ribbon_spark_r_s04.lua
|
Github Open Source
|
Open Source
|
Zlib, OpenSSL
| 2,021
|
FlurryClone
|
V-Fib
|
Lua
|
Code
| 7
| 126
|
object_draft_schematic_dance_prop_prop_ribbon_spark_r_s04 = object_draft_schematic_dance_prop_shared_prop_ribbon_spark_r_s04:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_dance_prop_prop_ribbon_spark_r_s04, "object/draft_schematic/dance_prop/prop_ribbon_spark_r_s04.iff")
| 43,203
|
https://github.com/EricWen229/JuliaSetPython/blob/master/juliaset/utility.py
|
Github Open Source
|
Open Source
|
MIT
| null |
JuliaSetPython
|
EricWen229
|
Python
|
Code
| 111
| 380
|
import colorsys
import math
import PIL.ImageColor
class Complex:
def __init__(self, x=0.0, y=0.0):
self.x = float(x)
self.y = float(y)
class RGBRange:
colorIn = (0.0, 0.0, 0.0)
colorOut = (0.0, 0.0, 0,0)
class HSBComponents:
h = 0.0
s = 0.0
b = 0.0
def double3(self):
return (self.h, self.s, self.b)
def toRGB(self):
return colorsys.hsv_to_rgb(self.h, self.s, self.b)
class JuliaSetColor:
def __init__(self, hue=0.0, brightness=0.0, saturation=1.0):
self.hue = hue
self.brightness = brightness
self.saturation = saturation
def toRGBRange(self):
s = RGBRange()
hsb = HSBComponents()
hsb.h = self.hue
hsb.s = self.brightness / 10 + 0.65 * self.saturation
hsb.b = 1 - self.brightness
s.colorOut = hsb.toRGB()
hsb.b = (1 - math.cos(hsb.b * math.pi)) / 8
s.colorIn = hsb.toRGB()
return s
| 37,728
|
https://github.com/spegustavo/VaadinProject/blob/master/node_modules/@vaadin/vaadin-virtual-list/src/virtualizer.js
|
Github Open Source
|
Open Source
|
Unlicense
| null |
VaadinProject
|
spegustavo
|
JavaScript
|
Code
| 362
| 718
|
import { IronListAdapter } from './virtualizer-iron-list-adapter.js';
export class Virtualizer {
/**
* @typedef {Object} VirtualizerConfig
* @property {Function} createElements Function that returns the given number of new elements
* @property {Function} updateElement Function that updates the element at a specific index
* @property {HTMLElement} scrollTarget Reference to the scrolling element
* @property {HTMLElement} scrollContainer Reference to a wrapper for the item elements (or a slot) inside the scrollTarget
* @property {HTMLElement | undefined} elementsContainer Reference to the container in which the item elements are placed, defaults to scrollContainer
* @property {boolean | undefined} reorderElements Determines whether the physical item elements should be kept in order in the DOM
* @param {VirtualizerConfig} config Configuration for the virtualizer
*/
constructor(config) {
this.__adapter = new IronListAdapter(config);
}
/**
* The size of the virtualizer
* @param {number} size The size of the virtualizer
*/
set size(size) {
this.__adapter.size = size;
}
/**
* The size of the virtualizer
* @return {number | undefined} The size of the virtualizer
*/
get size() {
return this.__adapter.size;
}
/**
* Scroll to a specific index in the virtual list
*
* @method scrollToIndex
* @param {number} index The index of the item
*/
scrollToIndex(index) {
this.__adapter.scrollToIndex(index);
}
/**
* Requests the virtualizer to re-render the item elements on an index range, if currently in the DOM
*
* @method update
* @param {number | undefined} startIndex The start index of the range
* @param {number | undefined} endIndex The end index of the range
*/
update(startIndex = 0, endIndex = this.size - 1) {
this.__adapter.update(startIndex, endIndex);
}
/**
* Flushes active asynchronous tasks so that the component and the DOM end up in a stable state
*
* @method update
* @param {number | undefined} startIndex The start index of the range
* @param {number | undefined} endIndex The end index of the range
*/
flush() {
this.__adapter.flush();
}
/**
* Gets the index of the first visible item in the viewport.
*
* @return {number}
*/
get firstVisibleIndex() {
return this.__adapter.adjustedFirstVisibleIndex;
}
/**
* Gets the index of the last visible item in the viewport.
*
* @return {number}
*/
get lastVisibleIndex() {
return this.__adapter.adjustedLastVisibleIndex;
}
}
| 32,897
|
https://github.com/vckai/novel/blob/master/app/services/feedback.go
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
novel
|
vckai
|
Go
|
Code
| 329
| 919
|
// Copyright 2017 Vckai Author. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package services
import (
"errors"
"github.com/astaxie/beego/validation"
"github.com/vckai/novel/app/models"
)
// 定义FeedbackService
type Feedback struct {
}
func NewFeedback() *Feedback {
return &Feedback{}
}
// 获取单个反馈信息
func (this *Feedback) Get(id uint32) *models.Feedback {
if id < 0 {
return nil
}
feedback := &models.Feedback{Id: id}
err := feedback.Read()
if err != nil {
return nil
}
return feedback
}
// 批量获取反馈列表
func (this *Feedback) GetAll(size, offset int, args map[string]interface{}) ([]*models.Feedback, int64) {
qs := map[string]string{}
if q, ok := args["q"]; ok && len(q.(string)) > 0 {
qs["q"] = q.(string)
}
if c, ok := args["count"]; ok && c.(bool) == true {
qs["count"] = "1"
}
feedbacks, count := models.FeedbackModel.GetAll(size, offset, qs)
return feedbacks, count
}
// 批量删除反馈内容
func (this *Feedback) DeleteBatch(ids []string) error {
if len(ids) == 0 {
return errors.New("params error")
}
return models.FeedbackModel.DeleteBatch(ids)
}
// 删除反馈内容
func (this *Feedback) Delete(id uint32) error {
if id < 0 {
return errors.New("params error")
}
log := models.Feedback{Id: id}
err := log.Delete()
if err != nil {
return err
}
return nil
}
// 添加/修改
func (this *Feedback) Save(feed *models.Feedback) error {
// 参数校验
valid := validation.Validation{}
valid.Required(feed.Content, "nameEmpty").Message("反馈内容不能为空")
valid.MaxSize(feed.Content, 255, "nameMax").Message("反馈内容长度不能超过255个字符")
valid.Required(feed.Contact, "contactEmpty").Message("联系方式不能为空")
valid.MaxSize(feed.Contact, 100, "contactMax").Message("联系方式长度不能超过100个字符")
if valid.HasErrors() {
for _, err := range valid.Errors {
return err
}
}
var err error
if feed.Id > 0 {
err = feed.Update("status", "reply", "reply_at")
} else {
err = feed.Insert()
}
return err
}
| 27,074
|
https://github.com/getlocal-travel/tinacms/blob/master/packages/@tinacms/toolkit/src/packages/icons/Redo.tsx
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
tinacms
|
getlocal-travel
|
TypeScript
|
Code
| 138
| 354
|
/**
Copyright 2021 Forestry.io Holdings, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import * as React from 'react'
export const RedoIcon = ({ ...props }) => (
<svg
viewBox="0 0 32 32"
fill="inherit"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
<path d="M24.5333 14.1333C22.0667 11.9867 18.8667 10.6667 15.3333 10.6667C9.13333 10.6667 3.89333 14.7067 2.05333 20.2933L5.2 21.3333C6.6 17.08 10.6 14 15.3333 14C17.9333 14 20.3067 14.96 22.16 16.5067L17.3333 21.3333H29.3333V9.33334L24.5333 14.1333Z" />
</svg>
)
| 18,914
|
https://github.com/travers-rhodes/ricnn/blob/master/code/testing.m
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
ricnn
|
travers-rhodes
|
MATLAB
|
Code
| 4
| 52
|
plot(fft([1,0,0,0]))
plot(fft([0,1,0,0]))
plot(fft([0,0,1,0]))
plot(fft([0,1,1,0]))
| 21,187
|
https://github.com/thirumurthy/NewGeneralCommon/blob/master/src/Common/FileOperations.java
|
Github Open Source
|
Open Source
|
MIT
| null |
NewGeneralCommon
|
thirumurthy
|
Java
|
Code
| 412
| 1,309
|
package Common;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import org.apache.commons.codec.binary.StringUtils;
import com.sun.xml.bind.v2.model.util.ArrayInfoUtil;
public class FileOperations {
public static String readFile(String filename)
{
String resp="";
try (BufferedReader br = new BufferedReader(new FileReader(filename)))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
resp+=sCurrentLine;
}
} catch (IOException e) {
e.printStackTrace();
}
return resp;
}
public static void WriteData(String filename,String content)
{
try {
File file = new File(filename);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String[] ListDirectory(String path)
{
try
{
File file = new File(path);
String[] directories = file.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
return directories;
}
catch (Exception exp) {
return null;
// TODO: handle exception
}
}
public static boolean DeleteFile(String path)
{
boolean result=false;
try
{
File file = new File(path);
if(file.delete()){
result=true;
}
return result;
}
catch (Exception e) {
return result;
// TODO: handle exception
}
}
public static boolean CreateFile(String path)
{
boolean result=false;
try
{
File file = new File(path);
if(file.createNewFile()){
result=true;
}
return result;
}
catch (Exception e) {
return result;
// TODO: handle exception
}
}
public static boolean checkFileExists(String path)
{
boolean result=false;
try
{
File file = new File(path);
if(file.exists()){
result=true;
}
return result;
}
catch (Exception e) {
return result;
// TODO: handle exception
}
}
public static String geLastline(String path)
{
String result="";
try
{
BufferedReader input = new BufferedReader(new FileReader(path));
String line;
while ((line = input.readLine()) != null) {
result = line;
}
return result;
}
catch (Exception e) {
return result;
// TODO: handle exception
}
}
public static void appendFile(String filename,String content)
{
BufferedWriter bw = null;
FileWriter fw = null;
PrintWriter out = null;
try
{
File file = new File(filename);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(filename, true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println(content);
out.close();
}
catch(Exception exp)
{
exp.printStackTrace();
}
finally {
if(out != null)
out.close();
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
}
}
| 26,022
|
https://github.com/acfreitas/agile-itsm/blob/master/agile-itsm-web/agile-itsm-web-portal/src/main/java/br/com/centralit/citcorpore/ajaxForms/OrigemOcorrencia.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
agile-itsm
|
acfreitas
|
Java
|
Code
| 268
| 1,255
|
package br.com.centralit.citcorpore.ajaxForms;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.com.centralit.citajax.html.AjaxFormAction;
import br.com.centralit.citajax.html.DocumentHTML;
import br.com.centralit.citajax.html.HTMLForm;
import br.com.centralit.citcorpore.bean.OrigemOcorrenciaDTO;
import br.com.centralit.citcorpore.negocio.OrigemOcorrenciaService;
import br.com.centralit.citcorpore.util.WebUtil;
import br.com.citframework.service.ServiceLocator;
import br.com.citframework.util.UtilDatas;
import br.com.citframework.util.UtilI18N;
/**
* @author thiago.monteiro
*/
@SuppressWarnings("rawtypes")
public class OrigemOcorrencia extends AjaxFormAction {
@Override
public void load(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
document.focusInFirstActivateField(null);
}
@Override
public Class getBeanClass() {
return OrigemOcorrenciaDTO.class;
}
/**
* @param document
* @param request
* @param response
* @throws Exception
*/
public void save(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
OrigemOcorrenciaDTO origemOcorrenciaDTO = (OrigemOcorrenciaDTO) document.getBean();
OrigemOcorrenciaService origemOcorrenciaService = (OrigemOcorrenciaService) ServiceLocator.getInstance().getService(OrigemOcorrenciaService.class, null);
// Verifica se o DTO e o servico existem.
if (origemOcorrenciaDTO != null && origemOcorrenciaService != null) {
origemOcorrenciaDTO.setDataInicio(UtilDatas.getDataAtual() );
// Inserir
if (origemOcorrenciaDTO.getIdOrigemOcorrencia() == null) {
origemOcorrenciaService.create(origemOcorrenciaDTO);
document.alert(UtilI18N.internacionaliza(request, "MSG05") );
} else {
// Atualiar
origemOcorrenciaService.update(origemOcorrenciaDTO);
document.alert(UtilI18N.internacionaliza(request, "MSG06") );
}
HTMLForm form = document.getForm("formOrigemOcorrencia");
form.clear();
}
}
/**
* @param document
* @param request
* @param response
* @throws Exception
*/
public void delete(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
OrigemOcorrenciaDTO origemOcorrenciaDTO = (OrigemOcorrenciaDTO) document.getBean();
OrigemOcorrenciaService origemOcorrenciaService = (OrigemOcorrenciaService) ServiceLocator.getInstance().
getService(OrigemOcorrenciaService.class, WebUtil.getUsuarioSistema(request) );
if (origemOcorrenciaDTO != null && origemOcorrenciaService != null) {
if (origemOcorrenciaDTO.getIdOrigemOcorrencia() != null && (origemOcorrenciaDTO.getIdOrigemOcorrencia().intValue() > 0) ) {
origemOcorrenciaService.deletarOrigemOcorrencia(origemOcorrenciaDTO, document);
HTMLForm form = document.getForm("formOrigemOcorrencia");
form.clear();
}
}
}
/**
* @param document
* @param request
* @param response
* @throws Exception
*/
public void restore(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
OrigemOcorrenciaDTO origemOcorrenciaDTO = (OrigemOcorrenciaDTO) document.getBean();
OrigemOcorrenciaService origemOcorrenciaService = (OrigemOcorrenciaService) ServiceLocator.getInstance().
getService(OrigemOcorrenciaService.class, null);
if (origemOcorrenciaDTO != null && origemOcorrenciaService != null) {
origemOcorrenciaDTO = (OrigemOcorrenciaDTO) origemOcorrenciaService.restore(origemOcorrenciaDTO);
HTMLForm form = document.getForm("formOrigemOcorrencia");
form.clear();
form.setValues(origemOcorrenciaDTO);
}
}
}
| 32,139
|
https://github.com/offen/offen/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
Apache-2.0, LicenseRef-scancode-unknown-license-reference, MIT, CC-BY-NC-ND-4.0
| 2,023
|
offen
|
offen
|
Ignore List
|
Code
| 28
| 130
|
# Copyright 2020-2022 - Offen Authors <hioffen@posteo.de>
# SPDX-License-Identifier: Apache-2.0
node_modules/
dist/
bin/
bundle.*
package-lock.json
!*/package-lock.json
integration/cypress/screenshots
integration/cypress/videos
dependencies.csv
*.deb
*.tab
*.tar.gz
*.db
*.log
.jekyll-cache
docs-site
*.pem
*.crx
| 16,084
|
https://github.com/bellmit/ibizlab-runtime/blob/master/ibznotify/ibznotify-core/src/main/java/cn/ibizlab/core/notify/service/impl/MsgTemplateServiceImpl.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
ibizlab-runtime
|
bellmit
|
Java
|
Code
| 497
| 2,362
|
package cn.ibizlab.core.notify.service.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.math.BigInteger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import cn.ibizlab.util.errors.BadRequestAlertException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.core.notify.domain.MsgTemplate;
import cn.ibizlab.core.notify.filter.MsgTemplateSearchContext;
import cn.ibizlab.core.notify.service.IMsgTemplateService;
import cn.ibizlab.util.helper.CachedBeanCopier;
import cn.ibizlab.util.helper.DEFieldCacheMap;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.core.notify.mapper.MsgTemplateMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;
/**
* 实体[消息模板] 服务对象接口实现
*/
@Slf4j
@Service("MsgTemplateServiceImpl")
public class MsgTemplateServiceImpl extends ServiceImpl<MsgTemplateMapper, MsgTemplate> implements IMsgTemplateService {
@Autowired
@Lazy
protected cn.ibizlab.core.notify.service.IMsgOpenAccessService msgopenaccessService;
protected int batchSize = 500;
@Override
@Transactional
public boolean create(MsgTemplate et) {
fillParentData(et);
if(!this.retBool(this.baseMapper.insert(et))) {
return false;
}
CachedBeanCopier.copy(get(et.getTid()), et);
return true;
}
@Override
@Transactional
public void createBatch(List<MsgTemplate> list) {
list.forEach(item->fillParentData(item));
this.saveBatch(list, batchSize);
}
@Override
@Transactional
public boolean update(MsgTemplate et) {
fillParentData(et);
if(!update(et, (Wrapper) et.getUpdateWrapper(true).eq("tid", et.getTid()))) {
return false;
}
CachedBeanCopier.copy(get(et.getTid()), et);
return true;
}
@Override
@Transactional
public void updateBatch(List<MsgTemplate> list) {
list.forEach(item->fillParentData(item));
updateBatchById(list, batchSize);
}
@Override
@Transactional
public boolean remove(String key) {
boolean result = removeById(key);
return result ;
}
@Override
@Transactional
public void removeBatch(Collection<String> idList) {
removeByIds(idList);
}
@Override
@Transactional
public MsgTemplate get(String key) {
MsgTemplate et = getById(key);
if (et == null) {
throw new BadRequestAlertException("数据不存在", this.getClass().getSimpleName(), key);
}
else {
}
return et;
}
@Override
public MsgTemplate getDraft(MsgTemplate et) {
fillParentData(et);
return et;
}
@Override
public boolean checkKey(MsgTemplate et) {
return (!ObjectUtils.isEmpty(et.getTid())) && (!Objects.isNull(this.getById(et.getTid())));
}
@Override
@Transactional
public boolean save(MsgTemplate et) {
if(!saveOrUpdate(et)) {
return false;
}
return true;
}
@Override
@Transactional
public boolean saveOrUpdate(MsgTemplate et) {
if (null == et) {
return false;
} else {
return checkKey(et) ? getProxyService().update(et) : getProxyService().create(et);
}
}
@Override
@Transactional
public boolean saveBatch(Collection<MsgTemplate> list) {
list.forEach(item->fillParentData(item));
List<MsgTemplate> create = new ArrayList<>();
List<MsgTemplate> update = new ArrayList<>();
for (MsgTemplate et : list) {
if (ObjectUtils.isEmpty(et.getTid()) || ObjectUtils.isEmpty(getById(et.getTid()))) {
create.add(et);
} else {
update.add(et);
}
}
if (create.size() > 0) {
getProxyService().createBatch(create);
}
if (update.size() > 0) {
getProxyService().updateBatch(update);
}
return true;
}
@Override
@Transactional
public void saveBatch(List<MsgTemplate> list) {
list.forEach(item->fillParentData(item));
List<MsgTemplate> create = new ArrayList<>();
List<MsgTemplate> update = new ArrayList<>();
for (MsgTemplate et : list) {
if (ObjectUtils.isEmpty(et.getTid()) || ObjectUtils.isEmpty(getById(et.getTid()))) {
create.add(et);
} else {
update.add(et);
}
}
if (create.size() > 0) {
getProxyService().createBatch(create);
}
if (update.size() > 0) {
getProxyService().updateBatch(update);
}
}
@Override
public List<MsgTemplate> selectByAccessId(String id) {
return baseMapper.selectByAccessId(id);
}
@Override
public void removeByAccessId(String id) {
this.remove(new QueryWrapper<MsgTemplate>().eq("accessid",id));
}
/**
* 查询集合 DEFAULT
*/
@Override
public Page<MsgTemplate> searchDefault(MsgTemplateSearchContext context) {
com.baomidou.mybatisplus.extension.plugins.pagination.Page<MsgTemplate> pages=baseMapper.searchDefault(context.getPages(),context,context.getSelectCond());
return new PageImpl<MsgTemplate>(pages.getRecords(), context.getPageable(), pages.getTotal());
}
/**
* 为当前实体填充父数据(外键值文本、外键值附加数据)
* @param et
*/
private void fillParentData(MsgTemplate et){
//实体关系[DER1N_MSG_TEMPLATE_MSG_OPEN_ACCESS_ACCESSID]
if(!ObjectUtils.isEmpty(et.getAccessId())){
cn.ibizlab.core.notify.domain.MsgOpenAccess openaccess=et.getOpenaccess();
if(ObjectUtils.isEmpty(openaccess)){
cn.ibizlab.core.notify.domain.MsgOpenAccess majorEntity=msgopenaccessService.get(et.getAccessId());
et.setOpenaccess(majorEntity);
openaccess=majorEntity;
}
et.setAccessName(openaccess.getName());
et.setOpenType(openaccess.getOpenType());
}
}
@Override
public List<JSONObject> select(String sql, Map param){
return this.baseMapper.selectBySQL(sql,param);
}
@Override
@Transactional
public boolean execute(String sql , Map param){
if (sql == null || sql.isEmpty()) {
return false;
}
if (sql.toLowerCase().trim().startsWith("insert")) {
return this.baseMapper.insertBySQL(sql,param);
}
if (sql.toLowerCase().trim().startsWith("update")) {
return this.baseMapper.updateBySQL(sql,param);
}
if (sql.toLowerCase().trim().startsWith("delete")) {
return this.baseMapper.deleteBySQL(sql,param);
}
log.warn("暂未支持的SQL语法");
return true;
}
public IMsgTemplateService getProxyService() {
return cn.ibizlab.util.security.SpringContextHolder.getBean(this.getClass());
}
}
| 7,057
|
https://github.com/avinaba/affectiva-invision-demo/blob/master/nullaffdex-worker.js
|
Github Open Source
|
Open Source
|
MIT
| null |
affectiva-invision-demo
|
avinaba
|
JavaScript
|
Code
| 710
| 2,372
|
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
addEventListener("message", function(evt) {
if (evt.data && evt.data.message) {
var message = evt.data.message;
switch(message) {
case "ctor":
ctor(evt.data.url);
break;
case "process":
processImg(evt.data.img, evt.data.time);
break;
case "start":
start(evt.data);
break;
case "reset":
reset();
break;
case "stop":
stop();
break;
}
}
});
var Module = null;
var detector = null;
var imgPtr = null;
var frame = null;
var staticMode = false;
var emotions = null;
var expressions = null;
var appearance = null;
var detectEmojis = false;
var emojis = [ "relaxed", "smiley", "laughing", "kissing", "disappointed",
"rage", "smirk", "wink", "stuckOutTongueWinkingEye", "stuckOutTongue",
"flushed", "scream", "dominantEmoji"];
function ctor(url) {
try {
Module = Module || {
"memoryInitializerPrefixURL": url,
"filePackagePrefixURL": url
};
importScripts(url + "affdex-native-bindings.asm.js");
importScripts(url + "affdex-native-bindings.js");
Module.onLoaded = function() {
postMessage({ "message": "ready", "status": true });
};
}
catch(err) {
postMessage({ "message": "ready", "status": false, "detail": err });
}
}
function reset() {
try {
if (detector) {
detector.reset();
postMessage({"message":"reset", "status": true});
}
}
catch(err) {
postMessage({"message": "reset", "status": false, "detail": err});
}
}
function stop() {
try {
if (detector) {
detector.stop();
detector.delete();
if(imgPtr) {
frame.delete();
Module._free(imgPtr);
}
self.close();
postMessage({"message":"stopped", "status": true});
}
}
catch(err) {
postMessage({"message": "stopped", "status": false, "detail": err});
}
}
function start(data) {
try
{
staticMode = data.staticMode;
if (staticMode) {
detector = new Module.PhotoDetector(data.faceMode);
}
else {
detector = new Module.FrameDetector(data.processFPS, data.faceMode);
}
expressions = data.metrics.expressions;
emotions = data.metrics.emotions;
appearance = data.metrics.appearance;
detectEmojis = data.detectEmojis;
//Initialize the metrics to use
for (var metricClass in data.metrics) {
for (var indx in data.metrics[metricClass]) {
var metric = data.metrics[metricClass][indx];
detector["setDetect"+metric.capitalize()](true);
}
}
if(detectEmojis) {
detector.setDetectAllEmojis(true);
}
detector.start();
}
catch (e) {
postMessage({"message":"started", "status": false, "detail": e});
}
postMessage({"message":"started", "status": true});
}
function processImg(img, timeStamp) {
try {
if(imgPtr === null) {
var numBytes = img.width * img.height * 4;
imgPtr = Module._malloc(numBytes);
frame = new Module.Frame();
}
Module.HEAP8.set(img.data, imgPtr);
frame.init(img.width, img.height, imgPtr, Module.COLOR_FORMAT.RGBA, Module.ROTATION.UPRIGHT, timeStamp);
var message = {"message":"results", "img": img, "time": timeStamp, "status": true};
var faces = detector.process(frame);
if(imgPtr && staticMode) {
frame.delete();
Module._free(imgPtr);
imgPtr = null;
frame = null;
}
metrics = ["emotions", "expressions", "emojis"];
message.faces = [];
for (var indx = 0 ; indx < faces.size() ; indx++) {
var face = faces.get(indx);
data = {};
for (var j = 0; j < metrics.length; j++) {
data[metrics[j]] = {};
this[metrics[j]].forEach( function(val, indx) {
data[metrics[j]][val] = face[metrics[j]][val];
});
}
data.emojis.dominantEmoji = emojiUnicode(face.emojis.dominantEmoji);
data.appearance = {};
appearance.forEach( function(val, idx) {
data.appearance[val] = this[val+"Str"].call(null, face.appearance[val]);
});
data.measurements = {
"interocularDistance": face.measurements.interocularDistance,
"orientation": {
"pitch": face.measurements.orientation.pitch,
"yaw": face.measurements.orientation.yaw,
"roll": face.measurements.orientation.roll
}
};
data.featurePoints = {};
var featurePoints = face.featurePoints;
var featurePointsSize = face.featurePoints.size();
for (i=0; i < featurePointsSize; i++) {
data.featurePoints[i] = {
"x": face.featurePoints.get(i).x,
"y": face.featurePoints.get(i).y
};
}
featurePoints.delete();
message.faces.push(data);
}
postMessage(message);
}
catch(err) {
var msg = "worker code reported an exception" + err;
postMessage({"message": "results", "status": false,
"img": img, "time": timeStamp, "detail": msg});
}
}
function emojiUnicode(e) {
var ret = '';
if (e) {
ret = String.fromCodePoint(e.value);
}
return ret;
}
function genderStr(g) {
var ret = '';
if (Module.Gender) {
if (g.value == Module.Gender.Female.value) ret = "Female";
else if (g.value == Module.Gender.Male.value) ret = "Male";
else if (g.value == Module.Gender.Unknown.value) ret = "Unknown";
}
return ret;
}
function ethnicityStr(g) {
var ret = '';
if (Module.Ethnicity) {
if (g.value == Module.Ethnicity.CAUCASIAN.value) ret = "Caucasian";
else if (g.value == Module.Ethnicity.BLACK_AFRICAN.value) ret = "Black African";
else if (g.value == Module.Ethnicity.SOUTH_ASIAN.value) ret = "South Asian";
else if (g.value == Module.Ethnicity.EAST_ASIAN.value) ret = "East Asian";
else if (g.value == Module.Ethnicity.HISPANIC.value) ret = "Hispanic";
else if (g.value == Module.Ethnicity.UNKNOWN.value) ret = "Unknown";
}
return ret;
}
function ageStr(g) {
var ret = '';
if (Module.Age) {
if (g.value == Module.Age.AGE_UNKNOWN.value) ret = "Unknown";
else if (g.value == Module.Age.AGE_UNDER_18.value) ret = "Under 18";
else if (g.value == Module.Age.AGE_18_24.value) ret = "18 - 24";
else if (g.value == Module.Age.AGE_25_34.value) ret = "25 - 34";
else if (g.value == Module.Age.AGE_35_44.value) ret = "35 - 44";
else if (g.value == Module.Age.AGE_45_54.value) ret = "45 - 54";
else if (g.value == Module.Age.AGE_55_64.value) ret = "55 - 64";
else if (g.value == Module.Age.AGE_65_PLUS.value) ret = "65+";
}
return ret;
}
function glassesStr(g) {
var ret = '';
if (Module.Glasses) {
if (g.value == Module.Glasses.No.value) ret = "No";
else if (g.value == Module.Glasses.Yes.value) ret = "Yes";
}
return ret;
}
| 43,363
|
https://github.com/sho25/karaf/blob/master/features/core/src/main/java/org/apache/karaf/features/internal/model/Scoping.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
karaf
|
sho25
|
Java
|
Code
| 415
| 1,449
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|karaf
operator|.
name|features
operator|.
name|internal
operator|.
name|model
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|ArrayList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|bind
operator|.
name|annotation
operator|.
name|XmlAccessType
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|bind
operator|.
name|annotation
operator|.
name|XmlAccessorType
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|bind
operator|.
name|annotation
operator|.
name|XmlAttribute
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|bind
operator|.
name|annotation
operator|.
name|XmlElement
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|bind
operator|.
name|annotation
operator|.
name|XmlType
import|;
end_import
begin_class
annotation|@
name|XmlAccessorType
argument_list|(
name|XmlAccessType
operator|.
name|FIELD
argument_list|)
annotation|@
name|XmlType
argument_list|(
name|name
operator|=
literal|"scoping"
argument_list|,
name|propOrder
operator|=
block|{
literal|"imports"
block|,
literal|"exports"
block|}
argument_list|)
specifier|public
class|class
name|Scoping
implements|implements
name|org
operator|.
name|apache
operator|.
name|karaf
operator|.
name|features
operator|.
name|Scoping
block|{
annotation|@
name|XmlAttribute
name|boolean
name|acceptDependencies
decl_stmt|;
annotation|@
name|XmlElement
argument_list|(
name|name
operator|=
literal|"import"
argument_list|)
name|List
argument_list|<
name|ScopeFilter
argument_list|>
name|imports
decl_stmt|;
annotation|@
name|XmlElement
argument_list|(
name|name
operator|=
literal|"export"
argument_list|)
name|List
argument_list|<
name|ScopeFilter
argument_list|>
name|exports
decl_stmt|;
specifier|public
name|List
argument_list|<
name|ScopeFilter
argument_list|>
name|getImport
parameter_list|()
block|{
if|if
condition|(
name|imports
operator|==
literal|null
condition|)
block|{
name|imports
operator|=
operator|new
name|ArrayList
argument_list|<>
argument_list|()
expr_stmt|;
block|}
return|return
name|imports
return|;
block|}
specifier|public
name|List
argument_list|<
name|ScopeFilter
argument_list|>
name|getExport
parameter_list|()
block|{
if|if
condition|(
name|exports
operator|==
literal|null
condition|)
block|{
name|exports
operator|=
operator|new
name|ArrayList
argument_list|<>
argument_list|()
expr_stmt|;
block|}
return|return
name|exports
return|;
block|}
annotation|@
name|Override
specifier|public
name|boolean
name|acceptDependencies
parameter_list|()
block|{
return|return
name|acceptDependencies
return|;
block|}
annotation|@
name|Override
specifier|public
name|List
argument_list|<
name|?
extends|extends
name|org
operator|.
name|apache
operator|.
name|karaf
operator|.
name|features
operator|.
name|ScopeFilter
argument_list|>
name|getImports
parameter_list|()
block|{
return|return
name|getImport
argument_list|()
return|;
block|}
annotation|@
name|Override
specifier|public
name|List
argument_list|<
name|?
extends|extends
name|org
operator|.
name|apache
operator|.
name|karaf
operator|.
name|features
operator|.
name|ScopeFilter
argument_list|>
name|getExports
parameter_list|()
block|{
return|return
name|getExport
argument_list|()
return|;
block|}
block|}
end_class
end_unit
| 37,267
|
https://github.com/melissawm/napari.github.io/blob/master/theme/src/components/media.tsx
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
napari.github.io
|
melissawm
|
TypeScript
|
Code
| 98
| 184
|
import { createMedia } from '@artsy/fresnel';
import { breakpoints } from '@/theme';
const AppMedia = createMedia({ breakpoints });
/**
* Styles for SSG.
*/
export const mediaStyles = AppMedia.createMediaStyle();
export const {
/**
* This component provides an easy-to-use API for responding to media
* queries. This adds a wrapper div over the component with fresnel CSS
* classes to respond to media queries.
*
* If you don't need the wrapper div, use the MediaFragment component
* instead.
*/
Media,
/**
* This provides context data related to the media query component.
*/
MediaContextProvider,
} = AppMedia;
| 6,217
|
https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/master/internal/aws/k8s/k8sclient/node_info.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
opentelemetry-collector-contrib
|
open-telemetry
|
Go
|
Code
| 34
| 133
|
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package k8sclient // import "github.com/open-telemetry/opentelemetry-collector-contrib/internal/aws/k8s/k8sclient"
import (
v1 "k8s.io/api/core/v1"
)
type nodeInfo struct {
conditions []*nodeCondition
}
type nodeCondition struct {
Type v1.NodeConditionType
Status v1.ConditionStatus
}
| 49,563
|
https://github.com/ExperitestOfficial/ng2-smart-table/blob/master/projects/ng2-smart-table/src/lib/components/cell/cell-edit-mode/default-edit.component.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
ng2-smart-table
|
ExperitestOfficial
|
TypeScript
|
Code
| 42
| 143
|
import {Component} from '@angular/core';
import {EditCellDefault} from './edit-cell-default';
@Component({
selector: 'table-cell-default-editor',
templateUrl: './default-edit.component.html',
})
export class DefaultEditComponent<T extends object, C, D extends keyof T> extends EditCellDefault<T, C, D> {
constructor() {
super();
}
getEditorType(): string {
return this.cell.getColumn().editor && this.cell.getColumn().editor.type;
}
}
| 23,822
|
https://github.com/stainless-steel/mcpat-sys/blob/master/build/wrapper/processor.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
mcpat-sys
|
stainless-steel
|
C
|
Code
| 53
| 263
|
#ifndef __WRAPPER_PROCESSOR_H__
#define __WRAPPER_PROCESSOR_H__
#include <wrapper/XML_Parse.h>
#include <wrapper/cacti/component.h>
#include <wrapper/sharedcache.h>
extern "C" {
typedef struct Processor_t;
Processor_t *new_Processor(ParseXML_t *XML_interface);
void delete_Processor(Processor_t *);
Core_t *Processor_cores(Processor_t *, int);
SharedCache_t *Processor_l3array(Processor_t *, int);
Component_t *Processor_l3(Processor_t *);
int Processor_numCore(Processor_t *);
int Processor_numL2(Processor_t *);
int Processor_numL3(Processor_t *);
int Processor_numNOC(Processor_t *);
int Processor_numL1Dir(Processor_t *);
int Processor_numL2Dir(Processor_t *);
}
#endif
| 34,342
|
https://github.com/kencharos/yakimashi/blob/master/app/models/Models.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,013
|
yakimashi
|
kencharos
|
Scala
|
Code
| 169
| 589
|
package models
import play.api.Play.current
import com.novus.salat._
import com.novus.salat.annotations._
import com.novus.salat.dao._
import com.mongodb.casbah.Imports._
import se.radley.plugin.salat._
import com.mongodb.casbah.commons.MongoDBObject
import mongoContext._
object Label extends ModelCompanion[Label, String] {
val dao = new SalatDAO[Label, String](collection = mongoCollection("label")) {}
def findSortedAll = findAll.toList.sortBy(_.id);
def updateName(label:Label) = dao.update(MongoDBObject("_id" -> label.id),
MongoDBObject("name" -> label.name), false, false)
}
object Photo extends ModelCompanion[Photo, ObjectId] {
val dao = new SalatDAO[Photo, ObjectId](collection = mongoCollection("photo")) {}
def findOneByName(album:String, name:String) = dao.findOne(
MongoDBObject("album" -> album, "name" -> name))
def findByLabel(album:String, label:String) = dao.find(
MongoDBObject("album" -> album, "noDisp" -> false, "labels" -> label))
.sort(MongoDBObject("name" -> 1))
.toList
def uniqueIndex() = mongoCollection("photo").ensureIndex(
MongoDBObject("album" -> 1, "name" -> 1), MongoDBObject("unique" -> true))
}
object User extends ModelCompanion[User, String] {
val dao = new SalatDAO[User, String](collection = mongoCollection("user")) {}
}
case class User(@(Key)("_id")user:String, passwordHash:String)
case class Photo(@Key("_id")id:ObjectId = new ObjectId,
album:String,
name:String,
labels:Seq[String] = Seq(),
etc:Int = 0,
comment:String = "",
noDisp:Boolean = false) {
def count = labels.size + etc
def url = "album/" + album + "/" + name
}
case class Label(@Key("_id")id:String, name:String);
| 45,980
|
https://github.com/kamyu104/LeetCode-Solutions/blob/master/C++/binary-tree-paths.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
LeetCode-Solutions
|
kamyu104
|
C++
|
Code
| 113
| 380
|
// Time: O(n * h)
// Space: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<TreeNode *> path;
binaryTreePathsRecu(root, &path, &result);
return result;
}
void binaryTreePathsRecu(TreeNode *node, vector<TreeNode *> *path, vector<string> *result) {
if (!node) {
return;
}
if (!node->left && !node->right) {
string ans = "";
for (const auto& n : *path) {
ans.append(to_string(n->val).append("->"));
}
result->emplace_back(move(ans.append(to_string(node->val))));
}
if (node->left) {
path->emplace_back(node);
binaryTreePathsRecu(node->left, path, result);
path->pop_back();
}
if (node->right) {
path->emplace_back(node);
binaryTreePathsRecu(node->right, path, result);
path->pop_back();
}
}
};
| 48,225
|
https://github.com/ColuLocalNetwork/CLN-community-app/blob/master/dapp/src/services/api/business.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
CLN-community-app
|
ColuLocalNetwork
|
JavaScript
|
Code
| 32
| 113
|
import request from 'superagent'
export const fetchBusinesses = (apiRoot, { listAddress, page }) =>
request.get(`${apiRoot}/businesses/${listAddress}?page=${page}`)
.then(response => response.body)
export const fetchBusiness = (apiRoot, { listAddress, hash }) =>
request.get(`${apiRoot}/businesses/${listAddress}/${hash}`)
.then(response => response.body)
| 47,307
|
https://github.com/exced/hermes/blob/master/external/esprima/test_fixtures/invalid-syntax/migrated_0278.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
hermes
|
exced
|
JavaScript
|
Code
| 4
| 11
|
class A {static [static](){};}
| 20,996
|
https://github.com/TwinDots/email-service/blob/master/src/Services/EmailService.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
email-service
|
TwinDots
|
PHP
|
Code
| 391
| 1,071
|
<?php
namespace TwinDots\EmailService\Services;
use Exception;
use \Illuminate\Support\Facades\Mail;
use TwinDots\EmailService\Mail\EmailTemplate;
class EmailService
{
/**
* Recipient email
* @var array|string
*/
protected string|array $email = '';
/**
* CC
* @var array|string
*/
protected string|array $cc = '';
/**
* BCC
* @var array|string
*/
protected string|array $bcc = '';
/**
* Reply to email
* @var string
*/
protected string $replyTo = '';
/**
* Email subject
* @var string
*/
protected string $subject = '';
/**
* Email body
* @var string
*/
protected string $body = '';
/**
* Email attachments
* @var array
*/
protected array $attachments = [];
/**
* EmailService constructor.
* @param array|string|null $email
* @param string|null $subject
* @param string|null $body
*/
public function __construct($email = null, $subject = null, $body = null)
{
if( $email )
$this->email($email);
if( $subject )
$this->subject($subject);
if( $body )
$this->body($body);
}
/**
* Set the recipients emails.
* @param array|string $email
* @return EmailService
*/
public function email(array|string $email): static
{
$this->email = $email;
return $this;
}
/**
* Set the cc emails.
* @param array|string $cc
* @return EmailService
*/
public function cc(array|string $cc): static
{
$this->cc = $cc;
return $this;
}
/**
* Set the bcc emails.
* @param array|string $bcc
* @return EmailService
*/
public function bcc(array|string $bcc): static
{
$this->bcc = $bcc;
return $this;
}
/**
* Set the reply to email.
* @param string $replyTo
* @return EmailService
*/
public function replyTo(string $replyTo): static
{
$this->replyTo = $replyTo;
return $this;
}
/**
* Set the email subject.
* @param string $subject
* @return EmailService
*/
public function subject(string $subject): static
{
$this->subject = $subject;
return $this;
}
/**
* Set the email body.
* @param string $body
* @return EmailService
*/
public function body(string $body): static
{
$this->body = $body;
return $this;
}
/**
* Set the email attachments.
* @param array['attachment_name' => 'attachment_path'] $attachments
* @return EmailService
*/
public function attach(array $attachments): static
{
$this->attachments = $attachments;
return $this;
}
/**
* Send email
* @return array
*/
public function send(): array
{
try {
$mail = Mail::to($this->email);
if( $this->cc )
$mail = $mail->cc($this->cc);
if( $this->bcc )
$mail = $mail->bcc($this->bcc);
$mail->send(
new EmailTemplate(
$this->subject,
$this->body,
$this->attachments,
$this->replyTo
)
);
return [
'sent' => true,
];
} catch (Exception $e) {
return [
'sent' => false,
'message' => $e->getMessage()
];
}
}
}
| 23,054
|
https://github.com/LaTueur/reddit-detective/blob/master/tests/test_data_models.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
reddit-detective
|
LaTueur
|
Python
|
Code
| 250
| 835
|
from reddit_detective.data_models import Comment, Submission, Subreddit, Redditor
from tests import api_
"""
Testing the basic properties/methods of data models and abstract classes
"""
def test_subreddit():
sub = Subreddit(api_, "learnpython", limit=100)
assert sub.data["created_utc"]
assert sub.main_type in sub.types
assert sub.properties["created_utc"]
assert sub.submissions() is not None
assert sub.subscribers is not None # it might be zero, 0 gives AssertionError
def test_submission():
sub = Submission(api_, "jhd0px", limit=100)
assert sub.data["created_utc"]
assert sub.main_type in sub.types
assert sub.properties["created_utc"]
assert isinstance(sub.subreddit, Subreddit)
assert sub.comments() is not None
assert sub.score is not None
assert sub.upvote_ratio is not None
assert sub.author_accessible, "Submission has no accessible author."
assert isinstance(sub.author, Redditor)
def test_redditor():
red = Redditor(api_, "Anub_Rekhan", limit=100)
red_susp = Redditor(api_, "deleted", limit=100)
assert red.data["created_utc"]
assert red.main_type in red.types
assert red.properties["created_utc"]
assert red.submissions() is not None
assert red.comments() is not None
assert red.link_karma is not None
assert red.comment_karma is not None
assert "Suspended" in red_susp.types
assert red_susp.comments() == []
assert red_susp.submissions() == []
def test_comment():
cd = Comment(api_, "ga5umu3")
cd_by_deleted = Comment(api_, "fo2ap22")
assert cd.properties["text"]
assert isinstance(cd.submission, Submission)
assert cd.replies() is not None
assert cd.score is not None
assert cd.author_accessible, "Comment has no accessible author."
assert isinstance(cd.author, Redditor)
assert not cd_by_deleted.author_accessible
def test_cypher_codes_node():
sub = Subreddit(api_, "learnpython", limit=100)
assert sub.types_code()
assert sub.types[0] in sub.types_code()
assert ":" in sub.types_code()
assert sub.props_code()
assert sub.properties["id"] in sub.props_code()
assert ":" in sub.props_code()
assert "{" in sub.props_code() and "}" in sub.props_code()
assert sub.merge_code()
assert "MERGE" in sub.merge_code()
assert sub.types_code() in sub.merge_code()
assert sub.props_code() in sub.merge_code()
def run():
test_subreddit()
test_submission()
test_redditor()
test_comment()
test_cypher_codes_node()
if __name__ == '__main__':
run()
| 2,046
|
https://github.com/RAnLabNL/RAnLab-frontend/blob/master/store/reducers/business.tsx
|
Github Open Source
|
Open Source
|
RSA-MD
| null |
RAnLab-frontend
|
RAnLabNL
|
TypeScript
|
Code
| 122
| 547
|
import { getNewBusinesses } from '../helpers/business';
import {
ADD_BUSINESS_BY_REGION_ID_SUCCESS,
ADD_BUSINESS_BY_REGION_ID_STARTED,
ADD_BUSINESS_BY_REGION_ID_FAILURE,
FETCH_BUSINESSES_BY_REGION_ID_SUCCESS,
FETCH_BUSINESSES_BY_REGION_ID_STARTED,
FETCH_BUSINESSES_BY_REGION_ID_FAILURE,
BusinessActionTypes,
BusinessState,
} from '../types/business';
const initialState: BusinessState = {
error: null,
loading: false,
businesses: {},
};
const businessReducer = (
state = initialState,
action: BusinessActionTypes
): BusinessState => {
const prevBusinesses = state.businesses ? state.businesses : {};
switch (action.type) {
case ADD_BUSINESS_BY_REGION_ID_STARTED:
case FETCH_BUSINESSES_BY_REGION_ID_STARTED:
return {
...state,
loading: true,
};
case ADD_BUSINESS_BY_REGION_ID_FAILURE:
case FETCH_BUSINESSES_BY_REGION_ID_FAILURE:
return {
...state,
loading: false,
error: action.payload.error,
};
case ADD_BUSINESS_BY_REGION_ID_SUCCESS:
return {
...state,
loading: false,
error: null,
businesses: getNewBusinesses(
prevBusinesses,
action.payload.regionId,
action.payload.business,
),
};
case FETCH_BUSINESSES_BY_REGION_ID_SUCCESS:
return {
...state,
loading: false,
error: null,
businesses: {
...prevBusinesses,
[action.payload.regionId]: {
businesses: action.payload.businesses,
filters: action.payload.filters,
},
},
};
default:
return state;
}
};
export default businessReducer;
| 28,866
|
https://github.com/kreghek/Zilon_Roguelike/blob/master/Zilon.Core/Zilon.Core/PersonModules/IPersonExtensions.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Zilon_Roguelike
|
kreghek
|
C#
|
Code
| 92
| 314
|
using System;
using Zilon.Core.Persons;
namespace Zilon.Core.PersonModules
{
public static class IPersonExtensions
{
public static TPersonModule GetModule<TPersonModule>(this IPerson person) where TPersonModule : IPersonModule
{
if (person is null)
{
throw new ArgumentNullException(nameof(person));
}
return person.GetModule<TPersonModule>(typeof(TPersonModule).Name);
}
public static TPersonModule? GetModuleSafe<TPersonModule>(this IPerson source)
where TPersonModule : IPersonModule
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
if (!source.HasModule<TPersonModule>())
{
return default;
}
return source.GetModule<TPersonModule>();
}
/// <inheritdoc />
public static bool HasModule<TPersonModule>(this IPerson person) where TPersonModule : IPersonModule
{
if (person is null)
{
throw new ArgumentNullException(nameof(person));
}
return person.HasModule(typeof(TPersonModule).Name);
}
}
}
| 44,482
|
https://github.com/aalleavitch/react-storefront/blob/master/packages/react-storefront/test/TabsRow.test.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
react-storefront
|
aalleavitch
|
JavaScript
|
Code
| 145
| 446
|
import React from 'react';
import TabsRow from '../src/TabsRow'
import { mount } from 'enzyme'
import TestProvider from './TestProvider'
describe('TabsRow', () => {
describe('render', () => {
it('should render tabs with images', () => {
expect(mount(
<TestProvider>
<TabsRow
items={[
{ imageUrl: 'https://example.com' },
{ imageUrl: 'https://example.com' }
]}
/>
</TestProvider>
)).toMatchSnapshot()
})
it('should render tabs with text', () => {
expect(mount(
<TestProvider>
<TabsRow
items={[
{ text: 'Tab 1' },
{ text: 'Tab 2' }
]}
/>
</TestProvider>
)).toMatchSnapshot()
})
it('should render tabs with urls', () => {
expect(mount(
<TestProvider>
<TabsRow
items={[
{ text: 'Tab 1', url: 'https://www.example.com' },
{ text: 'Tab 2', url: 'https://www.example.com' }
]}
/>
</TestProvider>
)).toMatchSnapshot()
})
it('should render in amp', () => {
expect(mount(
<TestProvider app={{ amp: true }}>
<TabsRow
items={[
{ text: 'Tab 1', url: 'https://www.example.com' },
{ text: 'Tab 2', url: 'https://www.example.com' }
]}
/>
</TestProvider>
)).toMatchSnapshot()
})
})
})
| 43,423
|
https://github.com/rhernandez90/MenuCategoryApp/blob/master/src/app/pages/account/register/register.component.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
MenuCategoryApp
|
rhernandez90
|
TypeScript
|
Code
| 179
| 665
|
import { Component, OnInit } from '@angular/core';
import { RegisterUserDto } from '../../../Services/authentication/Dto/RegisterUserDto';
import { LoginService } from '../../../Services/authentication/login/login.service';
import Swal from 'sweetalert2'
import { ActivatedRoute, Router } from '@angular/router';
import { UserService } from '../../../Services/User/user.service';
@Component({
selector: 'ngx-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
user: RegisterUserDto;
saveButtonTitle = "Register";
updating = false;
constructor(
private _loginService: LoginService,
private _userService: UserService,
private router: Router,
private route: ActivatedRoute
) {
}
ngOnInit(): void {
this.user = new RegisterUserDto();
this.route.paramMap.subscribe(params => {
if (params['params'].id) {
this.loadUser(params['params'].id);
this.saveButtonTitle = "Update";
this.updating = true;
}
});
}
loadUser(id: string) {
this._userService.GetById(id).subscribe(res => {
this.user.id = id;
this.user.username = res.username;
this.user.email = res.email;
this.user.role = res.roles;
this.user.password = res.password;
})
}
cancel() {
this.router.navigate(['/pages/users'])
}
onSubmit(): void {
if (this.updating)
this.update();
else
this.save()
}
save(){
this._loginService.register(this.user).subscribe(res => {
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'User has been saved',
showConfirmButton: false,
timer: 7000
})
this.router.navigate(['/pages/users'])
})
}
update() {
this._userService.Update(this.user).subscribe(res => {
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'User has been saved',
showConfirmButton: false,
timer: 7000
})
this.router.navigate(['/pages/users'])
})
}
}
| 43,704
|
https://github.com/nadirlatif532/brighto-npx/blob/master/src/app/views/project/project.module.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
brighto-npx
|
nadirlatif532
|
TypeScript
|
Code
| 85
| 238
|
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ProjectComponent } from './component/project/project.component';
import { FormsModule } from '@angular/forms';
import { ProjectRoutingModule } from './project-routing.module';
import { TableModule } from 'primeng/table';
import { DialogModule } from 'primeng/dialog';
import { ButtonModule } from 'primeng/button';
import { ColorPickerModule } from 'primeng/colorpicker';
import { KeyFilterModule } from 'primeng/keyfilter';
import {FileUploadModule} from 'primeng/fileupload';
@NgModule({
declarations: [ProjectComponent],
imports: [
CommonModule,
FormsModule,
ProjectRoutingModule,
TableModule,
DialogModule,
ButtonModule,
ColorPickerModule,
KeyFilterModule,
FileUploadModule
]
})
export class ProjectModule { }
| 27,596
|
https://github.com/mehdilaktaf/epimovies-server/blob/master/routes/auth.js
|
Github Open Source
|
Open Source
|
MIT
| null |
epimovies-server
|
mehdilaktaf
|
JavaScript
|
Code
| 102
| 262
|
const Router = require('express-promise-router')
const { verifySignUp } = require("../middleware");
const settings = require('../settings');
const controller = require("../controllers/auth.controller");
// create a new express-promise-router
// this has the same API as the normal express router except
// it allows you to use async functions as route handlers
const router = new Router()
// export our router to be mounted by the parent application
module.exports = router
// ROUTES //
router.use(function(req, res, next) {
res.header(
"Access-Control-Allow-Headers",
"x-access-token, Origin, Content-Type, Accept"
);
next();
});
// create a user profile
router.post(
"/signup",
[
verifySignUp.checkDuplicateUsernameOrEmail,
verifySignUp.checkRolesExisted
],
controller.signup
);
// connect to a user profile
router.post("/signin", controller.signin);
| 28,375
|
https://github.com/aungkhanthtoo/PagingHelper/blob/master/app/src/main/java/com/dev/droid/data/persistence/AppDatabase.kt
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
PagingHelper
|
aungkhanthtoo
|
Kotlin
|
Code
| 52
| 184
|
package com.dev.droid.data.persistence
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.dev.droid.SampleApp
import com.dev.droid.data.network.Movie
/**
* Created by A.K.HTOO on 02/07/2020,July,2020.
*/
@Database(entities = [Movie::class], version = 2)
abstract class AppDatabase : RoomDatabase() {
abstract fun movieDao(): MovieDao
companion object {
fun create(): AppDatabase {
return Room.databaseBuilder(
SampleApp.appContext,
AppDatabase::class.java, "database"
).build()
}
}
}
| 50,419
|
https://github.com/eric-xujun/Judge-at-fgdsb/blob/master/judge/build_tests/peek-iterator.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
Judge-at-fgdsb
|
eric-xujun
|
Ruby
|
Code
| 44
| 176
|
require './common'
require '../ruby/common'
class Test_peek_iterator < TestBase
def initialize(name)
@manual_test = true
super(name)
end
def add_test(arr)
@test_in[0] << arr
end
def gen_tests
@test_in, @test_out = [[]], []
20.times do
add_test gen_array(rand(1...20), 1..20)
end
30.times do
add_test gen_array(rand(1...50), 1..50)
end
end
end
Test_peek_iterator.new 'peek-iterator'
| 15,353
|
https://github.com/lymanZerga11/arbitrage_bot/blob/master/exchanges/binance.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
arbitrage_bot
|
lymanZerga11
|
C++
|
Code
| 252
| 1,223
|
#include "../utils/restapi.h"
#include "../utils/unique_json.hpp"
#include "binance.h"
#include "../symbols.h"
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <array>
#include <cmath>
#include <ctime>
std::vector<std::string> BINANCE_SYMBOLS = {
"BTCETH",
"XRPETH",
"LTCETH",
"BCCETH",
"XMRETH",
"EOSETH",
"QTUMETH",
"ETCETH",
"ZECETH",
"BTGETH",
"DASHETH",
"USDTETH",
"IOTAETH"
};
std::unordered_map<std::string, int> BINANCE_SYMBOL_MAP = {
{"BTCETH", 0},
{"XRPETH", 1},
{"LTCETH", 2},
{"BCCETH", 3},
{"XMRETH", 4},
{"EOSETH", 5},
{"QTUMETH",6},
{"ETCETH", 7},
{"ZECETH", 8},
{"BTGETH", 9},
{"DASHETH", 10},
{"USDTETH", 11},
{"IOTAETH", 12}
};
std::unordered_map<std::string, std::string> BINANCE_UNIVERSAL_SYMBOL_CORRESPONDENCE_MAP = {
{"BTC", "BTCETH"},
{"XRP", "XRPETH"},
{"LTC", "LTCETH"},
{"BCH", "BCCETH"},
{"XMR", "XMRETH"},
{"EOS", "EOSETH"},
{"QTUM", "QTUMETH"},
{"ETC", "ETCETH"},
{"ZEC", "ZECETH"},
{"BTG", "BTGETH"},
{"DASH", "DASHETH"},
{"USDT", "USDTETH"},
{"IOTA", "IOTAETH"}
};
RestApi& Binance::query_handle(std::ofstream& log_file) {
static RestApi query("https://www.binance.com", nullptr, log_file);
return query;
}
Binance::Binance (std::ofstream& _log_file) : log_file(_log_file){
symbols = BINANCE_SYMBOLS;
symbol_map = BINANCE_SYMBOL_MAP;
universal_symbol_correspondence_map = BINANCE_UNIVERSAL_SYMBOL_CORRESPONDENCE_MAP;
for(int i=0; i<BINANCE_SYMBOLS.size(); i++)
price.push_back(quote_t(std::make_pair(0, 0)));
update_quotes();
}
double Binance::get_time() const {
auto &exchange = query_handle(log_file);
std::string url;
url = "/api/v1/time";
unique_json root { exchange.get_request(url) };
double cur_time = json_integer_value(json_object_get(root.get(), "serverTime"));
return cur_time;
}
void Binance::update_quotes() {
auto &exchange = query_handle(log_file);
std::string url;
url = "/api/v3/ticker/bookTicker";
unique_json root { exchange.get_request(url) };
int quote_array_size = json_array_size(root.get());
for(int i=0; i<quote_array_size; i++) {
json_t *json_object = json_array_get(root.get(), i);
std::string symbol = json_string_value(json_object_get(json_object, "symbol"));
if(BINANCE_SYMBOL_MAP.find(symbol) == BINANCE_SYMBOL_MAP.end()) continue;
const char *quote = json_string_value(json_object_get(json_object, "bidPrice"));
double symbol_bid_price = quote ? std::stod(quote) : 0.0;
quote = json_string_value(json_object_get(json_object, "askPrice"));
double symbol_ask_price = quote ? std::stod(quote) : 0.0;
price[BINANCE_SYMBOL_MAP[symbol]] = std::make_pair(symbol_bid_price, symbol_ask_price);
}
}
const quote_t& Binance::get_quote(std::string symbol) const {
return price[BINANCE_SYMBOL_MAP[symbol]];
}
const quote_array_t& Binance::get_quote_array() const {
return price;
}
| 40,153
|
https://github.com/cuongponggon/webadmin/blob/master/src/app/models/camera.model.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
webadmin
|
cuongponggon
|
TypeScript
|
Code
| 47
| 110
|
import { Area } from './area.model';
export class Camera {
public id: number;
public ip: String;
public name: String;
public account: String;
public password: String;
public createdDate: String;
public updatedDate: String;
public status: String;
public imageUrl: String;
public updatedBy: String;
public areaID: number;
public area: Area;
}
| 6,690
|
https://github.com/schmitch/elasticsearch-net/blob/master/src/Nest/Cluster/ClusterStats/ClusterIndicesStats.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
elasticsearch-net
|
schmitch
|
C#
|
Code
| 245
| 673
|
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System.Runtime.Serialization;
namespace Nest
{
[DataContract]
public class ClusterIndicesStats
{
[DataMember(Name ="completion")]
public CompletionStats Completion { get; internal set; }
[DataMember(Name ="count")]
public long Count { get; internal set; }
[DataMember(Name ="docs")]
public DocStats Documents { get; internal set; }
[DataMember(Name ="fielddata")]
public FielddataStats Fielddata { get; internal set; }
[DataMember(Name ="query_cache")]
public QueryCacheStats QueryCache { get; internal set; }
[DataMember(Name ="segments")]
public SegmentsStats Segments { get; internal set; }
[DataMember(Name ="shards")]
public ClusterIndicesShardsStats Shards { get; internal set; }
[DataMember(Name ="store")]
public StoreStats Store { get; internal set; }
}
[DataContract]
public class ClusterIndicesShardsStats
{
[DataMember(Name ="index")]
public ClusterIndicesShardsIndexStats Index { get; internal set; }
[DataMember(Name ="primaries")]
public double Primaries { get; internal set; }
[DataMember(Name ="replication")]
public double Replication { get; internal set; }
[DataMember(Name ="total")]
public double Total { get; internal set; }
}
[DataContract]
public class ClusterIndicesShardsIndexStats
{
[DataMember(Name ="primaries")]
public ClusterShardMetrics Primaries { get; internal set; }
[DataMember(Name ="replication")]
public ClusterShardMetrics Replication { get; internal set; }
[DataMember(Name ="shards")]
public ClusterShardMetrics Shards { get; internal set; }
}
[DataContract]
public class ClusterShardMetrics
{
[DataMember(Name ="avg")]
public double Avg { get; internal set; }
[DataMember(Name ="max")]
public double Max { get; internal set; }
[DataMember(Name ="min")]
public double Min { get; internal set; }
}
}
| 8,966
|
https://github.com/ahmed-afzal1/geniusnews/blob/master/project/app/Models/Category.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
geniusnews
|
ahmed-afzal1
|
PHP
|
Code
| 79
| 356
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['language_id','title','slug','parent_id','color','category_order','show_at_homepage','show_on_menu'];
protected $table = 'categories';
public $timestamps = false;
public function parent(){
return $this->belongsTo('App\Models\Category','parent_id')->withDefault(function ($data) {
foreach($data->getFillable() as $dt){
$data[$dt] = __('Deleted');
}
});
}
public function child(){
return $this->hasMany('App\Models\Category','parent_id');
}
public function posts(){
return $this->hasMany('App\Models\Post','category_id');
}
public function subcategoryPosts(){
return $this->hasMany('App\Models\Post','subcategories_id');
}
public function language(){
return $this->belongsTo('App\Models\Language')->withDefault(function ($data) {
foreach($data->getFillable() as $dt){
$data[$dt] = __('Deleted');
}
});
}
public function rss(){
return $this->hasMany('App\Models\Rss','category_id');
}
}
| 14,799
|
https://github.com/les1smore/mlnotes/blob/master/Regression/Random Forest/Random Forest Regression Tree.r
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
mlnotes
|
les1smore
|
R
|
Code
| 211
| 521
|
# Random Forest Regression
# Importing the dataset
dataset = read.csv('Position_Salaries.csv')
dataset = dataset[2:3] # Select the second column "Level" and the third column "Salary" only
# Splitting the data set into the Training set and Test set
#library(caTools)
#set.seed(123)
#split = sample.split(dataset$Profit, SplitRatio = 0.8)
#training_set = subset(dataset, split == TRUE)
#test_set = subset(dataset, split == FALSE)
# Feature Scaling
# training_set = scale(training_set)
# test_set = scale(test_set)
# Fitting the Random Forest Regression Model to the dataset
install.packages('randomForest')
library(randomForest)
set.seed(1234) # equals to random_state = 0
regressor = randomForest(x = dataset[1],
y = dataset$Salary,
ntree = 500)# dataset[1] will result in a dataframe, dataset$Salary will result in a vector
# Predicting a new result with Random Forest Regression
y_pred = predict(regressor, data.frame(Level = 6.5)) # make sure the 6.5 value showed in dataframe
# Visualizing the Random Forest Regression results (for higher resolution ans smoother curve)
# Non-linear and Non-continuous Regression Model
# install.packages('ggplot2')
library(ggplot2)
x_grid = seq(min(dataset$Level), max(dataset$Level), 0.01) # from 1-10 incremented by 0.01
ggplot() +
geom_point(aes(x = dataset$Level, y = dataset$Salary),
color = 'red') +
geom_line(aes(x = x_grid, y = predict(regressor, newdata = data.frame(Level = x_grid))),#transform x_grid vector to a data frame
color = 'blue') +
ggtitle('Truth or Bluff (Random Forest Regression)') +
xlab('Level') +
ylab('Salary')
| 46,440
|
https://github.com/olivertembodev/agrokimia-cms-laravel/blob/master/resources/views/kios/editKios.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
agrokimia-cms-laravel
|
olivertembodev
|
PHP
|
Code
| 933
| 4,755
|
@extends('layouts._layout')
@section('content')
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAvTkPKa1jErT_Kh9ZPTIP2az48f8y0WGo&libraries=places"></script>
<script>
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed',
function() {
var place = autocomplete.getPlace();
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
document.getElementById('latitude').value=lat;
document.getElementById('longitude').value=lng;
}
);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div class="container-fluid">
<div class="row page-titles">
<div class="col-md-5 align-self-center">
<h4 class="text-themecolor">Edit kios</h4>
</div>
<div class="col-md-7 align-self-center text-right">
<div class="d-flex justify-content-end align-items-center">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="{{ route('list-kios') }}">kios</a></li>
<li class="breadcrumb-item active">Tambah kios</li>
</ol>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-body">
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{route('updateKios',$data->id)}}" method="post" enctype="multipart/form-data">@csrf
<div class="form-body">
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-check">
<input type="checkbox" class="form-check-input" id="cabangkios">
<label class="form-check-label" for="exampleCheck1">Cabang Kios</label>
</div>
</div>
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Nama Kios</label>
<input type="text" name="nama_kios" id="nama_kios" class="form-control" value="{{ $data->nama_Kios }}" placeholder="" required>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Alamat Kios</label>
<input type="text" name="alamat_kios" id="alamat_kios" class="form-control" value="{{ $data->alamat_kios }}" placeholder="" required>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Pilih Kota</label>
<select name="id_kota" id="id_kota" class="form-control select2" required>
<option value="">Pilih Kota</option>
@foreach ($cities as $item)
@if ($item->city_code == $data->id_kota)
<option value="{{$item->city_code}}" selected>{{$item->name}}</option>
@else
<option value="{{$item->city_code}}">{{$item->name}}</option>
@endif
@endforeach
</select>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Pilih Area</label>
<select class="form-control select2" name="area_code" id="area">
<option value=''>Pilih Area</option>
@foreach ($area as $item)
@if ($item->area_code == $data->id_area)
<option value="{{$item->area_code}}" selected>{{$item->name}}</option>
@else
<option value="{{$item->area_code}}">{{$item->name}}</option>
@endif
@endforeach
</select>
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Category Kios</label>
<select name="category_kios" id="category_kios" class="form-control" required>
<option value="">Pilih Category Kios</option>
@foreach ($category_kios as $item)
@if ($item->id == $data->id_category)
<option value="{{$item->id}}" selected>{{$item->nama_tipe}}</option>
@else
<option value="{{$item->id}}">{{$item->nama_tipe}}</option>
@endif
@endforeach
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label" id="labelkiosutama" >Kios Utama</label>
<select name="kios_utama" id="kios_utama" class="form-control">
<option value="">Pilih Kios Utama</option>
@foreach ($kios_utama as $item)
<option value="{{$item->id}}">{{$item->nama_Kios}}</option>
@endforeach
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Tipe Kios</label>
<select name="tipe_kios" id="tipe_kios" class="form-control" required>
<option value="">Pilih Tipe Kios</option>
@foreach ($tipe_kios as $item)
@if ($item->id == $data->tipe_kios)
<option value="{{$item->id}}" selected>{{$item->nama_tipe_kios}}</option>
@else
<option value="{{$item->id}}">{{$item->nama_tipe_kios}}</option>
@endif
@endforeach
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">MAPS</label>
<input id="searchTextField" value="{{$data->alamat}}" name="alamat" type="text" class="form-control" placeholder="Masukkan Lokasi" autocomplete="on" runat="server"/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="hidden" name="id_kios_utama" id="id_kios_utama" class="form-control" value="{{ $data->id_kios_utama}}" placeholder="" required>
</div>
</div>
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Latitude</label>
<input type="text" readonly name="latitude" id="latitude" class="form-control" value="{{ $data->latitude}}" placeholder="" required>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Longitude</label>
<input type="text" readonly name="longitude" id="longitude" class="form-control" value="{{ $data->longitude}}" placeholder="" required>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Email</label>
<input type="text" name="email" id="email" class="form-control" value="{{ $data->email }}" placeholder="" required>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Nama PIC</label>
<input type="text" name="nama_pic" id="nama_pic" class="form-control" value="{{ $data->nama_pic }}" placeholder="" required>
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Nomor HP PIC</label>
<input type="text" name="nomor_hp_pic" id="nomor_hp_pic" class="form-control" value="{{ $data->nomor_hp_pic }}" placeholder="" required>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Nomor KTP PIC</label>
<input type="text" name="nomor_ktp_pic" id="nomor_ktp_pic" class="form-control" value="{{ $data->nomor_ktp_pic }}" placeholder="" required>
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Nomor NPWP PIC</label>
<input type="text" name="nomor_npwp_pic" id="nomor_npwp_pic" class="form-control" value="{{ $data->nomor_npwp_pic }}" placeholder="" required>
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Images NPWP</label><br>
<input id="image_npwp" class="form-control col-md-8 mb-2" type="file" name="image_npwp">
<output class="w-100" id="result_npwp">
<div>
<img class="thumbnail_npwp" src="{{ $data['image_npwp'] }}" title="preview image" style="width: 50%">
</div>
</output>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Images KTP</label><br>
<input id="image_ktp" class="form-control col-md-8 mb-2" type="file" name="image_ktp">
<output class="w-100" id="result_ktp">
<div>
<img class="thumbnail_ktp" src="{{ $data['image_ktp'] }}" title="preview image" style="width: 50%">
</div>
</output>
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Images Kios Depan</label><br>
<input id="image_kios_depan" class="form-control col-md-8 mb-2" type="file" name="image_kios_depan">
<output class="w-100" id="result_kios_dpn">
<div>
<img class="thumbnail_kios_dpn" src="{{ $data['image_kios_depan'] }}" title="preview image" style="width: 50%">
</div>
</output>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Images Kios Dalam</label><br>
<input id="image_kios_dalam" class="form-control col-md-8 mb-2" type="file" name="image_kios_dalam">
<output class="w-100" id="result_kios_dlm">
<div>
<img class="thumbnail_kios_dlm" src="{{ $data['image_kios_dalam'] }}" title="preview image" style="width: 50%">
</div>
</output>
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Images Selfie KTP</label><br>
<input id="image_selfi_ktp" class="form-control col-md-8 mb-2" type="file" name="image_selfi_ktp">
<output class="w-100" id="result_selfie">
<div>
<img class="thumbnail_selfie" src="{{ $data['image_selfi_ktp'] }}" title="preview image" style="width: 50%">
</div>
</output>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Status</label>
<select name="status" id="status" class="form-control" required>
@if ($data->status == '1')
<option value="">Pilih Status</option>
<option value="1" selected>Aktif</option>
<option value="0">Tidak Aktif</option>
<option value="2">Exipred</option>
@elseif($data->status == '0')
<option value="">Pilih Status</option>
<option value="1">Aktif</option>
<option value="0" selected>Tidak Aktif</option>
<option value="2">Exipred</option>
@else
<option value="">Pilih Status</option>
<option value="1">Aktif</option>
<option value="0">Tidak Aktif</option>
<option value="2" selected>Exipred</option>
@endif
</select>
</div>
</div>
</div>
<!--/row-->
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success"> <i class="fa fa-check"></i> Save</button>
<a href="{{ route('list-kios')}}"><button type="button" class="btn btn-inverse">Cancel</button></a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
@section('script')
<script>
$(document).ready(function() {
var name = $('input#id_kios_utama').val(); // get the value of the input field
if(name.trim() != "") {
$('#cabangkios').prop('checked', true);
$("#labelkiosutama").show();
$("#kios_utama").show();
}else{
$('#cabangkios').prop('checked', false);
$("#labelkiosutama").hide();
$("#kios_utama").hide();
}
$("#cabangkios").change(function(){
if($(this).is(':checked')){
$("#labelkiosutama").show(); // checked
$("#kios_utama").show(); // checked
}
else{
$("#labelkiosutama").hide();
$("#kios_utama").hide();
}
});
});
function myMap() {
var mapProp= {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
$(document).ready(function() {
$("#id_kota").change(function() {
console.log("jaya tampan");
var provid = $("#id_kota").val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
if(provid){
$.ajax({
type: 'GET',
url: '/area/' + provid,
dataType: 'json',
success: function(data) {
$("#area").empty();
$("#area").append("<option value=''>Pilih Area</option>");
for (let i = 0; i < data.length; i++) {
$("#area").append("<option value=" + data[i].area_code + ">" + data[i].name + "</option>");
}
console.log(data);
},
error: function(data) {
console.log(data);
}
});
}
});
});
</script>
<script>
</script>
@endsection
| 28,066
|
https://github.com/parvillanueva/AlagangUL/blob/master/application/views/content_management/template/footer.php
|
Github Open Source
|
Open Source
|
MIT
| null |
AlagangUL
|
parvillanueva
|
PHP
|
Code
| 6
| 23
|
<footer class="main-footer">
<strong>All rights reserved.
</footer>
| 23,135
|
https://github.com/plaforgue/kae/blob/master/kae/kae.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
kae
|
plaforgue
|
Python
|
Code
| 3,062
| 9,077
|
import time
import torch
import torch.optim as optim
###############################################################################
# Dictionaries functions
###############################################################################
def mk_ker_dic(kernels, kparams, outmats, lambdas):
"""Create the global kernel dictionary for the L layers
Parameters
----------
kernels: list of L str
Successive kernels. Ex: "gaussian", "polynomial", "precomputed"
kparams: list of L float/tuple/str
Parameters associated to kernels
outmats: list of L torch.Tensor of shape (n_features_l, n_features_l)/str
Output matrices. "identity" if infinite dimensional output.
Identity matrices are not stored for efficiency
lambdas: list of L float
Regularization parameters
Returns
-------
ker_dic: dict
Kernels and their parameters
keys: {1, ..., L, 'dim_tot'}
values: dict with kernel info / sum of intermediate spaces dims
"""
# Create individual layer dico from 1 kernel, 1 param, 1 outmat, 1 lambda
def mk_k_dic(kernel, kparam, outmat, lambda_):
k_dic = {'kernel': kernel,
'kparam': kparam,
'lambda': lambda_}
if isinstance(outmat, torch.Tensor):
k_dic['outdim'] = outmat.shape[0]
# If outmat = torch.eye(d), no need to store it
if torch.norm(outmat - torch.eye(outmat.shape[0],
dtype=torch.float64)) > 1e-10:
k_dic['outmat'] = outmat.clone()
elif outmat == 'identity':
k_dic['outmat'] = 'identity'
k_dic['outdim'] = 'infty'
return k_dic
# Return the dico of individual layer dicos + 'dim_tot'
L = len(kernels)
ker_dic = {'dim_tot': 0}
for l in range(L):
ker_dic[l + 1] = mk_k_dic(kernels[l], kparams[l], outmats[l],
lambdas[l])
# Count total dimension (exception with 'infty')
try:
ker_dic['dim_tot'] += ker_dic[l + 1]['outdim']
except TypeError:
pass
return ker_dic
def mk_Phi_dic(Phi_ravel, ker_dic):
"""Structure Phi_ravel into layers
Parameters
----------
Phi_ravel: torch.Tensor of shape (n_samples * dim_tot, )
All coefficients flattened
ker_dic: dict
Kernels and their parameters
keys : {1, ..., L, 'dim_tot'}
values: dict with kernel info / sum of intermediate spaces dims
Returns
-------
Phi_dic: dict
Coefficients organized in layers
keys: {1, ..., L-1, (L)} depending on implicitness of last layer
values: arrays of shape (n_samples, n_features_l)
"""
# Get constants
L = len(ker_dic.keys()) - 1
n = len(Phi_ravel) // ker_dic['dim_tot']
# Create the separators that will split the ravel
Phi_dic = {}
sep = [0]
# Loop over layers, select the corresponding coef in the ravel and reshape.
# No .copy(), only a pointer. If dict value is modified, so is Phi_ravel.
for l in range(1, L + 1):
try:
sep.append(sep[-1] + n * ker_dic[l]['outdim'])
Phi_dic[l] = Phi_ravel[sep[l - 1]: sep[l]].view(
n, ker_dic[l]['outdim']).requires_grad_(True)
# Subtlety at last layer for OKAE (outdim = 'infty')
except TypeError:
pass
return Phi_dic
###############################################################################
# Gram functions
###############################################################################
def poly_kernel(X, Y=None, degree=3, gamma=None, coef0=1):
"""Compute polynomial Gram matrix between X and Y (or X)
Parameters
----------
X: torch.Tensor of shape (n_samples_1, n_features)
First input on which Gram matrix is computed
Y: torch.Tensor of shape (n_samples_2, n_features), default None
Second input on which Gram matrix is computed. X is reused if None
degree: int
Degree parameter of the kernel (see sklearn implementation)
gamma: float
Gamma parameter of the kernel
coef0: float
coef0 parameter of the kernel
Returns
-------
K: torch.Tensor of shape (n_samples_1, n_samples_2)
Gram matrix on X/Y
"""
if Y is None:
Y = X
if gamma is None:
gamma = 1.0 / X.shape[1]
K_tmp = torch.mm(X, torch.t(Y))
K_tmp *= gamma
K_tmp += coef0
K = K_tmp ** degree
return K
def rbf_kernel(X, Y=None, gamma=None):
"""Compute rbf Gram matrix between X and Y (or X)
Parameters
----------
X: torch.Tensor of shape (n_samples_1, n_features)
First input on which Gram matrix is computed
Y: torch.Tensor of shape (n_samples_2, n_features), default None
Second input on which Gram matrix is computed. X is reused if None
gamma: float
Gamma parameter of the kernel (see sklearn implementation)
Returns
-------
K: torch.Tensor of shape (n_samples_1, n_samples_2)
Gram matrix on X/Y
"""
if Y is None:
Y = X
if gamma is None:
gamma = 1.0 / X.shape[1]
X_norm = (X ** 2).sum(1).view(-1, 1)
Y_norm = (Y ** 2).sum(1).view(1, -1)
K_tmp = X_norm + Y_norm - 2. * torch.mm(X, torch.t(Y))
K_tmp *= -gamma
K = torch.exp(K_tmp)
return K
def compute_Gram(k_dic, X, Y=None):
"""Compute the Gram matrix of an individual kernel
Parameters
----------
k_dic: dict
Kernel and its parameter
keys: {'kernel', 'kparam', 'lambda', 'outdim'}
values: kernel type, parameter, regularization output dimension
X: torch.Tensor of shape (n_samples_1, n_features)
First input on which Gram matrix is computed
Y: torch.Tensor of shape (n_samples_2, n_features), default None
Second input on which Gram matrix is computed. X is reused if None
Returns
-------
K: torch.Tensor of shape (n_samples_1, n_samples_2)
Gram matrix on X/Y
"""
# Compute Gram matrix depending on the kernel passed
if k_dic['kernel'] == 'gaussian':
K = rbf_kernel(X, Y=Y, gamma=k_dic['kparam'])
elif k_dic['kernel'] == 'polynomial':
K = poly_kernel(X, Y=Y, degree=k_dic['kparam'][0],
gamma=k_dic['kparam'][1], coef0=k_dic['kparam'][2])
else:
raise ValueError("Invalid kernel %s" % k_dic['kernel'])
return K
def compute_Reprs_Grams(Phi_dic, ker_dic, X=None, G_in=None):
"""Compute the intermediate representations/Gram matrices from X or G_in
Parameters
----------
Phi_dic: dict
Coefficients organized in layers
keys: {1, ..., L-1, (L)} depending on dimension of last layer
values: arrays of shape (n_samples, n_features_l)
ker_dic: dict
Kernels and their parameters
keys : {1, ..., L, 'dim_tot'}
values: dict with kernel info / sum of intermediate spaces dims
X: torch.Tensor of shape (n_samples, n_features_0), default None
Input representation. None if implicit representation via Gram matrix
G_in: torch.Tensor of shape (n_samples, n_samples), default None
Input Gram matrix of 1st layer. Necessary in implicit case, avoid re-
computation in standard case
Returns
-------
Reprs: dict
Intermediate representations
keys: {(0), 1, ..., L-1, (L)} depending on dim of 1st/last layer
values: torch.Tensor of shape (n_samples, n_features_l)
Grams: dict
Intermediate Gram matrices
keys: {1, ..., L}
values: torch.Tensor of shape (n_samples, n_samples)
"""
L = len(ker_dic.keys()) - 1
try:
Reprs = {0: X.clone()}
except AttributeError:
Reprs = {}
if G_in is not None:
Grams = {1: G_in.clone()}
else:
Grams = {1: compute_Gram(ker_dic[1], X)}
# Recursive computation
for l in range(1, L + 1):
# No need to compute Gram at first layer (computed at initialization)
if l > 1:
Grams[l] = compute_Gram(ker_dic[l], Reprs[l - 1])
try:
try:
Reprs[l] = torch.mm(Grams[l], torch.mm(Phi_dic[l],
ker_dic[l]['outmat']))
# If no outmat, means torch.eye, simpler formula
except KeyError:
Reprs[l] = torch.mm(Grams[l], Phi_dic[l])
# OKAE exception
except KeyError:
pass
return Reprs, Grams
def compute_Reprs_Grams_te(Phi_dic, ker_dic, Reprs_tr, X_te=None,
G_in_te=None):
"""Compute intermediate Reprs and final Gram from X_te and/or G_in_te
Parameters
----------
Phi_dic: dict
Coefficients organized in layers
keys: {1, ..., L-1, (L)} depending on dimension of last layer
values: arrays of shape (n_samples, n_features_l)
ker_dic: dict
Kernels and their parameters
keys : {1, ..., L, 'dim_tot'}
values: dict with kernel info / sum of intermediate spaces dims
Reprs_tr: dict
Intermediate representations of train data
keys: {(0), 1, ..., L-1, (L)} depending on dim of 1st/last layer
values: torch.Tensor of shape (n_samples, n_features_l)
X_te: torch.Tensor of shape (n_samples, n_features_0), default None
Test Input representation. None if implicit representation
G_in_te: torch.Tensor of shape (n_samples, n_samples), default None
Test input Gram matrix of first layer. Necessary in implicit case,
avoid re-computation in standard one
Returns
-------
Reprs_te: dict
Intermediate test representations
keys: {(0), 1, ..., L-1, (L)} depending on dim of 1st/last layer
values: torch.Tensor of shape (n_samples, n_features_l)
Grams_te: dict
Intermediate test Gram matrices
keys: {1, ..., L}
values: torch.Tensor of shape (n_samples, n_samples)
"""
L = len(ker_dic.keys()) - 1
try:
Reprs_te = {0: X_te.clone()}
except AttributeError:
Reprs_te = {}
if G_in_te is not None:
Gram_te = G_in_te.clone()
else:
Gram_te = compute_Gram(ker_dic[1], X_te, Y=Reprs_tr[0])
# Recursive computation
for l in range(1, L + 1):
# No need to compute Gram at first layer (computed at initialization)
if l > 1:
Gram_te = compute_Gram(ker_dic[l], Reprs_te[l - 1],
Y=Reprs_tr[l - 1])
try:
try:
Reprs_te[l] = torch.mm(Gram_te, torch.mm(Phi_dic[l],
ker_dic[l]['outmat']))
# If no outmat, means torch.eye, simpler formula
except KeyError:
Reprs_te[l] = torch.mm(Gram_te, Phi_dic[l])
# OKAE exception
except KeyError:
pass
return Reprs_te, Gram_te
###############################################################################
# Objective functions
###############################################################################
def layer_pen(Phi, k_dic, Gram):
"""Compute layer's penalization from layer's information
Parameters
----------
Phi: torch.Tensor of shape (n_samples, n_features_l+1)
Coefficient tensor
k_dic: dict
Kernel and its parameter
keys: {'kernel', 'kparam', 'lambda', 'outdim'}
values: kernel type, parameter, regularization output dimension
Gram: torch.Tensor of shape (n_samples, n_samples)
Gram matrix
Returns
-------
pen: float
Penalization value
"""
# Simpler formula if outmat = torch.eye
try:
N = torch.mm(Phi, torch.mm(k_dic['outmat'], torch.t(Phi)))
except KeyError:
N = torch.mm(Phi, torch.t(Phi))
pen = k_dic['lambda'] * (Gram * N).sum()
return pen
def o_layer_pen(N_L, Gram_L, lambda_L):
"""Compute last layer penalization
Parameters
----------
N_L: torch.Tensor of shape (n_samples, n_samples)
Last layer coefficients' dot products
Gram_L: torch.Tensor of shape (n_samples, n_samples)
Last layer Gram matrix
lambda_L: float
Last layer regularization parameter
Returns
-------
pen: float
Penalization value
"""
pen = lambda_L * (Gram_L * N_L).sum()
return pen
def MSD(Z, Y):
"""Compute the mean square distortion (MSD) between Z and Y
Parameters
----------
Z: torch.Tensor of shape (n_samples, n_features)
Tensor to be compared
Y: torch.Tensor of shape (n_samples, n_features)
Tensor to be compared
Returns
-------
msd: float
Mean square distance between Z and Y
"""
msd = ((Z - Y) ** 2).sum()
msd /= Z.shape[0]
return msd
def o_MSD(N_L, lambda_L):
"""Compute MSD (after KRR)
Parameters
----------
N_L: torch.Tensor of shape (n_samples, n_samples)
Last layer coefficients' dot products
lambda_L: float
Last layer regularization parameter
Returns
-------
msd: float
(Implicit) mean square distance between last layer output and Y
"""
msd = N_L.shape[0] * lambda_L ** 2 * N_L.trace()
return msd
def o_MSD_te(Phi_dic, N_L, ker_dic, Reprs_tr, G_tr_L, G_in_te, G_out_te,
G_out_own_te):
"""Compute test distortion
Parameters
----------
Phi_dic: dict
Coefficients organized in layers
keys: {1, ..., L-1, (L)} depending on dimension of last layer
values: arrays of shape (n_samples, n_features_l)
N_L: torch.Tensor of shape (n_samples, n_samples)
Last layer coefficients' dot products
ker_dic: dict
Kernels and their parameters
keys : {1, ..., L, 'dim_tot'}
values: dict with kernel info / sum of intermediate spaces dims
Reprs_tr: dict
Intermediate representations of train data
keys: {(0), 1, ..., L-1, (L)} depending on dim of 1st/last layer
values: torch.Tensor of shape (n_samples_tr, n_features_l)
G_tr_L: torch.Tensor of shape (n_samples_tr, n_samples_tr)
Last layer train Gram matrix
G_in_te: torch.Tensor of shape (n_samples_tr, n_samples_te)
First layer test Gram matrix
G_out_te: torch.Tensor of shape (n_samples_tr, n_samples_te)
Test output Gram matrix
G_out_own_te: torch.Tensor of shape (n_samples_te, n_samples_te)
Test-test output Gram matrix
Returns
-------
msd: float
Test (implicit) mean square distance
"""
L = len(ker_dic.keys()) - 1
Reprs_te, Gram_te = compute_Reprs_Grams_te(Phi_dic, ker_dic, Reprs_tr,
G_in_te=G_in_te)
n_tr = G_tr_L.shape[0]
W = G_tr_L + n_tr * ker_dic[L]['lambda'] * torch.eye(n_tr,
dtype=torch.float64)
W_inv = torch.inverse(W)
A = torch.trace(G_out_own_te)
B = (torch.mm(Gram_te, N_L) * Gram_te).sum()
C = -2 * (torch.mm(Gram_te, W_inv) * G_out_te).sum()
# Return the distortion
msd = 1. / Gram_te.shape[0] * (A + B + C)
return msd
def objective(Phi_dic, ker_dic, N_L=None, X=None, G_in=None, Y=None,
Reprs=None, Grams=None):
"""Compute objective
Parameters
----------
Phi_dic: dict
Coefficients organized in layers
keys: {1, ..., L-1, (L)} depending on dimension of last layer
values: arrays of shape (n_samples, n_features_l)
ker_dic: dict
Kernels and their parameters
keys : {1, ..., L, 'dim_tot'}
values: dict with kernel info / sum of intermediate spaces dims
N_L: torch.Tensor of shape (n_samples, n_samples), default None
Last layer coefficients' dot products. Useless in standard case
X: torch.Tensor of shape (n_samples, n_features_0), default None
Input representation. None if implicit representation via Gram matrix
G_in: torch.Tensor of shape (n_samples, n_samples), default None
Input Gram matrix of 1st layer. Necessary in implicit case, avoid re-
computation in standard case
Y: torch.Tensor of shape (n_samples, n_features_L), default None
Target. None in implicit case, information already contained in N_L
Reprs: dict
Intermediate representations
keys: {(0), 1, ..., L-1, (L)} depending on dim of 1st/last layer
values: torch.Tensor of shape (n_samples, n_features_l)
Grams: dict
Intermediate Gram matrices
keys: {1, ..., L}
values: torch.Tensor of shape (n_samples, n_samples)
Returns
-------
obj: float
Objective = (implicit) msd + penalizations
"""
L = len(ker_dic.keys()) - 1
obj = 0
# If Reprs and Grams not pre-computed, compute them
if Reprs is None and Grams is None:
Reprs, Grams = compute_Reprs_Grams(Phi_dic, ker_dic, X=X, G_in=G_in)
# Add internal layers penalizations
for l in range(1, L):
obj += layer_pen(Phi_dic[l], ker_dic[l], Grams[l])
# Difference on MSD / last layer penalization
if ker_dic[L]['outdim'] == 'infty':
obj += o_layer_pen(N_L, Grams[L], ker_dic[L]['lambda'])
obj += o_MSD(N_L, ker_dic[L]['lambda'])
else:
obj += layer_pen(Phi_dic[L], ker_dic[L], Grams[L])
obj += MSD(Reprs[L], Y)
return obj
###############################################################################
# Alternate functions
###############################################################################
def kron(t1, t2):
"""
Compute Kronecker product in pytorch between two tensors (not optimized)
Parameters
----------
t1: torch.Tensor of size (h1, w1)
First matrix of Kronecker product
t2: torch.Tensor of size (h2, w2)
Second matrix of Kronecker product
Returns
-------
t3: torch.Tensor of size (h1 * h2, w1 * w2)
Kronecker product of t1 and t2
"""
t1_height, t1_width = t1.size()
t2_height, t2_width = t2.size()
out_height, out_width = t1_height * t2_height, t1_width * t2_width
tiled_t2 = t2.repeat(t1_height, t1_width)
expanded_t1 = (t1.unsqueeze(2).unsqueeze(3).
repeat(1, t2_height, t2_width, 1).
view(out_height, out_width))
t3 = expanded_t1 * tiled_t2
return t3
def compute_Phi_L(k_dic_L, Gram_L, Y):
"""Compute Phi_L using KRR
Parameters
----------
k_dic_L: dict
Last layer kernel and its parameter
keys: {'kernel', 'kparam', 'lambda', 'outdim'}
values: kernel type, parameter, regularization output dimension
Gram_L: torch.Tensor of shape (n_samples, n_samples)
Last layer Gram matrix
Y: torch.Tensor of shape (n_samples, n_features_L)
Target
Returns
-------
Phi_L: torch.Tensor of size (n_samples, n_features_L)
Optimal last coefficient computed thanks to KRR
"""
n, d = Y.shape
# Simpler formula if output matrix is torch.eye
try:
Gram_Tot = kron(Gram_L, k_dic_L['outmat'])
M = Gram_Tot + n * k_dic_L['lambda'] * torch.eye(n * d,
dtype=torch.float64)
Phi_L, _ = torch.solve(Y.flatten(), M)
Phi_L = Phi_L.view(n, -1)
except KeyError:
M = Gram_L + n * k_dic_L['lambda'] * torch.eye(n, dtype=torch.float64)
Phi_L, _ = torch.solve(Y, M)
# Should be independent from previous layers: .data
return Phi_L.data
def compute_N_L(lambda_L, Gram_L, G_out):
"""Compute N_L using KRR
Parameters
----------
lambda_L: float
Last layer regularization parameter
Gram_L: torch.Tensor of shape (n_samples, n_samples)
Last layer Gram matrix
G_out: torch.Tensor of shape (n_samples, n_samples)
Output Gram matrix
Returns
-------
N_L: torch.Tensor of shape (n_samples, n_samples), default None
Optimal last layer coefficients' dot products computed thanks to KRR
"""
n = Gram_L.shape[0]
M_L = Gram_L + n * lambda_L * torch.eye(n, dtype=torch.float64)
M_L_1 = torch.inverse(M_L)
N_L = torch.mm(M_L_1, torch.mm(G_out, M_L_1))
# Should be independent from previous layers: .data
return N_L.data
###############################################################################
# Class
###############################################################################
class KAE:
"""K(2)AE class with fitting (optimization) procedures in pytorch
"""
def __init__(self, kernels, kparams, outmats, lambdas):
self.ker_dic = mk_ker_dic(kernels, kparams, outmats, lambdas)
self.L = len(self.ker_dic.keys()) - 1
def set_Phi(self, Phi_ravel):
"""Set Phi_dic to specified value
"""
self.Phi_dic = mk_Phi_dic(Phi_ravel.clone(), self.ker_dic)
def compute_RG_tr(self, X=None, G_in=None):
"""Compute intermediate Reprs/Grams from X and/or G_in
"""
self.Reprs_tr, self.Grams_tr = compute_Reprs_Grams(
self.Phi_dic, self.ker_dic, X=X, G_in=G_in)
def set_PhiL_KRR(self, Y):
"""Compute optimal KRR Phi_L
"""
self.Phi_dic[self.L] = compute_Phi_L(self.ker_dic[self.L],
self.Grams_tr[self.L], Y)
def set_NL(self, NL='auto', G_in=None, G_out=None):
"""Compute KRR optimal N_L, or set arbitrary one
"""
if isinstance(NL, torch.Tensor):
self.N_L = NL.clone()
elif NL == 'auto':
# If no Reprs_tr, need to compute them (and a G_in to do it)
if not hasattr(self, 'Reprs_tr'):
if G_in is None:
raise ValueError('No train representations'
', need fitting or G_in')
else:
self.compute_RG_tr(G_in=G_in)
# Finally, compute N_L using KRR
self.N_L = compute_N_L(self.ker_dic[self.L]['lambda'],
self.Grams_tr[self.L], G_out)
def fit(self, X=None, Y=None, G_in=None, G_out=None, method='gd',
n_epoch=100, n_loop=10, solver='sgd', **kwargs):
"""Fit best parameters Phi_dic from X and Y or G_in and G_out
Parameters
----------
X: torch.Tensor of shape (n_samples, n_features_0), default None
Input. None in the implicit case as given via an input Gram matrix
Y: torch.Tensor of shape (n_samples, n_features_L), default None
Target. None in the implicit case as given via an output Gram matrix
G_in: torch.Tensor of shape (n_samples, n_samples), default None
Input Gram matrix. Necessary in implicit case. Avoid re-
computation in standard one
G_out: torch.Tensor of shape (n_samples, n_samples), default None
Output Gram matrix. Useless in standard case
method: str, default 'gd'
Method to use for the optimization
n_epoch: int, default 100
Number of epochs in inner solver
n_loop: int, default 10
Number of epochs for inner + outer update
solver: str, default 'sgd'
Inner solver to use
**params: kwargs
keyword arguments passed to inner solver
"""
# Test if optimization method is valid
if method in ['gd', 'md']:
if not isinstance(self.ker_dic[self.L]['outdim'], int):
raise ValueError('Invalid optimization method called')
elif method in ['ogd', 'omd']:
if self.ker_dic[self.L]['outdim'] != 'infty':
raise ValueError('Invalid optimization method called')
else:
raise ValueError('Invalid optimization method called')
# Random initialization if no parameter
if not hasattr(self, 'Phi_dic'):
try:
n = X.shape[0]
except TypeError:
n = G_in.shape[0]
Phi_init = torch.randn(n * self.ker_dic['dim_tot'],
dtype=torch.float64)
self.set_Phi(Phi_init)
if method in ['gd', 'md']:
self.N_L = None
elif method in ['ogd', 'omd']:
self.set_NL(G_in=G_in, G_out=G_out)
# To store objective/time iterations
if not hasattr(self, 'losses'):
self.losses = []
self.times = [0]
# Coefficients to be updated (only L - 1 internal ones in md)
if method == 'gd':
params = (self.Phi_dic[l] for l in range(1, self.L + 1))
elif method in ['md', 'ogd', 'omd']:
params = (self.Phi_dic[l] for l in range(1, self.L))
# Criterion to be optimized
def closure():
loss = objective(self.Phi_dic, self.ker_dic, N_L=self.N_L, X=X,
G_in=G_in, Y=Y)
optimizer.zero_grad()
loss.backward()
return loss
# Optimizer
if solver == 'sgd':
optimizer = optim.SGD(params, **kwargs)
elif solver == 'lbfgs':
optimizer = optim.LBFGS(params, **kwargs)
else:
raise ValueError('Invalid solver: %s' % solver)
# By default (gd, ogd), only 1 outer loop
n_outer_epoch = 1
if method in ['md', 'omd']:
n_outer_epoch = n_loop
t0 = time.time() - self.times[-1]
for k in range(n_outer_epoch):
for t in range(n_epoch):
# Coefficient update
loss = closure()
self.losses.append(loss.item())
self.times.append(time.time() - t0)
optimizer.step(closure)
# Compute intermediate train Reprs/Grams
self.compute_RG_tr(X=X, G_in=G_in)
# Last layer update in mirror descents
if method == 'md':
self.set_PhiL_KRR(Y)
elif method == 'omd':
self.set_NL(G_in=G_in, G_out=G_out)
# Clean times if necessary (i.e. remove first 0)
try:
self.times.remove(0)
except ValueError:
pass
def predict(self, X_te=None, G_in_te=None):
"""Give prediction from X_te or G_in_te
X_te: torch.Tensor of shape (n_samples, n_features_0), default None
Test Input representation. None if implicit representation
G_in_te: torch.Tensor of shape (n_samples, n_samples), default None
Test input Gram matrix of first layer. Necessary in implicit
case, avoid re-computation in standard one
Returns
-------
Reprs_te: dict
Intermediate test representations
keys: {(0), 1, ..., L-1, (L)} depending on implicitness
values: torch.Tensor of shape (n_samples, n_features_l)
"""
Reprs_te, _ = compute_Reprs_Grams_te(
self.Phi_dic, self.ker_dic, self.Reprs_tr, X_te=X_te,
G_in_te=G_in_te)
return Reprs_te
def test_disto(self, X_te=None, Y_te=None, G_in_te=None, G_out_te=None,
G_out_own_te=None):
"""Compute test distortion
Parameters
----------
X_te: torch.Tensor of shape (n_samples_te, n_features_0),
default None
Test input in non implicit case
Y_te: torch.Tensor of shape (n_samples_te, n_features_L),
default None
Test target in non implicit case
G_in_te: torch.Tensor of shape (n_samples_tr, n_samples_te),
default None
First layer test Gram matrix. For the implicit case
G_out_te: torch.Tensor of shape (n_samples_tr, n_samples_te),
default None
Last layer test output Gram matrix. For the implicit case
G_out_own_te: torch.Tensor of shape (n_samples_te, n_samples_te),
default None
Test-test output Gram matrix in the implicit case
Returns
-------
disto: float
Test distortion
"""
Reprs_te, Gram_te = compute_Reprs_Grams_te(
self.Phi_dic, self.ker_dic, self.Reprs_tr,
X_te=X_te, G_in_te=G_in_te)
try:
disto = MSD(Y_te, Reprs_te[self.L])
except KeyError:
disto = o_MSD_te(
self.Phi_dic, self.N_L, self.ker_dic, self.Reprs_tr,
self.Grams_tr[self.L], G_in_te, G_out_te, G_out_own_te)
return disto
def clear_memory(self):
"""Clear fitting memory
"""
self.losses, self.times = [], [0]
| 26,102
|
https://github.com/edesz/electricity-consumption-forecast/blob/master/src/processing_helpers.py
|
Github Open Source
|
Open Source
|
MIT
| null |
electricity-consumption-forecast
|
edesz
|
Python
|
Code
| 102
| 354
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
def median_filter_outliers(df_train, df_val, window=24 * 1, std=3):
# train
medianv = df_train["y"].rolling(window, center=True).median()
stdv = df_train["y"].rolling(window, center=True).std()
# transform train
mask = (df_train.loc[:, "y"] >= medianv + (std * stdv)) | (
df_train.loc[:, "y"] <= medianv - (std * stdv)
)
df_train.loc[mask, "y"] = np.nan
# transform val
num_obs_from_end = len(df_val)
medianv_val = medianv.iloc[-num_obs_from_end:]
stdv_val = stdv.iloc[-num_obs_from_end:]
medianv_val.index = df_val.index
stdv_val.index = df_val.index
mask = (df_val.loc[:, "y"] >= medianv_val + (std * stdv_val)) | (
df_val.loc[:, "y"] <= medianv_val - (std * stdv_val)
)
df_val.loc[mask, "y"] = np.nan
return [df_train, df_val]
| 16,340
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.