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/alucard263096/MagicMainLand/blob/master/app/src/main/java/com/helpfooter/magicmainland/Classes/MenuExtendes/ConsumerItemUseMenu.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
MagicMainLand
|
alucard263096
|
Java
|
Code
| 111
| 833
|
package com.helpfooter.magicmainland.Classes.MenuExtendes;
import com.helpfooter.magicmainland.Common.StaticObject;
import com.helpfooter.magicmainland.Classes.MenuManager;
import com.helpfooter.magicmainland.Classes.SceneBuilder;
import com.helpfooter.magicmainland.Classes.DialogExtends.HeroStatusDialog;
import com.helpfooter.magicmainland.Classes.DialogExtends.ItemShowDialog;
import com.helpfooter.magicmainland.Classes.PersonExtends.FightPerson;
import com.helpfooter.magicmainland.ClassesItemExtends.ConsumableItem;
import com.helpfooter.magicmainland.ClassesItemExtends.ItemQty;
import com.helpfooter.magicmainland.ClassesItemExtends.Luggage;
import com.helpfooter.magicmainland.Utils.EnumControllerButton;
import com.helpfooter.magicmainland.Utils.GameConfig;
public class ConsumerItemUseMenu extends QueueMenu {
ItemQty itemQty;
public ConsumerItemUseMenu(ItemQty itemQty) {
super("");
// TODO Auto-generated constructor stub
menuStartX=(int)(4*GameConfig.BUTTON_SIZE+5*GameConfig.BUTTON_ARGIN);
this.itemQty=itemQty;
}
public void initialization(){
super.initialization();
if(((ConsumableItem)itemQty.item).isQueueUse){
optionDialog.selectAll=true;
}
}
public void notSelectedSetControll(EnumControllerButton irButton) {
// TODO Auto-generated method stub
if(irButton==EnumControllerButton.DOWN){
if(cursor+colNum<alOp.size()){
cursor+=colNum;
}
}
else if(irButton==EnumControllerButton.UP){
if(cursor-colNum>=0){
cursor-=colNum;
}
}
else if(irButton==EnumControllerButton.RIGHT){
cursor++;
if(cursor>=alOp.size()){
cursor=alOp.size()-1;
}
}
else if(irButton==EnumControllerButton.LEFT){
cursor--;
if(cursor<0){
cursor=0;
}
}
else if(irButton==EnumControllerButton.A){
FightPerson fightPerson=super.alFightPerson.get(cursor);
Luggage luggage=StaticObject.StarHero.luggage;
luggage.consumerItem(fightPerson,itemQty);
if(itemQty.qty==0){
//superMenu.alOp.remove(superMenu.cursor-1);
ConsumerItemListMenu ilm=(ConsumerItemListMenu)superMenu;
ilm.reloadItemList();
}
}
else if(irButton==EnumControllerButton.B){
super.notSelectedSetControll(irButton);
}
if(optionDialog!=null){
optionDialog.setCursor(cursor);
}
}
}
| 30,631
|
https://github.com/Rohit484/Distribution/blob/master/a/aws-sdk/src/main/scala/typings/awsSdk/mturkMod/NotifyWorkersResponse.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Distribution
|
Rohit484
|
Scala
|
Code
| 136
| 551
|
package typings.awsSdk.mturkMod
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait NotifyWorkersResponse extends js.Object {
/**
* When MTurk sends notifications to the list of Workers, it returns back any failures it encounters in this list of NotifyWorkersFailureStatus objects.
*/
var NotifyWorkersFailureStatuses: js.UndefOr[NotifyWorkersFailureStatusList] = js.native
}
object NotifyWorkersResponse {
@scala.inline
def apply(): NotifyWorkersResponse = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[NotifyWorkersResponse]
}
@scala.inline
implicit class NotifyWorkersResponseOps[Self <: NotifyWorkersResponse] (val x: Self) extends AnyVal {
@scala.inline
def duplicate: Self = (js.Dynamic.global.Object.assign(js.Dynamic.literal(), x)).asInstanceOf[Self]
@scala.inline
def combineWith[Other <: js.Any](other: Other): Self with Other = (js.Dynamic.global.Object.assign(js.Dynamic.literal(), x, other.asInstanceOf[js.Any])).asInstanceOf[Self with Other]
@scala.inline
def set(key: java.lang.String, value: js.Any): Self = {
x.asInstanceOf[js.Dynamic].updateDynamic(key)(value)
x
}
@scala.inline
def setNotifyWorkersFailureStatusesVarargs(value: NotifyWorkersFailureStatus*): Self = this.set("NotifyWorkersFailureStatuses", js.Array(value :_*))
@scala.inline
def setNotifyWorkersFailureStatuses(value: NotifyWorkersFailureStatusList): Self = this.set("NotifyWorkersFailureStatuses", value.asInstanceOf[js.Any])
@scala.inline
def deleteNotifyWorkersFailureStatuses: Self = this.set("NotifyWorkersFailureStatuses", js.undefined)
}
}
| 13,408
|
https://github.com/andriux26/wx-ground-station/blob/master/aws-s3/upload-wx-images.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
wx-ground-station
|
andriux26
|
JavaScript
|
Code
| 557
| 1,692
|
var fs = require('fs');
var path = require('path');
var glob = require("glob");
var AWS = require('aws-sdk');
var uuid = require('uuid');
var Jimp = require('jimp');
var dateFormat = require('dateformat');
var REGION = "";
var BUCKET = "";
var LOCATION = "";
var IMAGE_DIR = "images/";
AWS.config.update({region: REGION});
var s3 = new AWS.S3();
var satellite = process.argv[2];
var frequency = process.argv[3];
var filebase = process.argv[4];
var elevation = process.argv[5];
var direction = process.argv[6];
var duration = process.argv[7];
var tle1 = process.argv[8];
var tle2 = process.argv[9];
var gain = process.argv[10];
var chan_a = process.argv[11];
var chan_b = process.argv[12];
var basename = filebase.slice(filebase.lastIndexOf('/')+1);
var dirname = filebase.slice(0, filebase.lastIndexOf('/')+1);
var components = basename.split("-");
var date = components[1];
date = date.slice(0, 4) + '-' + date.slice(4, 6) + '-' + date.slice(6);
var time = components[2];
time = time.slice(0, 2) + ':' + time.slice(2, 4) + ':' + time.slice(4) + ' ' + dateFormat(new Date, "o");
// example "Gain: 15.2"
if (gain) {
gain = gain.substring(gain.indexOf(": ") + 2)
}
// example "Channel A: 1 (visible)"
if (chan_a) {
chan_a = chan_a.substring(chan_a.indexOf(": ")+2);
}
// example "Channel B: 4 (thermal infrared)"
if (chan_b) {
chan_b = chan_b.substring(chan_b.indexOf(": ")+2);
}
console.log("Uploading files " + path.basename(filebase) + "* to S3...");
var metadata = {
satellite: satellite,
date: date,
time: time,
elevation: elevation,
direction: direction,
duration: duration,
imageKey: filebase.slice(filebase.lastIndexOf('/')+1),
tle1: tle1,
tle2: tle2,
frequency: frequency,
gain: gain,
chan_a: chan_a,
chan_b: chan_b,
images: []
};
async function uploadImage(image, filename) {
var w = image.bitmap.width;
var h = image.bitmap.height;
var enhancement;
if (filename.endsWith("-ZA.png")) enhancement = "normal infrared";
if (filename.endsWith("-NO.png")) enhancement = "color infrared";
if (filename.endsWith("-MSA.png")) enhancement = "multispectral analysis";
if (filename.endsWith("-MSAPRECIP.png")) enhancement = "multispectral precip";
if (filename.endsWith("-MCIR.png")) enhancement = "map color infrared";
if (filename.endsWith("-THERM.png")) enhancement = "thermal";
var imageInfo = {
filename: filename,
width: w,
height: h,
thumbfilename: 'thumbs/' + filename,
enhancement: enhancement
};
var font = await Jimp.loadFont(Jimp.FONT_SANS_16_WHITE);
var newImage = await new Jimp(image.bitmap.width, image.bitmap.height+64, '#000000');
newImage.composite(image, 0, 48);
image = newImage;
image.print(font, 5, 5, metadata.date + " " + metadata.time + " satellite: " + metadata.satellite +
" elevation: " + metadata.elevation + '\xB0' + " enhancement: " + enhancement);
image.print(font, 5, 25, LOCATION);
image.getBuffer(Jimp.MIME_PNG, (err, buffer) => {
var params = {
ACL: "public-read",
ContentType: "image/png",
Bucket: BUCKET,
Key: IMAGE_DIR + filename,
Body: buffer
};
s3.putObject(params, (err, data) => {
if (err) {
console.log(err)
} else {
console.log(" successfully uploaded " + filename);
}
});
});
var thumb = image.clone();
thumb.cover(260, 200);
var thumbFilename = "thumbs/" + filename;
thumb.getBuffer(Jimp.MIME_PNG, (err, buffer) => {
var params = {
ACL: "public-read",
ContentType: "image/png",
Bucket: BUCKET,
Key: IMAGE_DIR + thumbFilename,
Body: buffer
};
s3.putObject(params, (err, data) => {
if (err) {
console.log(err)
} else {
console.log(" successfully uploaded thumb " + filename);
}
});
});
return imageInfo;
}
function uploadMetadata(filebase) {
var metadataFilename = filebase + ".json";
console.log("uploading metadata " + JSON.stringify(metadata, null, 2));
var params = {
ACL: "public-read",
Bucket: BUCKET,
Key: IMAGE_DIR + metadataFilename,
Body: JSON.stringify(metadata, null, 2)
};
s3.putObject(params, function(err, data) {
if (err) {
console.log(err)
} else {
console.log(" successfully uploaded metadata " + metadataFilename);
}
});
}
glob(filebase + "-[A-Z]*.png", {}, function (err, files) {
var uploadPromises = [];
files.forEach(function(filename) {
var basename = path.basename(filename);
Jimp.read(filename)
.then(image => {
uploadPromises.push(uploadImage(image, basename));
if (uploadPromises.length == files.length) {
Promise.all(uploadPromises).then((values) => {
metadata.images = values;
console.log("values: " + JSON.stringify(values, null, 2));
uploadMetadata(path.basename(filebase));
});
}
});
});
});
| 1,244
|
https://github.com/armandomeeuwenoord/freight/blob/master/freight/api/serializer/base.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
freight
|
armandomeeuwenoord
|
Python
|
Code
| 32
| 128
|
__all__ = ["Serializer"]
class Serializer(object):
def __call__(self, *args, **kwargs):
return self.serialize(*args, **kwargs)
def get_attrs(self, item_list):
return {}
def serialize(self, item, attrs):
return {}
def format_datetime(self, datetime):
if not datetime:
return
return datetime.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
| 26,616
|
https://github.com/stevegio/jekyll/blob/master/doc/book/book.asc
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, MIT
| 2,011
|
jekyll
|
stevegio
|
AsciiDoc
|
Code
| 10
| 72
|
Jekyll
======
:Author: Tom Preston-Werner
:Email: <tom@mojombo.com>
include::ch00-preface.asc[]
include::ch01-quick-start.asc[]
include::ch02-directory-layout.asc[]
| 26,336
|
https://github.com/zachdimitrov/Learning_2016/blob/master/CSharp-Part-1/04.Console-In-and-Out/10. Fibonacci Numbers/10.Fibonacci.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Learning_2016
|
zachdimitrov
|
C#
|
Code
| 160
| 294
|
using System;
class Fibonacci
{
static void Main()
{
ulong N = ulong.Parse(Console.ReadLine());
ulong a = 0;
ulong b = 1;
for (ulong i = 0; i < N - 1; i++)
{
Console.Write("{0}, ", a);
ulong c = a + b;
a = b;
b = c;
}
Console.WriteLine(a);
}
}
/*
Fibonacci Numbers
Description
Write a program that reads a number N and prints on the console
the first N members of the Fibonacci sequence (at a single line,
separated by comma and space - ", ") : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ….
Input
On the only line you will receive the number N
Output
On the only line you should print the first N numbers of the sequence,
separated by ", " (comma and space)
Constraints
1 <= N <= 50
N will always be a valid positive integer number
Time limit: 0.1s
Memory limit: 8MB
*/
| 3,581
|
https://github.com/game-x50/android_client_app/blob/master/features/game/storage/impl/src/main/java/com/ruslan/hlushan/game/storage/impl/local/db/entities/LocalActionTypeDb.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
android_client_app
|
game-x50
|
Kotlin
|
Code
| 62
| 233
|
package com.ruslan.hlushan.game.storage.impl.local.db.entities
import com.ruslan.hlushan.game.api.play.dto.LocalAction
internal enum class LocalActionTypeDb {
CREATE,
UPDATE,
DELETE;
}
internal val LocalAction.typeDb: LocalActionTypeDb
get() = when (this) {
is LocalAction.Create -> LocalActionTypeDb.CREATE
is LocalAction.Update -> LocalActionTypeDb.UPDATE
is LocalAction.Delete -> LocalActionTypeDb.DELETE
}
internal fun LocalActionTypeDb.toLocalAction(
actionId: String
): LocalAction = when (this) {
LocalActionTypeDb.CREATE -> LocalAction.Create(actionId = actionId)
LocalActionTypeDb.UPDATE -> LocalAction.Update(actionId = actionId)
LocalActionTypeDb.DELETE -> LocalAction.Delete(actionId = actionId)
}
| 9,456
|
https://github.com/swsachith/harp/blob/master/core/harp-collective/src/main/java/edu/iu/harp/combiner/IntArrCombiner.java
|
Github Open Source
|
Open Source
|
Apache-1.1
| 2,021
|
harp
|
swsachith
|
Java
|
Code
| 202
| 567
|
package edu.iu.harp.combiner;
import edu.iu.harp.partition.PartitionCombiner;
import edu.iu.harp.partition.PartitionStatus;
import edu.iu.harp.resource.IntArray;
/**
* Combine two Integer arrays according to a operation specified.
* Supported operations are
* SUM,
* MINUS,
* MULTIPLY,
* MAX,
* MIN
*/
public class IntArrCombiner extends PartitionCombiner<IntArray> {
private Operation operation;
public IntArrCombiner(Operation operation) {
this.operation = operation;
}
@Override
public PartitionStatus combine(IntArray curPar,
IntArray newPar) {
int[] arr1 = curPar.get();
int size1 = curPar.size();
int[] arr2 = newPar.get();
int size2 = newPar.size();
if (size1 != size2) {
// throw new Exception("size1: " + size1
// + ", size2: " + size2);
return PartitionStatus.COMBINE_FAILED;
}
switch (operation) {
case SUM:
for (int i = 0; i < size2; i++) {
arr1[i] += arr2[i];
}
break;
case MINUS:
for (int i = 0; i < size2; i++) {
arr1[i] -= arr2[i];
}
break;
case MAX:
for (int i = 0; i < size2; i++) {
if (arr1[i] < arr2[i]) {
arr1[i] = arr2[i];
}
}
break;
case MIN:
for (int i = 0; i < size2; i++) {
if (arr1[i] > arr2[i]) {
arr1[i] = arr2[i];
}
}
break;
case MULTIPLY:
for (int i = 0; i < size2; i++) {
arr1[i] *= arr2[i];
}
break;
}
return PartitionStatus.COMBINED;
}
}
| 46,352
|
https://github.com/mukeshbasira/swift-animation/blob/master/Source/render/TextRenderer.swift
|
Github Open Source
|
Open Source
|
MIT
| null |
swift-animation
|
mukeshbasira
|
Swift
|
Code
| 356
| 1,054
|
import Foundation
import UIKit
class TextRenderer: NodeRenderer {
weak var text: Text?
init(text: Text, ctx: RenderContext, animationCache: AnimationCache?) {
self.text = text
super.init(node: text, ctx: ctx, animationCache: animationCache)
}
override func node() -> Node? {
return text
}
override func doAddObservers() {
super.doAddObservers()
guard let text = text else {
return
}
observe(text.textVar)
observe(text.fontVar)
observe(text.fillVar)
observe(text.alignVar)
observe(text.baselineVar)
}
override func doRender(_ force: Bool, opacity: Double) {
guard let text = text else {
return
}
let message = text.text
let font = getUIFont()
// positive NSBaselineOffsetAttributeName values don't work, couldn't find why
// for now move the rect itself
if var color = text.fill as? Color {
color = RenderUtils.applyOpacity(color, opacity: opacity)
UIGraphicsPushContext(ctx.cgContext!)
message.draw(in: getBounds(font), withAttributes: [NSFontAttributeName: font,
NSForegroundColorAttributeName: getTextColor(color)])
UIGraphicsPopContext()
}
}
override func doFindNodeAt(location: CGPoint, ctx: CGContext) -> Node? {
guard let contains = node()?.bounds()?.cgRect().contains(location) else {
return .none
}
if contains {
return node()
}
return .none
}
fileprivate func getUIFont() -> UIFont {
guard let text = text else {
return UIFont.systemFont(ofSize: 18.0)
}
if let textFont = text.font {
if let customFont = RenderUtils.loadFont(name: textFont.name, size: textFont.size) {
return customFont
} else {
return UIFont.systemFont(ofSize: CGFloat(textFont.size))
}
}
return UIFont.systemFont(ofSize: UIFont.systemFontSize)
}
fileprivate func getBounds(_ font: UIFont) -> CGRect {
guard let text = text else {
return .zero
}
let textAttributes = [NSFontAttributeName: font]
let textSize = NSString(string: text.text).size(attributes: textAttributes)
return CGRect(x: calculateAlignmentOffset(text, font: font),
y: calculateBaselineOffset(text, font: font),
width: CGFloat(textSize.width), height: CGFloat(textSize.height))
}
fileprivate func calculateBaselineOffset(_ text: Text, font: UIFont) -> CGFloat {
var baselineOffset = CGFloat(0)
switch text.baseline {
case Baseline.alphabetic:
baselineOffset = font.ascender
case Baseline.bottom:
baselineOffset = font.ascender - font.descender
case Baseline.mid:
baselineOffset = (font.ascender - font.descender) / 2
default:
break
}
return -baselineOffset
}
fileprivate func calculateAlignmentOffset(_ text: Text, font: UIFont) -> CGFloat {
let textAttributes = [
NSFontAttributeName: font
]
let textSize = NSString(string: text.text).size(attributes: textAttributes)
var alignmentOffset = CGFloat(0)
switch text.align {
case Align.mid:
alignmentOffset = textSize.width / 2
case Align.max:
alignmentOffset = textSize.width
default:
break
}
return -alignmentOffset
}
fileprivate func getTextColor(_ fill: Fill) -> UIColor {
if let color = fill as? Color {
return UIColor(cgColor: RenderUtils.mapColor(color))
}
return UIColor.black
}
}
| 23,611
|
https://github.com/ASWC/pixi-5-ts/blob/master/raw-pixi-ts/ProjectionSystem.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
pixi-5-ts
|
ASWC
|
TypeScript
|
Code
| 390
| 1,002
|
import { System } from "./System";
import { Matrix } from "./Matrix";
export class ProjectionSystem extends System
{
destinationFrame
defaultFrame
transform
sourceFrame
projectionMatrix
constructor(renderer)
{
super(renderer);
/**
* Destination frame
* @member {PIXI.Rectangle}
* @readonly
*/
this.destinationFrame = null;
/**
* Source frame
* @member {PIXI.Rectangle}
* @readonly
*/
this.sourceFrame = null;
/**
* Default destination frame
* @member {PIXI.Rectangle}
* @readonly
*/
this.defaultFrame = null;
/**
* Project matrix
* @member {PIXI.Matrix}
* @readonly
*/
this.projectionMatrix = new Matrix();
/**
* A transform that will be appended to the projection matrix
* if null, nothing will be applied
* @member {PIXI.Matrix}
*/
this.transform = null;
}
/**
* Updates the projection matrix based on a projection frame (which is a rectangle)
*
* @param {PIXI.Rectangle} destinationFrame - The destination frame.
* @param {PIXI.Rectangle} sourceFrame - The source frame.
* @param {Number} resolution - Resolution
* @param {boolean} root - If is root
*/
update (destinationFrame, sourceFrame, resolution, root)
{
this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame;
this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame;
this.calculateProjection(this.destinationFrame, this.sourceFrame, resolution, root);
if (this.transform)
{
this.projectionMatrix.append(this.transform);
}
var renderer = this.renderer;
renderer.globalUniforms.uniforms.projectionMatrix = this.projectionMatrix;
renderer.globalUniforms.update();
// this will work for now
// but would be sweet to stick and even on the global uniforms..
if (renderer.shader.shader)
{
renderer.shader.syncUniformGroup(renderer.shader.shader.uniforms.globals);
}
};
/**
* Updates the projection matrix based on a projection frame (which is a rectangle)
*
* @param {PIXI.Rectangle} destinationFrame - The destination frame.
* @param {PIXI.Rectangle} sourceFrame - The source frame.
* @param {Number} resolution - Resolution
* @param {boolean} root - If is root
*/
calculateProjection (destinationFrame, sourceFrame, resolution, root)
{
var pm = this.projectionMatrix;
// I don't think we will need this line..
// pm.identity();
if (!root)
{
pm.a = (1 / destinationFrame.width * 2) * resolution;
pm.d = (1 / destinationFrame.height * 2) * resolution;
pm.tx = -1 - (sourceFrame.x * pm.a);
pm.ty = -1 - (sourceFrame.y * pm.d);
}
else
{
pm.a = (1 / destinationFrame.width * 2) * resolution;
pm.d = (-1 / destinationFrame.height * 2) * resolution;
pm.tx = -1 - (sourceFrame.x * pm.a);
pm.ty = 1 - (sourceFrame.y * pm.d);
}
};
/**
* Sets the transform of the active render target to the given matrix
*
* @param {PIXI.Matrix} matrix - The transformation matrix
*/
setTransform ()// matrix)
{
// this._activeRenderTarget.transform = matrix;
};
}
| 22,628
|
https://github.com/mDemianchuk/Arabic-Roman-Converter/blob/master/src/main/java/com/demianchuk/models/converter/NumeralConverter.java
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
Arabic-Roman-Converter
|
mDemianchuk
|
Java
|
Code
| 10
| 33
|
package com.demianchuk.models.converter;
public interface NumeralConverter {
String convert(String value);
}
| 7,699
|
https://github.com/dirkvanrensburg/hazelcast/blob/master/hazelcast/src/main/java/com/hazelcast/cluster/client/AddMembershipListenerRequest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
hazelcast
|
dirkvanrensburg
|
Java
|
Code
| 348
| 1,118
|
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. 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 com.hazelcast.cluster.client;
import com.hazelcast.client.ClientEndpoint;
import com.hazelcast.client.impl.client.CallableClientRequest;
import com.hazelcast.client.impl.client.ClientPortableHook;
import com.hazelcast.client.impl.client.RetryableRequest;
import com.hazelcast.cluster.MemberAttributeOperationType;
import com.hazelcast.cluster.impl.ClusterServiceImpl;
import com.hazelcast.core.MemberAttributeEvent;
import com.hazelcast.core.MembershipEvent;
import com.hazelcast.core.MembershipListener;
import com.hazelcast.instance.MemberImpl;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.spi.impl.SerializableCollection;
import java.security.Permission;
import java.util.ArrayList;
import java.util.Collection;
public final class AddMembershipListenerRequest extends CallableClientRequest implements RetryableRequest {
public AddMembershipListenerRequest() {
}
@Override
public Object call() throws Exception {
ClusterServiceImpl service = getService();
ClientEndpoint endpoint = getEndpoint();
String registrationId = service.addMembershipListener(new MembershipListenerImpl(endpoint));
String name = ClusterServiceImpl.SERVICE_NAME;
endpoint.setListenerRegistration(name, name, registrationId);
Collection<MemberImpl> memberList = service.getMemberList();
Collection<Data> response = new ArrayList<Data>(memberList.size());
for (MemberImpl member : memberList) {
response.add(serializationService.toData(member));
}
return new SerializableCollection(response);
}
@Override
public String getServiceName() {
return ClusterServiceImpl.SERVICE_NAME;
}
@Override
public int getFactoryId() {
return ClientPortableHook.ID;
}
@Override
public int getClassId() {
return ClientPortableHook.MEMBERSHIP_LISTENER;
}
@Override
public Permission getRequiredPermission() {
return null;
}
private class MembershipListenerImpl implements MembershipListener {
private final ClientEndpoint endpoint;
public MembershipListenerImpl(ClientEndpoint endpoint) {
this.endpoint = endpoint;
}
@Override
public void memberAdded(MembershipEvent membershipEvent) {
if (!endpoint.isAlive()) {
return;
}
MemberImpl member = (MemberImpl) membershipEvent.getMember();
ClientMembershipEvent event = new ClientMembershipEvent(member, MembershipEvent.MEMBER_ADDED);
endpoint.sendEvent(null, event, getCallId());
}
@Override
public void memberRemoved(MembershipEvent membershipEvent) {
if (!endpoint.isAlive()) {
return;
}
MemberImpl member = (MemberImpl) membershipEvent.getMember();
ClientMembershipEvent event = new ClientMembershipEvent(member, MembershipEvent.MEMBER_REMOVED);
endpoint.sendEvent(null, event, getCallId());
}
@Override
public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) {
if (!endpoint.isAlive()) {
return;
}
MemberImpl member = (MemberImpl) memberAttributeEvent.getMember();
String uuid = member.getUuid();
MemberAttributeOperationType op = memberAttributeEvent.getOperationType();
String key = memberAttributeEvent.getKey();
Object value = memberAttributeEvent.getValue();
MemberAttributeChange memberAttributeChange = new MemberAttributeChange(uuid, op, key, value);
ClientMembershipEvent event = new ClientMembershipEvent(member, memberAttributeChange);
endpoint.sendEvent(null, event, getCallId());
}
}
}
| 35,961
|
https://github.com/jackw/eyeglass-image-dimensions/blob/master/sass/index.scss
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
eyeglass-image-dimensions
|
jackw
|
SCSS
|
Code
| 23
| 113
|
@import "eyeglass/assets";
@function image-width($assetPath) {
@return eg-image-width($assetPath, $eg-registered-assets);
}
@function image-height($assetPath) {
@return eg-image-height($assetPath, $eg-registered-assets);
}
@function image-dimensions($assetPath) {
@return eg-image-dimensions($assetPath, $eg-registered-assets);
}
| 29,261
|
https://github.com/chromium/chromium/blob/master/chrome/test/data/extensions/api_test/gcm/events/on_messages_deleted.js
|
Github Open Source
|
Open Source
|
BSD-3-Clause, GPL-3.0-only
| 2,023
|
chromium
|
chromium
|
JavaScript
|
Code
| 43
| 110
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
onload = function() {
chrome.test.runTests([
function messagesDeleted() {
chrome.test.listenOnce(chrome.gcm.onMessagesDeleted, function() {
chrome.test.assertTrue(true);
});
}
]);
};
| 21,980
|
https://github.com/coderYB/ZYKit/blob/master/Pods/Headers/Private/SensorsAnalyticsSDK/SAServerUrl.h
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ZYKit
|
coderYB
|
C
|
Code
| 183
| 433
|
//
// SAServerUrl.h
// SensorsAnalyticsSDK
//
// Created by 王灼洲 on 2018/1/2.
// Copyright © 2015-2019 Sensors Data Inc. 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.
//
#import <Foundation/Foundation.h>
@interface SAServerUrl : NSObject
@property (nonatomic, copy, readonly) NSString *url;
@property (nonatomic, copy, readonly) NSString *host;
@property (nonatomic, copy, readonly) NSString *project;
@property (nonatomic, copy, readonly) NSString *token;
- (instancetype)initWithUrl:(NSString *)url;
- (BOOL)check:(SAServerUrl *)serverUrl;
/**
解析 URL 的参数
@param urlComponents URL 的 urlComponents
@return 参数字典
*/
+ (NSDictionary *)analysisQueryItemWithURLComponent:(NSURLComponents *)urlComponents;
/**
根据参数拼接 URL Query
@param params 参数字典
@return query 字符串
*/
+ (NSString *)collectURLQueryWithParams:(NSDictionary <NSString *, NSString*>*)params;
@end
| 41,275
|
https://github.com/bozzzzo/quark/blob/master/quarkc/test/emit/expected/java/static/src/main/java/static_/Functions.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,016
|
quark
|
bozzzzo
|
Java
|
Code
| 72
| 855
|
package static_;
public class Functions {
static static_md.Root root = new static_md.Root();
public static final void main(String[] args) {
main(new java.util.ArrayList(java.util.Arrays.asList(args)));
}
public static void main(java.util.ArrayList<String> args) {
do{System.out.println(Foo.count);System.out.flush();}while(false);
Foo f = new Foo();
do{System.out.println(Foo.count);System.out.flush();}while(false);
do{System.out.println(Foo.count);System.out.flush();}while(false);
f = new Foo();
do{System.out.println(Foo.count);System.out.flush();}while(false);
do{System.out.println(Foo.count);System.out.flush();}while(false);
do{System.out.println("==");System.out.flush();}while(false);
(f).test1();
do{System.out.println(Foo.count);System.out.flush();}while(false);
do{System.out.println(Foo.count);System.out.flush();}while(false);
do{System.out.println("==");System.out.flush();}while(false);
(f).test2();
do{System.out.println(Foo.count);System.out.flush();}while(false);
do{System.out.println(Foo.count);System.out.flush();}while(false);
do{System.out.println("==");System.out.flush();}while(false);
(f).test3();
do{System.out.println(Foo.count);System.out.flush();}while(false);
do{System.out.println(Foo.count);System.out.flush();}while(false);
do{System.out.println("==");System.out.flush();}while(false);
(f).test4();
do{System.out.println(Foo.getCount());System.out.flush();}while(false);
do{System.out.println(Foo.getCount());System.out.flush();}while(false);
do{System.out.println("==");System.out.flush();}while(false);
Foo.setCount(0);
do{System.out.println(Foo.count);System.out.flush();}while(false);
do{System.out.println(Foo.count);System.out.flush();}while(false);
do{System.out.println(Foo.getCount());System.out.flush();}while(false);
do{System.out.println(Foo.getCount());System.out.flush();}while(false);
do{System.out.println("==");System.out.flush();}while(false);
Foo.setCount(-(1));
do{System.out.println(Foo.count);System.out.flush();}while(false);
do{System.out.println(Foo.count);System.out.flush();}while(false);
do{System.out.println(Foo.getCount());System.out.flush();}while(false);
do{System.out.println(Foo.getCount());System.out.flush();}while(false);
}
}
| 15,481
|
https://github.com/disco-trooper/blog-api/blob/master/controllers/commentController.js
|
Github Open Source
|
Open Source
|
MIT
| null |
blog-api
|
disco-trooper
|
JavaScript
|
Code
| 159
| 475
|
const { body, validationResult } = require('express-validator');
const debug = require('debug')('commentController');
const createError = require('http-errors');
const Comment = require('../models/comment');
// GET Comments
exports.getComments = async (req, res, next) => {
try {
const comments = await Comment.find({ post_id: req.post_id });
res.json(comments);
} catch (error) {
debug(error);
next(createError(500));
}
};
// POST Comment
exports.postNewComment = [
body('author')
.custom((value) => {
if (value) {
return value.length >= 2 && value.length <= 25;
}
return true;
})
.withMessage('Name must be between 2 and 25 characters long')
.escape(),
body('text').trim(),
async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
debug(errors.array());
next(createError(500));
}
try {
const comment = new Comment({
author: req.body.author ? req.body.author : 'Anonymous',
text: req.body.text,
timestamp: Date.now(),
post_id: req.post_id,
});
await comment.save();
res.status(201);
res.send();
} catch (error) {
debug(error);
next(createError(500));
}
},
];
// DELETE Comment
exports.deleteComment = async (req, res, next) => {
try {
await Comment.findByIdAndDelete(req.params.id);
res.status(200);
res.send();
} catch (error) {
debug(error);
next(createError(500));
}
};
| 13,077
|
https://github.com/cdsalmons/gridgain/blob/master/modules/core/src/test/java/org/gridgain/grid/kernal/processors/cache/GridCacheAbstractMetricsSelfTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,015
|
gridgain
|
cdsalmons
|
Java
|
Code
| 757
| 1,959
|
/*
Copyright (C) GridGain Systems. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* _________ _____ __________________ _____
* __ ____/___________(_)______ /__ ____/______ ____(_)_______
* _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \
* / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /
* \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/
*/
package org.gridgain.grid.kernal.processors.cache;
import org.gridgain.grid.*;
import org.gridgain.grid.cache.*;
import static org.gridgain.grid.cache.GridCacheWriteSynchronizationMode.*;
/**
* Cache metrics test.
*/
public abstract class GridCacheAbstractMetricsSelfTest extends GridCacheAbstractSelfTest {
/** */
private static final int KEY_CNT = 50;
/** {@inheritDoc} */
@Override protected GridCacheWriteSynchronizationMode writeSynchronization() {
return FULL_SYNC;
}
/** {@inheritDoc} */
@Override protected boolean swapEnabled() {
return false;
}
/**
* @return Key count.
*/
protected int keyCount() {
return KEY_CNT;
}
/**
* Gets number of inner reads per "put" operation.
*
* @param isPrimary {@code true} if local node is primary for current key, {@code false} otherwise.
* @return Expected number of inner reads.
*/
protected int expectedReadsPerPut(boolean isPrimary) {
return isPrimary ? 1 : 2;
}
/**
* Gets number of missed per "put" operation.
*
* @param isPrimary {@code true} if local node is primary for current key, {@code false} otherwise.
* @return Expected number of misses.
*/
protected int expectedMissesPerPut(boolean isPrimary) {
return isPrimary ? 1 : 2;
}
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
super.afterTest();
for (int i = 0; i < gridCount(); i++) {
Grid g = grid(i);
g.cache(null).removeAll();
assert g.cache(null).isEmpty();
g.cache(null).resetMetrics();
}
}
/**
* @throws Exception If failed.
*/
public void testWritesReads() throws Exception {
GridCache<Integer, Integer> cache0 = grid(0).cache(null);
int keyCnt = keyCount();
int expReads = 0;
int expMisses = 0;
// Put and get a few keys.
for (int i = 0; i < keyCnt; i++) {
cache0.put(i, i); // +1 read
boolean isPrimary = cache0.affinity().isPrimary(grid(0).localNode(), i);
expReads += expectedReadsPerPut(isPrimary);
expMisses += expectedMissesPerPut(isPrimary);
info("Writes: " + cache0.metrics().writes());
for (int j = 0; j < gridCount(); j++) {
GridCache<Integer, Integer> cache = grid(j).cache(null);
int cacheWrites = cache.metrics().writes();
assertEquals("Wrong cache metrics [i=" + i + ", grid=" + j + ']', i + 1, cacheWrites);
}
assertEquals("Wrong value for key: " + i, Integer.valueOf(i), cache0.get(i)); // +1 read
expReads++;
}
// Check metrics for the whole cache.
long writes = 0;
long reads = 0;
long hits = 0;
long misses = 0;
for (int i = 0; i < gridCount(); i++) {
GridCacheMetrics m = grid(i).cache(null).metrics();
writes += m.writes();
reads += m.reads();
hits += m.hits();
misses += m.misses();
}
info("Stats [reads=" + reads + ", hits=" + hits + ", misses=" + misses + ']');
assertEquals(keyCnt * gridCount(), writes);
assertEquals(expReads, reads);
assertEquals(keyCnt, hits);
assertEquals(expMisses, misses);
}
/**
* @throws Exception If failed.
*/
public void testMisses() throws Exception {
GridCache<Integer, Integer> cache = grid(0).cache(null);
// TODO: GG-7578.
if (cache.configuration().getCacheMode() == GridCacheMode.REPLICATED)
return;
int keyCnt = keyCount();
int expReads = 0;
// Get a few keys missed keys.
for (int i = 0; i < keyCnt; i++) {
assertNull("Value is not null for key: " + i, cache.get(i));
if (cache.affinity().isPrimary(grid(0).localNode(), i))
expReads++;
else
expReads += 2;
}
// Check metrics for the whole cache.
long writes = 0;
long reads = 0;
long hits = 0;
long misses = 0;
for (int i = 0; i < gridCount(); i++) {
GridCacheMetrics m = grid(i).cache(null).metrics();
writes += m.writes();
reads += m.reads();
hits += m.hits();
misses += m.misses();
}
assertEquals(0, writes);
assertEquals(expReads, reads);
assertEquals(0, hits);
assertEquals(expReads, misses);
}
/**
* @throws Exception If failed.
*/
public void testMissesOnEmptyCache() throws Exception {
GridCache<Integer, Integer> cache = grid(0).cache(null);
// TODO: GG-7578.
if (cache.configuration().getCacheMode() == GridCacheMode.REPLICATED)
return;
Integer key = null;
for (int i = 0; i < 1000; i++) {
if (cache.affinity().isPrimary(grid(0).localNode(), i)) {
key = i;
break;
}
}
assertNotNull(key);
cache.get(key);
assertEquals("Expected 1 read", 1, cache.metrics().reads());
assertEquals("Expected 1 miss", 1, cache.metrics().misses());
cache.put(key, key); // +1 read, +1 miss.
cache.get(key);
assertEquals("Expected 1 write", 1, cache.metrics().writes());
assertEquals("Expected 3 reads", 3, cache.metrics().reads());
assertEquals("Expected 2 misses", 2, cache.metrics().misses());
assertEquals("Expected 1 hit", 1, cache.metrics().hits());
}
}
| 2,508
|
https://github.com/piteredo/SOCKET.IO_PHINA.JS_TEST/blob/master/assets.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
SOCKET.IO_PHINA.JS_TEST
|
piteredo
|
JavaScript
|
Code
| 241
| 968
|
//
//
// assets.js
// 2018 @auther piteredo
// This Program is MIT license.
//
//
const ASSETS = {
image: {
"tomapiko": "https://rawgit.com/phi-jp/phina.js/develop/assets/images/tomapiko_ss.png",
"nasupiyo": "https://rawgit.com/phinajs/phina.js/develop/assets/images/character/nasupiyo.png"
},
spritesheet: {
"tomapiko_ss": {
"frame": {
"width": 64,
"height": 64,
"cols": 6,
"rows": 3,
},
"animations": {
"right_down": {
"frames": [7, 8, 6],
"next": "right_down",
"frequency": 4,
},
"down": {
"frames": [7, 8, 6],
"next": "down",
"frequency": 4,
},
"left_down": {
"frames": [7, 8, 6],
"next": "left_down",
"frequency": 4,
},
"left": {
"frames": [13, 14, 12],
"next": "left",
"frequency": 4,
},
"left_up": {
"frames": [10, 11, 9],
"next": "left_up",
"frequency": 4,
},
"up": {
"frames": [10, 11, 9],
"next": "up",
"frequency": 4,
},
"right_up": {
"frames": [10, 11, 9],
"next": "right_up",
"frequency": 4,
},
"right": {
"frames": [16, 17, 15],
"next": "right",
"frequency": 4,
}
}
},
"nasupiyo_ss": {
"frame": {
"width": 64,
"height": 64,
"cols": 6,
"rows": 3,
},
"animations": {
"right_down": {
"frames": [7, 8, 6],
"next": "right_down",
"frequency": 4,
},
"down": {
"frames": [7, 8, 6],
"next": "down",
"frequency": 4,
},
"left_down": {
"frames": [7, 8, 6],
"next": "left_down",
"frequency": 4,
},
"left": {
"frames": [16, 17, 15],
"next": "left",
"frequency": 4,
},
"left_up": {
"frames": [10, 11, 9],
"next": "left_up",
"frequency": 4,
},
"up": {
"frames": [10, 11, 9],
"next": "up",
"frequency": 4,
},
"right_up": {
"frames": [10, 11, 9],
"next": "right_up",
"frequency": 4,
},
"right": {
"frames": [13, 14, 12],
"next": "right",
"frequency": 4,
}
}
}
}
};
| 16,582
|
https://github.com/Rishank2610/gammapy/blob/master/gammapy/astro/darkmatter/utils.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
gammapy
|
Rishank2610
|
Python
|
Code
| 167
| 540
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Utilities to compute J-factor maps."""
import astropy.units as u
__all__ = ["JFactory"]
class JFactory:
"""Compute J-Factor maps.
All J-Factors are computed for annihilation. The assumed dark matter
profiles will be centered on the center of the map.
Parameters
----------
geom : `~gammapy.maps.WcsGeom`
Reference geometry
profile : `~gammapy.astro.darkmatter.profiles.DMProfile`
Dark matter profile
distance : `~astropy.units.Quantity`
Distance to convert angular scale of the map
"""
def __init__(self, geom, profile, distance):
self.geom = geom
self.profile = profile
self.distance = distance
def compute_differential_jfactor(self):
r"""Compute differential J-Factor.
.. math::
\frac{\mathrm d J}{\mathrm d \Omega} =
\int_{\mathrm{LoS}} \mathrm d r \rho(r)
"""
# TODO: Needs to be implemented more efficiently
separation = self.geom.separation(self.geom.center_skydir)
rmin = separation.rad * self.distance
rmax = self.distance
val = [self.profile.integral(_, rmax) for _ in rmin.flatten()]
jfact = u.Quantity(val).to("GeV2 cm-5").reshape(rmin.shape)
return jfact / u.steradian
def compute_jfactor(self):
r"""Compute astrophysical J-Factor.
.. math::
J(\Delta\Omega) =
\int_{\Delta\Omega} \mathrm d \Omega^{\prime}
\frac{\mathrm d J}{\mathrm d \Omega^{\prime}}
"""
diff_jfact = self.compute_differential_jfactor()
return diff_jfact * self.geom.to_image().solid_angle()
| 49,575
|
https://github.com/kjappelbaum/xrd-analysis/blob/master/src/from/__tests__/fromPowDLLXY.test.js
|
Github Open Source
|
Open Source
|
MIT
| null |
xrd-analysis
|
kjappelbaum
|
JavaScript
|
Code
| 58
| 322
|
import { readFileSync } from 'fs';
import { join } from 'path';
import { fromPowDLLXY } from '../fromPowDLLXY';
describe('fromXY', () => {
const xy = readFileSync(
join(__dirname, '../../../testFiles/MG1-Cu2O-28_bg_subtracted.xy'),
'utf8',
);
it('check the dictionary', () => {
const analysis = fromPowDLLXY(xy);
let diffractogram = analysis.getSpectrum();
expect(diffractogram.meta.userName).toBe('Lab Manager');
expect(diffractogram.variables.x.data[0]).toStrictEqual(10);
expect(diffractogram.variables.y.data[1]).toStrictEqual(
-0.0755227112146954,
);
expect(diffractogram.variables.x.data[3448]).toStrictEqual(
70.0050142705441,
);
expect(diffractogram.variables.y.data[3448]).toStrictEqual(0);
expect(diffractogram.variables.x.data).toHaveLength(3449);
expect(diffractogram.variables.y.data).toHaveLength(3449);
});
});
| 37,405
|
https://github.com/trackwayx/Dianoga/blob/master/src/Dianoga/MediaRequestHandler.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
Dianoga
|
trackwayx
|
C#
|
Code
| 115
| 421
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Dianoga.Invokers.MediaCacheAsync;
using Sitecore.Configuration;
using Sitecore.Resources.Media;
using Sitecore.Rules.Conditions;
namespace Dianoga
{
public class MediaRequestHandler : Sitecore.Resources.Media.MediaRequestHandler
{
protected override bool DoProcessRequest(HttpContext context, MediaRequest request, Media media)
{
if (context?.Request.AcceptTypes != null && (context.Request.AcceptTypes).Contains("image/webp"))
{
request.Options.CustomOptions["extension"] = "webp";
}
return base.DoProcessRequest(context, request, media);
}
private static bool AcceptWebP(HttpContext context)
{
return context?.Request.AcceptTypes != null && (context.Request.AcceptTypes).Contains("image/webp");
}
protected override void SendMediaHeaders(Media media, HttpContext context)
{
base.SendMediaHeaders(media, context);
if (MediaManager.Cache is OptimizingMediaCache)
{
// CDNs should only cache the optimized version of the media, so we disallow public caching until the optimization is finished.
if (Settings.MediaResponse.Cacheability != HttpCacheability.NoCache
&& ((OptimizingMediaCache)MediaManager.Cache).IsCurrentlyOptimizing(media))
context.Response.Cache.SetCacheability(HttpCacheability.Private);
}
}
}
}
| 21,400
|
https://github.com/tyron/google-oauth-plugin/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
Apache-2.0, LicenseRef-scancode-unknown-license-reference
| 2,019
|
google-oauth-plugin
|
tyron
|
Ignore List
|
Code
| 15
| 40
|
# Maven
target
work
# IntelliJ IDEA
.idea/
*.iml
# Jenkins
work/
# Emacs
*~
| 23,273
|
https://github.com/agusismawan/rusdiantokom/blob/master/laporan.php
|
Github Open Source
|
Open Source
|
MIT
| null |
rusdiantokom
|
agusismawan
|
PHP
|
Code
| 328
| 1,870
|
<?php include "head.php" ?>
<?php
if (isset($_GET['action']) && $_GET['action']=="detail_transaksi") {
include "detail_transaksi.php";
}
else{
?>
<script type="text/javascript">
document.title="Laporan Penjualan";
document.getElementById('laporan').classList.add('active');
</script>
<div class="content">
<div class="padding">
<div class="bgwhite">
<div class="padding">
<div class="contenttop">
<div class="left">
<h3 class="jdl">Laporan penjualan</h3>
</div>
<div class="right">
<script type="text/javascript">
function gotojenis(val){
var value=val.options[val.selectedIndex].value;
window.location.href="laporan.php?jenis="+value+"";
}
function gotofilter(val){
var value=val.options[val.selectedIndex].value;
window.location.href="laporan.php?jenis=<?php if (isset($_GET['jenis'])) {
echo $_GET['jenis'];
} ?>&filter_record="+value;
}
</script>
<span style="float: left;
padding: 5px;
margin-right: 10px;
color: #666;">Filter dan cetak :</span>
<form action="cetak_laporan.php" style="display: inline;" target="_blank" method="post">
<select class="leftin1" onchange="gotojenis(this)" name="jenis_laporan" required="required">
<option>Pilih Jenis</option>
<option value="perhari" <?php if (isset($_GET['jenis'])&&$_GET['jenis']=='perhari'){ echo "selected"; } ?>>Perhari</option>
<option value="perbulan" <?php if (isset($_GET['jenis'])&&$_GET['jenis']=='perbulan'){ echo "selected"; } ?>>Perbulan</option>
</select>
<select class="leftin1" onchange="gotofilter(this)" required="required" name="tgl_laporan">
<?php
if (isset($_GET['jenis'])&&$_GET['jenis']=='perhari') {
?>
<option>Pilih Hari</option>
<?php
$data=$root->con->query("select distinct date(tgl_transaksi) as tgl_transaksi from transaksi order by id_transaksi desc");
while ($f=$data->fetch_assoc()) {
?>
<option <?php if (isset($_GET['filter_record'])) { if ($_GET['filter_record'] == date('d-m-Y',strtotime($f['tgl_transaksi']))) { echo "selected"; } } ?> value="<?= date('d-m-Y',strtotime($f['tgl_transaksi'])) ?>"><?= date('d-m-Y',strtotime($f['tgl_transaksi'])) ?></option>
<?php
}
}else if(isset($_GET['jenis'])&&$_GET['jenis']=='perbulan') {
?>
<option value="">Pilih Bulan</option>
<?php
$data=$root->con->query("select distinct EXTRACT(YEAR FROM tgl_transaksi) AS OrderYear,EXTRACT(MONTH FROM tgl_transaksi) AS OrderMonth from transaksi order by id_transaksi desc");
while ($f=$data->fetch_assoc()) {
?>
<option <?php if (isset($_GET['filter_record'])) {
if($f['OrderMonth']<=9){
$aaaa="0".$f['OrderMonth']."-".$f['OrderYear'];
}else{
$aaaa=$f['OrderMonth']."-".$f['OrderYear'];
}
if ($_GET['filter_record'] == $aaaa) {
echo "selected"; } } ?>
value="<?php
if($f['OrderMonth']<=9){
echo "0".$f['OrderMonth']."-".$f['OrderYear'];
}else{
echo $f['OrderMonth']."-".$f['OrderYear'];
} ?>"><?php
if($f['OrderMonth']<=9){
echo "0".$f['OrderMonth']."-".$f['OrderYear'];
}else{
echo $f['OrderMonth']."-".$f['OrderYear'];
}
?></option>
<?php
}
}else{
echo "<option>Pilih Jenis Cetak terlebih dahulu</option>";
}
?>
</select>
<button class="btn-ctk" style="background: #41b3f9;color: #fff;border-radius: 3px;border-color: #41b3f9;border:1px solid #41b3f9" <?php if (isset($_GET['filter_record'])) {}else{ ?> disabled="disabled" title="Pilih jenis dan tanggal lebih dulu"<?php } ?>>Cetak</button>
</form>
</div>
<div class="both"></div>
</div>
<table class="datatable" id="datatable">
<thead>
<tr>
<th width="10px">#</th>
<th>No Invoice</th>
<th>Kasir</th>
<th>Pembeli</th>
<th>Tanggal Transaksi</th>
<th>Total Bayar</th>
<th width="60px">Aksi</th>
</tr>
</thead>
<tbody>
<?php
if (isset($_GET['filter_record'])) {
if ($_GET['jenis']=='perhari') {
$aksi1=1;
}else{
$aksi1=2;
}
$root->filter_tampil_laporan($_GET['filter_record'],$aksi1);
}else{
$root->tampil_laporan();
}
?>
</tbody>
<table style="margin-left: 700px">
<tr>
<?php
if (isset($_GET['filter_record'])) {
if ($_GET['jenis']=='perhari') {
$aksi1=1;
}else{
$aksi1=2;
}
$root->hitung_penjualan($_GET['filter_record'],$aksi1);
}
?>
</tr>
</table>
</table>
</div>
</div>
</div>
</div>
<?php
}
include "foot.php" ?>
| 19,453
|
https://github.com/forj-oss/puppet-gardener/blob/master/lib/puppet/parser/functions/to_json.rb
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
puppet-gardener
|
forj-oss
|
Ruby
|
Code
| 209
| 470
|
# (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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.
#
# convert object to json
require 'json' if Puppet.features.json?
module Puppet::Parser::Functions
newfunction(:to_json, :type => :rvalue, :doc => <<-EOS
This function will attempt to take an input object and
convert it to json.
*Arguments:*
object : some object
*Examples:*
to_json( [1,2,3] )
returns : {1,2,3}
EOS
) do |arguments|
Puppet.debug "in to_json.."
unless Puppet.features.json?
Puppet.warning "to_json requires json gem to be installed."
return nil
end
if (arguments.size != 1) then
raise(Puppet::ParseError, "to_json(): Wrong number of arguments "+
"given #{arguments.size} for 1")
end
res_json = nil
begin
res_json = JSON.generate arguments[0]
rescue Exception => e
Puppet.err "problem converting object to_json"
Puppet.err "#{e}"
raise "problem converting object to_json"
end
return res_json
end
end
| 11,526
|
https://github.com/kudocc/CCKit/blob/master/CCKitDemo/other/CCRemoteNotificationManager.m
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
CCKit
|
kudocc
|
Objective-C
|
Code
| 372
| 1,104
|
//
// CCRemoteNotificationManager.m
// dodopay
//
// Created by KudoCC on 2016/12/7.
// Copyright © 2016年 KudoCC. All rights reserved.
//
#import "CCRemoteNotificationManager.h"
#import <UserNotifications/UserNotifications.h>
@interface CCRemoteNotificationManager () <UNUserNotificationCenterDelegate>
@end
@implementation CCRemoteNotificationManager
+ (instancetype)sharedManager {
static CCRemoteNotificationManager *manager;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[CCRemoteNotificationManager alloc] init];
});
return manager;
}
- (instancetype)init {
self = [super init];
if (self) {
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
}
return self;
}
- (void)requestAuthorization {
NSLog(@"%@", NSStringFromSelector(_cmd));
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
// Enable or disable features based on authorization.
NSLog(@"granted:%@, error:%@", @(granted), error.localizedDescription);
}];
}
- (void)requestUserNotificationSettings {
NSLog(@"%@", NSStringFromSelector(_cmd));
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge+UIUserNotificationTypeSound+UIUserNotificationTypeAlert) categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
#pragma mark -
- (void)didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
}
- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token {
NSString *deviceToken = [[[[token description] stringByReplacingOccurrencesOfString:@"<"withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"%@, devToken=%@", NSStringFromSelector(_cmd), deviceToken);
// Forward the token to your server.
//[self enableRemoteNotificationFeatures];
//[self forwardTokenToServer:devTokenBytes];
}
- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"%@, error:%@", NSStringFromSelector(_cmd), [error localizedDescription]);
//NSLog(@"Remote notification support is unavailable due to error: %@", err);
//[self disableRemoteNotificationFeatures];
}
#pragma mark -
/*
If your app is in the foreground when a notification arrives, the notification center calls this method to deliver the notification directly to your app. If you implement this method, you can take whatever actions are necessary to process the notification and update your app. When you finish, execute the completionHandler block and specify how you want the system to alert the user, if at all.
If your delegate does not implement this method, the system silences alerts as if you had passed the UNNotificationPresentationOptionNone option to the completionHandler block. If you do not provide a delegate at all for the UNUserNotificationCenter object, the system uses the notification’s original options to alert the user.
*/
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
NSLog(@"%@", NSStringFromSelector(_cmd));
completionHandler(UNNotificationPresentationOptionAlert);
}
// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler {
NSLog(@"notification info [%@], app state:%ld", response.notification.request.content.userInfo, (long)[UIApplication sharedApplication].applicationState);
completionHandler();
}
@end
| 11,513
|
https://github.com/MatthieuPoullin/ethel-core/blob/master/src/utils/actionMapper.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
ethel-core
|
MatthieuPoullin
|
JavaScript
|
Code
| 302
| 800
|
/* eslint import/no-dynamic-require: 0, no-loop-func: 0 */
const fs = require('fs');
const path = require('path');
const logger = require('../utils/logger');
let instance;
const actions = {};
function getAllFuncs(param) {
let props = [];
let obj = param;
do {
const l = Object.getOwnPropertyNames(obj)
.concat(Object.getOwnPropertySymbols(obj).map(s => s.toString()))
.sort()
.filter((p, i, arr) =>
typeof obj[p] === 'function' && // only the methods
p !== 'constructor' && // not the constructor
(i === 0 || p !== arr[i - 1]) && // not overriding in this prototype
props.indexOf(p) === -1, // not overridden in a child
);
props = props.concat(l);
}
while (
(obj = Object.getPrototypeOf(obj)) && // walk-up the prototype chain
Object.getPrototypeOf(obj) // not the the Object prototype methods (hasOwnProperty, etc...)
);
return props;
}
class ActionMapper {
constructor() {
if (instance === undefined) {
instance = this;
}
return instance;
}
getActions() {
return { ...actions };
}
getAction(actionName) {
if (!actions[actionName]) {
return dialogParams => new Promise((resolve) => { resolve(dialogParams); });
}
return actions[actionName];
}
addAction(actionName, actionFn) {
actions[actionName] = actionFn;
}
mapActions(folder) {
let controllers;
try {
controllers = fs.readdirSync(folder);
} catch (error) {
logger.error(` ==> error mapping ${folder}`);
}
for (let index = 0; index < controllers.length; index++) {
const file = controllers[index];
if (file !== 'index.js') {
const absolutePath = path.resolve(`${folder}/${file}`);
logger.log(` ==> mapping file: ${absolutePath}`);
const ControllerModule = require(`${absolutePath}`);
const controller = new ControllerModule();
const controllerProps = getAllFuncs(controller);
for (let i = 0; i < controllerProps.length; i += 1) {
const action = controllerProps[i];
if (typeof controller[action] === 'function'
&& (action.length > 0 && action[0] !== '_')) {
let actionName;
const controllerName = file.split('Actions.js')[0];
if (action === 'index') {
actionName = controllerName;
} else {
actionName = `${controllerName}.${action.replace(/__/g,'.')}`;
}
actionName = actionName.toLowerCase();
logger.log(` -> mapping action: ${actionName}`);
this.addAction(actionName, controller[action]);
}
}
}
}
}
}
module.exports = new ActionMapper();
| 25,758
|
https://github.com/ryankurte/codechecker/blob/master/web/server/vue-cli/src/components/Icons/AnalyzerStatisticsIcon.vue
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
codechecker
|
ryankurte
|
Vue
|
Code
| 36
| 141
|
<template>
<v-icon
v-if="value === 'successful'"
color="#587549"
>
mdi-check
</v-icon>
<v-icon
v-else-if="value === 'failed'"
color="#964739"
>
mdi-close
</v-icon>
</template>
<script>
export default {
name: "AnalyzerStatisticsIcon",
props: {
value: { type: String, required: true }
}
};
</script>
| 47,644
|
https://github.com/dravanet/ganeti-extstorage-csi/blob/master/pkg/ganeti/extstorage/interface.go
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| null |
ganeti-extstorage-csi
|
dravanet
|
Go
|
Code
| 912
| 1,479
|
package extstorage
import "context"
// Interface is the ganeti-extstorage interface according to
// https://docs.ganeti.org/docs/ganeti/3.0/html/man-ganeti-extstorage-interface.html#executable-scripts
type Interface interface {
/*
The create command is used for creating a new volume inside the external storage. The VOL_NAME denotes the volume’s name, which should be unique. After creation, Ganeti will refer to this volume by this name for all other actions.
Ganeti produces this name dynamically and ensures its uniqueness inside the Ganeti context. Therefore, you should make sure not to provision manually additional volumes inside the external storage with this type of name, because this will lead to conflicts and possible loss of data.
The VOL_SIZE variable denotes the size of the new volume to be created in mebibytes.
If the script ends successfully, a new volume of size VOL_SIZE should exist inside the external storage. e.g:: a lun inside a NAS appliance.
The script returns 0 on success.
*/
Create(context.Context, *VolumeInfo) error
/*
This command is used in order to make an already created volume visible to the physical node which will host the instance. This is done by mapping the already provisioned volume to a block device inside the host node.
The VOL_NAME variable denotes the volume to be mapped.
After successful attachment the script returns to its stdout a string, which is the full path of the block device to which the volume is mapped. e.g:: /dev/dummy1
When attach returns, this path should be a valid block device on the host node.
The attach script should be idempotent if the volume is already mapped. If the requested volume is already mapped, then the script should just return to its stdout the path which is already mapped to.
In case the storage technology supports userspace access to volumes as well, e.g. the QEMU Hypervisor can see an RBD volume using its embedded driver for the RBD protocol, then the provider can return extra lines denoting the available userspace access URIs per hypervisor. The URI should be in the following format: <hypervisor>:<uri>. For example, a RADOS provider should return kvm:rbd:<pool>/<volume name> in the second line of stdout after the local block device path (e.g. /dev/rbd1).
So, if the access disk parameter is userspace for the ext disk template, then the QEMU command will end up having file=<URI> in the -drive option.
In case the storage technology supports only userspace access to volumes, then the first line of stdout should be an empty line, denoting that a local block device is not available. If neither a block device nor a URI is returned, then Ganeti will complain.
*/
Attach(context.Context, *VolumeInfo) error
/*
This command is used in order to unmap an already mapped volume from the host node. Detach undoes everything attach did. This is done by unmapping the requested volume from the block device it is mapped to.
The VOL_NAME variable denotes the volume to be unmapped.
detach doesn’t affect the volume itself. It just unmaps it from the host node. The volume continues to exist inside the external storage. It’s just not accessible by the node anymore. This script doesn’t return anything to its stdout.
The detach script should be idempotent if the volume is already unmapped. If the volume is not mapped, the script doesn’t perform any action at all.
The script returns 0 on success.
*/
Detach(context.Context, *VolumeInfo) error
/*
This command is used to remove an existing volume from the external storage. The volume is permanently removed from inside the external storage along with all its data.
The VOL_NAME variable denotes the volume to be removed.
The script returns 0 on success.
*/
Remove(context.Context, *VolumeInfo) error
/*
This command is used to grow an existing volume of the external storage.
The VOL_NAME variable denotes the volume to grow.
The VOL_SIZE variable denotes the current volume’s size (in mebibytes). The VOL_NEW_SIZE variable denotes the final size after the volume has been grown (in mebibytes).
The amount of grow can be easily calculated by the script and is:
grow_amount = VOL_NEW_SIZE - VOL_SIZE (in mebibytes)
Ganeti ensures that: VOL_NEW_SIZE > VOL_SIZE
If the script returns successfully, then the volume inside the external storage will have a new size of VOL_NEW_SIZE. This isn’t immediately reflected to the instance’s disk. See gnt-instance grow for more details on when the running instance becomes aware of its grown disk.
The script returns 0 on success.
*/
Grow(context.Context, *VolumeInfo) error
/*
This script is used to add metadata to an existing volume. It is helpful when we need to keep an external, Ganeti-independent mapping between instances and volumes; primarily for recovery reasons. This is provider specific and the author of the provider chooses whether/how to implement this. You can just exit with 0, if you do not want to implement this feature, without harming the overall functionality of the provider.
The VOL_METADATA variable contains the metadata of the volume.
Currently, Ganeti sets this value to originstname+X where X is the instance’s name.
The script returns 0 on success.
*/
Setinfo(context.Context, *VolumeInfo) error
/*
The verify script is used to verify consistency of the external parameters (ext-params) (see below). The command should take one or more arguments denoting what checks should be performed, and return a proper exit code depending on whether the validation failed or succeeded.
Currently, the script is not invoked by Ganeti, but should be present for future use and consistency with gnt-os-interface’s verify script.
The script should return 0 on success.
*/
Verify(context.Context, *VolumeInfo) error
// Close closes the driver
Close(context.Context) error
}
| 39,010
|
https://github.com/i-gaven/Just_a_dumper/blob/master/all_headers/百度 - 有事搜一搜,没事看一看-10.4.5(越狱应用)_headers/HSWebCore.h
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
Just_a_dumper
|
i-gaven
|
Objective-C
|
Code
| 661
| 3,575
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <UIKit/UIView.h>
#import "HSPanGestureManagerDelegate-Protocol.h"
#import "HSUIWebViewDelegate-Protocol.h"
#import "HSWebViewProviderDelegate-Protocol.h"
#import "UIWebViewDelegate-Protocol.h"
#import "WKNavigationDelegate-Protocol.h"
#import "WKUIDelegate-Protocol.h"
@class BBADialog, HSBrowseActionEngine, HSBrowseSpeedEngine, HSCommandEngine, HSCookieEngine, HSDecideActionEngine, HSFileDownloadEngine, HSHeaderEngine, HSHistoryEngine, HSJSEngine, HSLightAppEngine, HSLoadFailEngine, HSNetworkEngine, HSPageLoadInfoEngine, HSPanGestureManager, HSPassportEngine, HSPreloadEngine, HSResourcesEngine, HSRewriteEngine, HSSchemeEngine, HSScrollViewEngine, HSSearchEngine, HSUIWebView, HSURLProtocolEngine, HSUntrustCertEngine, HSUserStatisticEngine, HSVideoEngine, HSWebCoreStateController, HSWebViewProvider, HSWebsiteBlockEngine, NSNumber, NSString, NSURLRequest;
@protocol HSWebCoreDelegate;
@interface HSWebCore : UIView <HSWebViewProviderDelegate, UIWebViewDelegate, HSUIWebViewDelegate, WKNavigationDelegate, WKUIDelegate, HSPanGestureManagerDelegate>
{
_Bool _enableWK;
UIView *_containerHistoryView;
_Bool _enableWKWebView;
_Bool _isWKABTesting;
_Bool _shouldUploadLandingPageTiming;
_Bool _landingPageFromTCJump;
id <HSWebCoreDelegate> _webCoreDelegate;
HSUIWebView *_webView;
HSWebViewProvider *_webViewProvider;
HSWebCoreStateController *_stateMachine;
id _viewContext;
NSURLRequest *_lastLoadRequest;
HSBrowseActionEngine *_browseActionEngine;
HSBrowseSpeedEngine *_browseSpeedEngine;
HSCommandEngine *_commandEngine;
HSFileDownloadEngine *_fileDownloadEngine;
HSHeaderEngine *_headerEngine;
HSHistoryEngine *_historyEngine;
HSJSEngine *_JSEngine;
HSLightAppEngine *_LAEngine;
HSLoadFailEngine *_loadFailEngine;
HSNetworkEngine *_networkEngine;
HSPreloadEngine *_preloadEngine;
HSResourcesEngine *_resourcesEngine;
HSScrollViewEngine *_scrollEngine;
HSSearchEngine *_searchEngine;
HSUntrustCertEngine *_untrustCertEngine;
HSURLProtocolEngine *_URLProtocolEngine;
HSUserStatisticEngine *_usEngine;
HSVideoEngine *_videoEngine;
HSWebsiteBlockEngine *_websiteBlockEngine;
HSPassportEngine *_passportEngine;
HSCookieEngine *_cookieEngine;
HSSchemeEngine *_schemeEngine;
HSRewriteEngine *_rewriteEngine;
HSPageLoadInfoEngine *_pageLoadInfoEngine;
HSDecideActionEngine *_decideActionEngine;
HSPanGestureManager *_backForwardGestureManager;
BBADialog *_dialogWindow;
NSNumber *_userClickedLinkTimestamp;
double _firstLayoutTimestamp;
double _firstVistuallNoneEmptyTimestamp;
}
+ (id)hadesSDKVersion;
@property(nonatomic) double firstVistuallNoneEmptyTimestamp; // @synthesize firstVistuallNoneEmptyTimestamp=_firstVistuallNoneEmptyTimestamp;
@property(nonatomic) double firstLayoutTimestamp; // @synthesize firstLayoutTimestamp=_firstLayoutTimestamp;
@property(nonatomic) _Bool landingPageFromTCJump; // @synthesize landingPageFromTCJump=_landingPageFromTCJump;
@property(retain, nonatomic) NSNumber *userClickedLinkTimestamp; // @synthesize userClickedLinkTimestamp=_userClickedLinkTimestamp;
@property(nonatomic) _Bool shouldUploadLandingPageTiming; // @synthesize shouldUploadLandingPageTiming=_shouldUploadLandingPageTiming;
@property(retain, nonatomic) BBADialog *dialogWindow; // @synthesize dialogWindow=_dialogWindow;
@property(retain, nonatomic) HSPanGestureManager *backForwardGestureManager; // @synthesize backForwardGestureManager=_backForwardGestureManager;
@property(retain, nonatomic) HSDecideActionEngine *decideActionEngine; // @synthesize decideActionEngine=_decideActionEngine;
@property(retain, nonatomic) HSPageLoadInfoEngine *pageLoadInfoEngine; // @synthesize pageLoadInfoEngine=_pageLoadInfoEngine;
@property(retain, nonatomic) HSRewriteEngine *rewriteEngine; // @synthesize rewriteEngine=_rewriteEngine;
@property(retain, nonatomic) HSSchemeEngine *schemeEngine; // @synthesize schemeEngine=_schemeEngine;
@property(retain, nonatomic) HSCookieEngine *cookieEngine; // @synthesize cookieEngine=_cookieEngine;
@property(retain, nonatomic) HSPassportEngine *passportEngine; // @synthesize passportEngine=_passportEngine;
@property(retain, nonatomic) HSWebsiteBlockEngine *websiteBlockEngine; // @synthesize websiteBlockEngine=_websiteBlockEngine;
@property(retain, nonatomic) HSVideoEngine *videoEngine; // @synthesize videoEngine=_videoEngine;
@property(retain, nonatomic) HSUserStatisticEngine *usEngine; // @synthesize usEngine=_usEngine;
@property(retain, nonatomic) HSURLProtocolEngine *URLProtocolEngine; // @synthesize URLProtocolEngine=_URLProtocolEngine;
@property(retain, nonatomic) HSUntrustCertEngine *untrustCertEngine; // @synthesize untrustCertEngine=_untrustCertEngine;
@property(retain, nonatomic) HSSearchEngine *searchEngine; // @synthesize searchEngine=_searchEngine;
@property(retain, nonatomic) HSScrollViewEngine *scrollEngine; // @synthesize scrollEngine=_scrollEngine;
@property(retain, nonatomic) HSResourcesEngine *resourcesEngine; // @synthesize resourcesEngine=_resourcesEngine;
@property(retain, nonatomic) HSPreloadEngine *preloadEngine; // @synthesize preloadEngine=_preloadEngine;
@property(retain, nonatomic) HSNetworkEngine *networkEngine; // @synthesize networkEngine=_networkEngine;
@property(retain, nonatomic) HSLoadFailEngine *loadFailEngine; // @synthesize loadFailEngine=_loadFailEngine;
@property(retain, nonatomic) HSLightAppEngine *LAEngine; // @synthesize LAEngine=_LAEngine;
@property(retain, nonatomic) HSJSEngine *JSEngine; // @synthesize JSEngine=_JSEngine;
@property(retain, nonatomic) HSHistoryEngine *historyEngine; // @synthesize historyEngine=_historyEngine;
@property(retain, nonatomic) HSHeaderEngine *headerEngine; // @synthesize headerEngine=_headerEngine;
@property(retain, nonatomic) HSFileDownloadEngine *fileDownloadEngine; // @synthesize fileDownloadEngine=_fileDownloadEngine;
@property(retain, nonatomic) HSCommandEngine *commandEngine; // @synthesize commandEngine=_commandEngine;
@property(retain, nonatomic) HSBrowseSpeedEngine *browseSpeedEngine; // @synthesize browseSpeedEngine=_browseSpeedEngine;
@property(retain, nonatomic) HSBrowseActionEngine *browseActionEngine; // @synthesize browseActionEngine=_browseActionEngine;
@property(retain, nonatomic) NSURLRequest *lastLoadRequest; // @synthesize lastLoadRequest=_lastLoadRequest;
@property(nonatomic) __weak id viewContext; // @synthesize viewContext=_viewContext;
@property(retain, nonatomic) HSWebCoreStateController *stateMachine; // @synthesize stateMachine=_stateMachine;
@property(retain, nonatomic) HSWebViewProvider *webViewProvider; // @synthesize webViewProvider=_webViewProvider;
@property(retain, nonatomic) HSUIWebView *webView; // @synthesize webView=_webView;
@property(nonatomic) _Bool isWKABTesting; // @synthesize isWKABTesting=_isWKABTesting;
@property(nonatomic) _Bool enableWKWebView; // @synthesize enableWKWebView=_enableWKWebView;
@property(nonatomic) __weak id <HSWebCoreDelegate> webCoreDelegate; // @synthesize webCoreDelegate=_webCoreDelegate;
- (void).cxx_destruct;
- (void)clearHistoryContainerView;
- (id)historyContainerView;
- (id)currentURL;
- (id)goForwardURL;
- (id)goBackURL;
- (void)endGesture:(_Bool)arg1 direction:(unsigned long long)arg2;
- (void)beginGesture:(unsigned long long)arg1;
- (void)reportkMMSVoiceSearchHalfViewWillAppearHandleNotification:(id)arg1;
- (void)applicationWillEnterForegroundNotification:(id)arg1;
- (void)applicationWillResignActive:(id)arg1;
- (void)setBounces:(_Bool)arg1;
- (void)loadDefaultSettings;
- (unsigned long long)experimentCoreType;
- (void)loadHTMLPath:(id)arg1 baseURL:(id)arg2 createNewPage:(_Bool)arg3;
- (void)loadHTMLPath:(id)arg1 baseURL:(id)arg2;
- (void)loadURL:(id)arg1 createNewPage:(_Bool)arg2;
- (void)loadURL:(id)arg1;
- (void)loadWebCore;
- (_Bool)HSUIWebView:(id)arg1 shouldDecideForAction:(id)arg2 request:(id)arg3;
- (void)HSUIWebView:(id)arg1 restoreStateToHistoryItem:(id)arg2;
- (void)HSUIWebView:(id)arg1 saveStateToHistoryItem:(id)arg2;
- (void)HSUIWebViewDidReceiveMainFrameFirstPaint:(id)arg1;
- (void)HSUIWebViewDidReceiveFirstLayout:(id)arg1;
- (void)HSUIWebView:(id)arg1 didReceiveTitle:(id)arg2 forFrame:(id)arg3;
- (void)dealloc;
- (id)init;
- (id)initWithCoder:(id)arg1;
- (id)initWithFrame:(struct CGRect)arg1;
- (id)viewContextView;
- (id)loadCustomEngine:(id)arg1 forClass:(Class)arg2;
- (void)cancelNoneFinishRequestHandler;
- (void)handleNoneFinishRequest;
- (void)uploadLandingPageTiming;
- (void)extractTimeStampFromTCURL:(id)arg1;
- (_Bool)mainFrameIsFileRequest;
- (_Bool)urlIsFileRequest:(id)arg1;
- (void)handleFailedViewDisplayWithError:(id)arg1;
- (void)handleNetworkRequestFailure:(id)arg1;
- (id)sourceViewController;
- (_Bool)isAppScheme:(id)arg1;
- (void)reportHSURLProtocolEngineRequestFailedNotification:(id)arg1;
- (void)reportHSURLProtocolEngineRequestFinishedNotification:(id)arg1;
- (void)HSWebCoreDidFailLoadWithError:(id)arg1;
- (void)HSWebCoreDidFinishLoad;
- (void)HSWebCoreDidStartLoad;
- (void)HSWebCoreShouldStartLoadWithRequestFinished:(id)arg1 navigationAction:(id)arg2;
- (void)alertUBCByTapButtonValue:(id)arg1;
- (void)applicationOpenURL:(id)arg1;
- (void)checkIsNeedDisplayAlertViewOrDerictOpenForUrl:(id)arg1;
- (_Bool)HSWebCoreShouldStartLoadWithRequest:(id)arg1 navigationAction:(id)arg2 webView:(id)arg3;
- (void)webViewProvider:(id)arg1 runJavaScriptTextInputPanelWithPrompt:(id)arg2 defaultText:(id)arg3 initiatedByFrame:(id)arg4 completionHandler:(CDUnknownBlockType)arg5;
- (void)webViewProvider:(id)arg1 runJavaScriptConfirmPanelWithMessage:(id)arg2 initiatedByFrame:(id)arg3 completionHandler:(CDUnknownBlockType)arg4;
- (void)webViewProvider:(id)arg1 runJavaScriptAlertPanelWithMessage:(id)arg2 initiatedByFrame:(id)arg3 completionHandler:(CDUnknownBlockType)arg4;
- (_Bool)webViewProvider:(id)arg1 decidePolicyForNavigationResponse:(id)arg2;
- (void)webViewProviderDidCommitNavigation:(id)arg1;
- (void)webViewProviderProcessDidTerminate:(id)arg1;
- (void)webViewProviderProgressEndUpdate:(id)arg1;
- (void)webViewProviderProgressBeginUpdate:(id)arg1;
- (void)webViewProvider:(id)arg1 firstShouldStartLoadWithNavigationAction:(id)arg2;
- (_Bool)webViewProvider:(id)arg1 shouldStartLoadWithRequest:(id)arg2 navigationAction:(id)arg3;
- (void)webViewProvider:(id)arg1 didFailLoadWithError:(id)arg2;
- (void)webViewProviderDidFinishLoad:(id)arg1;
- (void)webViewProviderDidStartLoad:(id)arg1;
- (void)webViewProvider:(id)arg1 withWKUserContentController:(id)arg2;
- (void)webView:(id)arg1 didFailLoadWithError:(id)arg2;
- (void)webViewDidFinishLoad:(id)arg1;
- (void)webViewDidStartLoad:(id)arg1;
- (_Bool)webView:(id)arg1 shouldStartLoadWithRequest:(id)arg2 navigationType:(long long)arg3;
- (_Bool)loadEngine:(id)arg1 forClass:(Class)arg2;
- (void)loadEngines;
- (void)preLoadViews;
- (void)loadViews;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 46,108
|
https://github.com/TheGrizzlyDev/natalie/blob/master/include/natalie/string.hpp
|
Github Open Source
|
Open Source
|
MIT
| null |
natalie
|
TheGrizzlyDev
|
C++
|
Code
| 1,466
| 4,345
|
#pragma once
#include <assert.h>
#include <ctype.h>
#include <stdarg.h>
#include <string.h>
#include "natalie/forward.hpp"
#include "natalie/gc.hpp"
// from dtoa.c by David Gay
extern "C" char *dtoa(double d, int mode, int ndigits, int *decpt, int *sign, char **rve);
namespace Natalie {
class String : public Cell {
public:
const int STRING_GROW_FACTOR = 2;
String() {
set_str("");
}
String(const char *str) {
assert(str);
set_str(str);
}
String(const char *str, size_t length) {
assert(str);
set_str(str, length);
}
String(const String &other) {
set_str(other.c_str(), other.length());
}
String(const String *other) {
assert(other);
set_str(other->c_str(), other->length());
}
String(char c) {
char buf[2] = { c, 0 };
set_str(buf);
}
String(size_t length, char c) {
char buf[length];
memset(buf, c, sizeof(char) * length);
set_str(buf, length);
}
String(long long number) {
int length = snprintf(NULL, 0, "%lli", number);
char buf[length + 1];
snprintf(buf, length + 1, "%lli", number);
set_str(buf);
}
String(int number) {
int length = snprintf(NULL, 0, "%d", number);
char buf[length + 1];
snprintf(buf, length + 1, "%d", number);
set_str(buf);
}
String(double number, int precision = 4) {
int length = snprintf(NULL, 0, "%.*f", precision, number);
char buf[length + 1];
snprintf(buf, length + 1, "%.*f", precision, number);
set_str(buf);
}
virtual ~String() override {
delete[] m_str;
}
String &operator=(const String &other) {
set_str(other.c_str(), other.length());
return *this;
}
char at(size_t index) const {
assert(index < m_length);
return m_str[index];
}
char operator[](size_t index) const {
return m_str[index];
}
char &operator[](size_t index) { return m_str[index]; }
char last_char() const {
assert(m_length > 0);
return m_str[m_length - 1];
}
char pop_char() {
assert(m_length > 0);
return m_str[--m_length];
}
String *clone() const { return new String { *this }; }
String *substring(size_t start, size_t length) const {
assert(start < m_length);
assert(start + length <= m_length);
return new String(c_str() + start, length);
}
String *substring(size_t start) const {
return substring(start, m_length - start);
}
const char *c_str() const { return m_str; }
size_t bytesize() const { return m_length; }
size_t length() const { return m_length; }
size_t size() const { return m_length; }
size_t capacity() const { return m_capacity; }
void set_str(const char *str) {
assert(str);
auto old_str = m_str;
m_length = strlen(str);
m_capacity = m_length;
m_str = new char[m_length + 1];
memcpy(m_str, str, sizeof(char) * (m_length + 1));
if (old_str)
delete[] old_str;
}
void set_str(const char *str, size_t length) {
assert(str);
auto old_str = m_str;
m_str = new char[length + 1];
memcpy(m_str, str, sizeof(char) * length);
m_str[length] = 0;
m_length = length;
m_capacity = length;
if (old_str)
delete[] old_str;
}
void prepend_char(char c) {
size_t total_length = m_length + 1;
grow_at_least(total_length);
memmove(m_str + 1, m_str, m_length + 1); // 1 extra for null terminator
m_str[0] = c;
m_length = total_length;
}
void prepend(long long i) {
int length = snprintf(NULL, 0, "%lli", i);
char buf[length + 1];
snprintf(buf, length + 1, "%lli", i);
prepend(buf);
}
void prepend(const char *str) {
if (!str) return;
size_t new_length = strlen(str);
if (new_length == 0) return;
char buf[m_length + 1];
memcpy(buf, m_str, sizeof(char) * (m_length + 1));
set_str(str);
append(buf);
}
void prepend(const String *str) {
if (!str) return;
size_t new_length = str->length();
if (new_length == 0) return;
char buf[new_length + m_length + 1];
memcpy(buf, str->m_str, sizeof(char) * new_length);
memcpy(buf + new_length, m_str, sizeof(char) * (m_length + 1));
set_str(buf);
}
void insert(size_t position, char c) {
assert(position < m_length);
grow_at_least(m_length + 1);
m_length++;
size_t nbytes = m_length - position + 1; // 1 extra for null terminator
memmove(m_str + position + 1, m_str + position, nbytes);
m_str[position] = c;
}
void append_char(char c) {
size_t total_length = m_length + 1;
grow_at_least(total_length);
m_str[total_length - 1] = c;
m_str[total_length] = 0;
m_length = total_length;
}
void append(signed char c) {
size_t total_length = m_length + 1;
grow_at_least(total_length);
m_str[total_length - 1] = c;
m_str[total_length] = 0;
m_length = total_length;
}
void append(unsigned char c) {
append(static_cast<signed char>(c));
}
void append(size_t i) {
int length = snprintf(NULL, 0, "%zu", i);
char buf[length + 1];
snprintf(buf, length + 1, "%zu", i);
append(buf);
}
void append(long long i) {
int length = snprintf(NULL, 0, "%lli", i);
char buf[length + 1];
snprintf(buf, length + 1, "%lli", i);
append(buf);
}
void append(int i) {
int length = snprintf(NULL, 0, "%i", i);
char buf[length + 1];
snprintf(buf, length + 1, "%i", i);
append(buf);
}
void append(const char *str) {
if (!str) return;
size_t new_length = strlen(str);
if (new_length == 0) return;
size_t total_length = m_length + new_length;
grow_at_least(total_length);
strncat(m_str, str, total_length - m_length);
m_length = total_length;
}
void append_sprintf(const char *format, ...) {
va_list args, args_copy;
va_start(args, format);
append_vsprintf(format, args);
va_end(args);
}
void append_vsprintf(const char *format, va_list args) {
va_list args_copy;
va_copy(args_copy, args);
int fmt_length = vsnprintf(nullptr, 0, format, args_copy);
va_end(args_copy);
char buf[fmt_length + 1];
vsnprintf(buf, fmt_length + 1, format, args);
append(buf);
}
void append(const String *str) {
if (!str) return;
if (str->length() == 0) return;
size_t total_length = m_length + str->length();
grow_at_least(total_length);
memcpy(m_str + m_length, str->m_str, sizeof(char) * str->length());
m_length = total_length;
}
void append(const StringObject *str);
void append(size_t n, char c) {
size_t total_length = m_length + n;
grow_at_least(total_length);
memset(m_str + m_length, c, sizeof(char) * n);
m_length = total_length;
m_str[m_length] = 0;
}
bool operator==(const String &other) const {
if (length() != other.length())
return false;
return memcmp(m_str, other.c_str(), sizeof(char) * m_length) == 0;
}
bool operator==(const char *other) const {
assert(other);
if (length() != strlen(other))
return false;
return memcmp(m_str, other, sizeof(char) * m_length) == 0;
}
bool operator!=(const String &other) const {
return !operator==(other);
}
bool operator>(const String &other) const {
return strcmp(m_str, other.c_str()) > 0;
}
bool operator<(const String &other) const {
return strcmp(m_str, other.c_str()) < 0;
}
ssize_t find(const String &needle) const {
if (m_length < needle.length())
return -1;
size_t max_index = m_length - needle.length();
size_t byte_count = sizeof(char) * needle.length();
for (size_t index = 0; index <= max_index; ++index) {
if (memcmp(m_str + index, needle.c_str(), byte_count) == 0)
return index;
}
return -1;
}
ssize_t find(const char c) const {
for (size_t i = 0; i < m_length; ++i) {
if (c == m_str[i]) return i;
}
return -1;
}
void truncate(size_t length) {
assert(length <= m_length);
m_str[length] = 0;
m_length = length;
}
void clear() { truncate(0); }
void chomp() { truncate(m_length - 1); }
void strip_trailing_whitespace() {
while (m_length > 0) {
switch (m_str[m_length - 1]) {
case ' ':
case '\t':
case '\n':
case '\r':
chomp();
break;
default:
return;
}
}
}
void strip_trailing_spaces() {
while (m_length > 0) {
if (m_str[m_length - 1] == ' ')
chomp();
else
return;
}
}
void remove(char character) {
size_t i;
int offset = 0;
for (i = 0; i < m_length; ++i) {
if (m_str[i] == character) {
for (size_t j = i; j < m_length; ++j)
m_str[j] = m_str[j + 1];
--m_length;
--i;
}
}
m_str[m_length] = '\0';
}
bool is_empty() const { return m_length == 0; }
String successive() {
auto result = String { *this };
size_t index = length() - 1;
char last_char = m_str[index];
if (last_char == 'z') {
result.increment_successive_char('a', 'a', 'z');
} else if (last_char == 'Z') {
result.increment_successive_char('A', 'A', 'Z');
} else if (last_char == '9') {
result.increment_successive_char('0', '1', '9');
} else {
result.m_str[index]++;
}
return result;
}
template <typename... Args>
static String *format(const char *fmt, Args... args) {
String *out = new String {};
format(out, fmt, args...);
return out;
}
static void format(String *out, const char *fmt) {
for (const char *c = fmt; *c != 0; c++) {
out->append_char(*c);
}
}
template <typename T, typename... Args>
static void format(String *out, const char *fmt, T first, Args... rest) {
for (const char *c = fmt; *c != 0; c++) {
if (*c == '{' && *(c + 1) == '}') {
c++;
out->append(first);
format(out, c + 1, rest...);
return;
} else {
out->append_char(*c);
}
}
}
virtual void visit_children(Visitor &visitor) override final {
}
virtual void gc_inspect(char *buf, size_t len) const override {
snprintf(buf, len, "<String %p str='%s'>", this, m_str);
}
String *uppercase() const {
auto new_str = new String(this);
for (size_t i = 0; i < new_str->m_length; ++i) {
new_str->m_str[i] = toupper(new_str->m_str[i]);
}
return new_str;
}
String *lowercase() const {
auto new_str = new String(this);
for (size_t i = 0; i < new_str->m_length; ++i) {
new_str->m_str[i] = tolower(new_str->m_str[i]);
}
return new_str;
}
private:
void grow(size_t new_capacity) {
assert(new_capacity >= m_length);
auto old_str = m_str;
m_str = new char[new_capacity + 1];
memcpy(m_str, old_str, sizeof(char) * (m_capacity + 1));
delete[] old_str;
m_capacity = new_capacity;
}
void grow_at_least(size_t min_capacity) {
if (m_capacity >= min_capacity) return;
if (m_capacity > 0 && min_capacity <= m_capacity * STRING_GROW_FACTOR) {
grow(m_capacity * STRING_GROW_FACTOR);
} else {
grow(min_capacity);
}
}
void increment_successive_char(char append, char begin_char, char end_char) {
assert(m_length > 0);
ssize_t index = m_length - 1;
char last_char = m_str[index];
while (last_char == end_char) {
m_str[index] = begin_char;
last_char = m_str[--index];
}
if (index == -1) {
this->append_char(append);
} else {
m_str[index]++;
}
}
char *m_str { nullptr };
size_t m_length { 0 };
size_t m_capacity { 0 };
};
}
| 1,093
|
https://github.com/pg83/mix/blob/master/pkgs/boot/9/flex/2.5.10.0.sh
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
mix
|
pg83
|
Shell
|
Code
| 209
| 726
|
{% extends '//mix/template/c_std.sh' %}
{% block fetch %}
https://github.com/westes/flex/archive/refs/tags/flex-2-5-10.tar.gz
4e57770c7dfc2b1d113729f62d6ae3b6
{% block flex_extra_fetch %}
https://gitlab.com/giomasce/flex/-/raw/506e9605baf4638ba47d37133c348df1385ef06c/scan.lex.l
3a8bef1b4d0b0823aff29ff0dc76d8c3
{% endblock %}
{% endblock %}
{% block bld_libs %}
{% endblock %}
{% block bld_deps %}
boot/9/lex
boot/4/byacc
boot/8/env/std
{% endblock %}
{% block unpack %}
extract1 ${src}/flex*
{% endblock %}
{% block c_rename_symbol %}
warn
{% endblock %}
{% block build %}
cat << EOF > config.h
#define HAVE_DCGETTEXT 1
#define HAVE_GETTEXT 1
#define HAVE_INTTYPES_H 1
#define HAVE_MEMORY_H 1
#define HAVE_STDBOOL_H 1
#define HAVE_STDINT_H 1
#define HAVE_STDLIB_H 1
#define HAVE_STRINGS_H 1
#define HAVE_STRING_H 1
#define HAVE_SYS_STAT_H 1
#define HAVE_SYS_TYPES_H 1
#define HAVE_UNISTD_H 1
#define PACKAGE "flex"
#define PACKAGE_BUGREPORT "help-flex@gnu.org"
#define PACKAGE_NAME "flex"
#define PACKAGE_STRING "flex 2.5.10"
#define PACKAGE_TARNAME "flex"
#define PACKAGE_URL ""
#define PACKAGE_VERSION "2.5.10"
#define STDC_HEADERS 1
#define VERSION "2.5.11"
#define YYTEXT_POINTER 1
EOF
byacc -d parse.y
mv y.tab.h parse.h
mv y.tab.c parse.c
{% block invoke_lex %}
lex ${src}/scan.lex.l
sed -e 's|yylex|flexscan|g' < lex.yy.c > scan.c
{% endblock %}
sh mkskel.sh ./flex.skl > skel.c
for x in ccl dfa ecs gen main misc nfa parse scan skel sym tblcmp yylex options scanopt buf; do
${CC} -c -o ${x}.o ${x}.c
done
${CC} -o flex *.o
{% endblock %}
{% block install %}
mkdir ${out}/bin && cp flex ${out}/bin/
{% endblock %}
| 22,025
|
https://github.com/YasserMahdi/E_Archiver/blob/master/app/Http/Controllers/ImgController.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
E_Archiver
|
YasserMahdi
|
PHP
|
Code
| 300
| 1,389
|
<?php
namespace App\Http\Controllers;
use App\Empimg;
use App\Programimg;
use App\Unitimg;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Image;
use Illuminate\Support\Facades\Response;
class ImgController extends Controller
{
// public function uploadEmpImg(Request $request)
// {
// if($request->isMethod('post'))
// {
// $data = new Empimg();
//
// $url = $request["image"]->store("public");
// $data["doc"] = str_replace("public", "/storage", $url);
//
// $data["name"] = $request["name"];
// $data["emp_id"] = $request["id"];
//
// $data->save();
// $newImg = new Empimg();
// $newImg->name = $request->input('name');
// $file = $request->file('image');
// // $tmpName = $_FILES['image']['tmp_name'];
//
// //$fp = fopen($tmpName, 'rb'); // read binary
//
// //$newImg->doc = Image::make(base64_encode($_FILES["image"]["tmp_name"])->save();
// //$newImg->doc = $data;
//
// //$newImg->doc = Image::make( addslashes(file_get_contents($_FILES["image"]["tmp_name"])));
// //$newImg->doc = ($request->getContent($file));
// $path = $file->path();
// $name = $file->getClientOriginalName();
// $fullpath =$path .'\\'.$name;
// $t = file_get_contents($_FILES['image']['tmp_name']);
// $request->file('image')->store('uploads');
// $newImg->doc = $t;
// $newImg->emp_id = $request->input('id');
// $newImg->save();
// return view('home');
// }
//
// return view('home');
// }
public function imgSaver(Request $request){
if ($request->hasFile('image')) {
$name = $request->input('name');
$id = $request->input('id');
$realName =$request->file('image')->getClientOriginalName();
$image = $request->file('image')->storeAs('public/uploads',$realName);
$paper = $request->file('image');
$newImg=new Empimg();
$newImg->name=$name;
$newImg->doc=$realName;
$newImg->emp_id=$id;
$newImg->save();
return view('person.uploadEmpPaper');
}
else{
echo '<script>alert("الرجاء اختيار صورة");</script>';
return view('person.uploadEmpPaper');
}
// if ($request->hasFile('image')) {
// $image = $request->file('image');
// $name = $image->getClientOriginalName();
// $size = $image->getClientSize();
// $destinationPath = public_path('/images');
// $image->move($destinationPath, $name);
// }
}
public function binToImg($id){
$img= DB::table('empimgs')->where('id',$id)->get();
$arr = array('img'=>$img);
return view('person.imgshow',$arr);
}
public function UnitimgSaver(Request $request){
if ($request->hasFile('image')) {
$name = $request->input('name');
$id = $request->input('id');
$realName =$request->file('image')->getClientOriginalName();
$image = $request->file('image')->storeAs('public/uploads',$realName);
$paper = $request->file('image');
$newImg=new Unitimg();
$newImg->name=$name;
$newImg->paper=$realName;
$newImg->unit_id=$id;
$newImg->save();
return view('units.uploadPaper');
}
else{
echo '<script>alert("الرجاء اختيار صورة");</script>';
return view('units.uploadPaper');
}
}
public function ProgimgSaver(Request $request){
if ($request->hasFile('image')) {
$name = $request->input('name');
$id = $request->input('id');
$realName =$request->file('image')->getClientOriginalName();
$image = $request->file('image')->storeAs('public/uploads',$realName);
$paper = $request->file('image');
$newImg=new Programimg();
$newImg->name=$name;
$newImg->paper=$realName;
$newImg->program_id=$id;
$newImg->save();
return view('programs.uploadPaper');
}
else{
echo '<script>alert("الرجاء اختيار صورة");</script>';
return view('programs.uploadPaper');
}
}
}
| 9,029
|
https://github.com/ai408/abp-vue-admin-element-typescript/blob/master/aspnet-core/modules/common/LINGYUN.Abp.Notifications/Newtonsoft/Json/HexLongConverter.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
abp-vue-admin-element-typescript
|
ai408
|
C#
|
Code
| 86
| 238
|
using System;
namespace Newtonsoft.Json
{
public class HexLongConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
long v = value is ulong ? (long)(ulong)value : (long)value;
writer.WriteValue(v.ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
string value = reader.Value as string;
long lValue = long.Parse(value);
return typeof(ulong) == objectType ? (object)(ulong)lValue : lValue;
}
public override bool CanConvert(Type objectType)
{
switch (objectType.FullName)
{
case "System.Int64":
case "System.UInt64":
return true;
default:
return false;
}
}
}
}
| 24,485
|
https://github.com/yujh-yujh/apgspaceinvaders/blob/master/recompile.sh
|
Github Open Source
|
Open Source
|
MIT
| null |
apgspaceinvaders
|
yujh-yujh
|
Shell
|
Code
| 319
| 923
|
#!/bin/bash
set -e
chmod 755 *.sh
# Ensures 'make' works properly:
rm -f ".depend" | true
rm -f "main.o" | true
make clean
# Ensures compilation will fail unless rule2asm succeeds:
rm -f "includes/params.h" | true
rulearg=`echo "$@" | grep -o "\\-\\-rule [^ ]*" | sed "s/\\-\\-rule\\ //"`
symmarg=`echo "$@" | grep -o "\\-\\-symmetry [^ ]*" | sed "s/\\-\\-symmetry\\ //"`
profilearg=`echo "$@" | grep -o "\\-\\-profile" | sed "s/\\-\\-profile/u/"`
mingwarg=`echo "$@" | grep -o "\\-\\-mingw" | sed "s/\\-\\-mingw/u/"`
gpuarg=`echo "$@" | grep -o "\\-\\-cuda" | sed "s/\\-\\-cuda/u/"`
immarg=`echo "$@" | grep -o "\\-\\-immediate" | sed "s/\\-\\-immediate/u/"`
if [ "${#symmarg}" -ne 0 ]; then
if [ "${symmarg:0:1}" = "G" ]; then
gpuarg="true"
elif [ "${symmarg:0:1}" = "H" ]; then
gpuarg="true"
fi
fi
if [ "${#mingwarg}" -ne 0 ]; then
export USE_MINGW=1
fi
if [ "${#profilearg}" -ne 0 ]; then
if [ "${#gpuarg}" -ne 0 ]; then
printf "\033[31;1mWarning: --cuda and --profile are incompatible; omitting the latter.\033[0m\n"
else
export PROFILE_APGLUXE=1
fi
fi
# Ensure lifelib matches the version in the repository:
bash update-lifelib.sh
rm -rf "lifelib/avxlife/lifelogic" | true
if [ "${#rulearg}" -eq 0 ]; then
rulearg="b3s23"
echo "Rule unspecified; assuming b3s23."
fi
if [ "${#symmarg}" -eq 0 ]; then
symmarg="C1"
echo "Symmetry unspecified; assuming C1."
fi
gpuarg2="false"
if [ "${#gpuarg}" -ne 0 ]; then
export USE_GPU=1
gpuarg2="true"
fi
echo "Configuring rule $rulearg; symmetry $symmarg"
if command -v "python3" &>/dev/null; then
echo "Using $(which python3) to configure lifelib..."
python3 mkparams.py $rulearg $symmarg $gpuarg2
else
echo "Using $(which python) to configure lifelib..."
python mkparams.py $rulearg $symmarg $gpuarg2
fi
make
if [ "${#mingwarg}" -ne 0 ]; then
exit 0
fi
symmarg="$( grep 'SYMMETRY' 'includes/params.h' | grep -o '".*"' | tr '\n' '"' | sed 's/"//g' )"
rulearg="$( grep 'RULESTRING' 'includes/params.h' | grep -o '".*"' | tr '\n' '"' | sed 's/"//g' )"
if [ "${#immarg}" -ne 0 ]; then
./apgluxe --rule $rulearg --symmetry $symmarg "$@"
else
./apgluxe --rule $rulearg --symmetry $symmarg
fi
exit 0
| 15,535
|
https://github.com/JPMoresmau/camel/blob/master/docs/components/modules/dataformats/pages/mimeMultipart-dataformat.adoc
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
camel
|
JPMoresmau
|
AsciiDoc
|
Code
| 891
| 1,910
|
= MIME Multipart DataFormat
:doctitle: MIME Multipart
:shortname: mimeMultipart
:artifactid: camel-mail
:description: Marshal Camel messages with attachments into MIME-Multipart messages and back.
:since: 2.17
:supportlevel: Stable
//Manually maintained attributes
:camel-spring-boot-name: mail
*Since Camel {since}*
This data format that can convert a Camel message with attachments into
a Camel message having a MIME-Multipart message as message body (and no
attachments).
The use case for this is to enable the user to send attachments over
endpoints that do not directly support attachments, either as special
protocol implementation (e.g. send a MIME-multipart over an HTTP
endpoint) or as a kind of tunneling solution (e.g. because camel-jms
does not support attachments but by marshalling the message with
attachments into a MIME-Multipart, sending that to a JMS queue,
receiving the message from the JMS queue and unmarshalling it again
(into a message body with attachments).
The marshal option of the mimeMultipart data format will convert a
message with attachments into a MIME-Multipart message. If the parameter
"multipartWithoutAttachment" is set to true it will also marshal
messages without attachments into a multipart message with a single
part, if the parameter is set to false it will leave the message alone.
MIME headers of the mulitpart as "MIME-Version" and "Content-Type" are
set as camel headers to the message. If the parameter "headersInline" is
set to true it will also create a MIME multipart message in any case. +
Furthermore the MIME headers of the multipart are written as part of the
message body, not as camel headers.
The unmarshal option of the mimeMultipart data format will convert a
MIME-Multipart message into a camel message with attachments and leaves
other messages alone. MIME-Headers of the MIME-Multipart message have to
be set as Camel headers. The unmarshalling will only take place if the
"Content-Type" header is set to a "multipart" type. If the option
"headersInline" is set to true, the body is always parsed as a MIME
message.As a consequence if the message body is a stream and stream
caching is not enabled, a message body that is actually not a MIME
message with MIME headers in the message body will be replaced by an
empty message. Up to Camel version 2.17.1 this will happen all message
bodies that do not contain a MIME multipart message regardless of body
type and stream cache setting.
== Options
// dataformat options: START
include::partial$dataformat-options.adoc[]
// dataformat options: END
== Message Headers (marshal)
[width="100%",cols="20%,20%,60%",options="header",]
|=======================================================================
|Name |Type |Description
|Message-Id |String |The marshal operation will set this parameter to the generated MIME
message id if the "headersInline" parameter is set to false.
|MIME-Version |String |The marshal operation will set this parameter to the applied MIME
version (1.0) if the "headersInline" parameter is set to false.
|Content-Type |String |The content of this header will be used as a content type for the
message body part. If no content type is set, "application/octet-stream"
is assumed. After the marshal operation the content type is set to
"multipart/related" or empty if the "headersInline" parameter is set to
true.
|Content-Encoding |String |If the incoming content type is "text/*" the content encoding will be
set to the encoding parameter of the Content-Type MIME header of the
body part. Furthermore the given charset is applied for text to binary
conversions.
|=======================================================================
== Message Headers (unmarshal)
[width="100%",cols="20%,20%,60%",options="header",]
|=======================================================================
|Name |Type |Description
|Content-Type |String |If this header is not set to "multipart/*" the unmarshal operation will
not do anything. In other cases the multipart will be parsed into a
camel message with attachments and the header is set to the Content-Type
header of the body part, except if this is application/octet-stream. In
the latter case the header is removed.
|Content-Encoding |String |If the content-type of the body part contains an encoding parameter this
header will be set to the value of this encoding parameter (converted
from MIME endoding descriptor to Java encoding descriptor)
|MIME-Version |String |The unmarshal operation will read this header and use it for parsing the
MIME multipart. The header is removed afterwards
|=======================================================================
== Examples
[source,java]
-----------------------------------
from(...).marshal().mimeMultipart()
-----------------------------------
With a message where no Content-Type header is set, will create a
Message with the following message Camel headers:
*Camel Message Headers*
-------------------------------------------------------------------------------
Content-Type=multipart/mixed; \n boundary="----=_Part_0_14180567.1447658227051"
Message-Id=<...>
MIME-Version=1.0
-------------------------------------------------------------------------------
-------------------------
The message body will be:
-------------------------
*Camel Message Body*
----------------------------------------------------------------
------=_Part_0_14180567.1447658227051
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Qm9keSB0ZXh0
------=_Part_0_14180567.1447658227051
Content-Type: application/binary
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="Attachment File Name"
AAECAwQFBgc=
------=_Part_0_14180567.1447658227051--
----------------------------------------------------------------
A message with the header Content-Type set to "text/plain" sent to the
route
[source,java]
------------------------------------------------------------------------------------
from("...").marshal().mimeMultipart("related", true, true, "(included|x-.*)", true);
------------------------------------------------------------------------------------
will create a message without any specific MIME headers set as Camel
headers (the Content-Type header is removed from the Camel message) and
the following message body that includes also all headers of the
original message starting with "x-" and the header with name "included":
*Camel Message Body*
----------------------------------------------------------------
Message-ID: <...>
MIME-Version: 1.0
Content-Type: multipart/related;
boundary="----=_Part_0_1134128170.1447659361365"
x-bar: also there
included: must be included
x-foo: any value
------=_Part_0_1134128170.1447659361365
Content-Type: text/plain
Content-Transfer-Encoding: 8bit
Body text
------=_Part_0_1134128170.1447659361365
Content-Type: application/binary
Content-Transfer-Encoding: binary
Content-Disposition: attachment; filename="Attachment File Name"
[binary content]
------=_Part_0_1134128170.1447659361365
----------------------------------------------------------------
== Dependencies
To use MIME-Multipart in your Camel routes you need to add a dependency
on *camel-mail* which implements this data format.
If you use Maven you can just add the following to your pom.xml:
[source,xml]
-----------------------------------------------------------------------------------
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-mail</artifactId>
<version>x.x.x</version> <!-- use the same version as your Camel core version -->
</dependency>
-----------------------------------------------------------------------------------
include::spring-boot:partial$starter.adoc[]
| 971
|
https://github.com/Junkdance/LDtkUnity/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
LDtkUnity
|
Junkdance
|
Ignore List
|
Code
| 24
| 137
|
Temp/
Library/
Logs/
UserSettings/
Assets/AssetStoreTools/
Assets/AssetStoreTools.meta
Assets/Plugins/Editor/JetBrains
Assets/Plugins/Editor/JetBrains.meta
Assets/Plugins.meta
Assets/Plugins/Editor.meta
ExportedObj/
obj/
.vs/
.vscode/
.idea/
*.svd
*.userprefs
*.csproj
*.pidb
*.suo
*.sln
*.user
*.unityproj
*.booproj
| 29,510
|
https://github.com/MateusNazare/desafio_nestjs/blob/master/src/professores/dto/update-professore.dto.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
desafio_nestjs
|
MateusNazare
|
TypeScript
|
Code
| 18
| 57
|
import { PartialType } from '@nestjs/mapped-types';
import { CreateProfessoreDto } from './create-professore.dto';
export class UpdateProfessoreDto extends PartialType(CreateProfessoreDto) {}
| 13,500
|
https://github.com/phpactor/phpactor/blob/master/lib/Extension/LanguageServerBridge/TextDocument/WorkspaceTextDocumentLocator.php
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
phpactor
|
phpactor
|
PHP
|
Code
| 50
| 253
|
<?php
namespace Phpactor\Extension\LanguageServerBridge\TextDocument;
use Phpactor\Extension\LanguageServerBridge\Converter\TextDocumentConverter;
use Phpactor\LanguageServer\Core\Workspace\Exception\UnknownDocument;
use Phpactor\LanguageServer\Core\Workspace\Workspace as PhpactorWorkspace;
use Phpactor\TextDocument\Exception\TextDocumentNotFound;
use Phpactor\TextDocument\TextDocument;
use Phpactor\TextDocument\TextDocumentLocator;
use Phpactor\TextDocument\TextDocumentUri;
class WorkspaceTextDocumentLocator implements TextDocumentLocator
{
public function __construct(private PhpactorWorkspace $workspace)
{
}
public function get(TextDocumentUri $uri): TextDocument
{
try {
return TextDocumentConverter::fromLspTextItem($this->workspace->get($uri->__toString()));
} catch (UnknownDocument) {
}
throw TextDocumentNotFound::fromUri($uri);
}
}
| 1,811
|
https://github.com/steleman/flang9/blob/master/tools/flang/test/f90_correct/src/pre11.f90
|
Github Open Source
|
Open Source
|
Apache-2.0, NCSA, LLVM-exception
| 2,020
|
flang9
|
steleman
|
Fortran Free Form
|
Code
| 231
| 413
|
!
! Copyright (c) 2014, NVIDIA CORPORATION. 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.
!
! This tests replacement and concatenation with single and
! double quote literals.
!
#define STR(_s) _s
#define CAT(_a, _b) _a##_b
program p
logical :: res(2), expect(2) = (/.true., .true./)
print *, STR('c character ! bang " quote * asterisk') ! Single-quote
res(1) = STR('c character ! bang " quote * asterisk') .eq. 'c character ! bang " quote * asterisk'
print *, STR("c character ! bang ' quote * asterisk") ! Double-quote
res(2) = STR("c character ! bang ' quote * asterisk") .eq. "c character ! bang ' quote * asterisk"
print *, CAT('! bang " quote * asterisk', '! bang " quote * asterisk') ! Single-quote
print *, CAT("! bang ' quote * asterisk", "! bang ' quote * asterisk") ! Double-quote
call check(res, expect, 2)
end program
| 26,186
|
https://github.com/mat-1/brigadier/blob/master/src/lib/arguments/FloatArgumentType.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
brigadier
|
mat-1
|
TypeScript
|
Code
| 219
| 622
|
import StringReader from "../StringReader"
import CommandContext from "../context/CommandContext"
import CommandSyntaxException from "../exceptions/CommandSyntaxException"
import Suggestions from "../suggestion/Suggestions"
import SuggestionsBuilder from "../suggestion/SuggestionsBuilder"
import ArgumentType from "./ArgumentType"
const EXAMPLES = ["0", "1.2", ".5", "-1", "-.5", "-1234.56"];
export default class FloatArgumentType implements ArgumentType<number> {
private minimum: number;
private maximum: number;
private constructor (minimum: number, maximum: number) {
this.minimum = minimum;
this.maximum = maximum;
}
public static float(min: number = -Infinity, max: number = Infinity): FloatArgumentType {
return new FloatArgumentType(min, max);
}
public static getFloat(context: CommandContext<any>, name: string): number {
return context.getArgument(name, Number);
}
public getMinimum(): number {
return this.minimum;
}
public getMaximum(): number {
return this.maximum;
}
public parse(reader: StringReader): number {
let start = reader.getCursor();
let result = reader.readFloat();
if (result < this.minimum) {
reader.setCursor(start);
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.integerTooLow().createWithContext(reader, result, this.minimum);
}
if (result > this.maximum) {
reader.setCursor(start);
throw CommandSyntaxException.BUILT_IN_EXCEPTIONS.integerTooHigh().createWithContext(reader, result, this.maximum);
}
return result;
}
public equals(o: object): boolean {
if (this === o) return true;
if (!(o instanceof FloatArgumentType)) return false;
return this.maximum == o.maximum && this.minimum == o.minimum;
}
public toString(): string {
if (this.minimum === -Infinity && this.maximum === Infinity) {
return "float()";
}
else if (this.maximum == Infinity) {
return "float(" + this.minimum + ")";
}
else {
return "float(" + this.minimum + ", " + this.maximum + ")";
}
}
public getExamples(): Iterable<string> {
return EXAMPLES;
}
}
| 4,629
|
https://github.com/reez/Tabs/blob/master/LightningNode/Invoice.swift
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Tabs
|
reez
|
Swift
|
Code
| 115
| 324
|
//
// LightningNode
//
// Created by Matthew Ramsden on 1/1/19.
// Copyright © 2019 Matthew Ramsden. All rights reserved.
//
import Foundation
import LNDrpc
extension Invoice {
convenience init(value: Int, memo: String) {
self.init()
self.memo = memo
self.value = Int64(value)
}
}
extension ListInvoiceRequest {
convenience init(reversed: Bool) {
self.init()
self.reversed = reversed
}
}
struct InvoiceRequest {
let memo: String
let value: Int
}
struct InvoiceState {
let invoiceState: String
}
extension InvoiceState {
init(state: Invoice_InvoiceState) {
switch state {
case .gpbUnrecognizedEnumeratorValue:
invoiceState = "gpbUnrecognizedEnumeratorValue"
case .open:
invoiceState = "open"
case .settled:
invoiceState = "settled"
case .canceled:
invoiceState = "canceled"
case .accepted:
invoiceState = "accepted"
@unknown default:
invoiceState = "unknown"
}
}
}
| 14,440
|
https://github.com/nicolafavata/SmartLogistics/blob/master/resources/views/employee/profile.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
SmartLogistics
|
nicolafavata
|
PHP
|
Code
| 238
| 1,220
|
@extends('layouts.employee')
@section('title','Profilo di '.$dati->name.' '.$dati->cognome)
@section('content_header')
<h2 class="shadow verdino center">{{$dati->name.' '.$dati->cognome.' questi sono i dati del tuo profilo'}}</h2>
@endsection
@section('content_section')
<div id="body_page" class="container-fluid home_employee">
<div class="row">
<div class="col-md-12 jumbotron border employee">
<table class="table table-responsive">
@if($dati->responsabile=='1')
<tr>
<td class="fucsia ombra" colspan="3">
<h2>Sei il responsabile della sede di </h2><h2 class=" grigio ombra uppercase">{{$dati->rag_soc_company}}</h2>
</td>
</tr>
@else
<tr>
<td class="fucsia ombra" colspan="3">
<h2> Ti occupi di
@if($dati->acquisti=='1')
acquisti
@endif
@if($dati->produzione=='1')
produzione
@endif
@if($dati->vendite=='1')
vendite
@endif
</h2>
</td>
</tr>
@endif
<tr>
<td class="grigio ombra" colspan="2">
<h3>Creazione account: {{$employee->created_at->format('d/m/Y')}}</h3>
</td>
</tr>
<tr>
<td rowspan="6">
<img class="border-border-fucsia doppio img-fluid image-responsive" title="{{$dati->name.' '.$dati->cognome}}" alt="Profilo {{$dati->name.' '.$dati->cognome}}"
@if(($dati->img_employee)!='0')
src="{{env('APP_URL').'/storage/'.$dati->img_employee}}">
@else
src="{{env('APP_URL').'/img/profile.jpg'}}">
@endif
</td>
<td class="grigio shadow destra">
Matricola: 
</td>
<td class="fucsia ombra sinistra">
@if($employee->matricola!=null)
{{$employee->matricola}}
@else
{{'Nessuna'}}
@endif
</td>
</tr>
<tr>
<td class="grigio shadow destra">
Nome: 
</td>
<td class="fucsia ombra sinistra">
{{$dati->name}}
</td>
</tr>
<tr>
<td class="grigio shadow destra">
Cognome: 
</td>
<td class="fucsia ombra sinistra">
{{$dati->cognome}}
</td>
</tr>
<tr>
<td class="grigio shadow destra">
Email: 
</td>
<td class="fucsia ombra sinistra">
{{$employee->email}}
</td>
</tr>
<tr>
<td class="grigio shadow destra">
Telefono: 
</td>
<td class="fucsia ombra sinistra">
@if($employee->tel_employee!=null)
{{$employee->tel_employee}}
@else
{{'Nessuno'}}
@endif
</td>
</tr>
<tr>
<td class="grigio shadow destra">
Mobile: 
</td>
<td class="fucsia ombra sinistra">
@if($employee->cell_employee!=null)
{{$employee->cell_employee}}
@else
{{'Nessuno'}}
@endif
</td>
</tr>
</table>
<br />
<div class="row center grigio shadow">
Vuoi aggiornare i tuoi dati?
</div><br />
<div class="row center">
<a href="{{ route('upprofile') }}" class="form-group text-center btn btn-primary pulsante">
Aggiorna
</a>
</div>
</div>
</div>
</div>
@endsection
@section('footer')
@parent
@endsection
@section('script')
@parent
@endsection
| 46,828
|
https://github.com/SultanKs4/laporan-praktikum-pbo-2019/blob/master/src/14_GUI_dan_Database/backend/Peminjaman1841720019Sultan.java
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
laporan-praktikum-pbo-2019
|
SultanKs4
|
Java
|
Code
| 566
| 2,490
|
package id.natlus.backend;
import java.sql.ResultSet;
import java.util.ArrayList;
public class Peminjaman1841720019Sultan {
private int mIdpeminjaman, mIdanggota, mIdbuku;
private Anggota1841720019Sultan mAnggota = new Anggota1841720019Sultan();
private Buku1841720019Sultan mBuku = new Buku1841720019Sultan();
private String mTanggalPinjam;
private String mTanggalKembali;
public Peminjaman1841720019Sultan() {
}
public Peminjaman1841720019Sultan(Anggota1841720019Sultan anggota, Buku1841720019Sultan buku, String tanggalpinjam, String tanggalkembali) {
this.mAnggota = anggota;
this.mBuku = buku;
this.mTanggalPinjam = tanggalpinjam;
this.mTanggalKembali = tanggalkembali;
}
public int getmIdanggotaSultan() {
return mIdanggota;
}
public void setmIdanggotaSultan(int mIdanggota) {
this.mIdanggota = mIdanggota;
}
public int getmIdbukuSultan() {
return mIdbuku;
}
public void setmIdbukuSultan(int mIdbuku) {
this.mIdbuku = mIdbuku;
}
public int getmIdpeminjamanSultan() {
return mIdpeminjaman;
}
public void setmIdpeminjamanSultan(int mIdpeminjaman) {
this.mIdpeminjaman = mIdpeminjaman;
}
public Anggota1841720019Sultan getmAnggotaSultan() {
return mAnggota;
}
public void setmAnggotaSultan(Anggota1841720019Sultan mAnggota) {
this.mAnggota = mAnggota;
}
public Buku1841720019Sultan getmBukuSultan() {
return mBuku;
}
public void setmBukuSultan(Buku1841720019Sultan mBuku) {
this.mBuku = mBuku;
}
public String getmTanggalPinjamSultan() {
return mTanggalPinjam;
}
public void setmTanggalPinjamSultan(String mTanggalPinjam) {
this.mTanggalPinjam = mTanggalPinjam;
}
public String getmTanggalKembaliSultan() {
return mTanggalKembali;
}
public void setmTanggalKembaliSultan(String mTanggalKembali) {
this.mTanggalKembali = mTanggalKembali;
}
public Peminjaman1841720019Sultan getByIdSultan(int id) {
Peminjaman1841720019Sultan pinjam = new Peminjaman1841720019Sultan();
ResultSet rs = DBHelper1841720019Sultan.selectQuerySultan("SELECT "
+ " p.idpeminjaman AS idpeminjaman, "
+ " p.tanggalpinjam AS tanggalpinjam, "
+ " p.tanggalkembali AS tanggalkembali, "
+ " a.idanggota AS idanggota, "
+ " b.idbuku AS idbuku "
+ " FROM peminjaman p LEFT JOIN anggota a ON p.idanggota = a.idanggota "
+ " LEFT JOIN buku b ON p.idbuku = b.idbuku WHERE p.idpeminjaman = '" + id + "'");
try {
while (rs.next()) {
pinjam = new Peminjaman1841720019Sultan();
pinjam.setmIdpeminjamanSultan(rs.getInt("idpeminjaman"));
pinjam.setmIdanggotaSultan(rs.getInt("idanggota"));
pinjam.setmIdbukuSultan(rs.getInt("idbuku"));
pinjam.setmTanggalPinjamSultan(rs.getString("tanggalpinjam"));
pinjam.setmTanggalKembaliSultan(rs.getString("tanggalkembali"));
pinjam.setmAnggotaSultan(new Anggota1841720019Sultan().getByIdSultan(getmIdanggotaSultan()));
pinjam.setmBukuSultan(new Buku1841720019Sultan().getByIdSultan(pinjam.getmIdbukuSultan()));
}
} catch (Exception e) {
e.printStackTrace();
}
return pinjam;
}
public ArrayList<Peminjaman1841720019Sultan> getAllSultan() {
ArrayList<Peminjaman1841720019Sultan> ListPinjam = new ArrayList<>();
ResultSet rs = DBHelper1841720019Sultan.selectQuerySultan("SELECT "
+ "p.idpeminjaman AS idpeminjaman, "
+ "p.tanggalpinjam AS tanggalpinjam, "
+ "p.tanggalkembali AS tanggalkembali, "
+ "a.idanggota AS idanggota, "
+ "b.idbuku AS idbuku "
+ "FROM peminjaman p LEFT JOIN anggota a ON p.idanggota = a.idanggota "
+ "LEFT JOIN buku b ON p.idbuku = b.idbuku");
try {
while (rs.next()) {
Peminjaman1841720019Sultan pinjam = new Peminjaman1841720019Sultan();
pinjam.setmIdpeminjamanSultan(rs.getInt("idpeminjaman"));
pinjam.setmIdanggotaSultan(rs.getInt("idanggota"));
pinjam.setmIdbukuSultan(rs.getInt("idbuku"));
pinjam.setmTanggalPinjamSultan(rs.getString("tanggalpinjam"));
pinjam.setmTanggalKembaliSultan(rs.getString("tanggalkembali"));
pinjam.setmAnggotaSultan(new Anggota1841720019Sultan().getByIdSultan(pinjam.getmIdanggotaSultan()));
pinjam.setmBukuSultan(new Buku1841720019Sultan().getByIdSultan(pinjam.getmIdbukuSultan()));
ListPinjam.add(pinjam);
}
} catch (Exception e) {
e.printStackTrace();
}
return ListPinjam;
}
public void saveSultan() {
if (getByIdSultan(mIdpeminjaman).getmIdpeminjamanSultan() == 0) {
String sql = "INSERT INTO peminjaman (idanggota, idbuku, tanggalpinjam, tanggalkembali) "
+ "values ("
+ "'" + this.getmAnggotaSultan().getmIdAnggotaSultan() + "', "
+ "'" + this.getmBukuSultan().getmIdBukuSultan() + "',"
+ "'" + this.mTanggalPinjam + "', "
+ "'" + this.mTanggalKembali + "' "
+ ")";
this.mIdpeminjaman = DBHelper1841720019Sultan.insertQueryGetIdSultan(sql);
} else {
String sql = "UPDATE buku SET "
+ "idanggota = '" + this.getmAnggotaSultan().getmIdAnggotaSultan() + "', "
+ "idbuku = '" + this.getmBukuSultan().getmIdBukuSultan() + "', "
+ "tanggalpinjam = '" + this.mTanggalPinjam + "', "
+ "tanggalkembali = '" + this.mTanggalKembali + "'";
DBHelper1841720019Sultan.executeQuerySultan(sql);
}
}
public void cariAnggotaSultan(int id) {
ResultSet rs = DBHelper1841720019Sultan.selectQuerySultan("SELECT * FROM anggota WHERE idanggota = '" + id + "'");
try {
while (rs.next()) {
getmAnggotaSultan().setmIdAnggotaSultan(rs.getInt("idanggota"));
getmAnggotaSultan().setmNamaSultan(rs.getString("nama"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void cariBukuSultan(int id) {
ResultSet rs = DBHelper1841720019Sultan.selectQuerySultan("SELECT * FROM buku WHERE idbuku = '" + id + "'");
try {
while (rs.next()) {
getmBukuSultan().setmIdBukuSultan(rs.getInt("idbuku"));
getmBukuSultan().setmJudulSultan(rs.getString("judul"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void deleteSultan() {
String sql = "DELETE FROM peminjaman WHERE idpeminjaman = '" + this.mIdpeminjaman + "'";
DBHelper1841720019Sultan.executeQuerySultan(sql);
}
}
| 4,736
|
https://github.com/ScalablyTyped/Distribution/blob/master/a/aws-sdk/src/main/scala/typings/awsSdk/clientsSchemasMod/CreateDiscovererRequest.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
Distribution
|
ScalablyTyped
|
Scala
|
Code
| 172
| 576
|
package typings.awsSdk.clientsSchemasMod
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
trait CreateDiscovererRequest extends StObject {
/**
* Support discovery of schemas in events sent to the bus from another account. (default: true).
*/
var CrossAccount: js.UndefOr[boolean] = js.undefined
/**
* A description for the discoverer.
*/
var Description: js.UndefOr[stringMin0Max256] = js.undefined
/**
* The ARN of the event bus.
*/
var SourceArn: stringMin20Max1600
/**
* Tags associated with the resource.
*/
var Tags: js.UndefOr[typings.awsSdk.clientsSchemasMod.Tags] = js.undefined
}
object CreateDiscovererRequest {
inline def apply(SourceArn: stringMin20Max1600): CreateDiscovererRequest = {
val __obj = js.Dynamic.literal(SourceArn = SourceArn.asInstanceOf[js.Any])
__obj.asInstanceOf[CreateDiscovererRequest]
}
@scala.inline
implicit open class MutableBuilder[Self <: CreateDiscovererRequest] (val x: Self) extends AnyVal {
inline def setCrossAccount(value: boolean): Self = StObject.set(x, "CrossAccount", value.asInstanceOf[js.Any])
inline def setCrossAccountUndefined: Self = StObject.set(x, "CrossAccount", js.undefined)
inline def setDescription(value: stringMin0Max256): Self = StObject.set(x, "Description", value.asInstanceOf[js.Any])
inline def setDescriptionUndefined: Self = StObject.set(x, "Description", js.undefined)
inline def setSourceArn(value: stringMin20Max1600): Self = StObject.set(x, "SourceArn", value.asInstanceOf[js.Any])
inline def setTags(value: Tags): Self = StObject.set(x, "Tags", value.asInstanceOf[js.Any])
inline def setTagsUndefined: Self = StObject.set(x, "Tags", js.undefined)
}
}
| 28,200
|
https://github.com/joshel123/Api.Core.ControllerTemplates/blob/master/BaseControllerTemplate.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Api.Core.ControllerTemplates
|
joshel123
|
C#
|
Code
| 145
| 504
|
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Text;
namespace Api.Core.ControllerTemplates
{
[ApiController]
public abstract class BaseControllerTemplate<T>
{
protected readonly ILogger _logger;
protected readonly IConfiguration _configuration;
protected BaseControllerTemplate(IConfiguration config, ILogger logger)
{
_configuration = config;
_logger = logger;
}
/// <summary>
/// Prints the exposed APIs for this controller.
/// Not meant to be consumed, for testing purposes only.
/// </summary>
/// <returns>Formatted text with exposed API endpoints.</returns>
[HttpGet("Test")]
public virtual IActionResult Test()
{
var sb = new StringBuilder();
var methods = GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
string partition = $"------------------------------\n";
//header
sb.Append(partition);
sb.Append($"Service Name: {GetType().Name}<{typeof(T).GetType().Name}>\n");
sb.Append(partition);
//body
foreach(var m in methods)
sb.Append($"public {m.ReturnType.Name} {m.Name}\n");
//footer
sb.Append(partition);
return new OkObjectResult(sb.ToString());
}
protected virtual void TryLogException(Exception ex, [CallerMemberName] string callerName = "")
{
if (_logger != null)
_logger.Log(LogLevel.Error, ex, GetLoggerMessege(callerName));
}
private string GetLoggerMessege(string rootMethod) =>
$"{GetType().Name}<{typeof(T).Name}> -> {rootMethod}<{typeof(T).Name}>";
}
}
| 36,240
|
https://github.com/sifodyas/sifodyas/blob/master/core/src/psr/container/IContainerException.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
sifodyas
|
sifodyas
|
TypeScript
|
Code
| 20
| 44
|
/* eslint-disable @typescript-eslint/no-empty-interface */
/**
* Base interface representing a generic exception in a container.
*/
export interface IContainerException {}
| 37,878
|
https://github.com/m809745357/hospital/blob/master/resources/views/pc/scheduling/index.blade.php
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
hospital
|
m809745357
|
PHP
|
Code
| 10
| 51
|
@extends('pc.layouts.app')
@section('content')
<scheduling-index :attributes="{{ $doctors }}" :categories="{{ $departments }}"></scheduling-index>
@endsection
| 2,600
|
https://github.com/mcopik/perf-taint/blob/master/benchmarks/milc/milc_qcd-7.8.1/arb_dirac_invert/addsite_fp_bi.h
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
perf-taint
|
mcopik
|
C
|
Code
| 28
| 53
|
/* Addition to site structure for biconjugate gradient inverter */
wilson_vector sss; /* internal biconjugate gradient vector */
wilson_vector tmp; /* auxiliary for other internal biCG vectors */
| 20,686
|
https://github.com/DownloadMii/DownloadMii-3DS/blob/master/source/utils.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
DownloadMii-3DS
|
DownloadMii
|
C++
|
Code
| 3,341
| 12,723
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <sys/stat.h>
#include <iostream>
#include <string>
#include <sstream>
#include <3ds.h>
#include <zlib.h>
#include "utils.h"
#include "print.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
const int commandPort=5000;
using namespace std;
int sock = 0;
unsigned long htonl(unsigned long v)
{
u8* v2=(u8*)&v;
return (v2[0]<<24)|(v2[1]<<16)|(v2[2]<<8)|(v2[3]);
}
unsigned short htons(unsigned short v)
{
u8* v2=(u8*)&v;
return (v2[0]<<8)|(v2[1]);
}
void sock_debuginit()
{
SOC_Initialize((u32*)memalign(0x1000, 0x100000), 0x100000);
int listenfd;
struct sockaddr_in serv_addr;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(commandPort);
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
listen(listenfd, 10);
sock = accept(listenfd, (struct sockaddr*)NULL, NULL);
closesocket(listenfd);
}
void sock_debugsendstr(char* mes)
{
send(sock, mes, strlen(mes), 0);
}
void sock_debugwait()
{
char d[] = {0x01, 0x01};
send(sock, d, 2, 0);
while (d[0] != 'E' && d[1] != 'X')
recv(sock, d, 0x2, 0); //just a wait
}
Result loadfile(char *file, int *size, char** buffer)
{
FILE *fp;
long lSize;
fp = fopen(file, "rb");
if (!fp) {
perror(file);
return -1;
}
fseek(fp, 0L, SEEK_END);
lSize = ftell(fp);
rewind(fp);
/* allocate memory for entire content */
*buffer = (char*)calloc(1, lSize + 1);
if (!*buffer){
fclose(fp);
fputs("memory alloc fails", stderr);
return -1;
}
/* copy the file into the buffer */
if (1 != fread(*buffer, lSize, 1, fp)) {
fclose(fp);
free(*buffer);
fputs("entire read fails", stderr);
return -1;
}
size = (int *)lSize;
fclose(fp);
return 0;
}
std::string insert_newlines(const std::string &in, const size_t every_n)
{
std::string out;
out.reserve(in.size() + in.size() / every_n);
for (std::string::size_type i = 0; i < in.size(); i++) {
out.push_back(in[i]);
if (!((i + 1) % every_n)) {
out.push_back('\n');
}
}
return out;
}
/*std::string get_suffix(int n)
{
std::string num_s = to_string(n);
std::string return_s = "";
switch (num_s.back())
{
case '1': return_s = "st"; break;
case '2': return_s = "nd"; break;
case '3': return_s = "rd"; break;
default: return_s = "th";
}
if (num_s.length() > 1) {
num_s.pop_back();
if (num_s.back() == '1')
{
return_s = "th";
}
}
return return_s;
}*/
bool replace(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = str.find(from);
if (start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
/******************************************************************************
** UnZip *********************************************************************
*******************************************************************************/
#define _ZIP_BUFFER_SIZE (16384)
#define _ZIP_MAX_FILENAME_SIZE (256)
#define _ZIP_CENTRALDIR_ITEM_SIZE (0x2e)
#define _ZIP_LOCALHEADER_SIZE (0x1e)
#define _ZIP_OK (0)
#define _ZIP_EOF_LIST (-100)
#define _ZIP_ERRNO (Z_ERRNO)
#define _ZIP_EOF (0)
#define _ZIP_PARAM_ERROR (-102)
#define _ZIP_BAD_FILE (-103)
#define _ZIP_INTERNAL_ERROR (-104)
#define _ZIP_CRC_ERROR (-105)
#define CRC32(c, b) ((*(crc32tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8))
#define zdecode(pkeys, crc32tab, c) (ZipUpdateKeys(pkeys, crc32tab, c ^= ZipDecryptByte(pkeys, crc32tab)))
#define _ZIP_BUF_READ_COMMENT (0x400)
typedef struct
{
unsigned long version;
unsigned long versionneeded;
unsigned long flag;
unsigned long compressionmethod;
unsigned long dosdate;
unsigned long crc;
unsigned long compressedsize;
unsigned long uncompressedsize;
unsigned long filenamesize;
unsigned long fileextrasize;
unsigned long filecommentsize;
unsigned long disknumstart;
unsigned long internalfileattr;
unsigned long externalfileattr;
} zipFileInfo;
typedef struct
{
unsigned long currentfileoffset;
} zipFileInternalInfo;
typedef struct
{
char *buffer;
z_stream stream;
unsigned long posinzip;
unsigned long streaminitialised;
unsigned long localextrafieldoffset;
unsigned int localextrafieldsize;
unsigned long localextrafieldpos;
unsigned long crc32;
unsigned long crc32wait;
unsigned long restreadcompressed;
unsigned long restreaduncompressed;
FILE* file;
unsigned long compressionmethod;
unsigned long bytebeforezip;
} zipFileInfoInternal;
typedef struct
{
unsigned long countentries;
unsigned long commentsize;
} zipGlobalInfo;
typedef struct
{
FILE* file;
zipGlobalInfo gi;
unsigned long bytebeforezip;
unsigned long numfile;
unsigned long posincentraldir;
unsigned long currentfileok;
unsigned long centralpos;
unsigned long centraldirsize;
unsigned long centraldiroffset;
zipFileInfo currentfileinfo;
zipFileInternalInfo currentfileinfointernal;
zipFileInfoInternal* currentzipfileinfo;
int encrypted;
unsigned long keys[3];
const unsigned long* crc32tab;
} _zip;
void *MallocPatch(int size)
{
void *ptr = malloc(size);
return ptr;
}
void FreePatch(void *ptr)
{
if (ptr != NULL)
free(ptr);
}
static int ZitByte(FILE *file, int *pi)
{
unsigned char c;
int err = fread(&c, 1, 1, file);
if (err == 1)
{
*pi = (int)c;
return _ZIP_OK;
}
else
{
if (ferror(file))
return _ZIP_ERRNO;
else
return _ZIP_EOF;
}
}
static int ZitShort(FILE *file, unsigned long *px)
{
unsigned long x;
int i = 0;
int err;
err = ZitByte(file, &i);
x = (unsigned long)i;
if (err == _ZIP_OK)
err = ZitByte(file, &i);
x += ((unsigned long)i) << 8;
if (err == _ZIP_OK)
*px = x;
else
*px = 0;
return err;
}
static int ZitLong(FILE *file, unsigned long *px)
{
unsigned long x;
int i = 0;
int err;
err = ZitByte(file, &i);
x = (unsigned long)i;
if (err == _ZIP_OK)
err = ZitByte(file, &i);
x += ((unsigned long)i) << 8;
if (err == _ZIP_OK)
err = ZitByte(file, &i);
x += ((unsigned long)i) << 16;
if (err == _ZIP_OK)
err = ZitByte(file, &i);
x += ((unsigned long)i) << 24;
if (err == _ZIP_OK)
*px = x;
else
*px = 0;
return err;
}
static int ZipDecryptByte(unsigned long* pkeys, const unsigned long* crc32tab)
{
(void)crc32tab;
unsigned temp;
temp = ((unsigned)(*(pkeys + 2)) & 0xffff) | 2;
return (int)(((temp * (temp ^ 1)) >> 8) & 0xff);
}
static int ZipUpdateKeys(unsigned long* pkeys, const unsigned long* crc32tab, int c)
{
(*(pkeys + 0)) = CRC32((*(pkeys + 0)), c);
(*(pkeys + 1)) += (*(pkeys + 0)) & 0xff;
(*(pkeys + 1)) = (*(pkeys + 1)) * 134775813L + 1;
{
register int keyshift = (int)((*(pkeys + 1)) >> 24);
(*(pkeys + 2)) = CRC32((*(pkeys + 2)), keyshift);
}
return c;
}
static void ZipInitKeys(const char* passwd, unsigned long* pkeys, const unsigned long* crc32tab)
{
*(pkeys + 0) = 305419896L;
*(pkeys + 1) = 591751049L;
*(pkeys + 2) = 878082192L;
while (*passwd != '\0')
{
ZipUpdateKeys(pkeys, crc32tab, (int)*passwd);
passwd++;
}
}
static unsigned long ZipLocateCentralDir(FILE *file)
{
unsigned char* buf;
unsigned long usizefile;
unsigned long ubackread;
unsigned long umaxback = 0xffff;
unsigned long uposfound = 0;
if (fseek(file, 0, SEEK_END) != 0)
return 0;
usizefile = ftell(file);
if (umaxback > usizefile)
umaxback = usizefile;
buf = (unsigned char*)MallocPatch(_ZIP_BUF_READ_COMMENT + 4);
if (buf == NULL)
return 0;
ubackread = 4;
while (ubackread < umaxback)
{
unsigned long ureadsize, ureadpos;
int i;
if (ubackread + _ZIP_BUF_READ_COMMENT > umaxback)
ubackread = umaxback;
else
ubackread += _ZIP_BUF_READ_COMMENT;
ureadpos = usizefile - ubackread;
ureadsize = ((_ZIP_BUF_READ_COMMENT + 4) < (usizefile - ureadpos)) ? (_ZIP_BUF_READ_COMMENT + 4) : (usizefile - ureadpos);
if (fseek(file, ureadpos, SEEK_SET) != 0)
break;
if (fread(buf, (unsigned int)ureadsize, 1, file) != 1)
break;
for (i = (int)ureadsize - 3; (i--) > 0;)
if (((*(buf + i)) == 0x50) && ((*(buf + i + 1)) == 0x4b) && ((*(buf + i + 2)) == 0x05) && ((*(buf + i + 3)) == 0x06))
{
uposfound = ureadpos + i;
break;
}
if (uposfound != 0)
break;
}
FreePatch(buf);
return uposfound;
}
static int ZitZipFileInfoInternal(Zip* file, zipFileInfo *pfileinfo, zipFileInternalInfo *pfileinfointernal, char *filename, unsigned long filenamebuffersize, void *extrafield, unsigned long extrafieldbuffersize, char *comment, unsigned long commentbuffersize)
{
_zip* s;
zipFileInfo fileinfo;
zipFileInternalInfo fileinfointernal;
int err = _ZIP_OK;
unsigned long umagic;
long lseek = 0;
if (file == NULL)
return _ZIP_PARAM_ERROR;
s = (_zip*)file;
if (fseek(s->file, s->posincentraldir + s->bytebeforezip, SEEK_SET) != 0)
err = _ZIP_ERRNO;
if (err == _ZIP_OK)
{
if (ZitLong(s->file, &umagic) != _ZIP_OK)
err = _ZIP_ERRNO;
else if (umagic != 0x02014b50)
err = _ZIP_BAD_FILE;
}
if (ZitShort(s->file, &fileinfo.version) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(s->file, &fileinfo.versionneeded) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(s->file, &fileinfo.flag) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(s->file, &fileinfo.compressionmethod) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitLong(s->file, &fileinfo.dosdate) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitLong(s->file, &fileinfo.crc) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitLong(s->file, &fileinfo.compressedsize) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitLong(s->file, &fileinfo.uncompressedsize) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(s->file, &fileinfo.filenamesize) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(s->file, &fileinfo.fileextrasize) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(s->file, &fileinfo.filecommentsize) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(s->file, &fileinfo.disknumstart) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(s->file, &fileinfo.internalfileattr) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitLong(s->file, &fileinfo.externalfileattr) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitLong(s->file, &fileinfointernal.currentfileoffset) != _ZIP_OK)
err = _ZIP_ERRNO;
lseek += fileinfo.filenamesize;
if ((err == _ZIP_OK) && (filename != NULL))
{
unsigned long usizeread;
if (fileinfo.filenamesize < filenamebuffersize)
{
*(filename + fileinfo.filenamesize) = '\0';
usizeread = fileinfo.filenamesize;
}
else
usizeread = filenamebuffersize;
if ((fileinfo.filenamesize > 0) && (filenamebuffersize > 0))
{
if (fread(filename, (unsigned int)usizeread, 1, s->file) != 1)
err = _ZIP_ERRNO;
}
lseek -= usizeread;
}
if ((err == _ZIP_OK) && (extrafield != NULL))
{
unsigned long usizeread;
if (fileinfo.fileextrasize < extrafieldbuffersize)
usizeread = fileinfo.fileextrasize;
else
usizeread = extrafieldbuffersize;
if (lseek != 0)
{
if (fseek(s->file, lseek, SEEK_CUR) == 0)
lseek = 0;
else
err = _ZIP_ERRNO;
}
if ((fileinfo.fileextrasize > 0) && (extrafieldbuffersize > 0))
{
if (fread(extrafield, (unsigned int)usizeread, 1, s->file) != 1)
err = _ZIP_ERRNO;
}
lseek += fileinfo.fileextrasize - usizeread;
}
else
lseek += fileinfo.fileextrasize;
if ((err == _ZIP_OK) && (comment != NULL))
{
unsigned long usizeread;
if (fileinfo.filecommentsize < commentbuffersize)
{
*(comment + fileinfo.filecommentsize) = '\0';
usizeread = fileinfo.filecommentsize;
}
else
usizeread = commentbuffersize;
if (lseek != 0)
{
if (fseek(s->file, lseek, SEEK_CUR) == 0)
lseek = 0;
else
err = _ZIP_ERRNO;
}
if ((fileinfo.filecommentsize > 0) && (commentbuffersize > 0))
{
if (fread(comment, (unsigned int)usizeread, 1, s->file) != 1)
err = _ZIP_ERRNO;
}
lseek += fileinfo.filecommentsize - usizeread;
}
else
lseek += fileinfo.filecommentsize;
if ((err == _ZIP_OK) && (pfileinfo != NULL))
*pfileinfo = fileinfo;
if ((err == _ZIP_OK) && (pfileinfointernal != NULL))
*pfileinfointernal = fileinfointernal;
return err;
}
static int ZitGlobalInfo(Zip* file, zipGlobalInfo *zipinfo)
{
_zip* s;
if (file == NULL)
return _ZIP_PARAM_ERROR;
s = (_zip*)file;
*zipinfo = s->gi;
return _ZIP_OK;
}
static int ZipGotoFirstFile(Zip* file)
{
int err = _ZIP_OK;
_zip* s;
if (file == NULL)
return _ZIP_PARAM_ERROR;
s = (_zip*)file;
s->posincentraldir = s->centraldiroffset;
s->numfile = 0;
err = ZitZipFileInfoInternal(file, &s->currentfileinfo, &s->currentfileinfointernal, NULL, 0, NULL, 0, NULL, 0);
s->currentfileok = (err == _ZIP_OK);
return err;
}
static int ZipCloseCurrentFile(Zip* file)
{
int err = _ZIP_OK;
_zip* s;
zipFileInfoInternal *pfileinzipreadinfo;
if (file == NULL)
return _ZIP_PARAM_ERROR;
s = (_zip*)file;
pfileinzipreadinfo = s->currentzipfileinfo;
if (pfileinzipreadinfo == NULL)
return _ZIP_PARAM_ERROR;
if (pfileinzipreadinfo->restreaduncompressed == 0)
{
if (pfileinzipreadinfo->crc32 != pfileinzipreadinfo->crc32wait)
err = _ZIP_CRC_ERROR;
}
FreePatch(pfileinzipreadinfo->buffer);
pfileinzipreadinfo->buffer = NULL;
if (pfileinzipreadinfo->streaminitialised)
inflateEnd(&pfileinzipreadinfo->stream);
pfileinzipreadinfo->streaminitialised = 0;
FreePatch(pfileinzipreadinfo);
s->currentzipfileinfo = NULL;
return err;
}
static int ZitCurrentFileInfo(Zip* file, zipFileInfo *pfileinfo, char *filename, unsigned long filenamebuffersize, void *extrafield, unsigned long extrafieldbuffersize, char *comment, unsigned long commentbuffersize)
{
return ZitZipFileInfoInternal(file, pfileinfo, NULL, filename, filenamebuffersize, extrafield, extrafieldbuffersize, comment, commentbuffersize);
}
static int ZipGotoNextFile(Zip* file)
{
_zip* s;
int err;
if (file == NULL)
return _ZIP_PARAM_ERROR;
s = (_zip*)file;
if (!s->currentfileok)
return _ZIP_EOF_LIST;
if (s->numfile + 1 == s->gi.countentries)
return _ZIP_EOF_LIST;
s->posincentraldir += _ZIP_CENTRALDIR_ITEM_SIZE + s->currentfileinfo.filenamesize + s->currentfileinfo.fileextrasize + s->currentfileinfo.filecommentsize;
s->numfile++;
err = ZitZipFileInfoInternal(file, &s->currentfileinfo, &s->currentfileinfointernal, NULL, 0, NULL, 0, NULL, 0);
s->currentfileok = (err == _ZIP_OK);
return err;
}
static int ZipLocateFile(Zip* file, const char *filename, int casesensitive)
{
(void)casesensitive;
_zip* s;
int err;
unsigned long numfilesaved;
unsigned long posincentraldirsaved;
if (file == NULL)
return _ZIP_PARAM_ERROR;
if (strlen(filename) >= _ZIP_MAX_FILENAME_SIZE)
return _ZIP_PARAM_ERROR;
s = (_zip*)file;
if (!s->currentfileok)
return _ZIP_EOF_LIST;
numfilesaved = s->numfile;
posincentraldirsaved = s->posincentraldir;
err = ZipGotoFirstFile(file);
char currentfilename[_ZIP_MAX_FILENAME_SIZE + 1];
while (err == _ZIP_OK)
{
ZitCurrentFileInfo(file, NULL, currentfilename, sizeof(currentfilename) - 1, NULL, 0, NULL, 0);
if (strcmp(currentfilename, filename) == 0)
return _ZIP_OK;
err = ZipGotoNextFile(file);
}
s->numfile = numfilesaved;
s->posincentraldir = posincentraldirsaved;
return err;
}
static int ZipCheckCurrentFileCoherencyHeader(_zip *s, unsigned int *pisizevar, unsigned long *poffsetstaticextrafield, unsigned int *psizestaticextrafield)
{
unsigned long umagic, udata, uflags;
unsigned long filenamesize;
unsigned long sizeextrafield;
int err = _ZIP_OK;
*pisizevar = 0;
*poffsetstaticextrafield = 0;
*psizestaticextrafield = 0;
if (fseek(s->file, s->currentfileinfointernal.currentfileoffset + s->bytebeforezip, SEEK_SET) != 0)
return _ZIP_ERRNO;
if (err == _ZIP_OK)
{
if (ZitLong(s->file, &umagic) != _ZIP_OK)
err = _ZIP_ERRNO;
else if (umagic != 0x04034b50)
err = _ZIP_BAD_FILE;
}
if (ZitShort(s->file, &udata) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(s->file, &uflags) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(s->file, &udata) != _ZIP_OK)
err = _ZIP_ERRNO;
else if ((err == _ZIP_OK) && (udata != s->currentfileinfo.compressionmethod))
err = _ZIP_BAD_FILE;
if ((err == _ZIP_OK) && (s->currentfileinfo.compressionmethod != 0) && (s->currentfileinfo.compressionmethod != Z_DEFLATED))
err = _ZIP_BAD_FILE;
if (ZitLong(s->file, &udata) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitLong(s->file, &udata) != _ZIP_OK)
err = _ZIP_ERRNO;
else if ((err == _ZIP_OK) && (udata != s->currentfileinfo.crc) && ((uflags & 8) == 0))
err = _ZIP_BAD_FILE;
if (ZitLong(s->file, &udata) != _ZIP_OK)
err = _ZIP_ERRNO;
else if ((err == _ZIP_OK) && (udata != s->currentfileinfo.compressedsize) && ((uflags & 8) == 0))
err = _ZIP_BAD_FILE;
if (ZitLong(s->file, &udata) != _ZIP_OK)
err = _ZIP_ERRNO;
else if ((err == _ZIP_OK) && (udata != s->currentfileinfo.uncompressedsize) && ((uflags & 8) == 0))
err = _ZIP_BAD_FILE;
if (ZitShort(s->file, &filenamesize) != _ZIP_OK)
err = _ZIP_ERRNO;
else if ((err == _ZIP_OK) && (filenamesize != s->currentfileinfo.filenamesize))
err = _ZIP_BAD_FILE;
*pisizevar += (unsigned int)filenamesize;
if (ZitShort(s->file, &sizeextrafield) != _ZIP_OK)
err = _ZIP_ERRNO;
*poffsetstaticextrafield = s->currentfileinfointernal.currentfileoffset + _ZIP_LOCALHEADER_SIZE + filenamesize;
*psizestaticextrafield = (unsigned int)sizeextrafield;
*pisizevar += (unsigned int)sizeextrafield;
return err;
}
static int ZipOpenCurrentFile(Zip* file, const char *password)
{
int err = _ZIP_OK;
int store;
unsigned int isizevar;
_zip* s;
zipFileInfoInternal* pfileinzipreadinfo;
unsigned long localextrafieldoffset;
unsigned int localextrafieldsize;
char source[12];
if (file == NULL)
return _ZIP_PARAM_ERROR;
s = (_zip*)file;
if (!s->currentfileok)
return _ZIP_PARAM_ERROR;
if (s->currentzipfileinfo != NULL)
ZipCloseCurrentFile(file);
if (ZipCheckCurrentFileCoherencyHeader(s, &isizevar, &localextrafieldoffset, &localextrafieldsize) != _ZIP_OK)
return _ZIP_BAD_FILE;
pfileinzipreadinfo = (zipFileInfoInternal*)MallocPatch(sizeof(zipFileInfoInternal));
if (pfileinzipreadinfo == NULL)
return _ZIP_INTERNAL_ERROR;
pfileinzipreadinfo->buffer = (char*)MallocPatch(_ZIP_BUFFER_SIZE);
pfileinzipreadinfo->localextrafieldoffset = localextrafieldoffset;
pfileinzipreadinfo->localextrafieldsize = localextrafieldsize;
pfileinzipreadinfo->localextrafieldpos = 0;
if (pfileinzipreadinfo->buffer == NULL)
{
FreePatch(pfileinzipreadinfo);
return _ZIP_INTERNAL_ERROR;
}
pfileinzipreadinfo->streaminitialised = 0;
if ((s->currentfileinfo.compressionmethod != 0) && (s->currentfileinfo.compressionmethod != Z_DEFLATED))
err = _ZIP_BAD_FILE;
store = s->currentfileinfo.compressionmethod == 0;
pfileinzipreadinfo->crc32wait = s->currentfileinfo.crc;
pfileinzipreadinfo->crc32 = 0;
pfileinzipreadinfo->compressionmethod = s->currentfileinfo.compressionmethod;
pfileinzipreadinfo->file = s->file;
pfileinzipreadinfo->bytebeforezip = s->bytebeforezip;
pfileinzipreadinfo->stream.total_out = 0;
if (!store)
{
pfileinzipreadinfo->stream.zalloc = (alloc_func)0;
pfileinzipreadinfo->stream.zfree = (free_func)0;
pfileinzipreadinfo->stream.opaque = (voidpf)0;
err = inflateInit2(&pfileinzipreadinfo->stream, -MAX_WBITS);
if (err == Z_OK)
pfileinzipreadinfo->streaminitialised = 1;
}
pfileinzipreadinfo->restreadcompressed = s->currentfileinfo.compressedsize;
pfileinzipreadinfo->restreaduncompressed = s->currentfileinfo.uncompressedsize;
pfileinzipreadinfo->posinzip = s->currentfileinfointernal.currentfileoffset + _ZIP_LOCALHEADER_SIZE + isizevar;
pfileinzipreadinfo->stream.avail_in = (unsigned int)0;
s->currentzipfileinfo = pfileinzipreadinfo;
if (password != NULL)
{
int i;
s->crc32tab = get_crc_table();
ZipInitKeys(password, s->keys, s->crc32tab);
if (fseek(pfileinzipreadinfo->file, s->currentzipfileinfo->posinzip + s->currentzipfileinfo->bytebeforezip, SEEK_SET) != 0)
{
FreePatch(pfileinzipreadinfo->buffer);
FreePatch(pfileinzipreadinfo);
return _ZIP_INTERNAL_ERROR;
}
if (fread(source, 1, 12, pfileinzipreadinfo->file) < 12)
{
FreePatch(pfileinzipreadinfo->buffer);
FreePatch(pfileinzipreadinfo);
return _ZIP_INTERNAL_ERROR;
}
for (i = 0; i < 12; i++)
zdecode(s->keys, s->crc32tab, source[i]);
s->currentzipfileinfo->posinzip += 12;
s->encrypted = 1;
}
return _ZIP_OK;
}
static int ZipReadCurrentFile(Zip* file, void* buf, unsigned int len)
{
int err = _ZIP_OK;
unsigned int iread = 0;
_zip* s;
zipFileInfoInternal* pfileinzipreadinfo;
if (file == NULL)
return _ZIP_PARAM_ERROR;
s = (_zip*)file;
pfileinzipreadinfo = s->currentzipfileinfo;
if (pfileinzipreadinfo == NULL)
return _ZIP_PARAM_ERROR;
if ((pfileinzipreadinfo->buffer == NULL))
return _ZIP_EOF_LIST;
if (len == 0)
return 0;
pfileinzipreadinfo->stream.next_out = (Bytef*)buf;
pfileinzipreadinfo->stream.avail_out = (unsigned int)len;
if (len > pfileinzipreadinfo->restreaduncompressed)
pfileinzipreadinfo->stream.avail_out = (unsigned int)pfileinzipreadinfo->restreaduncompressed;
while (pfileinzipreadinfo->stream.avail_out > 0)
{
if ((pfileinzipreadinfo->stream.avail_in == 0) && (pfileinzipreadinfo->restreadcompressed > 0))
{
unsigned int ureadthis = _ZIP_BUFFER_SIZE;
if (pfileinzipreadinfo->restreadcompressed < ureadthis)
ureadthis = (unsigned int)pfileinzipreadinfo->restreadcompressed;
if (ureadthis == 0)
return _ZIP_EOF;
if (fseek(pfileinzipreadinfo->file, pfileinzipreadinfo->posinzip + pfileinzipreadinfo->bytebeforezip, SEEK_SET) != 0)
return _ZIP_ERRNO;
if (fread(pfileinzipreadinfo->buffer, ureadthis, 1, pfileinzipreadinfo->file) != 1)
return _ZIP_ERRNO;
if (s->encrypted)
{
unsigned int i;
for (i = 0; i < ureadthis; i++)
pfileinzipreadinfo->buffer[i] = zdecode(s->keys, s->crc32tab, pfileinzipreadinfo->buffer[i]);
}
pfileinzipreadinfo->posinzip += ureadthis;
pfileinzipreadinfo->restreadcompressed -= ureadthis;
pfileinzipreadinfo->stream.next_in = (Bytef*)pfileinzipreadinfo->buffer;
pfileinzipreadinfo->stream.avail_in = (unsigned int)ureadthis;
}
if (pfileinzipreadinfo->compressionmethod == 0)
{
unsigned int udocopy, i;
if ((pfileinzipreadinfo->stream.avail_in == 0) && (pfileinzipreadinfo->restreadcompressed == 0))
return (iread == 0) ? _ZIP_EOF : iread;
if (pfileinzipreadinfo->stream.avail_out < pfileinzipreadinfo->stream.avail_in)
udocopy = pfileinzipreadinfo->stream.avail_out;
else
udocopy = pfileinzipreadinfo->stream.avail_in;
for (i = 0; i < udocopy; i++)
*(pfileinzipreadinfo->stream.next_out + i) = *(pfileinzipreadinfo->stream.next_in + i);
pfileinzipreadinfo->crc32 = crc32(pfileinzipreadinfo->crc32, pfileinzipreadinfo->stream.next_out, udocopy);
pfileinzipreadinfo->restreaduncompressed -= udocopy;
pfileinzipreadinfo->stream.avail_in -= udocopy;
pfileinzipreadinfo->stream.avail_out -= udocopy;
pfileinzipreadinfo->stream.next_out += udocopy;
pfileinzipreadinfo->stream.next_in += udocopy;
pfileinzipreadinfo->stream.total_out += udocopy;
iread += udocopy;
}
else
{
unsigned long utotaloutbefore, utotaloutafter;
const Bytef *bufbefore;
unsigned long uoutthis;
int flush = Z_SYNC_FLUSH;
utotaloutbefore = pfileinzipreadinfo->stream.total_out;
bufbefore = pfileinzipreadinfo->stream.next_out;
err = inflate(&pfileinzipreadinfo->stream, flush);
utotaloutafter = pfileinzipreadinfo->stream.total_out;
uoutthis = utotaloutafter - utotaloutbefore;
pfileinzipreadinfo->crc32 = crc32(pfileinzipreadinfo->crc32, bufbefore, (unsigned int)(uoutthis));
pfileinzipreadinfo->restreaduncompressed -= uoutthis;
iread += (unsigned int)(utotaloutafter - utotaloutbefore);
if (err == Z_STREAM_END)
return (iread == 0) ? _ZIP_EOF : iread;
if (err != Z_OK)
break;
}
}
if (err == Z_OK)
return iread;
return err;
}
Zip* ZipOpen(const char *filename)
{
//print("Opening zip\n");
_zip us;
_zip *s;
unsigned long centralpos, ul;
FILE *file;
unsigned long numberdisk;
unsigned long numberdiskwithCD;
unsigned long numberentryCD;
int err = _ZIP_OK;
file = fopen(filename, "rb");
if (file == NULL)
return NULL;
centralpos = ZipLocateCentralDir(file);
if (centralpos == 0)
err = _ZIP_ERRNO;
if (fseek(file, centralpos, SEEK_SET) != 0)
err = _ZIP_ERRNO;
if (ZitLong(file, &ul) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(file, &numberdisk) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(file, &numberdiskwithCD) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(file, &us.gi.countentries) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(file, &numberentryCD) != _ZIP_OK)
err = _ZIP_ERRNO;
if ((numberentryCD != us.gi.countentries) || (numberdiskwithCD != 0) || (numberdisk != 0))
err = _ZIP_BAD_FILE;
if (ZitLong(file, &us.centraldirsize) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitLong(file, &us.centraldiroffset) != _ZIP_OK)
err = _ZIP_ERRNO;
if (ZitShort(file, &us.gi.commentsize) != _ZIP_OK)
err = _ZIP_ERRNO;
if ((centralpos < us.centraldiroffset + us.centraldirsize) && (err == _ZIP_OK))
err = _ZIP_BAD_FILE;
if (err != _ZIP_OK)
{
fclose(file);
return NULL;
}
us.file = file;
us.bytebeforezip = centralpos - (us.centraldiroffset + us.centraldirsize);
us.centralpos = centralpos;
us.currentzipfileinfo = NULL;
us.encrypted = 0;
s = (_zip*)MallocPatch(sizeof(_zip));
*s = us;
ZipGotoFirstFile((Zip*)s);
return(Zip*)s;
}
int ZipClose(Zip* zip)
{
_zip* s;
if (zip == NULL)
return 0;
s = (_zip*)zip;
if (s->currentzipfileinfo != NULL)
ZipCloseCurrentFile(zip);
//print("Fclose: %d\n", fclose(s->file));
FreePatch(s);
return 1;
}
int ZipExtractCurrentFile(Zip *zip, int *nopath, const char *password)
{
//void(overwrite);
char filenameinzip[256];
char *filenameWithoutPath;
char *p;
void *buffer;
unsigned int buffersize = 64 * 1024;
int err = 0;
FILE *fout = NULL;
zipFileInfo fileInfo;
err = ZitCurrentFileInfo(zip, &fileInfo, filenameinzip, sizeof(filenameinzip), NULL, 0, NULL, 0);
if (err != 0)
{
print("error %d with zipfile in ZitCurrentFileInfo\n", err);
return -1;
}
buffer = (void *)MallocPatch(buffersize);
if (!buffer)
{
print("Error allocating buffer\n");
return 0;
}
p = filenameWithoutPath = filenameinzip;
while ((*p) != '\0')
{
if (((*p) == '/') || ((*p) == '\\'))
filenameWithoutPath = p + 1;
p++;
}
if ((*filenameWithoutPath) == '\0')
{
if ((*nopath) == 0)
{
//print("Creating directory: %s\n", filenameinzip);
mkdir(filenameinzip, 0777);
}
}
else
{
const char *writeFilename;
if ((*nopath) == 0)
writeFilename = filenameinzip;
else
writeFilename = filenameWithoutPath;
err = ZipOpenCurrentFile(zip, password);
if (err != _ZIP_OK)
print("Error with zipfile in ZipOpenCurrentFile\n");
fout = fopen(writeFilename, "wb");
if ((fout == NULL) && ((*nopath) == 0) && (filenameWithoutPath != (char *)filenameinzip))
{
char c = *(filenameWithoutPath - 1);
*(filenameWithoutPath - 1) = '\0';
mkdir(writeFilename, 0777);
*(filenameWithoutPath - 1) = c;
fout = fopen(writeFilename, "wb");
}
if (fout == NULL)
print("Error opening file\n");
do
{
err = ZipReadCurrentFile(zip, buffer, buffersize);
if (err < 0)
{
print("Error with zipfile in ZipReadCurrentFile\n");
break;
}
if (err > 0)
{
fwrite(buffer, 1, err, fout);
}
} while (err > 0);
fclose(fout);
err = ZipCloseCurrentFile(zip);
if (err != _ZIP_OK)
print("Error with zipfile in ZipCloseCurrentFile\n");
}
if (buffer)
FreePatch(buffer);
return err;
}
int ZipExtract(Zip* zip, const char *password)
{
unsigned int i;
zipGlobalInfo gi;
memset(&gi, 0, sizeof(zipGlobalInfo));
int err;
int nopath = 0;
err = ZitGlobalInfo(zip, &gi);
if (err != _ZIP_OK)
print("Error with zipfile in ZitGlobalInfo\n");
for (i = 0; i < gi.countentries; i++)
{
if (ZipExtractCurrentFile(zip, &nopath, password) != _ZIP_OK)
break;
if ((i + 1) < gi.countentries)
{
err = ZipGotoNextFile(zip);
if (err != _ZIP_OK)
print("Error with zipfile in ZipGotoNextFile\n");
}
}
return err;
}
ZipFile* ZipFileRead(Zip* zip, const char *filename, const char *password)
{
char filenameinzip[256];
int err = 0;
ZipFile* zipfile = (ZipFile*)MallocPatch(sizeof(ZipFile));
if (!zipfile)
return NULL;
if (ZipLocateFile(zip, filename, 0) != 0)
{
FreePatch(zipfile);
return NULL;
}
zipFileInfo fileinfo;
err = ZitCurrentFileInfo(zip, &fileinfo, filenameinzip, sizeof(filenameinzip), NULL, 0, NULL, 0);
if (err != 0)
{
print("error %d with zipfile in ZitCurrentFileInfo\n", err);
FreePatch(zipfile);
return NULL;
}
err = ZipOpenCurrentFile(zip, password);
if (err != 0)
{
print("error %d with zipfile in ZipOpenCurrentFile\n", err);
FreePatch(zipfile);
return NULL;
}
zipfile->size = fileinfo.uncompressedsize;
zipfile->data = (unsigned char*)MallocPatch(fileinfo.uncompressedsize);
if (!zipfile->data)
{
print("error allocating data for zipfile\n");
FreePatch(zipfile);
return NULL;
}
unsigned int count = 0;
err = 1;
while (err > 0)
{
err = ZipReadCurrentFile(zip, &zipfile->data[count], fileinfo.uncompressedsize);
if (err < 0)
{
print("error %d with zipfile in ZipReadCurrentFile\n", err);
break;
}
else
count += err;
}
if (err == 0)
{
err = ZipCloseCurrentFile(zip);
if (err != 0)
{
print("error %d with zipfile in ZipCloseCurrentFile\n", err);
FreePatch(zipfile->data);
FreePatch(zipfile);
return NULL;
}
return zipfile;
}
else
{
ZipCloseCurrentFile(zip);
FreePatch(zipfile->data);
FreePatch(zipfile);
return NULL;
}
}
void ZipFileFreePatch(ZipFile* file)
{
if (file->data)
FreePatch(file->data);
if (file)
FreePatch(file);
}
| 21,946
|
https://github.com/Pis-moove-it/reciclando-mobile/blob/master/src/__test__/__reducers__/Edit-bale-modal-reducer.test.js
|
Github Open Source
|
Open Source
|
MIT
| null |
reciclando-mobile
|
Pis-moove-it
|
JavaScript
|
Code
| 126
| 442
|
import editBaleModalReducer, { initialState } from '../../reducers/EditBaleModalReducer';
import { actionTypes } from '../../actions/EditBaleModalActions';
jest.mock(
'react-native-localization',
() =>
class RNLocalization {
language = 'en';
constructor(props) {
this.props = props;
this.setLanguage(this.language);
}
setLanguage(interfaceLanguage) {
this.language = interfaceLanguage;
}
},
);
describe('edit bale modal reducer', () => {
it('should return the same state', () => {
expect(editBaleModalReducer(initialState, { users: [], type: 'not_an_action' })).toEqual(initialState);
});
it('should a state with isVisible in false', () => {
expect(editBaleModalReducer(initialState, {
type: actionTypes.CLOSE_EDIT_BALE_MODAL,
})).toEqual({
bale: false,
baleData: false,
editBaleModalIsOpen: false,
isLoading: false,
material: false,
weight: false,
});
});
it('should a state with isVisible in true', () => {
expect(editBaleModalReducer(initialState, {
type: actionTypes.OPEN_EDIT_BALE_MODAL,
bale: '99',
material: 'Glass',
weight: '99',
})).toEqual({
bale: '99',
baleData: false,
editBaleModalIsOpen: true,
isLoading: false,
material: 'Glass',
weight: '99',
});
});
});
| 25,124
|
https://github.com/miguelortega03/Inacap_Mobile/blob/master/www/addons/mod/scorm/services/scorm_online.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Inacap_Mobile
|
miguelortega03
|
JavaScript
|
Code
| 1,033
| 2,900
|
// (C) Copyright 2015 Martin Dougiamas
//
// 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.
angular.module('mm.addons.mod_scorm')
/**
* Service to handle SCORM online features.
* This service holds getters and setters that have some kind of equivalent feature in $mmaModScormOffline.
*
* @module mm.addons.mod_scorm
* @ngdoc service
* @name $mmaModScormOnline
*/
.factory('$mmaModScormOnline', function($mmSitesManager, $mmSite, $q, $mmWS, $log, mmCoreWSPrefix, $mmSyncBlock,
mmaModScormComponent) {
$log = $log.getInstance('$mmaModScormOnline');
var self = {};
/**
* Get cache key for SCORM attempt count WS calls.
*
* @param {Number} scormId SCORM ID.
* @param {Number} [userId] User ID. If not defined, current user.
* @return {String} Cache key.
*/
function getAttemptCountCacheKey(scormId, userId) {
userId = userId || $mmSite.getUserId();
return 'mmaModScorm:attemptcount:' + scormId + ':' + userId;
}
/**
* Get the number of attempts done by a user in the given SCORM.
*
* @module mm.addons.mod_scorm
* @ngdoc method
* @name $mmaModScormOnline#getAttemptCount
* @param {String} siteId Site ID.
* @param {Number} scormId SCORM ID.
* @param {Number} [userId] User ID. If not defined use site's current user.
* @param {Boolean} ignoreMissing True if it should ignore attempts that haven't reported a grade/completion.
* @param {Boolean} ignoreCache True if it should ignore cached data (it will always fail in offline or server down).
* @return {Promise} Promise resolved when the attempt count is retrieved.
*/
self.getAttemptCount = function(siteId, scormId, userId, ignoreMissing, ignoreCache) {
return $mmSitesManager.getSite(siteId).then(function(site) {
userId = userId || site.getUserId();
var params = {
scormid: scormId,
userid: userId,
ignoremissingcompletion: ignoreMissing ? 1 : 0
},
preSets = {
cacheKey: getAttemptCountCacheKey(scormId, userId)
};
if (ignoreCache) {
preSets.getFromCache = 0;
preSets.emergencyCache = 0;
}
return site.read('mod_scorm_get_scorm_attempt_count', params, preSets).then(function(response) {
if (response && typeof response.attemptscount != 'undefined') {
return response.attemptscount;
}
return $q.reject();
});
});
};
/**
* Get cache key for SCORM user data WS calls.
*
* @param {Number} scormId SCORM ID.
* @param {Number} attempt Attempt number.
* @return {String} Cache key.
*/
function getScormUserDataCacheKey(scormId, attempt) {
return getScormUserDataCommonCacheKey(scormId) + ':' + attempt;
}
/**
* Get common cache key for SCORM user data WS calls.
*
* @param {Number} scormId SCORM ID.
* @return {String} Cache key.
*/
function getScormUserDataCommonCacheKey(scormId) {
return 'mmaModScorm:userdata:' + scormId;
}
/**
* Get the user data for a certain SCORM and attempt.
*
* @module mm.addons.mod_scorm
* @ngdoc method
* @name $mmaModScormOnline#getScormUserData
* @param {String} siteId Site ID.
* @param {Number} scormId SCORM ID.
* @param {Number} attempt Attempt number.
* @param {Boolean} ignoreCache True if it should ignore cached data (it will always fail in offline or server down).
* @return {Promise} Promise resolved when the user data is retrieved.
*/
self.getScormUserData = function(siteId, scormId, attempt, ignoreCache) {
return $mmSitesManager.getSite(siteId).then(function(site) {
var params = {
scormid: scormId,
attempt: attempt
},
preSets = {
cacheKey: getScormUserDataCacheKey(scormId, attempt)
};
if (ignoreCache) {
preSets.getFromCache = 0;
preSets.emergencyCache = 0;
}
return site.read('mod_scorm_get_scorm_user_data', params, preSets).then(function(response) {
if (response && response.data) {
// Format the response.
var data = {};
angular.forEach(response.data, function(sco) {
var formattedDefaultData = {},
formattedUserData = {};
angular.forEach(sco.defaultdata, function(entry) {
formattedDefaultData[entry.element] = entry.value;
});
angular.forEach(sco.userdata, function(entry) {
formattedUserData[entry.element] = entry.value;
});
sco.defaultdata = formattedDefaultData;
sco.userdata = formattedUserData;
data[sco.scoid] = sco;
});
return data;
}
return $q.reject();
});
});
};
/**
* Invalidates attempt count.
*
* @module mm.addons.mod_scorm
* @ngdoc method
* @name $mmaModScormOnline#invalidateAttemptCount
* @param {String} siteId Site ID.
* @param {Number} scormId SCORM ID.
* @param {Number} [userId] User ID. If not defined use site's current user.
* @return {Promise} Promise resolved when the data is invalidated.
*/
self.invalidateAttemptCount = function(siteId, scormId, userId) {
return $mmSitesManager.getSite(siteId).then(function(site) {
userId = userId || site.getUserId();
return site.invalidateWsCacheForKey(getAttemptCountCacheKey(scormId, userId));
});
};
/**
* Invalidates SCORM user data for all attempts.
*
* @module mm.addons.mod_scorm
* @ngdoc method
* @name $mmaModScormOnline#invalidateScormUserData
* @param {String} siteId Site ID.
* @param {Number} scormId SCORM ID.
* @return {Promise} Promise resolved when the data is invalidated.
*/
self.invalidateScormUserData = function(siteId, scormId) {
return $mmSitesManager.getSite(siteId).then(function(site) {
return site.invalidateWsCacheForKeyStartingWith(getScormUserDataCommonCacheKey(scormId));
});
};
/**
* Saves a SCORM tracking record.
*
* @module mm.addons.mod_scorm
* @ngdoc method
* @name $mmaModScormOnline#saveTracks
* @param {String} siteId Site ID. If not set, use current site.
* @param {Number} scormId SCORM ID.
* @param {Number} scoId Sco ID.
* @param {Number} attempt Attempt number.
* @param {Object[]} tracks Tracking data.
* @return {Promise} Promise resolved when data is saved.
*/
self.saveTracks = function(siteId, scormId, scoId, attempt, tracks) {
return $mmSitesManager.getSite(siteId).then(function(site) {
var params = {
scoid: scoId,
attempt: attempt,
tracks: tracks
};
if (!tracks || !tracks.length) {
return $q.when(); // Nothing to save.
}
$mmSyncBlock.blockOperation(mmaModScormComponent, scormId, 'saveTracksOnline', siteId);
return site.write('mod_scorm_insert_scorm_tracks', params).then(function(response) {
if (response && response.trackids) {
return response.trackids;
}
return $q.reject();
}).finally(function() {
$mmSyncBlock.unblockOperation(mmaModScormComponent, scormId, 'saveTracksOnline', siteId);
});
});
};
/**
* Saves a SCORM tracking record using a synchronous call.
* Please use this function only if synchronous is a must. It's recommended to use $mmaModScorm#saveTracks.
*
* @module mm.addons.mod_scorm
* @ngdoc method
* @name $mmaModScormOnline#saveTracksSync
* @param {Number} scoId Sco ID.
* @param {Number} attempt Attempt number.
* @param {Object[]} tracks Tracking data.
* @return {Boolean} True if success, false otherwise.
*/
self.saveTracksSync = function(scoId, attempt, tracks) {
var params = {
scoid: scoId,
attempt: attempt,
tracks: tracks
},
preSets = {
siteurl: $mmSite.getURL(),
wstoken: $mmSite.getToken()
},
wsFunction = $mmSite.getCompatibleFunction('mod_scorm_insert_scorm_tracks'),
response;
if (!tracks || !tracks.length) {
return true; // Nothing to save.
}
// Check if the method is available, use a prefixed version if possible.
if (!$mmSite.wsAvailable(wsFunction, false)) {
if ($mmSite.wsAvailable(mmCoreWSPrefix + wsFunction, false)) {
wsFunction = mmCoreWSPrefix + wsFunction;
} else {
$log.error("WS function '" + wsFunction + "' is not available, even in compatibility mode.");
return false;
}
}
response = $mmWS.syncCall(wsFunction, params, preSets);
if (response && !response.error && response.trackids) {
return true;
}
return false;
};
return self;
});
| 9,243
|
https://github.com/Topface/plus1-android-sdk/blob/master/sdk/src/ru/wapstart/plus1/sdk/BaseAdView.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
plus1-android-sdk
|
Topface
|
Java
|
Code
| 410
| 950
|
/**
* Copyright (c) 2012, Alexander Zaytsev <a.zaytsev@co.wapstart.ru>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the "Wapstart" nor the names
* of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ru.wapstart.plus1.sdk;
import android.content.Context;
import android.webkit.WebView;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
public abstract class BaseAdView extends WebView {
private static final String LOGTAG = "BaseAdView";
public BaseAdView(Context context) {
super(context);
}
abstract public void loadHtmlData(String data);
public void pauseAdView() {
callHiddenWebViewMethod("onPause");
}
public void resumeAdView() {
callHiddenWebViewMethod("onResume");
}
/**
* NOTE: NPE workaround for WebView
*/
@Override
public void onWindowFocusChanged(boolean hasFocus) {
try {
super.onWindowFocusChanged(hasFocus);
} catch (NullPointerException npe) { }
}
protected String completeHtml(String data) {
// If the string data lacks the HTML boilerplate, add it.
if (data.indexOf("<html>") == -1) {
data = "<html><head></head><body style='margin:0;padding:0;'>"
+ data + "</body></html>";
}
return data;
}
/**
* @see http://stackoverflow.com/questions/3431351/how-do-i-pause-flash-content-in-an-android-webview-when-my-activity-isnt-visible
*/
private void callHiddenWebViewMethod(String name) {
try {
WebView.class.getMethod(name).invoke(this);
} catch (NoSuchMethodException e) {
Log.w(LOGTAG, "No such method: " + name, e);
} catch (IllegalAccessException e) {
Log.e(LOGTAG, "Illegal Access: " + name, e);
} catch (InvocationTargetException e) {
Log.e(LOGTAG, "Invocation Target Exception: " + name, e);
}
}
}
| 37,746
|
https://github.com/TomBrossy/event_map_planner/blob/master/pages/_app.js
|
Github Open Source
|
Open Source
|
MIT
| null |
event_map_planner
|
TomBrossy
|
JavaScript
|
Code
| 35
| 120
|
import Layout from '../components/Layout';
import '../styles/global.css';
import 'tailwindcss/tailwind.css'
import "react-notifications-component/dist/theme.css";
import ReactNotification from "react-notifications-component";
export default function MyApp({ Component, pageProps }) {
return (
<>
<Layout>
<ReactNotification />
<Component {...pageProps} />
</Layout>
</>
);
}
| 7,652
|
https://github.com/postBG/CIFAR10-CNN-tensorflow/blob/master/data.py
|
Github Open Source
|
Open Source
|
MIT
| null |
CIFAR10-CNN-tensorflow
|
postBG
|
Python
|
Code
| 344
| 1,275
|
import os
import pickle
import numpy as np
from sklearn.preprocessing import LabelBinarizer
from utils import Cifar10, unpickle
preprocessed_data_path = "preprocessed-cifar10-data"
lb = LabelBinarizer()
lb.fit(range(Cifar10.num_classes))
if not os.path.exists(preprocessed_data_path):
os.makedirs(preprocessed_data_path)
def one_hot_encode(x):
"""
One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
: x: List of sample Labels
: return: Numpy array of one-hot encoded labels
"""
return lb.transform(x)
def normalize(x):
"""
Normalize a list of sample image data in the range of 0 to 1
used min-max normalization
: x: List of image data. The image shape is (32, 32, 3)
: return: Numpy array of normalize data
"""
max_value = 255
min_value = 0
return (x - min_value) / (max_value - min_value)
class DataManager(Cifar10):
@staticmethod
def _get_preprocessed_filename(filename):
return os.path.join(preprocessed_data_path, filename)
@staticmethod
def _get_processed_train_batch_filename(batch_id):
return DataManager._get_preprocessed_filename('preprocess_batch_' + str(batch_id) + '.p')
@staticmethod
def _preprocess_and_save(features_preprocessor, labels_preprocessor, features, labels, filename):
"""
Preprocess data and save it to file
"""
processed_features = features_preprocessor(features)
processed_labels = labels_preprocessor(labels)
pickle.dump((processed_features, processed_labels), open(filename, 'wb'))
def preprocess_and_save(self, features_preprocessor, labels_preprocessor, validation_rate=0.1):
n_batches = 5
validation_features = []
validation_labels = []
for batch_id in range(1, n_batches + 1):
features, labels = self.load_batch(batch_id)
validation_count = int(len(features) * validation_rate)
# Prprocess and save a batch of training data
DataManager._preprocess_and_save(
features_preprocessor,
labels_preprocessor,
features[:-validation_count],
labels[:-validation_count],
DataManager._get_processed_train_batch_filename(batch_id))
# Use a portion of training batch for validation
validation_features.extend(features[-validation_count:])
validation_labels.extend(labels[-validation_count:])
# Preprocess and Save all validation data
DataManager._preprocess_and_save(
features_preprocessor,
labels_preprocessor,
np.array(validation_features),
np.array(validation_labels),
os.path.join(preprocessed_data_path, 'preprocess_validation.p'))
test_batch = unpickle('test_batch')
# load the training data
test_features = test_batch['data'].reshape((len(test_batch['data']), 3, 32, 32)).transpose(0, 2, 3, 1)
test_labels = test_batch['labels']
# Preprocess and Save all training data
DataManager._preprocess_and_save(
features_preprocessor,
labels_preprocessor,
np.array(test_features),
np.array(test_labels),
os.path.join(preprocessed_data_path, 'preprocess_test.p'))
@staticmethod
def batch_features_labels(features, labels, batch_size):
"""
Split features and labels into batches
"""
for start in range(0, len(features), batch_size):
end = min(start + batch_size, len(features))
yield features[start:end], labels[start:end]
@staticmethod
def load_preprocess_training_batch(batch_id, batch_size):
"""
Load the Preprocessed Training data and return them in batches of <batch_size> or less
"""
filename = DataManager._get_processed_train_batch_filename(batch_id)
features, labels = pickle.load(open(filename, mode='rb'))
return DataManager.batch_features_labels(features, labels, batch_size)
@staticmethod
def load_preprocess_validation():
validation_filepath = DataManager._get_preprocessed_filename('preprocess_validation.p')
return pickle.load(open(validation_filepath, mode='rb'))
@staticmethod
def load_preprocess_test():
test_filepath = DataManager._get_preprocessed_filename('preprocess_test.p')
return pickle.load(open(test_filepath, mode='rb'))
| 44,648
|
https://github.com/54481280/tp5/blob/master/runtime/temp/e2b8115d175c8eed1a9b7dbe15247f56.php
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
tp5
|
54481280
|
PHP
|
Code
| 201
| 1,203
|
<?php if (!defined('THINK_PATH')) exit(); /*a:1:{s:53:"E:\phpStudy\PHPTutorial\WWW\tp5\addons/digg\vote.html";i:1496373782;}*/ ?>
<link rel="stylesheet" type="text/css" href="__STATIC__/addons/digg/css/style.css">
<link rel="stylesheet" type="text/css" href="__STATIC__/addons/digg/css/font-awesome.min.css">
<script type="text/javascript">
var vote_flag=false;
var uid = <?php echo is_login(); ?>;
function vote(id,type){
if(<?php echo is_login(); ?> == 0){
alert('请登录后再投票');
return;
}
if(vote_flag == true){
alert('<?php echo $addons_config['stop_repeat_tip']; ?>');
return;
}
$.ajax({
url: '<?php echo addons_url("Digg://Digg/vote"); ?>',
data: {
'id':id,
'type':type
},
success:function(data){
if(data.code){
$('#vote_'+type).text(parseInt($('#vote_'+type).text())+1);
update_vote();
}else{
alert(data.msg);
}
vote_flag = true;
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert('发送请求失败了,请刷新后继续投票');
}
});
}
function update_vote(){
var sUp = parseInt($('#vote_1').text());
var sDown = parseInt($("#vote_2").text());
var sTotal = sUp+sDown;
if(sTotal == 0){
var spUp = spDown = 50;
}else{
var spUp = (sUp/sTotal)*100;
spUp = Math.round(spUp*10)/10;
var spDown=100-spUp;
spDown=Math.round(spDown*10)/10;
}
$('#sp1').text(spUp+'%');
$('#sp2').text(spDown+'%');
$('#eimg1').width(parseInt(spUp/100*70));
$('#eimg2').width(parseInt(spDown/100*70));
}
$(function(){
update_vote();
})
</script>
<div id="vote_addon_box">
<div class="pub_style up" onclick="vote(<?php echo $addons_vote_record['document_id']; ?>,1)">
<div class="font_line">
<i class="fa fa-thumbs-o-up fa-lg"></i><span><?php echo $addons_config['good_tip']; ?></span>
</div>
<div class="bar_line">
<div class="prosess_bar">
<div class="prosess_bar_content" id="eimg1"></div>
</div>
<span id="sp1">%</span>
(<span id="vote_1"><?php echo (isset($addons_vote_record['good']) && ($addons_vote_record['good'] !== '')?$addons_vote_record['good']:0); ?></span>)
</div>
<b>顶</b>
</div>
<div class="pub_style down" onclick="vote(<?php echo $addons_vote_record['document_id']; ?>,2)">
<div class="font_line">
<i class="fa fa-thumbs-o-down fa-lg"></i><span><?php echo $addons_config['bad_tip']; ?></span>
</div>
<div class="bar_line">
<div class="prosess_bar">
<div class="prosess_bar_content" id="eimg2"></div>
</div>
<span id="sp2">%</span>
(<span id="vote_2"><?php echo (isset($addons_vote_record['bad']) && ($addons_vote_record['bad'] !== '')?$addons_vote_record['bad']:0); ?></span>)
</div>
<b>踩</b>
</div>
</div>
<div class="clearfix"></div>
| 13,172
|
https://github.com/YX577/MonthlyRunoffForecastByAutoReg/blob/master/Huaxian_eemd/projects/pred_ana.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
MonthlyRunoffForecastByAutoReg
|
YX577
|
Python
|
Code
| 79
| 546
|
import os
current_path = os.path.dirname(os.path.abspath(__file__))
parent_path = os.path.abspath(os.path.join(current_path, os.path.pardir))
grandpa_path = os.path.abspath(os.path.join(parent_path, os.path.pardir))
data_path = parent_path + '\\data\\'
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
MODEL_ID = 8
model_path = current_path+'\\lstm-models-history\\imf'+str(MODEL_ID)+'\\'
pred_files_list=[]
train_rmse=[]
dev_rmse=[]
test_rmse=[]
train_r2=[]
dev_r2=[]
test_r2=[]
for files in os.listdir(model_path):
if files.find('.csv')>=0 and (files.find('HISTORY')<0 and files.find('metrics')<0):
pred_files_list.append(files)
print(files)
data = pd.read_csv(model_path+files)
train_rmse.append(data['rmse_train'][0])
dev_rmse.append(data['rmse_dev'][0])
test_rmse.append(data['rmse_test'][0])
train_r2.append(data['r2_train'][0])
dev_r2.append(data['r2_dev'][0])
test_r2.append(data['r2_test'][0])
metrics_dict = {
'model':pred_files_list,
'train_rmse':train_rmse,
'dev_rmse':dev_rmse,
'test_rmse':test_rmse,
'train_r2':train_r2,
'dev_r2':dev_r2,
'test_r2':test_r2,
}
metrics_df = pd.DataFrame(metrics_dict)
metrics_df.to_csv(model_path+'imf'+str(MODEL_ID)+'-metrics.csv')
| 44,463
|
https://github.com/NanoCode012/ITStep/blob/master/C Programming/Two Dimension Array Shift/main.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
ITStep
|
NanoCode012
|
C++
|
Code
| 269
| 709
|
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int ShiftHorizontal(bool shiftRight, int amount, int arr[2][6]){
//create a new array which stores new value
//set value from old array into correct position is new array
//copy from new array back into old array
int array[2][6];
if (!shiftRight) amount *= -1;
for (int i = 0; i < 6; i++){
int position = (i + amount) % 6;
if (position < 0) position += 6;
array[0][position] = arr[0][i];
array[1][position] = arr[1][i];
}
for (int i = 0; i < 6; i++){
arr[0][i] = array[0][i];
arr[1][i] = array[1][i];
}
return 0;
}
int ShiftVertical(bool shiftDown, int amount, int arr[2][6]){
int array[2][6];
if (!shiftDown) amount *= -1;
for (int i = 0; i < 6; i++){
int position = (amount) % 2;
if (position < 0) position += 2;
array[position][i] = arr[0][i];
array[(position + 1) % 2][i] = arr[1][i];
}
for (int i = 0; i < 6; i++){
arr[0][i] = array[0][i];
arr[1][i] = array[1][i];
}
return 0;
}
int ShowArrays(int arr[2][6]){
for (int i = 0; i < 6; i++) cout << arr[0][i%6] << " ";
cout << endl;
for (int i = 0; i < 6; i++) cout << arr[1][i%6] << " ";
cout << endl;
return 0;
}
int main(){
srand(time(NULL));
int arr[2][6];
for (int i = 0; i < 12; i++) arr[i/6][i%6] = rand() % 20;
ShowArrays(arr);
char c;
cin >> c;
int amount;
cin >> amount;
switch(c)
{
case 'w':
ShiftVertical(false, amount, arr);
break;
case 's':
ShiftVertical(true, amount, arr);
break;
case 'a':
ShiftHorizontal(false, amount, arr);
break;
case 'd':
ShiftHorizontal(true, amount, arr);
break;
}
ShowArrays(arr);
return 0;
}
| 30,474
|
https://github.com/silcam/cmbpayroll/blob/master/db/migrate/20171006140754_create_loans.rb
|
Github Open Source
|
Open Source
|
MIT
| null |
cmbpayroll
|
silcam
|
Ruby
|
Code
| 39
| 151
|
class CreateLoans < ActiveRecord::Migration[5.1]
def change
create_table :loans do |t|
t.float :amount
t.string :comment
t.date :origination
t.integer :term
t.timestamps
end
add_reference :loans, :employee
create_table :loan_payments do |t|
t.float :amount
t.timestamps
end
add_index :loan_payments, :amount
add_reference :loan_payments, :loan
end
end
| 37,944
|
https://github.com/sajeer-nooh/pacbot/blob/master/api/pacman-api-asset/src/main/java/com/tmobile/pacman/api/asset/service/AssetService.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
pacbot
|
sajeer-nooh
|
Java
|
Code
| 2,517
| 4,829
|
/*******************************************************************************
* Copyright 2018 T Mobile, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package com.tmobile.pacman.api.asset.service;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.tmobile.pacman.api.asset.domain.ResponseWithFieldsByTargetType;
import com.tmobile.pacman.api.asset.model.DefaultUserAssetGroup;
import com.tmobile.pacman.api.commons.exception.DataException;
import com.tmobile.pacman.api.commons.exception.ServiceException;
/**
* This is the main interface for asset service which contains business logics and method calls to repository
*/
public interface AssetService {
/**
* Fetches the total count of assets for the particular asset group. If no
* type is passed, all the assets of valid target type for the asset group
* is considered.
*
* @param aseetGroupName name of the asset group
* @param type target type
* @param domain the domain of asset group
*
* @return list of type and its asset count.
*/
public List<Map<String, Object>> getAssetCountByAssetGroup(String aseetGroupName, String type, String domain);
/**
* Fetches all the target types for the particular asset group. If asset
* group is passed as aws then all the available target types is returned .
*
* @param aseetGroupName name of the asset group
* @param domain the domain of asset group
*
* @return list of target types.
*/
public List<Map<String, Object>> getTargetTypesForAssetGroup(String aseetGroupName, String domain);
/**
* Fetches all the applications for the particular asset group.
*
* @param aseetGroupName name of the asset group
* @param domain the domain of asset group
*
* @return list of applications.
* @throws DataException when there is an error while fetching data
*/
public List<Map<String, Object>> getApplicationsByAssetGroup(String aseetGroupName, String domain) throws DataException;
/**
* Fetches all the environments for the particular asset group. Application
* and Domain can also be passed to filter the environments
*
* @param assetGroup name of the asset group
* @param application name of the application
* @param domain the domain of asset group
*
* @return list of environments.
*/
public List<Map<String, Object>> getEnvironmentsByAssetGroup(String assetGroup, String application, String domain);
/**
* Fetches all the asset groups and its name, display name, description,
* type, createdby and domains
*
* @return list of asset group details.
*/
public List<Map<String, Object>> getAllAssetGroups();
/**
* Fetches all the details of the asset group - name, display name,
* description, type, createdby, appcount, assetcount and domains.
*
* @param assetGroup name of the asset group
*
* @return asset group info.
*/
public Map<String, Object> getAssetGroupInfo(String assetGroup);
/**
* Fetches the total asset count for each application for the given target
* type and asset group.
*
* @param assetGroup name of the asset group
* @param type target type of the asset group
*
* @return list of applications and its asset count.
* @throws DataException when there is an error while fetching data
*/
public List<Map<String, Object>> getAssetCountByApplication(String assetGroup, String type) throws DataException;
/**
* Fetches the asset trends(daily min/max) over the period of last 1 month
* for the given asset group. From and to can be passed to fetch the asset
* trends for particular days.
*
* @param assetGroup name of the asset group
* @param type target type of the asset group
* @param from from date
* @param to to date
*
* @return list of days with its min/max asset count.
*/
public List<Map<String, Object>> getAssetMinMax(String assetGroup, String type, Date from, Date to);
/**
* Save/update asset group details in DB.Saves default asset group for the
* user id.
*
* @param defaultUserAssetGroup This request expects userid and assetgroup name as mandatory.
*
* @return boolean as updated status.
*/
public Boolean saveOrUpdateAssetGroup(DefaultUserAssetGroup defaultUserAssetGroup);
/**
* Fetches the default asset group the user has saved for the given asset
* group.
*
* @param userId id of the user
*
* @return asset group name.
*/
public String getUserDefaultAssetGroup(String userId);
/**
* Fetches the total asset count for each environment for the given target
* type and asset group.
*
* @param assetGroup name of the asset group
* @param type target type of the asset group
* @param application application needed for the count
*
* @return list of environment and its asset count.
*/
public List<Map<String, Object>> getAssetCountByEnvironment(String assetGroup, String application, String type);
/**
* Saves the recently viewed asset group for the user id.
*
* @param assetGroup name of the asset group
* @param userId id of the user
*
* @return updated list of asset group for the userId.
* @throws DataException when there is an error while fetching data
*/
public List<Map<String, Object>> saveAndAppendToRecentlyViewedAG(String userId, String assetGroup) throws DataException;
/**
* Fetches all the asset for the given asset group.
*
* @param assetGroup name of the asset group
* @param filter application,environment,resourceType as optional filters
* @param searchText searchText is used to match any text you are looking for
* @param from for pagination
* @param size for pagination
*
* @return list of assets and its some details.
*/
public List<Map<String, Object>> getListAssets(String assetGroup, Map<String, String> filter, int from, int size,
String searchText);
/**
* Fetches the total asset count for the given asset group.
*
* @param assetGroup name of the asset group
* @param filter application,environment,resourceType as optional filters
* @param searchText searchText is used to match any text you are looking for
* @param from for pagination
* @param size for pagination
*
* @return list of assets and its some details.
*/
public long getAssetCount(String assetGroup, Map<String, String> filter, String searchText);
/**
* Fetches the CPU utilization for the given instanceid.
*
* @param instanceid id of the instance
*
* @return list of date and its CPU utilization of the instance id.
* @throws DataException when there is an error while fetching data
*/
public List<Map<String, Object>> getInstanceCPUUtilization(String instanceid) throws DataException;
/**
* Fetches the Disk utilization for the given instanceid.
*
* @param instanceid id of the instance
*
* @return list of disk name, size and free space of the instance id.
* @throws DataException when there is an error while fetching data
*/
public List<Map<String, Object>> getInstanceDiskUtilization(String instanceid) throws DataException;
/**
* Fetches the Softwares installed for the given instanceid.
*
* @param instanceId id of the instance
* @param from for pagination
* @param size for pagination
* @param searchText searchText is used to match any text you are looking for
*
* @return list of software name and its version installed on the instance id.
* @throws DataException when there is an error while fetching data
*/
public List<Map<String, Object>> getInstanceSoftwareInstallDetails(String instanceId, Integer from, Integer size,
String searchText) throws DataException;
/**
* Fetches the ec2 resource details for the given assetgroup and resourceId.
*
* @param ag name of the asset group
* @param resourceId id of the resource
*
* @return all the ec2 details for assetgroup.
* @throws DataException when there is an error while fetching data
* @throws ServiceException when there is an error while fetching data
*/
public Map<String, Object> getEc2ResourceDetail(String ag, String resourceId) throws DataException,ServiceException;
/**
* Fetches the patchable assets for the given assetgroup.If patched filter is false it returns the unpatched assets
* and if patched is true returns the patched assets.It also filters the the list based on resource type passed in filter
* else returns all the assets of the asset group
*
* @param assetGroup name of the asset group
* @param filter patched(true/false),application,environment,resourcetype,
* executivesponsor,director as optional filters
*
* @return list of assets patched/unpatched.
*/
public List<Map<String, Object>> getListAssetsPatchable(String assetGroup, Map<String, String> filter);
/**
* Fetches the taggable assets for the given assetgroup.If tagged filter is false it returns the untagged assets
* and if tagged is true returns the tagged assets.It also filters the the list based on resource type passed in filter
* else returns all the assets of the asset group
*
* @param assetGroup name of the asset group
* @param filter tagged(true/false),application,environment,resourcetype,
* tagname(must with tagged) as optional filters
*
* @return list of assets tagged/untagged.
*/
public List<Map<String, Object>> getListAssetsTaggable(String assetGroup, Map<String, String> filter);
/**
* Fetches the resource details for the given resourceId
*
* @param dataSource the dataSource
* @param resourceType type of the resource
* @param resourceId id of the resource
*
* @return name,value and category of the resourceId.
* @throws DataException when there is an error while fetching data
*/
public Map<String, Object> getGenericResourceDetail(String dataSource, String resourceType, String resourceId)
throws DataException;
/**
* Fetches the vulnerable assets for the given assetgroup. It looks for any particular resourceType passed in the filter
* else considers ec2 and onpremserver for targetype and fetch it vulnerable asset details.
*
* @param assetGroup name of the asset group
* @param filter qid as mandatory and application,environment as optional filters
*
* @return list of vulnerable assets.
*/
public List<Map<String, Object>> getListAssetsVulnerable(String assetGroup, Map<String, String> filter);
/**
* Fetches the port which are in open status for the given instanceId.
*
* @param instanceId id of the instance
* @param from for pagination
* @param size for pagination
* @param searchText searchText is used to match any text you are looking for
*
* @return list of open ports.
* @throws DataException when there is an error while fetching data
*/
public List<Map<String, Object>> getOpenPortDetails(String instanceId, Integer from, Integer size, String searchText)
throws DataException;
/**
* Fetches the state of the resourceId for the given asset group.
*
* @param ag name of the asset group
* @param resourceId id of the resource
*
* @return state of resourceId
* @throws DataException when there is an error while fetching data
*/
public String getEc2StateDetail(String ag, String resourceId) throws DataException;
/**
* Fetches the assets with open issue status for the rule id passed in the filter.
*
* @param assetGroup name of the asset group
* @param filter ruleid as mandatory and compliant(true/false),application,environment,resourcetype as
* optional filters
*
* @return list of assets with open issue status.
*/
public List<Map<String, Object>> getListAssetsScanned(String assetGroup, Map<String, String> filter);
/**
* Fetches the open,closed and upcoming notification count for the given instance.
*
* @param instanceId id of the instance
*
* @return list of assets with open,closed and upcoming count.
* @throws DataException when there is an error while fetching data
*/
public List<Map<String, Object>> getNotificationSummary(String instanceId) throws DataException;
/**
* Fetches the total count of the notification from the list passed.
*
* @param sevList list of assets with open,closed and upcoming count
*
* @return count of total notifications.
* @throws DataException when there is an error while fetching data
*/
public String getNotificationSummaryTotal(List<Map<String, Object>> sevList) throws DataException;
/**
* Saves the config details for the given resourceId.
*
* @param resourceId id of the resource
* @param configType type of the config
* @param config config of the asset
*
* @return 1 or any Integer.
*/
public Integer saveAssetConfig(String resourceId, String configType, String config);
/**
* Fetches the config details for the given resourceId and config type.
*
* @param resourceId id of the resource
* @param configType type of the config
*
* @return config details as string.
*/
public String retrieveAssetConfig(String resourceId, String configType);
/**
* Fetches the creator details for the given resourceId.
*
* @param resourceId id of the resource
*
* @return created by, creation date and email.
* @throws DataException when there is an error while fetching data
*/
public Map<String, Object> getEc2CreatorDetail(String resourceId) throws DataException;
/**
* Fetches the notification details of the instanceId.
*
* @param instanceId id of the instance
* @param filter any filter
* @param searchText searchText is used to match any text you are looking for
*
* @return list of notification details.
* @throws DataException when there is an error while fetching data
*/
public List<Map<String, Object>> getNotificationDetails(String instanceId, Map<String, String> filter,
String searchText) throws DataException;
/**
* Fetches the qualys details of the resourceId.
*
* @param resourceId id of the resource
*
* @return list of qualys details.
* @throws DataException when there is an error while fetching data
*/
public List<Map<String, Object>> getResourceQualysDetail(String resourceId) throws DataException;
/**
* Fetches the AD group details of the resourceId for the given asset group.
*
* @param ag name of the asset group
* @param resourceId id of the resource
*
* @return list of AD group details.
* @throws DataException when there is an error while fetching data
*/
public List<Map<String, String>> getAdGroupsDetail(String ag, String resourceId) throws DataException;
/**
* Fetches the average last week cost and total cost of the ec2 instance.
*
* @param resourceId id of the resource
*
* @return average last week cost and total cost of ec2.
* @throws DataException when there is an error while fetching data
*/
public Map<String, Object> getEC2AvgAndTotalCost(String resourceId) throws DataException;
/**
* Updates the asset details.
*
* @param assetGroup name of the asset group
* @param targettype target type to be updated
* @param resources resources that needs to updated
* @param updatedBy user id of the user
* @param updates the values with which the resources needs to be updated.
*
* @return integer count of rows updated.
* @throws DataException when there is an error while fetching data
*/
public int updateAsset(String assetGroup, String targettype, Map<String, Object> resources, String updatedBy,
List<Map<String, Object>> updates) throws DataException;
/**
* Fetches all the asset details for the given asset group.
*
* @param assetGroup name of the asset group
* @param filter application,environment,resourceType as optional filters
* @param from for pagination
* @param size for pagination
* @param searchText is used to match any text you are looking for
*
* @return list of complete asset details.
*/
public List<Map<String, Object>> getAssetLists(String assetGroup, Map<String, String> filter, int from, int size,
String searchText);
/**
* Fetches the list of fields that can be edited for the given resource type.
*
* @param resourceType type of the resource
*
* @return ResponseWithFieldsByTargetType has list of editable fields and target type
*/
public ResponseWithFieldsByTargetType getEditFieldsByTargetType(String resourceType);
/**
* Fetches the total count of the documents for the index and type.
*
* @param index ES index
* @param type ES type
*
* @return count of docs
*/
public long getTotalCountForListingAsset(String index, String type);
/**
* Fetches the created date for the give resourceId.
*
* @param resourceId id of the resource
* @param resourceType type of the resource
*
* @return created date as string
*/
public String getResourceCreatedDate(String resourceId, String resourceType);
/**
* Fetches the data type info maintained in RDS for the given resourceId.
*
* @param resourceId id of the resource
*
* @return list of data type info
* @throws ServiceException when the datatype is not maintained in RDS
*/
public List<Map<String, Object>> getDataTypeInfoByTargetType(String resourceId) throws ServiceException;
}
| 34,864
|
https://github.com/sunshinex/jpuppeteer/blob/master/src/main/java/jpuppeteer/cdp/client/entity/dom/ResolveNodeRequest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
jpuppeteer
|
sunshinex
|
Java
|
Code
| 108
| 279
|
package jpuppeteer.cdp.client.entity.dom;
/**
*/
public class ResolveNodeRequest {
/**
* Id of the node to resolve.
*/
public final Integer nodeId;
/**
* Backend identifier of the node to resolve.
*/
public final Integer backendNodeId;
/**
* Symbolic group name that can be used to release multiple objects.
*/
public final String objectGroup;
/**
* Execution context in which to resolve the node.
*/
public final Integer executionContextId;
public ResolveNodeRequest(Integer nodeId, Integer backendNodeId, String objectGroup, Integer executionContextId) {
this.nodeId = nodeId;
this.backendNodeId = backendNodeId;
this.objectGroup = objectGroup;
this.executionContextId = executionContextId;
}
public ResolveNodeRequest() {
this.nodeId = null;
this.backendNodeId = null;
this.objectGroup = null;
this.executionContextId = null;
}
}
| 48,551
|
https://github.com/issyzac/fhircore/blob/master/android/engine/src/main/java/org/smartregister/fhircore/engine/util/DateUtils.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
fhircore
|
issyzac
|
Kotlin
|
Code
| 230
| 625
|
/*
* Copyright 2021 Ona Systems, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartregister.fhircore.engine.util
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import org.hl7.fhir.r4.model.DateTimeType
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.DateTimeFormatter
object DateUtils {
private var simpleDateFormat = SimpleDateFormat("MM-dd-yyyy", Locale.getDefault())
fun addDays(
initialDate: String,
daysToAdd: Int = 0,
returnDateFormat: String = "M-d-Y",
dateTimeFormat: String? = null
): String {
val fmt: DateTimeFormatter = DateTimeFormat.forPattern(returnDateFormat)
val date: DateTime =
if (dateTimeFormat == null) DateTime.parse(initialDate)
else DateTime.parse(initialDate, DateTimeFormat.forPattern(dateTimeFormat))
return date.plusDays(daysToAdd).toString(fmt)
}
fun hasPastDays(initialDate: DateTimeType, days: Int = 0): Boolean {
val copy = initialDate.copy()
copy.add(Calendar.DATE, days)
return copy.after(DateTimeType.now())
}
fun simpleDateFormat(pattern: String = "hh:mm aa, MMM d") =
SimpleDateFormat(pattern, Locale.getDefault())
fun Date.makeItReadable(): String = simpleDateFormat.format(this)
fun String.getDate(formatNeeded: String): Date {
val format = SimpleDateFormat(formatNeeded)
var date = Date()
try {
date = format.parse(this)
println(date)
} catch (e: ParseException) {
e.printStackTrace()
}
return date
}
}
| 38,016
|
https://github.com/ConnectionMaster/Umbraco-CMS/blob/master/src/Umbraco.Web/umbraco.presentation/umbraco/create/PartialViewTasks.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,013
|
Umbraco-CMS
|
ConnectionMaster
|
C#
|
Code
| 290
| 999
|
using System.IO;
using System.Web;
using Umbraco.Core.CodeAnnotations;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Web.Mvc;
using Umbraco.Web.UI;
using umbraco.BasePages;
using Umbraco.Core;
using umbraco.BusinessLogic;
namespace umbraco
{
/// <summary>
/// The UI 'tasks' for the create dialog and delete processes
/// </summary>
[UmbracoWillObsolete("http://issues.umbraco.org/issue/U4-1373", "This will one day be removed when we overhaul the create process")]
public class PartialViewTasks : LegacyDialogTask
{
protected virtual string EditViewFile
{
get { return "Settings/Views/EditView.aspx"; }
}
protected string BasePath
{
get { return SystemDirectories.MvcViews + "/" + ParentFolderName.EnsureEndsWith('/'); }
}
protected virtual string ParentFolderName
{
get { return "Partials"; }
}
public override bool PerformSave()
{
var pipesIndex = Alias.IndexOf("|||", System.StringComparison.Ordinal);
var template = Alias.Substring(0, pipesIndex).Trim();
var fileName = Alias.Substring(pipesIndex + 3, Alias.Length - pipesIndex - 3) + ".cshtml";
var fullFilePath = IOHelper.MapPath(BasePath + fileName);
//return the link to edit the file if it already exists
if (File.Exists(fullFilePath))
{
_returnUrl = string.Format(EditViewFile + "?file={0}", HttpUtility.UrlEncode(ParentFolderName.EnsureEndsWith('/') + fileName));
return true;
}
//create the file
using (var sw = File.CreateText(fullFilePath))
{
using (var templateFile = File.OpenText(IOHelper.MapPath(SystemDirectories.Umbraco + "/PartialViews/Templates/" + template)))
{
var templateContent = templateFile.ReadToEnd();
sw.Write(templateContent);
}
}
// Create macro?
if (ParentID == 1)
{
var name = fileName
.Substring(0, (fileName.LastIndexOf('.') + 1)).Trim('.')
.SplitPascalCasing().ToFirstUpperInvariant();
var m = cms.businesslogic.macro.Macro.MakeNew(name);
m.ScriptingFile = BasePath + fileName;
m.Save();
}
_returnUrl = string.Format(EditViewFile + "?file={0}", HttpUtility.UrlEncode(ParentFolderName.EnsureEndsWith('/') + fileName));
return true;
}
protected virtual void WriteTemplateHeader(StreamWriter sw)
{
//write out the template header
sw.Write("@inherits ");
sw.Write(typeof(UmbracoTemplatePage).FullName.TrimEnd("`1"));
}
public override bool PerformDelete()
{
var path = IOHelper.MapPath(BasePath + Alias.TrimStart('/'));
if (File.Exists(path))
File.Delete(path);
else if (Directory.Exists(path))
Directory.Delete(path, true);
LogHelper.Info<PartialViewTasks>(string.Format("{0} Deleted by user {1}", Alias, UmbracoEnsuredPage.CurrentUser.Id));
return true;
}
private string _returnUrl = "";
public override string ReturnUrl
{
get { return _returnUrl; }
}
public override string AssignedApp
{
get { return DefaultApps.settings.ToString(); }
}
}
}
| 24,742
|
https://github.com/Rami-Majdoub/bagel/blob/master/core/src/ru/icarumbas/bagel/engine/components/other/OpenComponent.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
bagel
|
Rami-Majdoub
|
Kotlin
|
Code
| 17
| 58
|
package ru.icarumbas.bagel.engine.components.other
import com.badlogic.ashley.core.Component
class OpenComponent() : Component{
var isCollidingWithPlayer = false
var opening = false
}
| 49,039
|
https://github.com/RaulV10/Proyecto-Multicapa/blob/master/app/Drink.php
|
Github Open Source
|
Open Source
|
MIT
| null |
Proyecto-Multicapa
|
RaulV10
|
PHP
|
Code
| 55
| 202
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Drink extends Model
{
protected $guardable = [];
public function saveDrink($data) {
$this->name = $data['name'];
$this->description = $data['description'];
$this->price = $data['price'];
$this->menu_id = $data['menu_id'];
$this->save();
return 1;
}
public function updateDrink($data) {
$drink = $this->find($data['id']);
$drink->name = $data['name'];
$drink->description = $data['description'];
$drink->price = $data['price'];
$drink->save();
return 1;
}
}
| 41,866
|
https://github.com/alldatacenter/alldata/blob/master/dts/bitsail/bitsail-base/src/main/java/com/bytedance/bitsail/base/messenger/checker/LowVolumeTestChecker.java
|
Github Open Source
|
Open Source
|
Apache-2.0, BSD-3-Clause, MIT
| 2,023
|
alldata
|
alldatacenter
|
Java
|
Code
| 287
| 636
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bytedance.bitsail.base.messenger.checker;
import com.bytedance.bitsail.common.configuration.BitSailConfiguration;
import com.bytedance.bitsail.common.option.CommonOptions;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import java.io.Serializable;
import java.util.Arrays;
/**
* test job in low volume data mode
*/
@Slf4j
public class LowVolumeTestChecker implements Serializable {
private final long threshold;
public LowVolumeTestChecker(BitSailConfiguration configuration) {
this.threshold = configuration.get(CommonOptions.LOW_VOLUME_TEST_COUNT_THRESHOLD);
log.info("Low Volume test is {}, threshold: {}", (threshold > 0 ? "enabled" : "disabled"), threshold);
}
/**
* check if records handled is enough
*/
public boolean check(long successRecords, long failRecords) {
if (threshold <= 0) {
return false;
}
val totalCount = successRecords + failRecords;
val result = totalCount >= threshold;
if (result) {
log.info("Reached threshold of low volume test, total count {}, threshold {}", totalCount, threshold);
}
return result;
}
/**
* return at most 100 InputSplits in low volume data mode
*/
public <T> T[] restrictSplitsNumber(T[] splits) {
if (threshold > 0) {
final int restrictedLength = Math.min(splits.length, 100);
log.info("Restricting input splits length to {}", restrictedLength);
return Arrays.copyOf(splits, restrictedLength);
}
return splits;
}
}
| 38,737
|
https://github.com/TobiasLudwig/boost.simd/blob/master/test/api/algorithm/copy_n.cpp
|
Github Open Source
|
Open Source
|
BSL-1.0
| 2,021
|
boost.simd
|
TobiasLudwig
|
C++
|
Code
| 83
| 318
|
//==================================================================================================
/*
Copyright 2017 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy_n at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#include <boost/simd/algorithm/copy_n.hpp>
#include <numeric>
#include <vector>
#include <simd_test.hpp>
using namespace boost::simd;
using namespace boost::alignment;
STF_CASE_TPL( "Check unary simd::copy_n", STF_NUMERIC_TYPES )
{
static const int N = pack<T>::static_size;
std::vector<T> values(2*N+1), ref(2*N+3), out(2*N+3);
std::iota(values.begin(), values.end(),T(1));
std::copy(values.begin(), values.begin()+N, ref.begin());
// verify we stopped where we should
STF_EQUAL ( (boost::simd::copy_n(values.data(), N, out.data()))
, out.data()+N
);
// verify values
STF_EQUAL( out, ref );
}
| 32,499
|
https://github.com/juozasg/suis4j/blob/master/src/com/eviware/soapui/impl/support/definition/support/XmlSchemaBasedInterfaceDefinition.java
|
Github Open Source
|
Open Source
|
MIT
| null |
suis4j
|
juozasg
|
Java
|
Code
| 240
| 724
|
/*
* SoapUI, Copyright (C) 2004-2016 SmartBear Software
*
* Licensed under the EUPL, Version 1.1 or - as soon as they will be approved by the European Commission - subsequen
* versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl
*
* Unless required by applicable law or agreed to in writing, software distributed under the Licence is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the Licence for the specific language governing permissions and limitations
* under the Licence.
*/
package com.eviware.soapui.impl.support.definition.support;
import com.eviware.soapui.impl.support.AbstractInterface;
import com.eviware.soapui.impl.support.definition.DefinitionLoader;
import com.eviware.soapui.impl.wsdl.support.xsd.SchemaException;
import com.eviware.soapui.impl.wsdl.support.xsd.SchemaUtils;
import org.apache.xmlbeans.SchemaType;
import org.apache.xmlbeans.SchemaTypeLoader;
import org.apache.xmlbeans.SchemaTypeSystem;
import org.apache.xmlbeans.XmlBeans;
import javax.xml.namespace.QName;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public abstract class XmlSchemaBasedInterfaceDefinition<T extends AbstractInterface<?>> extends
AbstractInterfaceDefinition<T> {
private SchemaTypeSystem schemaTypes;
private SchemaTypeLoader schemaTypeLoader;
public XmlSchemaBasedInterfaceDefinition(T iface) {
super(iface);
}
public SchemaTypeLoader getSchemaTypeLoader() {
return schemaTypeLoader;
}
public SchemaTypeSystem getSchemaTypeSystem() {
return schemaTypes;
}
public boolean hasSchemaTypes() {
return schemaTypes != null;
}
public Collection<String> getDefinedNamespaces() throws Exception {
Set<String> namespaces = new HashSet<String>();
SchemaTypeSystem schemaTypes = getSchemaTypeSystem();
if (schemaTypes != null) {
namespaces.addAll(SchemaUtils.extractNamespaces(getSchemaTypeSystem(), true));
}
namespaces.add(getTargetNamespace());
return namespaces;
}
public SchemaType findType(QName typeName) {
return getSchemaTypeLoader().findType(typeName);
}
public void loadSchemaTypes(DefinitionLoader loader) throws SchemaException {
schemaTypes = SchemaUtils.loadSchemaTypes(loader.getBaseURI(), loader);
schemaTypeLoader = XmlBeans.typeLoaderUnion(new SchemaTypeLoader[]{schemaTypes,
XmlBeans.getBuiltinTypeSystem()});
}
}
| 10,756
|
https://github.com/nathan-lai234/Tierator/blob/master/backend/routes/dummyQuery.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Tierator
|
nathan-lai234
|
JavaScript
|
Code
| 77
| 213
|
const express = require("express");
const router = express.Router();
const pool = require("../dev/databaseDetails");
const getUsers = (request, response) => {
pool.query("SELECT * FROM dummy", (error, results) => {
if (error) {
console.log(error);
throw error;
}
response.status(200).json(results.rows);
});
};
const getUserById = (request, response) => {
const id = parseInt(request.params.id);
pool.query("SELECT * FROM dummy WHERE id = $1", [id], (error, results) => {
if (error) {
console.log(error);
throw error;
}
response.status(200).json(results.rows);
});
};
module.exports = { getUsers, getUserById };
| 26,630
|
https://github.com/prostickman/retrofit-spring-boot-starter/blob/master/src/main/java/com/github/lianjiatech/retrofit/spring/boot/interceptor/LogLevel.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
retrofit-spring-boot-starter
|
prostickman
|
Java
|
Code
| 22
| 84
|
package com.github.lianjiatech.retrofit.spring.boot.interceptor;
/**
* @author 陈添明
*/
public enum LogLevel {
/**
* No config
*/
NULL,
ERROR,
WARN,
INFO,
DEBUG,
}
| 39,124
|
https://github.com/OptimusKe/LoveLiveSimulator/blob/master/LoveLiveSimulator/Component/LLBeatCircle.m
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
LoveLiveSimulator
|
OptimusKe
|
Objective-C
|
Code
| 228
| 764
|
//
// LLBeatCircle.m
// LoveLiveSimulator
//
// Created by OptimusKe on 2014/10/11.
// Copyright (c) 2014年 KerKer. All rights reserved.
//
#import "LLBeatCircle.h"
#import "LLBeatManager.h"
@interface LLBeatCircle ()
@property (nonatomic) UIColor *borderColor;
@property (nonatomic, assign) int index;
@property (nonatomic, assign) CGPoint startValue, endValue;
@property (nonatomic, assign) CGFloat rate, totaltime, scaleStartValue;
@property (nonatomic, assign) CFTimeInterval startTime;
@property (nonatomic, strong) CADisplayLink *link;
@property (nonatomic, assign) LLBeatManager *beatManager;
@end
@implementation LLBeatCircle
- (id)initWithFrame:(CGRect)frame circle:(UIColor *)borderColor index:(int)index launcher:(LLBeatManager *)launcher {
self = [super initWithFrame:frame];
if (self) {
self.index = index;
self.borderColor = borderColor;
self.beatManager = launcher;
self.userInteractionEnabled = NO;
[self draw];
}
return self;
}
- (void)draw {
CALayer *layer = self.layer;
layer.borderWidth = 2.0;
layer.borderColor = self.borderColor.CGColor;
layer.cornerRadius = CGRectGetHeight(self.frame) / 2;
layer.masksToBounds = YES;
}
#pragma mark - animation
- (void)animationFrom:(CGPoint)fromValue to:(CGPoint)toValue withDuration:(NSTimeInterval)duration {
self.startValue = fromValue;
self.endValue = toValue;
self.startTime = CACurrentMediaTime();
self.totaltime = duration;
self.scaleStartValue = 0.3;
self.transform = CGAffineTransformMakeScale(self.scaleStartValue, self.scaleStartValue);
}
- (void)update:(CADisplayLink *)displayLink {
float dt = ([displayLink timestamp] - self.startTime) / self.totaltime;
self.dTime = dt;
//move
CGFloat dx = (self.endValue.x - self.startValue.x) * displayLink.duration / self.totaltime;
CGFloat dy = (self.endValue.y - self.startValue.y) * displayLink.duration / self.totaltime;
CGPoint dPoint = CGPointMake(self.center.x + dx, self.center.y + dy);
self.center = dPoint;
//scale
CGFloat dScaleX = self.scaleStartValue + (1 - self.scaleStartValue) * dt;
CGFloat dScaleY = self.scaleStartValue + (1 - self.scaleStartValue) * dt;
self.transform = CGAffineTransformMakeScale(dScaleX, dScaleY);
}
@end
| 45,449
|
https://github.com/Ruke45/DManagement/blob/master/DSCMS/DSCMS/Views/Certificate/EditCertificateRequest.aspx.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
DManagement
|
Ruke45
|
C#
|
Code
| 2,689
| 10,412
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DCISDBManager.objLib.Certificate;
using DCISDBManager.trnLib.CertificateManagement;
using DCISDBManager.trnLib.MasterDataManagement;
using DCISDBManager.trnLib.Utility;
using System.IO;
using DCISDBManager.objLib.Usr;
using DCISDBManager.trnLib.CheckAuth;
namespace DSCMS
{
public partial class EditCertificateRequest : System.Web.UI.Page
{
UserSession userSession;
CertificateRequestManager Crm = new CertificateRequestManager();
List<CertificateRequestDetail> ReDe = new List<CertificateRequestDetail>();
List<SupportingDocUpload> SupList = new List<SupportingDocUpload>();
CertificateRequestDetail CRD = new CertificateRequestDetail();
CertificateRequestHeader Crh = new CertificateRequestHeader();
CheckAuthManager authorized;
string HSCODEHAS = System.Configuration.ConfigurationManager.AppSettings["HSCODEHAS"];
string GOLOBALTMP = System.Configuration.ConfigurationManager.AppSettings["GOLOBALTMP"];
string MASSACTIVE = System.Configuration.ConfigurationManager.AppSettings["MASSACTIVE"];
string NINDROTMP = System.Configuration.ConfigurationManager.AppSettings["NINDROTMP"];
string ROWWITHOUTHS = System.Configuration.ConfigurationManager.AppSettings["ROWWITHOUTHS"];
string ROWWITH_HS = System.Configuration.ConfigurationManager.AppSettings["ROWWITH_HS"];
string COLUMNWITHOUTHS = System.Configuration.ConfigurationManager.AppSettings["COLUMNWITHOUTHS"];
string COLUMNWITHOUTHS2 = System.Configuration.ConfigurationManager.AppSettings["COLUMNWITHOUTHS2"];
protected void Page_Load(object sender, EventArgs e)
{
userSession = new UserSession();
//this.Form.Enctype = "multipart/form-data";
authorized = new CheckAuthManager();
if (!authorized.IsUserGroupAuthorised(userSession.User_Group, "CREQE"))
{
Response.Redirect("~/Views/Home/Forbidden.aspx");
}
if (!IsPostBack)
{
string id = Request.QueryString["ReqstID"];
if (Crm.checkCertificateEditRequest(userSession.Customer_ID, id))
{
//getPackageType();
getCountries();
LoadCertificateRequest();
if (userSession.Template_ID.Equals(ROWWITHOUTHS))
{
divOtherComments.Visible = false;
diveRemarkGlobl.Visible = false;
DivNormal.Visible = false;
HSDetails.Visible = false;
}
else if (userSession.Template_ID.Equals(ROWWITH_HS))
{
divOtherComments.Visible = false;
diveRemarkGlobl.Visible = false;
DivNormal.Visible = false;
}
else if (userSession.Template_ID.Equals(COLUMNWITHOUTHS))
{
txtHScode.Visible = false;
lblHScode.Visible = false;
divOtherComments.Visible = false;
diveRemarkGlobl.Visible = false;
ROWBase.Visible = false;
}
else if (userSession.Template_ID.Equals(COLUMNWITHOUTHS2))
{
txtHScode.Visible = false;
lblHScode.Visible = false;
divOtherComments.Visible = false;
diveRemarkGlobl.Visible = false;
ROWBase.Visible = false;
}
else if (userSession.Template_ID.Equals(NINDROTMP))
{
divPOD.Visible = false;
divPODE.Visible = false;
txtPortDischrg.Visible = false;
txtPlcofDelivry.Visible = false;
diveRemarkGlobl.Visible = false;
ROWBase.Visible = false;
}
else if (userSession.Template_ID.Equals(MASSACTIVE))
{
txtHScode.Visible = false;
lblHScode.Visible = false;
divPOD.Visible = false;
divPODE.Visible = false;
txtPortDischrg.Visible = false;
txtPlcofDelivry.Visible = false;
diveRemarkGlobl.Visible = false;
ROWBase.Visible = false;
}
else if (userSession.Template_ID.Equals(HSCODEHAS))
{
divOtherComments.Visible = false;
diveRemarkGlobl.Visible = false;
ROWBase.Visible = false;
}
else
{
divOtherComments.Visible = false;
ROWBase.Visible = false;
}
}
else
{
Response.Redirect("~/Views/Home/Forbidden.aspx");
}
}
}
//protected void getPackageType()
//{
// try
// {
// PackageTypeManager Pkm = new PackageTypeManager();//Here
// drpPakgType.DataSource = Pkm.getPackageTypeList("%").Packageresultset;
// drpPakgType.DataTextField = "PackageDescription";
// drpPakgType.DataValueField = "PackageType";
// drpPakgType.DataBind();
// }
// catch (Exception Ex)
// {
// ErrorLog.LogError(Ex);
// }
//}
protected void getCountries()
{
try
{
CountryManager cm = new CountryManager();
drpCountry.DataSource = cm.getCountry("%").Countryresultset;
drpCountry.DataTextField = "CountryName";
drpCountry.DataValueField = "CountryCode";
drpCountry.DataBind();
}
catch (Exception Ex)
{
ErrorLog.LogError(Ex);
}
// drpCountry.SelectedIndex = drpCountry.Items.IndexOf(drpCountry.Items.FindByValue("SL"));
}
private void getSupportingDOC(string id, CertificateRequestManager Crm)
{
try
{
SupList = Crm.getSupportingDOCfRequest(id);
gvSupportingDOc.DataSource = SupList;
gvSupportingDOc.DataBind();
}
catch (Exception Ex)
{
ErrorLog.LogError(Ex);
}
}
private void getNotUploadedSupportingDOC(string id, CertificateRequestManager Crm)
{
try
{
gvNotUploadedDOC.DataSource = Crm.getNotUploadedSupportingDOCfRequest(id).Not_Uploaded_SD;
gvNotUploadedDOC.DataBind();
}
catch (Exception Ex)
{
ErrorLog.LogError(Ex);
}
}
protected void LoadCertificateRequest()
{
try
{
string id = Request.QueryString["ReqstID"];
Crh = Crm.getRequestByID(id);
txtConsignee.Text = Crh.Consignee1.Replace("<br />", "\r\n");
txtDate.Text = Crh.InvoiceDate1.ToString("yyyy/MM/dd");
txtExporter.Text = Crh.Consignor1.Replace("<br />", "\r\n"); ;
txtInvoNo.Text = Crh.InvoiceNo1;
txtInvoVal.Text = Crh.TotalInvoiceValue1.ToString();
txtPlcofDelivry.Text = Crh.PlaceOfDelivery1;
txtPortDischrg.Text = Crh.PortOfDischarge1;
txtPortLoading.Text = Crh.LoadingPort1;
txtTotQunatity.Text = Crh.TotalQuantity1;
txtVessel.Text = Crh.Vessel1;
drpCountry.SelectedIndex = drpCountry.Items.IndexOf(drpCountry.Items.FindByValue(Crh.CountryCode1));
txtOtherComments.Text = Crh.OtherComments1;
txtOtherDetails.Text = Crh.OtherDetails1;
chckSealRequired.Checked = Convert.ToBoolean(Crh.Seal_Required);
if (userSession.Template_ID.Equals(ROWWITH_HS) || userSession.Template_ID.Equals(ROWWITHOUTHS))
{
CRD = Crm.getROWbasedCertificateRequestDetails(id);
txtSeqNo.Text = Convert.ToString(CRD.SeqNo1);
txtGoodDetails.Text = CRD.Good_Details.Replace("<br />", "\r\n");
txtHSDetails.Text = CRD.HSCode_Details.Replace("<br />", "\r\n");
txtQuantityDetails.Text = CRD.Quantity_Details.Replace("<br />", "\r\n");
}
else
{
getItemDetails(id, Crm);
}
getSupportingDOC(id, Crm);
getNotUploadedSupportingDOC(id, Crm);
}
catch (Exception Ex)
{
ErrorLog.LogError(Ex);
}
}
private void getItemDetails(string id, CertificateRequestManager Crm)
{
try
{
ReDe = Crm.getReqDetailByReqID(id,false);
gvItemDetails.DataSource = ReDe;
gvItemDetails.DataBind();
}
catch (Exception Ex)
{
ErrorLog.LogError(Ex);
}
}
protected void linkEditItem_Click(object sender, EventArgs e)
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
Label lblSeqNo = (Label)row.FindControl("lblSeqNo");
Label lblPackageType = (Label)row.FindControl("lblPackageType");
Label lblSummary = (Label)row.FindControl("lblSummary");
txtGoodItem.Text = row.Cells[0].Text;
txtShippingMark.Text = row.Cells[1].Text;
//drpPakgType.SelectedIndex = drpPakgType.Items.IndexOf(drpPakgType.Items.FindByValue(lblPackageType.Text));//Here
drpPakgType.Text = lblPackageType.Text;
txtSummary.Text = lblSummary.Text;// Replace("<br />", "\n");
txtQuntity.Text = row.Cells[4].Text;
if (row.Cells[5].Text == " ")
{
txtHScode.Text = "";
}
else
{
txtHScode.Text = row.Cells[5].Text;
}
txtSequence.Text = lblSeqNo.Text;
}
mp1.Show();
}
protected void btnUpdateCertificate_Click(object sender, EventArgs e)
{
if (checkGridView() != 0)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>IF the Supporting Document Needs to Signed Please Upload a '.pdf' File</div>";
ErrorMessage.InnerHtml = qu;
return;
}
if (checkNotUploadedGridView() != 0)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Please Upload the Mandatory Supporting Documents.</div>";
ErrorMessage.InnerHtml = qu;
return;
}
if (txtConsignee.Text == "" || txtExporter.Text == "" || txtDate.Text == "" || txtInvoNo.Text == "" || txtVessel.Text == "")
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Please Fill out All the required Fields before submitting the Request</div>";
ErrorMessage.InnerHtml = qu;
return;
}
if (txtPortLoading.Text == "")//|| txtInvoVal.Text == "" || txtTotQunatity.Text == ""
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Please Fill out All the required Fields before submitting the Request</div>";
ErrorMessage.InnerHtml = qu;
return;
}
if (txtPlcofDelivry.Visible == true)
{
if (txtPlcofDelivry.Text == "" || txtPortDischrg.Text == "")
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Please Fill All the Required Fields Before Submitting.";
qu += "</div>";
ErrorMessage.InnerHtml = qu;
return;
}
}
if (ROWBase.Visible == true)
{
if (txtQuantityDetails.Text == "" || txtGoodDetails.Text == "")
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Please Fill the Shipping Goods Details.";
qu += "</div>";
ErrorMessage.InnerHtml = qu;
return;
}
if (txtHSDetails.Visible == true && txtHSDetails.Text == "")
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Please Fill the HS Code Details.";
qu += "</div>";
ErrorMessage.InnerHtml = qu;
return;
}
}
try
{
Convert.ToDateTime(txtDate.Text);
}
catch (Exception ex)
{
ErrorLog.LogError(ex);
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Please Enter a Date in Invoice Date Text Box Ex: 2016/01/01</div>";
ErrorMessage.InnerHtml = qu;
return;
}
string RequestId = Request.QueryString["ReqstID"];
CertificateRequestHeader HeaderR = new CertificateRequestHeader();
HeaderR.RequestId1 = RequestId;
HeaderR.Consignee1 = txtConsignee.Text.Replace("\r\n", "<br />");
HeaderR.Consignor1 = txtExporter.Text.Replace("\r\n", "<br />");
HeaderR.CountryCode1 = drpCountry.SelectedValue.ToString();
HeaderR.CreatedBy1 = userSession.User_Id;
HeaderR.CustomerId1 = userSession.Customer_ID;
HeaderR.InvoiceDate1 = Convert.ToDateTime(txtDate.Text);
HeaderR.InvoiceNo1 = txtInvoNo.Text;
HeaderR.LoadingPort1 = txtPortLoading.Text;
HeaderR.PlaceOfDelivery1 = txtPlcofDelivry.Text;
HeaderR.PortOfDischarge1 = txtPortDischrg.Text;
//HeaderR.TemplateId1 = userSession.te;
HeaderR.TotalInvoiceValue1 = txtInvoVal.Text;
HeaderR.TotalQuantity1 = txtTotQunatity.Text;
HeaderR.Vessel1 = txtVessel.Text;
HeaderR.Status1 = "P";
HeaderR.OtherDetails1 = txtOtherDetails.Text;
HeaderR.OtherComments1 = txtOtherComments.Text;
HeaderR.Seal_Required = chckSealRequired.Checked.ToString();
bool resutl = false;
if (userSession.Template_ID.Equals(ROWWITH_HS) || userSession.Template_ID.Equals(ROWWITHOUTHS))
{
CertificateRequestDetail CRD = new CertificateRequestDetail();
CRD.Good_Details = txtGoodDetails.Text.Replace("\r\n", "<br />");
CRD.HSCode_Details = txtHSDetails.Text.Replace("\r\n", "<br />");
CRD.Quantity_Details = txtQuantityDetails.Text.Replace("\r\n", "<br />");
CRD.CreatedBy1 = userSession.User_Id;
CRD.SeqNo1 = Convert.ToInt64(txtSeqNo.Text);
resutl = Crm.updateCertificateRequest(HeaderR, CRD);
}
else
{
resutl = Crm.updateCertificateRequest(HeaderR, ReDe);
}
if (resutl)
{
foreach (GridViewRow row in gvSupportingDOc.Rows)
{
Label SeqNo = (Label)row.FindControl("lblseqid");
string d = SeqNo.Text;
//TextBox ename = (TextBox)row.FindControl("txtename");
//TextBox emid = (TextBox)row.FindControl("txtemid");
CheckBox chkSelect = (CheckBox)row.FindControl("chkSelect");
FileUpload fu = (FileUpload)row.FindControl("btnEditFileUpload");
bool sr = fu.HasFile;
string DirectoryPath = "~/Uploads/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("yyyy_MM_dd") + "/" + RequestId;
if (fu.HasFile)
{
if (!Directory.Exists(Server.MapPath(DirectoryPath)))
{
Directory.CreateDirectory(Server.MapPath(DirectoryPath));
}
string file = Path.Combine(Server.MapPath(DirectoryPath + "/"), fu.FileName.Replace(" ", "_"));
fu.SaveAs(file);
SupportingDocUpload objsup = new SupportingDocUpload();
objsup.Seq_No = Convert.ToInt64(SeqNo.Text);
objsup.Uploaded_By = userSession.User_Id;
objsup.Uploaded_Path = DirectoryPath + "/" + fu.FileName.Replace(" ", "_");
objsup.Document_Name = fu.FileName.Replace(" ", "_");
Crm.setUpdateSupportingDocumentFRequest(objsup);
}
if (chkSelect.Checked)
{
Crm.setUpdateSupportingDocumenSignature(Convert.ToInt64(SeqNo.Text), chkSelect.Checked, "Certification");
}
else
{
Crm.setUpdateSupportingDocumenSignature(Convert.ToInt64(SeqNo.Text), chkSelect.Checked, "");
}
}
LoadCertificateRequest();
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-success\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += "Certificate Request Edit Successfull.</div>";
ErrorMessage.InnerHtml = qu;
}
}
protected void btnAddItem_Click(object sender, EventArgs e)
{
lblError.Text = string.Empty;
if (txtSequence.Text.Equals("A"))
{
CRD.RequestId1 = Request.QueryString["ReqstID"];
CRD.GoodItem1 = txtGoodItem.Text;
CRD.HSCode1 = txtHScode.Text;
CRD.PackageType1 = drpPakgType.Text;//Here
CRD.Quantity1 = txtQuntity.Text;
CRD.SummaryDesc1 = txtSummary.Text;
CRD.ShippingMark1 = txtShippingMark.Text;
CRD.CreatedBy1 = userSession.User_Id;
Crm.setCertificateRequestDetails(CRD);
LoadCertificateRequest();
}
else
{
if (userSession.Template_ID == ROWWITHOUTHS || userSession.Template_ID == COLUMNWITHOUTHS || userSession.Template_ID == COLUMNWITHOUTHS2 || userSession.Template_ID == MASSACTIVE)
{
if (txtSummary.Text == "")
{
lblError.Text = "Please Fill out the Summary field";
mp1.Show();
return;
}
}
else
{
if (txtSummary.Text == "")//|| txtHScode.Text == ""
{
lblError.Text = "Please Fill out the Summary field";
mp1.Show();
return;
}
}
CertificateRequestDetail CRd = new CertificateRequestDetail();
CRd.GoodItem1 = txtGoodItem.Text;
CRd.PackageType1 = drpPakgType.Text;//here
CRd.Quantity1 = txtQuntity.Text;
CRd.ShippingMark1 = txtShippingMark.Text;
CRd.SummaryDesc1 = txtSummary.Text;
CRd.HSCode1 = txtHScode.Text;
CRd.SeqNo1 = Convert.ToInt64(txtSequence.Text);
Crm.setUpdateCertificateRequestDetails(CRd);
this.LoadCertificateRequest();
}
}
protected void linkDownload_Click(object sender, EventArgs e)
{
try
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
Label lblseqid = (Label)row.FindControl("lblseqid");
Label Document_Name = (Label)row.FindControl("lblDocument_Name");
Label Uploaded_Path = (Label)row.FindControl("lblUploadP");
Response.ContentType = "APPLICATION/OCTET-STREAM";
String Header = "Attachment; Filename=" + Document_Name.Text;
Response.AppendHeader("Content-Disposition", Header);
System.IO.FileInfo Dfile = new System.IO.FileInfo(Server.MapPath(Uploaded_Path.Text));
Response.WriteFile(Dfile.FullName);
//Don't forget to add the following line
Response.End();
}
}
catch (Exception Ex)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Unable To Download The File....</div>";
ErrorMessage.InnerHtml = qu;
ErrorLog.LogError(Ex);
}
}
private int checkGridView()
{
int count = 0;
foreach (GridViewRow row in gvSupportingDOc.Rows)
{
Label lblUploadP = (Label)row.FindControl("lblUploadP");
CheckBox IsSign = (CheckBox)row.FindControl("chkSelect");
FileUpload fu = (FileUpload)row.FindControl("btnEditFileUpload");
string UpPath = Server.MapPath(lblUploadP.Text);
if (fu.HasFile == false)
{
if (IsSign.Checked && !Path.GetExtension(UpPath).ToLower().Equals(".pdf"))
{
count++;
}
}
else
{
string FuPath = System.IO.Path.GetExtension(fu.PostedFile.FileName);
if (IsSign.Checked && !Path.GetExtension(FuPath).ToLower().Equals(".pdf"))
{
count++;
}
}
}
return count;
}
private int checkNotUploadedGridView()
{
int count = 0;
foreach (GridViewRow row in gvNotUploadedDOC.Rows)
{
Label DocID = (Label)row.FindControl("SupDOCID");
Label isMandotory = (Label)row.FindControl("lblIsmandatory");
FileUpload fu = (FileUpload)row.FindControl("btnFileUpload");
if (isMandotory.Text.ToUpper() == "Y")
{
count++;
}
}
return count;
}
private int isPDF()
{
int count = 0;
foreach (GridViewRow row in gvNotUploadedDOC.Rows)
{
CheckBox chkRow = (CheckBox)row.FindControl("chkRow2");
FileUpload fu = (FileUpload)row.FindControl("btnFileUpload");
if (chkRow.Checked && fu.HasFile)
{
string extension = System.IO.Path.GetExtension(fu.PostedFile.FileName);
if (extension.ToLower() != ".pdf")
{
count++;
}
}
}
return count;
}
protected void linkRemoveItem_Click(object sender, EventArgs e)
{
if (ReDe.Count == 1)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Cannot Remove ! </strong> There is only one item in the Request</div>";
ErrorMessage.InnerHtml = qu;
return;
}
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
Int64 Seq = Convert.ToInt64(row.Cells[6].Text);
Crm.setDELETECertificatRequestDetails(Seq);
}
LoadCertificateRequest();
}
protected void btnSendForApproval_Click(object sender, EventArgs e)
{
if (checkGridView() != 0)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>IF the Supporting Document Needs to Signed Please Upload a '.pdf' File</div>";
ErrorMessage.InnerHtml = qu;
return;
}
if (checkNotUploadedGridView() != 0)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Please Upload the Mandatory Supporting Documents.</div>";
ErrorMessage.InnerHtml = qu;
return;
}
if (txtConsignee.Text == "" || txtExporter.Text == "" || txtDate.Text == "" || txtInvoNo.Text == "" || txtVessel.Text == "")
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Please Fill out All the required Fields before submitting the Request</div>";
ErrorMessage.InnerHtml = qu;
return;
}
if (txtPortLoading.Text == "")//|| txtInvoVal.Text == "" || txtTotQunatity.Text == ""
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Please Fill out All the required Fields before submitting the Request</div>";
ErrorMessage.InnerHtml = qu;
return;
}
if (txtPlcofDelivry.Visible == true)
{
if (txtPlcofDelivry.Text == "" || txtPortDischrg.Text == "")
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Please Fill All the Required Fields Before Submitting.";
qu += "</div>";
ErrorMessage.InnerHtml = qu;
return;
}
}
if (ROWBase.Visible == true)
{
if (txtQuantityDetails.Text == "" || txtGoodDetails.Text == "")
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Please Fill the Shipping Goods Details.";
qu += "</div>";
ErrorMessage.InnerHtml = qu;
return;
}
if (txtHSDetails.Visible == true && txtHSDetails.Text == "")
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Please Fill the HS Code Details.";
qu += "</div>";
ErrorMessage.InnerHtml = qu;
return;
}
}
try
{
Convert.ToDateTime(txtDate.Text);
}
catch (Exception ex)
{
ErrorLog.LogError(ex);
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Please Enter a Date in Invoice Date Text Box Ex: 2016/01/01</div>";
ErrorMessage.InnerHtml = qu;
return;
}
try
{
bool Created = false;
string Template = userSession.Template_ID.ToString();
LoadCertificateRequest();
string LogoPath = Server.MapPath("~/img/NCELOGO.PNG"); // NCE Certificate logo Image path
string DirectoryPath = "~/Documents/" + DateTime.Now.ToString("yyyy")
+ "/Web_Based_Certificates/" + DateTime.Now.ToString("yyyy_MM_dd")+"/" + Crh.RequestId1;
//Crh.Customer_Telephone = userSession.Telephone_;
//Crh.CustomerName1 = userSession.Customer_Name;
//DirectoryPath which will save the NOT singed PDF File as NOT_Signed.pdf in the given Path
if (!Directory.Exists(Server.MapPath(DirectoryPath)))
{
Directory.CreateDirectory(Server.MapPath(DirectoryPath));
}
/**PDF Cerator
* Parameters
* Certificate Reques Header Detail Object
* Certificate Request Item Details Object List
* Document Save Path
*
*/
if (Template.Equals(ROWWITH_HS))
{
PDFCreator.RowWithHSTemplate Certificate =
new PDFCreator.RowWithHSTemplate(Crh,
CRD, LogoPath,
Server.MapPath(DirectoryPath + "/" + Crh.RequestId1 + "_Sample_Cert.pdf"), "","");
Created = Certificate.CreateCertificate("");
}
else if (Template.Equals(ROWWITHOUTHS))
{
PDFCreator.RowWithoutHSTemplate Certificate =
new PDFCreator.RowWithoutHSTemplate(Crh,
CRD, LogoPath,
Server.MapPath(DirectoryPath + "/" + Crh.RequestId1 + "_Sample_Cert.pdf"), "", "");
Created = Certificate.CreateCertificate("");
}
else if (Template.Equals(GOLOBALTMP))
{
PDFCreator.OrientGlobalCertificateTemplate Certificate =
new PDFCreator.OrientGlobalCertificateTemplate(Crh,
ReDe, LogoPath,
Server.MapPath(DirectoryPath + "/" + Crh.RequestId1 + "_Sample_Cert.pdf"), "", "");
Created = Certificate.CreateCertificate("");
}
else if (Template.Equals(MASSACTIVE))
{
PDFCreator.MassActiveCertificateTemplate Certificate =
new PDFCreator.MassActiveCertificateTemplate(Crh,
ReDe, LogoPath,
Server.MapPath(DirectoryPath + "/" + Crh.RequestId1 + "_Sample_Cert.pdf"), "", "");
Created = Certificate.CreateCertificate("");
}
else if (Template.Equals(NINDROTMP))
{
PDFCreator.NidroCertificateTemplate Certificate =
new PDFCreator.NidroCertificateTemplate(Crh,
ReDe, LogoPath,
Server.MapPath(DirectoryPath + "/" + Crh.RequestId1 + "_Sample_Cert.pdf"), "", "");
Created = Certificate.CreateCertificate("");
}
else if (Template.Equals(COLUMNWITHOUTHS))
{
PDFCreator.ColumnWithoutHSTemplate Certificate =
new PDFCreator.ColumnWithoutHSTemplate(Crh,
ReDe, LogoPath,
Server.MapPath(DirectoryPath + "/" + Crh.RequestId1 + "_Sample_Cert.pdf"), "", "");
Created = Certificate.CreateCertificate("");
}
else if (Template.Equals(COLUMNWITHOUTHS2))
{
PDFCreator.ColumnWithoutHSTemplate Certificate =
new PDFCreator.ColumnWithoutHSTemplate(Crh,
ReDe, LogoPath,
Server.MapPath(DirectoryPath + "/" + Crh.RequestId1 + "_Sample_Cert.pdf"), "", "");
Created = Certificate.CreateCertificate("");
}
else
{
PDFCreator.ColumnWithHSTemplate Certificate =
new PDFCreator.ColumnWithHSTemplate(Crh,
ReDe, LogoPath,
Server.MapPath(DirectoryPath + "/" + Crh.RequestId1 + "_Sample_Cert.pdf"), "", "");
Created = Certificate.CreateCertificate("");
}
if (Created)
{
if (Crm.setWebBasedCertificateCreation(Crh.RequestId1,
DirectoryPath + "/" + Crh.RequestId1 + "_Sample_Cert.pdf",
Crh.RequestId1 + "_Sample_Cert.pdf"))
{
Crm.UpdateReqeustHeadStatus(Crh.RequestId1, "G");
}
}
Response.Redirect("~/Views/Certificate/PendingCertificateRequest.aspx");
Response.End();
}
catch (Exception Ex)
{
ErrorLog.LogError("Certificate Generate", Ex);
}
}
protected void btnAddNewItem_Click(object sender, EventArgs e)
{
Clear();
txtSequence.Text = "A";
mp1.Show();
}
protected void Clear()
{
txtGoodItem.Text = string.Empty;
txtShippingMark.Text = string.Empty;
drpPakgType.Text = string.Empty; //here
txtSummary.Text = string.Empty;
txtQuntity.Text = string.Empty;
txtHScode.Text = string.Empty; ;
txtSequence.Text = string.Empty;
}
protected void linkUploadSDOC_Click(object sender, EventArgs e)
{
if (isPDF() > 0)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>You must Upload a PDF document if needed to be Singed.</div>";
ErrorMessage.InnerHtml = qu;
return;
}
try
{
string Request_Ref_No = Request.QueryString["ReqstID"];
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
Label lblRequestID = (Label)row.FindControl("lblRequestID");
Label DocID = (Label)row.FindControl("SupDOCID");
FileUpload FileUploader = (FileUpload)row.FindControl("btnFileUpload");
CheckBox chkRow = (CheckBox)row.FindControl("chkRow2");
string DirectoryPath = "~/Uploads/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("yyyy_MM_dd") + "/" + Request_Ref_No;
if (FileUploader.HasFile)
{
if (!Directory.Exists(Server.MapPath(DirectoryPath)))
{
Directory.CreateDirectory(Server.MapPath(DirectoryPath));
}
string file = Path.Combine(Server.MapPath(DirectoryPath + "/"), FileUploader.FileName.Replace(" ", "_"));
FileUploader.SaveAs(file);
SupportingDocUpload objsup = new SupportingDocUpload();
objsup.Request_Ref_No = Request_Ref_No;
objsup.Document_Id = DocID.Text.ToString();
if (chkRow.Checked)
{
objsup._Remarks = "NCE_Certification";
objsup.Signature_Required = true;
}
else { objsup._Remarks = ""; objsup.Signature_Required = false; }
objsup.Uploaded_By = userSession.User_Id;
objsup.Uploaded_Path = DirectoryPath + "/" + FileUploader.FileName.Replace(" ", "_");
objsup.Document_Name = FileUploader.FileName.Replace(" ", "_");
Crm.setSupportingDocumentFRequest(objsup);
}
}
LoadCertificateRequest();
}
catch (Exception Ex)
{
string qu = null;
qu += "<div class=\"alert alert-dismissable alert-warning\">";
qu += " <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>";
qu += " <strong> Error ! </strong>Unable To Upload The File....</div>";
ErrorMessage.InnerHtml = qu;
ErrorLog.LogError(Ex);
}
}
protected void linkRemoveSD_Click(object sender, EventArgs e)
{
try
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
Label lblseqid = (Label)row.FindControl("lblseqid");
Label lblUploadP = (Label)row.FindControl("lblUploadP");
File.Delete(Server.MapPath(lblUploadP.Text));
Crm.setDELETESupportingDocUpload(Convert.ToInt64(lblseqid.Text));
}
LoadCertificateRequest();
}
catch (Exception Ex)
{
ErrorLog.LogError(Ex);
}
}
}
}
| 25,760
|
https://github.com/alhamsya/boilerplate-go/blob/master/transport/grpc/handler/types.go
|
Github Open Source
|
Open Source
|
MIT
| null |
boilerplate-go
|
alhamsya
|
Go
|
Code
| 26
| 157
|
package grpcHandler
import (
"github.com/alhamsya/boilerplate-go/lib/helpers/config"
"github.com/alhamsya/boilerplate-go/transport/grpc/routers"
"google.golang.org/grpc"
"google.golang.org/grpc/health/grpc_health_v1"
)
type HealthChecker struct {
grpc_health_v1.HealthServer
}
type Handler struct {
Cfg *config.ServiceConfig
GrpcServer *grpc.Server
Interactor *grpcRouters.GrpcInteractor
}
| 12,862
|
https://github.com/Jiansen/TAkka/blob/master/EnMAS/src/main/scala/org/enmas/typed/client/Agent.scala
|
Github Open Source
|
Open Source
|
BSD-Source-Code
| 2,019
|
TAkka
|
Jiansen
|
Scala
|
Code
| 331
| 691
|
package org.enmas.typed.client
import org.enmas.pomdp._, org.enmas.typed.messaging._,
takka.actor._
abstract class Agent() extends Client {
private var replyChannel: ActorRef[ClientManagerMessage] = null // type refined
private var aNumber: Int = 0
private var aType: AgentType = Symbol("")
private var actionSet = Set[Action]()
/** For Java API */
val NO_ACTION = Symbol("")
/** Returns the unique (per-server instance) identifier for this agent.
*/
final def agentNumber = aNumber
/** Returns the type of this agent, as defined by the POMDP model.
*/
final def agentType = aType
/** Returns the set of actions that this agent may choose to take.
*/
final def actions = actionSet
/** Returns this instance, after setting the reply channel. The
* return value is to promote method chaining at the call site,
* as in:
*
* {{{
* val myAgent = actorOf(new MyAgent repliesTo self)
* }}}
*/
final def repliesTo(chan: ActorRef[ClientManagerMessage]): Agent = { replyChannel = chan; this }
def name: String
def policy(observation: Observation, reward: Float): Action
def handleError(error: Throwable): Unit = {}
/** Initially defaultMessageHandler.
*/
final def typedReceive = defaultMessageHandler
/** Handles only the ConfirmAgentRegistration message. The last step in
* handling the confirmation is to redefine the receive behavior to include
* the policy from the implementation.
*/
// private final def defaultMessageHandler: PartialFunction[Any, Unit] = {
private final def defaultMessageHandler: PartialFunction[ClientMessage, Unit] = {
case ConfirmAgentRegistration(n, t, a) => {
aNumber = n
aType = t
actionSet = a
context.become { // TODO: do something to typed_context
//case t: Throwable => handleError(t)
case ClientError(t) => handleError(t) // borrow it
case UpdateAgent(_, observation, reward) =>
takeAction(policy(observation, reward))
case _ => ()
}
}
}
/** Replies to the replyChannel (a local client manager) with a TakeAction
* message indicating that this agent wants to take the supplied action.
*
* If the message passes security checks, it is forwarded to the server.
*/
protected final def takeAction(action: Action) {
if (actionSet contains action) replyChannel ! TakeAction(agentNumber, action)
else replyChannel ! TakeAction(agentNumber, NO_ACTION)
}
}
| 20,676
|
https://github.com/BBVA/purescript-google-apps/blob/master/src/Data/Google/Apps/Forms/ParagraphTextValidation.purs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
purescript-google-apps
|
BBVA
|
PureScript
|
Code
| 9
| 30
|
module Data.Google.Apps.Forms.ParagraphTextValidation where
foreign import data ParagraphTextValidation :: Type
| 48,005
|
https://github.com/wmtiger/shelongmen/blob/master/shelongmen_egret/bin-debug/base/Sound.js
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,017
|
shelongmen
|
wmtiger
|
JavaScript
|
Code
| 126
| 429
|
var snd;
(function (snd) {
function setEffect() {
}
snd.setEffect = setEffect;
function setBg() {
}
snd.setBg = setBg;
function playEffect(sound) {
sound.play(0, 1);
}
snd.playEffect = playEffect;
snd.bgShoundChannel = null;
snd.bgSound = null;
/** 如果正在播放相同音乐,是否重新播放。如果正在播放音乐,是否替换 */
function playBg(sound, replay, override) {
if (replay === void 0) { replay = false; }
if (override === void 0) { override = true; }
if (snd.bgShoundChannel == null) {
snd.bgSound = sound;
snd.bgShoundChannel = sound.play();
}
else {
if (snd.bgShoundChannel != null && !override)
return;
if (snd.bgSound == sound && !replay)
return;
stopBg();
snd.bgSound = sound;
snd.bgShoundChannel = sound.play();
}
}
snd.playBg = playBg;
function stopBg() {
if (snd.bgShoundChannel != null) {
snd.bgShoundChannel.stop();
snd.bgShoundChannel = null;
}
}
snd.stopBg = stopBg;
})(snd || (snd = {}));
//# sourceMappingURL=Sound.js.map
| 16,912
|
https://github.com/mgjeong/support-dataprocessing-runtime/blob/master/engine/engine-flink/src/main/java/org/edgexfoundry/support/dataprocessing/runtime/engine/flink/connectors/zmq/ZmqSink.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
support-dataprocessing-runtime
|
mgjeong
|
Java
|
Code
| 285
| 900
|
/*******************************************************************************
* Copyright 2018 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.edgexfoundry.support.dataprocessing.runtime.engine.flink.connectors.zmq;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.flink.streaming.util.serialization.SerializationSchema;
import org.edgexfoundry.support.dataprocessing.runtime.engine.flink.connectors.zmq.common.ZmqConnectionConfig;
import org.edgexfoundry.support.dataprocessing.runtime.engine.flink.connectors.zmq.common.ZmqUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zeromq.ZMQ;
public class ZmqSink<DataT> extends RichSinkFunction<DataT> {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory.getLogger(ZmqSink.class);
private final ZmqConnectionConfig zmqConnectionConfig;
private final String topic;
private SerializationSchema<DataT> schema;
private transient ZMQ.Context zmqContext;
private transient ZMQ.Socket zmqSocket;
/**
* Class constructor specifying ZeroMQ connection with data schema.
*
* @param zmqConnectionConfig ZeroMQ connection configuration including ip, port, parallelism
* @param topic ZeroMQ topic name
* @param schema Serialization schema when reading the entity on ZeroMQ
*/
public ZmqSink(ZmqConnectionConfig zmqConnectionConfig, String topic,
SerializationSchema<DataT> schema) {
this.zmqConnectionConfig = zmqConnectionConfig;
this.topic = topic;
this.schema = schema;
}
@Override
public void open(Configuration parameters) throws Exception {
super.open(parameters);
this.zmqContext = ZMQ.context(this.zmqConnectionConfig.getIoThreads());
this.zmqSocket = this.zmqContext.socket(ZMQ.PUB);
// Attempt to bind first, connect if bind fails.
LOGGER.info("Binding ZMQ to {}", this.zmqConnectionConfig.getConnectionAddress());
this.zmqSocket.bind(this.zmqConnectionConfig.getConnectionAddress());
}
@Override
public void close() throws Exception {
super.close();
if (this.zmqSocket != null) {
this.zmqSocket.close();
}
if (this.zmqContext != null) {
this.zmqContext.close();
}
}
@Override
public void invoke(DataT dataT) throws Exception {
byte[] msg = schema.serialize(dataT);
this.zmqSocket.sendMore(this.topic);
this.zmqSocket.send(ZmqUtil.encode(msg));
}
}
| 47,749
|
https://github.com/Saruspete/pawn/blob/master/pawn.cc
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
pawn
|
Saruspete
|
C++
|
Code
| 752
| 2,258
|
// Copyright 2014-2018 Google LLC. 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.
// Pawn, a companion utility to Bishop (go/bishop) to extract BIOS firmware from
// corp machines.
#include <unistd.h>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <memory>
#include "third_party/zynamics/pawn/bits.h"
#include "third_party/zynamics/pawn/chipset.h"
#include "third_party/zynamics/pawn/pci.h"
#include "third_party/zynamics/pawn/physical_memory.h"
namespace security {
namespace zynamics {
namespace {
int PawnMain(const char* dump_filename) {
util::Status status;
// We need to access the PCI configuration space, which requires to enable
// ring-3 I/O privileges. This needs to be done as root.
printf("Acquiring I/O port read permissions, this may fail...\n");
auto pci = Pci::Create(&status);
QCHECK_OK(status);
// Read chipset vendor and device ids as well as the hardware revision. Hint:
// a vendor id of 0x8086 is "Intel".
// TODO(cblichmann): Do what lspci does and lookup the vendor/device to
// display the device name.
printf("Reading chipset LPC device identification: ");
Chipset::HardwareId hw_id;
auto chipset = Chipset::Create(pci.get(), &hw_id, &status);
// TODO(cblichmann): Deal with Intel's "Compatible Revision Ids". They're
// essentially faking RIDs on boot.
printf(" VID: 0x%04X DID: 0x%04X RID: 0x%02X (%d)\n", hw_id.vendor,
hw_id.device, hw_id.revision, hw_id.revision);
QCHECK_OK(status);
// Map 16KiB of chipset configuration space at the physical address indicated
// by the RCBA register into our process. This also requires elevated
// privileges.
auto rcba = chipset->ReadRcbaRegister();
// Root Complex Register Block Chipset Register Space
printf(
"Mapping 16KiB chipset configuration space at RCBA = 0x%8X, this may "
"fail...\n",
rcba.base_address);
status = chipset->MapRootComplex(rcba);
if (!status.ok()) {
printf(
"Error: %s\n"
" Check if your kernel was compiled with IO_STRICT_DEVMEM=y.\n"
" On Debian kernels > 4.8.4, boot with iomem=relaxed to\n"
" temporarily disable /dev/mem IO protection.\n",
status.error_message().c_str());
return EXIT_FAILURE;
}
auto gcs = chipset->ReadGcsRegister();
constexpr const char* kBootBiosStrapsDesc[] = {"LPC", "Reserved", "PCI",
"SPI"};
printf("Boot BIOS Straps (BBS): %s\n",
kBootBiosStrapsDesc[gcs.boot_bios_straps]);
if (gcs.boot_bios_straps != Chipset::kBbsSpi) {
printf("Error: BIOS not located in SPI flash.\n");
return EXIT_FAILURE;
}
auto bfpr = chipset->ReadBfprRegister();
printf("PRB: 0x%08X PRL: 0x%08X\n", bfpr.bios_flash_primary_region_base,
bfpr.bios_flash_primary_region_limit);
auto frap = chipset->ReadFrapRegister();
printf("FRAP: 0x%08X\n", *reinterpret_cast<uint32*>(&frap));
enum { kNumFlashRegions = 5 };
struct FlashRegion {
Chipset::FregN freg;
Chipset::PrN pr;
} regions[kNumFlashRegions];
for (int i = 0; i < arraysize(regions); ++i) {
auto& region = regions[i];
region = {chipset->ReadFregNRegister(i), chipset->ReadPrNRegister(i)};
printf("FREG%d Base: 0x%08X Limit: 0x%08X\n", i, region.freg.region_base,
region.freg.region_limit);
}
printf("BIOS protection mechanisms:\n");
auto hsfs = chipset->ReadHsfsRegister();
printf(" HSFS Flash Configuration Lock-Down (FLOCKDN): %d\n",
hsfs.flash_configuration_lockdown);
printf(" BIOS Control Register (BIOS_CNTL):\n");
auto bios_cntl = chipset->ReadBiosCntlRegister();
printf(" SMM BIOS Write Protect Disable (SMM_BWP): %d\n",
bios_cntl.smm_bios_write_protect_disable);
printf(" BIOS Lock Enable (BLE): %d\n",
bios_cntl.bios_lock_enable);
printf(" BIOS Write Enable (BIOSWE): %d\n",
bios_cntl.bios_write_enable);
printf(" Protected Range Registers:\n");
for (int i = 0; i < arraysize(regions); ++i) {
const auto& region = regions[i];
printf(" PR%d Write Protection Enable: %d\n", i,
region.pr.write_protection_enable);
printf(" Read Protection Enable: %d\n",
region.pr.read_protection_enable);
printf(" Protected Range Base: 0x%08X Limit: 0x%08X\n",
region.pr.protected_range_base, region.pr.protected_range_limit);
}
// Ensure the chipset considers the flash descriptor valid. We don't bother
// with the now obsolete non-descriptor mode (machines before 2009).
printf("Flash Descriptor Valid (FDV): %d\n", hsfs.flash_descriptor_valid);
if (!hsfs.flash_descriptor_valid) {
printf("Warning: System not in descriptor mode!\n");
return EXIT_FAILURE;
}
auto* dump = fopen(dump_filename, "wb");
if (dump == nullptr) {
printf("Error: Could not open output file for writing.\n");
return 1;
}
std::shared_ptr<FILE> dump_closer(dump, [](FILE* dump) { fclose(dump); });
enum {
kBlockSize = 64,
kMaxFlash = 16 << 20 /* 16MiB, must be divisible by kBlockSize */
};
printf("Reading SPI flash");
fflush(STDIN_FILENO);
auto ssfs = chipset->ReadSsfsRegister();
if (ssfs.spi_cycle_in_progress) {
printf("SPI flash cycle in progress");
return EXIT_FAILURE;
}
QCHECK_OK(chipset->ReadSpiWithHardwareSequencing(
0 /* Start address */, kMaxFlash, kBlockSize,
[&dump](int64 fla, const char* data) -> bool {
if (fla / kBlockSize % 256 == 0) {
printf(".");
fflush(STDIN_FILENO);
}
if (fwrite(static_cast<const void*>(data), 1 /* Size */, kBlockSize,
dump) != kBlockSize) {
LOG(FATAL) << "Could not write " << kBlockSize << " bytes.";
}
return true;
},
nullptr /* Ignore block read errors */, [] { printf("\n"); }));
return EXIT_SUCCESS;
}
} // anonymous namespace
} // namespace zynamics
} // namespace security
int main(int argc, char* argv[]) {
const char* dump_filename = argc == 2 ? argv[1] : "bios_via_spi_hs.bin";
QCHECK(argc <= 2); // NOLINT
return security::zynamics::PawnMain(dump_filename);
}
| 12,354
|
https://github.com/swoopfx/cm/blob/master/public/vendors/echarts/src/chart/themeRiver/themeRiverVisual.js
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,020
|
cm
|
swoopfx
|
JavaScript
|
Code
| 54
| 177
|
define(function (require) {
return function (ecModel) {
ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
var data = seriesModel.getData();
var rawData = seriesModel.getRawData();
var colorList = seriesModel.get('color');
data.each(function (index) {
var name = data.getName(index);
var rawIndex = data.getRawIndex(index);
// use rawData just for drawing legend
rawData.setItemVisual(
rawIndex,
'color',
colorList[(seriesModel.nameMap[name] - 1) % colorList.length]
);
});
});
};
});
| 14,646
|
https://github.com/bluethefoxofficial/dogehouse-reloaded/blob/master/pilaf/storybook/stories/MultipleUserAvatar.stories.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
dogehouse-reloaded
|
bluethefoxofficial
|
TSX
|
Code
| 95
| 300
|
// the boolean knob renders a switch which lets you toggle a value between true or false
// you call it like boolean("name here", default_value)
import { radios } from "@storybook/addon-knobs";
import { storiesOf } from "@storybook/react-native";
import React from "react";
import { MultipleUserAvatar } from "../../src/components/avatars/MultipleUserAvatar";
import CenterView from "./CenterView";
const buttonStories = storiesOf("MultipleUserAvatar", module);
// lets storybook know to show the knobs addon for this story
buttonStories.addDecorator((getStory) => <CenterView>{getStory()}</CenterView>);
buttonStories.add("Main", () => (
<MultipleUserAvatar
srcArray={[
require("../../src/assets/images/100.png"),
require("../../src/assets/images/100.png"),
require("../../src/assets/images/100.png"),
]}
size={radios(
"Size",
{
default: "default",
sm: "sm",
xs: "xs",
},
"default"
)}
/>
));
| 2,955
|
https://github.com/szhorvath/no-no-framework/blob/master/src/client/src/views/Transaction.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
no-no-framework
|
szhorvath
|
Vue
|
Code
| 868
| 3,796
|
<template>
<div class="transaction">
<h1>
Portal Braintree Transaction
<small>{{ $route.params.transactionId }}</small>
<small
v-if="latestHistoryRecord.completed && transaction.status !== 'authorized' && latestHistoryRecord.electraRef"
class="pull-right completed"
>
<i class="fa fa-check fa-fw" aria-hidden="true"/>Completed
</small>
</h1>
<v-wait for="braintree.transaction">
<template slot="waiting"><loading/></template>
<div class="row">
<div class="col-md-6">
<div class="panel panel-primary">
<h3 class="panel-heading v-panel-heading">Customer information</h3>
<div class="panel-body">
<div class="table-responsive">
<table v-if="Object.keys(latestHistoryRecord).length !== 0" class="table table-striped v-table">
<tr>
<td>Electra Ref</td>
<td>
<strong v-if="latestHistoryRecord.electraRef">{{ latestHistoryRecord.electraRef }}</strong>
<div
v-else
:class="{
'has-error': $v.settleForm.electraRef.$invalid && $v.settleForm.electraRef.$dirty,
'has-success': !$v.settleForm.electraRef.$invalid
}"
class="form-group"
>
<input
id="electraRef"
v-model="settleForm.electraRef"
type="text"
class="form-control"
placeholder="Enter Electra Reference"
@input="$v.settleForm.electraRef.$touch()"
>
<div v-if="$v.settleForm.electraRef.$invalid && $v.settleForm.electraRef.$dirty">
<span v-if="!$v.settleForm.electraRef.integer" id="error" class="help-block">Electra refrerence must be numbers only</span>
<span v-if="!$v.settleForm.electraRef.required" id="error" class="help-block">Electra refrerence is required</span>
</div>
</div>
</td>
</tr>
<tr>
<td>Firstname</td>
<td><strong>{{ latestHistoryRecord.billing.firstname }}</strong></td>
</tr>
<tr>
<td>Surname</td>
<td><strong>{{ latestHistoryRecord.billing.surname }}</strong></td>
</tr>
<tr>
<td>Billing Address</td>
<td>
<strong>
<address>
{{ latestHistoryRecord.billing.address.line1 }}<br>
{{ latestHistoryRecord.billing.address.city }}<br>
{{ latestHistoryRecord.billing.address.postcode }}
</address>
</strong>
</td>
</tr>
<tr>
<td>Phone</td>
<td><strong>{{ latestHistoryRecord.phone }}</strong></td>
</tr>
<tr>
<td>Email</td>
<td><strong>{{ latestHistoryRecord.email }}</strong></td>
</tr>
<tr>
<td>Vehicle Reg </td>
<td><strong>{{ latestHistoryRecord.vehicleReg }}</strong></td>
</tr>
<tr>
<td>Additional Information</td>
<td><strong>{{ latestHistoryRecord.additionalInformation }}</strong></td>
</tr>
</table>
</div><!-- /.table-responsive -->
</div><!-- /.panel-body -->
</div><!-- /.panel -->
</div><!-- /.col-md-6 -->
<div class="col-md-6">
<div v-if="Object.keys(transaction).length !== 0" class="panel panel-default">
<h3 class="panel-heading v-panel-heading">Payment information</h3>
<div class="panel-body">
<div class="table-responsive">
<table class="table table-striped v-table">
<tr>
<td>Transaction Id</td>
<td><strong>{{ transaction.id }}</strong></td>
</tr>
<tr>
<td>Amount</td>
<td><strong>{{ transaction.amount }} <small>{{ transaction.currency }}</small></strong></td>
</tr>
<template v-if="transaction.cardType">
<tr>
<td>Card Type</td>
<td><img :src="transaction.cardImageUrl" :alt="transaction.cardType"></td>
</tr>
<tr>
<td>Last 4</td>
<td><strong>{{ transaction.last4 }}</strong></td>
</tr>
<tr>
<td>Card Holder Name</td>
<td><strong>{{ transaction.cardholderName }}</strong></td>
</tr>
<tr>
<td>Pay For</td>
<td><strong>{{ transaction.payFor }}</strong></td>
</tr>
</template>
<template v-else>
<tr>
<td>Payment Type</td>
<td><img :src="transaction.paypalImageUrl" alt="Paypal"></td>
</tr>
<tr>
<td>Paypal Email</td>
<td><strong>{{ transaction.paypalEmail }}</strong></td>
</tr>
<tr>
<td>Payer name</td>
<td><strong>{{ transaction.paypalFirstname }} {{ transaction.paypalSurname }} </strong></td>
</tr>
<tr>
<td>Pay For</td>
<td><strong>{{ transaction.paypalDescription }}</strong></td>
</tr>
</template>
<tr>
<td>Current Status</td>
<td>
<strong
:class="{
'ai-danger': transaction.status === 'settlement_declined'
}"
>
{{ transaction.status }}
</strong>
</td>
</tr>
<tr v-if="transaction.additionalProcessorResponse">
<td>Additional Processor Response</td>
<td><strong>{{ transaction.additionalProcessorResponse }}</strong></td>
</tr>
<tr>
<td>Created At</td>
<td><strong>{{ transaction.createdAt }}</strong></td>
</tr>
<tr>
<td>Updated At</td>
<td><strong>{{ transaction.updatedAt }}</strong></td>
</tr>
</table>
</div>
</div>
</div><!-- /.panel -->
</div><!-- /.col-md-6 -->
</div><!-- /.row -->
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-body">
<a class="btn btn-default" @click="$router.go(-1)"><i class="fa fa-undo fa-fw" aria-hidden="true"/>Back to Transactions</a>
<div class="btn-group pull-right">
<v-button
v-if="transaction.status === 'authorized'"
:loading="settleForm.busy"
:disabled="$v.settleForm.$invalid"
type="button"
variant="primary"
@click.native="settle()"
>
<i class="fa fa-university fa-fw" aria-hidden="true"/>Submit for settlement
</v-button>
<v-button
v-if="!latestHistoryRecord.completed && transaction.status !== 'authorized'"
:loading="settleForm.busy"
:disabled="$v.settleForm.$invalid"
type="button"
variant="warning"
@click.native="complete()"
>
<i class="fa fa-check fa-fw" aria-hidden="true"/>Mark as complete
</v-button>
</div>
</div>
</div>
</div><!-- /.col-md-12 -->
</div><!-- /.row -->
</v-wait>
<v-wait for="braintree.transactionHistory">
<template slot="waiting"><loading/></template>
<h2>Transaction History</h2>
<div class="row">
<div class="col-md-12">
<table class="table table-striped v-table">
<tr>
<th>Electra Ref</th>
<th>Date</th>
<th>Time</th>
<th>Transaction Id</th>
<th>Payment Type</th>
<th>Billing Name</th>
<th>Amount</th>
<th>User</th>
<th>Status</th>
<th>Vendor</th>
</tr>
<tr v-for="transaction in transactionHistory" :key="transaction.id" >
<td>
<div v-if="transaction.electraRef">{{ transaction.electraRef }}</div>
<div v-else class="ai-danger">missing</div>
</td>
<td>{{ transaction.date }}</td>
<td>{{ transaction.time }}</td>
<td>{{ transaction.transactionId }}</td>
<td><img :src="transaction.imageUrl" :alt="transaction.cardType"></td>
<td>{{ transaction.billing.firstname }} {{ transaction.billing.surname }}</td>
<td>{{ transaction.amount }} <small>{{ transaction.currency }}</small></td>
<td>{{ transaction.userId }}</td>
<td>{{ transaction.status }}</td>
<td>{{ transaction.vendor }}</td>
</tr>
</table>
</div>
</div><!-- /.row -->
</v-wait>
</div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import Form from "vform";
import { required, integer } from "vuelidate/lib/validators";
export default {
name: "Transaction",
data: () => ({
settleForm: new Form({
electraRef: null,
transactionId: null
}),
success: false
}),
validations: {
settleForm: {
electraRef: {
required,
integer
}
}
},
computed: {
...mapGetters({
transaction: "braintree/transaction",
transactionHistory: "braintree/transactionHistory"
}),
latestHistoryRecord: function() {
let maxid = 0;
this.transactionHistory.map(function(transaction) {
if (transaction.id > maxid) maxid = transaction.id;
});
let trans = this.transactionHistory.filter(function(transaction) {
return transaction.id === maxid;
});
if (trans.length === 1) {
return trans[0];
} else {
return {};
}
}
},
async mounted() {
await this.getTransactionHistory(this.$route.params.transactionId);
await this.getTransaction(this.$route.params.transactionId);
if (this.latestHistoryRecord.electraRef) {
this.settleForm.electraRef = this.latestHistoryRecord.electraRef;
}
},
methods: {
...mapActions({
getTransaction: "braintree/getTransaction",
getTransactionHistory: "braintree/getTransactionHistory",
setTransSettlement: "braintree/setTransactionSettlement"
}),
async settle() {
this.settleForm.transactionId = this.transaction.id;
try {
const { value } = await this.$swal({
title: "Are you sure?",
text: `Amount: £${this.transaction.amount}, Electra Reference: ${
this.settleForm.electraRef
}`,
type: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Submit!"
});
if (value) {
const { data } = await this.settleForm.post(
"/app/braintree/submit-for-settlement"
);
this.success = data.success;
this.setTransSettlement({
transaction: data.data.transaction,
history: data.data.transactionHistory
});
this.$swal({
title: "Transaction",
text: data.message,
type: this.success ? "success" : "error",
confirmButtonText: "OK"
});
}
} catch (e) {
console.error(e);
}
},
async complete() {
try {
this.settleForm.transactionId = this.transaction.id;
const { data } = await this.settleForm.post(
"/app/braintree/mark-complete"
);
this.success = data.success;
await this.getTransactionHistory(this.transaction.id);
} catch (e) {
this.$swal(
"Error",
"Transaction can't be completed without a valid braintree transaction! Please contact a member of the dev team",
"error"
);
console.error(e.response);
}
}
}
};
</script>
<style scoped lang="scss">
.v-table {
td {
padding: 10px 0;
font-size: 16px;
text-align: left;
vertical-align: middle;
}
}
.v-panel-heading {
margin-top: 0;
}
.completed {
color: #679a01;
}
.enter {
transform: translateX(100%);
}
.enter-to {
transform: translateX(0);
}
.slide-enter-active {
position: absolute;
}
.leave {
transform: translateX(0);
}
.leave-to {
transform: translateX(-100%);
}
.slide-enter-active,
.slide-leave-active {
transition: all 750ms ease-in-out;
}
.history {
backface-visibility: hidden;
z-index: 1;
}
/* moving */
.history-move {
transition: all 600ms ease-in-out 50ms;
}
/* appearing */
.history-enter-active {
transition: all 400ms ease-out;
}
/* disappearing */
.history-leave-active {
transition: all 200ms ease-in;
position: absolute;
z-index: 0;
}
/* appear at / disappear to */
.history-enter,
.history-leave-to {
opacity: 0;
}
</style>
| 9,517
|
https://github.com/Thomas-Jensen/dragonlancers/blob/master/resources/lang/da/routes.php
|
Github Open Source
|
Open Source
|
MIT
| null |
dragonlancers
|
Thomas-Jensen
|
PHP
|
Code
| 51
| 158
|
<?php
return array(
/*
|--------------------------------------------------------------------------
| Route Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used for the routes of the app.
|
*/
'home' => 'hjem',
'work' => 'arbejde',
'coming' => 'på-vej',
'services' => 'services',
'about' => 'om-os',
'authors' => 'blog/forfattere',
'authors-home' => 'forfattere',
'client' => 'klient',
);
| 27,245
|
https://github.com/MrPSnrub/NMRVisualisation/blob/master/app/Model/Peaks/Peak.py
|
Github Open Source
|
Open Source
|
MIT
| null |
NMRVisualisation
|
MrPSnrub
|
Python
|
Code
| 150
| 411
|
class Peak:
"""A peak found in spectra.
Attributes:
id: Rounded X-coordinate used to collate peak data
x: X-coordinates of peak along its traversal through spectra
y: Y-coordinates of peak along its traversal through spectra
z: Z-coordinates of peak along its traversal through spectra
"""
def __init__(self, peak_id, x, y, z):
self.peak_id = peak_id
self.x = x
self.y = y
self.z = z
self.length = len(x) + len(y) + len(z)
def add_coordinates(self, x, y, z):
"""Adds x, y, z co-ordinates to their respective lists."""
self.x.extend(x)
self.y.extend(y)
self.z.extend(z)
def remove_coordinates(self, amount):
"""Removes number of co-ordinates to solve missing data problem (https://en.wikipedia.org/wiki/Missing_data)
(Length of peak data will differ across all peaks, so remove redundant
data to ensure peak data matches average length of all detected peak data."""
for i in range(amount):
self.x.pop()
self.y.pop()
self.z.pop()
def peak_length(self):
self.length = len(self.z)
return self.length
def x_coordinates(self):
return self.x
def y_coordinates(self):
return self.y
def z_coordinates(self):
return self.z
| 26,226
|
https://github.com/JaxVanYang/acm/blob/master/cyj/cf/div2_712/b.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
acm
|
JaxVanYang
|
C++
|
Code
| 279
| 639
|
/*
* @Descripttion:
* @Topic link:
* @Question meaning:
* @Status: Wrong Answer 从前往后做限制条件太多,难以考虑清楚
* @Author: cyj
* @Date: 2021-04-10 20:49:54
* @LastEditTime: 2021-04-10 22:47:06
*/
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int N = 3e5+ 10;
int n;
bool st[N];
string a, b;
int main(){
int T;
cin >> T;
while (T --){
cin >> n >> a >> b;
bool suc = false;
for (int i = 0; i <= n; i ++) st[i] = 0;
if (n & 1 && a[n-1] != b[n-1]){
cout <<"NO" <<endl;
continue;
}
int zero = 0, one = 0;
bool both = 1, rever = 1;
for (int i = 0; i < n; i += 2){
if (a[i] == '0') zero ++;
else one ++;
if (a[i +1]== '0') zero ++;
else one ++;
st[i + 1] = one == zero ? 1 : 0;
if (a[i] == b[i] && a[i + 1] == b[i + 1]){
both &= 1;
}else both = 0;
if (a[i] != b[i] && a[i + 1] != b[i + 1]){
rever &= 1;
}else rever = 0;
if (both) rever = 0;
else if (rever) both = 0;
if ((a[i] == a[i+1] && b[i] != b[i+1]) || (b[i] == b[i+1] && a[i] != a[i + 1])){
suc = true;
break;
}
if (!st[i + 1] && (!both && !rever)){
suc = true;
break;
}
// cout << "i " << i << " " << both << " " << rever << endl;
if (st[i+ 1]) both = rever = 1;
}
if (suc) cout << "NO" << endl;
else cout << "YES" << endl;
}
return 0;
}
| 5,930
|
https://github.com/royi1000/tizen_mishna/blob/master/html/app.js
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
tizen_mishna
|
royi1000
|
JavaScript
|
Code
| 191
| 797
|
function update_last_location() {
localStorage.setItem("mish-masechet", $.masechet);
localStorage.setItem("mish-chap", $.chap);
localStorage.setItem("mish-mishna", $.mishna);
}
function load_text() {
console.log("loading text", $.masechet, $.chap, $.mishna)
$('.header-title').text(mishna_text[$.masechet].name + ' ' + ($.chap+1).toString() + ' ' + ($.mishna+1).toString())
$('.subject').text(mishna_text[$.masechet].text[$.chap][$.mishna]);
update_last_location();
}
function next_masechet() {
if ($.masechet+1 == mishna_text.length) {
$.masechet = 0;
}
else {
$.masechet += 1;
}
}
function prev_masechet() {
if ($.masechet == 0) {
$.masechet = mishna_text.length - 1;
}
else {
$.masechet -= 1;
}
}
function next_chapter() {
if ($.chap+1 == mishna_text[$.masechet].text.length) {
$.chap = 0;
next_masechet();
}
else {
$.chap += 1;
}
}
function prev_chapter() {
if ($.chap == 0) {
prev_masechet();
$.chap = mishna_text[$.masechet].text.length - 1;
}
else {
$.chap -= 1;
}
}
function next_mishna() {
if ($.mishna+1 == mishna_text[$.masechet].text[$.chap].length) {
$.mishna = 0;
next_chapter();
}
else {
$.mishna += 1;
}
load_text();
}
function prev_mishna() {
if ($.mishna == 0) {
prev_chapter();
$.mishna = mishna_text[$.masechet].text[$.chap].length -1;
}
else {
$.mishna -= 1;
}
load_text();
}
$( document ).ready(function() {
console.log( "ready!" );
if(!(localStorage.getItem("mish-set"))) {
console.error( "loading new config" );
localStorage.setItem("mish-masechet", 0);
localStorage.setItem("mish-chap", 0);
localStorage.setItem("mish-mishna", 0);
localStorage.setItem("mish-set", 1);
}
$.masechet = parseInt(localStorage.getItem("mish-masechet"));
$.chap = parseInt(localStorage.getItem("mish-chap"));
$.mishna = parseInt(localStorage.getItem("mish-mishna"));
load_text();
});
| 46,608
|
https://github.com/UniversalNotification/unotifier-desktop/blob/master/webpack.common.js
|
Github Open Source
|
Open Source
|
MIT
| null |
unotifier-desktop
|
UniversalNotification
|
JavaScript
|
Code
| 76
| 253
|
const path = require('path')
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')
module.exports = {
target: 'web'
, entry: {
'app': './src/renderer/app.tsx'
, 'notification': './src/renderer/notification.tsx'
}
, output: {
path: path.join(__dirname, 'dist')
, filename: '[name].js'
}
, resolve: {
extensions: ['.ts', '.tsx', '.js', '.json']
, plugins: [new TsconfigPathsPlugin()]
}
, module: {
rules: [
{
test: /\.tsx?$/
, exclude: /node_module/
, use: 'ts-loader'
}
, {
test: /\.css$/i
, use: ['style-loader', 'css-loader', 'postcss-loader']
}
]
}
, plugins: []
}
| 10,423
|
https://github.com/felixniemeyer/gluon-app/blob/master/webapp/src/views/Home.vue
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
gluon-app
|
felixniemeyer
|
Vue
|
Code
| 25
| 91
|
<template>
<div class="tea-page h-center">
<CommingSoon />
</div>
</template>
<script>
import CommingSoon from '../components/ComingSoon';
export default {
components: {
CommingSoon
}
}
</script>
<style lang="scss">
</style>
| 14,662
|
https://github.com/alex-popov-tech/.dotfiles/blob/master/.scripts/backup/backupWithNotify.sh
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
.dotfiles
|
alex-popov-tech
|
Shell
|
Code
| 27
| 73
|
#!/bin/zsh
terminal-notifier -sound default \
-title "Start backing up your passwords?" \
-message "Make sure LastPass is authorized and click on this notification" \
-execute "zsh $HOME/.dotfiles/.scripts/backup/backup.sh"
| 47
|
https://github.com/fickreey149/nakula/blob/master/app/Beli.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
nakula
|
fickreey149
|
PHP
|
Code
| 61
| 255
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Beli extends Model
{
protected $table = 'bahan_pembelian';
protected $fillable = [
'harga_bahan', 'jumlah', 'bahan_id', 'pembelian_id'
];
protected $guarded = ['id', '_token'];
public function bahan()
{
return $this->belongsTo('App\Bahan', 'bahan_id');
}
public function pembelian()
{
return $this->belongsTo('App\Pembelian', 'pembelian_id');
}
public function getBahanrAttribute()
{
return $this->bahan->lists('id')->toArray();
}
public function scopeBahan($query, $id_bahan)
{
return $query->where('bahan_id', $bahan_id);
}
}
| 23,169
|
https://github.com/AlternatiOne/StepikSimple/blob/master/Examples/src/main/java/ru/alttiri/examples/others/trash/test14/Main.java
|
Github Open Source
|
Open Source
|
MIT
| null |
StepikSimple
|
AlternatiOne
|
Java
|
Code
| 37
| 118
|
package ru.alttiri.examples.others.trash.test14;
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
Number[] numbers = new Integer[10];
numbers[0] = new Integer("0");
//numbers[1] = new BigDecimal(""); // java.lang.NumberFormatException
numbers[1] = new BigDecimal("0"); // java.lang.ArrayStoreException
}
}
| 36,508
|
https://github.com/dvjyothsna/codehouse/blob/master/node_modules/clarity-angular/src/layout/main-container.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
codehouse
|
dvjyothsna
|
TypeScript
|
Code
| 189
| 753
|
/*
* Copyright (c) 2016 VMware, Inc. All Rights Reserved.
* This software is released under MIT license.
* The full license information can be found in LICENSE in the root directory of this project.
*/
import {
Directive,
ElementRef,
OnDestroy,
OnInit
} from "@angular/core";
import {Subscription} from "rxjs/Subscription";
import { ClrResponsiveNavigationService } from "../nav/clrResponsiveNavigationService";
import { ClrResponsiveNavCodes } from "../nav/clrResponsiveNavCodes";
import { ClrResponsiveNavControlMessage } from "../nav/clrResponsiveNavControlMessage";
@Directive({
selector: "clr-main-container",
host: {
"[class.main-container]": "true"
}
})
export class MainContainer implements OnDestroy, OnInit {
private _subscription: Subscription;
private _classList: DOMTokenList;
constructor(
private elRef: ElementRef,
private responsiveNavService: ClrResponsiveNavigationService
) {}
ngOnInit() {
this._classList = this.elRef.nativeElement.classList;
this._subscription = this.responsiveNavService.navControl.subscribe({
next: (message: ClrResponsiveNavControlMessage) => {
this.processMessage(message);
}
});
}
processMessage(message: ClrResponsiveNavControlMessage): void {
let navClass: string = ClrResponsiveNavCodes.NAV_CLASS_HAMBURGER_MENU;
if (message.controlCode === ClrResponsiveNavCodes.NAV_CLOSE_ALL) {
this._classList.remove(ClrResponsiveNavCodes.NAV_CLASS_HAMBURGER_MENU);
this._classList.remove(ClrResponsiveNavCodes.NAV_CLASS_OVERFLOW_MENU);
} else if (message.navLevel === ClrResponsiveNavCodes.NAV_LEVEL_1) {
this.controlNav(message.controlCode, navClass);
} else if (message.navLevel === ClrResponsiveNavCodes.NAV_LEVEL_2) {
navClass = ClrResponsiveNavCodes.NAV_CLASS_OVERFLOW_MENU;
this.controlNav(message.controlCode, navClass);
}
}
controlNav(controlCode: string, navClass: string): void {
if (controlCode === ClrResponsiveNavCodes.NAV_OPEN) {
this._classList.add(navClass);
} else if (controlCode === ClrResponsiveNavCodes.NAV_CLOSE) {
this._classList.remove(navClass);
} else if (controlCode === ClrResponsiveNavCodes.NAV_TOGGLE) {
this._classList.toggle(navClass);
}
}
ngOnDestroy() {
this._subscription.unsubscribe();
}
}
| 28,688
|
https://github.com/juanfelipe82193/opensap/blob/master/sapui5-sdk-1.74.0/resources/sap/apf/modeler/ui/utils/staticValuesBuilder-dbg.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
opensap
|
juanfelipe82193
|
JavaScript
|
Code
| 145
| 565
|
/*!
* SAP APF Analysis Path Framework
*
* (c) Copyright 2012-2014 SAP AG. All rights reserved
*/
sap.ui.define([
'sap/apf/modeler/ui/utils/nullObjectChecker',
'sap/apf/modeler/ui/utils/textManipulator'
], function(nullObjectChecker, textManipulator) {
'use strict';
/**
* @class staticValuesBuilder
* @memberOf sap.apf.modeler.ui.utils
* @name staticValuesBuilder
* @description builds static model data
*/
function StaticValuesBuilder(oTextReader, oOptionsValueModelBuilder) {
this.oTextReader = oTextReader;
this.oOptionsValueModelBuilder = oOptionsValueModelBuilder;
}
StaticValuesBuilder.prototype.constructor = StaticValuesBuilder;
/**
* @function
* @name sap.apf.modeler.ui.utils.staticValuesBuilder#getNavTargetTypeData
* @returns a model with navigation target types
* */
StaticValuesBuilder.prototype.getNavTargetTypeData = function() {
var aNavTargetTypes = [ this.oTextReader("globalNavTargets"), this.oTextReader("stepSpecific") ];
return this.oOptionsValueModelBuilder.convert(aNavTargetTypes, aNavTargetTypes.length);
};
/**
* @function
* @name sap.apf.modeler.ui.utils.staticValuesBuilder#getSortDirections
* @returns a model with sort directions
* */
StaticValuesBuilder.prototype.getSortDirections = function() {
var aSortDirections = [ {
key : "true",
name : this.oTextReader("ascending")
}, {
key : "false",
name : this.oTextReader("descending")
} ];
return this.oOptionsValueModelBuilder.prepareModel(aSortDirections, aSortDirections.length);
};
/*BEGIN_COMPATIBILITY*/
sap.apf.modeler.ui.utils.StaticValuesBuilder = StaticValuesBuilder;
/*END_COMPATIBILITY*/
return StaticValuesBuilder;
}, true /* GLOBAL_EXPORT*/ );
| 35,685
|
https://github.com/WorldUtils/world-utils/blob/master/src/main/java/me/frauenfelderflorian/worldutils/commands/CPTimer.java
|
Github Open Source
|
Open Source
|
MIT
| null |
world-utils
|
WorldUtils
|
Java
|
Code
| 640
| 2,080
|
package me.frauenfelderflorian.worldutils.commands;
import me.frauenfelderflorian.worldutils.Messages;
import me.frauenfelderflorian.worldutils.Timer;
import me.frauenfelderflorian.worldutils.WorldUtils;
import me.frauenfelderflorian.worldutils.config.Prefs;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
/**
* CommandExecutor and TabCompleter for command personaltimer
*/
public record CPTimer(WorldUtils plugin) implements TabExecutor {
public static final String CMD = "personaltimer";
/**
* Done when command sent
*
* @param sender sender of the command
* @param command sent command
* @param alias used alias
* @param args used arguments
* @return true if correct command syntax used and no errors, false otherwise
*/
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias,
String[] args) {
if (sender instanceof Player) switch (args.length) {
case 1 -> {
switch (args[0]) {
case "visible" -> {
//change visibility status
plugin.getTimer((Player) sender).setVisible(!plugin.prefs.getBoolean(
(Player) sender, Prefs.Option.PTIMER_VISIBLE));
return true;
}
case "running" -> {
//change running status
plugin.getTimer((Player) sender).setRunning(!plugin.prefs.getBoolean(
(Player) sender, Prefs.Option.PTIMER_RUNNING));
return true;
}
case "reverse" -> {
//change reverse status
plugin.prefs.set((Player) sender, Prefs.Option.PTIMER_REVERSE, !plugin.prefs.getBoolean(
(Player) sender, Prefs.Option.PTIMER_REVERSE), true);
Messages.sendMessage(plugin, "§eTimer reversed, now in §b" + (plugin.prefs.getBoolean(
(Player) sender, Prefs.Option.TIMER_REVERSE) ? "reverse" : "normal") + "§e mode.");
return true;
}
case "reset" -> {
//set timer to 0
plugin.getTimer((Player) sender).setRunning(false);
plugin.getTimer((Player) sender).setTime(0);
Messages.sendMessage(plugin, sender, "§ePersonal timer set to 0.");
return true;
}
}
}
case 2, 3, 4, 5 -> {
switch (args[0]) {
case "invite", "join" -> {
//add another player to the personal timer or join another player's personal timer
if (args.length == 2) {
Player other = Bukkit.getPlayer(args[1]);
if (other != null && other.isOnline()) {
if (args[0].equals("invite")
&& !plugin.getTimer((Player) sender).containsPlayer(other)) {
plugin.getTimer((Player) sender).addPlayer(other);
return true;
} else if (args[0].equals("join")
&& !plugin.getTimer(other).containsPlayer((Player) sender)
&& plugin.prefs.getBoolean(other, Prefs.Option.PTIMER_JOINABLE)) {
plugin.getTimer(other).addPlayer((Player) sender);
return true;
}
} else Messages.playerNotFound(plugin, sender);
}
}
case "leave", "remove" -> {
//leave another player's personal timer or remove a player from the personal timer
if (args.length == 2) {
Player other = Bukkit.getPlayer(args[1]);
if (other != null && other.isOnline()) {
if (args[0].equals("leave") && plugin.getTimer(other).containsPlayer((Player) sender)) {
plugin.getTimer(other).removePlayer((Player) sender);
return true;
} else if (args[0].equals("remove")
&& plugin.getTimer((Player) sender).containsPlayer(other)) {
plugin.getTimer((Player) sender).removePlayer(other);
return true;
}
} else Messages.playerNotFound(plugin, sender);
}
}
case "set" -> {
//set time to input values
try {
plugin.getTimer((Player) sender).setTime(CTimer.getTime(args));
Messages.sendMessage(plugin, sender, "§ePersonal timer set to §b"
+ Timer.formatTime(plugin.prefs.getInt((Player) sender, Prefs.Option.TIMER_TIME)));
return true;
} catch (IllegalStateException e) {
Messages.wrongArgumentNumber(plugin, sender);
} catch (NumberFormatException e) {
Messages.wrongArguments(plugin, sender);
}
}
case "add" -> {
//add input values to current time
try {
plugin.getTimer((Player) sender).setTime(plugin.prefs.getInt(
(Player) sender, Prefs.Option.TIMER_TIME) + CTimer.getTime(args));
Messages.sendMessage(plugin, sender, "§eAdded §b"
+ Timer.formatTime(CTimer.getTime(args)) + " §eto personal timer");
return true;
} catch (IllegalStateException e) {
Messages.wrongArgumentNumber(plugin, sender);
} catch (NumberFormatException e) {
Messages.wrongArguments(plugin, sender);
}
}
}
}
}
else {
Messages.notConsole(plugin, sender);
return true;
}
return false;
}
/**
* Done while entering command
*
* @param sender sender of the command
* @param command sent command
* @param alias used alias
* @param args used arguments
* @return List of Strings for tab completion
*/
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias,
String[] args) {
List<String> completions = new ArrayList<>();
//get names of all online players
List<String> players = new ArrayList<>();
for (Player player : Bukkit.getOnlinePlayers())
players.add(player.getName());
//get names of all players that can view the personal timer
List<String> removablePlayers = new ArrayList<>();
for (Player player : Bukkit.getOnlinePlayers())
if (plugin.getTimer((Player) sender).containsPlayer(player)) removablePlayers.add(player.getName());
//get names of all players whose personal timer is visible
List<String> leavableTimers = new ArrayList<>();
for (Player player : Bukkit.getOnlinePlayers())
if (plugin.getTimer(player).containsPlayer((Player) sender)) leavableTimers.add(player.getName());
switch (args.length) {
case 1 -> StringUtil.copyPartialMatches(args[0], List.of("visible", "running", "reverse", "reset", "invite",
"join", "leave", "remove", "set", "add"), completions);
case 2, 3, 4, 5 -> {
if (args.length == 2) switch (args[0]) {
case "invite" -> StringUtil.copyPartialMatches(args[1], players, completions);
case "leave" -> StringUtil.copyPartialMatches(args[1], leavableTimers, completions);
case "remove" -> StringUtil.copyPartialMatches(args[1], removablePlayers, completions);
}
if (List.of("set", "add").contains(args[0])) completions.add("<time>");
}
}
return completions;
}
}
| 37,651
|
https://github.com/YCOOTRIP/Uni_todo/blob/master/pages/index/index.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
Uni_todo
|
YCOOTRIP
|
Vue
|
Code
| 766
| 3,341
|
<template>
<view class="content">
<!-- 状态栏 -->
<view v-if="list.length !== 0" class="todo-header">
<view class="todo-header__left">
<text class="active-text">{{text}}</text>
<text>{{listData.length}}条</text>
</view>
<view class="todo-header__right">
<view class="todo-header__right-item" :class="{'active-tab':activeIndex === 0}" @click="tab(0)">全部</view>
<view class="todo-header__right-item" :class="{'active-tab':activeIndex === 1}" @click="tab(1)">待办</view>
<view class="todo-header__right-item" :class="{'active-tab':activeIndex === 2}" @click="tab(2)">已完成</view>
</view>
</view>
<!-- 没有数据的状态 -->
<view v-if="list.length === 0" class="default">
<view class="image-default">
<image src="../../static/default.png" mode="aspectFit"></image>
</view>
<view class="default-info">
<view class="default-info__text">您还没有创建任何待办事项</view>
<view class="default-info__text">点击下方+号创建一个吧</view>
</view>
</view>
<!-- content -->
<view v-else class="todo-content">
<view class="todo-list" :class="{'todo--finish':item.checked}" v-for="(item,index) in listData" :key="index" @click="finish(item.id)">
<view class="todo-list__checkbox">
<view class="checkbox"></view>
</view>
<view class="todo-list__content">{{item.content}}</view>
</view>
</view>
<!-- 创建按钮 -->
<view class="create-todo" @click="create">
<text class="iconfont icon-add" :class="{'create-todo-active':active}"></text>
</view>
<!-- 输入框 -->
<view class="create-content" :class="{'create--show':active}">
<view class="create-content-box">
<!-- input 输入 -->
<view class="create-input">
<input type="text" v-model="value" placeholder="请输入您的待办事项" />
</view>
<!-- 发布按钮 -->
<view class="create-button" @click="add">
创建
</view>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
value: '',
list: [],
active: false,
activeIndex: 0,
text: '全部'
}
},
computed:{
listData(){
let list = JSON.parse(JSON.stringify(this.list))
let newList = []
if(this.activeIndex === 0) {
this.text = '全部'
return list
}
if(this.activeIndex === 1) {
list.forEach(item => {
if(!item.checked) {
newList.push(item)
}
})
this.text = '待办'
return newList
}
if(this.activeIndex === 2) {
list.forEach(item => {
if(item.checked) {
newList.push(item)
}
})
this.text = '已完成'
return newList
}
}
},
methods: {
// 打开输入框
create() {
this.active = !this.active ? true : false
},
add() {
// console.log(this.value)
if(!this.value) {
uni.showToast({
title:"请输入内容",
icon:'none'
})
return
}
this.list.unshift({
content: this.value,
id: 'id' + new Date().getTime(),
checked: false
})
this.value = ''
this.active = false
},
// 点击列表触发
finish(id) {
let index = this.list.findIndex((item) => item.id === id)
// console.log('我被点击了', this.list[index]);
this.list[index].checked = !this.list[index].checked
},
tab(index) {
this.activeIndex = index
}
}
}
</script>
<style>
@import "../../common/icon.css";
.todo-header {
position: fixed;
top: 44px;
left: 0;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 15px;
font-size: 12px;
color: #333333;
width: 100%;
height: 45px;
box-sizing: border-box;
box-shadow: -1px 1px 5px 0 rgba(0, 0, 0, 0.1);
background: #FFFFFF;
z-index: 10;
}
.active-text {
font-size: 14px;
color: #279abf;
padding-right: 10px;
}
.todo-header__right {
display: flex;
}
.todo-header__right-item {
padding: 0 5px;
}
.active-tab {
color: #279abf;
}
.todo-content {
position: relative;
padding-top: 50px;
padding-bottom: 100px;
}
.todo-list {
position: relative;
display: flex;
align-items: center;
padding: 15px;
margin: 15px;
color: #0c3854;
font-size: 14px;
border-radius: 10px;
background: #cfebfd;
box-shadow: -1px 1px 5px 1px rgba(0, 0, 0, 0.1), -1px 2px 1px 0 rgba(255, 255, 255) inset;
overflow: hidden;
}
.todo-list::after {
position: absolute;
content: '';
top: 0;
bottom: 0;
left: 0;
width: 5px;
background: #91d1e8;
}
.todo-list__checkbox {
padding-right: 15px;
}
.checkbox {
width: 20px;
height: 20px;
border-radius: 50%;
background: #FFFFFF;
box-shadow: 0 0 5px 1px rgba(0, 0, 0, 0.1);
}
.todo--finish .checkbox {
position: relative;
background: #eee;
}
.todo--finish .checkbox::after {
content: '';
position: absolute;
width: 10px;
height: 10px;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
border-radius: 50%;
background: #CFEBFD;
box-shadow: 0 0 2px 0px rgba(0, 0, 0, 0.2) inset;
}
.todo--finish .todo-list__content {
color: #999999;
}
.todo--finish.todo-list::before {
content: '';
position: absolute;
top: 0;
bottom: 0;
left: 40px;
right: 10px;
height: 2px;
margin: auto 0;
background: #bdcdd8;
}
.todo--finish.todo-list:after {
background: #cccccc;
}
.create-todo {
display: flex;
justify-content: center;
align-items: center;
position: fixed;
bottom: 20px;
left: 0;
right: 0;
margin: 0 auto;
width: 50px;
height: 50px;
border-radius: 50%;
background-color: #deeff5;
box-shadow: -1px 1px 5px 2px rgba(0, 0, 0, 0.1), -1px 1px 1px 0 rgba(255, 255, 255) inset;
}
.icon-add {
font-size: 30px;
color: #add8e6;
transition: transform 0.3s;
}
.create-content {
position: fixed;
bottom: 95px;
left: 20px;
right: 20px;
transition: all 0.2s;
visibility: hidden;
opacity: 0;
transform: scale(0) translateY(200%)
}
.create--show {
visibility: visible;
opacity: 1;
transform: scale(1) translateY(0);
}
.create-content-box {
display: flex;
align-items: center;
padding: 0 15px;
padding-right: 0;
border-radius: 50px;
background: #DEEFF5;
box-shadow: -1px 1px 5px 2px rgba(0, 0, 0, 0.1), -1px 1px 1px 0 rgba(255, 255, 255) inset;
z-index: 2;
}
.create-input {
width: 100%;
padding-right: 15px;
color: #add8e6;
}
.create-button {
display: flex;
justify-content: center;
align-items: center;
flex-shrink: 0;
width: 80px;
height: 50px;
border-radius: 50px;
font-size: 16px;
color: #88d4ec;
box-shadow: -2px 0px 2px 1px rgba(0, 0, 0, 0.1);
}
.create-content::after {
content: '';
position: absolute;
right: 0;
left: 0;
bottom: -8px;
margin: 0 auto;
width: 20px;
height: 20px;
background: #DEEFF5;
transform: rotate(45deg);
box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.1);
z-index: -1;
}
.create-content-box::after {
content: '';
position: absolute;
right: 0;
left: 0;
bottom: -8px;
margin: 0 auto;
width: 20px;
height: 20px;
background: #DEEFF5;
transform: rotate(45deg);
}
.default {
padding-top: 100px;
}
.image-default {
display: flex;
justify-content: center;
}
.image-default image {
width: 100%;
}
.default-info {
text-align: center;
font-size: 14px;
color: #CCCCCC;
}
.create-todo-active {
transform: rotate(135deg);
}
</style>
| 49,298
|
https://github.com/borglab/gtsam.org/blob/master/doxygen/a03864.js
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
gtsam.org
|
borglab
|
JavaScript
|
Code
| 10
| 54
|
var a03864 =
[
[ "boost::serialization::access", "a03864.html#ac98d07dd8f7b70e16ccb9a01abf56b9c", null ]
];
| 49,279
|
https://github.com/itepifanio/vhdl/blob/master/exercicios/trabalho_final/final/modulo_acesso.vhd
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
vhdl
|
itepifanio
|
VHDL
|
Code
| 662
| 1,817
|
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
entity modulo_acesso is
PORT (
clk, escrever_valor, exec_op: IN STD_LOGIC;
instrucao: IN STD_LOGIC_VECTOR (17 DOWNTO 0);
valor_banco_regs: IN STD_LOGIC_VECTOR (15 DOWNTO 0); -- valor vindo do banco de registradores
valor_ula: IN STD_LOGIC_VECTOR (15 DOWNTO 0); -- valor vindo da ula
seletor: OUT STD_LOGIC_VECTOR (2 DOWNTO 0); -- registrador que vai para o banco
ler_escrever: OUT STD_LOGIC; -- diz se escrita ou leitura para o banco de reg
valor_out: OUT STD_LOGIC_VECTOR (15 DOWNTO 0); -- valor que vai para o banco de registradores
exec_op_out: OUT STD_LOGIC; -- diz pra ULA que pode operar
escrever_valor_out: OUT STD_LOGIC; -- diz pro banco se pode escrever ou ler o valor
a, b: OUT STD_LOGIC_VECTOR (15 DOWNTO 0); -- saidas da ULA
l1, l2, l3, l4: OUT STD_LOGIC; -- LEDS para testar o PO
valor_ula_out: OUT STD_LOGIC_VECTOR (15 DOWNTO 0) -- (teste)
-- valor_banco_regs_out: OUT STD_LOGIC_VECTOR (15 DOWNTO 0) -- (teste)
);
end entity;
architecture arq of modulo_acesso is
-- esses signals e constants sao pra fazer a PC aqui no modulo de acesso
signal aux_in: STD_LOGIC_VECTOR (15 DOWNTO 0); -- sinal auxiliar para armazenar o valor vindo do banco
constant init: STD_LOGIC_VECTOR (2 DOWNTO 0) := "000"; -- note que o ideal sera armazenar o valor na RAM
constant ler_a: STD_LOGIC_VECTOR (2 DOWNTO 0) := "001";
constant ler_b: STD_LOGIC_VECTOR (2 DOWNTO 0) := "010";
constant escrever_em_c: STD_LOGIC_VECTOR (2 DOWNTO 0) := "011";
constant wait_ler_a: STD_LOGIC_VECTOR (2 DOWNTO 0) := "100"; -- espera um clock
constant wait_ler_b: STD_LOGIC_VECTOR (2 DOWNTO 0) := "101"; -- espera um clock
constant wait_escrever_em_c: STD_LOGIC_VECTOR (2 DOWNTO 0) := "110"; -- espera um clock
constant wait_init: STD_LOGIC_VECTOR (2 DOWNTO 0) := "111"; -- espera um clock
signal pc: STD_LOGIC_VECTOR (2 DOWNTO 0) := init; -- sinal auxiliar para a PC
constant pc2_init: STD_LOGIC_VECTOR(1 DOWNTO 0) := "00";
constant pc2_ler_a: STD_LOGIC_VECTOR(1 DOWNTO 0) := "01";
constant pc2_ler_b: STD_LOGIC_VECTOR(1 DOWNTO 0) := "10";
signal pc2: STD_LOGIC_VECTOR(1 DOWNTO 0):= pc2_init;
begin
process(clk, escrever_valor, exec_op, instrucao, valor_banco_regs, valor_ula)
begin
if (clk'event and clk = '1') then
if(escrever_valor = '1') then
if(pc2 = pc2_init) then
ler_escrever <= '1'; -- manda o banco escrever
seletor <= '0' & instrucao(1 DOWNTO 0);
valor_out <= instrucao(17 DOWNTO 2);
-- a <= instrucao(17 DOWNTO 2);
pc2 <= pc2_ler_b;
elsif(pc2 = pc2_ler_b) then
ler_escrever <= '1'; -- manda o banco escrever
seletor <= '0' & instrucao(1 DOWNTO 0);
valor_out <= instrucao(17 DOWNTO 2);
-- b <= instrucao(17 DOWNTO 2);
pc2 <= pc2_init;
end if;
-- | 16 bits (valor) | 2 bits (reg destino) |
end if;
-- preciso que leia A do banco e depois leia B do banco, envie pra ULA
-- e depois receba o valor da ULA pra gravar no registrador
-- | 4 bits (op) | 3 bits (regA) | 3 bits (regB) | 3 bits (regC) | 3 bits 000 |
if(pc = init and exec_op = '1') then
-- manda pro banco ler o valor de regB
-- lembre que regA salva a operacao em regB e regC
valor_ula_out <= valor_ula; -- (teste)
ler_escrever <= '0';
seletor <= instrucao(10 downto 8); -- regB
pc <= wait_ler_a;
exec_op_out <= '0'; -- atribuindo zero just in case
l1 <= '1';
else
l1 <= '0';
-- valor_ula_out <= "0000000000000000"; -- (teste)
end if;
if(pc = wait_ler_a) then
pc <= ler_a;
end if;
if(pc = ler_a) then
a <= valor_banco_regs;
ler_escrever <= '0';
seletor <= instrucao(7 downto 5); -- regC
pc <= wait_ler_b;
l2 <= '1';
else
-- valor_banco_regs_out <= "0000000000000000"; -- (teste)
l2 <= '0';
end if;
if(pc = wait_ler_b) then
pc <= ler_b;
end if;
if(pc = ler_b) then
b <= valor_banco_regs;
l3 <= '1';
pc <= wait_init;
exec_op_out <= '1';
else
l3 <= '0';
end if;
if(pc = wait_init) then
ler_escrever <= '1'; -- manda o banco escrever
seletor <= instrucao(13 downto 11); -- regA
valor_out <= valor_ula; -- talvez tenha que mandar um sinal pra ULA pra poder dizer "opere"
pc <= init;
end if;
end if;
end process;
end architecture;
| 28,719
|
https://github.com/heatblayze/CustomProjectSettings/blob/master/Samples~/ExampleScripts/ExampleSettingsChildA.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
CustomProjectSettings
|
heatblayze
|
C#
|
Code
| 27
| 68
|
using CustomProjectSettings;
using UnityEngine;
public class ExampleSettingsChildA : CustomSettingsChild<ExampleSettingsRoot>
{
public override string Title => "Example Settings A";
public string String => _string;
[SerializeField]
string _string;
}
| 52
|
https://github.com/MostafaEsmaeili/AccessControl/blob/master/src/application/Api/GetById/GetMenuResourceById.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
AccessControl
|
MostafaEsmaeili
|
C#
|
Code
| 84
| 317
|
using AutoMapper;
using AutoMapper.QueryableExtensions;
using DotnetAccessControl.Application.Api.Dto;
using DotnetAccessControl.Application.common.interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DotnetAccessControl.Application.Api.GetById
{
public record GetMenuResourceById(Guid Id) : IRequest<ApiResourceResponse>;
public class GetMenuResourceByIdHandler : IRequestHandler<GetMenuResourceById, ApiResourceResponse>
{
private readonly IDotnetAccessControlDbContext _context;
private readonly IMapper _mapper;
public GetMenuResourceByIdHandler(IDotnetAccessControlDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task<ApiResourceResponse> Handle(GetMenuResourceById request, CancellationToken cancellationToken)
{
var entity = _context.ApiResources.AsNoTracking()
.Where(x => x.Id == request.Id);
return await _mapper.ProjectTo<ApiResourceResponse>(entity).SingleOrDefaultAsync();
}
}
}
| 22,517
|
https://github.com/scikit-mine/scikit-mine/blob/master/skmine/tests/test_base.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,023
|
scikit-mine
|
scikit-mine
|
Python
|
Code
| 145
| 484
|
import pandas as pd
import pytest
from ..base import BaseMiner, MDLOptimizer
def test_inst_params():
class MyMiner(BaseMiner):
def __init__(self, eps=3):
self.eps = eps
self._a = 2
def fit(self, D):
self._a = 12
discover = lambda self: pd.DataFrame()
kwargs = dict(eps=4)
miner = MyMiner(**kwargs)
assert miner.get_params() == kwargs # get_params returns only unprotected attributes so only eps
kwargs.update(eps=10)
miner.set_params(**kwargs)
assert miner.get_params() == kwargs
assert miner.set_params().get_params() == kwargs # stay untouched
with pytest.raises(ValueError):
miner.set_params(random_key=2)
def test_inst_params_no_init():
class MyMiner(BaseMiner):
def fit(self, D, y=None):
return self
discover = lambda self: pd.DataFrame()
miner = MyMiner()
assert miner.get_params() == dict() # compared to the previous test, eps is not an attribute of the class
def test_mdl_repr():
class A(MDLOptimizer):
def __init__(self):
self.codetable_ = {1: [0, 1], 2: [1]}
def fit(self):
return self
def evaluate(self):
return True
def generate_candidates(self):
return list()
discover = lambda self: pd.Series(self.__dict__)
a = A()
assert isinstance(a._repr_html_(), str)
assert isinstance(a.fit()._repr_html_(), str)
| 7,555
|
https://github.com/akamenev/IntelligentExperiences.OnContainers/blob/master/src/core/PersonIdentificationLib/PersonIdentificationLib/Services/VisitorIdentificationManager.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
IntelligentExperiences.OnContainers
|
akamenev
|
C#
|
Code
| 1,003
| 3,536
|
using CognitiveServiceHelpers;
using CoreLib.Abstractions;
using CoreLib.Repos;
using Microsoft.Azure.CognitiveServices.Vision.Face.Models;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using PersonIdentificationLib.Abstractions;
using PersonIdentificationLib.Models;
using PersonIdentificationLib.Repos;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace PersonIdentificationLib.Services
{
public class VisitorIdentificationManager : IVisitorIdentificationManager
{
private string key = string.Empty;
private string endpoint = string.Empty;
private string faceWorkspaceDataFilter;
private IStorageRepository filesStorageRepo;
//private ICamFrameAnalysisRepository camFrameAnalysisRepo;
private IAzureServiceBusRepository serviceBusRepo;
private CognitiveFacesAnalyzer cognitiveFacesAnalyzer;
private IdentifiedVisitorRepo identifiedVisitorRepo;
private IdentifiedVisitorGroupRepo identifiedVisitorGroupRepo;
private AzureBlobStorageRepository storageRepo;
private byte[] photoData;
List<FaceAttributeType> faceAttributes = new List<FaceAttributeType> { FaceAttributeType.Age, FaceAttributeType.Gender };
public VisitorIdentificationManager(string cognitiveKey,
string cognitiveEndpoint,
string faceFilter,
string cosmosDbEndpoint,
string cosmosDbKey,
string cosmosDbName,
string storageConnection,
string storageContainerName)
{
key = cognitiveKey;
endpoint = cognitiveEndpoint;
faceWorkspaceDataFilter = faceFilter;
FaceServiceHelper.ApiKey = key;
FaceServiceHelper.ApiEndpoint = endpoint;
FaceListManager.FaceListsUserDataFilter = faceWorkspaceDataFilter;
var dbClient = new DocumentClient(
new Uri(cosmosDbEndpoint),
cosmosDbKey,
new ConnectionPolicy { EnableEndpointDiscovery = false });
var dbFactory = new CosmosDbClientFactory(
cosmosDbName,
new Dictionary<string, string> {
{ AppConstants.DbColIdentifiedVisitor, AppConstants.DbColIdentifiedVisitorPartitionKey },
{ AppConstants.DbColIdentifiedVisitorGroup, AppConstants.DbColIdentifiedVisitorPartitionKey }
},
dbClient);
identifiedVisitorRepo = new IdentifiedVisitorRepo(dbFactory);
identifiedVisitorGroupRepo = new IdentifiedVisitorGroupRepo(dbFactory);
storageRepo = new AzureBlobStorageRepository(storageConnection, storageContainerName);
//serviceBusRepo = new AzureServiceBusRepository(serviceBusConnection, AppConstants.SBTopic, AppConstants.SBSubscription);
}
//Groups
public async Task<IdentifiedVisitorGroup> CreateVisitorsGroupAsync(string groupName)
{
IdentifiedVisitorGroup result = null;
//var isValidGroupId = Regex.IsMatch(groupId, "^[a-z0-9-_]+");
//if (!isValidGroupId)
// throw new InvalidExpressionException("Group id must be only alpha numeric letters with - and _");
try
{
var newItem = new IdentifiedVisitorGroup
{
Name = groupName,
Filter = faceWorkspaceDataFilter,
PartitionKey = AppConstants.DbColIdentifiedVisitorPartitionKeyValue,
IsActive = true,
CreatedAt = DateTime.UtcNow,
Origin = AppConstants.Origin
};
result = await identifiedVisitorGroupRepo.AddAsync(newItem);
result.GroupId = result.Id.ToLower();
await FaceServiceHelper.CreatePersonGroupAsync(result.GroupId, newItem.Name, newItem.Filter);
}
catch (Exception ex)
{
throw ex;
}
return result;
}
public async Task<IdentifiedVisitorGroup> GetVisitorsGroupByIdAsync(string groupId)
{
IdentifiedVisitorGroup result = null;
try
{
result = await identifiedVisitorGroupRepo.GetByIdAsync(groupId);
}
catch (Exception ex)
{
throw ex;
}
return result;
}
public async Task<List<IdentifiedVisitorGroup>> GetAllVisitorsGroupsAsync()
{
List<IdentifiedVisitorGroup> result = null;
try
{
result = await identifiedVisitorGroupRepo.GetAllAsync();
}
catch (Exception ex)
{
throw ex;
}
return result;
}
public async Task<IdentifiedVisitorGroup> GetVisitorsGroupByNameAsync(string groupName)
{
var result = await identifiedVisitorGroupRepo.QueryDocuments(
"visitorsGroup",
"visitorsGroup.Name=@GroupName",
new SqlParameterCollection {
new SqlParameter { Name = "@GroupName", Value = groupName }
});
if (result.Any())
{
return result[0];
}
return null;
}
public async Task TrainVisitorGroup(string groupId, bool waitForTrainingToComplete)
{
//var group = await identifiedVisitorGroupRepo.GetByIdAsync(groupId);
//if (group != null)
//{
await FaceServiceHelper.TrainPersonGroupAsync(groupId);
TrainingStatus trainingStatus = null;
while (waitForTrainingToComplete)
{
trainingStatus = await GetVisitorsGroupTrainingStatusAsync(groupId);
if (trainingStatus.Status != TrainingStatusType.Running)
{
break;
}
await Task.Delay(1000);
}
//group.LastTrainingDate = DateTime.UtcNow;
//await identifiedVisitorGroupRepo.UpdateAsync(group);
//}
//else
//{
// throw new KeyNotFoundException($"Group ({groupId}) not found");
//}
}
public async Task<TrainingStatus> GetVisitorsGroupTrainingStatusAsync(string groupId)
{
return await FaceServiceHelper.GetPersonGroupTrainingStatusAsync(groupId);
}
public async Task<ResultStatus> DeleteVisitorsGroup(string groupId)
{
var result = new ResultStatus();
var group = await identifiedVisitorGroupRepo.GetByIdAsync(groupId);
if (group != null)
{
var visitorsInGroup = (await identifiedVisitorRepo.GetAllAsync()).Where(v => v.GroupId == group.Id);
foreach (var visitor in visitorsInGroup)
await identifiedVisitorRepo.DeleteAsync(visitor);
await FaceServiceHelper.DeletePersonGroupAsync(groupId);
await identifiedVisitorGroupRepo.DeleteAsync(group);
result.StatusCode = "0";
result.Message = $"Successfully deleted group ({group.Id}) and the associated visitors ({visitorsInGroup.Count()}";
result.IsSuccessful = true;
}
else
{
result.StatusCode = "1";
result.Message = $"Group id ({group.Id}) not found!";
result.IsSuccessful = false;
}
return result;
}
//Visitors
public async Task<IdentifiedVisitor> CreateVisitorAsync(IdentifiedVisitor identifiedVisitor)
{
//TODO: Validate if the visitor exists
identifiedVisitor.CreatedAt = DateTime.UtcNow;
identifiedVisitor.IsActive = true;
identifiedVisitor.IsDeleted = false;
identifiedVisitor.PartitionKey = string.IsNullOrEmpty(identifiedVisitor.PartitionKey) ? AppConstants.DbColIdentifiedVisitorPartitionKeyValue : identifiedVisitor.PartitionKey;
identifiedVisitor.Id = $"{Guid.NewGuid().ToString()}-{identifiedVisitor.PartitionKey}";
var cognitivePerson = await FaceServiceHelper.CreatePersonAsync(identifiedVisitor.GroupId, identifiedVisitor.Name, identifiedVisitor.Id);
identifiedVisitor.PersonDetails = cognitivePerson;
double? age = null;
Gender? gender = null;
foreach (var photo in identifiedVisitor.Photos)
{
if (!photo.IsSaved)
{
photoData = photo.PhotoData;
var photoFileExtension = Path.GetExtension(photo.Name);
var newPhotoFileName = $"{identifiedVisitor.Id}-{identifiedVisitor.Photos.IndexOf(photo) + 1}{photoFileExtension}";
//Only accept photos with single face
var detectedFaces = await FaceServiceHelper.DetectWithStreamAsync(GetPhotoStream, returnFaceAttributes: faceAttributes);
if (detectedFaces.Count == 0)
{
photo.Status = "Invalid: No faces detected in photo";
continue;
}
else if (detectedFaces.Count > 1)
{
photo.Status = "Invalid: More than 1 face detected in photo. Only photos with single face can be used to train";
continue;
}
//Upload the new photo to storage
photo.Url = await storageRepo.CreateFileAsync(newPhotoFileName, photo.PhotoData);
age = detectedFaces[0].FaceAttributes.Age;
gender = detectedFaces[0].FaceAttributes.Gender;
var persistedFace = await AddVisitorPhotoAsync(identifiedVisitor.GroupId, cognitivePerson.PersonId, photo.Url, detectedFaces[0].FaceRectangle);
//Update photo details
photo.IsSaved = true;
photo.Name = newPhotoFileName;
photo.Status = "Saved";
}
}
//Save the new identified visitor details to database
identifiedVisitor.Age = age.HasValue ? age.Value : 0;
identifiedVisitor.Gender = gender.HasValue ? gender.ToString() : "NA";
var result = await identifiedVisitorRepo.AddAsync(identifiedVisitor);
return result;
}
public async Task<PersistedFace> AddVisitorPhotoAsync(string groupId, Guid cognitivePersonId, string photoUrl, FaceRectangle faceRect)
{
var persistedFace = await FaceServiceHelper.AddPersonFaceFromStreamAsync(groupId, cognitivePersonId, GetPhotoStream, photoUrl, faceRect);
return persistedFace;
}
public async Task<IdentifiedVisitor> GetVisitorByIdAsync(string id)
{
var visitor = await identifiedVisitorRepo.GetByIdAsync(id);
return visitor;
}
public async Task<IdentifiedVisitor> GetVisitorByPersonIdAsync(Guid personId)
{
var result = await identifiedVisitorRepo.QueryDocuments(
"visitor",
"visitor.PersonDetails.PersonId=@PersonId",
new SqlParameterCollection {
new SqlParameter { Name = "@PersonId", Value = personId }
});
if (result.Any())
{
return result[0];
}
return null;
}
public async Task<IdentifiedVisitor> UpdateVisitorAsync(IdentifiedVisitor identifiedVisitor)
{
if (identifiedVisitor == null)
throw new InvalidDataException("No visitor data");
if (identifiedVisitor.Photos != null && identifiedVisitor.Photos.Count > 0)
{
double? age = null;
Gender? gender = null;
foreach (var photo in identifiedVisitor.Photos)
{
if (!photo.IsSaved)
{
photoData = photo.PhotoData;
var photoFileExtension = Path.GetExtension(photo.Name);
var newPhotoFileName = $"{identifiedVisitor.Id}-{identifiedVisitor.Photos.IndexOf(photo) + 1}{photoFileExtension}";
//Only accept photos with single face
var detectedFaces = await FaceServiceHelper.DetectWithStreamAsync(GetPhotoStream, returnFaceAttributes: faceAttributes);
if (detectedFaces.Count == 0)
{
photo.Status = "Invalid: No faces detected in photo";
continue;
}
else if (detectedFaces.Count > 1)
{
photo.Status = "Invalid: More than 1 face detected in photo. Only photos with single face can be used to train";
continue;
}
//Upload the new photo to storage
photo.Url = await storageRepo.CreateFileAsync(newPhotoFileName, photo.PhotoData);
age = detectedFaces[0].FaceAttributes.Age;
gender = detectedFaces[0].FaceAttributes.Gender;
var persistedFace = await AddVisitorPhotoAsync(identifiedVisitor.GroupId, identifiedVisitor.PersonDetails.PersonId, photo.Url, detectedFaces[0].FaceRectangle);
//Update photo details
photo.IsSaved = true;
photo.Name = newPhotoFileName;
photo.Status = "Saved";
}
}
}
await identifiedVisitorRepo.UpdateAsync(identifiedVisitor);
return identifiedVisitor;
}
public async Task<List<IdentifiedVisitor>> GetAllIdentifiedVisitorsAsync()
{
return await identifiedVisitorRepo.GetAllAsync();
}
public async Task<ResultStatus> DeleteVisitorAsync(string visitorId, string groupId)
{
var result = new ResultStatus();
var visitor = await identifiedVisitorRepo.GetByIdAsync(visitorId);
if (visitor != null)
{
await FaceServiceHelper.DeletePersonAsync(groupId, visitor.PersonDetails.PersonId);
await identifiedVisitorRepo.DeleteAsync(visitor);
result.StatusCode = "0";
result.Message = $"Successfully deleted visitor ({visitor.Id})";
result.IsSuccessful = true;
}
else
{
result.StatusCode = "1";
result.Message = $"Visitor id ({visitor.Id}) not found!";
result.IsSuccessful = false;
}
return result;
}
private async Task<Stream> GetPhotoStream()
{
return new MemoryStream(photoData);
}
}
}
| 44,139
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.