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/meeh420/coinffeine/blob/master/coinffeine-gui/src/main/scala/com/coinffeine/gui/application/operations/OperationsView.scala
Github Open Source
Open Source
MIT
2,014
coinffeine
meeh420
Scala
Code
34
110
package com.coinffeine.gui.application.operations import scalafx.scene.control.Label import scalafx.scene.layout.{Pane, StackPane} import com.coinffeine.gui.application.ApplicationView class OperationsView extends ApplicationView { override def name: String = "Operations" override def centerPane: Pane = new StackPane { content = Seq(new Label("Operations")) } }
10,970
https://github.com/torproject/metrics-lib/blob/master/src/main/java/org/torproject/descriptor/package-info.java
Github Open Source
Open Source
Apache-2.0
2,022
metrics-lib
torproject
Java
Code
434
968
/* Copyright 2016--2020 The Tor Project * See LICENSE for licensing information */ /** * Interfaces and essential classes for obtaining and processing Tor * descriptors. * * <p>This package contains all relevant interfaces and * classes that an application would need to use this library. * Applications are strongly discouraged from accessing types from the * implementation package ({@code org.torproject.descriptor.impl}) * directly, because those may change without prior notice.</p> * * <p>Interfaces and classes in this package can be grouped into * general-purpose types to obtain and process any type of descriptor and * descriptors produced by different components of the Tor network:</p> * * <ol> * <li>General-purpose types comprise * {@link org.torproject.descriptor.DescriptorSourceFactory} which is the * main entry point into using this library. This factory is used to * create the descriptor sources for obtaining remote descriptor data * ({@link org.torproject.descriptor.DescriptorCollector}) and descriptor * sources for processing local descriptor data * ({@link org.torproject.descriptor.DescriptorReader} and * {@link org.torproject.descriptor.DescriptorParser}). General-purpose * types also include the superinterface for all provided descriptors * ({@link org.torproject.descriptor.Descriptor}).</li> * * <li>The first group of descriptors is published by relays and servers * in the Tor network. These interfaces include server descriptors * ({@link org.torproject.descriptor.ServerDescriptor} with subinterfaces * {@link org.torproject.descriptor.RelayServerDescriptor} and * {@link org.torproject.descriptor.BridgeServerDescriptor}), extra-info * descriptors ({@link org.torproject.descriptor.ExtraInfoDescriptor} with * subinterfaces * {@link org.torproject.descriptor.RelayExtraInfoDescriptor} and * {@link org.torproject.descriptor.BridgeExtraInfoDescriptor}), * microdescriptors which are derived from server descriptors by the * directory authorities * ({@link org.torproject.descriptor.Microdescriptor}), and helper types * for parts of the aforementioned descriptors * ({@link org.torproject.descriptor.BandwidthHistory}).</li> * * <li>The second group of descriptors is generated by authoritative * directory servers that form an opinion about relays and bridges in the * Tor network. These include descriptors specified in version 3 of the * directory protocol * ({@link org.torproject.descriptor.RelayNetworkStatusConsensus}, * {@link org.torproject.descriptor.RelayNetworkStatusVote}, * {@link org.torproject.descriptor.DirectoryKeyCertificate}, and helper * types for descriptor parts * {@link org.torproject.descriptor.DirSourceEntry}, * {@link org.torproject.descriptor.NetworkStatusEntry}, and * {@link org.torproject.descriptor.DirectorySignature}), descriptors from * earlier directory protocol version 2 * ({@link org.torproject.descriptor.RelayNetworkStatus}) and version 1 * ({@link org.torproject.descriptor.RelayDirectory} and * {@link org.torproject.descriptor.RouterStatusEntry}), as well as * descriptors published by the bridge authority and sanitized by the * CollecTor service * ({@link org.torproject.descriptor.BridgeNetworkStatus}).</li> * * <li>The third group of descriptors is created by auxiliary services * connected to the Tor network rather than by the Tor software. This * group comprises descriptors by the bridge distribution service BridgeDB * ({@link org.torproject.descriptor.BridgePoolAssignment}), the exit list * service TorDNSEL ({@link org.torproject.descriptor.ExitList}), the * performance measurement service Torperf * ({@link org.torproject.descriptor.TorperfResult}), and sanitized access logs * of Tor's web servers * ({@link org.torproject.descriptor.WebServerAccessLog}).</li> * </ol> * * @since 1.0.0 */ package org.torproject.descriptor;
27,897
https://github.com/liyanone/ci-android/blob/master/app/src/main/java/net/squanchy/support/lang/Predicate.java
Github Open Source
Open Source
Apache-2.0
null
ci-android
liyanone
Java
Code
17
44
package net.squanchy.support.lang; public interface Predicate<T> extends Func1<T, Boolean> { // Just a convenience subclass of Func1 }
44,351
https://github.com/haboy52581/alcor/blob/master/services/api_gateway/src/main/java/com/futurewei/alcor/apigateway/proxies/VpcManagerServiceProxy.java
Github Open Source
Open Source
Apache-2.0
null
alcor
haboy52581
Java
Code
294
1,105
/* Copyright 2019 The Alcor Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.futurewei.alcor.apigateway.proxies; import com.futurewei.alcor.apigateway.vpc.VpcWebDestinations; import com.futurewei.alcor.common.entity.ResponseId; import com.futurewei.alcor.web.entity.vpc.VpcWebJson; import com.futurewei.alcor.web.exception.VpcNotFoundException; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; import java.util.UUID; @Deprecated //@Service public class VpcManagerServiceProxy { private VpcWebDestinations webDestinations; private WebClient webClient; public VpcManagerServiceProxy(VpcWebDestinations destinations, WebClient vpcManagerWebClient) { this.webDestinations = destinations; this.webClient = vpcManagerWebClient; } public Mono<VpcWebJson> findVpcById(String projectId, String vpcId) { Mono<ClientResponse> response = webClient .get() .uri(webDestinations.getVpcManagerServiceUrl() + "/project/{projectId}/vpcs/{vpcId}", projectId, vpcId) .exchange(); return response.flatMap(resp -> { switch (resp.statusCode()) { case OK: return resp.bodyToMono(VpcWebJson.class); case NOT_FOUND: return Mono.error(new VpcNotFoundException()); default: return Mono.error(new RuntimeException("Unknown" + resp.statusCode())); } }); } public Mono<VpcWebJson> createVpc(UUID projectId, Mono<VpcWebJson> newVpcJson) { Mono<ClientResponse> response = webClient .post() .uri(webDestinations.getVpcManagerServiceUrl() + "/project/{projectId}/vpcs", projectId) .body(newVpcJson, VpcWebJson.class) .exchange(); return response.flatMap(resp -> { switch (resp.statusCode()) { case CREATED: return resp.bodyToMono(VpcWebJson.class); case NOT_FOUND: return Mono.error(new VpcNotFoundException()); default: return Mono.error(new RuntimeException("Unknown" + resp.statusCode())); } }); } public Mono<ResponseId> deleteVpcById(String projectId, String vpcId) { Mono<ClientResponse> response = webClient .delete() .uri(webDestinations.getVpcManagerServiceUrl() + "/project/{projectId}/vpcs/{vpcId}", projectId, vpcId) .exchange(); return response.flatMap(resp -> { switch (resp.statusCode()) { case OK: return resp.bodyToMono(ResponseId.class); case NOT_FOUND: return Mono.error(new VpcNotFoundException()); default: return Mono.error(new RuntimeException("Unknown" + resp.statusCode())); } }); } public Mono<String> getHealthStatus() { Mono<ClientResponse> healthStatusResponse = webClient .get() .uri(webDestinations.getVpcManagerServiceUrl() + "/actuator/health") .exchange(); return healthStatusResponse.flatMap(resp -> { switch (resp.statusCode()) { case OK: return resp.bodyToMono(String.class); default: return Mono.error(new RuntimeException("Unknown" + resp.statusCode())); } }); } }
19,961
https://github.com/vllab-under/attention/blob/master/mmdetection/mmdet/models/necks/attention_module/context_weight_block.py
Github Open Source
Open Source
Apache-2.0
2,021
attention
vllab-under
Python
Code
274
986
import torch from mmcv.cnn import constant_init, kaiming_init from torch import nn import matplotlib.pyplot as plt def last_zero_init(m): if isinstance(m, nn.Sequential): constant_init(m[-1], val=0) else: constant_init(m, val=0) class ContextWeightBlcok(nn.Module): def __init__(self, inplanes, levels, ratio=1. / 4, pooling_type='att', weight_type=False, eps=0.0001, viz=False): super(ContextWeightBlcok, self).__init__() assert pooling_type in ['avg', 'att'] assert levels > 0, 'at least one feature should be used' assert weight_type in [False, 'before_attention', 'before_sigmoid', 'after_attention'] self.inplanes = inplanes self.ratio = ratio self.planes = int(inplanes * ratio) self.pooling_type = pooling_type self.levels = levels self.weight_type = weight_type self.eps = eps self.relu = nn.ReLU(inplace=False) self.viz = viz if pooling_type == 'att': self.conv_mask = nn.Conv2d(inplanes, 1, kernel_size=1) self.softmax = nn.Softmax(dim=2) else: self.avg_pool = nn.AdaptiveAvgPool2d(1) self.channel_add_conv = nn.Sequential( nn.Conv2d(self.inplanes, self.planes, kernel_size=1), nn.LayerNorm([self.planes, 1, 1]), nn.ReLU(inplace=True), # yapf: disable nn.Conv2d(self.planes, self.inplanes // self.levels, kernel_size=1)) self.reset_parameters() def reset_parameters(self): if self.pooling_type == 'att': kaiming_init(self.conv_mask, mode='fan_in') self.conv_mask.inited = True if self.channel_add_conv is not None: last_zero_init(self.channel_add_conv) def spatial_pool(self, x): batch, channel, height, width = x.size() if self.pooling_type == 'att': input_x = x # [N, C, H * W] input_x = input_x.view(batch, channel, height * width) # [N, 1, C, H * W] input_x = input_x.unsqueeze(1) # [N, 1, H, W] context_mask = self.conv_mask(x) # [N, 1, H * W] context_mask = context_mask.view(batch, 1, height * width) # [N, 1, H * W] context_mask = self.softmax(context_mask) # [N, 1, H * W, 1] context_mask = context_mask.unsqueeze(-1) # [N, 1, C, 1] context = torch.matmul(input_x, context_mask) # [N, C, 1, 1] context = context.view(batch, channel, 1, 1) else: # [N, C, 1, 1] context = self.avg_pool(x) return context def forward(self, x): x = torch.cat(x, dim=1) context = self.spatial_pool(x) # [N, C, 1, 1] add_maps = self.channel_add_conv(context) return add_maps
49,717
https://github.com/JustinZuidgeest/Javascript-Memory-Practicum/blob/master/vuejwt/src/components/Memory/Tile.vue
Github Open Source
Open Source
MIT
null
Javascript-Memory-Practicum
JustinZuidgeest
Vue
Code
85
312
<template> <td v-on:click='$emit("cardClicked", data)' v-bind:class="data.class"> {{tileChar}} </td> </template> <script> export default { name: 'Tile', props: ["data"], data: function() { return { } }, computed: { tileChar: function(){ let char = ""; if(this.data.class === "inactive"){ char = this.data.backside; }else if(this.data.class === "active" || this.data.class === "found"){ char = this.data.frontside; } return char; }, }, } </script> <style scoped> td.inactive { cursor: pointer; background-color: var(--inactive-color); border-radius: 10px; } td.active { cursor: pointer; background-color: var(--active-color); border-radius: 10px; } td.found { background-color: var(--found-color); cursor: default; border-radius: 10px; } </style>
30,654
https://github.com/christRescues/portfolio/blob/master/TODO/UtilityProjects/GameOfLife/Reset.js
Github Open Source
Open Source
MIT
2,017
portfolio
christRescues
JavaScript
Code
47
140
import React from 'react' import Radium from 'radium' const styles = { button: { marginRight: '20px', cursor: 'pointer', } } let Reset = ({reset}) => { return ( <button style={styles.button} className="btn btn-info" onClick={reset}>&#8635; </button> ) } Reset.propTypes = { reset: React.PropTypes.func.isRequired, } export default Reset = Radium(Reset)
34,214
https://github.com/finphie/FToolkit/blob/master/Source/FToolkit.Diagnostics/Extensions/BufferWriterExtensions.cs
Github Open Source
Open Source
MIT
null
FToolkit
finphie
C#
Code
47
257
using System.Buffers; using System.Runtime.CompilerServices; namespace FToolkit.Diagnostics.Extensions; /// <summary> /// <see cref="IBufferWriter{T}"/>を実装オブジェクト関連の拡張メソッド集です。 /// </summary> static class BufferWriterExtensions { /// <summary> /// <paramref name="bufferWriter"/>に<paramref name="value"/>と改行を書き込みます。 /// </summary> /// <param name="bufferWriter"><see cref="char"/>データを書き込むことができる出力シンク</param> /// <param name="value"><paramref name="value"/>に書き込む値</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteLine(this IBufferWriter<char> bufferWriter, ReadOnlySpan<char> value) { bufferWriter.Write(value); bufferWriter.Write("\n"); } }
27,364
https://github.com/AshHipgrave/SQLBackup/blob/master/src/SQL Backup/Backup/Settings/SettingsReader.cs
Github Open Source
Open Source
Unlicense
2,015
SQLBackup
AshHipgrave
C#
Code
123
401
using System; using System.Data.SqlServerCe; namespace Backup { public class SettingsReader { private static readonly string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\SQL Backup\\"; private static readonly string dataFilePath = appDataPath + "SxSettings.sdf"; public static string QuerySetting(string SettingName) { string settingValue = null; string connectionString = String.Format("Data Source={0};Persist Security Info=False;", dataFilePath); string queryString = String.Format("SELECT SET_VALUE FROM TH_SETTINGS WHERE SET_NAME = '{0}'", SettingName); SqlCeConnection sqlConnection = new SqlCeConnection(connectionString); SqlCeCommand sqlCommand = new SqlCeCommand(queryString, sqlConnection); try { sqlConnection.Open(); var cmdResult = sqlCommand.ExecuteScalar(); if (cmdResult != DBNull.Value) settingValue = (string) cmdResult; } catch (SqlCeException Ex) { LogEvent.Error(String.Format("Failed to access Settings Database. The error returned was:\r\n\r\n {0} \r\n\r\nThe backup will not continue", Ex)); Environment.Exit(1); } sqlConnection.Close(); if (SettingName.Contains("Password") && settingValue != null) return System.Text.Encoding.ASCII.GetString(Convert.FromBase64String(settingValue)); return settingValue; } } }
43,422
https://github.com/jonas/cucumber-jvm/blob/master/examples/java-webbit-websockets-selenium/src/test/java/cucumber/examples/java/websockets/TemperatureStepdefs.java
Github Open Source
Open Source
MIT
2,012
cucumber-jvm
jonas
Java
Code
70
319
package cucumber.examples.java.websockets; import cucumber.annotation.en.Given; import cucumber.annotation.en.Then; import cucumber.annotation.en.When; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import static org.junit.Assert.assertEquals; public class TemperatureStepdefs { private final WebDriver webDriver; public TemperatureStepdefs(SharedDriver webDriver) { this.webDriver = webDriver; } @Given("^I am on the front page$") public void i_am_on_the_front_page() { webDriver.get("http://localhost:" + ServerHooks.PORT); } @When("^I enter (.+) Celcius$") public void i_enter_Celcius(double celcius) { webDriver.findElement(By.id("celcius")).sendKeys(String.valueOf(celcius)); } @Then("^I should see (.+) Fahrenheit$") public void i_should_see_Fahrenheit(double fahrenheit) { assertEquals(String.valueOf(fahrenheit), webDriver.findElement(By.id("fahrenheit")).getAttribute("value")); } }
11,167
https://github.com/uk-gov-mirror/alphagov.notifications-paas-autoscaler/blob/master/main.py
Github Open Source
Open Source
MIT
null
alphagov.notifications-paas-autoscaler
uk-gov-mirror
Python
Code
18
95
import logging import sys from app.autoscaler import Autoscaler logging.basicConfig( level=logging.WARNING, handlers=[ logging.FileHandler('/home/vcap/logs/app.log'), logging.StreamHandler(sys.stdout), ]) autoscaler = Autoscaler() autoscaler.run()
11,932
https://github.com/Georgette/fastlane-register-devices/blob/master/test/options.js
Github Open Source
Open Source
MIT
2,020
fastlane-register-devices
Georgette
JavaScript
Code
260
888
var proxyquire = require('proxyquire') var test = require('tape') var sinon = require('sinon') var exec = sinon.stub().callsArgWith(2, null, '', '') var writeFile = sinon.stub().callsArgWith(2, null) var mkdirp = sinon.stub().callsArgWith(1, null) var child_process = { exec } var fs = { writeFile } var register = proxyquire('..', { child_process, fs, mkdirp }) test('missing devices option throws error', (t) => { t.plan(1) exec.reset() writeFile.reset() mkdirp.reset() t.throws(() => { register({}) }, 'missing devices option throws error') }) test('accepts callback', (t) => { t.plan(1) exec.reset() writeFile.reset() mkdirp.reset() register({devices: {}}, () => { t.pass('function called') }) }) test('accepts no callback', (t) => { t.plan(1) exec.reset() writeFile.reset() mkdirp.reset() t.doesNotThrow(() => { register({devices: {}}) }) }) test('accepts a runtime option of timeout', (t) => { t.plan(1) exec.reset() writeFile.reset() mkdirp.reset() register({ devices: {}, timeout: 1 }, () => { t.ok(exec.calledWithMatch('fastlane register', { timeout: 1 }), 'called with timeout runtime option') }) }) test('accepts a runtime option of password', (t) => { t.plan(1) exec.reset() writeFile.reset() mkdirp.reset() register({ devices: {}, password: 'password' }, () => { t.ok(exec.calledWithMatch('fastlane register', { env: { FASTLANE_PASSWORD: 'password' } }), 'called with password runtime option') }) }) test('creates a Fastfile and calls fastlane register', (t) => { t.plan(7) exec.reset() writeFile.reset() mkdirp.reset() register({ devices: { 'test1': '123456789', 'test2': '987654321' }, user : 'gege', teamId: 'teamA' }, (_, stdout, stderr) => { var writeFileArgs = writeFile.getCall(0).args var fastfilePath = writeFileArgs[0] var fastfileContent = writeFileArgs[1] t.ok(fastfilePath.match(/\/fastlane\/Fastfile$/.match), 'writes to Fastfile') t.ok(fastfileContent.match(/lane :register/), 'register lane exists') t.ok(fastfileContent.match(/"test1" => "123456789"/), 'device1 included') t.ok(fastfileContent.match(/"test2" => "987654321"/), 'device2 included') t.ok(fastfileContent.match(/username: "gege"/), 'username included') t.ok(fastfileContent.match(/team_id: "teamA"/), 'team included') t.ok(exec.calledWith('fastlane register'), 'fastlane register executed') }) })
47,156
https://github.com/mattnischan/evelib/blob/master/EveLib.EveCrest/Models/Resources/Market/MarketOrder.cs
Github Open Source
Open Source
Apache-2.0
2,015
evelib
mattnischan
C#
Code
340
871
// *********************************************************************** // Assembly : EveLib.EveCrest // Author : Lars Kristian // Created : 12-18-2014 // // Last Modified By : Lars Kristian // Last Modified On : 12-18-2014 // *********************************************************************** // <copyright file="MarketOrder.cs" company=""> // Copyright (c) . All rights reserved. // </copyright> // <summary></summary> // *********************************************************************** using System; using System.Runtime.Serialization; using eZet.EveLib.EveCrestModule.Models.Links; namespace eZet.EveLib.EveCrestModule.Models.Resources.Market { /// <summary> /// Class MarketOrder. /// </summary> [DataContract] public class MarketOrder : LinkedEntity<NotImplemented> { /// <summary> /// Gets or sets a value indicating whether this <see cref="MarketOrder" /> is buy. /// </summary> /// <value><c>true</c> if buy; otherwise, <c>false</c>.</value> [DataMember(Name = "buy")] public bool Buy { get; set; } /// <summary> /// Gets or sets the duration. /// </summary> /// <value>The duration.</value> [DataMember(Name = "duration")] public int Duration { get; set; } /// <summary> /// Gets or sets the issued. /// </summary> /// <value>The issued.</value> [DataMember(Name = "issued")] public DateTime Issued { get; set; } /// <summary> /// Gets or sets the location. /// </summary> /// <value>The location.</value> [DataMember(Name = "location")] public LinkedEntity<NotImplemented> Location { get; set; } /// <summary> /// Gets or sets the minimum volume. /// </summary> /// <value>The minimum volume.</value> [DataMember(Name = "minVolume")] public int MinVolume { get; set; } /// <summary> /// Gets or sets the volume entered. /// </summary> /// <value>The volume entered.</value> [DataMember(Name = "volumeEntered")] public int VolumeEntered { get; set; } /// <summary> /// Gets or sets the price. /// </summary> /// <value>The price.</value> [DataMember(Name = "price")] public double Price { get; set; } /// <summary> /// Gets or sets the range. /// </summary> /// <value>The range.</value> [DataMember(Name = "range")] public string Range { get; set; } /// <summary> /// Gets or sets the type. /// </summary> /// <value>The type.</value> [DataMember(Name = "type")] public LinkedEntity<ItemType> Type { get; set; } /// <summary> /// Gets or sets the volume. /// </summary> /// <value>The volume.</value> [DataMember(Name = "volume")] public int Volume { get; set; } /// Gets or sets the order identifier. /// /// The identifier. [DataMember(Name = "id")] public new long Id { get; set; } } }
24,983
https://github.com/pointfreeco/composable-core-motion/blob/master/Sources/ComposableCoreMotion/HeadphoneMotionManager/HeadphoneMotionManagerInterface.swift
Github Open Source
Open Source
MIT
2,022
composable-core-motion
pointfreeco
Swift
Code
405
1,058
import ComposableArchitecture import CoreMotion /// A wrapper around Core Motion's `CMHeadphoneMotionManager` that exposes its functionality /// through effects and actions, making it easy to use with the Composable Architecture, and easy /// to test. @available(iOS 14, *) @available(macCatalyst 14, *) @available(macOS, unavailable) @available(tvOS, unavailable) @available(watchOS 7, *) public struct HeadphoneMotionManager { /// Actions that correspond to `CMHeadphoneMotionManagerDelegate` methods. /// /// See `CMHeadphoneMotionManagerDelegate` for more information. public enum Action: Equatable { case didConnect case didDisconnect } /// Creates a headphone motion manager. /// /// A motion manager must be first created before you can use its functionality, such as /// starting device motion updates or accessing data directly from the manager. public func create(id: AnyHashable) -> Effect<Action, Never> { self.create(id) } /// Destroys a currently running headphone motion manager. /// /// In is good practice to destroy a headphone motion manager once you are done with it, such as /// when you leave a screen or no longer need motion data. public func destroy(id: AnyHashable) -> Effect<Never, Never> { self.destroy(id) } /// The latest sample of device-motion data. public func deviceMotion(id: AnyHashable) -> DeviceMotion? { self.deviceMotion(id) } /// A Boolean value that determines whether the app is receiving updates from the device-motion /// service. public func isDeviceMotionActive(id: AnyHashable) -> Bool { self.isDeviceMotionActive(id) } /// A Boolean value that indicates whether the device-motion service is available on the device. public func isDeviceMotionAvailable(id: AnyHashable) -> Bool { self.isDeviceMotionAvailable(id) } /// Starts device-motion updates without a block handler. /// /// Returns a long-living effect that emits device motion data each time the headphone motion /// manager receives a new value. public func startDeviceMotionUpdates( id: AnyHashable, to queue: OperationQueue = .main ) -> Effect<DeviceMotion, Error> { self.startDeviceMotionUpdates(id, queue) } /// Stops device-motion updates. public func stopDeviceMotionUpdates(id: AnyHashable) -> Effect<Never, Never> { self.stopDeviceMotionUpdates(id) } public init( create: @escaping (AnyHashable) -> Effect<Action, Never>, destroy: @escaping (AnyHashable) -> Effect<Never, Never>, deviceMotion: @escaping (AnyHashable) -> DeviceMotion?, isDeviceMotionActive: @escaping (AnyHashable) -> Bool, isDeviceMotionAvailable: @escaping (AnyHashable) -> Bool, startDeviceMotionUpdates: @escaping (AnyHashable, OperationQueue) -> Effect<DeviceMotion, Error>, stopDeviceMotionUpdates: @escaping (AnyHashable) -> Effect<Never, Never> ) { self.create = create self.destroy = destroy self.deviceMotion = deviceMotion self.isDeviceMotionActive = isDeviceMotionActive self.isDeviceMotionAvailable = isDeviceMotionAvailable self.startDeviceMotionUpdates = startDeviceMotionUpdates self.stopDeviceMotionUpdates = stopDeviceMotionUpdates } var create: (AnyHashable) -> Effect<Action, Never> var destroy: (AnyHashable) -> Effect<Never, Never> var deviceMotion: (AnyHashable) -> DeviceMotion? var isDeviceMotionActive: (AnyHashable) -> Bool var isDeviceMotionAvailable: (AnyHashable) -> Bool var startDeviceMotionUpdates: (AnyHashable, OperationQueue) -> Effect<DeviceMotion, Error> var stopDeviceMotionUpdates: (AnyHashable) -> Effect<Never, Never> }
21,115
https://github.com/laikuaut/AOJ/blob/master/Introduction_to_Programming/ITP1_1_B/Main.d
Github Open Source
Open Source
MIT
2,016
AOJ
laikuaut
D
Code
18
60
import std.stdio; import std.string; import std.conv; import std.math; void main() { auto num = readln().chomp().to!int(); writeln(pow(num, 3)); }
5,523
https://github.com/mrjojo11/malpaca-pub/blob/master/scripts/filtered_dataset_creation/filtered_dataset_creation.py
Github Open Source
Open Source
MIT
null
malpaca-pub
mrjojo11
Python
Code
3,025
11,249
import csv import glob import math import os import sys from random import random, seed from timeit import default_timer as timer import time from statistics import mean from pathlib import Path import networkx as nx import numpy as np from scapy.layers.inet import IP, UDP, TCP, ICMP from scapy.layers.ntp import NTPInfoIfStatsIPv4, NTPInfoIfStatsIPv6 from scapy.utils import PcapWriter, PcapReader import tkinter as tk from tkinter import filedialog import zat from zat.log_to_dataframe import LogToDataFrame import pandas as pd import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties from matplotlib.pyplot import cm import matplotlib.transforms as mtrans class Filtered_Dataset_Creation(): @staticmethod def restart_filter_connections_based_on_netflow_into_separate_files_max_length(threshold, max_length, path_to_iot_scenarios_folder, folder_to_restart, experiment_name): threshold = threshold path_to_iot_scenarios_folder = path_to_iot_scenarios_folder folder_to_restart = folder_to_restart experiment_name = experiment_name new_folder_path = folder_to_restart to_skip_scenario = "CTU-IoT-Malware-Capture-60-1" folders = sorted([f.path for f in os.scandir(path_to_iot_scenarios_folder) if f.is_dir()]) folders = list(map(lambda x: (x, str(os.path.basename(x)).strip()), folders)) scan_file_order_path = folder_to_restart + "/" + "scan_order.txt" with open(scan_file_order_path, 'r') as inputfile: scanned_files = inputfile.readlines() scanned_files_list = [x.strip() for x in scanned_files] scanned_files_set = set() for file in scanned_files_list: scanned_files_set.add(file.split(",")[0]) filtered_folders = [] folders_still_to_scan = [] for path, folder in folders: if folder not in scanned_files_set and folder != to_skip_scenario: folders_still_to_scan.append(path) folders = folders_still_to_scan scan_file_order_path = new_folder_path + "/" + "scan_order.txt" for index, folder in enumerate(folders): scenario_name = str(os.path.basename(folder)).strip() scenario_folder_storage = new_folder_path + "/" + scenario_name os.mkdir(scenario_folder_storage) print("Scenario: " + str(index + 1) + "/" + str(len(folders))) print("Scenario name: " + scenario_name) connections = {} pcap_files = glob.glob(folder + "/*.pcap") for index_file, pcap_file in enumerate(pcap_files): file_name = str(os.path.basename(pcap_file)).strip() file_folder = scenario_folder_storage + "/" + file_name os.mkdir(file_folder) path_to_pcap_file = pcap_file print("File: " + str(index_file + 1) + "/" + str(len(pcap_files))) print("File name : " + file_name) with open(scan_file_order_path, 'a') as scan_file: scan_file.write(scenario_name + "," + file_name + "\n") scan_file.close() count_file_name = file_name + "_count.txt" count_file_path = path_to_iot_scenarios_folder + "/" + scenario_name + "/" + count_file_name count_file_exist = os.path.exists(count_file_path) write_counter = 1 appended_packet_counter = 0 if count_file_exist: with open(count_file_path, 'r') as count_file: total_number_packets = int(count_file.readline()) count_file.close() start_time = time.time() last_packet = None last_packet_src = None last_packet_dst = None counted_packets = 0 log_file_path = file_folder + "/" + file_name + "_log.txt" new_file_path = file_folder + "/" + file_name + "_" + experiment_name + ".pcap" with PcapReader(path_to_pcap_file) as packets: for packet_count, packet in enumerate(packets): counted_packets = packet_count + 1 if IP in packet: packet_string = packet.show(dump=True) packet_for_print = packet_string packet_string = packet_string.split("\n") packet_string = [x.replace(" ", "") for x in packet_string] current_layer = "none" packet_dic = {} for line in packet_string: if len(line) > 0: if line[0] == '#': new_layer = line.split('[')[1].split(']')[0] current_layer = new_layer packet_dic[current_layer] = {} elif (line[0] != '\\') & (line[0] != '|'): key = line.split("=")[0] value = line.split("=")[1] packet_dic[current_layer][key] = value src_ip = packet_dic["IP"]["src"] dst_ip = packet_dic["IP"]["dst"] ip_protocol = packet_dic["IP"]["proto"].upper() if ip_protocol == "UDP" and "UDP" in packet_dic: src_port = packet_dic["UDP"]["sport"] dst_port = packet_dic["UDP"]["dport"] elif ip_protocol == "TCP" and "TCP" in packet_dic: src_port = packet_dic["TCP"]["sport"] dst_port = packet_dic["TCP"]["dport"] elif ip_protocol == "ICMP" and "ICMP" in packet_dic: src_port = 0 dst_port = str(packet_dic["ICMP"]["type"]) + "/" + str(packet_dic["ICMP"]["code"]) else: src_port = 0 dst_port = 0 ip_tos = packet_dic["IP"]["tos"] last_packet_src = src_ip last_packet_dst = dst_ip last_packet = packet if ( src_ip, dst_ip, ip_protocol, src_port, dst_port, ip_protocol, ip_tos) not in connections: connections[(src_ip, dst_ip, ip_protocol, src_port, dst_port, ip_protocol, ip_tos)] = [ packet] appended_packet_counter = appended_packet_counter + 1 else: connections[ (src_ip, dst_ip, ip_protocol, src_port, dst_port, ip_protocol, ip_tos)].append( packet) appended_packet_counter = appended_packet_counter + 1 if appended_packet_counter == 500000: print("Write " + str(write_counter)) for address, packets_value in connections.items(): amount = len(packets_value) if amount >= threshold: pktdump = PcapWriter(new_file_path, append=True, sync=True) for index, packet in enumerate(packets_value): if index < max_length: pktdump.write(packet) else: break pktdump.close() with open(log_file_path, 'w') as log_file: log_file.write("last_packet_count:" + str(packet_count) + "\n") log_file.write("last_packet_src:" + last_packet_src + "\n") log_file.write("last_packet_dst:" + last_packet_dst + "\n") log_file.write("last_packet:" + str(last_packet) + "\n") log_file.close() connections.clear() appended_packet_counter = 0 print("Write " + str(write_counter) + " Finish") write_counter = write_counter + 1 if count_file_exist: end_time = time.time() passed_time = end_time - start_time progress_percent = int((counted_packets / total_number_packets) * 100) packets_remaining = total_number_packets - counted_packets average_time_packet = counted_packets / passed_time time_remaining = packets_remaining * average_time_packet time_remaining_minutes = round((time_remaining / 60), 2) print("Progress: " + str(progress_percent) + " %") print("Time remaining: " + str(time_remaining_minutes) + " minutes") packets.close() if (len(connections) > 0): print("Write " + str(write_counter)) for address, packets_value in connections.items(): amount = len(packets_value) if amount >= threshold: pktdump = PcapWriter(new_file_path, append=True, sync=True) for index, packet in enumerate(packets_value): if index < max_length: pktdump.write(packet) else: break connections.clear() with open(log_file_path, 'w') as log_file: log_file.write("last_packet_count:end\n") log_file.write("last_packet_src:" + last_packet_src + "\n") log_file.write("last_packet_dst:" + last_packet_dst + "\n") log_file.write("last_packet:" + str(last_packet) + "\n") log_file.close() print("Write " + str(write_counter) + " Finish") if (count_file_exist == False): with open(count_file_path, 'w') as output_file: output_file.write(str(counted_packets)) output_file.close() sys.exit() @staticmethod def filter_connections_based_on_netflow_into_separate_files_max_length(threshold, max_length, path_to_iot_scenarios_folder, folder_to_store, experiment_name): threshold = threshold path_to_iot_scenarios_folder = path_to_iot_scenarios_folder folder_to_store = folder_to_store experiment_name = experiment_name to_skip_scenario = "CTU-IoT-Malware-Capture-60-1" new_folder_path = folder_to_store + "/" + experiment_name os.mkdir(new_folder_path) folders = sorted([f.path for f in os.scandir(path_to_iot_scenarios_folder) if f.is_dir()]) folders = list(map(lambda x: (x, str(os.path.basename(x)).strip()), folders)) filtered_folders = [] for path, folder in folders: if folder != to_skip_scenario: filtered_folders.append(path) folders = filtered_folders scan_file_order_path = new_folder_path + "/" + "scan_order.txt" for index, folder in enumerate(folders): scenario_name = str(os.path.basename(folder)).strip() scenario_folder_storage = new_folder_path + "/" + scenario_name os.mkdir(scenario_folder_storage) print("Scenario: " + str(index + 1) + "/" + str(len(folders))) print("Scenario name: " + scenario_name) connections = {} pcap_files = glob.glob(folder + "/*.pcap") for index_file, pcap_file in enumerate(pcap_files): file_name = str(os.path.basename(pcap_file)).strip() file_folder = scenario_folder_storage + "/" + file_name os.mkdir(file_folder) path_to_pcap_file = pcap_file print("File: " + str(index_file + 1) + "/" + str(len(pcap_files))) print("File name : " + file_name) with open(scan_file_order_path, 'a') as scan_file: scan_file.write(scenario_name + "," + file_name + "\n") scan_file.close() count_file_name = file_name + "_count.txt" count_file_path = path_to_iot_scenarios_folder + "/" + scenario_name + "/" + count_file_name count_file_exist = os.path.exists(count_file_path) write_counter = 1 appended_packet_counter = 0 if count_file_exist: with open(count_file_path, 'r') as count_file: total_number_packets = int(count_file.readline()) count_file.close() start_time = time.time() last_packet = None last_packet_src = None last_packet_dst = None counted_packets = 0 log_file_path = file_folder + "/" + file_name + "_log.txt" new_file_path = file_folder + "/" + file_name + "_" + experiment_name + ".pcap" with PcapReader(path_to_pcap_file) as packets: for packet_count, packet in enumerate(packets): counted_packets = packet_count + 1 if IP in packet: packet_string = packet.show(dump=True) packet_for_print = packet_string packet_string = packet_string.split("\n") packet_string = [x.replace(" ", "") for x in packet_string] current_layer = "none" packet_dic = {} for line in packet_string: if len(line) > 0: if line[0] == '#': new_layer = line.split('[')[1].split(']')[0] current_layer = new_layer packet_dic[current_layer] = {} elif (line[0] != '\\') & (line[0] != '|'): key = line.split("=")[0] value = line.split("=")[1] packet_dic[current_layer][key] = value src_ip = packet_dic["IP"]["src"] dst_ip = packet_dic["IP"]["dst"] ip_protocol = packet_dic["IP"]["proto"].upper() if ip_protocol == "UDP" and "UDP" in packet_dic: src_port = packet_dic["UDP"]["sport"] dst_port = packet_dic["UDP"]["dport"] elif ip_protocol == "TCP" and "TCP" in packet_dic: src_port = packet_dic["TCP"]["sport"] dst_port = packet_dic["TCP"]["dport"] elif ip_protocol == "ICMP" and "ICMP" in packet_dic: src_port = 0 dst_port = str(packet_dic["ICMP"]["type"]) + "/" + str(packet_dic["ICMP"]["code"]) else: src_port = 0 dst_port = 0 ip_tos = packet_dic["IP"]["tos"] last_packet_src = src_ip last_packet_dst = dst_ip last_packet = packet if (src_ip, dst_ip, ip_protocol, src_port, dst_port, ip_protocol, ip_tos) not in connections: connections[(src_ip, dst_ip, ip_protocol, src_port, dst_port, ip_protocol, ip_tos)] = [packet] appended_packet_counter = appended_packet_counter + 1 else: connections[(src_ip, dst_ip, ip_protocol, src_port, dst_port, ip_protocol, ip_tos)].append(packet) appended_packet_counter = appended_packet_counter + 1 if appended_packet_counter == 500000: print("Write " + str(write_counter)) for address, packets_value in connections.items(): amount = len(packets_value) if amount >= threshold: pktdump = PcapWriter(new_file_path, append=True, sync=True) for index, packet in enumerate(packets_value): if index < max_length: pktdump.write(packet) else: break pktdump.close() with open(log_file_path, 'w') as log_file: log_file.write("last_packet_count:" + str(packet_count) + "\n") log_file.write("last_packet_src:" + last_packet_src + "\n") log_file.write("last_packet_dst:" + last_packet_dst + "\n") log_file.write("last_packet:" + str(last_packet) + "\n") log_file.close() connections.clear() appended_packet_counter = 0 print("Write " + str(write_counter) + " Finish") write_counter = write_counter + 1 if count_file_exist: end_time = time.time() passed_time = end_time - start_time progress_percent = int((counted_packets / total_number_packets) * 100) packets_remaining = total_number_packets - counted_packets average_time_packet = counted_packets / passed_time time_remaining = packets_remaining * average_time_packet time_remaining_minutes = round((time_remaining / 60), 2) print("Progress: " + str(progress_percent) + " %") print("Time remaining: " + str(time_remaining_minutes) + " minutes") packets.close() if (len(connections) > 0): print("Write " + str(write_counter)) for address, packets_value in connections.items(): amount = len(packets_value) if amount >= threshold: pktdump = PcapWriter(new_file_path, append=True, sync=True) for index, packet in enumerate(packets_value): if index < max_length: pktdump.write(packet) else: break connections.clear() with open(log_file_path, 'w') as log_file: log_file.write("last_packet_count:end\n") log_file.write("last_packet_src:" + last_packet_src + "\n") log_file.write("last_packet_dst:" + last_packet_dst + "\n") log_file.write("last_packet:" + str(last_packet) + "\n") log_file.close() print("Write " + str(write_counter) + " Finish") if (count_file_exist == False): with open(count_file_path, 'w') as output_file: output_file.write(str(counted_packets)) output_file.close() sys.exit() @staticmethod def filter_connections_based_on_length_into_separate_files_with_udp(threshold, path_to_iot_scenarios_folder, folder_to_store, experiment_name): threshold = threshold path_to_iot_scenarios_folder = path_to_iot_scenarios_folder folder_to_store = folder_to_store experiment_name = experiment_name to_skip_scenario = "CTU-IoT-Malware-Capture-60-1" new_folder_path = folder_to_store + "/" + experiment_name os.mkdir(new_folder_path) folders = sorted([f.path for f in os.scandir(path_to_iot_scenarios_folder) if f.is_dir()]) folders = list(map(lambda x: (x, str(os.path.basename(x)).strip()), folders)) filtered_folders = [] for path, folder in folders: if folder != to_skip_scenario: filtered_folders.append(path) folders = filtered_folders scan_file_order_path = new_folder_path + "/" + "scan_order.txt" for index, folder in enumerate(folders): scenario_name = str(os.path.basename(folder)).strip() scenario_folder_storage = new_folder_path + "/" + scenario_name os.mkdir(scenario_folder_storage) print("Scenario: " + str(index + 1) + "/" + str(len(folders))) print("Scenario name: " + scenario_name) connections = {} pcap_files = glob.glob(folder + "/*.pcap") for index_file, pcap_file in enumerate(pcap_files): file_name = str(os.path.basename(pcap_file)).strip() file_folder = scenario_folder_storage + "/" + file_name os.mkdir(file_folder) print("File: " + str(index_file + 1) + "/" + str(len(pcap_files))) print("File name : " + file_name) with open(scan_file_order_path, 'a') as scan_file: scan_file.write(scenario_name + "," + file_name + "\n") scan_file.close() count_file_name = file_name + "_count.txt" count_file_path = path_to_iot_scenarios_folder + "/" + scenario_name + "/" + count_file_name count_file_exist = os.path.exists(count_file_path) write_counter = 1 appended_packet_counter = 0 if count_file_exist: with open(count_file_path, 'r') as count_file: total_number_packets = int(count_file.readline()) count_file.close() start_time = time.time() last_packet = None last_packet_src = None last_packet_dst = None counted_packets = 0 log_file_path = file_folder + "/" + file_name + "_log.txt" new_file_path = file_folder + "/" + file_name + "_" + experiment_name + ".pcap" with PcapReader(pcap_file) as packets: for packet_count, packet in enumerate(packets): counted_packets = packet_count + 1 if IP in packet: src_ip = packet[IP].src dst_ip = packet[IP].dst last_packet = packet last_packet_src = src_ip last_packet_dst = dst_ip if (src_ip, dst_ip) not in connections: connections[(src_ip, dst_ip)] = [packet] appended_packet_counter = appended_packet_counter + 1 else: connections[(src_ip, dst_ip)].append(packet) appended_packet_counter = appended_packet_counter + 1 if appended_packet_counter == 500000: print("Write " + str(write_counter)) for address, packets_value in connections.items(): amount = len(packets_value) if amount >= threshold: pktdump = PcapWriter(new_file_path, append=True, sync=True) for index, packet in enumerate(packets_value): pktdump.write(packet) pktdump.close() with open(log_file_path, 'w') as log_file: log_file.write("last_packet_count:" + str(packet_count) + "\n") log_file.write("last_packet_src:" + last_packet_src + "\n") log_file.write("last_packet_dst:" + last_packet_dst + "\n") log_file.write("last_packet:" + str(last_packet) + "\n") log_file.close() connections.clear() appended_packet_counter = 0 print("Write " + str(write_counter) + " Finish") write_counter = write_counter + 1 if count_file_exist: end_time = time.time() passed_time = end_time - start_time progress_percent = int((counted_packets / total_number_packets) * 100) packets_remaining = total_number_packets - counted_packets average_time_packet = counted_packets / passed_time time_remaining = packets_remaining * average_time_packet time_remaining_minutes = round((time_remaining / 60), 2) print("Progress: " + str(progress_percent) + " %") print("Time remaining: " + str(time_remaining_minutes) + " minutes") packets.close() if (len(connections) > 0): print("Write " + str(write_counter)) for address, packets_value in connections.items(): amount = len(packets_value) if amount >= threshold: pktdump = PcapWriter(new_file_path, append=True, sync=True) for index, packet in enumerate(packets_value): pktdump.write(packet) connections.clear() with open(log_file_path, 'w') as log_file: log_file.write("last_packet_count:end\n") log_file.write("last_packet_src:" + last_packet_src + "\n") log_file.write("last_packet_dst:" + last_packet_dst + "\n") log_file.write("last_packet:" + str(last_packet) + "\n") log_file.close() print("Write " + str(write_counter) + " Finish") if (count_file_exist == False): with open(count_file_path, 'w') as output_file: output_file.write(str(counted_packets)) output_file.close() sys.exit() @staticmethod def filter_connections_based_on_length_into_separate_files(threshold, slice=None): threshold = threshold if slice: slice = slice path_to_iot_scenarios_folder = "C:/Users/Johannes/iCloudDrive/Uni/CSE/Year 3/Q4/Code/Dataset/Original/IoTScenarios" folder_to_store = "C:/Users/Johannes/iCloudDrive/Uni/CSE/Year 3/Q4/Code/Dataset/Filtered" to_skip_scenario = "CTU-IoT-Malware-Capture-60-1" if slice: new_folder_name = str(threshold) + "_" + str(slice) new_folder_path = folder_to_store + "/" + new_folder_name if os.path.exists(new_folder_path): existing_runs = glob.glob(new_folder_path + "*") largest_version = 0 for run in existing_runs: base_name = os.path.basename(run).strip().split("_") if len(base_name) > 2: addition = int(base_name[2]) if addition > largest_version: largest_version = addition addition = str(largest_version + 1) new_folder_name_addition = new_folder_name + "_" + addition new_folder_path = folder_to_store + "/" + new_folder_name_addition os.mkdir(new_folder_path) else: os.mkdir(new_folder_path) else: new_folder_name = str(threshold) + "_none" new_folder_path = folder_to_store + "/" + new_folder_name if os.path.exists(new_folder_path): existing_runs = glob.glob(new_folder_path + "*") largest_version = 0 for run in existing_runs: base_name = os.path.basename(run).strip().split("_") if len(base_name) > 2: addition = int(base_name[2]) if addition > largest_version: largest_version = addition addition = str(largest_version + 1) new_folder_name_addition = new_folder_name + "_" + addition new_folder_path = folder_to_store + "/" + new_folder_name_addition os.mkdir(new_folder_path) else: os.mkdir(new_folder_path) folders = sorted([f.path for f in os.scandir(path_to_iot_scenarios_folder) if f.is_dir()]) folders = list(map(lambda x: (x, str(os.path.basename(x)).strip()), folders)) filtered_folders = [] for path, folder in folders: if folder != to_skip_scenario: filtered_folders.append(path) folders = filtered_folders scan_file_order_path = new_folder_path + "/" + "scan_order.txt" for index, folder in enumerate(folders): scenario_name = str(os.path.basename(folder)).strip() scenario_folder_storage = new_folder_path + "/" + scenario_name os.mkdir(scenario_folder_storage) print("Scenario: " + str(index + 1) + "/" + str(len(folders))) print("Scenario name: " + scenario_name) connections = {} pcap_files = glob.glob(folder + "/*.pcap") for index_file, pcap_file in enumerate(pcap_files): file_name = str(os.path.basename(pcap_file)).strip() file_folder = scenario_folder_storage + "/" + file_name os.mkdir(file_folder) print("File: " + str(index_file + 1) + "/" + str(len(pcap_files))) print("File name : " + file_name) with open(scan_file_order_path, 'a') as scan_file: scan_file.write(scenario_name + "," + file_name + "\n") scan_file.close() count_file_name = file_name + "_count.txt" count_file_path = path_to_iot_scenarios_folder + "/" + scenario_name + "/" + count_file_name count_file_exist = os.path.exists(count_file_path) write_counter = 1 appended_packet_counter = 0 if count_file_exist: with open(count_file_path, 'r') as count_file: total_number_packets = int(count_file.readline()) count_file.close() start_time = time.time() last_packet = None last_packet_src = None last_packet_dst = None counted_packets = 0 log_file_path = file_folder + "/" + file_name + "_log.txt" new_file_path = file_folder + "/" + file_name + "_filtered_20.pcap" with PcapReader(pcap_file) as packets: for packet_count, packet in enumerate(packets): counted_packets = packet_count + 1 if IP in packet and not UDP in packet: src_ip = packet[IP].src dst_ip = packet[IP].dst last_packet = packet last_packet_src = src_ip last_packet_dst = dst_ip if (src_ip, dst_ip) not in connections: connections[(src_ip, dst_ip)] = [packet] appended_packet_counter = appended_packet_counter + 1 else: connections[(src_ip, dst_ip)].append(packet) appended_packet_counter = appended_packet_counter + 1 if appended_packet_counter == 500000: print("Write " + str(write_counter)) for address, packets_value in connections.items(): amount = len(packets_value) if amount >= threshold: pktdump = PcapWriter(new_file_path, append=True, sync=True) for index, packet in enumerate(packets_value): # if index < 100: pktdump.write(packet) # else: # break pktdump.close() with open(log_file_path, 'w') as log_file: log_file.write("last_packet_count:" + str(packet_count) + "\n") log_file.write("last_packet_src:" + last_packet_src + "\n") log_file.write("last_packet_dst:" + last_packet_dst + "\n") log_file.write("last_packet:" + str(last_packet) + "\n") log_file.close() connections.clear() appended_packet_counter = 0 print("Write " + str(write_counter) + " Finish") write_counter = write_counter + 1 if count_file_exist: end_time = time.time() passed_time = end_time - start_time progress_percent = int((counted_packets / total_number_packets) * 100) packets_remaining = total_number_packets - counted_packets average_time_packet = counted_packets / passed_time time_remaining = packets_remaining * average_time_packet time_remaining_minutes = round((time_remaining / 60), 2) print("Progress: " + str(progress_percent) + " %") print("Time remaining: " + str(time_remaining_minutes) + " minutes") packets.close() if (len(connections) > 0): print("Write " + str(write_counter)) for address, packets_value in connections.items(): amount = len(packets_value) if amount >= threshold: pktdump = PcapWriter(new_file_path, append=True, sync=True) for index, packet in enumerate(packets_value): # if index < 100: pktdump.write(packet) # else: # last_packet = packet # break connections.clear() with open(log_file_path, 'w') as log_file: log_file.write("last_packet_count:end\n") log_file.write("last_packet_src:" + last_packet_src + "\n") log_file.write("last_packet_dst:" + last_packet_dst + "\n") log_file.write("last_packet:" + str(last_packet) + "\n") log_file.close() print("Write " + str(write_counter) + " Finish") if (count_file_exist == False): with open(count_file_path, 'w') as output_file: output_file.write(str(counted_packets)) output_file.close() sys.exit() @staticmethod def restart_process_into_multiple_files_with_to_skip_scenario(threshold, slice=None): threshold = threshold if slice: slice = slice path_to_iot_scenarios_folder = "C:/Users/Johannes/iCloudDrive/Uni/CSE/Year 3/Q4/Code/Dataset/Original/IoTScenarios" folder_to_restart_store = "C:/Users/Johannes/iCloudDrive/Uni/CSE/Year 3/Q4/Code/Dataset/Filtered/5_none" to_skip_scenario = "CTU-IoT-Malware-Capture-60-1" folders = sorted([f.path for f in os.scandir(path_to_iot_scenarios_folder) if f.is_dir()]) folders = list(map(lambda x: (x, str(os.path.basename(x)).strip()), folders)) scan_file_order_path = folder_to_restart_store + "/" + "scan_order.txt" with open(scan_file_order_path, 'r') as inputfile: scanned_files = inputfile.readlines() scanned_files_list = [x.strip() for x in scanned_files] scanned_files_set = set() for file in scanned_files_list: scanned_files_set.add(file.split(",")[0]) folders_still_to_scan = [] for path, folder in folders: if folder not in scanned_files_set and folder != to_skip_scenario: folders_still_to_scan.append(path) folders = folders_still_to_scan scan_file_order_path = folder_to_restart_store + "/" + "scan_order.txt" for index, folder in enumerate(folders): scenario_name = str(os.path.basename(folder)).strip() scenario_folder_storage = folder_to_restart_store + "/" + scenario_name os.mkdir(scenario_folder_storage) print("Scenario: " + str(index + 1) + "/" + str(len(folders))) print("Scenario name: " + scenario_name) connections = {} pcap_files = glob.glob(folder + "/*.pcap") for index_file, pcap_file in enumerate(pcap_files): file_name = str(os.path.basename(pcap_file)).strip() file_folder = scenario_folder_storage + "/" + file_name os.mkdir(file_folder) print("File: " + str(index_file + 1) + "/" + str(len(pcap_files))) print("File name : " + file_name) with open(scan_file_order_path, 'a') as scan_file: scan_file.write(scenario_name + "," + file_name + "\n") scan_file.close() count_file_name = file_name + "_count.txt" count_file_path = path_to_iot_scenarios_folder + "/" + scenario_name + "/" + count_file_name count_file_exist = os.path.exists(count_file_path) write_counter = 1 appended_packet_counter = 0 if count_file_exist: with open(count_file_path, 'r') as count_file: total_number_packets = int(count_file.readline()) count_file.close() start_time = timer() last_packet = None last_packet_src = None last_packet_dst = None counted_packets = 0 log_file_path = file_folder + "/" + file_name + "_log.txt" new_file_path = file_folder + "/" + file_name + "_filtered_20.pcap" with PcapReader(pcap_file) as packets: for packet_count, packet in enumerate(packets): counted_packets = packet_count + 1 if IP in packet and not UDP in packet: src_ip = packet[IP].src dst_ip = packet[IP].dst last_packet = packet last_packet_src = src_ip last_packet_dst = dst_ip if (src_ip, dst_ip) not in connections: connections[(src_ip, dst_ip)] = [packet] appended_packet_counter = appended_packet_counter + 1 else: connections[(src_ip, dst_ip)].append(packet) appended_packet_counter = appended_packet_counter + 1 if appended_packet_counter == 500000: print("Write " + str(write_counter)) for address, packets_value in connections.items(): amount = len(packets_value) if amount >= threshold: pktdump = PcapWriter(new_file_path, append=True, sync=True) for index, packet in enumerate(packets_value): pktdump.write(packet) pktdump.close() with open(log_file_path, 'w') as log_file: log_file.write("last_packet_count:" + str(packet_count) + "\n") log_file.write("last_packet_src:" + last_packet_src + "\n") log_file.write("last_packet_dst:" + last_packet_dst + "\n") log_file.write("last_packet:" + str(last_packet) + "\n") log_file.close() connections.clear() appended_packet_counter = 0 print("Write " + str(write_counter) + " Finish") write_counter = write_counter + 1 if count_file_exist: end_time = timer() passed_time = end_time - start_time progress_percent = int((counted_packets / total_number_packets) * 100) packets_remaining = total_number_packets - counted_packets average_time_packet = counted_packets / passed_time time_remaining = packets_remaining * average_time_packet time_remaining_minutes = round((time_remaining / 60), 2) print("Progress: " + str(progress_percent) + " %") print("Time remaining: " + str(time_remaining_minutes) + " minutes") packets.close() if (len(connections) > 0): print("Write " + str(write_counter)) for address, packets_value in connections.items(): amount = len(packets_value) if amount >= threshold: pktdump = PcapWriter(new_file_path, append=True, sync=True) for index, packet in enumerate(packets_value): pktdump.write(packet) connections.clear() with open(log_file_path, 'w') as log_file: log_file.write("last_packet_count:end\n") log_file.write("last_packet_src:" + last_packet_src + "\n") log_file.write("last_packet_dst:" + last_packet_dst + "\n") log_file.write("last_packet:" + str(last_packet) + "\n") log_file.close() print("Write " + str(write_counter) + " Finish") if (count_file_exist == False): with open(count_file_path, 'w') as output_file: output_file.write(str(counted_packets)) output_file.close() sys.exit()
43,247
https://github.com/Hayamiosukei/DVersion-Data-Workarounds/blob/master/Python/dm-git.py
Github Open Source
Open Source
MIT
2,021
DVersion-Data-Workarounds
Hayamiosukei
Python
Code
88
425
import urllib.request from re import compile from json import loads def build_dm(): """ Workaround that uses latest commits from https://github.com/DJScias/Discord-Datamining with GitHub's API (https://api.github.com/repos/DJScias/Discord-Datamining/commits) Limitations: Exclusive to canary, gets latest data only :return: """ the_url = "https://api.github.com/repos/DJScias/Discord-Datamining/commits" headers = { "User-Agent": "*" } requ = (urllib.request.urlopen(urllib.request.Request(the_url, headers=headers)).read()).decode('utf-8') data = '' try: data = loads(requ)[0]["commit"]["message"] except(): pass canary_reg = compile("[A-Za-z0-9]+ \(Canary build: [0-9]+\)") canary_bn_reg = compile('Canary build: [0-9]+') canary_h_reg = compile("[A-Za-z0-9]+") canary_data = str(canary_reg.findall(data)) canary_bn = str(canary_bn_reg.findall(canary_data)[0]).split(":")[-1].replace(" ", "") canary_h = str(canary_h_reg.findall(canary_data)[0]) canary_id = canary_h[0:7:1] return canary_bn, canary_h, canary_id
13,499
https://github.com/EFTAY/Hostel-Management-System-Laravel-WebProject-Eftay-Khyrul-Alam/blob/master/resources/views/layouts/frontEnd/font/google.blade.php
Github Open Source
Open Source
MIT
null
Hostel-Management-System-Laravel-WebProject-Eftay-Khyrul-Alam
EFTAY
PHP
Code
3
49
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
7,126
https://github.com/yan0908/client/blob/master/shared/wallets/common/participants-row/index.stories.tsx
Github Open Source
Open Source
BSD-3-Clause
2,022
client
yan0908
TypeScript
Code
53
127
import * as React from 'react' import * as Sb from '../../../stories/storybook' import ParticipantsRow from '.' const load = () => { Sb.storiesOf('Wallets/Common/Participants Row', module) .add('To heading', () => <ParticipantsRow heading="To" />) .add('From heading with a divider and right aligned', () => ( <ParticipantsRow heading="From" bottomDivider={true} headingAlignment="Right" /> )) } export default load
40,559
https://github.com/mohnoor94/ProblemsSolving/blob/master/src/main/python/string/rabin_karp_substring_search.py
Github Open Source
Open Source
Apache-2.0
2,021
ProblemsSolving
mohnoor94
Python
Code
198
535
""" An algorithm used to search for a substring in a string. - Read more in: Cracking the coding interview, a book by Gayle Mcdowell (6th ed, pg636), or Google it. """ import math def rabin_karp_search(sub, main): """ Time: O(len(main)) Space: O(1) * if we want to return the [matches] list below, space will have O(len(main)/len(sub)). If space is a problem (e.g., we won't use 1 additional list for some weird reason), we could return the index of first occurrence of the sub in main. """ if len(sub) > len(main): return -1 if sub == main: return 0 if len(sub) == len(main): return -1 size = len(sub) matches = [] sub_hash = fingerprint(sub) base_hash = fingerprint(main[0:size]) for i in range(size, len(main)): if base_hash == sub_hash: matches.append(i - size) base_hash = (base_hash - code(main[i - size]) * math.pow(128, size - 1)) * 128 + code(main[i]) if base_hash == sub_hash: matches.append(len(main) - len(sub)) return matches def fingerprint(string): p = len(string) - 1 h = 0 for c in string: h += code(c) * math.pow(128, p) p -= 1 return h def code(char): return ord(char) if __name__ == '__main__': print(rabin_karp_search('hi', 'hello')) print(rabin_karp_search('hi', 'hillo')) print(rabin_karp_search('hi', 'hillhio')) print(rabin_karp_search('hi', 'hi ll hio')) print(rabin_karp_search('hi', 'hillhiollalahi'))
4,149
https://github.com/fooblahblah/bloop/blob/master/backend/src/main/scala/bloop/CompileMode.scala
Github Open Source
Open Source
Apache-2.0
2,022
bloop
fooblahblah
Scala
Code
58
186
package bloop import _root_.monix.eval.Task import scala.concurrent.Promise import bloop.io.AbsolutePath import xsbti.compile.Signature /** * Defines the mode in which compilation should run. */ sealed trait CompileMode { def oracle: CompilerOracle } object CompileMode { case class Sequential( oracle: CompilerOracle ) extends CompileMode final case class Pipelined( completeJavaCompilation: Promise[Unit], finishedCompilation: Promise[Option[CompileProducts]], fireJavaCompilation: Task[JavaSignal], oracle: CompilerOracle, separateJavaAndScala: Boolean ) extends CompileMode }
46,309
https://github.com/TonyHong15/Food-Calories-Tracker/blob/master/client/src/components/ManageFood/index.js
Github Open Source
Open Source
MIT
2,021
Food-Calories-Tracker
TonyHong15
JavaScript
Code
166
537
import React from "react"; import { Grid } from "@material-ui/core"; import FoodForm from "./FoodForm"; import FoodList from "./FoodList"; import "./styles.css"; import { loadFood } from "../../api"; /* Component for ManageFood */ class ManageFood extends React.Component { constructor(props) { super(props) this.app = props.app; // TODO call the backend here to initialize foodList this.state = { foodList: [] } } componentDidMount(){ this.loadFood() } loadFood = () =>{ const request = new Request('/api/users/'+ window.sessionStorage.getItem('currentUser'), { method: "get", headers: { Accept: "application/json, text/plain, */*", "Content-Type": "application/json" } }); // Send the request with fetch() fetch(request) .then(res => { console.log(res.status) if (res.status === 200) { return res.json(); } }) .then(json => { console.log(json.foods) this.setState( {foodList: json.foods} ) }) .catch(error => { console.log(error); }); } render() { const { history, app } = this.props; return ( <div className="ManageFoodBackground"> <Grid container className="requests-grid"> <Grid item xs={1}></Grid> <Grid item xs={3}> {<FoodForm appState={this.props.appState} foodList={this.state} dashboard={this} app={app}/>} </Grid> <Grid item xs={2}></Grid> <Grid item xs={3}> {<FoodList appState={this.props.appState} foodList={this.state} app={app}/>} </Grid> </Grid> </div> ); } } export default ManageFood;
16,305
https://github.com/koendeschacht/count-db/blob/master/src/main/java/be/bagofwords/db/remote/RemoteDataInterface.java
Github Open Source
Open Source
MIT
2,022
count-db
koendeschacht
Java
Code
1,410
4,633
package be.bagofwords.db.remote; import be.bagofwords.db.DataInterface; import be.bagofwords.db.combinator.Combinator; import be.bagofwords.db.impl.BaseDataInterface; import be.bagofwords.db.impl.UpdateListener; import be.bagofwords.db.impl.UpdateListenerCollection; import be.bagofwords.db.methods.DataStream; import be.bagofwords.db.methods.KeyFilter; import be.bagofwords.db.methods.ObjectSerializer; import be.bagofwords.db.remote.RemoteDataInterfaceServer.Action; import be.bagofwords.exec.RemoteObjectConfig; import be.bagofwords.iterator.CloseableIterator; import be.bagofwords.jobs.AsyncJobService; import be.bagofwords.logging.Log; import be.bagofwords.util.ExecutorServiceFactory; import be.bagofwords.util.KeyValue; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.function.Predicate; import java.util.stream.Collectors; import static be.bagofwords.db.remote.Protocol.*; public class RemoteDataInterface<T> extends BaseDataInterface<T> { private final static int MAX_NUM_OF_CONNECTIONS = 50; private final static long MAX_WAIT = 60 * 1000; private final String host; private final int port; private final List<Connection> smallBufferConnections; private final List<Connection> largeWriteBufferConnections; private final List<Connection> largeReadBufferConnections; private final ExecutorService executorService; private final UpdateListenerCollection<T> updateListenerCollection; public RemoteDataInterface(String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer, String host, int port, boolean isTemporaryDataInterface, AsyncJobService asyncJobService) { super(name, objectClass, combinator, objectSerializer, isTemporaryDataInterface); this.host = host; this.port = port; this.smallBufferConnections = new ArrayList<>(); this.largeReadBufferConnections = new ArrayList<>(); this.largeWriteBufferConnections = new ArrayList<>(); executorService = ExecutorServiceFactory.createExecutorService("remote_data_interface"); asyncJobService.schedulePeriodicJob(() -> ifNotClosed(this::removeUnusedConnections), 1000); updateListenerCollection = new UpdateListenerCollection<>(); } private Connection selectSmallBufferConnection() throws IOException { return selectConnection(smallBufferConnections, false, false, RemoteDataInterfaceServer.ConnectionType.CONNECT_TO_INTERFACE); } private Connection selectLargeWriteBufferConnection() throws IOException { return selectConnection(largeWriteBufferConnections, true, false, RemoteDataInterfaceServer.ConnectionType.BATCH_WRITE_TO_INTERFACE); } private Connection selectLargeReadBufferConnection() throws IOException { return selectConnection(largeReadBufferConnections, false, true, RemoteDataInterfaceServer.ConnectionType.BATCH_READ_FROM_INTERFACE); } private Connection selectConnection(List<Connection> connections, boolean largeWriteBuffer, boolean largeReadBuffer, RemoteDataInterfaceServer.ConnectionType connectionType) throws IOException { Connection result = selectFreeConnection(connections); if (result != null) { return result; } else { //Can we create an extra connection? synchronized (connections) { if (connections.size() < MAX_NUM_OF_CONNECTIONS) { Connection newConn = new Connection(this, host, port, largeWriteBuffer, largeReadBuffer, connectionType); connections.add(newConn); newConn.setTaken(true); return newConn; } } //Let's wait until a connection becomes available long start = System.currentTimeMillis(); while (System.currentTimeMillis() - start < MAX_WAIT) { result = selectFreeConnection(connections); if (result != null) { return result; } } } throw new RuntimeException("Failed to reserve a connection!"); } private Connection selectFreeConnection(List<Connection> connections) { synchronized (connections) { for (Connection connection : connections) { if (!connection.isTaken()) { connection.setTaken(true); return connection; } } } return null; } @Override public T read(long key) { Connection connection = null; try { connection = selectSmallBufferConnection(); doAction(Action.READ_VALUE, connection); connection.writeLong(key); connection.flush(); T value = readValue(connection); releaseConnection(connection); return value; } catch (Exception e) { dropConnection(connection); throw new RuntimeException(e); } } private T readValue(Connection connection) throws IOException { int size = objectSerializer.getObjectSize(); if (size == -1) { size = connection.readInt(); } byte[] bytes = connection.readByteArray(size); DataStream ds = new DataStream(bytes); return objectSerializer.readValue(ds, size); } @Override public boolean mightContain(long key) { Connection connection = null; try { connection = selectSmallBufferConnection(); doAction(Action.MIGHT_CONTAIN, connection); connection.writeLong(key); connection.flush(); boolean result = connection.readBoolean(); releaseConnection(connection); return result; } catch (Exception e) { dropConnection(connection); throw new RuntimeException(e); } } @Override public long apprSize() { return readLong(Action.APPROXIMATE_SIZE); } @Override public long exactSize() { return readLong(Action.EXACT_SIZE); } @Override public void write(long key, T value) { Connection connection = null; try { connection = selectSmallBufferConnection(); doAction(Action.WRITE_VALUE, connection); connection.writeLong(key); writeValue(value, connection); connection.flush(); long response = connection.readLong(); if (response != LONG_OK) { dropConnection(connection); throw new RuntimeException("Unexpected error while reading approximate size " + connection.readString()); } else { releaseConnection(connection); } } catch (Exception e) { dropConnection(connection); throw new RuntimeException(e); } updateListenerCollection.dateUpdated(key, value); } @Override public void write(CloseableIterator<KeyValue<T>> entries) { Connection connection = null; try { connection = selectLargeWriteBufferConnection(); doAction(Action.WRITE_VALUES, connection); while (entries.hasNext()) { KeyValue<T> entry = entries.next(); connection.writeLong(entry.getKey()); writeValue(entry.getValue(), connection); updateListenerCollection.dateUpdated(entry.getKey(), entry.getValue()); } connection.writeLong(LONG_END); connection.flush(); long response = connection.readLong(); if (response != LONG_OK) { throw new RuntimeException("Unexpected error while reading approximate size " + connection.readString()); } releaseConnection(connection); } catch (Exception e) { dropConnection(connection); throw new RuntimeException(e); } finally { entries.close(); } } private void writeValue(T value, Connection connection) throws IOException { DataStream ds = new DataStream(); objectSerializer.writeValue(value, ds); int objectSize = objectSerializer.getObjectSize(); if (objectSize == -1) { connection.writeInt(ds.position); } connection.writeByteArray(ds.buffer, ds.position); } @Override public CloseableIterator<KeyValue<T>> iterator(final CloseableIterator<Long> keyIterator) { Connection connection = null; try { connection = selectLargeReadBufferConnection(); Connection thisConnection = connection; doAction(Action.ITERATOR_WITH_KEY_ITERATOR, thisConnection); executorService.submit(() -> { try { while (keyIterator.hasNext()) { Long nextKey = keyIterator.next(); thisConnection.writeLong(nextKey); } thisConnection.writeLong(LONG_END); thisConnection.flush(); keyIterator.close(); } catch (Exception e) { Log.e("Received exception while sending keys for read(..), for interface " + getName() + ". Closing connection. ", e); dropConnection(thisConnection); } }); return createKeyValueIterator(thisConnection); } catch (Exception e) { dropConnection(connection); throw new RuntimeException("Received exception while sending keys for read(..) for interface " + getName(), e); } } @Override public CloseableIterator<KeyValue<T>> iterator() { Connection connection = null; try { connection = selectLargeReadBufferConnection(); doAction(Action.ITERATOR, connection); connection.flush(); return createKeyValueIterator(connection); } catch (Exception e) { dropConnection(connection); throw new RuntimeException("Failed to iterate over values from " + host + ":" + port, e); } } @Override public CloseableIterator<KeyValue<T>> iterator(KeyFilter keyFilter) { Connection connection = null; try { RemoteObjectConfig remoteObjectConfig = RemoteObjectConfig.create(keyFilter).add(keyFilter.getClass()); connection = selectLargeReadBufferConnection(); doAction(Action.ITERATOR_WITH_KEY_FILTER, connection); connection.writeValue(remoteObjectConfig.pack()); connection.flush(); return createKeyValueIterator(connection); } catch (Exception e) { dropConnection(connection); throw new RuntimeException("Failed to iterate over values from " + host + ":" + port, e); } } @Override public CloseableIterator<T> valueIterator(KeyFilter keyFilter) { Connection connection = null; try { RemoteObjectConfig remoteObjectConfig = RemoteObjectConfig.create(keyFilter).add(keyFilter.getClass()); connection = selectLargeReadBufferConnection(); doAction(Action.VALUES_ITERATOR_WITH_KEY_FILTER, connection); connection.writeValue(remoteObjectConfig.pack()); connection.flush(); return createValueIterator(connection); } catch (Exception e) { dropConnection(connection); throw new RuntimeException("Failed to iterate over values from " + host + ":" + port, e); } } @Override public CloseableIterator<KeyValue<T>> iterator(Predicate<T> valueFilter) { Connection connection = null; try { RemoteObjectConfig execConfig = RemoteObjectConfig.create(valueFilter).add(valueFilter.getClass()); connection = selectLargeReadBufferConnection(); doAction(Action.ITERATOR_WITH_VALUE_FILTER, connection); connection.writeValue(execConfig.pack()); connection.flush(); return createKeyValueIterator(connection); } catch (Exception e) { dropConnection(connection); throw new RuntimeException("Failed to iterate over values from " + host + ":" + port, e); } } @Override public CloseableIterator<T> valueIterator(Predicate<T> valueFilter) { Connection connection = null; try { RemoteObjectConfig execConfig = RemoteObjectConfig.create(valueFilter).add(valueFilter.getClass()); connection = selectLargeReadBufferConnection(); doAction(Action.VALUES_ITERATOR_WITH_VALUE_FILTER, connection); connection.writeValue(execConfig.pack()); connection.flush(); return createValueIterator(connection); } catch (Exception e) { dropConnection(connection); throw new RuntimeException("Failed to iterate over values from " + host + ":" + port, e); } } private CloseableIterator<KeyValue<T>> createKeyValueIterator(final Connection connection) { return new KeyValueSocketIterator<>(this, connection); } private CloseableIterator<T> createValueIterator(final Connection connection) { return new ValueSocketIterator<>(this, connection); } @Override public CloseableIterator<Long> keyIterator() { Connection connection = null; try { connection = selectLargeReadBufferConnection(); doAction(Action.READ_KEYS, connection); connection.flush(); Connection thisConnection = connection; return new CloseableIterator<Long>() { private Long next; private boolean readLastValue = false; { //Constructor findNext(); } private void findNext() { try { long key = thisConnection.readLong(); if (key == LONG_END) { //End next = null; readLastValue = true; } else if (key != LONG_ERROR) { next = key; } else { throw new RuntimeException("Unexpected response " + thisConnection.readString()); } } catch (Exception e) { dropConnection(thisConnection); throw new RuntimeException(e); } } @Override public boolean hasNext() { return next != null; } @Override public Long next() { Long result = next; findNext(); return result; } @Override public void closeInt() { if (readLastValue) { releaseConnection(thisConnection); } else { dropConnection(thisConnection); } } }; } catch (Exception e) { dropConnection(connection); throw new RuntimeException(e); } } @Override public CloseableIterator<KeyValue<T>> cachedValueIterator() { Connection connection = null; try { connection = selectLargeReadBufferConnection(); doAction(Action.READ_CACHED_VALUES, connection); connection.flush(); return createKeyValueIterator(connection); } catch (Exception e) { dropConnection(connection); throw new RuntimeException("Failed to iterate over values from " + host + ":" + port, e); } } @Override public void dropAllData() { doSimpleAction(Action.DROP_ALL_DATA); updateListenerCollection.dataDropped(); } private long readLong(Action action) { Connection connection = null; try { connection = selectSmallBufferConnection(); doAction(action, connection); connection.flush(); long response = connection.readLong(); if (response == LONG_OK) { long result = connection.readLong(); releaseConnection(connection); return result; } else { dropConnection(connection); throw new RuntimeException("Unexpected error while reading approximate size " + connection.readString()); } } catch (Exception e) { dropConnection(connection); throw new RuntimeException(e); } } @Override public synchronized void flush() { ifNotClosed(() -> doSimpleAction(Action.FLUSH)); updateListenerCollection.dataFlushed(); } private void removeUnusedConnections() { removeUnusedConnections(smallBufferConnections); removeUnusedConnections(largeReadBufferConnections); removeUnusedConnections(largeWriteBufferConnections); } private void removeUnusedConnections(List<Connection> connections) { synchronized (connections) { List<Connection> unusedConnections = connections.stream().filter(connection -> (!connection.isTaken() && System.currentTimeMillis() - connection.getLastUsage() > 60 * 1000) || !connection.isOpen()).collect(Collectors.toList()); for (Connection unusedConnection : unusedConnections) { dropConnection(unusedConnection); } } } @Override public void optimizeForReading() { doSimpleAction(Action.OPTMIZE_FOR_READING); } @Override protected void doClose() { dropConnections(smallBufferConnections); dropConnections(largeWriteBufferConnections); dropConnections(largeReadBufferConnections); executorService.shutdownNow(); } private void dropConnections(List<Connection> connections) { synchronized (connections) { for (Connection connection : connections) { IOUtils.closeQuietly(connection); } connections.clear(); } } @Override public DataInterface<T> getCoreDataInterface() { return this; } @Override public void registerUpdateListener(UpdateListener<T> updateListener) { updateListenerCollection.registerUpdateListener(updateListener); } void doAction(Action action, Connection connection) throws IOException { connection.writeByte((byte) action.ordinal()); } private void doSimpleAction(Action action) { Connection connection = null; try { connection = selectSmallBufferConnection(); doAction(action, connection); connection.flush(); long response = connection.readLong(); if (response != LONG_OK) { dropConnection(connection); throw new RuntimeException("Unexpected response for action " + action + " " + connection.readString()); } else { releaseConnection(connection); } } catch (Exception e) { dropConnection(connection); throw new RuntimeException(e); } } void releaseConnection(Connection connection) { if (connection != null) { connection.release(); } } void dropConnection(Connection connection) { if (connection != null) { IOUtils.closeQuietly(connection); synchronized (smallBufferConnections) { smallBufferConnections.remove(connection); } synchronized (largeReadBufferConnections) { largeReadBufferConnections.remove(connection); } synchronized (largeWriteBufferConnections) { largeWriteBufferConnections.remove(connection); } } } }
44,927
https://github.com/SindelarPetr/Uniwiki/blob/master/Uniwiki/Uniwiki.Server.Application/Extensions/QueryableExtension.cs
Github Open Source
Open Source
Apache-2.0
null
Uniwiki
SindelarPetr
C#
Code
419
1,890
using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Query.Internal; using Uniwiki.Server.Persistence.Models; using Uniwiki.Shared.ModelDtos; using Uniwiki.Shared.RequestResponse; using Uniwiki.Shared.RequestResponse.Authentication; namespace Uniwiki.Server.Application.Extensions { internal static class QueryableExtension { public static IQueryable<StudyGroupDto> ToStudyGroupDto(this IQueryable<StudyGroupModel> studyGroups) => studyGroups .Include(g => g.University) .Select(g => new StudyGroupDto(g.Id, g.ShortName, g.LongName, g.Url, g.University.LongName, g.University.ShortName, g.University.Url, g.UniversityId)); public static IQueryable<CourseDto> ToCourseDto(this IQueryable<CourseModel> courses) => courses .Include(c => c.StudyGroup) .ThenInclude(g => g.University) .Select(c => new CourseDto( c.Id, c.LongName, c.Code, c.Url, c.StudyGroup.LongName, c.StudyGroup.Url, c.StudyGroup.University.ShortName, c.StudyGroup.University.Url) ); public static IQueryable<PostFileDto> ToPostFileDto(this IQueryable<PostFileModel> postFiles) => postFiles .Select(f => new PostFileDto(f.Id, f.NameWithoutExtension, f.Extension, f.Size)); public static ProfileViewModel? ToProfileViewModel(this IQueryable<ProfileModel> profileQuery) { var p = profileQuery .Include(p => p.HomeFaculty) .ThenInclude(p => p.University) .FirstOrDefault(); return p == null ? null : new ProfileViewModel( p.Id, p.FirstName, p.FamilyName, p.FullName, p.ProfilePictureSrc, p.CreationDate, p.Url, (p.Feedbacks?.Count ?? 0) > 0, p.HomeFaculty == null ? null : new HomeStudyGroupDto( p.HomeFaculty.Id, p.HomeFaculty.ShortName, p.HomeFaculty.LongName, p.HomeFaculty.University.ShortName, p.HomeFaculty.University.LongName, p.HomeFaculty.Url, p.HomeFaculty.University.Url, p.HomeFaculty.University.Id) ); // Include the email just for the owner of the email } public static UniversityDto ToUniversityDto(this UniversityModel university) => new UniversityDto(university.Id, university.LongName, university.ShortName, university.Url); public static IQueryable<FoundCourseDto> ToFoundCourses(this IQueryable<CourseModel> courses) => courses .Select(c => new FoundCourseDto( c.Id, c.UniversityUrl + '/' + c.StudyGroupUrl + '/' + c.Url, $"{ c.StudyGroup.University.ShortName } - { c.StudyGroup.LongName }", c.Code, c.LongName)); public static IEnumerable<PostViewModel> ToPostViewModel(this IQueryable<PostModel> posts, Guid? userId) { // Future: This can be optimized var postViewModels = posts .Include(p => p.Likes) .Include(p => p.PostFiles) .Include(p => p.Author) .Include(p => p.Comments) .ThenInclude(c => c.Author) .Include(p => p.Comments) .ThenInclude(c => c.Likes) .AsEnumerable() .Select(p => new PostViewModel( p.Id, p.Author.Url, p.Text, p.CreationTime, p.PostFiles.Select(pf => new PostFileDto( pf.Id, pf.NameWithoutExtension, pf.Extension, pf.Size) ).ToArray(), p.PostFiles.Count, p.PostType, p.Likes.Count(l => l.IsLiked), p.Likes.Any(l => l.IsLiked && l.ProfileId == userId), p.Comments.Select( c => new PostCommentDto( c.Id, c.CreationTime, c.Likes.Count(l => l.IsLiked), c.Author.Url, c.Text, c.Likes.Any(l => l.IsLiked && l.ProfileId == userId), c.Author.ProfilePictureSrc, c.Author.Url, c.Author.FullName, c.AuthorId )).ToArray(), p.AuthorId, p.Author.FullName, p.Author.Url, p.Author.ProfilePictureSrc ) ) .ToList(); postViewModels .ForEach(p => p.PostComments = p.PostComments.OrderBy(c => c.CreationTime) .ToArray()); return postViewModels; } public static IQueryable<LoginTokenDto> ToLoginTokenDto(this IQueryable<LoginTokenModel> loginTokens) => loginTokens .Select(t => new LoginTokenDto(t.ProfileId, t.PrimaryTokenId, t.Expiration, t.SecondaryTokenId)); public static AuthorizedUserDto ToAuthorizedUserDto(this IQueryable<ProfileModel> profileQuery) { var profileWithFeedbackProvided = profileQuery .Include(p => p.HomeFaculty) .ThenInclude(p => p!.University) .Select(p => new {Profile = p, FeedbacksCount = p.Feedbacks.Count()}) .First(); var profile = profileWithFeedbackProvided.Profile; return new AuthorizedUserDto( profile.Id, profile.FirstName, profile.FamilyName, profile.FullName, profile.ProfilePictureSrc, profile.Url, profileWithFeedbackProvided.FeedbacksCount > 0, profile.Email, profile.HomeFaculty == null ? null : new HomeStudyGroupDto( profile.HomeFaculty.Id, profile.HomeFaculty.ShortName, profile.HomeFaculty.LongName, profile.HomeFaculty.University.ShortName, profile.HomeFaculty.University.LongName, profile.HomeFaculty.Url, profile.HomeFaculty.University.Url, profile.HomeFaculty.University.Id) ); } public static IQueryable<RecentCourseDto> ToRecentCourseDto(this IQueryable<CourseModel> recentCourses) => recentCourses .Include(c => c.StudyGroup) .ThenInclude(c => c.University) .Select(c => new RecentCourseDto( c.LongName, c.Code, c.StudyGroupUrl, c.StudyGroup.LongName, c.UniversityUrl, c.StudyGroup.University.ShortName, c.Id, c.Url)); } }
18,253
https://github.com/mlazzarotto/port-scanner/blob/master/main.py
Github Open Source
Open Source
MIT
null
port-scanner
mlazzarotto
Python
Code
475
1,462
from concurrent.futures.thread import ThreadPoolExecutor import socket import sys import time import argparse import concurrent.futures class PScan: def __init__(self): self.portlist_raw_string = "" self.remote_host = "" self.remote_host_fqdn = "" self.remote_ip = "" self.number_of_open_ports = 0 def get_ports(self, portlist_raw_string): """ Take a string with ports and splits into single port, then calculates the range of ports to check """ range_min_max = [] inflated_port_list = [] portlist_raw_list = portlist_raw_string.split(',') # for every port number in the list for port in portlist_raw_list: if port != '': # if the dash symbol is present, it's a range if (port.find("-") != -1): # adding the range of ports in a list range_min_max.append(port.split('-')) else: # if the port doesn't contain letters if port.isdigit(): port = int(port) if port >= 0 and port <= 65535: inflated_port_list.append(port) # for every range to create for range_to_create in range_min_max: min, max = int(range_to_create[0]), int(range_to_create[1]) for port in range(min, max+1): if port >= 0 and port <= 65535: inflated_port_list.append(port) # remove duplicates and sort the list inflated_port_list = sorted(set(inflated_port_list)) return inflated_port_list def scan_port(self, remote_host, port): """ New function to scan ports """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(self.timeout) # if port is open if not sock.connect_ex((remote_host, port)): try: # get the service name for the port serviceName = socket.getservbyport(port, "tcp") except: serviceName = "" sock.close() self.number_of_open_ports += 1 print(port, "\t", serviceName) def scan_host(self, remote_host, ports_to_scan): """ Scans a host to check if the given ports are open """ # trying to obtain the ip address try: ip = socket.gethostbyname(remote_host) except: print("Error: ip invalid or can't resolve the host name in IP address!") sys.exit() # trying to obtain the FQDN try: fqdn = socket.getfqdn(remote_host) except: fqdn = remote_host print("Starting port scan of host: {} ({})".format(remote_host, fqdn)) # this is to get the execution time startTime = time.time() # using multithreading to scan multiple ports simultaneously with concurrent.futures.ThreadPoolExecutor(max_workers=self.max_workers) as executor: {executor.submit(self.scan_port, remote_host, port) : port for port in ports_to_scan} # i wait for all the threads to complete executor.shutdown(wait=True) # calculating execution time executionTime = round((time.time() - startTime), 2) # printing some info print("\nScan finished in {} seconds".format(executionTime)) print("Found {} open ports!".format(self.number_of_open_ports)) def initialize(self): self.ports_to_scan = self.get_ports(self.portlist_raw_string) if len(self.ports_to_scan): self.scan_host(self.remote_host, self.ports_to_scan) def parse_args(self): parser_usage = '''main.py -p 21 192.168.1.1 main.py -p 21,80-90 192.168.1.1 main.py --port 21 192.168.1.1 main.py --port 21,80-90 192.168.1.1''' parser = argparse.ArgumentParser( description="A simple port scanner tool", usage=parser_usage) parser.add_argument( "ipaddress", help="The IP address you want to scan") parser.add_argument( "-p", "--port", help="A list of ports to scan", required=True, dest="ports_to_scan", action="store") parser.add_argument( "-t", "--timeout", help="Timeout to check if port is open (Default 0.1)", required=False, dest="timeout", action="store", default=0.1) parser.add_argument( "-w", "--workers", help="Maximum number of workers to use for multithreading (Default 1000)", required=False, dest="max_workers", action="store", default=1000) # printing help if no argument given if len(sys.argv) == 1: parser.print_help() sys.exit(1) arguments = parser.parse_args() self.remote_host = arguments.ipaddress self.portlist_raw_string = arguments.ports_to_scan self.timeout = arguments.timeout self.max_workers = int(arguments.max_workers) if __name__ == '__main__': pscan = PScan() pscan.parse_args() pscan.initialize()
11,612
https://github.com/mohsen-dl/AnimatedSvgView/blob/master/demo/src/main/java/com/jrummyapps/android/animatedsvgview/demo/MainActivity.java
Github Open Source
Open Source
Apache-2.0
2,017
AnimatedSvgView
mohsen-dl
Java
Code
252
861
/* * Copyright (C) 2016 Jared Rummler <jared.rummler@gmail.com> * * 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.jrummyapps.android.animatedsvgview.demo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.jrummyapps.android.widget.AnimatedSvgView; public class MainActivity extends AppCompatActivity { private AnimatedSvgView svgView; private int index = -1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); svgView = (AnimatedSvgView) findViewById(R.id.animated_svg_view); svgView.postDelayed(new Runnable() { @Override public void run() { svgView.start(); } }, 500); svgView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (svgView.getState() == AnimatedSvgView.STATE_FINISHED) { svgView.start(); } } }); svgView.setOnStateChangeListener(new AnimatedSvgView.OnStateChangeListener() { @Override public void onStateChange(int state) { if (state == AnimatedSvgView.STATE_TRACE_STARTED) { findViewById(R.id.btn_previous).setEnabled(false); findViewById(R.id.btn_next).setEnabled(false); } else if (state == AnimatedSvgView.STATE_FINISHED) { findViewById(R.id.btn_previous).setEnabled(index != -1); findViewById(R.id.btn_next).setEnabled(true); if (index == -1) index = 0; // first time } } }); } public void onNext(View view) { if (++index >= SVG.values().length) index = 0; setSvg(SVG.values()[index]); } public void onPrevious(View view) { if (--index < 0) index = SVG.values().length - 1; setSvg(SVG.values()[index]); } private void setSvg(SVG svg) { svgView.setGlyphStrings(svg.glyphs); svgView.setFillColors(svg.colors); svgView.setViewportSize(svg.width, svg.height); svgView.setTraceResidueColor(0x32000000); svgView.setTraceColors(svg.colors); svgView.rebuildGlyphData(); svgView.start(); } }
19,496
https://github.com/debuglevel/walkingdinner-geneticplanner/blob/master/backend/src/main/kotlin/de/debuglevel/walkingdinner/backend/dinner/Dinner.kt
Github Open Source
Open Source
Unlicense
null
walkingdinner-geneticplanner
debuglevel
Kotlin
Code
149
474
package de.debuglevel.walkingdinner.backend.dinner import de.debuglevel.walkingdinner.backend.calculation.Calculation import de.debuglevel.walkingdinner.backend.organisation.Organisation import de.debuglevel.walkingdinner.backend.team.Team import org.hibernate.annotations.GenericGenerator import java.time.LocalDateTime import java.util.* import javax.persistence.* @Entity data class Dinner( @Id @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2") @Column(columnDefinition = "BINARY(16)") val id: UUID? = null, val name: String, @OneToMany(fetch = FetchType.EAGER, cascade = [CascadeType.ALL]) val teams: Set<Team> = setOf(), @OneToMany(cascade = [CascadeType.ALL]) val calculations: Set<Calculation> = setOf(), val city: String, val begin: LocalDateTime, @ManyToOne val organisation: Organisation ) { override fun toString(): String { return "Dinner(" + "id=$id, " + "name='$name', " + "city='$city', " + "begin=$begin" + ")" } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Dinner if (name != other.name) return false if (city != other.city) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + city.hashCode() return result } }
25,441
https://github.com/jasonshere/imooc_advanced_code/blob/master/8_jstree/basic/controllers/PayController.php
Github Open Source
Open Source
BSD-3-Clause, MIT
2,017
imooc_advanced_code
jasonshere
PHP
Code
72
244
<?php namespace app\controllers; use app\controllers\CommonController; use app\models\Pay; use Yii; class PayController extends CommonController { public $enableCsrfValidation = false; public function actionNotify() { if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if (Pay::notify($post)) { echo "success"; exit; } echo "fail"; exit; } } public function actionReturn() { $this->layout = 'layout1'; $status = Yii::$app->request->get('trade_status'); if ($status == 'TRADE_SUCCESS') { $s = 'ok'; } else { $s = 'no'; } return $this->render("status", ['status' => $s]); } }
10,355
https://github.com/CruGlobal/godtools-ios/blob/master/godtools/godtools-ios-api/Models/GTLanguage.m
Github Open Source
Open Source
MIT
2,016
godtools-ios
CruGlobal
Objective-C
Code
87
302
// // GTLanguage.m // godtools // // Created by Michael Harrison on 10/13/15. // Copyright © 2015 Michael Harrison. All rights reserved. // #import "GTLanguage.h" #import "GTPackage.h" @implementation GTLanguage + (instancetype)languageWithCode:(NSString *)code inContext:(NSManagedObjectContext *)context { GTLanguage *language = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([self class]) inManagedObjectContext:context]; language.code = code; return language; } - (NSComparisonResult)compare:(GTLanguage *)otherLanguage { NSLocale *deviceLocale = [NSLocale currentLocale]; return [[deviceLocale displayNameForKey:NSLocaleIdentifier value: self.code] compare: [deviceLocale displayNameForKey:NSLocaleIdentifier value:otherLanguage.code]]; } - (BOOL)hasUpdates { for (GTPackage *package in self.packages) { if (package.needsUpdate) { return YES; } } return NO; } @end
645
https://github.com/wobiancao/CoinMore/blob/master/app/src/main/java/com/morecoin/app/mvp/NoticeCoinImpl.java
Github Open Source
Open Source
Apache-2.0
2,018
CoinMore
wobiancao
Java
Code
157
608
package com.morecoin.app.mvp; import android.support.annotation.NonNull; import com.morecoin.app.base.BasePresenterImpl; import com.morecoin.app.base.IView; import com.morecoin.app.base.observer.SimpleObserver; import com.morecoin.app.bean.CoinNoticeBean; import com.morecoin.app.model.impl.BiNoticeModelImpl; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; /** * Created by wxy on 2018/1/4. */ public class NoticeCoinImpl extends BasePresenterImpl<NoticeCoinContract.NoticeCoinIView> implements NoticeCoinContract.NoticeCoinPresenter { private final long timeTask = 60 * 1000; private boolean isFirst = true; private Timer timer; @Override public void attachView(@NonNull IView iView) { super.attachView(iView); timer = new Timer(true); } @Override public void detachView() { if (timer != null) { task.cancel(); timer.cancel(); } } TimerTask task = new TimerTask() { public void run() { //每次需要执行的代码放到这里面。 onRefresh(); } }; @Override public void onRefresh() { BiNoticeModelImpl.getInstance().getNotice() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.newThread()) .subscribe(new SimpleObserver<CoinNoticeBean>() { @Override public void onNext(CoinNoticeBean value) { if (mView != null) { mView.onRefreshOver(); mView.onBindData(value); if (isFirst) { isFirst = false; if (timer != null) { timer.schedule(task, new Date(), timeTask); } } } } @Override public void onError(Throwable e) { if (mView != null) { mView.onRefreshOver(); } } }); } }
30,397
https://github.com/dongqingyueyue/imu_veh_calib/blob/master/run.sh
Github Open Source
Open Source
MIT
2,021
imu_veh_calib
dongqingyueyue
Shell
Code
5
25
./build/src/main -alsologtostderr -log_dir ./logs -logtostderr
50,310
https://github.com/CSWCSS-InnoTech/Schobol/blob/master/InnoTecheLearning/InnoTecheLearning/InnoTecheLearning/Utils/ValueTask.cs
Github Open Source
Open Source
Apache-2.0
2,017
Schobol
CSWCSS-InnoTech
C#
Code
2,021
5,352
using System; using System.Runtime.InteropServices; using System.Security; using System.Threading.Tasks; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { /// <summary> /// Indicates the type of the async method builder that should be used by a language compiler to /// build the attributed type when used as the return type of an async method. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Delegate | AttributeTargets.Enum, Inherited = false, AllowMultiple = false)] public sealed class AsyncMethodBuilderAttribute : Attribute { /// <summary>Initializes the <see cref="AsyncMethodBuilderAttribute"/>.</summary> /// <param name="builderType">The <see cref="Type"/> of the associated builder.</param> public AsyncMethodBuilderAttribute(Type builderType) { BuilderType = builderType; } /// <summary>Gets the <see cref="Type"/> of the associated builder.</summary> public Type BuilderType { get; } } /// <summary>Represents a builder for asynchronous methods that returns a <see cref="ValueTask{TResult}"/>.</summary> /// <typeparam name="TResult">The type of the result.</typeparam> [StructLayout(LayoutKind.Auto)] public struct AsyncValueTaskMethodBuilder<TResult> { /// <summary>The <see cref="AsyncTaskMethodBuilder{TResult}"/> to which most operations are delegated.</summary> private AsyncTaskMethodBuilder<TResult> _methodBuilder; /// <summary>The result for this builder, if it's completed before any awaits occur.</summary> private TResult _result; /// <summary>true if <see cref="_result"/> contains the synchronous result for the async method; otherwise, false.</summary> private bool _haveResult; /// <summary>true if the builder should be used for setting/getting the result; otherwise, false.</summary> private bool _useBuilder; /// <summary>Creates an instance of the <see cref="AsyncValueTaskMethodBuilder{TResult}"/> struct.</summary> /// <returns>The initialized instance.</returns> public static AsyncValueTaskMethodBuilder<TResult> Create() => new AsyncValueTaskMethodBuilder<TResult>() { _methodBuilder = AsyncTaskMethodBuilder<TResult>.Create() }; /// <summary>Begins running the builder with the associated state machine.</summary> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { _methodBuilder.Start(ref stateMachine); // will provide the right ExecutionContext semantics } /// <summary>Associates the builder with the specified state machine.</summary> /// <param name="stateMachine">The state machine instance to associate with the builder.</param> public void SetStateMachine(IAsyncStateMachine stateMachine) => _methodBuilder.SetStateMachine(stateMachine); /// <summary>Marks the task as successfully completed.</summary> /// <param name="result">The result to use to complete the task.</param> public void SetResult(TResult result) { if (_useBuilder) { _methodBuilder.SetResult(result); } else { _result = result; _haveResult = true; } } /// <summary>Marks the task as failed and binds the specified exception to the task.</summary> /// <param name="exception">The exception to bind to the task.</param> public void SetException(Exception exception) => _methodBuilder.SetException(exception); /// <summary>Gets the task for this builder.</summary> public ValueTask<TResult> Task { get { if (_haveResult) { return new ValueTask<TResult>(_result); } else { _useBuilder = true; return new ValueTask<TResult>(_methodBuilder.Task); } } } /// <summary>Schedules the state machine to proceed to the next action when the specified awaiter completes.</summary> /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="awaiter">the awaiter</param> /// <param name="stateMachine">The state machine.</param> public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); } /// <summary>Schedules the state machine to proceed to the next action when the specified awaiter completes.</summary> /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="awaiter">the awaiter</param> /// <param name="stateMachine">The state machine.</param> [SecuritySafeCritical] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); } } /// <summary>Provides an awaitable type that enables configured awaits on a <see cref="ValueTask{TResult}"/>.</summary> /// <typeparam name="TResult">The type of the result produced.</typeparam> [StructLayout(LayoutKind.Auto)] public struct ConfiguredValueTaskAwaitable<TResult> { /// <summary>The wrapped <see cref="ValueTask{TResult}"/>.</summary> private readonly ValueTask<TResult> _value; /// <summary>true to attempt to marshal the continuation back to the original context captured; otherwise, false.</summary> private readonly bool _continueOnCapturedContext; /// <summary>Initializes the awaitable.</summary> /// <param name="value">The wrapped <see cref="ValueTask{TResult}"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original synchronization context captured; otherwise, false. /// </param> internal ConfiguredValueTaskAwaitable(ValueTask<TResult> value, bool continueOnCapturedContext) { _value = value; _continueOnCapturedContext = continueOnCapturedContext; } /// <summary>Returns an awaiter for this <see cref="ConfiguredValueTaskAwaitable{TResult}"/> instance.</summary> public ConfiguredValueTaskAwaiter GetAwaiter() { return new ConfiguredValueTaskAwaiter(_value, _continueOnCapturedContext); } /// <summary>Provides an awaiter for a <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary> [StructLayout(LayoutKind.Auto)] public struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion { /// <summary>The value being awaited.</summary> private readonly ValueTask<TResult> _value; /// <summary>The value to pass to ConfigureAwait.</summary> private readonly bool _continueOnCapturedContext; /// <summary>Initializes the awaiter.</summary> /// <param name="value">The value to be awaited.</param> /// <param name="continueOnCapturedContext">The value to pass to ConfigureAwait.</param> internal ConfiguredValueTaskAwaiter(ValueTask<TResult> value, bool continueOnCapturedContext) { _value = value; _continueOnCapturedContext = continueOnCapturedContext; } /// <summary>Gets whether the <see cref="ConfiguredValueTaskAwaitable{TResult}"/> has completed.</summary> public bool IsCompleted { get { return _value.IsCompleted; } } /// <summary>Gets the result of the ValueTask.</summary> public TResult GetResult() { return _value._task == null ? _value._result : _value._task.GetAwaiter().GetResult(); } /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary> public void OnCompleted(Action continuation) { _value.AsTask().ConfigureAwait(_continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary> public void UnsafeOnCompleted(Action continuation) { _value.AsTask().ConfigureAwait(_continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } } } /// <summary>Provides an awaiter for a <see cref="ValueTask{TResult}"/>.</summary> public struct ValueTaskAwaiter<TResult> : ICriticalNotifyCompletion { /// <summary>The value being awaited.</summary> private readonly ValueTask<TResult> _value; /// <summary>Initializes the awaiter.</summary> /// <param name="value">The value to be awaited.</param> internal ValueTaskAwaiter(ValueTask<TResult> value) { _value = value; } /// <summary>Gets whether the <see cref="ValueTask{TResult}"/> has completed.</summary> public bool IsCompleted { get { return _value.IsCompleted; } } /// <summary>Gets the result of the ValueTask.</summary> public TResult GetResult() { return _value._task == null ? _value._result : _value._task.GetAwaiter().GetResult(); } /// <summary>Schedules the continuation action for this ValueTask.</summary> public void OnCompleted(Action continuation) { _value.AsTask().ConfigureAwait(continueOnCapturedContext: true).GetAwaiter().OnCompleted(continuation); } /// <summary>Schedules the continuation action for this ValueTask.</summary> public void UnsafeOnCompleted(Action continuation) { _value.AsTask().ConfigureAwait(continueOnCapturedContext: true).GetAwaiter().UnsafeOnCompleted(continuation); } } } namespace System.Threading.Tasks { /// <summary> /// Provides a value type that wraps a <see cref="Task{TResult}"/> and a <typeparamref name="TResult"/>, /// only one of which is used. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <remarks> /// <para> /// Methods may return an instance of this value type when it's likely that the result of their /// operations will be available synchronously and when the method is expected to be invoked so /// frequently that the cost of allocating a new <see cref="Task{TResult}"/> for each call will /// be prohibitive. /// </para> /// <para> /// There are tradeoffs to using a <see cref="ValueTask{TResult}"/> instead of a <see cref="Task{TResult}"/>. /// For example, while a <see cref="ValueTask{TResult}"/> can help avoid an allocation in the case where the /// successful result is available synchronously, it also contains two fields whereas a <see cref="Task{TResult}"/> /// as a reference type is a single field. This means that a method call ends up returning two fields worth of /// data instead of one, which is more data to copy. It also means that if a method that returns one of these /// is awaited within an async method, the state machine for that async method will be larger due to needing /// to store the struct that's two fields instead of a single reference. /// </para> /// <para> /// Further, for uses other than consuming the result of an asynchronous operation via await, /// <see cref="ValueTask{TResult}"/> can lead to a more convoluted programming model, which can in turn actually /// lead to more allocations. For example, consider a method that could return either a <see cref="Task{TResult}"/> /// with a cached task as a common result or a <see cref="ValueTask{TResult}"/>. If the consumer of the result /// wants to use it as a <see cref="Task{TResult}"/>, such as to use with in methods like Task.WhenAll and Task.WhenAny, /// the <see cref="ValueTask{TResult}"/> would first need to be converted into a <see cref="Task{TResult}"/> using /// <see cref="ValueTask{TResult}.AsTask"/>, which leads to an allocation that would have been avoided if a cached /// <see cref="Task{TResult}"/> had been used in the first place. /// </para> /// <para> /// As such, the default choice for any asynchronous method should be to return a <see cref="Task"/> or /// <see cref="Task{TResult}"/>. Only if performance analysis proves it worthwhile should a <see cref="ValueTask{TResult}"/> /// be used instead of <see cref="Task{TResult}"/>. There is no non-generic version of <see cref="ValueTask{TResult}"/> /// as the Task.CompletedTask property may be used to hand back a successfully completed singleton in the case where /// a <see cref="Task"/>-returning method completes synchronously and successfully. /// </para> /// </remarks> [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder<>))] [StructLayout(LayoutKind.Auto)] public struct ValueTask<TResult> : IEquatable<ValueTask<TResult>> { /// <summary>The task to be used if the operation completed asynchronously or if it completed synchronously but non-successfully.</summary> internal readonly Task<TResult> _task; /// <summary>The result to be used if the operation completed successfully synchronously.</summary> internal readonly TResult _result; /// <summary>Initialize the <see cref="ValueTask{TResult}"/> with the result of the successful operation.</summary> /// <param name="result">The result.</param> public ValueTask(TResult result) { _task = null; _result = result; } /// <summary> /// Initialize the <see cref="ValueTask{TResult}"/> with a <see cref="Task{TResult}"/> that represents the operation. /// </summary> /// <param name="task">The task.</param> public ValueTask(Task<TResult> task) { _task = task ?? throw new ArgumentNullException(nameof(task)); _result = default(TResult); } /// <summary> /// Initialize the <see cref="ValueTask{TResult}"/> with an async <see cref="Func{TResult}"/>. /// </summary> /// <param name="func">The function.</param> public ValueTask(Func<TResult> func) { _task = Task.Run(func ?? throw new ArgumentNullException(nameof(func))); _result = default(TResult); } /// <summary> /// Initialize the <see cref="ValueTask{TResult}"/> with an async <see cref="Func{Task{TResult}}"/>. /// </summary> /// <param name="taskfunc">The function.</param> public ValueTask(Func<Task<TResult>> taskfunc) { _task = Task.Run(taskfunc ?? throw new ArgumentNullException(nameof(taskfunc))); _result = default(TResult); } /// <summary>Returns the hash code for this instance.</summary> public override int GetHashCode() { return _task != null ? _task.GetHashCode() : _result != null ? _result.GetHashCode() : 0; } /// <summary>Returns a value indicating whether this value is equal to a specified <see cref="object"/>.</summary> public override bool Equals(object obj) { return obj is ValueTask<TResult> && Equals((ValueTask<TResult>)obj); } /// <summary>Returns a value indicating whether this value is equal to a specified <see cref="ValueTask{TResult}"/> value.</summary> public bool Equals(ValueTask<TResult> other) { return _task != null || other._task != null ? _task == other._task : EqualityComparer<TResult>.Default.Equals(_result, other._result); } /// <summary>Returns a value indicating whether two <see cref="ValueTask{TResult}"/> values are equal.</summary> public static bool operator ==(ValueTask<TResult> left, ValueTask<TResult> right) { return left.Equals(right); } /// <summary>Returns a value indicating whether two <see cref="ValueTask{TResult}"/> values are not equal.</summary> public static bool operator !=(ValueTask<TResult> left, ValueTask<TResult> right) { return !left.Equals(right); } /// <summary> /// Gets a <see cref="Task{TResult}"/> object to represent this ValueTask. It will /// either return the wrapped task object if one exists, or it'll manufacture a new /// task object to represent the result. /// </summary> public Task<TResult> AsTask() { // Return the task if we were constructed from one, otherwise manufacture one. We don't // cache the generated task into _task as it would end up changing both equality comparison // and the hash code we generate in GetHashCode. return _task ?? Task.FromResult(_result); } /// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a completed operation.</summary> public bool IsCompleted { get { return _task == null || _task.IsCompleted; } } /// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a successfully completed operation.</summary> public bool IsCompletedSuccessfully { get { return _task == null || _task.Status == TaskStatus.RanToCompletion; } } /// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a failed operation.</summary> public bool IsFaulted { get { return _task != null && _task.IsFaulted; } } /// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a canceled operation.</summary> public bool IsCanceled { get { return _task != null && _task.IsCanceled; } } /// <summary>Gets the result.</summary> public TResult Result { get { return _task == null ? _result : _task.GetAwaiter().GetResult(); } } /// <summary>Gets the id of this task, or -1 if task not running.</summary> public int Id { get => _task?.Id ?? -1; } /// <summary>Gets an awaiter for this value.</summary> public ValueTaskAwaiter<TResult> GetAwaiter() { return new ValueTaskAwaiter<TResult>(this); } /// <summary>Configures an awaiter for this value.</summary> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the captured context; otherwise, false. /// </param> public ConfiguredValueTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext) { return new ConfiguredValueTaskAwaitable<TResult>(this, continueOnCapturedContext: continueOnCapturedContext); } /// <summary>Gets a string-representation of this <see cref="ValueTask{TResult}"/>.</summary> public override string ToString() { if (_task != null) { return _task.Status == TaskStatus.RanToCompletion && _task.Result != null ? _task.Result.ToString() : string.Empty; } else { return _result != null ? _result.ToString() : string.Empty; } } // TODO: Remove CreateAsyncMethodBuilder once the C# compiler relies on the AsyncBuilder attribute. /// <summary>Creates a method builder for use with an async method.</summary> /// <returns>The created builder.</returns> [EditorBrowsable(EditorBrowsableState.Never)] // intended only for compiler consumption public static AsyncValueTaskMethodBuilder<TResult> CreateAsyncMethodBuilder() => AsyncValueTaskMethodBuilder<TResult>.Create(); } }
12,649
https://github.com/chat-codes/atom-chat-codes/blob/master/lib/services/watch-editor.js
Github Open Source
Open Source
MIT
2,017
atom-chat-codes
chat-codes
JavaScript
Code
444
1,819
'use babel'; const _ = require('underscore'); const $ = require('jquery'); const EventEmitter = require('events'); const {Point,Range} = require('atom'); export class WatchEditor extends EventEmitter { constructor(editor) { super(); this.editor = editor; this.observers = []; this.ignoreChanges = false; this.changeQueue = []; this.sendChanges = _.debounce(() => { const changeQueue = this.changeQueue; if(changeQueue.length > 0) { const changes = _ .chain(changeQueue) .pluck('changes') .flatten(true) .map((c) => { return { newRange: this.serializeRange(c.newRange), oldRange: this.serializeRange(c.oldRange), newText: c.newText, oldText: c.oldText }; }) .value(); const lastChange = _.last(changeQueue); const delta = { type: 'edit', id: editor.id, timestamp: lastChange.timestamp, changes: changes }; this.emit('editor-event', this.serializeDelta(delta)); } this.changeQueue = []; }, 50); } ready() { this.instrumentEditor(this.editor); // var teObserver = atom.workspace.observeTextEditors((editor) => { // this.instrumentEditor(editor); // }); // this.observers.push(teObserver); } beginIgnoringChanges() { this.ignoreChanges = true; } endIgnoringChanges() { this.ignoreChanges = false; } isIgnoringChanges() { return this.ignoreChanges; } serializeDelta(delta) { if(delta.type === 'edit') { return _.extend({}, delta, { changes: _.map(delta.changes, (c) => { return _.omit(c, 'oldRangeAnchor', 'newRangeAnchor'); }) }); } else { return delta; } } instrumentEditor(editor) { const buffer = editor.getBuffer(); this.currentGrammarName = editor.getGrammar().name; this.currentTitle = editor.getTitle(); const openDelta = { type: 'open', id: editor.id, contents: editor.getText(), grammarName: this.currentGrammarName, title: this.currentTitle, modified: editor.isModified() }; this.emit('editor-event', openDelta); var cursorObservers = editor.observeCursors((cursor) => { this.instrumentCursor(cursor, editor); }); var selectionObservers = editor.onDidChangeSelectionRange((event) => { const {oldBufferRange,newBufferRange,selection} = event; this.emit('cursor-event', { id: selection.cursor.id, editorID: editor.id, newRange: this.serializeRange(newBufferRange), oldRange: this.serializeRange(oldBufferRange), type: 'change-selection' }); }); var destroyObserver = editor.onDidDestroy(() => { const delta = { type: 'destroy', id: editor.id }; this.emit('editor-event', this.serializeDelta(delta)); }); var titleObserver = editor.onDidChangeTitle(() => { const title = editor.getTitle(); const delta = { type: 'title', newTitle: title, oldTitle: this.currentTitle, id: editor.id }; this.currentTitle = title; this.emit('editor-event', this.serializeDelta(delta)); }); var changeObserver = buffer.onDidChangeText((event) => { if(event.changes.length > 0) { if(!this.isIgnoringChanges()) { this.changeQueue.push({ changes: event.changes, }); this.sendChanges(); } } }); var grammarChangeObserver = editor.onDidChangeGrammar((grammar) => { const grammarName = editor.getGrammar().name; const delta = { type: 'grammar', newGrammarName: grammarName, oldGrammarName: this.currentGrammarName, id: editor.id }; this.currentGrammarName = grammarName; this.emit('editor-event', this.serializeDelta(delta)); }); var modifiedObserver = buffer.onDidChangeModified((isModified) => { const delta = { type: 'modified', id: editor.id, modified: isModified, oldModified: !isModified }; this.emit('editor-event', this.serializeDelta(delta)); }); this.observers.push(cursorObservers, destroyObserver, titleObserver, changeObserver, grammarChangeObserver, modifiedObserver, selectionObservers); } serializeCursor(cursor) { const marker = cursor.getMarker(); return { id: cursor.id, range: this.serializeRange(marker.getBufferRange()) }; } instrumentCursor(cursor, editor) { var destroyObserver = cursor.onDidDestroy(() => { this.emit('cursor-event', { type: 'destroy', editorID: editor.id, id: cursor.id }); }); var changePositionObserver = cursor.onDidChangePosition(_.throttle((event) => { const marker = cursor.getMarker(); this.emit('cursor-event', { id: cursor.id, editorID: editor.id, type: 'change-position', newRange: this.serializeRange(marker.getBufferRange()), oldBufferPosition: event.oldBufferPosition.serialize(), newBufferPosition: event.newBufferPosition.serialize(), }); }, 300)); this.observers.push(destroyObserver, changePositionObserver); } serializeRange(range) { return { start: range.start.serialize(), end: range.end.serialize() }; } serializeChange(change) { return this.serializeChange(c); } destroy() { _.each(this.observers, (o) => { o.dispose(); }) this.observers = []; } }
15,830
https://github.com/xy371661665/XYTrainTicket/blob/master/XYTrainTicket/Utils/Http/request/CheckVerify.h
Github Open Source
Open Source
MIT
null
XYTrainTicket
xy371661665
C
Code
36
127
// // CheckVerify.h // XYTrainTicket // // Created by apple on 2019/7/7. // Copyright © 2019 apple. All rights reserved. // #import <Foundation/Foundation.h> #import "RequestObj.h" NS_ASSUME_NONNULL_BEGIN @interface CheckVerify : NSObject<RequestObj> @property (nonatomic,copy) NSString* anwser; @end NS_ASSUME_NONNULL_END
2,483
https://github.com/wanswap/wansproject/blob/master/packages/testcases/src.ts/generation-scripts/abi.ts
Github Open Source
Open Source
MIT
2,020
wansproject
wanswap
TypeScript
Code
2,195
5,680
"use strict"; //let web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8549')); //import { compile as _compile } from "solc"; import { solc } from "@wansproject/cli"; import { randomHexString, randomNumber } from ".." import { BN, keccak256, toChecksumAddress } from "ethereumjs-util"; function hasPrefix(str: string, prefix: string): boolean { return (str.substring(0, prefix.length) === prefix); } function repeat(str: string, count: number): string { let result = ""; for (let i = 0; i < count; i++) { result += str; } return result; } function indent(tabs: number): string { let result = ''; while (result.length < 4 * tabs) { result += " "; } return result; } function getStructName(base: string): string { return "Struct" + keccak256(base).slice(0, 4).toString("hex"); } class Code { depth: number; lines: Array<string>; constructor() { this.depth = 0; this.lines = []; } get code(): string { return this.lines.join("\n"); //.replace(/ +\n/g, "\n").replace(/(\}\n\n+)/g, "}\n"); } comment(line: string): void { this.add(""); this.add("/" + "/ " + line); } add(line: string): void { let open = (line.trim().substring(line.trim().length - 1) === "{"); let close = line.trim()[0] === "}"; if (close) { this.depth--; } this.lines.push(indent(this.depth) + line); //if (close) { this.lines.push(""); } if (open) { this.depth++; } } } //idea: "tuple(address)/*StructABCDEFG*/" type TestData = { // The data type type: string, // Value must normally be defined, but may be omitted for // getting gen code for declarations value?: any, // The name of the struct (Tuples only) struct?: string }; let chars: Array<string> = []; function addChars(start: number, length: number): void { for (let i = start; i < start + length; i++) { chars.push(String.fromCharCode(i)); } } addChars(48, 10); addChars(65, 26); // Yen @TODO //addChars(165, 1); type GenCode = { assign: (name: string, code: Code) => void, decl: (name: string) => string, structs: (code: Code) => void, }; // Returns the functions required to generate code for a specific parameter type and value function getGenCode(testData: TestData): GenCode { let type = testData.type; let value = (testData.value != null) ? testData.value: "__crash__"; let isArray = type.match(/^(.*)(\[[0-9]*\])$/); if (isArray) { let base = isArray[1]; let suffix = isArray[2]; let isDynamic = (isArray[2] === "[]"); return { assign: (name: string, code: Code) => { if (isDynamic) { //let child = getGenCode({ type: base }); //let decl = child.decl(name).split(" "); let struct = base; if (type.substring(0, 5) === "tuple") { struct = getStructName(base); } code.add(name + " = new " + struct + "[](" + String(value.length) + ");"); } (<Array<any>>value).forEach((value, index) => { console.log("SSS", base, value); let child = getGenCode({ type: base, value: value }); child.assign(name + "[" + String(index) + "]", code); }); }, decl: (name: string) => { let child = getGenCode({ type: isArray[1] }); // Inject the array suffix to the type and add memory location // - uint256 p0 => uint256[] memory p0 // - bytes memory p0 => bytes[] memory p0 let result = child.decl(name).split(" "); result[0] = result[0] + suffix; if (result[1] !== "memory") { result.splice(1, 0, "memory"); } return result.join(" "); }, structs: (code: Code) => { let child = getGenCode({ type: isArray[1] }); child.structs(code); } } } let isTuple = type.match(/^tuple\((.*)\)$/); if (isTuple) { let children: Array<string> = []; // Split up the child types let accum = ""; let balance = 0; let types = isTuple[1]; for (let i = 0; i < types.length; i++) { let c = types[i]; if (c === "(") { balance++; accum += c; } else if (c === ")") { balance--; accum += c; } else if (c === ",") { if (balance === 0) { children.push(accum); accum = ""; } else { accum += c; } } else { accum += c; } } if (accum) { children.push(accum); } return { assign: (name: string, code: Code) => { children.forEach((child, index) => { console.log("TT", child, value[index]); getGenCode({ type: child, value: value[index] }).assign(name + ".m" + String(index), code); }); }, decl: (name: string) => { return (getStructName(type) + " memory " + name); }, structs: (code: Code) => { // Include any dependency Structs first children.forEach((child) => { getGenCode({ type: child }).structs(code); }); // Add this struct code.add("struct " + getStructName(type) + " {"); children.forEach((child, index) => { let decl = getGenCode({ type: child }).decl("m" + String(index)).replace(" memory ", " "); code.add(decl + ";"); }); code.add("}"); } } } let isFixedBytes = type.match(/^bytes([0-9]+)$/); let isNumber = type.match(/^(u?)int([0-9]*)$/); let isFixedNumber = type.match(/^(u?)fixed(([0-9]+)x([0-9]+))?$/); if (type === "address" || type === "bool" || isNumber || isFixedNumber || isFixedBytes) { return { assign: (name: string, code: Code) => { if (type === "boolean") { code.add(name + " = " + (value ? "true": "false") + ";"); } else if (isFixedBytes) { code.add(name + " = hex\"" + value.substring(2) + "\";"); } else { code.add(name + " = " + value + ";"); } }, decl: (name: string) => { return (type + " " + name); }, structs: (code: Code) => { } } } if (type === "string") { return { assign: (name: string, code: Code) => { code.add(name + " = " + JSON.stringify(value) + ";"); }, decl: (name: string) => { return ("string memory " + name); }, structs: (code: Code) => { } } } if (type === "bytes") { let valueBytes = Buffer.from(value.substring(2), "hex"); return { assign: (name: string, code: Code) => { code.add("{"); code.add("bytes memory temp = new bytes(" + valueBytes.length + ");"); code.add(name + " = temp;"); code.add("assembly {"); // Store the length code.add("mstore(temp, " + valueBytes.length + ")"); // Store each byte for (let i = 0; i < valueBytes.length; i++) { code.add("mstore8(add(temp, " + (32 + i) + "), " + valueBytes[i] + ")"); } code.add("}"); code.add("}"); }, decl: (name: string) => { return ("bytes memory " + name); }, structs: (code: Code) => { } } } throw new Error("Could not produce GenCode: " + type); return null; } // Generates a random type and value for the type function generateTest(seed: string): (seed: string) => TestData { let basetype = randomNumber(seed + "-type", 0, 10) switch (basetype) { // Address case 0: return (seed: string) => { let value = toChecksumAddress(randomHexString(seed + "-value", 20)); return { type: "address", value: value } } // Boolean case 1: return (seed: string) => { let value = (randomNumber(seed + "-value", 0, 2) ? true: false); return { type: "bool", value: value } } // Number case 2: { let signed = randomNumber(seed + "-signed", 0, 2); let width = randomNumber(seed + "-width", 0, 33) * 8; let type = (signed ? "": "u") + "int"; // Allow base int and uint if (width) { type += String(width); } else { width = 256; } return (seed: string) => { let hex = randomHexString(seed + "-value", width / 8).substring(2); if (signed) { // Sign bit set (we don't bother with 2's compliment let msb = parseInt(hex[0], 16); if (msb >= 8) { hex = "-" + String(msb & 0x7) + hex.substring(1); } } let value = (new BN(hex, 16)).toString(); return { type: type, value: value } } } // Fixed case 3: { // Fixed Point values are not supported yet return generateTest(seed + "-next"); let signed = randomNumber(seed + "-signed", 0, 2); let width = randomNumber(seed + "-width", 0, 33) * 8; let decimals = 0; let maxDecimals = (new BN(repeat("7f", ((width === 0) ? 32: (width / 8))), 16)).toString().length - 1; let attempt = 0; while (true) { decimals = randomNumber(seed + "-decimals" + String(attempt), 0, 80); if (decimals < maxDecimals) { break; } attempt++; } let type = (signed ? "": "u") + "fixed"; // Allow base int and uint if (width) { type += String(width) + "x" + String(decimals); } else { width = 128; decimals = 18; } return (seed: string) => { let hex = randomHexString(seed + "-value", width / 8).substring(2); // Use the top bit to indicate negative values let negative = false; if (signed) { // Sign bit set (we don't bother with 2's compliment let msb = parseInt(hex[0], 16); if (msb >= 8) { hex = String(msb & 0x7) + hex.substring(1); negative = true; } } // Zero-pad the value so we get at least 1 whole digit let dec = (new BN(hex, 16)).toString(); while (dec.length < decimals + 1) { dec = "0" + dec; } // Split the decimals with the decimal point let split = dec.length - decimals; let value = dec.substring(0, split) + "." + dec.substring(split); if (negative) { value = "-" + value; } // Prevent ending in a decimal (e.g. "45." if (value.substring(value.length - 1) === ".") { value = value.substring(0, value.length - 1); } return { type: type, value: value } } } // BytesXX case 4: { let length = randomNumber(seed + "-length", 1, 33); let type = "bytes" + String(length); return (seed: string) => { let value = randomHexString(seed + "-value", length); return { type: type, value: value } } } // String case 5: return (seed: string) => { let length = randomNumber(seed + "-length", 0, 36) let value = ""; while (value.length < length) { value += chars[randomNumber(seed + "-value" + String(value.length), 0, chars.length)]; } return { type: "string", value: value } } // Bytes case 6: return (seed: string) => { let length = randomNumber(seed + "-length", 0, 12); // @TODO: increase this let value = randomHexString(seed + "-value", length); //let valueBytes = Buffer.from(value.substring(2), "hex"); return { type: "bytes", value: value } } // Fixed-Length Array (e.g. address[4]) case 7: // Falls-through // Dynamic-Length Array (e.g. address[]) case 8: { let dynamic = (basetype === 8); let subType = generateTest(seed + "-subtype"); let length = randomNumber(seed + "-length", 1, 3); let suffix = "[" + ((!dynamic) ? length: "") + "]"; let type = subType("-index0").type + suffix; return (seed: string) => { if (dynamic) { length = randomNumber(seed + "-length", 0, 3); } let children: Array<TestData> = [ ]; for (let i = 0; i < length; i++) { children.push(subType(seed + "-index" + String(i))); } return { type: type, value: children.map((data) => data.value) } } } // Tuple case 9: { let count = randomNumber(seed + "-count", 1, 8); let subTypes: Array<(seed: string) => TestData> = [ ]; for (let i = 0; i < count; i++) { let cSeed = seed + "-subtype" + String(i); subTypes.push(generateTest(cSeed)); } let type = "tuple(" + subTypes.map(s => s("-index0").type).join(",") + ")"; let struct = "Struct" + randomHexString(seed + "-name", 4).substring(2); return (seed: string) => { let children: Array<any> = [ ]; subTypes.forEach((subType) => { children.push(subType(seed + "-value")) }); return { type: type, struct: struct, value: children.map(c => c.value), } } } } throw new Error("bad things"); return null; } export type TestCase = { type: string; bytecode: string; encoded: string; packed: string; source: string; value: any; }; // Returns true iff the types are able to be non-standard pack encoded function checkPack(types: Array<string>): boolean { for (let i = 0; i < types.length; i++) { let type = types[i]; if (hasPrefix(type, "tuple")) { return false; } if (hasPrefix(type, "bytes[")) { return false; } if (hasPrefix(type, "string[")) { return false; } let firstDynamic = type.indexOf("[]"); if (firstDynamic >= 0 && firstDynamic != type.length - 2) { return false; } } return true; } // Generates a Solidity source files with the parameter types and values function generateSolidity(params: Array<TestData>): string { let plist = [ ]; for (let i = 0; i < params.length; i++) { plist.push("p" + String(i)); } let genCodes = params.map(p => getGenCode(p)); let code = new Code(); /////////////////// // Pragma code.add("pragma experimental ABIEncoderV2;"); code.add("pragma solidity ^0.5.5;"); code.add(""); /////////////////// // Header code.add("contract Test {"); /////////////////// // Structs genCodes.forEach((genCode) => { genCode.structs(code); }); /////////////////// // test function code.add("function test() public pure returns (" + genCodes.map((g, i) => (g.decl("p" + String(i)))).join(", ") + ") {"); genCodes.forEach((genCode, index) => { genCode.assign("p" + index, code); }); code.add("}"); /////////////////// // encode code.add("function encode() public pure returns (bytes memory data){"); code.comment("Declare all parameters"); genCodes.forEach((genCode, index) => { code.add(genCode.decl("p" + index) + ";"); }); code.comment("Assign all parameters"); genCodes.forEach((genCode, index) => { genCode.assign("p" + index, code); }); code.add(""); code.add("return abi.encode(" + params.map((p, i) => ("p" + i)).join(", ") + ");") code.add("}"); /////////////////// // encodePacked if (checkPack(params.map(p => p.type))) { code.add("function encodePacked() public pure returns (bytes memory data){"); code.comment("Declare all parameters"); genCodes.forEach((genCode, index) => { code.add(genCode.decl("p" + index) + ";"); }); code.comment("Assign all parameters"); genCodes.forEach((genCode, index) => { genCode.assign("p" + index, code); }); code.add(""); code.add("return abi.encodePacked(" + params.map((p, i) => ("p" + i)).join(", ") + ");") code.add("}"); } /////////////////// // Footer code.add("}"); return code.code; } for (let i = 0; i < 100; i++) { let params = [ ]; console.log(i, randomNumber(String(i) + "-length", 1, 6)) let length = randomNumber(String(i) + "-length", 1, 6); for (let j = 0; j < length; j++) { params.push(generateTest(String(i) + String(j) + "-type")(String(i) + String(j) + "-test")); } let solidity = generateSolidity(params); console.log(solidity); console.log(i); let bytecode = solc.compile(solidity)[0].bytecode; //console.log(params.map(p => p.type).join(", ")); //console.log(bytecode); let testcase = { //solidity: solidity, bytecode: bytecode, types: params.map(p => p.type), value: params.map(p => p.value), }; console.log(testcase); } /* let solidity = generateSolidity([ generateTest("test37")("foo"), generateTest("test2")("bar"), ]); console.log(solidity); console.log(compile(solidity)); */ /* for (let i = 0; i < 20; i++) { let test = generateTest(String(i)); let data = test(String(i) + "-root"); console.log(i); console.dir(data, { depth: null }); data.solidityDeclare("p0").forEach((line) => { console.log(indent(1), line); }); data.solidityAssign("p0").forEach((line) => { console.log(indent(1), line); }); console.log(""); } */
39,524
https://github.com/garrettkatz/cubbies/blob/master/rcons_grow_fig.py
Github Open Source
Open Source
MIT
null
cubbies
garrettkatz
Python
Code
180
789
import cube domain = cube.CubeDomain(2) import pickle as pk # with open("rce/N2pocket_D11_M1_cn0_0_mdb.pkl", "rb") as f: with open("rce/N2s29k_D14_M1_cn0_0_mdb.pkl", "rb") as f: mdb = pk.load(f) action_map = {v:k for k,v in domain.get_action_map().items()} import matplotlib.pyplot as pt import matplotlib.patches as mp from matplotlib import rcParams rcParams['font.family'] = 'serif' rcParams['font.size'] = 18 rcParams['text.usetex'] = True rcParams['text.latex.preamble'] = r'\boldmath' # fig, axs = pt.subplots(6, 1, figsize=(4,8)) # for r in range(6): # domain.render(mdb.prototypes[r] * (1 - mdb.wildcards[r]), axs[r], x0=0, y0=0, text=False) # axs[r].text(3, -.75, ",".join([action_map[a] for a in mdb.macros[r]])) # axs[r].axis("equal") # axs[r].axis('off') # r = 1 # domain.render(mdb.wildcards[r] * cube._K, axs[r], x0=-4, text=False) # axs[r].axis("equal") # axs[r].axis('off') RA = list(range(6)) RB = [0,1,2,6,7,8] for ab in (0,1): fig = pt.figure(figsize=(14,8)) ax = pt.gca() for i,r in enumerate([RA, RB][ab]): domain.render(mdb.prototypes[r] * (1 - mdb.wildcards[r]), ax, x0=0, y0=-4*i, text=False) pt.text(3, -4*i-.75, ",".join([action_map[a] for a in mdb.macros[r]])) # domain.render((1 - mdb.wildcards[r]) * cube._K, ax, x0=-7, y0=-4*i, text=False) # domain.render(mdb.prototypes[r], ax, x0=-12, y0=-4*i, text=False) # pt.text(-12.5, 3, r"$S_{r}$") # pt.text(-7.5, 3, r"$W_{r}$") # pt.text(-2, 3, r"$S_{r} \vee W_{r}$") # pt.text(10, 3, r"$m_{r}$") ax.axis("equal") ax.axis('off') # pt.tight_layout() pt.savefig(f"rcons_grow_{ab}.png") pt.show()
45,112
https://github.com/KerinPithawala/tern/blob/master/tern/analyze/default/live/collect.py
Github Open Source
Open Source
BSD-2-Clause
2,020
tern
KerinPithawala
Python
Code
284
797
# -*- coding: utf-8 -*- # # Copyright (c) 2021 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: BSD-2-Clause """ Functions to collect package metadata from a live container filesystem. These functions are similar to the default collect.py functions except the invoking of the scripts occurs in a different environment. """ import logging import os import re from tern.utils import rootfs from tern.utils import constants # global logger logger = logging.getLogger(constants.logger_name) def create_script(command, prereqs, method): """Create the script to execute in an unshared environment""" chroot_script = """#!{host_shell} mount -t proc /proc {mnt}/proc chroot {mnt} {fs_shell} -c "{snip}" """ host_script = """#!{host_shell} {host_shell} -c "{snip}" """ script = '' script_path = os.path.join(rootfs.get_working_dir(), constants.script_file) if method == 'container': script = chroot_script.format(host_shell=prereqs.host_shell, mnt=prereqs.host_path, fs_shell=prereqs.fs_shell, snip=command) if method == 'host': script = host_script.format(host_shell=prereqs.host_shell, snip=command) with open(script_path, 'w', encoding='utf-8') as f: f.write(script) os.chmod(script_path, 0o700) return script_path def snippets_to_script(snippet_list): """Create a script out of the snippet list such that it can be invokable via chroot's -c command""" replace_dict = {r'\$': r'\\$', r'\`': r'\\`'} final_list = [] for snippet in snippet_list: # replace the escaped characters for key, val in replace_dict.items(): snippet = re.sub(key, val, snippet) final_list.append(snippet) return " && ".join(final_list) def invoke_live(snippet_list, prereqs, method): """Given a list of commands to run, invoke the commands and return the result. The prereqs object should""" # we first create a single command from the snippet list command = snippets_to_script(snippet_list) logger.debug("Invoking command: %s", command) # we then insert this command into our unshare script script_path = create_script(command, prereqs, method) if method == 'container': full_cmd = ['unshare', '-mpf', '-r', script_path] if method == 'host': full_cmd = ['unshare', '-pf', '-r', script_path] # invoke the script and remove it output, error = rootfs.shell_command(False, full_cmd) os.remove(script_path) return output, error
6,180
https://github.com/2694048168/ComputerVisionDeepLearning/blob/master/DigitalImageProcessing/cpp/spectral_residual_significance.cpp
Github Open Source
Open Source
Apache-2.0
2,022
ComputerVisionDeepLearning
2694048168
C++
Code
465
2,251
/** * @File : spectral_residual_significance.cpp * @Brief : 显著性检测: 谱残差显著性检测 * @Author : Wei Li * @Date : 2021-10-21 */ #include <iostream> #include <vector> #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> // ------------ 快速离散傅里叶变换 ------------ void FFT2Image(cv::InputArray InputImage, cv::OutputArray img_fourier) { cv::Mat image = InputImage.getMat(); int rows = image.rows; int cols = image.cols; // 满足快速傅里叶变换的最优 行数 和 列数 int row_padding = cv::getOptimalDFTSize(rows); int col_padding = cv::getOptimalDFTSize(cols); // 左侧和下侧 zero-padding cv::Mat fourier; cv::copyMakeBorder(image, fourier, 0, row_padding - rows, 0, col_padding - cols, cv::BORDER_CONSTANT, cv::Scalar::all(0)); // 快速傅里叶变换 cv::dft(fourier, img_fourier, cv::DFT_COMPLEX_OUTPUT); } // ------------ 傅里叶变换的两个度量: 幅度谱和相位谱 ------------ void AmplitudeSpectrumFFT(cv::InputArray _srcFFT, cv::OutputArray _dstSpectrum) { // 实部和虚部两个通道 CV_Assert(_srcFFT.channels() == 2); // 分离实部和虚部两个通道 std::vector<cv::Mat> FFT2channels; cv::split(_srcFFT, FFT2channels); // compute magnitude spectrum of FFT cv::magnitude(FFT2channels[0], FFT2channels[1], _dstSpectrum); } // 对于傅里叶谱的灰度级显示,OpenCV 提供了函数 log, // 该函数可以计算矩阵中每一个值的对数。 // 进行归一化后,为了保存傅里叶谱的灰度级,有时需要将矩阵乘以 255,然后转换为 8 位图。 cv::Mat graySpectrum(cv::Mat spectrum) { cv::Mat dst; cv::log(spectrum + 1, dst); cv::normalize(dst, dst, 0, 1, cv::NORM_MINMAX); // 为了灰度级可视化 dst.convertTo(dst, CV_8UC1, 255, 0); return dst; } // OpenCV function : cv::phase(x, y, angle, angleInDegress); cv::Mat PhaseSpectrum(cv::Mat _srcFFT) { cv::Mat phase_spectrum; phase_spectrum.create(_srcFFT.size(), CV_64FC1); std::vector<cv::Mat> FFT2channels; cv::split(_srcFFT, FFT2channels); // 计算相位谱 for (size_t r = 0; r < phase_spectrum.rows; ++r) { for (size_t c = 0; c < phase_spectrum.cols; ++c) { double real_part = FFT2channels[0].at<double>(r, c); double imaginary_part = FFT2channels[1].at<double>(r, c); // atan2 返回值范围 [0, 180], [-180, 0] phase_spectrum.at<double>(r, c) = std::atan2(imaginary_part, real_part); } } return phase_spectrum; } // ------------------------------- int main(int argc, char** argv) { if (argc > 1) { cv::Mat image = cv::imread(argv[1], 0); if (!image.data) { std::cout << "Error: reading image unsuccesfully." << std::endl; return -1; } cv::imshow("OriginImage", image); cv::Mat image_float; image.convertTo(image_float, CV_64FC1, 1.0 / 255); // ------------ 显著性检测: 谱残差检测 ------------ // step 1, computer fft of image cv::Mat fft_img; FFT2Image(image_float, fft_img); // step 2, compute amplitude spectrum of fft cv::Mat amplitude_spectrum; AmplitudeSpectrumFFT(fft_img, amplitude_spectrum); cv::Mat amplitude_spectrum_log; cv::log(amplitude_spectrum + 1.0, amplitude_spectrum_log); // step 3, 对幅度谱的灰度级进行均值平滑 cv::Mat mean_amplitude_spectrum_log; cv::blur(amplitude_spectrum_log, mean_amplitude_spectrum_log, cv::Size(3, 3), cv::Point(-1, -1)); // step 4, 计算谱残差 cv::Mat spectrum_residual = amplitude_spectrum_log - mean_amplitude_spectrum_log; // step 5, 相位谱 cv::Mat phase_spectrum = PhaseSpectrum(fft_img); cv::Mat cos_spectrum(phase_spectrum.size(), CV_64FC1); cv::Mat sin_spectrum(phase_spectrum.size(), CV_64FC1); for (size_t r = 0; r < phase_spectrum.rows; ++r) { for (size_t c = 0; c < phase_spectrum.cols; ++c) { cos_spectrum.at<double>(r, c) = std::cos(phase_spectrum.at<double>(r, c)); sin_spectrum.at<double>(r, c) = std::sin(phase_spectrum.at<double>(r, c)); } } // step 6, 谱残差的幂指数运算 cv::exp(spectrum_residual, spectrum_residual); cv::Mat real_part = spectrum_residual.mul(cos_spectrum); cv::Mat imaginary_part = spectrum_residual.mul(sin_spectrum); std::vector<cv::Mat> real_imaginary_img; real_imaginary_img.push_back(real_part); real_imaginary_img.push_back(imaginary_part); cv::Mat complex_img; cv::merge(real_imaginary_img, complex_img); // step 7, 根据新的幅度谱和相位谱, 进行傅里叶逆变换 cv::Mat ifft_img; cv::dft(complex_img, ifft_img, cv::DFT_COMPLEX_OUTPUT + cv::DFT_INVERSE); // step 8, 显著性 cv::Mat ifft_amplitude; AmplitudeSpectrumFFT(ifft_img, ifft_amplitude); // 平方运算 cv::pow(ifft_amplitude, 2.0, ifft_amplitude); // 对显著性进行高斯平滑 cv::GaussianBlur(ifft_amplitude, ifft_amplitude, cv::Size(5, 5), 2.5); // 显著性显示 cv::normalize(ifft_amplitude, ifft_amplitude, 1.0, 0, cv::NORM_MINMAX); // 利用 伽马变换提高对比度 cv::pow(ifft_amplitude, 0.5, ifft_amplitude); // data type convert cv::Mat saliency_map; ifft_amplitude.convertTo(saliency_map, CV_8UC1, 255); cv::imshow("SaliencyMap", saliency_map); cv::waitKey(0); cv::destroyAllWindows(); return 0; } else { std::cout << "Usage: OpenCV python script imageFile." << std::endl; return -1; } }
13,501
https://github.com/voutilad/nng-java/blob/master/src/main/java/io/sisu/nng/aio/Context.java
Github Open Source
Open Source
MIT
2,021
nng-java
voutilad
Java
Code
1,674
3,703
package io.sisu.nng.aio; import io.sisu.nng.Message; import io.sisu.nng.Nng; import io.sisu.nng.NngException; import io.sisu.nng.Socket; import io.sisu.nng.internal.ContextStruct; import io.sisu.nng.internal.NngOptions; import io.sisu.nng.internal.SocketStruct; import java.util.HashMap; import java.util.Map; import java.util.concurrent.*; import java.util.function.BiConsumer; import java.util.function.Consumer; /** * Wrapper of an NNG context, allowing for multi-threaded use of individual Sockets. * * Unlike the native nng_context, the Java Context provides a built in event dispatcher for the * common event types (data received, data sent, wake from sleep). While I'm still designing the * high-level API around this, for now there are 3 potential approaches for using a Context: * * 1. Synchronously using sendMessageSync()/recvMessageSync * 2. Asynchronously with CompletableFutures using sendMessage()/recvMessage() * 3. Asynchronously with callbacks via (optionally) registering event handlers. * * In the 3rd case (event handlers), one must "set the wheels in motion" by performing an initial * asynchronous operation (like via a recvMessage() call). * * NOTE: Given Contexts are primarily for asynchronous usage and don't require their own dedicated * threads, it's important to keep the Context from being garbage collected. */ public class Context implements AutoCloseable { private final Socket socket; private final ContextStruct.ByValue context; private AioCallback<?> aioCallback; private Aio aio; private final BlockingQueue<Work> queue = new LinkedBlockingQueue<>(); private final HashMap<String, Object> stateMap = new HashMap<>(); private final Map<Event, BiConsumer<ContextProxy, Message>> eventHandlers = new HashMap<>(); private static final BiConsumer<ContextProxy, Message> noop = (a, m) -> {}; /** * The supported asynchronous event types, corresponding to the core asynchronous operations */ public enum Event { RECV, SEND, WAKE, } /** * A unit of asynchronous work awaiting completion. Effectively a container for state while * the Context waits for the AioCallback to fire. */ public static class Work { // Type of Work we're expecting public final Event event; // The CompletableFuture to notify upon completion or exception public final CompletableFuture<Object> future; public Message msg = null; public Work(Event event, CompletableFuture<Object> future) { this.event = event; this.future = future; } } /** * A {@link ContextProxy} instance bound to this Context. */ private final ContextProxy proxy = new ContextProxy() { @Override public void send(Message message) { sendMessage(message); } @Override public void receive() { receiveMessage(); } @Override public void sleep(int millis) { Context.this.sleep(millis); } @Override public void put(String key, Object value) { stateMap.put(key, value); } @Override public Object get(String key) { return stateMap.get(key); } @Override public Object getOrDefault(Object key, Object defaultValue) { return stateMap.getOrDefault(key, defaultValue); } }; /** * Asynchronous handler for dispatching queued Work to appropriate event handlers based on the * Work's Event type. * * @param aioProxy reference to the AioProxy for the underlying nng aio instance * @param ctx reference to the Context this method is dispatching for */ private static void dispatch(AioProxy aioProxy, Context ctx) { try { // XXX: to guard against race conditions, we using a poll-based approach in case the // callback fires before the work is added to the queue. (Should only happen if empty.) Work work = ctx.queue.poll(5, TimeUnit.SECONDS); if (work == null) { // XXX: no known work or queue is cleared because we're closing the Context return; } try { // Raises an exception on error, but for successful sends, receives, or wakes will // pass normally. aioProxy.assertSuccessful(); // Look up a potential event handler BiConsumer<ContextProxy, Message> consumer = ctx.eventHandlers.getOrDefault(work.event, noop); Object result = null; // Todo: Excessive use of switch at the moment switch (work.event) { case RECV: result = aioProxy.getMessage(); break; case SEND: // fallthrough case WAKE: break; default: System.err.println("Unexpected event type: " + work.event); } // Apply the event handler with the optional Message consumer.accept(ctx.proxy, (Message) result); if (work.future != null) { work.future.complete(result); } } catch (NngException e) { // if we were sending and failed, we still own the message if (work.msg != null) { work.msg.setValid(); } if (work.future != null) { work.future.completeExceptionally(e); } } } catch (Exception e) { // We don't get specific yet on parsing failure types e.printStackTrace(); } } /** * Create a new Context for the given Socket. * * Note: Not all protocols support Contexts (e.g. Push0/Pull0) * * @param socket the given Socket to create a new Context for * @throws NngException on an nng error */ public Context(Socket socket) throws NngException { ContextStruct contextStruct = new ContextStruct(); SocketStruct.ByValue socketStruct = (SocketStruct.ByValue) socket.getSocketStruct(); int rv = Nng.lib().nng_ctx_open(contextStruct, socketStruct); if (rv != 0) { throw new NngException(Nng.lib().nng_strerror(rv)); } this.socket = socket; this.context = new ContextStruct.ByValue(contextStruct); this.aioCallback = new AioCallback<>(Context::dispatch, this); this.aio = new Aio(aioCallback); } /** * Set a receive event handler on the Context, replacing the existing if present. It will be * called upon completion of a Receive event regardless of outcome. * * The handler is of the form BiConsumer&lt;Contextproxy, Message&gt; and will have a * reference to this Context's {@link ContextProxy} set as well as a reference the received * {@link Message} instance. * * Note: For now, with the current API, it's advised that the handler free the Message itself * if it's not using it for a send operation or storing it for later use. * * @param handler the receive event handler */ public void setRecvHandler(BiConsumer<ContextProxy, Message> handler) { this.eventHandlers.put(Event.RECV, handler); } /** * Set a send event handler on the Context, replacing the existing if present. It will be called * upon completion of a Send event regardless of outcome. * * The send handler will be provided a reference to a {@link ContextProxy}, corresponding to * this Context, when called. The handler should interact with the Context using the proxy and * not via a captured reference to the Context. * * @param handler the send handler to set */ public void setSendHandler(Consumer<ContextProxy> handler) { this.eventHandlers.put(Event.SEND, (aioProxy, unused) -> handler.accept(aioProxy)); } /** * Set a wake event handler on the Context, replacing the existing if present. It will be called * on completion of a sleep event, regardless of outcome. * * The wake handler will be provided a reference to a {@link ContextProxy}, corresponding to * this Context, when called. The handler should interact with the Context using the proxy and * not via a captured reference to the Context. * * @param handler the send handler to set */ public void setWakeHandler(Consumer<ContextProxy> handler) { this.eventHandlers.put(Event.WAKE, (aioProxy, unused) -> handler.accept(aioProxy)); } /** * Close the Context and try to safely release any resources (e.g. the Aio) in advance of * garbage collection. * * @throws NngException on error closing the Context */ public void close() throws NngException { queue.clear(); int rv = Nng.lib().nng_ctx_close(context); if (rv != 0) { throw new NngException(Nng.lib().nng_strerror(rv)); } aio.free(); } /** * Receive a {@link Message} asynchronously on this Context. The {@link Message} is owned by * the JVM and caller and should be either used for a subsequent send operation or freed when * no longer required. * * @return a CompletableFuture that is fulfilled with the {@link Message} upon success, or * completed exceptionally on failure or error. */ public CompletableFuture<Message> receiveMessage() { CompletableFuture<Object> future = new CompletableFuture<>(); this.queue.add(new Work(Event.RECV, future)); Nng.lib().nng_ctx_recv(context, aio.getAioPointer()); return future.thenApply(obj -> (Message) obj); } /** * Try to receive a Message on the Context, blocking until received. * * @return the received Message * @throws NngException on error or timeout */ public Message receiveMessageSync() throws NngException { try { return receiveMessage().get(); } catch (InterruptedException e) { throw new NngException("interrupted"); } catch (ExecutionException e) { if (e.getCause() instanceof NngException) { throw (NngException) e.getCause(); } else { throw new NngException("unknown execution exception"); } } } /** * Send a Message on the Context. If the Message is accepted for sending, the Message will be * invalidated. * * @param msg the Message to send * @return a {@link CompletableFuture} that will either complete on success or complete * exceptionally on error or timeout. It's the caller's responsibility to then either retry or * free the Message. */ public CompletableFuture<Void> sendMessage(Message msg) { // XXX: potential for TOCTOU, but we set the Message optimistically invalid before we know // if it's successfully been accepted for sending if (!msg.isValid()) { CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new IllegalStateException("Message is invalid")); return future; } CompletableFuture<Object> future = new CompletableFuture<>(); Work work = new Work(Event.SEND, future); // Set the a reference to the Message on the Work instance to keep it from being garbage // collected in case the caller doesn't keep a reference as well work.msg = msg; this.queue.add(work); // XXX: we set the Message invalid for now, assuming success. If the Message fails to send // then the event handler will set it back to valid msg.setInvalid(); aio.setMessage(msg); Nng.lib().nng_ctx_send(context, aio.getAioPointer()); return future.thenApply((unused) -> null); } /** * Attempt to send the given Message synchronously on the Context, blocking until it's either * accepted for sending, an error occurs, or a timeout. * * If the Message is accepted for sending, it will be marked invalid for future use. * * @param msg the Message to send * @throws NngException on error or timeout */ public void sendMessageSync(Message msg) throws NngException { try { sendMessage(msg).join(); } catch (Exception e) { if (e.getCause() instanceof NngException) { throw (NngException) e.getCause(); } else { throw new NngException("unknown execution exception"); } } } /** * Sleep the Context for the given duration, triggering the Wake handler upon timeout. * * @param millis number of milliseconds to sleep * @return a CompletableFuture that completes upon the wake event concluding or an error */ public CompletableFuture<Void> sleep(int millis) { CompletableFuture<Object> future = new CompletableFuture<>(); this.queue.add(new Work(Event.WAKE, future)); aio.sleep(millis); return future.thenApply((unused) -> null); } /** * Set a receive timeout on the Context. * * @param timeoutMillis timeout in milliseconds * @throws NngException on error setting the timeout */ public void setReceiveTimeout(int timeoutMillis) throws NngException { int rv = Nng.lib().nng_ctx_set_ms(this.context, NngOptions.RECV_TIMEOUT, timeoutMillis); if (rv != 0) { String err = Nng.lib().nng_strerror(rv); throw new NngException(err); } } /** * Set a send timeout on the Context * * @param timeoutMillis timeout in milliseconds * @throws NngException on error setting the timeout */ public void setSendTimeout(int timeoutMillis) throws NngException { int rv = Nng.lib().nng_ctx_set_ms(this.context, NngOptions.SEND_TIMEOUT, timeoutMillis); if (rv != 0) { String err = Nng.lib().nng_strerror(rv); throw new NngException(err); } } }
11,213
https://github.com/skeggse/slurp/blob/master/index.js
Github Open Source
Open Source
Unlicense
2,018
slurp
skeggse
JavaScript
Code
3
14
module.exports = require('./lib/slurp');
28,775
https://github.com/Daiz/openxcom-namegen/blob/master/.gitignore
Github Open Source
Open Source
MIT
2,014
openxcom-namegen
Daiz
Ignore List
Code
4
13
node_modules *.txt SoldierName bin
48,019
https://github.com/hernandazevedo/beagle/blob/master/android/beagle/src/main/java/br/com/zup/beagle/android/context/operations/strategy/array/IncludesOperation.kt
Github Open Source
Open Source
Apache-2.0
2,020
beagle
hernandazevedo
Kotlin
Code
150
376
/* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * 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 br.com.zup.beagle.android.context.operations.strategy.array import br.com.zup.beagle.android.context.operations.strategy.Operations import br.com.zup.beagle.android.context.operations.strategy.BaseOperation import br.com.zup.beagle.android.context.operations.parameter.Argument import br.com.zup.beagle.android.context.operations.parameter.Parameter internal class IncludesOperation( override val operationType: Operations ) : BaseOperation<Operations>() { override fun solve(parameter: Parameter): Any { val list = parameter.arguments[0].value as MutableList<Any?> val itemToInsert = parameter.arguments[1] list.add(itemToInsert) return list.map { (it as Argument).value }.toMutableList() } }
34,363
https://github.com/zhaitailang/yiishop/blob/master/api/models/Order.php
Github Open Source
Open Source
BSD-3-Clause
null
yiishop
zhaitailang
PHP
Code
473
1,492
<?php namespace api\models; use Yii; /** * This is the model class for table "{{%order}}". * * @property integer $id * @property string $order_num * @property integer $user_id * @property integer $business_id * @property integer $good_id * @property integer $mb_id * @property integer $mbv_id * @property string $user_address * @property integer $pay_type * @property string $good_price * @property integer $pay_num * @property string $good_total_price * @property string $order_fare * @property string $order_total_price * @property string $express_name * @property string $express_num * @property integer $status * @property integer $created_at * @property integer $pay_at * @property integer $deliver_at * @property integer $complete_at * @property string $good_var * @property string $cancel_text * @property string $message * * @property User $user * @property User $business * @property Good $good * @property GoodMb $mb * @property GoodMbv $mbv */ class Order extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%order}}'; } /** * @inheritdoc */ public function rules() { return [ [['order_num', 'user_id', 'business_id', 'good_id', 'mb_id', 'mbv_id', 'user_address', 'good_price', 'pay_num', 'good_total_price', 'order_fare', 'order_total_price', 'created_at'], 'required'], [['user_id', 'business_id', 'good_id', 'mb_id', 'mbv_id', 'pay_type', 'pay_num', 'status', 'created_at', 'pay_at', 'deliver_at', 'complete_at'], 'integer'], [['good_price', 'good_total_price', 'order_fare', 'order_total_price'], 'number'], [['order_num'], 'string', 'max' => 128], [['user_address', 'good_var'], 'string', 'max' => 1000], [['express_name', 'express_num'], 'string', 'max' => 50], [['cancel_text'], 'string', 'max' => 100], [['message'], 'string', 'max' => 300], [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']], [['business_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['business_id' => 'id']], [['good_id'], 'exist', 'skipOnError' => true, 'targetClass' => Good::className(), 'targetAttribute' => ['good_id' => 'id']], [['mb_id'], 'exist', 'skipOnError' => true, 'targetClass' => GoodMb::className(), 'targetAttribute' => ['mb_id' => 'id']], [['mbv_id'], 'exist', 'skipOnError' => true, 'targetClass' => GoodMbv::className(), 'targetAttribute' => ['mbv_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'order_num' => 'Order Num', 'user_id' => 'User ID', 'business_id' => 'Business ID', 'good_id' => 'Good ID', 'mb_id' => 'Mb ID', 'mbv_id' => 'Mbv ID', 'user_address' => 'User Address', 'pay_type' => 'Pay Type', 'good_price' => 'Good Price', 'pay_num' => 'Pay Num', 'good_total_price' => 'Good Total Price', 'order_fare' => 'Order Fare', 'order_total_price' => 'Order Total Price', 'express_name' => 'Express Name', 'express_num' => 'Express Num', 'status' => 'Status', 'created_at' => 'Created At', 'pay_at' => 'Pay At', 'deliver_at' => 'Deliver At', 'complete_at' => 'Complete At', 'good_var' => 'Good Var', 'message' => 'Message', 'cancel_text' => 'cancel Text', 'library_at' => '出库时间', ]; } /** * @return \yii\db\ActiveQuery */ public function getUser() { return $this->hasOne(User::className(), ['id' => 'user_id']); } /** * @return \yii\db\ActiveQuery */ public function getBusiness() { return $this->hasOne(User::className(), ['id' => 'business_id']); } /** * @return \yii\db\ActiveQuery */ public function getGood() { return $this->hasOne(Good::className(), ['id' => 'good_id']); } /** * @return \yii\db\ActiveQuery */ public function getMb() { return $this->hasOne(GoodMb::className(), ['id' => 'mb_id']); } /** * @return \yii\db\ActiveQuery */ public function getMbv() { return $this->hasOne(GoodMbv::className(), ['id' => 'mbv_id']); } }
18,127
https://github.com/learningequality/kolibri-installer-osx/blob/master/setup.py
Github Open Source
Open Source
MIT
null
kolibri-installer-osx
learningequality
Python
Code
72
339
import codecs import os.path from setuptools import setup def read(rel_path): here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, rel_path), "r") as fp: return fp.read() def get_version(rel_path): for line in read(rel_path).splitlines(): if line.startswith("__version__"): delim = '"' if '"' in line else "'" return line.split(delim)[1] else: raise RuntimeError("Unable to find version string.") setup( name="kolibri-app", version=get_version("src/kolibri_app/__init__.py"), description="wxPython app for the Kolibri Learning Platform.", author="Learning Equality", author_email="dev@learningequality.org", packages=[str("kolibri_app")], # https://github.com/pypa/setuptools/pull/597 package_dir={"": "src"}, include_package_data=True, zip_safe=True, license="MIT", install_requires=["wxPython==4.1.1"], extras_require={"dev": ["pre-commit"]}, )
24,033
https://github.com/indigogetter/dotnet-jwt-auth/blob/master/Api/Indigogetter.WebService.Auth/Program.cs
Github Open Source
Open Source
MIT
2,019
dotnet-jwt-auth
indigogetter
C#
Code
67
296
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace Indigogetter.WebService.Auth { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? String.Empty; config.SetBasePath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false); config.AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: false); }) .UseStartup<Startup>(); } }
15,650
https://github.com/nakupenda178/gclib/blob/master/modules/widgets/src/main/java/com/github/guqt178/widgets/drag/DragScrollDetailsLayout.java
Github Open Source
Open Source
Apache-2.0
2,021
gclib
nakupenda178
Java
Code
1,125
3,882
package com.github.guqt178.widgets.drag; import android.content.Context; import android.content.res.TypedArray; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import android.widget.LinearLayout; import android.widget.Scroller; import com.github.guqt178.widgets.R; /** * 1 ViewPager+TabLayout as content * 2 FragmentTabHost+Fragment as content * 3 bug :can not assertain which View is inTouch */ public class DragScrollDetailsLayout extends LinearLayout { public interface OnSlideFinishListener { void onStatueChanged(CurrentTargetIndex status); } public enum CurrentTargetIndex { UPSTAIRS, DOWNSTAIRS; public static CurrentTargetIndex valueOf(int index) { return 1 == index ? DOWNSTAIRS : UPSTAIRS; } } private static final float DEFAULT_PERCENT = 0.3f; private static final int DEFAULT_DURATION = 300; private int mMaxFlingVelocity; private int mMiniFlingVelocity; private int mDefaultPanel = 0; private int mDuration = DEFAULT_DURATION; private float mTouchSlop; private float mDownMotionY; private float mDownMotionX; private float mInitialInterceptY; public void setPercent(float percent) { mPercent = percent; } private float mPercent = DEFAULT_PERCENT; /** * flag for listview or scrollview ,if child overscrolled ,do not judge view region 滚过头了,还是可以滚动 */ private boolean mChildHasScrolled; private View mUpstairsView; private View mDownstairsView; private View mCurrentTargetView; private Scroller mScroller; private VelocityTracker mVelocityTracker; private OnSlideFinishListener mOnSlideDetailsListener; private CurrentTargetIndex mCurrentViewIndex = CurrentTargetIndex.UPSTAIRS; public DragScrollDetailsLayout(Context context) { this(context, null); } public DragScrollDetailsLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public DragScrollDetailsLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DragScrollDetailsLayout, defStyleAttr, 0); mPercent = a.getFloat(R.styleable.DragScrollDetailsLayout_percent, DEFAULT_PERCENT); mDuration = a.getInt(R.styleable.DragScrollDetailsLayout_duration, DEFAULT_DURATION); mDefaultPanel = a.getInt(R.styleable.DragScrollDetailsLayout_default_panel, 0); a.recycle(); mScroller = new Scroller(getContext(), new DecelerateInterpolator()); mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); mMaxFlingVelocity = ViewConfiguration.get(getContext()).getScaledMaximumFlingVelocity(); mMiniFlingVelocity = ViewConfiguration.get(getContext()).getScaledMinimumFlingVelocity(); setOrientation(VERTICAL); } public void setOnSlideDetailsListener(OnSlideFinishListener listener) { this.mOnSlideDetailsListener = listener; } @Override protected void onFinishInflate() { super.onFinishInflate(); final int childCount = getChildCount(); if (1 >= childCount) { throw new RuntimeException("SlideDetailsLayout only accept childs more than 1!!"); } mUpstairsView = getChildAt(0); mDownstairsView = getChildAt(1); } /** * requestDisallowInterceptTouchEvent guarantee DragScrollDetailsLayout intercept event as wish */ @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (!mScroller.isFinished()) { resetDownPosition(ev); return true; } Log.v("lishang", "" + getScrollY()); requestDisallowInterceptTouchEvent(false); return super.dispatchTouchEvent(ev); } /** * intercept rules: * 1. The vertical displacement is larger than the horizontal displacement; * 2. Panel stauts is UPSTAIRS: slide up * 3. Panel status is DOWNSTAIRS:slide down * 4. child can requestDisallowInterceptTouchEvent(); */ @Override public boolean onInterceptTouchEvent(MotionEvent ev) { switch (ev.getActionMasked()) { case MotionEvent.ACTION_DOWN: resetDownPosition(ev); break; case MotionEvent.ACTION_MOVE: adjustValidDownPoint(ev); return checkCanInterceptTouchEvent(ev); default: break; } return false; } private void resetDownPosition(MotionEvent ev) { mDownMotionX = ev.getX(); mDownMotionY = ev.getY(); if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.clear(); mChildHasScrolled = false; mInitialInterceptY = (int) ev.getY(); } @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getActionMasked()) { case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: flingToFinishScroll(); recycleVelocityTracker(); break; case MotionEvent.ACTION_MOVE: scroll(ev); break; default: break; } return true; } private boolean checkCanInterceptTouchEvent(MotionEvent ev) { final float xDiff = ev.getX() - mDownMotionX; final float yDiff = ev.getY() - mDownMotionY; if (!canChildScrollVertically((int) yDiff, ev)) { mInitialInterceptY = (int) ev.getY(); if (Math.abs(yDiff) > mTouchSlop && Math.abs(yDiff) >= Math.abs(xDiff) && !(mCurrentViewIndex == CurrentTargetIndex.UPSTAIRS && yDiff > 0 || mCurrentViewIndex == CurrentTargetIndex.DOWNSTAIRS && yDiff < 0)) { return true; } } return false; } private void adjustValidDownPoint(MotionEvent event) { if (mCurrentViewIndex == CurrentTargetIndex.UPSTAIRS && event.getY() > mDownMotionY || mCurrentViewIndex == CurrentTargetIndex.DOWNSTAIRS && event.getY() < mDownMotionY) { mDownMotionX = event.getX(); mDownMotionY = event.getY(); } } /** * 拦截之后的拖动 */ private void scroll(MotionEvent event) { if (mCurrentViewIndex == CurrentTargetIndex.UPSTAIRS) { if (getScrollY() <= 0 && event.getY() >= mInitialInterceptY) { mInitialInterceptY = (int) event.getY(); } int distance = mInitialInterceptY - event.getY() >= 0 ? (int) (mInitialInterceptY - event.getY()) : 0; scrollTo(0, distance); } else { if (getScrollY() >= mUpstairsView.getMeasuredHeight() && event.getY() <= mInitialInterceptY) { mInitialInterceptY = (int) event.getY(); } int distance = event.getY() <= mInitialInterceptY ? mUpstairsView.getMeasuredHeight() : (int) (mInitialInterceptY - event.getY() + mUpstairsView.getMeasuredHeight()); scrollTo(0, distance); } mVelocityTracker.addMovement(event); } /** * 清理VelocityTracker */ private void recycleVelocityTracker() { if (mVelocityTracker != null) { mVelocityTracker.clear(); mVelocityTracker.recycle(); mVelocityTracker = null; } } /** * if speed is enough even though offset is not enough go */ private void flingToFinishScroll() { final int pHeight = mUpstairsView.getMeasuredHeight(); final int threshold = (int) (pHeight * mPercent); float needFlingDistance = 0; if (CurrentTargetIndex.UPSTAIRS == mCurrentViewIndex) { if (getScrollY() <= 0) { needFlingDistance = 0; } else if (getScrollY() <= threshold) { if (needFlingToToggleView()) { needFlingDistance = pHeight - getScrollY(); mCurrentViewIndex = CurrentTargetIndex.DOWNSTAIRS; } else { needFlingDistance = -getScrollY(); } } else { needFlingDistance = pHeight - getScrollY(); mCurrentViewIndex = CurrentTargetIndex.DOWNSTAIRS; } } else if (CurrentTargetIndex.DOWNSTAIRS == mCurrentViewIndex) { if (pHeight <= getScrollY()) { needFlingDistance = 0; } else if (pHeight - getScrollY() < threshold) { if (needFlingToToggleView()) { needFlingDistance = -getScrollY(); mCurrentViewIndex = CurrentTargetIndex.UPSTAIRS; } else { needFlingDistance = pHeight - getScrollY(); } } else { needFlingDistance = -getScrollY(); mCurrentViewIndex = CurrentTargetIndex.UPSTAIRS; } } mScroller.startScroll(0, getScrollY(), 0, (int) needFlingDistance, mDuration); if (mOnSlideDetailsListener != null) { mOnSlideDetailsListener.onStatueChanged(mCurrentViewIndex); } postInvalidate(); } private boolean needFlingToToggleView() { mVelocityTracker.computeCurrentVelocity(1000, mMaxFlingVelocity); if (mCurrentViewIndex == CurrentTargetIndex.UPSTAIRS) { if (-mVelocityTracker.getYVelocity() > mMiniFlingVelocity) { return true; } } else { if (mVelocityTracker.getYVelocity() > mMiniFlingVelocity) { return true; } } return false; } private View getCurrentTargetView() { return mCurrentViewIndex == CurrentTargetIndex.UPSTAIRS ? mUpstairsView : mDownstairsView; } @Override public void computeScroll() { super.computeScroll(); if (mScroller.computeScrollOffset()) { scrollTo(0, mScroller.getCurrY()); postInvalidate(); } } /*** * 复用已经实现的View,省却了测量布局之类的麻烦 */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); measureChildren(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight()); } protected boolean canChildScrollVertically(int offSet, MotionEvent ev) { mCurrentTargetView = getCurrentTargetView(); return canScrollVertically(mCurrentTargetView, -offSet, ev); } /*** * judge is event is in current view * 判断MotionEvent是否处于View上面 */ protected boolean isTransformedTouchPointInView(MotionEvent ev, View view) { float x = ev.getRawX(); float y = ev.getRawY(); int[] rect = new int[2]; view.getLocationInWindow(rect); float localX = x - rect[0]; float localY = y - rect[1]; return localX >= 0 && localX < (view.getRight() - view.getLeft()) && localY >= 0 && localY < (view.getBottom() - view.getTop()); } /*** * first can view self ScrollVertically * seconde if View is ViewPager only judge current page * third if view is viewgroup check it`s children */ private boolean canScrollVertically(View view, int offSet, MotionEvent ev) { if (!mChildHasScrolled && !isTransformedTouchPointInView(ev, view)) { return false; } if (ViewCompat.canScrollVertically(view, offSet)) { mChildHasScrolled = true; return true; } if (view instanceof ViewPager) { return canViewPagerScrollVertically((ViewPager) view, offSet, ev); } if (view instanceof ViewGroup) { ViewGroup vGroup = (ViewGroup) view; for (int i = 0; i < vGroup.getChildCount(); i++) { if (canScrollVertically(vGroup.getChildAt(i), offSet, ev)) { mChildHasScrolled = true; return true; } } } return false; } private boolean canViewPagerScrollVertically(ViewPager viewPager, int offset, MotionEvent ev) { if(viewPager.getAdapter() instanceof DragDetailFragmentPagerAdapter){ View showView = ((DragDetailFragmentPagerAdapter) viewPager.getAdapter()).getPrimaryItem(); return showView != null && canScrollVertically(showView, offset, ev); }else { return false; } } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); } public void scrollToTop() { if (mCurrentViewIndex == CurrentTargetIndex.DOWNSTAIRS) { mScroller.startScroll(0, getScrollY(), 0, -getScrollY(), mDuration); mCurrentViewIndex= CurrentTargetIndex.UPSTAIRS; postInvalidate(); } if (mOnSlideDetailsListener != null) { mOnSlideDetailsListener.onStatueChanged(mCurrentViewIndex); } } }
20,573
https://github.com/AngeloDavid/gemec/blob/master/resources/views/equipo/new.blade.php
Github Open Source
Open Source
MIT
null
gemec
AngeloDavid
PHP
Code
349
1,872
@extends('base') @section('principal') <div class="row"> <div class="col-lg-12"> <section class="panel"> <header class="panel-heading"> Nuevo Equipo </header> <div class="panel-body"> <form role="form" novalidate="" method="POST" action="{{url($urlForm)}}" > {!! csrf_field() !!} @if (!$isnew) {{ method_field('PUT') }} @endif <div class="row"> <div class="col-lg-2"> <div class="form-group"> <label for="exampleInputEmail1">Tipo</label> <select name="id_type" class="form-control m-bot15"> @foreach ($listType as $item) <option value="{{$item->id}}" >{{$item->name}}</option> @endforeach </select> </div> </div> <div class="col-lg-4"> <div class="form-group"> <label for="exampleInputEmail1">CODIGO AF</label> <input type="text" class="form-control" id="codeaf" name="codeaf" value="{{old('codeaf',$item->codeaf)}}" placeholder=""> </div> </div> <div class="col-lg-6"> <div class="form-group"> <label for="exampleInputEmail1">Descripcion</label> <input type="text" class="form-control" id="description" name="description" value="{{old('description',$item->description)}}" placeholder=""> </div> </div> </div> <div class="row"> <div class="col-lg-3"> <div class="form-group"> <label for="exampleInputEmail1">Serial</label> <input type="text" class="form-control" id="serie" name="serie" value="{{old('serie',$item->serie)}}" placeholder=""> </div> </div> <div class="col-lg-3"> <div class="form-group"> <label for="exampleInputEmail1">Marca</label> <input type="text" class="form-control" id="marca" name="marca" value="{{old('marca',$item->marca)}}" placeholder=""> </div> </div> <div class="col-lg-3"> <div class="form-group"> <label for="exampleInputEmail1">Año</label> <input type="text" class="form-control" id="ano" name="ano" value="{{old('ano',$item->ano)}}" placeholder=""> </div> </div> <div class="col-lg-3"> <div class="form-group"> <label for="exampleInputEmail1">Color</label> <input type="text" class="form-control" id="color" name="color" value="{{old('ano',$item->ano)}}" placeholder=""> </div> </div> </div> <div class="row"> <div class="col-lg-3"> <div class="form-group"> <label for="exampleInputEmail1">CPU</label> <select name="CPU" multiple="" class="form-control"> <option>CORE I7</option> <option>CORE I5</option> <option>CORE I3</option> <option>PENTIUM</option> <option>CELETRON</option> </select> </div> </div> <div class="col-lg-3"> <div class="form-group"> <label for="exampleInputEmail1">RAM</label> <select name="RAM" multiple="" class="form-control"> <option value="16">16GB</option> <option value="12">12GB</option> <option value="8">8GB</option> <option value="4">4GB</option> <option value="2">2GB</option> <option value="1" >1GB</option> <option value="0.5" >512MB</option> </select> </div> </div> <div class="col-lg-3"> <div class="form-group"> <label for="exampleInputEmail1">Sistema Operativo</label> <select name="SO" multiple="" class="form-control"> <option>Windows 10</option> <option>Windows 7</option> <option>Windows xp</option> <option>Linux</option> <option>Mac</option> <option>otros</option> </select> </div> </div> <div class="col-lg-3"> <div class="form-group"> <label for="exampleInputEmail1">Disco Duro (GB)</label> <input type="number" class="form-control" id="DISK" name="DISK" value="{{old('DISK',$item->DISK)}}" placeholder=""> </div> </div> </div> <h4>Datos de RED</h4> <hr> <div class="row"> <div class="col-lg-6"> <div class="form-group"> <label for="exampleInputEmail1">IP</label> <input type="text" class="form-control" id="ip" name="ip" value="{{old('marca',$item->marca)}}" placeholder=""> </div> </div> <div class="col-lg-6"> <div class="form-group"> <label for="exampleInputEmail1">MAC</label> <input type="text" class="form-control" id="mac" name="mac" value="{{old('marca',$item->marca)}}" placeholder=""> </div> </div> </div> <hr> <div class="row"> <div class="col-lg-12"> <div class="form-group"> <label for="exampleInputEmail1">Colaborador</label> <select name="id_colla" class="form-control m-bot15"> @foreach ($listCol as $item) <option value="{{$item->id}}">{{$item->name}}</option> @endforeach </select> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <div class="checkbox"> <label> @if (!$isnew) @if ($item->status) <input type="checkbox" id="status" name = "status" value="{{old('name',$item->status)}}" checked > Habilitado @else <input type="checkbox" id="status" name = "status" value="{{old('name',$item->status)}}" > Habilitado @endif @endif </label> </div> </div> </div> <button type="submit" class="btn btn-primary">Guardar</button> </form> </div> </section> </div> </div> @endsection
47,224
https://github.com/matthew-brett/regreg/blob/master/regreg/info.py
Github Open Source
Open Source
BSD-3-Clause
2,015
regreg
matthew-brett
Python
Code
225
609
""" This file contains defines parameters for regreg that we use to fill settings in setup.py, the regreg top-level docstring, and for building the docs. In setup.py in particular, we exec this file, so it cannot import regreg """ # regreg version information. An empty _version_extra corresponds to a # full release. '.dev' as a _version_extra string means this is a development # version _version_major = 0 _version_minor = 0 _version_micro = 1 _version_extra = '.dev' # Format expected by setup.py and doc/source/conf.py: string of form "X.Y.Z" __version__ = "%s.%s.%s%s" % (_version_major, _version_minor, _version_micro, _version_extra) CLASSIFIERS = ["Development Status :: 3 - Alpha", "Environment :: Console", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Scientific/Engineering"] description = 'A multi-algorithm Python framework for regularized regression' # Minimum versions # Check these against requirements.txt and .travis.yml NUMPY_MIN_VERSION='1.6.0' SCIPY_MIN_VERSION = '0.9' CYTHON_MIN_VERSION = '0.18' NAME = 'regreg' MAINTAINER = "regreg developers" MAINTAINER_EMAIL = "" DESCRIPTION = description URL = "http://github.org/regreg/regreg" DOWNLOAD_URL = ""#"http://github.com/regreg/regreg/archives/master" LICENSE = "BSD license" CLASSIFIERS = CLASSIFIERS AUTHOR = "regreg developers" AUTHOR_EMAIL = ""#"regreg-devel@neuroimaging.scipy.org" PLATFORMS = "OS Independent" MAJOR = _version_major MINOR = _version_minor MICRO = _version_micro ISRELEASE = _version_extra == '' VERSION = __version__ STATUS = 'alpha' PROVIDES = ["regreg"] REQUIRES = ["numpy (>=%s)" % NUMPY_MIN_VERSION, "scipy (>=%s)" % SCIPY_MIN_VERSION]
15,667
https://github.com/copy/v86/blob/master/tests/nasm/ret-imm.asm
Github Open Source
Open Source
BSD-2-Clause, LicenseRef-scancode-unknown-license-reference
2,023
v86
copy
Assembly
Code
30
70
global _start %include "header.inc" jmp start foo: mov eax, esp ret 123 start: call foo mov dword [eax], 0 ; clear the address pushed by the call instruction %include "footer.inc"
5,163
https://github.com/aws/aws-sdk-cpp/blob/master/generated/src/aws-cpp-sdk-connect/source/model/UpdateUserPhoneConfigRequest.cpp
Github Open Source
Open Source
Apache-2.0, MIT, JSON
2,023
aws-sdk-cpp
aws
C++
Code
51
251
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/connect/model/UpdateUserPhoneConfigRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Connect::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateUserPhoneConfigRequest::UpdateUserPhoneConfigRequest() : m_phoneConfigHasBeenSet(false), m_userIdHasBeenSet(false), m_instanceIdHasBeenSet(false) { } Aws::String UpdateUserPhoneConfigRequest::SerializePayload() const { JsonValue payload; if(m_phoneConfigHasBeenSet) { payload.WithObject("PhoneConfig", m_phoneConfig.Jsonize()); } return payload.View().WriteReadable(); }
18,200
https://github.com/hershel/hershel/blob/master/.npmignore
Github Open Source
Open Source
MIT
2,021
hershel
hershel
Ignore List
Code
12
56
media/ src/ test/ doc/ .nyc_output/ ava.config.js tsconfig.json .npmignore .nycrc .prettierignore .prettierignore .travis.yml
45,306
https://github.com/yuan204/spirit-ui/blob/master/src/components/cascader/cascader-panel.vue
Github Open Source
Open Source
MIT
2,019
spirit-ui
yuan204
Vue
Code
219
970
<template> <div class="s-cascader-panel"> <ul> <li v-for="(option,optionIndex) in options" class="s-cascader-item" @click="handleClick(option,optionIndex,option.value)" :class="{active:activeIndex === optionIndex,disabled:option.disabled}" @mouseenter="handleHover(option,optionIndex,option.value)"> <span class="s-cascader-label" >{{option.label}}</span> <s-icon name="rightArrow" v-if="option.children" class="s-cascader-right-arrow"></s-icon> </li> </ul> </div> </template> <script> import SIcon from "../icon/icon"; export default { name: "sCascaderPanel", props: { options: { type: Array, }, panelIndex: Number, activeIndex: { type: Number, default: -1 }, }, components: { SIcon }, data() { return { } }, methods: { handleClick(option,i,value) { this.$emit('panel',option.children,this.panelIndex,option.label,i,value) }, handleHover(option,i,value) { if (option.disabled || !option.children || this.$parent.trigger === "click") return; this.$emit('panel',option.children,this.panelIndex,option.label,i,value) } }, created() { this.$on("select-item",(l) => { const i = this.options.map(option => option.label).indexOf(l) this.handleClick(this.options[i],i,this.options[i].value) setTimeout(() => this.$parent.$emit("active-item"),0) }) } } </script> <style scoped lang="scss"> @import "../../styles/common.scss"; @import "../../styles/color.scss"; .s-cascader-panel { width: 180px; background-color: #fff; height: 187px; overflow: auto; border: 1px solid #e4e7ed; padding-top: 12px; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1); margin-top: 12px; .s-cascader-item { height: 34px; line-height: 34px; padding: 0 20px 0 20px; cursor: pointer; display: flex; justify-content: space-between; align-items: center; color: #606266; text-align: left; &:hover { background-color: #f5f7fa; } &.active { background-color: #f5f7fa; color: #409eff; font-weight: bold; outline: none; } &.disabled { color: #ccc; cursor: not-allowed; &:hover { background-color: #fff; } } .s-cascader-label { font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; /*&.active {*/ /* color: #409eff;*/ /* font-weight: bold;*/ /* outline: none;*/ /*}*/ } .s-cascader-right-arrow { font-size: 12px; } } } </style>
20,858
https://github.com/pureza/chembl-patent-annotator/blob/master/src/main/java/uk/ac/ebi/chembl/storage/ExternalEnsemblRepository.java
Github Open Source
Open Source
Apache-2.0
null
chembl-patent-annotator
pureza
Java
Code
134
444
package uk.ac.ebi.chembl.storage; import org.skife.jdbi.v2.sqlobject.CreateSqlObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.chembl.storage.dao.EnsemblPeptideUniProt; import uk.ac.ebi.chembl.storage.dao.ExternalEnsemblDao; import java.util.ArrayList; import java.util.List; /** * A repository that abstracts the Ensembl database */ public abstract class ExternalEnsemblRepository { private Logger logger = LoggerFactory.getLogger(getClass().getSuperclass()); /** Maximum number of Ensembl Peptide ids per batch */ private final static int BATCH_SIZE = 1000; @CreateSqlObject protected abstract ExternalEnsemblDao dao(); /** * Maps Ensembl Peptide ids to UniProt accessions using a specific Ensembl * release */ public List<EnsemblPeptideUniProt> mapToUniprotAtRelease(List<String> ensemblPeptideIds, String ensemblRelease) { List<EnsemblPeptideUniProt> rows = new ArrayList<>(); // Do this in batches, to avoid "to many items in IN" error for (int i = 0; i * BATCH_SIZE < ensemblPeptideIds.size(); i++) { int end = Math.min(ensemblPeptideIds.size(), (i + 1) * BATCH_SIZE); List<String> batch = ensemblPeptideIds.subList(i * BATCH_SIZE, end); rows.addAll(dao().mapToUniprot(batch, ensemblRelease)); } return rows; } }
41,421
https://github.com/aoberoi/java-slack-sdk/blob/master/slack-api-model/src/main/java/com/slack/api/model/block/UnknownBlockElement.java
Github Open Source
Open Source
MIT
null
java-slack-sdk
aoberoi
Java
Code
26
100
package com.slack.api.model.block; import com.slack.api.model.block.element.BlockElement; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class UnknownBlockElement extends BlockElement { private String type; }
40,061
https://github.com/Wisertown/Family_reunion_planner/blob/master/application/models/Trip.php
Github Open Source
Open Source
MIT
null
Family_reunion_planner
Wisertown
PHP
Code
340
1,231
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Trip extends CI_Model { public function get_user_info() { $query = "SELECT users.name, users.switch, users.pswitch, users.votes FROM users WHERE id = ?"; $values = $this->session->userdata('id'); return $this->db->query($query, $values)->row_array(); } public function create($post) { $this->form_validation->set_rules("link", "link", "trim|required"); $this->form_validation->set_rules("place", "destination", "trim|required"); $this->form_validation->set_rules("description", "description", "trim|required"); $this->form_validation->set_rules("d_from", "date from", "trim|required"); $this->form_validation->set_rules("d_to", "date to", "trim|required"); if($this->form_validation->run() === FALSE){ $this->session->set_flashdata("errors", validation_errors()); return FALSE; } else { $query2 = "INSERT INTO trips(place, description, link, d_from, d_to, created_by, created_at, updated_at) values(?, ?, ?, ?, ?, ?, NOW(), NOW())"; $values = array($post['place'], $post['description'], $post['link'], $post['d_from'], $post['d_to'], $this->session->userdata('id')); $this->db->query($query2, $values); $query = "INSERT INTO vacation(user_id, trip_id, place, description, link, d_from, d_to, votes, created_at, updated_at) values(?, last_insert_id(), ?, ?, ?, ?, ?, +1, NOW(), NOW())"; $values = array($this->session->userdata('id'), $post['place'], $post['description'], $post['link'], $post['d_from'], $post['d_to']); $this->db->query($query, $values); $query33 ="UPDATE users set votes = votes-1, switch = switch+1 where users.id = ?"; $values = array($this->session->userdata('id')); $this->db->query($query33, $values); return TRUE; } } public function get_my_trips() { $query = "SELECT vacation.trip_id as va_id, vacation.user_id, vacation.id, vacation.place, vacation.link, vacation.description, vacation.d_from, vacation.d_to, vacation.votes from vacation order by votes desc"; return $this->db->query($query)->result_array(); } // public function get_others_trips() // { // $query = "SELECT users.id, users.name, vacation.id as va_id, vacation.trip_id as tr_id, vacation.place, vacation.d_from, vacation.d_to, vacation.description from users join vacation on users.id = vacation.user_id where users.id != ? group by vacation.trip_id"; // $values = $this->session->userdata('id'); // return $this->db->query($query, $values)->result_array(); // } public function get_trip_users($id) { $query = "SELECT users.name, users.id, vacation.place, vacation.trip_id, vacation.added_by from users join vacation on users.id = vacation.added_by where vacation.trip_id = ?"; $values = array($id); return $this->db->query($query, $values)->result_array(); } public function get_trip_data($id) { $query3 = "SELECT users.name, vacation.id, users.id, vacation.place, vacation.trip_id, vacation.user_id, vacation.description, vacation.d_from, vacation.d_to from users join vacation on users.id = vacation.user_id where vacation.trip_id = ?"; $values = array($id); return $this->db->query($query3, $values)->result_array(); } public function vote($id) { $query = "UPDATE users set votes = votes-1 where users.id = ?"; $values = array($this->session->userdata('id')); $this->db->query($query, $values); $query21 = "UPDATE vacation set votes = votes+1 where vacation.trip_id = ?"; $values = array($id); $this->db->query($query21, $values); return TRUE; } } ?>
14,562
https://github.com/tongni1975/keras-anomaly-detection/blob/master/keras_anomaly_detection/library/plot_utils.py
Github Open Source
Open Source
MIT
2,022
keras-anomaly-detection
tongni1975
Python
Code
137
638
from matplotlib import pyplot as plt import seaborn as sns from sklearn.metrics import confusion_matrix import pandas as pd LABELS = ["Normal", "Fraud"] def plot_confusion_matrix(y_true, y_pred): conf_matrix = confusion_matrix(y_true, y_pred) plt.figure(figsize=(12, 12)) sns.heatmap(conf_matrix, xticklabels=LABELS, yticklabels=LABELS, annot=True, fmt="d") plt.title("Confusion matrix") plt.ylabel('True class') plt.xlabel('Predicted class') plt.show() def plot_training_history(history): if history is None: return plt.plot(history['loss']) plt.plot(history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper right') plt.show() def visualize_anomaly(y_true, reconstruction_error, threshold): error_df = pd.DataFrame({'reconstruction_error': reconstruction_error, 'true_class': y_true}) print(error_df.describe()) groups = error_df.groupby('true_class') fig, ax = plt.subplots() for name, group in groups: ax.plot(group.index, group.reconstruction_error, marker='o', ms=3.5, linestyle='', label="Fraud" if name == 1 else "Normal") ax.hlines(threshold, ax.get_xlim()[0], ax.get_xlim()[1], colors="r", zorder=100, label='Threshold') ax.legend() plt.title("Reconstruction error for different classes") plt.ylabel("Reconstruction error") plt.xlabel("Data point index") plt.show() def visualize_reconstruction_error(reconstruction_error, threshold): plt.plot(reconstruction_error, marker='o', ms=3.5, linestyle='', label='Point') plt.hlines(threshold, xmin=0, xmax=len(reconstruction_error)-1, colors="r", zorder=100, label='Threshold') plt.legend() plt.title("Reconstruction error") plt.ylabel("Reconstruction error") plt.xlabel("Data point index") plt.show()
20,638
https://github.com/hp-storage/horizon-ssmc-link/blob/master/horizon_hpe_storage/overrides.py
Github Open Source
Open Source
Apache-2.0
2,017
horizon-ssmc-link
hp-storage
Python
Code
750
2,094
# (c) Copyright [2015] Hewlett Packard Enterprise Development LP # # 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. from django.utils.translation import ugettext_lazy as _ from horizon import tables from openstack_dashboard.dashboards.admin.volumes.volumes import tables \ as volumes_tables from openstack_dashboard.dashboards.admin.volumes.snapshots import tables \ as snapshots_tables from openstack_dashboard.dashboards.admin.volumes import tabs from django.core.urlresolvers import reverse import logging import re import horizon_hpe_storage.api.keystone_api as keystone LOG = logging.getLogger(__name__) # save off keystone session so we don't have to retrieve it for # every volume in the volume table keystone_api = None class VolumeBaseElementManager(tables.LinkAction): # launch in new window attrs = {"target": "_blank"} policy_rules = (("volume", "volume:deep_link"),) def get_link_url(self, volume): link_url = reverse(self.url, args=[volume.id]) return link_url def get_deep_link_endpoints(self, request): global keystone_api endpoints = [] for i in range(0, 2): try: if not keystone_api: keystone_api = keystone.KeystoneAPI() keystone_api.do_setup(request) endpoints = keystone_api.get_ssmc_endpoints() return endpoints except Exception as ex: # try again, as this may be due to expired keystone session keystone_api = None continue return endpoints def allowed(self, request, volume=None): # don't allow deep link option if volume is not tied # to an SSMC endpoint if volume: host = getattr(volume, 'os-vol-host-attr:host', None) # pull out host from host name (comes between @ and #) if host: found = re.search('@(.+?)#', host) if found: backend = found.group(1) endpoints = self.get_deep_link_endpoints(request) for endpoint in endpoints: if endpoint['backend'] == backend: return True return False class VolumeLaunchElementManagerVolume(VolumeBaseElementManager): LOG.info(("Deep Link - launch element manager volume")) name = "link_volume" verbose_name = _("View Volume in HPE 3PAR SSMC") url = "horizon:admin:hpe_storage:config:link_to_volume" class VolumeLaunchElementManagerCPG(VolumeBaseElementManager): LOG.info(("Deep Link - launch element manager volume CPG")) name = "link_volume_cpg" verbose_name = _("View Volume CPG in HPE 3PAR SSMC") url = "horizon:admin:hpe_storage:config:link_to_volume_cpg" class VolumeLaunchElementManagerDomain(VolumeBaseElementManager): LOG.info(("Deep Link - launch element manager volume domain")) name = "link_volume_domain" verbose_name = _("View Volume Domain in HPE 3PAR SSMC") url = "horizon:admin:hpe_storage:config:link_to_volume_domain" class VolumeLaunchElementManagerCGroup(VolumeBaseElementManager): LOG.info(("Deep Link - launch element manager volume consistency group")) name = "link_volume_cgroup" verbose_name = _("View Volume Consistency Group in HPE 3PAR SSMC") url = "horizon:admin:hpe_storage:config:link_to_volume_cgroup" def allowed(self, request, volume=None): # only allow if this volume is associated # with a consistency group if volume: if volume.consistencygroup_id: return True return False class VolumesTableWithLaunch(volumes_tables.VolumesTable): """ Extend the VolumesTable by adding the new row action """ class Meta(volumes_tables.VolumesTable.Meta): # Add the extra action to the end of the row actions row_actions = volumes_tables.VolumesTable.Meta.row_actions + \ (VolumeLaunchElementManagerVolume, VolumeLaunchElementManagerCPG, VolumeLaunchElementManagerDomain, VolumeLaunchElementManagerCGroup) class SnapshotBaseElementManager(tables.LinkAction): # launch in new window attrs = {"target": "_blank"} policy_rules = (("volume", "volume:deep_link"),) def get_link_url(self, snapshot): link_url = reverse(self.url, args=[snapshot.id]) return link_url def get_deep_link_endpoints(self, request): global keystone_api endpoints = [] for i in range(0, 2): try: if not keystone_api: keystone_api = keystone.KeystoneAPI() keystone_api.do_setup(request) endpoints = keystone_api.get_ssmc_endpoints() return endpoints except Exception as ex: # try again, as this may be due to expired keystone session keystone_api = None continue return endpoints def allowed(self, request, snapshot=None): # don't allow deep link option if this snapshot # is associated with a consistency group (because we # can't determine the full 3PAR name) # if snapshot._volume.consistencygroup_id: # return False # don't allow deep link option if snapshot is not tied # to an SSMC endpoint if snapshot.host_name: # pull out host from host name (comes between @ and #) found = re.search('@(.+?)#', snapshot.host_name) if found: backend = found.group(1) endpoints = self.get_deep_link_endpoints(request) for endpoint in endpoints: if endpoint['backend'] == backend: if snapshot._volume.consistencygroup_id: # self.verbose_name = \ # _("View Volume Consistency Group " # "in HPE 3PAR SSMC") # REMOVE THIS OPTION FOR NOW - too confusing # for to show user vvset and them have # navigate to the snapshot return False else: return True return False class SnapshotLaunchElementManagerVolume(SnapshotBaseElementManager): LOG.info(("Deep Link - launch element manager snapshot")) name = "link_snapshot" verbose_name = _("View Snapshot in HPE 3PAR SSMC") url = "horizon:admin:hpe_storage:config:link_to_snapshot" class SnapshotsTableWithLaunch(snapshots_tables.VolumeSnapshotsTable): """ Extend the VolumeSnapshotsTable by adding the new row action """ class Meta(snapshots_tables.VolumeSnapshotsTable.Meta): # Add the extra action to the end of the row actions row_actions = \ snapshots_tables.VolumeSnapshotsTable.Meta.row_actions + \ (SnapshotLaunchElementManagerVolume,) # Replace the standard Volumes table with this extended version tabs.VolumeTab.table_classes = (VolumesTableWithLaunch,) # Replace the standard Volumes table with this extended version tabs.SnapshotTab.table_classes = (SnapshotsTableWithLaunch,)
22,084
https://github.com/swpm/supduction/blob/master/source/cityloader.py
Github Open Source
Open Source
BSD-3-Clause
null
supduction
swpm
Python
Code
22
46
#### Copyright (c) 2015, swpm, Jeffrey E. Erickson #### All rights reserved. #### See the accoompanying LICENSE file for terms of use
17,122
https://github.com/JenStokes79/Date-Night-React-v3/blob/master/frontend/src/Components/HomePage.js
Github Open Source
Open Source
MIT
null
Date-Night-React-v3
JenStokes79
JavaScript
Code
151
555
import React from 'react'; import Nav from './Nav/Nav'; import { Button, Card, Col, Input, Row, CardTitle, MediaBox, CardPanel, Dropdown, NavItem, Footer } from "react-materialize"; import "../App.css"; import "./Logon/Logon"; class HomePage extends React.Component{ render(){ return( <div> <div className="home-page"> <Nav /> <div className="mainBG"> <div class="content" > <div class="row"> <div class="row"> <div class="col s12 m4 l2"><p></p></div> <div class="col s12 m4 l8"><p><h2>Find the Best Date Places in Town</h2></p></div> <div class="col s12 m4 l2"><p></p></div> </div> </div> <div class="circles-parent"> <div class="square"><img src="/img/moviedinner.jpg" style={{width: 250, height: 200}} /> <p><a href="movienight">Dinner & Movie</a></p> </div> <div class="square"><img src="/img/spinthewheel3.jpg" style={{width: 250, height: 200}} /> <p><a href="wheel">Spin the Wheel</a></p> </div> <div class="square"><img src="/img/dollardates3.jpg" style={{width: 250, height: 200}} /> <p><a href="dollardates">Dollar Dates</a></p> </div> <div class="square"><img src="/img/saved.jpg" style={{width: 250, height: 200}} /> <p><a href="#">Saved Dates</a></p> </div> </div> </div> </div> {/* Footer Start */} <div class="Footer"> Date Night 2018. All Rights Reserved. </div> {/* Footer End */} </div> </div> ) } } export default HomePage;
49,340
https://github.com/endeavourhealth/Transforms/blob/master/src/main/java/org/endeavourhealth/transform/tpp/csv/transforms/patient/SRPatientTransformer.java
Github Open Source
Open Source
Apache-2.0
2,021
Transforms
endeavourhealth
Java
Code
796
3,150
package org.endeavourhealth.transform.tpp.csv.transforms.patient; import org.endeavourhealth.common.fhir.FhirIdentifierUri; import org.endeavourhealth.common.fhir.schema.EthnicCategory; import org.endeavourhealth.common.fhir.schema.MaritalStatus; import org.endeavourhealth.common.fhir.schema.NhsNumberVerificationStatus; import org.endeavourhealth.core.database.dal.publisherCommon.models.TppMappingRef; import org.endeavourhealth.core.exceptions.TransformException; import org.endeavourhealth.transform.common.*; import org.endeavourhealth.transform.common.resourceBuilders.*; import org.endeavourhealth.transform.tpp.csv.helpers.TppCsvHelper; import org.endeavourhealth.transform.tpp.csv.helpers.TppMappingHelper; import org.endeavourhealth.transform.tpp.csv.schema.patient.SRPatient; import org.hl7.fhir.instance.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map; public class SRPatientTransformer { private static final Logger LOG = LoggerFactory.getLogger(SRPatientTransformer.class); public static void transform(Map<Class, AbstractCsvParser> parsers, FhirResourceFiler fhirResourceFiler, TppCsvHelper csvHelper) throws Exception { AbstractCsvParser parser = parsers.get(SRPatient.class); if (parser != null) { while (parser.nextRecord()) { try { createResource((SRPatient) parser, fhirResourceFiler, csvHelper); } catch (Exception ex) { fhirResourceFiler.logTransformRecordError(ex, parser.getCurrentState()); } } } //call this to abort if we had any errors, during the above processing fhirResourceFiler.failIfAnyErrors(); } public static void createResource(SRPatient parser, FhirResourceFiler fhirResourceFiler, TppCsvHelper csvHelper) throws Exception { CsvCell rowIdCell = parser.getRowIdentifier(); PatientBuilder patientBuilder = csvHelper.getPatientResourceCache().borrowPatientBuilder(rowIdCell, csvHelper, fhirResourceFiler, true); //if deleted, delete all data for this patient CsvCell removeDataCell = parser.getRemovedData(); if (removeDataCell != null && removeDataCell.getIntAsBoolean()) { deleteEntirePatientRecord(fhirResourceFiler, parser); return; } try { createIdentifier(patientBuilder, fhirResourceFiler, rowIdCell, FhirIdentifierUri.IDENTIFIER_SYSTEM_TPP_PATIENT_ID, Identifier.IdentifierUse.SECONDARY); CsvCell nhsNumberCell = parser.getNHSNumber(); createIdentifier(patientBuilder, fhirResourceFiler, nhsNumberCell, FhirIdentifierUri.IDENTIFIER_SYSTEM_NHSNUMBER, Identifier.IdentifierUse.OFFICIAL); NhsNumberVerificationStatus numberVerificationStatus = null; CsvCell spineMatchedCell = parser.getSpineMatched(); if (spineMatchedCell != null //need null check because it's not in all versions && !spineMatchedCell.isEmpty() && !nhsNumberCell.isEmpty()) { //this is only relevant if there is an NHS number numberVerificationStatus = mapSpindeMatchedStatus(spineMatchedCell); } patientBuilder.setNhsNumberVerificationStatus(numberVerificationStatus, spineMatchedCell); createName(patientBuilder, parser, fhirResourceFiler); CsvCell dobCell = parser.getDateBirth(); if (!dobCell.isEmpty()) { //SystmOne captures time of birth too, so don't lose this by treating just as a date patientBuilder.setDateOfBirth(dobCell.getDateTime(), dobCell); //patientBuilder.setDateOfBirth(dobCell.getDate(), dobCell); } else { patientBuilder.setDateOfBirth(null, dobCell); } CsvCell dateDeathCell = parser.getDateDeath(); if (!dateDeathCell.isEmpty()) { patientBuilder.setDateOfDeath(dateDeathCell.getDate(), dateDeathCell); } else { patientBuilder.clearDateOfDeath(); } CsvCell genderCell = parser.getGender(); if (!genderCell.isEmpty()) { Enumerations.AdministrativeGender gender = mapGender(genderCell); patientBuilder.setGender(gender, genderCell); } else { patientBuilder.setGender(null, genderCell); } CsvCell emailCell = parser.getEmailAddress(); ceatePatientContactEmail(patientBuilder, parser, fhirResourceFiler, emailCell); //Speaks English //The SRPatient CSV record refers to the global mapping file, which supports only three values CsvCell speaksEnglishCell = parser.getSpeaksEnglish(); Boolean speaksEnglishValue = lookUpSpeaksEnglishValue(speaksEnglishCell, csvHelper); patientBuilder.setSpeaksEnglish(speaksEnglishValue, speaksEnglishCell); //see if there is a ethnicity for patient from pre-transformer (but don't set to null if a new one hasn't been received) TppCsvHelper.DateAndCode newEthnicity = csvHelper.findEthnicity(rowIdCell); TppMappingHelper.applyNewEthnicity(newEthnicity, patientBuilder); //see if there is a marital status for patient from pre-transformer (but don't set to null if a new one hasn't been received) TppCsvHelper.DateAndCode newMaritalStatus = csvHelper.findMaritalStatus(rowIdCell); TppMappingHelper.applyNewMaritalStatus(newMaritalStatus, patientBuilder); CsvCell testPatientCell = parser.getTestPatient(); patientBuilder.setTestPatient(testPatientCell.getBoolean(), testPatientCell); //IDOrgVisible to is "here" (the service being transformed), so carry that over to the managing organisation CsvCell idOrgVisibleToCell = parser.getIDOrganisationVisibleTo(); Reference orgReferencePatient = csvHelper.createOrganisationReference(idOrgVisibleToCell); if (patientBuilder.isIdMapped()) { orgReferencePatient = IdHelper.convertLocallyUniqueReferenceToEdsReference(orgReferencePatient, csvHelper); } patientBuilder.setManagingOrganisation(orgReferencePatient, idOrgVisibleToCell); } finally { csvHelper.getPatientResourceCache().returnPatientBuilder(rowIdCell, patientBuilder); } } private static Boolean lookUpSpeaksEnglishValue(CsvCell speaksEnglishCell, TppCsvHelper csvHelper) throws Exception { if (!speaksEnglishCell.isEmpty()) { TppMappingRef mapping = csvHelper.lookUpTppMappingRef(speaksEnglishCell); String term = mapping.getMappedTerm(); if (term.equals("Unknown")) { return null; } else if (term.equals("Yes")) { return Boolean.TRUE; } else if (term.equals("No")) { return Boolean.FALSE; } else { throw new TransformException("Unexpected english speaks value [" + term + "]"); } } else { return null; } } /** * adds the email address contact (all other contacts e.g. telephone numbers) are done in SRPatientContactDetailsTransformer */ private static void ceatePatientContactEmail(PatientBuilder patientBuilder, SRPatient parser, FhirResourceFiler fhirResourceFiler, CsvCell cell) throws Exception { if (!cell.isEmpty()) { ContactPointBuilder contactPointBuilder = new ContactPointBuilder(patientBuilder); contactPointBuilder.setValue(cell.getString(), cell); contactPointBuilder.setSystem(ContactPoint.ContactPointSystem.EMAIL); contactPointBuilder.setUse(ContactPoint.ContactPointUse.HOME); ContactPointBuilder.deDuplicateLastContactPoint(patientBuilder, fhirResourceFiler.getDataDate()); } else { ContactPointBuilder.endContactPoints(patientBuilder, fhirResourceFiler.getDataDate(), ContactPoint.ContactPointSystem.EMAIL, ContactPoint.ContactPointUse.HOME); } } private static void createName(PatientBuilder patientBuilder, SRPatient parser, FhirResourceFiler fhirResourceFiler) throws Exception { //Construct the name from individual fields CsvCell firstNameCell = parser.getFirstName(); CsvCell surnameCell = parser.getSurname(); CsvCell middleNamesCell = parser.getMiddleNames(); CsvCell titleCell = parser.getTitle(); if (!firstNameCell.isEmpty() || !surnameCell.isEmpty() || !middleNamesCell.isEmpty() || !titleCell.isEmpty()) { NameBuilder nameBuilder = new NameBuilder(patientBuilder); nameBuilder.setUse(HumanName.NameUse.OFFICIAL); if (!titleCell.isEmpty()) { nameBuilder.addPrefix(titleCell.getString(), titleCell); } if (!firstNameCell.isEmpty()) { nameBuilder.addGiven(firstNameCell.getString(), firstNameCell); } if (!middleNamesCell.isEmpty()) { nameBuilder.addGiven(middleNamesCell.getString(), middleNamesCell); } if (!surnameCell.isEmpty()) { nameBuilder.addFamily(surnameCell.getString(), surnameCell); } NameBuilder.deDuplicateLastName(patientBuilder, fhirResourceFiler.getDataDate()); } else { //if no name (for some reason), just end any existing ones in the resource NameBuilder.endNames(patientBuilder, fhirResourceFiler.getDataDate(), HumanName.NameUse.OFFICIAL); } } private static void createIdentifier(PatientBuilder patientBuilder, FhirResourceFiler fhirResourceFiler, CsvCell cell, String system, Identifier.IdentifierUse use) throws Exception { if (!cell.isEmpty()) { IdentifierBuilder identifierBuilderTpp = new IdentifierBuilder(patientBuilder); identifierBuilderTpp.setSystem(system); identifierBuilderTpp.setUse(use); identifierBuilderTpp.setValue(cell.getString(), cell); IdentifierBuilder.deDuplicateLastIdentifier(patientBuilder, fhirResourceFiler.getDataDate()); } else { IdentifierBuilder.endIdentifiers(patientBuilder, fhirResourceFiler.getDataDate(), system, use); } } private static NhsNumberVerificationStatus mapSpindeMatchedStatus(CsvCell spineMatched) { String s = spineMatched.getString(); if (Boolean.parseBoolean(s)) { return NhsNumberVerificationStatus.PRESENT_AND_VERIFIED; } else { //not enough info to make this choice - just leave null return null; //return NhsNumberVerificationStatus.PRESENT_BUT_NOT_TRACED; } } private static Enumerations.AdministrativeGender mapGender(CsvCell genderCell) throws TransformException { String s = genderCell.getString(); if (s.equalsIgnoreCase("m")) { return Enumerations.AdministrativeGender.MALE; } else if (s.equalsIgnoreCase("f")) { return Enumerations.AdministrativeGender.FEMALE; } else if (s.equalsIgnoreCase("i")) { return Enumerations.AdministrativeGender.OTHER; } else if (s.equalsIgnoreCase("u")) { return Enumerations.AdministrativeGender.UNKNOWN; } else { throw new TransformException("Unsupported gender " + s); } } /** * deletes all FHIR resources associated with this patient record */ private static void deleteEntirePatientRecord(FhirResourceFiler fhirResourceFiler, SRPatient parser) throws Exception { CsvCell patientIdCell = parser.getRowIdentifier(); CsvCell deletedCell = parser.getRemovedData(); CsvCurrentState currentState = parser.getCurrentState(); String sourceId = patientIdCell.getString(); PatientDeleteHelper.deleteAllResourcesForPatient(sourceId, fhirResourceFiler, currentState, deletedCell); } }
26,741
https://github.com/GhostMachineSoftware/SPFX_UsefulLinks/blob/master/node_modules/jest-cli/build/lib/active_filters_message.js
Github Open Source
Open Source
MIT
2,019
SPFX_UsefulLinks
GhostMachineSoftware
JavaScript
Code
165
412
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _chalk; function _load_chalk() { return _chalk = _interopRequireDefault(require('chalk')); } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ const activeFilters = function (globalConfig) { let delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '\n'; const testNamePattern = globalConfig.testNamePattern, testPathPattern = globalConfig.testPathPattern; if (testNamePattern || testPathPattern) { const filters = [testPathPattern ? (_chalk || _load_chalk()).default.dim('filename ') + (_chalk || _load_chalk()).default.yellow('/' + testPathPattern + '/') : null, testNamePattern ? (_chalk || _load_chalk()).default.dim('test name ') + (_chalk || _load_chalk()).default.yellow('/' + testNamePattern + '/') : null].filter(f => f).join(', '); const messages = ['\n' + (_chalk || _load_chalk()).default.bold('Active Filters: ') + filters]; return messages.filter(message => !!message).join(delimiter); } return ''; }; exports.default = activeFilters;
50,050
https://github.com/CurvaXa/org-helper/blob/master/src/managers/commands-parser.js
Github Open Source
Open Source
MIT
null
org-helper
CurvaXa
JavaScript
Code
1,482
3,665
'use strict'; /** * @module commands-parser * @author Alteh Union (alteh.union@gmail.com) * @license MIT (see the root LICENSE file for details) */ const LangManager = require('./lang-manager'); const BotPublicError = require('../utils/bot-public-error'); const ServerSettingsTable = require('../mongo_classes/server-settings-table'); const UserSettingsTable = require('../mongo_classes/user-settings-table'); const HelpCommand = require('../commands_discord/other/help-command'); /** * Parses and launches execution of the Bot's commands. * @alias CommandsParser */ class CommandsParser { /** * Constructs an instance of the class. * @param {Context} context the Bot's context */ constructor(context) { this.context = context; } /** * Tries to parse an incoming Discord message in a guild as a command and execute it, if possible. * In case the user forgot the command prefix or set an unexpected language, there should be a fallback * to parse the HelpCommand in the default locale and with the default prefix, even if the current * locale and the current prefix is different. * * The general flow of processing commands is the following: * 0) Determine which language should we use to parse the command * 1) Check if the incoming message a command * 2) If yes, get the corresponding class of the command and create it's instance * 3) Check which way we should parse arguments: sequentially or by name * 4) Scan the arguments * 5) Fill default values for unscanned arguments (at least with null values) * 6) Validate the arguments * 7) Check caller's permissions to launch command with such arguments * 8) Execute the command * 9) Respond back with the result of execution to the same channel * * If a problem happened due to user's actions on steps 4, 6, 7 (e.g. no permission to laucnh the command, * wrong arguments etc.) then abort the processing and respond back to the caller with information about the error. * * If a problem occured on some other step, then most probably it's an internal Bot's problem, so don't * pass details to the caller, instead suggest him to contact the Bot developers. * @see HelpCommand * @param {BaseMessage} message the incoming Discord message * @return {Promise<Boolean>} true if a command was executed successfully, false otherwise */ async processMessage(message) { const currentPrefix = await this.context.dbManager.getSetting( message.source.name, message.orgId, ServerSettingsTable.SERVER_SETTINGS.commandPrefix.name, message.source.DEFAULT_COMMAND_PREFIX ); const commandLangManager = await this.getCommandLangManager(message); const command = this.parseMessage(message, currentPrefix, commandLangManager); if (command) { await this.executeCommand(message, command, commandLangManager); } return command !== null; } /** * Parse message to get a bot command * @param message * @param currentPrefix * @param commandLangManager * @returns {constructor|HelpCommand|null} */ parseMessage(message, currentPrefix, commandLangManager) { if ( !message.content.startsWith(currentPrefix) && message.content.startsWith(message.source.DEFAULT_COMMAND_PREFIX) ) { const fallbackCommandName = message.content.slice( message.source.DEFAULT_COMMAND_PREFIX.length, message.content.includes(' ') ? message.content.indexOf(' ') : message.content.length ); if ( fallbackCommandName === this.context.langManager.getString(HelpCommand.getCommandInterfaceName()) || fallbackCommandName === commandLangManager.getString(HelpCommand.getCommandInterfaceName()) ) { this.context.log.i('Found help command with default prefix: ' + message.content); return HelpCommand; } return null; } if (!message.content.startsWith(currentPrefix)) { return null; } const commandName = message.content.slice( currentPrefix.length, message.content.includes(' ') ? message.content.indexOf(' ') : message.content.length ); this.context.log.i('parseDiscordCommand: command: ' + message.content + '; commandName: ' + commandName); for (const command of message.source.commandManager.definedCommands) { if (commandName === commandLangManager.getString(command.getCommandInterfaceName())) { this.context.log.i('Found command: ' + message.content); return command; } } return null; } /** * Get command lang manager based on message locale * @param message * @returns {Promise<void>} */ async getCommandLangManager(message) { const currentLocale = await this.context.dbManager.getSetting( message.source.name, message.orgId, ServerSettingsTable.SERVER_SETTINGS.localeName.name ); const currentUserLocale = await this.context.dbManager.getUserSetting( message.source.name, message.orgId, message.userId, UserSettingsTable.USER_SETTINGS.localeName.name ); return new LangManager( this.context.localizationPath, currentUserLocale === undefined ? currentLocale : currentUserLocale ); } /** * Tries to parse an incoming Discord private ("DM") message as a command and execute it, if possible. * Processing is somewhat similar to the gu8ld commands, but with respect to the fact that there is no * guild, so cannot use guild settings etc. * @todo To consider implementing user settings not related to any guild. * @see CommandsParser#processMessage * @param {BaseMessage} message the incoming Discord message * @return {Promise<Boolean>} true if a command was executed successfully, false otherwise */ async parsePrivateDiscordCommand(message) { const commandLangManager = this.context.langManager; const currentPrefix = message.source.DEFAULT_COMMAND_PREFIX; if (!message.content.startsWith(currentPrefix)) { return false; } const commandName = message.content.slice( currentPrefix.length, message.content.includes(' ') ? message.content.indexOf(' ') : message.content.length ); this.context.log.i('parsePrivateDiscordCommand: command: ' + message.content + '; commandName: ' + commandName); let commandFound = false; for (const command of message.source.commandManager.definedPrivateCommands) { if (commandName === commandLangManager.getString(command.getCommandInterfaceName())) { this.context.log.i('Found private command: ' + message.content); commandFound = true; // False positive for ESLint, since we break the loop immediately. /* eslint-disable no-await-in-loop */ await this.executePrivateDiscordCommand(message, command, commandLangManager); /* eslint-enable no-await-in-loop */ break; } } return commandFound; } /** * Executes a command from Discord source. Creates a command instance, parses arguments for it, checks * that the caller has necessary permissions and finally executes the instance. * If there were errors during parsing then replies to the source text channel with info about the error. * If there was no error, then replies to the channel with a string result generated by the command object. * @see DiscordCommand * @param {BaseMessage} message the message * @param {constructor<DiscordCommand>} commandClass the command class/constructor * @param {LangManager} commandLangManager the language manager to be used for the command * @return {Promise} nothing */ async executeCommand(message, commandClass, commandLangManager) { const command = await this.tryParseDiscordCommand(commandClass, message, commandLangManager); if (command === null) { return; } try { await this.context.permManager.checkDiscordCommandPermissions(message, command); } catch (error) { this.context.log.w( 'executeCommand: Not permitted to execute: "' + message.content + '"; Error message: ' + error + '; stack: ' + error.stack ); message.reply( commandLangManager.getString( 'permission_command_error', error instanceof BotPublicError ? error.message : commandLangManager.getString('internal_server_error') ) ); return; } let result; try { result = await command.executeForDiscord(message); } catch (error) { this.context.log.w( 'executeCommand: failed to execute command: "' + message.content + '"; Error message: ' + error + '; stack: ' + error.stack ); message.reply( commandLangManager.getString( 'execute_command_error', error instanceof BotPublicError ? error.message : commandLangManager.getString('internal_server_error') ) ); return; } if (result !== undefined && result !== null && result !== '') { message.reply(result); } } /** * Executes a private ("DM") command from Discord source. Creates a command instance, * parses arguments for it and executes the instance. * If there were errors during parsing then replies to the source text channel with info about the error. * If there was no error, then replies to the channel with a string result generated by the command object. * @see DiscordPrivateCommand * @param {BaseMessage} message the message * @param {constructor<DiscordCommand>} commandClass the command class/constructor * @param {LangManager} commandLangManager the language manager to be used for the command * @return {Promise} nothing */ async executePrivateDiscordCommand(message, commandClass, commandLangManager) { const command = await this.tryParsePrivateDiscordCommand(commandClass, message, commandLangManager); if (command === null) { return; } let result; try { result = await command.executeForDiscord(message); } catch (error) { this.context.log.w( 'executePrivateDiscordCommand: failed to execute command: "' + message.content + '"; Error message: ' + error + '; stack: ' + error.stack ); message.reply( commandLangManager.getString( 'execute_command_error', error instanceof BotPublicError ? error.message : commandLangManager.getString('internal_server_error') ) ); return; } if (result !== undefined && result !== null && result !== '') { message.reply(result); } } /** * Creates a command object based on a class, and parses arguments from the Discord message for it. * If there were errors during parsing then replies to the source text channel with info about the error. * @see DiscordCommand * @param {constructor<DiscordCommand>} commandClass the command class/constructor * @param {BaseMessage} message the message * @param {LangManager} commandLangManager the language manager to be used for the command * @return {Promise<DiscordCommand>} the command object with all arguments set up */ async tryParseDiscordCommand(commandClass, message, commandLangManager) { const command = commandClass.createForOrg(this.context, message.source.name, commandLangManager, message.orgId); try { await command.parseFromDiscord(message); } catch (error) { this.context.log.w( 'tryParseDiscordCommand: failed to parse command: "' + message.content + '"; Error message: ' + error + '; stack: ' + error.stack ); message.reply( commandLangManager.getString( 'validate_command_error', error instanceof BotPublicError ? error.message : commandLangManager.getString('internal_server_error'), await new HelpCommand( this.context, message.source.name, commandLangManager, message.orgId ).getHelpCommandString(commandClass.getCommandInterfaceName(), message.source) ) ); return null; } return command; } /** * Creates a private ("DM") command object based on a class, and parses arguments from the Discord message for it. * If there were errors during parsing then replies to the source text channel with info about the error. * @see DiscordCommand * @param {constructor<DiscordCommand>} commandClass the command class/constructor * @param {BaseMessage} message the message * @param {LangManager} commandLangManager the language manager to be used for the command * @return {Promise<DiscordCommand>} the command object with all arguments set up */ async tryParsePrivateDiscordCommand(commandClass, message, commandLangManager) { const command = commandClass.createForUser(this.context, message.source.name, commandLangManager); try { await command.parseFromDiscord(message); } catch (error) { this.context.log.w( 'tryParsePrivateDiscordCommand: failed to parse command: "' + message.content + '"; Error message: ' + error + '; stack: ' + error.stack ); message.reply( commandLangManager.getString( 'validate_command_error', error instanceof BotPublicError ? error.message : commandLangManager.getString('internal_server_error'), '' // @todo Create a private HelpCommand class and use it here to provide help on the private commands. ) ); return null; } return command; } } /** * Exports the CommandsParser class * @type {CommandsParser} */ module.exports = CommandsParser;
22,568
https://github.com/alexec/spring-cloud-sleuth/blob/master/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/TraceScope.java
Github Open Source
Open Source
LicenseRef-scancode-generic-cla, Apache-2.0
2,015
spring-cloud-sleuth
alexec
Java
Code
405
981
/* * Copyright 2013-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.sleuth; import java.io.Closeable; import lombok.SneakyThrows; import lombok.Value; import lombok.experimental.NonFinal; import org.springframework.cloud.sleuth.event.SpanReleasedEvent; import org.springframework.cloud.sleuth.util.ExceptionUtils; import org.springframework.context.ApplicationEventPublisher; /** * @author Spencer Gibb */ @Value @NonFinal public class TraceScope implements Closeable { private final ApplicationEventPublisher publisher; /** * the span for this scope */ private final Span span; /** * the span that was "current" before this scope was entered */ private final Span savedSpan; @NonFinal private boolean detached = false; public TraceScope(ApplicationEventPublisher publisher, Span span, Span savedSpan) { this.publisher = publisher; this.span = span; this.savedSpan = savedSpan; } /** * Remove this span as the current thread, but don't stop it yet or send it for * collection. This is useful if the span object is then passed to another thread for * use with Trace.continueTrace(). * * @return the same Span object */ public Span detach() { if (this.detached) { ExceptionUtils.error("Tried to detach trace span but " + "it has already been detached: " + this.span); } this.detached = true; Span cur = TraceContextHolder.getCurrentSpan(); if (cur != this.span) { ExceptionUtils.error("Tried to detach trace span but " + "it is not the current span for the '" + Thread.currentThread().getName() + "' thread: " + this.span + ". You have " + "probably forgotten to close or detach " + cur); } else { TraceContextHolder.setCurrentSpan(this.savedSpan); } return this.span; } @Override @SneakyThrows public void close() { if (this.detached) { return; } this.detached = true; Span cur = TraceContextHolder.getCurrentSpan(); if (cur != this.span) { ExceptionUtils.error("Tried to close trace span but " + "it is not the current span for the '" + Thread.currentThread().getName() + "' thread" + this.span + ". You have " + "probably forgotten to close or detach " + cur); } else { this.span.stop(); if (this.savedSpan != null && this.span.getParents().contains(this.savedSpan.getSpanId())) { this.publisher.publishEvent(new SpanReleasedEvent(this, this.savedSpan, this.span)); } else { this.publisher.publishEvent(new SpanReleasedEvent(this, this.span)); } TraceContextHolder.setCurrentSpan(this.savedSpan); } } }
42,029
https://github.com/Nimlotnik/yandex-route/blob/master/frontend/web/forum/phpbb/cache/driver/memcached.php
Github Open Source
Open Source
BSD-3-Clause
null
yandex-route
Nimlotnik
PHP
Code
328
1,078
<?php /** * * This file is part of the phpBB Forum Software package. * * @copyright (c) phpBB Limited <https://www.phpbb.com> * @license GNU General Public License, version 2 (GPL-2.0) * * For full copyright and license information, please see * the docs/CREDITS.txt file. * */ namespace phpbb\cache\driver; if (!defined('PHPBB_ACM_MEMCACHED_PORT')) { define('PHPBB_ACM_MEMCACHED_PORT', 11211); } if (!defined('PHPBB_ACM_MEMCACHED_COMPRESS')) { define('PHPBB_ACM_MEMCACHED_COMPRESS', true); } if (!defined('PHPBB_ACM_MEMCACHED_HOST')) { define('PHPBB_ACM_MEMCACHED_HOST', 'localhost'); } if (!defined('PHPBB_ACM_MEMCACHED')) { //can define multiple servers with host1/port1,host2/port2 format define('PHPBB_ACM_MEMCACHED', PHPBB_ACM_MEMCACHED_HOST . '/' . PHPBB_ACM_MEMCACHED_PORT); } /** * ACM for Memcached */ class memcached extends \phpbb\cache\driver\memory { /** @var string Extension to use */ protected $extension = 'memcached'; /** @var \Memcached Memcached class */ protected $memcached; /** @var int Flags */ protected $flags = 0; /** * Memcached constructor */ public function __construct() { // Call the parent constructor parent::__construct(); $this->memcached = new \Memcached(); $this->memcached->setOption(\Memcached::OPT_BINARY_PROTOCOL, true); // Memcached defaults to using compression, disable if we don't want // to use it if (!PHPBB_ACM_MEMCACHED_COMPRESS) { $this->memcached->setOption(\Memcached::OPT_COMPRESSION, false); } foreach (explode(',', PHPBB_ACM_MEMCACHED) as $u) { preg_match('#(.*)/(\d+)#', $u, $parts); $this->memcached->addServer(trim($parts[1]), (int) trim($parts[2])); } } /** * {@inheritDoc} */ public function unload() { parent::unload(); unset($this->memcached); } /** * {@inheritDoc} */ public function purge() { $this->memcached->flush(); parent::purge(); } /** * Fetch an item from the cache * * @param string $var Cache key * * @return mixed Cached data */ protected function _read($var) { return $this->memcached->get($this->key_prefix . $var); } /** * Store data in the cache * * @param string $var Cache key * @param mixed $data Data to store * @param int $ttl Time-to-live of cached data * @return bool True if the operation succeeded */ protected function _write($var, $data, $ttl = 2592000) { if (!$this->memcached->replace($this->key_prefix . $var, $data, $ttl)) { return $this->memcached->set($this->key_prefix . $var, $data, $ttl); } return true; } /** * Remove an item from the cache * * @param string $var Cache key * @return bool True if the operation succeeded */ protected function _delete($var) { return $this->memcached->delete($this->key_prefix . $var); } }
30
https://github.com/IvanSaavedra7/Programming-Logic-Exercises/blob/master/AppCap3/Desenvolvimento16.cs
Github Open Source
Open Source
MIT
null
Programming-Logic-Exercises
IvanSaavedra7
C#
Code
313
936
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppCap3 { class Desenvolvimento16 { int HInicio, Minicio, Sinicio; int Hfim, Mfim, Sfim; int SegundosHora, SegundosMin, SegundoSeg; int total; // 11 - 2 public void LerDados() { Console.Write(" Digite a HORA (p.m) de INICIO do evento: "); HInicio = Convert.ToInt16(Console.ReadLine()); Console.Write(" Digite o MINUTO (p.m) de INICIO do evento: "); Minicio = Convert.ToInt16(Console.ReadLine()); Console.Write(" Digite o SEGUNDOS (p.m) de INICIO do evento: "); Sinicio = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("-----------------------------------------"); Console.WriteLine("-----------------------------------------"); Console.Write(" Digite a HORA (A.m) de TERMINO do evento: "); Hfim = Convert.ToInt16(Console.ReadLine()); Console.Write(" Digite o MINUTO (A.m) de TERMINO do evento: "); Mfim = Convert.ToInt16(Console.ReadLine()); Console.Write(" Digite o SEGUNDOS (A.m) de TERMINO do evento: "); Sfim = Convert.ToInt16(Console.ReadLine()); } public void Conta() { if( HInicio <= 24 && HInicio >= 0 && Hfim <= 24 && Hfim >= 0 && Minicio <= 59 && Minicio >= 0 && Mfim <= 59 && Mfim >= 0 && Sinicio <= 59 && Sinicio >= 0 && Sfim <= 59 && Sfim >= 0) { // CODIGO NECESSARIO CASO O HORAIO ESTIVESSE EM P.M if (Hfim < HInicio) { Console.Clear(); Console.WriteLine(" O HORAIO DIGITADO NÃO CORREPONDE A UM CICLO DE 1 DIA !!! "); /* SegundosHora = ((12 - HInicio) + Hfim) * 3600; SegundosMin = (Mfim - Minicio) * 60; SegundoSeg = (Sfim - Sinicio); total = SegundosHora + SegundosMin + SegundoSeg; */ } else { SegundosHora = (Hfim - HInicio) * 3600; SegundosMin = (Mfim - Minicio) * 60; SegundoSeg = (Sfim - Sinicio); total = SegundosHora + SegundosMin + SegundoSeg; ////////////////////// Console.Clear(); Console.WriteLine(" Inicio: {0}H {1}MIN {2} SEG \n", HInicio, Minicio, Sinicio); Console.WriteLine(" Fim: {0}H {1}MIN {2} SEG ", Hfim, Mfim, Sfim); Console.WriteLine("-----------------------------------\n"); Console.WriteLine(" Duração do Evento: " + total + " SEGUNDOS"); } } else { Console.Clear(); Console.WriteLine( " O horário digitado não esta em (p.m) " ); } } } }
35,240
https://github.com/idies/SpecDash/blob/master/specdash/input/sdss/driver.py
Github Open Source
Open Source
Apache-2.0
2,022
SpecDash
idies
Python
Code
961
3,840
from specdash import api_urls from specdash.input import DataDriver from specdash.models import data_models as dm from specdash.models import enum_models as em import numpy as np from specdash.flux import fnu_to_flambda from specdash.models.data_models import Trace, SpectralLine from specdash import base_data_directories #import os.path import os from specdash.input import load_data_from_file import astropy import io import requests import json __all__ = ["FitsDataDriver"] class FitsDataDriver(DataDriver): MASK_BITS = { 0:'NOPLUG', 1:'BADTRACE', 2:'BADFLAT', 3:'BADARC', 4:'MANYBADCOLUMNS', 5:'MANYREJECTED', 6:'LARGESHIFT', 7:'BADSKYFIBER', 8:'NEARWHOPPER', 9:'WHOPPER', 10:'SMEARIMAGE', 11:'SMEARHIGHSN', 12:'SMEARMEDSN', 16:'NEARBADPIXEL', 17:'LOWFLAT', 18:'FULLREJECT', 19:'PARTIALREJECT', 20:'SCATTEREDLIGHT', 21:'CROSSTALK', 22:'NOSKY', 23:'BRIGHTSKY', 24:'NODATA', 25:'COMBINEREJ', 26:'BADFLUXFACTOR', 27:'BADSKYCHI', 28:'REDMONSTER' } def __init__(self): super().__init__() @classmethod def get_catalog_name(cls): #return "sdss" dir_path = os.path.dirname(os.path.abspath(__file__)) dir = dir_path.split("/")[-1] return dir @classmethod def get_spectrum_path(cls, specid): path_to_spec_file = base_data_directories[cls.get_catalog_name()] + specid + ".fits" if os.path.exists(path_to_spec_file): return path_to_spec_file else: return "" @classmethod def is_file_from_catalog(cls, hdulist): # this is a simple check for now hdu_names = ["PRIMARY", "COADD", "SPZLINE"] hdulist_names = [ hdulist[i].name.upper() for i in range(len(hdulist)) ] is_from_catalog = True for name in hdu_names: if name.upper() not in hdulist_names: is_from_catalog = False return is_from_catalog @classmethod def is_specid_from_catalog(cls, specid): _specid = specid + ".fits" if not specid.endswith(".fits") else specid path_to_spec_file = base_data_directories[cls.get_catalog_name()] + _specid return os.path.exists(path_to_spec_file) @classmethod def get_trace_list_from_fits(cls, name, hdulist=None, file_object=None): if hdulist is None and file_object is not None: hdulist = astropy.io.read(file_object)#(io.BytesIO(decoded_bytes))) elif hdulist is None and file_object is None: raise Exception("Unspecified parameters hdulist or decoded_bytes") if not cls.is_file_from_catalog(hdulist): raise Exception("Input spectrum does not belong to sdss catalog") catalog_name = cls.get_catalog_name() trace_list = [] coaddData =1 # the index of Coadd data in the HDU list zData =3 # index of absorption and emission line data in HDU list c=hdulist[coaddData].data z=hdulist[zData].data prim_header = hdulist[0].header if hdulist[2].data['Z'] is not None: zlist = hdulist[2].data['Z'] redshift = [round(z,6) for z in hdulist[2].data['Z']] if type(zlist) == list else [round(float(zlist),6)] else: redshift = None # the name of the data unit can be found on the official SDSS DR webpage #note: always convert data types to native python types, not numpy types. The reason is that everything has # to be serialized as json, and numpy objects cannot be automatically serialized as such. # object spectrum trace = Trace() trace.name = name wavelength = [float(10**lam) for lam in c['loglam']] trace.wavelength = wavelength trace.wavelength_unit = dm.WavelengthUnit.ANGSTROM trace.flux = [1.0*10**-17*float(x) for x in c['flux']] trace.flux_error = [1.0*10**-17*np.sqrt(float(1.0/x)) if x != 0 and x != np.nan else None for x in c['ivar']] trace.flux_unit = dm.FluxUnit.F_lambda trace.flambda = [x for x in trace.flux] trace.flambda_error = [x for x in trace.flux_error] trace.ancestors = [] trace.catalog = catalog_name trace.spectrum_type = em.SpectrumType.OBJECT trace.is_visible = True trace.redshift = redshift # and its masks: mask_info = cls.get_mask_info(trace_name=name, mask_array=[int(m) for m in c['and_mask']], mask_bits=cls.MASK_BITS) #trace.masks = {'mask': mask_info.get('mask'), 'mask_values':mask_info.get('mask_values')} trace.masks = mask_info #trace.mask_bits = mask_info.get('mask_bits') # and its metadata metadata = {'catalog':catalog_name, "type":em.SpectrumType.OBJECT, 'ra':str(prim_header["RA"]),'dec':str(prim_header["DEC"]), 'mjd':prim_header["MJD"],'plateID':prim_header["PLATEID"],'fiberID':prim_header["FIBERID"] } # add redshift values to metadata for i in range(len(redshift)): metadata['redshift_'+str(i+1)] = str(redshift[i]) trace.metadata = metadata # Loading the sky lines: speclines_list = [] speclines = hdulist[3].data for i in range(speclines.size): # adding only real lines data: if speclines['LINEAREA_ERR'][i] is not None and speclines['LINEAREA_ERR'][i] > 0: sline = SpectralLine() sline.line = speclines['LINENAME'][i] sline.wavelength = speclines['LINEWAVE'][i] sline.wavelength_unit = em.WavelengthUnit.ANGSTROM sline.flux_unit = em.FluxUnit.F_lambda sline.sigma = speclines['LINESIGMA'][i] sline.sigma_err = speclines['LINESIGMA_ERR'][i] sline.area = speclines['LINEAREA'][i] sline.area_err = speclines['LINEAREA_ERR'][i] sline.ew = speclines['LINEEW'][i] sline.ew_err = speclines['LINEEW_ERR'][i] sline.cont_level = speclines['LINECONTLEVEL'][i] sline.cont_level_err = speclines['LINECONTLEVEL_ERR'][i] speclines_list.append(sline.to_dict()) trace.spectral_lines = speclines_list # append recently-created trace trace_list.append(trace) # sky spectrum sky_trace = Trace() sky_trace.catalog = catalog_name sky_trace.name = name + "_sky" sky_trace.wavelength = wavelength sky_trace.flux = [1.0*10**-17*float(x) for x in c['sky']] sky_trace.wavelength_unit = dm.WavelengthUnit.ANGSTROM sky_trace.flux_unit = dm.FluxUnit.F_lambda sky_trace.ancestors = [name] sky_trace.flambda = [f for f in sky_trace.flux] sky_trace.is_visible = False sky_trace.spectrum_type=em.SpectrumType.SKY trace_list.append(sky_trace) # model trace: model_trace = Trace() model_trace.catalog = catalog_name model_trace.name = name + "_model_1" model_trace.spectrum_type_rank = 1 model_trace.wavelength = wavelength model_trace.flux = [1.0*10**-17*float(x) for x in c['model']] model_trace.wavelength_unit = dm.WavelengthUnit.ANGSTROM model_trace.flux_unit = dm.FluxUnit.F_lambda model_trace.ancestors = [name] model_trace.flambda = [f for f in model_trace.flux] model_trace.is_visible = False model_trace.spectrum_type=em.SpectrumType.MODEL trace_list.append(model_trace) # add visits if len(hdulist) > 4: for i in range(4,len(hdulist)-1): try: visit = Trace() visit.catalog = catalog_name visit.name = name + "_" + hdulist[i].name visit.wavelength = [float(10**lam) for lam in hdulist[i].data['loglam']] visit.flux = [1.0 * 10 ** -17 * float(x) for x in hdulist[i].data['flux']] visit.flux_error = [1.0 * 10 ** -17 * np.sqrt(float(1.0 / x)) if x != 0 and x != np.nan else None for x in hdulist[i].data['ivar']] visit.wavelength_unit = dm.WavelengthUnit.ANGSTROM visit.flux_unit = dm.FluxUnit.F_lambda visit.ancestors = [name] visit.flambda = [f for f in visit.flux] visit.flambda_error = [x for x in visit.flux_error] visit.is_visible = False visit.spectrum_type = em.SpectrumType.VISIT visit.metadata = {'catalog':catalog_name, "type":em.SpectrumType.VISIT, 'id':hdulist[i].name} mask_info = cls.get_mask_info(trace_name=visit.name, mask_array=[int(m) for m in hdulist[i].data['mask']], mask_bits=cls.MASK_BITS) visit.masks = mask_info trace_list.append(visit) except Exception as ex: pass hdulist.close() return trace_list @classmethod def get_data_from_specid(cls, specid, trace_name=None): if specid.startswith("spec") or specid.endswith(".fits"): specid = specid if specid.endswith(".fits") else specid + ".fits" base_dir = base_data_directories[cls.get_catalog_name()] run2d_subdirs = [d for d in os.listdir(base_dir) if os.path.isdir(base_dir + "/" + d) is True] for run2d_subdir in run2d_subdirs: plate = specid.split("-")[1] path_to_spec_file = base_dir + run2d_subdir + "/" + plate + "/" + specid if not cls.is_safe_path(path_to_spec_file): raise Exception("Invalid specid or file " + specid) if os.path.isfile(path_to_spec_file): break else: #specid = specid if specid.endswith(".fits") else specid + ".fits" catalog_name = cls.get_catalog_name() url = api_urls[catalog_name] + "?cmd=select+top+1+run2d,plate,mjd,fiberid+from+specobjall+where+specobjid={}&format=json&TaskName=specdash".format(specid) response = requests.get(url, timeout=10) if response.status_code < 200 & response.status_code >= 300: raise Exception("Unable to query input spectrum data") dat = json.loads(response.content) if type(dat) == dict or len(dat[0]['Rows']) == 0: raise Exception("Unable to find " + catalog_name + " spectrum identified by " + str(specid) ) mjd = dat[0]['Rows'][0]['mjd'] plate = dat[0]['Rows'][0]['plate'] fiberid = dat[0]['Rows'][0]['fiberid'] run2d = dat[0]['Rows'][0]['run2d'] #path_to_spec_file = base_data_directories[cls.get_catalog_name()] + specid spec_file_name = "spec-{:04d}-{}-{:04d}.fits".format(plate,mjd,fiberid) path_to_spec_file = base_data_directories[cls.get_catalog_name()] + "{}/{:04d}/{}".format(run2d,plate,spec_file_name) if not os.path.isfile(path_to_spec_file): raise Exception("Spectrum " + specid + " not found on file system.") trace_name = trace_name if trace_name is not None else specid.replace(".fits", "") hdulist = astropy.io.fits.open(path_to_spec_file) trace_list = cls.get_trace_list_from_fits(trace_name, hdulist=hdulist, file_object=None) return (trace_list, None)
16,686
https://github.com/aw20368/OpenLoco/blob/master/src/OpenLoco/Objects/AirportObject.h
Github Open Source
Open Source
MIT
null
OpenLoco
aw20368
C
Code
166
650
#pragma once #include "../Types.hpp" namespace OpenLoco { namespace Gfx { struct drawpixelinfo_t; } #pragma pack(push, 1) struct airport_var_AE_object { int16_t x; // 0x00 int16_t y; // 0x02 int16_t z; // 0x04 uint16_t flags; // 0x06 }; struct airport_var_B2_object { uint8_t var_00; uint8_t var_01; uint8_t var_02; uint8_t var_03; uint32_t var_04; uint32_t var_08; }; struct airport_object { string_id name; uint16_t build_cost_factor; // 0x02 uint16_t sell_cost_factor; // 0x04 uint8_t cost_index; //0x06 uint8_t var_07; uint32_t image; // 0x08 uint8_t pad_0C[0x10 - 0x0C]; uint16_t allowed_plane_types; // 0x10 uint8_t num_sprite_sets; // 0x12 uint8_t num_tiles; // 0x13 uint8_t pad_14[0xA0 - 0x14]; uint32_t large_tiles; // 0xA0 uint8_t min_x; // 0xA4 uint8_t min_y; // 0xA5 uint8_t max_x; // 0xA6 uint8_t max_y; // 0xA7 uint16_t designed_year; // 0xA8 uint16_t obsolete_year; // 0xAA uint8_t num_nodes; // 0xAC uint8_t num_edges; // 0xAD airport_var_AE_object* var_AE; airport_var_B2_object* var_B2; uint8_t pad_B6[0xBA - 0xB6]; void drawPreviewImage(Gfx::drawpixelinfo_t& dpi, const int16_t x, const int16_t y) const; void drawDescription(Gfx::drawpixelinfo_t& dpi, const int16_t x, const int16_t y, [[maybe_unused]] const int16_t width) const; }; #pragma pack(pop) }
42,203
https://github.com/jcroall/coverity-report-output-v7-json/blob/master/lib/main.js
Github Open Source
Open Source
Apache-2.0
null
coverity-report-output-v7-json
jcroall
JavaScript
Code
683
2,404
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const fs_1 = __importDefault(require("fs")); const inputs_1 = require("./inputs"); const core_1 = require("@actions/core"); const lib_1 = require("@jcroall/synopsys-sig-node/lib"); const coverity_issue_mapper_1 = require("@jcroall/synopsys-sig-node/lib/utils/coverity-issue-mapper"); function run() { return __awaiter(this, void 0, void 0, function* () { lib_1.logger.info('Starting Coverity GitHub Action'); if (inputs_1.DEBUG_MODE) { lib_1.logger.level = 'debug'; lib_1.logger.debug(`Enabled debug mode`); } if (!(0, lib_1.githubIsPullRequest)()) { lib_1.logger.info('Not a Pull Request. Nothing to do...'); return Promise.resolve(); } lib_1.logger.info(`Using JSON file path: ${inputs_1.JSON_FILE_PATH}`); // TODO validate file exists and is .json? const jsonV7Content = fs_1.default.readFileSync(inputs_1.JSON_FILE_PATH); const coverityIssues = JSON.parse(jsonV7Content.toString()); let mergeKeyToIssue = new Map(); const canCheckCoverity = inputs_1.COVERITY_URL && inputs_1.COVERITY_USERNAME && inputs_1.COVERITY_PASSWORD && inputs_1.COVERITY_PROJECT_NAME; if (!canCheckCoverity) { lib_1.logger.warning('Missing Coverity Connect info. Issues will not be checked against the server.'); } else { const allMergeKeys = coverityIssues.issues.map(issue => issue.mergeKey); const allUniqueMergeKeys = new Set(allMergeKeys); if (canCheckCoverity && coverityIssues && coverityIssues.issues.length > 0) { try { mergeKeyToIssue = yield (0, coverity_issue_mapper_1.coverityMapMatchingMergeKeys)(inputs_1.COVERITY_URL, inputs_1.COVERITY_USERNAME, inputs_1.COVERITY_PASSWORD, inputs_1.COVERITY_PROJECT_NAME, allUniqueMergeKeys); } catch (error) { (0, core_1.setFailed)(error); return Promise.reject(); } } } const newReviewComments = []; const actionReviewComments = yield (0, lib_1.githubGetExistingReviewComments)(inputs_1.GITHUB_TOKEN).then(comments => comments.filter(comment => comment.body.includes(lib_1.COMMENT_PREFACE))); const actionIssueComments = yield (0, lib_1.githubGetExistingIssueComments)(inputs_1.GITHUB_TOKEN).then(comments => comments.filter(comment => { var _a; return (_a = comment.body) === null || _a === void 0 ? void 0 : _a.includes(lib_1.COMMENT_PREFACE); })); const diffMap = yield (0, lib_1.githubGetPullRequestDiff)(inputs_1.GITHUB_TOKEN).then(lib_1.githubGetDiffMap); for (const issue of coverityIssues.issues) { lib_1.logger.info(`Found Coverity Issue ${issue.mergeKey} at ${issue.mainEventFilePathname}:${issue.mainEventLineNumber}`); const projectIssue = mergeKeyToIssue.get(issue.mergeKey); let ignoredOnServer = false; let newOnServer = true; if (projectIssue) { ignoredOnServer = projectIssue.action == 'Ignore' || projectIssue.classification in ['False Positive', 'Intentional']; newOnServer = projectIssue.firstSnapshotId == projectIssue.lastSnapshotId; lib_1.logger.info(`Issue state on server: ignored=${ignoredOnServer}, new=${newOnServer}`); } const reviewCommentBody = (0, lib_1.coverityCreateReviewCommentMessage)(issue); const issueCommentBody = (0, lib_1.coverityCreateIssueCommentMessage)(issue); const reviewCommentIndex = actionReviewComments.findIndex(comment => comment.line === issue.mainEventLineNumber && comment.body.includes(issue.mergeKey)); let existingMatchingReviewComment = undefined; if (reviewCommentIndex !== -1) { existingMatchingReviewComment = actionReviewComments.splice(reviewCommentIndex, 1)[0]; } const issueCommentIndex = actionIssueComments.findIndex(comment => { var _a; return (_a = comment.body) === null || _a === void 0 ? void 0 : _a.includes(issue.mergeKey); }); let existingMatchingIssueComment = undefined; if (issueCommentIndex !== -1) { existingMatchingIssueComment = actionIssueComments.splice(issueCommentIndex, 1)[0]; } if (existingMatchingReviewComment !== undefined) { lib_1.logger.info(`Issue already reported in comment ${existingMatchingReviewComment.id}, updating if necessary...`); if (existingMatchingReviewComment.body !== reviewCommentBody) { (0, lib_1.githubUpdateExistingReviewComment)(inputs_1.GITHUB_TOKEN, existingMatchingReviewComment.id, reviewCommentBody); } } else if (existingMatchingIssueComment !== undefined) { lib_1.logger.info(`Issue already reported in comment ${existingMatchingIssueComment.id}, updating if necessary...`); if (existingMatchingIssueComment.body !== issueCommentBody) { (0, lib_1.githubUpdateExistingIssueComment)(inputs_1.GITHUB_TOKEN, existingMatchingIssueComment.id, issueCommentBody); } } else if (ignoredOnServer) { lib_1.logger.info('Issue ignored on server, no comment needed.'); } else if (!newOnServer) { lib_1.logger.info('Issue already existed on server, no comment needed.'); } else if (isInDiff(issue, diffMap)) { lib_1.logger.info('Issue not reported, adding a comment to the review.'); newReviewComments.push(createReviewComment(issue, reviewCommentBody)); } else { lib_1.logger.info('Issue not reported, adding an issue comment.'); (0, lib_1.githubCreateIssueComment)(inputs_1.GITHUB_TOKEN, issueCommentBody); } } for (const comment of actionReviewComments) { if ((0, lib_1.coverityIsPresent)(comment.body)) { (0, core_1.info)(`Comment ${comment.id} represents a Coverity issue which is no longer present, updating comment to reflect resolution.`); (0, lib_1.githubUpdateExistingReviewComment)(inputs_1.GITHUB_TOKEN, comment.id, (0, lib_1.coverityCreateNoLongerPresentMessage)(comment.body)); } } for (const comment of actionIssueComments) { if (comment.body !== undefined && (0, lib_1.coverityIsPresent)(comment.body)) { (0, core_1.info)(`Comment ${comment.id} represents a Coverity issue which is no longer present, updating comment to reflect resolution.`); (0, lib_1.githubUpdateExistingReviewComment)(inputs_1.GITHUB_TOKEN, comment.id, (0, lib_1.coverityCreateNoLongerPresentMessage)(comment.body)); } } if (newReviewComments.length > 0) { (0, core_1.info)('Publishing review...'); (0, lib_1.githubCreateReview)(inputs_1.GITHUB_TOKEN, newReviewComments); } (0, core_1.info)(`Found ${coverityIssues.issues.length} Coverity issues.`); }); } function isInDiff(issue, diffMap) { const diffHunks = diffMap.get(issue.mainEventFilePathname); if (!diffHunks) { return false; } return diffHunks.filter(hunk => hunk.firstLine <= issue.mainEventLineNumber).some(hunk => issue.mainEventLineNumber <= hunk.lastLine); } function createReviewComment(issue, commentBody) { return { path: (0, lib_1.githubRelativizePath)(issue.mainEventFilePathname), body: commentBody, line: issue.mainEventLineNumber, side: 'RIGHT' }; } run();
7,409
https://github.com/nflixiang/vue95-ui/blob/master/docs/.vuepress/components/AppBar95.vue
Github Open Source
Open Source
MIT
2,020
vue95-ui
nflixiang
Vue
Code
112
423
<template> <header class="app-bar-95"> <slot></slot> </header> </template> <script> export default { name: "AppBar95" }; </script> <style lang="less" scoped> .header { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; // vertical-align: baseline; display: block; } .box-styles(@bgColor: #ced0cf, @color: #050608) { box-sizing: border-box; display: inline-block; background-color: @bgColor; color: @color; } .border-styles(@firstBorderColor: #ffffff, @secondBorderColor: #050608) { border-style: solid; border-width: 2px; border-left-color: @firstBorderColor; border-top-color: @firstBorderColor; border-right-color: @secondBorderColor; border-bottom-color: @secondBorderColor; } .app-bar-95 { .border-styles; box-shadow: rgba(0, 0, 0, 0.35) 4px 4px 10px 0px, rgb(223, 224, 227) 1px 1px 0px 1px inset, rgb(136, 140, 143) -1px -1px 0px 1px inset; .box-styles; position: absolute; top: 0; right: 0; left: auto; display: flex; flex-direction: column; width: 100%; } </style>
24,469
https://github.com/jeswin/isotropy-parser-db/blob/master/src/schemas/sort.js
Github Open Source
Open Source
MIT
null
isotropy-parser-db
jeswin
JavaScript
Code
931
2,668
import R from "ramda"; import { builtins as $, capture, any, array, optionalItem, literal, Match, Skip } from "chimpanzee"; import composite from "../chimpanzee-utils/composite"; import { source } from "../chimpanzee-utils"; import { collection, select, slice } from "./"; import integer from "./common/integer"; import { sort } from "../db-statements"; const operators = any([">", "<", ">=", "<=", "==="].map(i => literal(i))); /* async function getTodos(who) { return myDb.todos .sort( (x, y) => x.assignee > y.assignee ? 1 : x.assignee === y.assignee ? 0 : -1 ); } Variants of (a,b) => a.total > b.total ? 1 : a.total < b.total ? -1 : 0; Terminology: 1 Swap 0 Same -1 Keep */ function getSortExpression1({ param1, param2, lhs1, lhsProp1, rhs1, rhsProp1, operator1, val1, lhs2, lhsProp2, rhs2, rhsProp2, operator2, val2, val3 }) { const INVALID_EXPR_ERROR = `The sort expression is invalid. Should return less than zero, zero and greater than zero according to JS specifications.`; //Make sure all the properties are the same. eg: "field" in x.field > y.field ? 1 : x.field === ... return lhsProp1 === rhsProp1 && lhsProp1 === lhsProp2 && lhsProp1 === rhsProp2 ? [val1, val2, val3].every(val => typeof val === "number") ? (() => { //val > 0 is 1, val < 0 is -1, 0 is 0 const normalizeValue = val => typeof val === "number" ? val > 0 ? 1 : val < 0 ? -1 : 0 : new Skip(INVALID_EXPR_ERROR); const ternaryExpr = [ { lhs: lhs1, rhs: rhs1, operator: operator1, val: normalizeValue(val1) }, { lhs: lhs2, rhs: rhs2, operator: operator2, val: normalizeValue(val2) } ]; //This picks the part of the ternary which has x.field > y.field or y.field < x.field const xGreaterThanY = ({ lhs, rhs, operator, val }) => (param1 === lhs && param2 === rhs && [">", ">="].includes(operator)) || (param2 === lhs && param1 === rhs && ["<", "<="].includes(operator)); //This picks the part of the ternary which has y.field > x.field or x.field < y.field const yGreaterThanX = ({ lhs, rhs, operator, val }) => (param2 === lhs && param1 === rhs && [">", ">="].includes(operator)) || (param1 === lhs && param2 === rhs && ["<", "<="].includes(operator)); //This picks the part of the ternary which has x.field === y.field const xEqualsY = ({ lhs, rhs, operator, val }) => param1 === lhs && param2 === rhs && ["==", "==="].includes(operator); const expressions = [ [xGreaterThanY, yGreaterThanX, 1], [yGreaterThanX, xGreaterThanY, -1] ]; const result = (function loop(_expressions) { const [first, second, ascendingVal] = _expressions[0]; const result = ternaryExpr.find(first) ? (() => { const firstVal = ternaryExpr.find(first).val; const secondVal = ternaryExpr.find(second) ? ternaryExpr.find(second).val : ternaryExpr.find(xEqualsY) ? normalizeValue(val3) : new Skip(INVALID_EXPR_ERROR); return !(secondVal instanceof Skip) ? firstVal === -secondVal ? { field: lhsProp1, ascending: firstVal === ascendingVal } : new Skip(INVALID_EXPR_ERROR) : secondVal; })() : undefined; return ( result || (_expressions.length > 1 ? loop(_expressions.slice(1)) : new Skip(INVALID_EXPR_ERROR)) ); })(expressions); return result; })() : new Skip(INVALID_EXPR_ERROR) : new Skip(`Sort expression should reference the same fields in the ternary expression.`); } const compareFn1 = $.obj( { type: "ArrowFunctionExpression", params: [ { type: "Identifier", name: capture("name") }, { type: "Identifier", name: capture("name") } ], body: { type: "ConditionalExpression", test: { type: "BinaryExpression", left: { type: "MemberExpression", object: { type: "Identifier", name: capture("lhs1") }, property: { type: "Identifier", name: capture("lhsProp1") } }, operator: capture("operator1"), right: { type: "MemberExpression", object: { type: "Identifier", name: capture("rhs1") }, property: { type: "Identifier", name: capture("rhsProp1") } } }, consequent: integer("val1"), alternate: { type: "ConditionalExpression", test: { type: "BinaryExpression", left: { type: "MemberExpression", object: { type: "Identifier", name: capture("lhs2") }, property: { type: "Identifier", name: capture("lhsProp2") } }, operator: capture("operator2"), right: { type: "MemberExpression", object: { type: "Identifier", name: capture("rhs2") }, property: { type: "Identifier", name: capture("rhsProp2") } } }, consequent: integer("val2"), alternate: integer("val3") } } }, { build: obj => context => result => result instanceof Match ? getSortExpression1({ param1: result.value.params[0].name, param2: result.value.params[1].name, ...result.value }) : result } ); /* async function getTodos(who) { // Ascending return myDb.todos .sort( (x, y) => x.assignee - y.assignee ); // Descending return myDb.todos .sort( (x, y) => y.assignee - x.assignee ); //well, we also support // Ascending return myDb.todos .sort( (x, y) => -(x.assignee - y.assignee) ); // Descending return myDb.todos .sort( (x, y) => -(y.assignee - x.assignee) ); } */ const sortExpression2Ascending = { type: "BinaryExpression", left: { type: "MemberExpression", object: { type: "Identifier", name: capture("lhsObject") }, property: { type: "Identifier", name: capture("lhsProp") } }, operator: "-", right: { type: "MemberExpression", object: { type: "Identifier", name: capture("rhsObject") }, property: { type: "Identifier", name: capture("rhsProp") } } }; const sortExpression2Descending = { type: "UnaryExpression", operator: capture("operator"), argument: sortExpression2Ascending }; function getSortExpression2({ param1, param2, lhsObject, lhsProp, rhsObject, rhsProp, operator }) { const getSortOrder = negated => (!negated && param1 === lhsObject) || (negated && param1 === rhsObject); return [param1, param2].every(p => [lhsObject, rhsObject].includes(p)) ? lhsProp === rhsProp ? { field: lhsProp, ascending: getSortOrder(operator === "-") } : new Skip(`The sort expression must reference the same property on compared objects.`) : new Skip(`The sort expression must reference parameters ${param1} and ${param2}.`); } const compareFn2 = $.obj( { type: "ArrowFunctionExpression", params: [ { type: "Identifier", name: capture("name") }, { type: "Identifier", name: capture("name") } ], body: any([sortExpression2Ascending, sortExpression2Descending]) }, { build: obj => context => result => result instanceof Match ? getSortExpression2({ param1: result.value.params[0].name, param2: result.value.params[1].name, ...result.value.body }) : result } ); export default function(state, analysisState) { return composite( { type: "CallExpression", callee: { type: "MemberExpression", object: source([collection])(state, analysisState), property: { type: "Identifier", name: "sort" } }, arguments: array([any([compareFn1, compareFn2])]) }, { build: obj => context => result => result instanceof Match ? sort(result.value.object, { fields: result.value.arguments }) : result } ); }
5,449
https://github.com/siam-biswas/Engine/blob/master/Example/Example/Feature/Root/RootEvent.swift
Github Open Source
Open Source
MIT
2,020
Engine
siam-biswas
Swift
Code
37
93
// // RootEvent.swift // Example // // Created by Md. Siam Biswas on 25/7/20. // Copyright © 2020 siambiswas. All rights reserved. // import Foundation import Engine enum RootState{ case normal,empty,populated,loading,error } enum RootAction{ case next }
32,545
https://github.com/Fuyun791/education/blob/master/src/main/java/com/education/controller/OnlineCourseHourController.java
Github Open Source
Open Source
Apache-2.0
2,021
education
Fuyun791
Java
Code
193
858
package com.education.controller; import com.education.entity.RespBody; import com.education.entity.OnlineCourseHour; import com.education.service.IOnlineCourseHourService; import com.github.pagehelper.PageInfo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; import org.springframework.web.bind.annotation.RestController; /** * <p> * 在线课程课时表 前端控制器 * </p> * * @author dell * @since 2020-05-24 */ @Api(tags = "OnlineCourseHourController", description = "在线课程课时管理") @RestController @RequestMapping("/education/online-course-hour") public class OnlineCourseHourController { private final IOnlineCourseHourService onlineCourseHourService; @Autowired public OnlineCourseHourController(IOnlineCourseHourService onlineCourseHourService) { this.onlineCourseHourService = onlineCourseHourService; } @ApiOperation("查询在线课程课时") @RequestMapping(value = "/list", method = RequestMethod.GET) public RespBody findOnlineCourseHour(OnlineCourseHour onlineCourseHour, @RequestParam(value = "pageStart", defaultValue = "1") Integer pageStart, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) { List<OnlineCourseHour> onlineCourseHourList = onlineCourseHourService .findOnlineCourseHour(onlineCourseHour, pageStart, pageSize); PageInfo<OnlineCourseHour> pageInfo = new PageInfo<>(onlineCourseHourList); return RespBody.ok(pageInfo); } @ApiOperation("添加在线课程课时") @RequestMapping(value = "/insert", method = RequestMethod.POST) public RespBody insertOnlineCourseHour(OnlineCourseHour onlineCourseHour) { int result = onlineCourseHourService.insertOnlineCourseHour(onlineCourseHour); if (result == 1) { return RespBody.ok(); } return RespBody.error(); } @ApiOperation("修改在线课程课时") @RequestMapping(value = "/update", method = RequestMethod.POST) public RespBody updateOnlineCourseHour(OnlineCourseHour onlineCourseHour) { int result = onlineCourseHourService.updateOnlineCourseHour(onlineCourseHour); if (result == 1) { return RespBody.ok(); } return RespBody.error(); } @ApiOperation("删除在线课程课时") @RequestMapping(value = "/delete", method = RequestMethod.DELETE) public RespBody deleteOnlineCourseHour(@RequestParam("id") int id) { int result = onlineCourseHourService.deleteOnlineCourseHour(id); if (result == 1) { return RespBody.ok(); } return RespBody.error(); } }
31,319
https://github.com/octonion/volleyball-m/blob/master/ncaa_pbp_older/extensions/predict_weekly.sql
Github Open Source
Open Source
MIT
2,019
volleyball-m
octonion
PLpgSQL
Code
327
1,887
begin; set timezone to 'America/New_York'; create temporary table predict ( game_date date, site text, home text, hd text, away text, vd text, p float, w25 float, l25 float, w15 float, l15 float ); insert into predict (game_date,site,home,hd,away,vd,p) ( select g.game_date::date as date, 'home' as site, hd.school_name as home, 'D'||hd.div_id as hd, vd.school_name as away, 'D'||vd.div_id as vd, h.offensive*o.exp_factor*v.defensive/(1.0+h.offensive*o.exp_factor*v.defensive) as p from ncaa.games g join ncaa_pbp._schedule_factors h on (h.year,h.school_id)=(g.year,g.school_id) join ncaa_pbp._schedule_factors v on (v.year,v.school_id)=(g.year,g.opponent_id) join ncaa.schools_divisions hd on (hd.year,hd.school_id)=(h.year,h.school_id) join ncaa.schools_divisions vd on (vd.year,vd.school_id)=(v.year,v.school_id) join ncaa_pbp._factors o on (o.parameter,o.level)=('field','offense_home') join ncaa_pbp._factors d on (d.parameter,d.level)=('field','defense_home') where not(g.game_date='') and g.game_date::date between current_date and current_date+6 and g.location='Home' union select g.game_date::date as date, 'neutral' as site, hd.school_name as home, 'D'||hd.div_id as hd, vd.school_name as away, 'D'||vd.div_id as vd, h.offensive*v.defensive/(1.0+h.offensive*v.defensive) as p from ncaa.games g join ncaa_pbp._schedule_factors h on (h.year,h.school_id)=(g.year,g.school_id) join ncaa_pbp._schedule_factors v on (v.year,v.school_id)=(g.year,g.opponent_id) join ncaa.schools_divisions hd on (hd.year,hd.school_id)=(h.year,h.school_id) join ncaa.schools_divisions vd on (vd.year,vd.school_id)=(v.year,v.school_id) --join set_probability(25, pr.p) sp25 on TRUE --join set_probability(15, pr.p) sp15 on TRUE where not(g.game_date='') and g.game_date::date between current_date and current_date+6 and g.location='Neutral' and (g.school_id < g.opponent_id) ); update predict set w25=set_probability(25, predict.p); update predict set l25=1-w25; update predict set w15=set_probability(15, predict.p); update predict set l15=1-w15; select game_date as date, site, home, hd, away, vd, (w25^3)::numeric(4,3) as w3, (3*w25^3*l25)::numeric(4,3) as w4, (6*w25^2*l25^2*w15)::numeric(4,3) as w5, (w25^3+3*w25^3*l25+6*w25^2*l25^2*w15)::numeric(4,3) as win, (1-(w25^3+3*w25^3*l25+6*w25^2*l25^2*w15))::numeric(4,3) as lose from predict order by date,home asc; select game_date as date, site, home, hd, away, vd, (l25^3)::numeric(4,3) as l3, (3*l25^3*w25)::numeric(4,3) as l4, (6*l25^2*w25^2*l15)::numeric(4,3) as l5, ( 3*(w25^3+3*w25^3*l25+6*w25^2*l25^2*w15)+ 2*(6*l25^2*w25^2*l15)+ 1*(3*l25^3*w25)+ 0*(l25^3) )::numeric(4,3) as e_ws, ( 3*(l25^3+3*l25^3*w25+6*l25^2*w25^2*l15)+ 2*(6*w25^2*l25^2*w15)+ 1*(3*w25^3*l25)+ 0*(w25^3) )::numeric(4,3) as e_ls from predict order by date,home asc; copy ( select game_date as date, site, home, hd, away, vd, (w25^3)::numeric(4,3) as w3, (3*w25^3*l25)::numeric(4,3) as w4, (6*w25^2*l25^2*w15)::numeric(4,3) as w5, (w25^3+3*w25^3*l25+6*w25^2*l25^2*w15)::numeric(4,3) as win, (1-(w25^3+3*w25^3*l25+6*w25^2*l25^2*w15))::numeric(4,3) as lose, (l25^3)::numeric(4,3) as l3, (3*l25^3*w25)::numeric(4,3) as l4, (6*l25^2*w25^2*l15)::numeric(4,3) as l5, ( 3*(w25^3+3*w25^3*l25+6*w25^2*l25^2*w15)+ 2*(6*l25^2*w25^2*l15)+ 1*(3*l25^3*w25)+ 0*(l25^3) )::numeric(4,3) as e_ws, ( 3*(l25^3+3*l25^3*w25+6*l25^2*w25^2*l15)+ 2*(6*w25^2*l25^2*w15)+ 1*(3*w25^3*l25)+ 0*(w25^3) )::numeric(4,3) as e_ls from predict order by date,home asc ) to '/tmp/predict_weekly.csv' csv header; commit;
50,919
https://github.com/GotanDev/msgraph-sdk-java/blob/master/src/main/java/com/microsoft/graph/requests/PersonCollectionPage.java
Github Open Source
Open Source
MIT
2,022
msgraph-sdk-java
GotanDev
Java
Code
160
386
// Template Source: BaseEntityCollectionPage.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.models.Person; import com.microsoft.graph.requests.PersonCollectionRequestBuilder; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.requests.PersonCollectionResponse; import com.microsoft.graph.http.BaseCollectionPage; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Person Collection Page. */ public class PersonCollectionPage extends BaseCollectionPage<Person, PersonCollectionRequestBuilder> { /** * A collection page for Person * * @param response the serialized PersonCollectionResponse from the service * @param builder the request builder for the next collection page */ public PersonCollectionPage(@Nonnull final PersonCollectionResponse response, @Nonnull final PersonCollectionRequestBuilder builder) { super(response, builder); } /** * Creates the collection page for Person * * @param pageContents the contents of this page * @param nextRequestBuilder the request builder for the next page */ public PersonCollectionPage(@Nonnull final java.util.List<Person> pageContents, @Nullable final PersonCollectionRequestBuilder nextRequestBuilder) { super(pageContents, nextRequestBuilder); } }
5,764
https://github.com/plugins-zander/docsify-slides/blob/master/src/index.js
Github Open Source
Open Source
MIT
2,021
docsify-slides
plugins-zander
JavaScript
Code
16
49
import { slidePlugin } from './slides' window.$docsify = window.$docsify || {} window.$docsify.plugins = (window.$docsify.plugins || []).concat([slidePlugin])
22,549
https://github.com/techno-express/sqrl/blob/master/src/Trianglman/Sqrl/Tests/TestScenario.php
Github Open Source
Open Source
MIT
2,021
sqrl
techno-express
PHP
Code
104
271
<?php namespace Trianglman\Sqrl\Tests; use PHPUnit\Framework\TestCase; abstract class TestScenario { /** * @var TestCase */ protected $test; public function __construct(TestCase $test) { $this->test = $test; } /** * Sets up the data that would be set on the server end before the scenario happens * * @param callable $run * * @return TestScenario */ public function given(callable $run): TestScenario { $run(); return $this; } /** * Describes the scenario happening * * @param callable $run * * @return TestScenario */ public function when(callable $run): TestScenario { $run(); return $this; } /** * @param callable $run */ public function then(callable $run): void { $run(); } }
46,916
https://github.com/hemslo/sicp-solutions/blob/master/ch2/07.scm
Github Open Source
Open Source
MIT
null
sicp-solutions
hemslo
Scheme
Code
53
101
; Alyssa’s program is incomplete because she has not specified the ; implementation of the interval abstraction. Here is a definition of the ; interval constructor: (define (make-interval a b) (cons a b)) ; Define selectors upper-bound and lower-bound to complete the implementation. (define (upper-bound interval) (cdr interval)) (define (lower-bound interval) (car interval))
50,941
https://github.com/JamesRandall/AccidentalFish.Foundations/blob/master/Source/AccidentalFish.Foundations.Resources.Azure/Implementation/IAzureSettings.cs
Github Open Source
Open Source
MIT
2,017
AccidentalFish.Foundations
JamesRandall
C#
Code
13
48
namespace AccidentalFish.Foundations.Resources.Azure.Implementation { interface IAzureSettings { bool CreateIfNotExists { get; } } }
30,927
https://github.com/boeyum/BoligPark/blob/master/examples/BoligparkAdm/src/main/java/no/jib/parkering/adm/domain/DataListe.java
Github Open Source
Open Source
Apache-2.0
null
BoligPark
boeyum
Java
Code
43
133
package no.jib.parkering.adm.domain; import java.util.ArrayList; public class DataListe { private ArrayList<DataRecord> list = new ArrayList<DataRecord>(); public void setList(DataRecord rec) { list.add(rec); } public int size() { return list.size(); } public DataRecord getList(int ix) { return list.get(ix); } public void clear() { list.clear(); } }
50,430
https://github.com/nicholasio/nicholasandre.com.br/blob/master/mantisbt/mantisbt-1.2.17/manage_config_work_threshold_set.php
Github Open Source
Open Source
Apache-2.0
null
nicholasandre.com.br
nicholasio
PHP
Code
702
2,420
<?php # MantisBT - a php based bugtracking system # MantisBT is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # MantisBT is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with MantisBT. If not, see <http://www.gnu.org/licenses/>. /** * @package MantisBT * @copyright Copyright (C) 2000 - 2002 Kenzaburo Ito - kenito@300baud.org * @copyright Copyright (C) 2002 - 2014 MantisBT Team - mantisbt-dev@lists.sourceforge.net * @link http://www.mantisbt.org */ /** * MantisBT Core API's */ require_once( 'core.php' ); require_once( 'email_api.php' ); form_security_validate( 'manage_config_work_threshold_set' ); auth_reauthenticate(); $t_redirect_url = 'manage_config_work_threshold_page.php'; $t_project = helper_get_current_project(); html_page_top( lang_get( 'manage_threshold_config' ), $t_redirect_url ); $t_access = current_user_get_access_level(); function set_capability_row( $p_threshold, $p_all_projects_only=false ) { global $t_access, $t_project; if ( ( $t_access >= config_get_access( $p_threshold ) ) && ( ( ALL_PROJECTS == $t_project ) || !$p_all_projects_only ) ) { $f_threshold = gpc_get_int_array( 'flag_thres_' . $p_threshold, array() ); $f_access = gpc_get_int( 'access_' . $p_threshold ); # @@debug @@ echo "<br />for $p_threshold "; var_dump($f_threshold, $f_access); echo '<br />'; $t_access_levels = MantisEnum::getAssocArrayIndexedByValues( config_get( 'access_levels_enum_string' ) ); ksort( $t_access_levels ); reset( $t_access_levels ); $t_lower_threshold = NOBODY; $t_array_threshold = array(); foreach( $t_access_levels as $t_access_level => $t_level_name ) { if ( in_array( $t_access_level, $f_threshold ) ) { if ( NOBODY == $t_lower_threshold ) { $t_lower_threshold = $t_access_level; } $t_array_threshold[] = $t_access_level; } else { if ( NOBODY <> $t_lower_threshold ) { $t_lower_threshold = -1; } } # @@debug @@ var_dump($$t_access_level, $t_lower_threshold, $t_array_threshold); echo '<br />'; } $t_existing_threshold = config_get( $p_threshold ); $t_existing_access = config_get_access( $p_threshold ); if ( -1 == $t_lower_threshold ) { if ( ( $t_existing_threshold != $t_array_threshold ) || ( $t_existing_access != $f_access ) ) { config_set( $p_threshold, $t_array_threshold, NO_USER, $t_project, $f_access ); } } else { if ( ( $t_existing_threshold != $t_lower_threshold ) || ( $t_existing_access != $f_access ) ) { config_set( $p_threshold, $t_lower_threshold, NO_USER, $t_project, $f_access ); } } } } function set_capability_boolean( $p_threshold, $p_all_projects_only=false ) { global $t_access, $t_project; if ( ( $t_access >= config_get_access( $p_threshold ) ) && ( ( ALL_PROJECTS == $t_project ) || !$p_all_projects_only ) ) { $f_flag = gpc_get( 'flag_' . $p_threshold, OFF ); $f_access = gpc_get_int( 'access_' . $p_threshold ); $f_flag = ( OFF == $f_flag ) ? OFF : ON; # @@debug @@ echo "<br />for $p_threshold "; var_dump($f_flag, $f_access); echo '<br />'; if ( ( $f_flag != config_get( $p_threshold ) ) || ( $f_access != config_get_access( $p_threshold ) ) ) { config_set( $p_threshold, $f_flag, NO_USER, $t_project, $f_access ); } } } function set_capability_enum( $p_threshold, $p_all_projects_only=false ) { global $t_access, $t_project; if ( ( $t_access >= config_get_access( $p_threshold ) ) && ( ( ALL_PROJECTS == $t_project ) || !$p_all_projects_only ) ) { $f_flag = gpc_get( 'flag_' . $p_threshold ); $f_access = gpc_get_int( 'access_' . $p_threshold ); # @@debug @@ echo "<br />for $p_threshold "; var_dump($f_flag, $f_access); echo '<br />'; if ( ( $f_flag != config_get( $p_threshold ) ) || ( $f_access != config_get_access( $p_threshold ) ) ) { config_set( $p_threshold, $f_flag, NO_USER, $t_project, $f_access ); } } } # Issues set_capability_row( 'report_bug_threshold' ); set_capability_enum( 'bug_submit_status' ); set_capability_row( 'update_bug_threshold' ); set_capability_boolean( 'allow_close_immediately' ); set_capability_boolean( 'allow_reporter_close' ); set_capability_row( 'monitor_bug_threshold' ); set_capability_row( 'handle_bug_threshold' ); set_capability_row( 'update_bug_assign_threshold' ); set_capability_row( 'move_bug_threshold', true ); set_capability_row( 'delete_bug_threshold' ); set_capability_row( 'reopen_bug_threshold' ); set_capability_boolean( 'allow_reporter_reopen' ); set_capability_enum( 'bug_reopen_status' ); set_capability_enum( 'bug_reopen_resolution' ); set_capability_enum( 'bug_resolved_status_threshold' ); set_capability_enum( 'bug_readonly_status_threshold' ); set_capability_row( 'private_bug_threshold' ); set_capability_row( 'update_readonly_bug_threshold' ); set_capability_row( 'update_bug_status_threshold' ); set_capability_row( 'set_view_status_threshold' ); set_capability_row( 'change_view_status_threshold' ); set_capability_row( 'show_monitor_list_threshold' ); set_capability_boolean( 'auto_set_status_to_assigned' ); set_capability_enum( 'bug_assigned_status' ); set_capability_boolean( 'limit_reporters', true ); # Notes set_capability_row( 'add_bugnote_threshold' ); set_capability_row( 'update_bugnote_threshold' ); set_capability_boolean( 'bugnote_allow_user_edit_delete' ); set_capability_row( 'delete_bugnote_threshold' ); set_capability_row( 'private_bugnote_threshold' ); # Others set_capability_row( 'view_changelog_threshold' ); set_capability_row( 'view_handler_threshold' ); set_capability_row( 'view_history_threshold' ); set_capability_row( 'bug_reminder_threshold' ); set_capability_row( 'reminder_receive_threshold' ); form_security_purge( 'manage_config_work_threshold_set' ); ?> <br /> <div align="center"> <?php echo lang_get( 'operation_successful' ) . '<br />'; print_bracket_link( $t_redirect_url, lang_get( 'proceed' ) ); ?> </div> <?php html_page_bottom();
12,272
https://github.com/9e-Docteur/DMUFRBot/blob/master/Events/ready.js
Github Open Source
Open Source
Apache-2.0
null
DMUFRBot
9e-Docteur
JavaScript
Code
18
54
module.exports = async(client) => { client.user.setPresence({ activity: { name: "DMU FR BOT // By 9e_Docteur" } }) };
27,908
https://github.com/grbinho/Resequencer/blob/master/src/IntermediateProcessor/MessageHeader.cs
Github Open Source
Open Source
MIT
2,018
Resequencer
grbinho
C#
Code
32
64
namespace IntermediateProcessor { public class MessageHeader { public string GroupId { get; set; } public int SequenceNumber { get; set; } public bool End { get; set; } = false; } }
48,694
https://github.com/ro-msg-spring-training/online-shop-chbianca/blob/master/shop/src/main/java/ro/msg/learning/shop/services/OrderService.java
Github Open Source
Open Source
MIT
null
online-shop-chbianca
ro-msg-spring-training
Java
Code
7
22
package ro.msg.learning.shop.services; public class OrderService { }
7,165
https://github.com/roymacdonald/ofxCeres/blob/master/Example-MovingHeadAdvanced/src/DMX/Channel.h
Github Open Source
Open Source
MIT
2,022
ofxCeres
roymacdonald
C
Code
70
245
#pragma once #include "Types.h" #include "ofParameter.h" #include "ofxCvGui.h" #include <string> #include <functional> namespace DMX { class Channel { public: Channel(const std::string& name, DMX::Value defaultValue = 0); Channel(); Channel(const std::string& name, const std::function<DMX::Value()> & generateValue); void update(); string getName() const; DMX::Value getValue() const; void setValue(DMX::Value); ofxCvGui::ElementPtr getWidget(); void serialize(nlohmann::json&); void deserialize(const nlohmann::json&); protected: ofParameter<float> value; // We use a float because then we can have a slider function<DMX::Value()> generateValue; }; }
50,616
https://github.com/JBA-Khalifa/slixon.js/blob/master/packages/api-derive/src/types/dex.ts
Github Open Source
Open Source
Apache-2.0
2,022
slixon.js
JBA-Khalifa
TypeScript
Code
12
34
import { Balance } from '@setheum.js/types/interfaces'; export type DerivedDexPool = [Balance, Balance];
36,674
https://github.com/mayyaab/csharp_training/blob/master/addressbook-web-tests/UnitTestProject1/appmanager/ContactHelper.cs
Github Open Source
Open Source
Apache-2.0
null
csharp_training
mayyaab
C#
Code
514
2,611
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; namespace WebAddressbookTests { public class ContactHelper : HelperBase { public ContactHelper(ApplicationMeneger meneger) : base(meneger) { } public ContactHelper Create(ContactData contact) { meneger.Navigator.GoToHomePage(); meneger.Navigator.GoToAddNewContact(); FillContactForm(contact); SubmitAccountCreation(); ReturnToHomePage(); return this; } public ContactHelper Modify(ContactData newDataC) { meneger.Navigator.GoToHomePage(); if (!IsElementPresent(By.Name("selected[]"))) { ContactData contactForMod = new ContactData("For del"); Create(contactForMod); } driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(3); InitContactModification(0); FillContactForm(newDataC); SubmitContactModification(); ReturnToContactPage(); return this; } public ContactHelper Remove(int p) { meneger.Navigator.GoToHomePage(); if (!IsElementPresent(By.Name("selected[]"))) { ContactData contactForMod = new ContactData("For del"); Create(contactForMod); } driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(3); SelectContact(p); Delete(); AcceptAllert(); ReturnToHomePage(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); return this; } public ContactHelper Delete() { driver.FindElement(By.XPath("//input[@value='Delete']")).Click(); contactCache = null; return this; } public ContactHelper ReturnToContactPage() { driver.FindElement(By.LinkText("home page")).Click(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(3); return this; } public ContactHelper ReturnToHomePage() { driver.FindElement(By.XPath("//a[contains(text(),'home')]")).Click(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(3); return this; } public ContactHelper SubmitContactModification() { driver.FindElement(By.Name("update")).Click(); contactCache = null; return this; } public void InitContactModification(int index) { driver.FindElements(By.Name("entry"))[index] .FindElements(By.TagName("td"))[7] .FindElement(By.TagName("a")).Click(); //driver.FindElement(By.XPath("/html[1]/body[1]/div[1]/div[4]/form[2]/table[1]/tbody[1]/tr[2]/td[8]/a[1]")).Click(); //return this; } public void InitContactView(int index) { driver.FindElements(By.Name("entry"))[index] .FindElements(By.TagName("td"))[6] .FindElement(By.TagName("a")).Click(); } public ContactHelper FillContactForm(ContactData contact) { Type(By.Name("firstname"), contact.Firstname); Type(By.Name("middlename"), contact.Middlename); Type(By.Name("lastname"), contact.Lastname); Type(By.Name("nickname"), contact.Nickname); Type(By.Name("title"), contact.Title); Type(By.Name("company"), contact.Company); Type(By.Name("address"), contact.Address); Type(By.Name("home"), contact.Home); Type(By.Name("mobile"), contact.Mobile); Type(By.Name("work"), contact.Work); Type(By.Name("fax"), contact.Fax); Type(By.Name("email"), contact.Email); Type(By.Name("email2"), contact.Email2); Type(By.Name("email2"), contact.Email2); Type(By.Name("email3"), contact.Email3); Type(By.Name("homepage"), contact.Homepage); Select(By.Name("bday"), contact.Bday); Select(By.Name("bmonth"), contact.Bmonth); Type(By.Name("byear"), contact.Byear); Select(By.Name("aday"), contact.Aday); Select(By.Name("amonth"), contact.Amonth); Type(By.Name("ayear"), contact.Ayear); Select(By.Name("new_group"), contact.Newgroup); Type(By.Name("address2"), contact.Address2); Type(By.Name("phone2"), contact.Phone2); Type(By.Name("notes"), contact.Notes); return this; } public ContactHelper SubmitAccountCreation() { driver.FindElement(By.XPath("(//input[@name='submit'])[2]")).Click(); contactCache = null; return this; } public ContactHelper AcceptAllert() { driver.SwitchTo().Alert().Accept(); return this; } public ContactHelper SelectContact(int index) { driver.FindElement(By.XPath("(//input[@name='selected[]'])[" + (index + 1) + "]")).Click(); return this; } private const string NameToFind = "//select[@name='amonth']"; private List<ContactData> contactCache = null; public List<ContactData> GetContactsList() { if (contactCache == null) { contactCache = new List<ContactData>(); meneger.Navigator.GoToHomePage(); ICollection<IWebElement> elements = driver.FindElements(By.XPath("//table//tbody//tr//td[text()][position()=1 or position()=2]")); var arrayElements = elements.AsEnumerable().ToArray(); for (int index = 0; index < arrayElements.Length; index += 2) { var FirstLast = new ContactData(arrayElements[index + 1].Text); FirstLast.Lastname = arrayElements[index].Text; contactCache.Add(FirstLast); } } return new List<ContactData>(contactCache); } public int GetContactCount() { return driver.FindElements(By.XPath("//table//tbody//tr//td[text()][1]")).Count; } public ContactData GetContactInformationFromEditForm(int index) { meneger.Navigator.GoToHomePage(); InitContactModification(0); string firstName = driver.FindElement(By.Name("firstname")).GetAttribute("value"); string middleName = driver.FindElement(By.Name("middlename")).GetAttribute("value"); string lastName = driver.FindElement(By.Name("lastname")).GetAttribute("value"); string address = driver.FindElement(By.Name("address")).GetAttribute("value"); string homePhone = driver.FindElement(By.Name("home")).GetAttribute("value"); string mobilePhone = driver.FindElement(By.Name("mobile")).GetAttribute("value"); string workPhone = driver.FindElement(By.Name("work")).GetAttribute("value"); return new ContactData(firstName) { Lastname = lastName, Middlename = middleName, Address = address, Home = homePhone, Mobile = mobilePhone, Work = workPhone }; } public ContactData GetContactInformationFromTable(int index) { meneger.Navigator.GoToHomePage(); IList<IWebElement> cells = driver.FindElements(By.Name("entry"))[index] .FindElements(By.TagName("td")); string lastName = cells[1].Text; string firstName = cells[2].Text; string address = cells[3].Text; string allEmails = cells[4].Text; string allPhones = cells[5].Text; return new ContactData(firstName) { Lastname = lastName, Address = address, AllPhones = allPhones, AllEmails = allEmails }; } public ContactData GetContactInformationFromViewForm(int index) { meneger.Navigator.GoToHomePage(); InitContactView(0); string fml = driver.FindElement(By.XPath("//*[@id='content']/b")).Text;//done string address = driver.FindElement(By.XPath("//*[@id='content']/text()[4]")).Text; string homePhone = driver.FindElement(By.XPath("//*[@id='content']/text()[6]")).Text; string mobilePhone = driver.FindElement(By.XPath("//*[@id='content']/text()[7]")).Text; string workPhone = driver.FindElement(By.XPath("//*[@id='content']/text()[8]")).Text; return new ContactData() { FML = fml, Address = address, Home = homePhone, Mobile = mobilePhone, Work = workPhone }; } public int GetNumberOfSearchResult() { meneger.Navigator.GoToHomePage(); string text = driver.FindElement(By.TagName("label")).Text; Match m = new Regex(@"\d+").Match(text); return Int32.Parse(m.Value); } } }
25,293
https://github.com/xudeheng/LionSettings/blob/master/src/LSExample/Flipside View/FlipsideViewController.h
Github Open Source
Open Source
MIT
2,018
LionSettings
xudeheng
C
Code
58
167
// // FlipsideViewController.h // LSExample // // Created by Scott Lawrence on 4/2/09. // Copyright __MyCompanyName__ 2009. All rights reserved. // #import <UIKit/UIKit.h> #import "LlamaSettings.h" @interface FlipsideViewController : UIViewController // LLAMASETTINGS 1: Make your class the delegate <LlamaSettingsDelegate> { IBOutlet UITableView * theTableView; // LLAMASETTINGS 2: Add the LlamaSettings object into the class LlamaSettings * ls; } @end
24,220
https://github.com/iCodeIN/typebinder/blob/master/ts_json_subset/src/common.rs
Github Open Source
Open Source
MIT
2,021
typebinder
iCodeIN
Rust
Code
113
348
use displaythis::Display; /// Askama filters pub mod filters { pub fn display_opt<T: std::fmt::Display>(value: &Option<T>) -> askama::Result<String> { match value { Some(val) => Ok(val.to_string()), None => Ok("".to_string()), } } } #[derive(Debug, Clone, PartialEq, Display)] #[display("\"{0}\"")] pub struct StringLiteral(pub String); impl<'a> From<&'a str> for StringLiteral { fn from(input: &str) -> Self { StringLiteral(input.to_string()) } } impl From<String> for StringLiteral { fn from(input: String) -> Self { StringLiteral(input) } } #[derive(Debug, Clone, PartialEq, Display)] #[display("{0}")] pub struct NumericLiteral(pub f64); impl From<f64> for NumericLiteral { fn from(input: f64) -> Self { NumericLiteral(input) } } #[derive(Debug, Clone, PartialEq, Display)] #[display("{0}")] pub struct BooleanLiteral(pub bool); impl From<bool> for BooleanLiteral { fn from(input: bool) -> Self { BooleanLiteral(input) } }
13,660
https://github.com/microsoft/pmod/blob/master/src/foundation_library/FastContainerUtil.h
Github Open Source
Open Source
MIT
2,022
pmod
microsoft
C++
Code
151
505
/*** * Copyright (C) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. * * File:FastContainerUtil.h ****/ #pragma once #include <foundation/pv_util.h> namespace foundation { namespace library { struct _ArrayPropertyValueSlot { UINT32 _size; LPVOID _pArrayBuffer; }; } } //------------------------------------------------------------------------------ // Class: CFastContainerUtil // Fast Container utils //------------------------------------------------------------------------------ class CFastContainerUtil { public: template <class T> static T ReadSlotValue(LPVOID pSlotValue) { T value; memcpy(&value, pSlotValue, sizeof(T)); return value; } template <class T> static void WriteSlotValue(LPVOID pSlotValue,_In_ const T *pValue) { foundation_assert(pValue != nullptr); memcpy(pSlotValue, pValue, sizeof(T)); } template <class T> static HRESULT SetSlotValue(foundation::IInspectable *pValue, LPVOID pSlotValue) { T value; _IFR_(foundation::pv_util::GetValue(pValue, &value)); WriteSlotValue(pSlotValue, &value); return S_OK; } static HRESULT ClearPropertySlot(foundation::PropertyType propertyType, LPVOID pSlotValue); static HRESULT GetPropertyValue( foundation::PropertyType propertyType, LPVOID pSlotValue, foundation::IInspectable **value); static HRESULT SetPropertyValue( foundation::PropertyType propertyType, LPVOID pSlotValue, foundation::IInspectable *value); static size_t GetSlotSize(foundation::PropertyType propertyType); private: static HRESULT ClearPropertySlotInternal(foundation::PropertyType _propertyType, LPVOID pSlotValue); };
8,281
https://github.com/Natalieprojectisizwe/wifi-chat/blob/master/public/scripts/app/models/Post.js
Github Open Source
Open Source
Apache-2.0
2,015
wifi-chat
Natalieprojectisizwe
JavaScript
Code
410
1,618
define(function(require) { 'use strict'; var Backbone = require('backbone') , _ = require('underscore') , log = require('bows.min')('Models:Post') , socket = require('app/utils/socket') return Backbone.Model.extend({ xmppEvents: { 'get': 'xmpp.buddycloud.retrieve', 'post': 'xmpp.buddycloud.publish' }, defaults: { content: null, author: {}, published: null, commentCount: 0 }, embedReceipts: [ { name: 'WiFi TV', regex: /.*connectuptv.pockittv.mobi\/v\/(\w*)/g, substitution: '<div class="post-media post-media--video post-media--wifitv"><video width="320" height="240" poster="https://connectuptv.pockittv.mobi/video/image/$1" controls><source src="$&"></video></div>' }, { name: 'Images', regex: /[a-z\-_0-9\/\:\.]*\.(jpg|jpeg|png|gif|svg)/g, substitution: '<div class="post-media post-media--image"><img src="$&"></img></div>' }, // { // name: 'Youtube', // regex: /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/g, // substitution: '<div class="post-media post-media--video post-media--youtube"><div class="iframe-wrapper"><iframe id="ytplayer" type="text/html" width="320" height="240" src="http://www.youtube.com/embed/$1" frameborder="0"/></div></div>' // } ], initialize: function(post) { if (!post.entry) { /* We probably want the model to * load this for us */ return this.set(post, { silent: true }) } var data = this._mapPost(post) this.set(data, { silent: true }) this.requestCommentCount() }, requestCommentCount: function() { var self = this var options = { node: this.get('node'), id: this.get('localId'), rsm: { max: 1 } } socket.send('xmpp.buddycloud.items.replies', options, function(error, data, rsm) { if (error) { return self.trigger('error', error) } self.set({ commentCount: rsm.count || 0 }) }) }, sync: function(method, collection, options) { if (!method) { method = 'get' } switch (method) { case 'get': return this.getPost() case 'post': case 'create': return this.publish() default: throw new Error('Unhandled method: ' + method) } }, getPost: function() { var event = this.xmppEvents['get'] var self = this var options = { node: this.get('node'), id: this.get('localId') } socket.send(event, options, function(error, post) { if (error) { return self.trigger('error', error) } self.set(self._mapPost(post[0]), { silent: true }) self.trigger('loaded:post') }) }, publish: function() { var payload = { node: this.get('node'), content: { atom: { content: this.get('content') }, 'in-reply-to': { ref: this.get('inReplyTo') } } } var self = this var event = this.xmppEvents['post'] socket.send(event, payload, function(error, success) { if (error) { return self.trigger('publish:error', error) } self.trigger('publish:success') }) }, _mapPost: function(post) { var author = post.entry.atom.author.uri.substr(5) var username = author var usernameParts = author.split('@') if (usernameParts[1] === localStorage.getItem('jid').split('@')[1]) { username = usernameParts[0] } return { displayName: null, username: username, authorJid: author, published: Date.parse(post.entry.atom.published), content: this.parseContent(post.entry.atom.content.content), unparsedContent: post.entry.atom.content.content, node: post.node, channelJid: post.node.split('/')[2], globalId: post.entry.atom.id, localId: post.entry.atom.id.split(',')[2] || post.entry.atom.id, canComment: true, isReply: ('comment' === post.entry.activity), inReplyTo: (post.entry['in-reply-to'] || {}).ref, likes: 1, commentCount: null } }, parseContent: function(content) { content = _.escape(content) .replace(/\{/g, '&#123;') .replace(/&#x2F;/g, '/') .replace(/\}/g, '&#125;') .replace(/\n/g, '<br/>') this.embedReceipts.forEach(function(receipt) { content = content .replace(receipt.regex, receipt.substitution) }, this) return content }, addComment: function() { this.set('commentCount', this.attributes.commentCount + 1) }, removeComment: function() { this.set( 'commentCount', (this.attributes.commentCount > 0) ? this.attributes.commentCount - 1 : 0 ) } }) })
12,514
https://github.com/18F/eca-exchanges-wordpress-site/blob/master/wp-content/themes/The-Standards/archive-programs.php
Github Open Source
Open Source
CC0-1.0
null
eca-exchanges-wordpress-site
18F
PHP
Code
120
357
<?php /** * The template for displaying archive programs * * @link https://developer.wordpress.org/themes/basics/template-hierarchy/ * * @package The_Standards */ get_header(); $args = array( 'post_type' => 'program', 'post_status' => 'publish' ); $programs = new WP_Query( $args ); ?> <section class="usa-grid usa-section"> <?php if ( $programs->have_posts() ) : ?> <?php /* Start the Loop */ while ( $programs->have_posts() ) : $programs->the_post(); /* * Include the Post-Type-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Type name) and that will be used instead. */ get_template_part( 'template-parts/content', get_post_type() ); endwhile; the_posts_navigation(); else : get_template_part( 'template-parts/content', 'none' ); endif; ?> </section><!-- .usa-grid .usa-section --> <?php get_sidebar(); get_footer();
16,470
https://github.com/jamhgit/pesc-transcript-jar/blob/master/pesccoltrn/src/main/java/org/pesc/core/coremain/v1_14/GenderCountType.java
Github Open Source
Open Source
CC0-1.0
2,016
pesc-transcript-jar
jamhgit
Java
Code
297
990
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.02.25 at 04:54:23 PM PST // package org.pesc.core.coremain.v1_14; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for GenderCountType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="GenderCountType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="CountMale" type="{urn:org:pesc:core:CoreMain:v1.14.0}TotalCountType"/> * &lt;element name="CountFemale" type="{urn:org:pesc:core:CoreMain:v1.14.0}TotalCountType"/> * &lt;element name="TotalCountAllGenders" type="{urn:org:pesc:core:CoreMain:v1.14.0}TotalCountType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "GenderCountType", propOrder = { "countMale", "countFemale", "totalCountAllGenders" }) public class GenderCountType { @XmlElement(name = "CountMale") @XmlSchemaType(name = "integer") protected int countMale; @XmlElement(name = "CountFemale") @XmlSchemaType(name = "integer") protected int countFemale; @XmlElement(name = "TotalCountAllGenders") @XmlSchemaType(name = "integer") protected Integer totalCountAllGenders; /** * Gets the value of the countMale property. * */ public int getCountMale() { return countMale; } /** * Sets the value of the countMale property. * */ public void setCountMale(int value) { this.countMale = value; } /** * Gets the value of the countFemale property. * */ public int getCountFemale() { return countFemale; } /** * Sets the value of the countFemale property. * */ public void setCountFemale(int value) { this.countFemale = value; } /** * Gets the value of the totalCountAllGenders property. * * @return * possible object is * {@link Integer } * */ public Integer getTotalCountAllGenders() { return totalCountAllGenders; } /** * Sets the value of the totalCountAllGenders property. * * @param value * allowed object is * {@link Integer } * */ public void setTotalCountAllGenders(Integer value) { this.totalCountAllGenders = value; } }
40,033
https://github.com/viktorMirev/SoftUni-tasks-others/blob/master/specialNummer/specialNummer/Program.cs
Github Open Source
Open Source
MIT
2,017
SoftUni-tasks-others
viktorMirev
C#
Code
110
238
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace specialNummer { class Program { static void Main(string[] args) { int one; int two; int three; int four; int n = int.Parse(Console.ReadLine()); for( int i = 1111; i<=9999; i++) { four = i % 10; three = (i / 10) % 10; two = (i / 100) % 10; one = (i / 1000); if(one!=0 && two!=0 && three!=0 && four != 0) { if (n % four == 0 && n % three == 0 && n % two == 0 && n % one == 0) { Console.Write(i + " "); } } } } } }
11,358
https://github.com/rkuska/gocqlx/blob/master/qb/cmp.go
Github Open Source
Open Source
Apache-2.0
null
gocqlx
rkuska
Go
Code
916
2,533
// Copyright (C) 2017 ScyllaDB // Use of this source code is governed by a ALv2-style // license that can be found in the LICENSE file. package qb import ( "bytes" ) // op specifies Cmd operation type. type op byte const ( eq op = iota lt leq gt geq in cnt cntKey like ) // Cmp if a filtering comparator that is used in WHERE and IF clauses. type Cmp struct { op op column string value value } func (c Cmp) writeCql(cql *bytes.Buffer) (names []string) { cql.WriteString(c.column) switch c.op { case eq: cql.WriteByte('=') case lt: cql.WriteByte('<') case leq: cql.WriteByte('<') cql.WriteByte('=') case gt: cql.WriteByte('>') case geq: cql.WriteByte('>') cql.WriteByte('=') case in: cql.WriteString(" IN ") case cnt: cql.WriteString(" CONTAINS ") case cntKey: cql.WriteString(" CONTAINS KEY ") case like: cql.WriteString(" LIKE ") } return c.value.writeCql(cql) } // Eq produces column=?. func Eq(column string) Cmp { return Cmp{ op: eq, column: column, value: param(column), } } // EqNamed produces column=? with a custom parameter name. func EqNamed(column, name string) Cmp { return Cmp{ op: eq, column: column, value: param(name), } } // EqLit produces column=literal and does not add a parameter to the query. func EqLit(column, literal string) Cmp { return Cmp{ op: eq, column: column, value: lit(literal), } } // EqFunc produces column=someFunc(?...). func EqFunc(column string, fn *Func) Cmp { return Cmp{ op: eq, column: column, value: fn, } } // Lt produces column<?. func Lt(column string) Cmp { return Cmp{ op: lt, column: column, value: param(column), } } // LtNamed produces column<? with a custom parameter name. func LtNamed(column, name string) Cmp { return Cmp{ op: lt, column: column, value: param(name), } } // LtLit produces column<literal and does not add a parameter to the query. func LtLit(column, literal string) Cmp { return Cmp{ op: lt, column: column, value: lit(literal), } } // LtFunc produces column<someFunc(?...). func LtFunc(column string, fn *Func) Cmp { return Cmp{ op: lt, column: column, value: fn, } } // LtOrEq produces column<=?. func LtOrEq(column string) Cmp { return Cmp{ op: leq, column: column, value: param(column), } } // LtOrEqNamed produces column<=? with a custom parameter name. func LtOrEqNamed(column, name string) Cmp { return Cmp{ op: leq, column: column, value: param(name), } } // LtOrEqLit produces column<=literal and does not add a parameter to the query. func LtOrEqLit(column, literal string) Cmp { return Cmp{ op: leq, column: column, value: lit(literal), } } // LtOrEqFunc produces column<=someFunc(?...). func LtOrEqFunc(column string, fn *Func) Cmp { return Cmp{ op: leq, column: column, value: fn, } } // Gt produces column>?. func Gt(column string) Cmp { return Cmp{ op: gt, column: column, value: param(column), } } // GtNamed produces column>? with a custom parameter name. func GtNamed(column, name string) Cmp { return Cmp{ op: gt, column: column, value: param(name), } } // GtLit produces column>literal and does not add a parameter to the query. func GtLit(column, literal string) Cmp { return Cmp{ op: gt, column: column, value: lit(literal), } } // GtFunc produces column>someFunc(?...). func GtFunc(column string, fn *Func) Cmp { return Cmp{ op: gt, column: column, value: fn, } } // GtOrEq produces column>=?. func GtOrEq(column string) Cmp { return Cmp{ op: geq, column: column, value: param(column), } } // GtOrEqNamed produces column>=? with a custom parameter name. func GtOrEqNamed(column, name string) Cmp { return Cmp{ op: geq, column: column, value: param(name), } } // GtOrEqLit produces column>=literal and does not add a parameter to the query. func GtOrEqLit(column, literal string) Cmp { return Cmp{ op: geq, column: column, value: lit(literal), } } // GtOrEqFunc produces column>=someFunc(?...). func GtOrEqFunc(column string, fn *Func) Cmp { return Cmp{ op: geq, column: column, value: fn, } } // In produces column IN ?. func In(column string) Cmp { return Cmp{ op: in, column: column, value: param(column), } } // InNamed produces column IN ? with a custom parameter name. func InNamed(column, name string) Cmp { return Cmp{ op: in, column: column, value: param(name), } } // InLit produces column IN literal and does not add a parameter to the query. func InLit(column, literal string) Cmp { return Cmp{ op: in, column: column, value: lit(literal), } } // Contains produces column CONTAINS ?. func Contains(column string) Cmp { return Cmp{ op: cnt, column: column, value: param(column), } } // ContainsKey produces column CONTAINS KEY ?. func ContainsKey(column string) Cmp { return Cmp{ op: cntKey, column: column, value: param(column), } } // ContainsNamed produces column CONTAINS ? with a custom parameter name. func ContainsNamed(column, name string) Cmp { return Cmp{ op: cnt, column: column, value: param(name), } } // ContainsKeyNamed produces column CONTAINS KEY ? with a custom parameter name. func ContainsKeyNamed(column, name string) Cmp { return Cmp{ op: cntKey, column: column, value: param(name), } } // ContainsLit produces column CONTAINS literal and does not add a parameter to the query. func ContainsLit(column, literal string) Cmp { return Cmp{ op: cnt, column: column, value: lit(literal), } } // Like produces column LIKE ?. func Like(column string) Cmp { return Cmp{ op: like, column: column, value: param(column), } } type cmps []Cmp func (cs cmps) writeCql(cql *bytes.Buffer) (names []string) { for i, c := range cs { names = append(names, c.writeCql(cql)...) if i < len(cs)-1 { cql.WriteString(" AND ") } } cql.WriteByte(' ') return } type where cmps func (w where) writeCql(cql *bytes.Buffer) (names []string) { if len(w) == 0 { return } cql.WriteString("WHERE ") return cmps(w).writeCql(cql) } type _if cmps func (w _if) writeCql(cql *bytes.Buffer) (names []string) { if len(w) == 0 { return } cql.WriteString("IF ") return cmps(w).writeCql(cql) }
7,637
https://github.com/nova-wallet/nova-android-app/blob/master/feature-crowdloan-impl/src/main/java/io/novafoundation/nova/feature_crowdloan_impl/data/network/api/moonbeam/MakeSignature.kt
Github Open Source
Open Source
Apache-2.0
2,022
nova-android-app
nova-wallet
Kotlin
Code
30
130
package io.novafoundation.nova.feature_crowdloan_impl.data.network.api.moonbeam import com.google.gson.annotations.SerializedName import java.util.UUID class MakeSignatureRequest( val address: String, @SerializedName("previous-total-contribution") val previousTotalContribution: String, val contribution: String, val guid: String = UUID.randomUUID().toString(), ) class MakeSignatureResponse( val signature: String, )
8,786
https://github.com/datree-demo/bcserver_demo/blob/master/cosmetic-modules/cosmetic-module-product/src/main/java/com/cyberlink/cosmetic/modules/product/dao/hibernate/RedirectLogDaoHibernate.java
Github Open Source
Open Source
Apache-2.0
2,019
bcserver_demo
datree-demo
Java
Code
17
121
package com.cyberlink.cosmetic.modules.product.dao.hibernate; import com.cyberlink.core.dao.hibernate.AbstractDaoCosmetic; import com.cyberlink.cosmetic.modules.product.dao.RedirectLogDao; import com.cyberlink.cosmetic.modules.product.model.RedirectLog; public class RedirectLogDaoHibernate extends AbstractDaoCosmetic<RedirectLog, Long> implements RedirectLogDao{ }
23,196
https://github.com/scraterpreter/scrape/blob/master/src/NestedBlock/SharpBlock/BinaryComparison/ComparisonE.cc
Github Open Source
Open Source
MIT
2,020
scrape
scraterpreter
C++
Code
17
72
#include <string> #include <stdexcept> #include <algorithm> #include "NestedBlock/SharpBlock/BinaryComparison/ComparisonE.h" #include <memory> bool ComparisonE::getBool() const { return left->getValue()==right->getValue(); }
42,904
https://github.com/AbdulhadiBassam/cp2019v2/blob/master/app/Category.php
Github Open Source
Open Source
MIT
2,019
cp2019v2
AbdulhadiBassam
PHP
Code
36
129
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Category extends Model { use SoftDeletes; public $table = 'categories'; public $primaryKey = 'id'; public $fillable = ['id', 'name','image', 'lang', 'created_at', 'updated_at','deleted_at']; public $dates = ['created_at', 'updated_at','deleted_at']; }
27,821
https://github.com/yourkarma/JWT/blob/master/Sources/JWT/ClaimSet/JWTClaimBase.m
Github Open Source
Open Source
MIT
2,022
JWT
yourkarma
Objective-C
Code
129
380
// // JWTClaimBase.m // JWT // // Created by Dmitry Lobanov on 10.08.2020. // Copyright © 2020 JWTIO. All rights reserved. // #import "JWTClaimBase.h" @interface JWTClaimBase () @property (nonatomic, readwrite) NSObject *value; @property (copy, nonatomic, readwrite) NSString *name; @end @implementation JWTClaimBase @synthesize value = _value; - (instancetype)initWithValue:(NSObject *)value { if (self = [super init]) { self.value = value; } return self; } // MARK: - NSCopying - (nonnull id)copyWithZone:(nullable NSZone *)zone { return [self copyWithValue:self.value]; } // MARK: - JWTClaimProtocol + (NSString *)name { return @""; } - (NSString *)name { return _name ?: self.class.name; } - (instancetype)copyWithValue:(NSObject *)value { typeof(self) result = [[self.class alloc] initWithValue:value]; result.name = self.name; return result; } - (instancetype)copyWithName:(NSString *)name { typeof(self) result = [[self.class alloc] initWithValue:self.value]; result.name = name; return result; } @end
49,212
https://github.com/hdpolover/iys-web/blob/master/application/views/templates/usr/sidebar.php
Github Open Source
Open Source
MIT
null
iys-web
hdpolover
PHP
Code
283
1,157
<div class="col-lg-3"> <!-- Navbar --> <div class="navbar-expand-lg navbar-light"> <div id="sidebarNav" class="collapse navbar-collapse navbar-vertical"> <!-- Card --> <div class="card flex-grow-1 mb-5"> <div class="card-body"> <!-- Avatar --> <div class="d-none d-lg-block text-center mb-5"> <div class="avatar avatar-xxl avatar-circle mb-3"> <?php if($this->session->userdata('photo') == null || $this->session->userdata('photo') == ''){ echo ' <div class="avatar avatar-xxl avatar-circle"> <span class="avatar avatar-lg avatar-primary avatar-circle"> <span class="avatar-initials">'.strtoupper(substr($this->session->userdata('name'), 0, 1)).'</span> </span> </div> '; }else{ echo ' <img class="avatar-img mb-3" src="'.$this->session->userdata('photo').'" style="max-width: 160px;" alt="Image Description"> '; } ?> <!-- <img class="avatar-status avatar-lg-status" src="<?site_url()?>assets/svg/illustrations/top-vendor.svg" alt="Image Description" data-bs-toggle="tooltip" data-bs-placement="top" title="Verified user"> --> </div> <h4 class="card-title mb-0"><?= $this->session->userdata('name')?></h4> <p class="card-text small"><?= $this->session->userdata('email')?></p> </div> <!-- End Avatar --> <!-- Nav --> <!-- List --> <ul class="nav nav-sm nav-tabs nav-vertical mb-4"> <li class="nav-item"> <a class="nav-link <?= $sidebar == "announcement" ? "active" : ""?>" href="<?= site_url('announcement')?>"> <i class="bi-bell nav-icon"></i> Announcements <?php $alertCount = $this->db->get_where('participant_details', ['id_user' => $this->session->userdata('id_user'), 'id_summit' => '1'])->row()->alert_announcement; if($alertCount == '0'){ echo ' <span class="badge bg-soft-secondary text-dark rounded-pill nav-link-badge">0</span> '; }else{ echo ' <span class="badge bg-soft-danger text-danger rounded-pill nav-link-badge">'.$alertCount.'</span> '; } ?> </a> </li> <li class="nav-item"> <a class="nav-link <?= $sidebar == "personal-info" ? "active" : ""?>" href="<?= site_url('personal-info')?>"> <i class="bi-person-badge nav-icon"></i> Personal info </a> </li> <li class="nav-item"> <a class="nav-link <?= $sidebar == "payment" ? "active" : ""?>" href="<?= site_url('payment')?>"> <i class="bi-credit-card nav-icon"></i> Payment </a> </li> <li class="nav-item"> <a class="nav-link <?= $sidebar == "certificate" ? "active" : ""?>" href="#"> <i class="bi-award nav-icon"></i> Certificate </a> </li> </ul> <!-- End List --> <div class="d-lg-none"> <div class="dropdown-divider"></div> <!-- List --> <ul class="nav nav-sm nav-tabs nav-vertical"> <li class="nav-item"> <a class="nav-link" href="#"> <i class="bi-box-arrow-right nav-icon"></i> Log out </a> </li> </ul> <!-- End List --> </div> <!-- End Nav --> </div> </div> <!-- End Card --> </div> </div> <!-- End Navbar --> </div> <!-- End Col -->
38,390