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/francis-pouatcha/forgelab/blob/master/adpharma/adpharma.modules/adpharma.client.frontoffice/src/main/java/org/adorsys/adpharma/client/jpa/articlelot/ModalArticleLotTransferCreateView.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
forgelab
|
francis-pouatcha
|
Java
|
Code
| 264
| 1,558
|
package org.adorsys.adpharma.client.jpa.articlelot;
import java.util.HashSet;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.validation.ConstraintViolation;
import org.adorsys.adpharma.client.jpa.productdetailconfig.ProductDetailConfig;
import org.adorsys.adpharma.client.jpa.warehouse.WareHouse;
import org.adorsys.javaext.format.NumberType;
import org.adorsys.javafx.crud.extensions.ViewModel;
import org.adorsys.javafx.crud.extensions.ViewType;
import org.adorsys.javafx.crud.extensions.control.BigDecimalField;
import org.adorsys.javafx.crud.extensions.locale.Bundle;
import org.adorsys.javafx.crud.extensions.locale.CrudKeys;
import org.adorsys.javafx.crud.extensions.validation.TextInputControlFoccusChangedListener;
import org.adorsys.javafx.crud.extensions.validation.TextInputControlValidator;
import org.adorsys.javafx.crud.extensions.validation.ToOneAggreggationFieldValidator;
import org.adorsys.javafx.crud.extensions.view.ApplicationModal;
import org.adorsys.javafx.crud.extensions.view.LazyViewBuilder;
import org.adorsys.javafx.crud.extensions.view.ViewBuilder;
import de.jensd.fx.fontawesome.AwesomeIcon;
public class ModalArticleLotTransferCreateView extends ApplicationModal{
private AnchorPane rootPane;
private ComboBox<ArticleLot> lotToTransfer;
private ComboBox<WareHouse> wareHouse;
private BigDecimalField qtyToTransfer;
private BigDecimalField lotQty;
private Button saveButton ;
private Button cancelButton ;
@Inject
@Bundle({ CrudKeys.class, ArticleLot.class })
private ResourceBundle resourceBundle;
@Inject
private Locale locale;
@Inject
private TextInputControlValidator textInputControlValidator;
@Inject
private ToOneAggreggationFieldValidator toOneAggreggationFieldValidator;
@PostConstruct
public void postConstruct(){
LazyViewBuilder lvb = new LazyViewBuilder();
lotToTransfer = lvb.addComboBox("ArticleLotTransferManager_lotToTransfer_description.title", "lotToTransfer", resourceBundle);
lotQty =lvb.addBigDecimalField("ArticleLotTransferManager_lotQty_description.title", "lotQty", resourceBundle, NumberType.INTEGER, locale,ViewModel.READ_ONLY);
wareHouse = lvb.addComboBox("ArticleLotTransferManager_wareHouse_description.title", "wareHouse", resourceBundle);
qtyToTransfer =lvb.addBigDecimalField("ArticleLotTransferManager_qtyToTransfer_description.title", "qtyToTransfer", resourceBundle, NumberType.INTEGER, locale);
ViewBuilder viewBuilder = new ViewBuilder();
viewBuilder.addRows(lvb.toRows(),ViewType.CREATE, false);
viewBuilder.addSeparator();
HBox buttonBar = viewBuilder.addButtonBar();
saveButton = viewBuilder.addButton(buttonBar, "Entity_save.title", "saveButton", resourceBundle, AwesomeIcon.SAVE);
cancelButton = viewBuilder.addButton(buttonBar, "Entity_cancel.title", "resetButton", resourceBundle, AwesomeIcon.REFRESH);
rootPane = viewBuilder.toAnchorPane();
}
public void bind(ArticleLotTransferManager model)
{
lotToTransfer.valueProperty().bindBidirectional(model.lotToTransferProperty());
wareHouse.valueProperty().bindBidirectional(model.wareHouseProperty());
qtyToTransfer.numberProperty().bindBidirectional(model.qtyToTransferProperty());
lotQty.numberProperty().bindBidirectional(model.lotQtyProperty());
}
public void addValidators()
{
qtyToTransfer.focusedProperty().addListener(new TextInputControlFoccusChangedListener<ArticleLotTransferManager>(textInputControlValidator, qtyToTransfer, ArticleLotTransferManager.class, "qtyToTransfer", resourceBundle));
// no active validator
// no active validator
}
public Set<ConstraintViolation<ArticleLotTransferManager>> validate(ArticleLotTransferManager model)
{
Set<ConstraintViolation<ArticleLotTransferManager>> violations = new HashSet<ConstraintViolation<ArticleLotTransferManager>>();
violations.addAll(textInputControlValidator.validate(qtyToTransfer, ArticleLotTransferManager.class, "qtyToTransfer", resourceBundle));
violations.addAll(toOneAggreggationFieldValidator.validate(wareHouse, model.getWareHouse(), ArticleLotTransferManager.class, "wareHouse", resourceBundle));
return violations;
}
public AnchorPane getRootPane()
{
return rootPane;
}
public Button getSaveButton()
{
return saveButton;
}
public Button getCancelButton()
{
return cancelButton;
}
public BigDecimalField getQtyToTransfer()
{
return qtyToTransfer;
}
public BigDecimalField getLotQty()
{
return lotQty;
}
public ComboBox<WareHouse> getWareHouse()
{
return wareHouse;
}
public ComboBox<ArticleLot> getLotToTransfer()
{
return lotToTransfer;
}
}
| 6,422
|
https://github.com/chengllNice/monkey-ui/blob/master/src/styles/checkbox.scss
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
monkey-ui
|
chengllNice
|
SCSS
|
Code
| 373
| 1,572
|
@import "./base/var";
@import "./mixins/index.scss";
@mixin checkboxSize($size) {
$font-size: $--font-size-default;
$width: $--checkbox-input-width-default;
$height: $--checkbox-input-height-default;
$after-width: 4px;
$after-height: 8px;
$border-width: 1px;
@if ($size == 'mini') {
$font-size: $--font-size-mini;
$width: $--checkbox-input-width-mini;
$height: $--checkbox-input-height-mini;
$after-width: 3px;
$after-height: 6px;
} @else if ($size == 'small') {
$font-size: $--font-size-small;
$width: $--checkbox-input-width-small;
$height: $--checkbox-input-height-small;
$after-width: 3.5px;
$after-height: 7px;
} @else if ($size == 'large') {
$font-size: $--font-size-large;
$width: $--checkbox-input-width-large;
$height: $--checkbox-input-height-large;
$after-width: 5px;
$after-height: 10px;
}
@include e(label, false) {
font-size: $font-size;
}
@include e(inner, false) {
width: $width;
height: $height;
}
&.is-checked {
@include e(inner, false) {
&::after {
border-width: $border-width;
width: $after-width;
height: $after-height;
}
}
}
&.is-indeterminate {
@include e(inner, false) {
&::after {
border-width: $border-width;
width: #{$width / 2};
height: $border-width;
}
}
}
}
@include c(checkbox) {
color: $--color-text-default;
display: inline-block;
position: relative;
transition: all $--animation-time ease-in-out;
margin-right: 20px;
@include e(input) {
display: inline-block;
vertical-align: middle;
line-height: normal;
font-size: 0;
}
@include e(label) {
//display: inline-block;
margin-left: 5px;
cursor: pointer;
vertical-align: middle;
}
@include e(inner) {
border-radius: $--border-radius-default;
border: $--checkbox-border;
background-color: $--color-white;
display: inline-block;
position: relative;
cursor: pointer;
transition: all $--animation-time ease-in-out;
&:hover {
border-color: $--radio-border-color-hover;
}
&::after {
content: '';
width: 0;
height: 0;
display: block;
transform-origin: top;
transform: rotate(45deg) scale(1) translate(-50%, -50%);
border: 0 solid $--color-white;
position: absolute;
top: 50%;
left: 50%;
}
}
@include when(checked) {
color: $--checkbox-font-color-checked;
@include e(inner, false) {
background-color: $--checkbox-background-color-checked;
border-color: $--checkbox-border-color-checked;
&::after {
border-top: 0;
border-left: 0;
}
}
}
@include when(indeterminate) {
@include e(inner, false) {
background-color: $--checkbox-background-color-checked;
border-color: $--checkbox-border-color-checked;
&::after {
content: '';
position: absolute;
display: block;
background-color: $--color-white;
border: none;
transform: translate(-50%, -50%);
left: 50%;
top: 50%;
}
}
}
@include when(disabled) {
cursor: not-allowed;
color: $--color-text-disabled;
@include e(label, false) {
cursor: not-allowed;
}
@include e(inner, false) {
cursor: not-allowed;
background-color: $--background-color-disabled;
border-color: $--border-color-disabled;
&::after {
cursor: not-allowed;
background: $--background-color-disabled;
}
}
}
&.is-disabled.is-checked {
color: $--color-text-disabled;
@include e(inner, false) {
cursor: not-allowed;
background-color: $--background-color-disabled;
border-color: $--border-color-disabled;
&::after {
border-color: $--color-text-icon;
cursor: not-allowed;
}
}
}
&.is-disabled.is-indeterminate {
color: $--color-text-disabled;
@include e(inner, false) {
background-color: $--background-color-disabled;
border-color: $--border-color-disabled;
cursor: not-allowed;
&::after {
background-color: $--color-text-icon;
cursor: not-allowed;
}
}
}
@include m(mini) {
@include checkboxSize(mini)
}
@include m(small) {
@include checkboxSize(small)
}
@include m(default) {
@include checkboxSize(default)
}
@include m(large) {
@include checkboxSize(large)
}
}
| 38,834
|
https://github.com/ds-modules/EPS-130-SP21/blob/master/HW2/tests/q1.1.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
EPS-130-SP21
|
ds-modules
|
Python
|
Code
| 54
| 210
|
test = { 'name': 'q1.1',
'points': 1,
'suites': [ { 'cases': [ { 'code': '>>> assert abs(P[0] - 0.003819) < .1*0.003819;\n'
'>>> assert abs(P[1] - 0.016803) < .1*0.016803;\n'
'>>> assert abs(P[2] - 0.180881) < .1*0.180881;\n'
'>>> assert abs(P[3] - 0.631248) < .1*0.631248\n',
'hidden': False,
'locked': False}],
'scored': True,
'setup': '',
'teardown': '',
'type': 'doctest'}]}
| 7,228
|
https://github.com/fabianofranz/release/blob/master/clusters/build-clusters/01_cluster/_install/install_cluster.sh
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
release
|
fabianofranz
|
Shell
|
Code
| 159
| 662
|
#!/bin/bash
### prerequisites
### 1. ~/.aws/credentials contains aws_access_key_id and aws_secret_access_key for an IAMUSER under openshift-ci-infra account
set -o errexit
set -o nounset
set -o pipefail
SCRIPT="$0"
readonly SCRIPT
if [[ "$#" -lt 1 ]]; then
>&2 echo "[FATAL] Illegal number of parameters"
>&2 echo "[INFO] usage: $SCRIPT <ocp_version> [path_to_install_config]"
>&2 echo "[INFO] e.g., $SCRIPT 4.3.0"
exit 1
fi
OCP_VERSION="$1"
readonly OCP_VERSION
INSTALL_FOLDER="${HOME}/install_openshift/$(date '+%Y%m%d_%H%M%S')"
readonly INSTALL_FOLDER
mkdir -pv "${INSTALL_FOLDER}"
unameOut="$(uname -s)"
readonly unameOut
case "${unameOut}" in
Linux*) machine=linux;;
Darwin*) machine=mac;;
*) >&2 echo "[FATAL] Unknow OS" and exit 1;;
esac
curl -o "${INSTALL_FOLDER}/openshift-install-${machine}-${OCP_VERSION}.tar.gz" "https://mirror.openshift.com/pub/openshift-v4/x86_64/clients/ocp/${OCP_VERSION}/openshift-install-${machine}-${OCP_VERSION}.tar.gz"
tar xzvf "${INSTALL_FOLDER}"/openshift-install*.tar.gz -C "${INSTALL_FOLDER}"
INSTALLER_BIN="${INSTALL_FOLDER}/openshift-install"
readonly INSTALLER_BIN
INSTALL_CONFIG="${2:-${HOME}/install-config.yaml}"
readonly INSTALL_CONFIG
if [[ ! -f "${INSTALL_CONFIG}" ]]; then
>&2 echo "[FATAL] file not found: install config ${INSTALL_CONFIG} ... specify it with the 2nd arg or copy it to '~/install-config.yaml'"
>&2 echo "[INFO] create by: ${INSTALLER_BIN}/openshift-install create install-config"
exit 1
fi
>&2 echo "[INFO] using install config ${INSTALL_CONFIG}"
cp -v "${INSTALL_CONFIG}" "${INSTALL_FOLDER}"
"${INSTALLER_BIN}" create cluster --dir="${INSTALL_FOLDER}" --log-level=debug
| 33,390
|
https://github.com/code-dot-org/javabuilder/blob/master/org-code-javabuilder/protocol/src/main/java/org/code/protocol/InputAdapter.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
javabuilder
|
code-dot-org
|
Java
|
Code
| 21
| 40
|
package org.code.protocol;
public interface InputAdapter {
/** @return The next user input to the currently running program */
String getNextMessage();
}
| 20,068
|
https://github.com/2kai2kai2/AntiGravMod/blob/master/src/main/java/com/kaikai/antigrav/item/ItemAntiGravSword.java
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
AntiGravMod
|
2kai2kai2
|
Java
|
Code
| 52
| 282
|
package com.kaikai.antigrav.item;
import java.util.concurrent.TimeUnit;
import com.kaikai.antigrav.main.Main;
import com.kaikai.antigrav.main.AntiGravTicks;
import net.minecraft.client.Minecraft;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.util.ResourceLocation;
public class ItemAntiGravSword extends ItemSword {
public ItemAntiGravSword() {
super(Main.toolmaterialantigrav);
this.setRegistryName(new ResourceLocation("antigrav", "antigravsword"));
this.setUnlocalizedName("antigravsword");
this.setCreativeTab(CreativeTabs.COMBAT);
}
public boolean hitEntity(ItemStack stack, EntityLivingBase target, EntityLivingBase attacker) {
new AntiGravTicks(20, target);
return true;
}
}
| 42,915
|
https://github.com/DPS2004/quest/blob/master/GameBrowser/PlayBrowser.xaml.vb
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
quest
|
DPS2004
|
Visual Basic
|
Code
| 396
| 1,441
|
Imports TextAdventures.Utility.Language.L
Public Class PlayBrowser
Private m_recentItems As RecentItems
Private WithEvents m_onlineGames As New OnlineGames
Private m_initialised As Boolean = False
Public Event LaunchGame(filename As String)
Public Event GotUpdateData(data As UpdatesData)
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
m_recentItems = New RecentItems("Recent")
ctlGameList.LaunchCaption = T("LauncherPlay")
ctlOnlineGameList.LaunchCaption = T("LauncherPlay")
ctlOnlineGameList.IsOnlineList = True
Populate()
End Sub
Public Sub AddToRecent(filename As String, name As String)
m_recentItems.AddToRecent(filename, name)
End Sub
Private Sub ctlGameList_Launch(filename As String) Handles ctlGameList.Launch
RaiseEvent LaunchGame(filename)
End Sub
Private Sub ctlGameList_ClearAllItems() Handles ctlGameList.ClearAllItems
m_recentItems.Clear()
Populate()
End Sub
Private Sub ctlGameList_RemoveItem(filename As String) Handles ctlGameList.RemoveItem
m_recentItems.Remove(filename)
End Sub
Private Sub ctlOnlineGameList_Launch(filename As String) Handles ctlOnlineGameList.Launch
RaiseEvent LaunchGame(filename)
End Sub
Public Sub Populate()
m_recentItems.PopulateGameList(ctlGameList)
End Sub
Public Sub MainWindowShown()
m_initialised = True
ctlOnlineGameList.IsDownloading = True
m_onlineGames.StartDownloadGameData()
End Sub
Private Sub m_onlineGames_DataReady() Handles m_onlineGames.DataReady
Dispatcher.BeginInvoke(Sub()
ctlOnlineGameList.IsDownloading = False
PopulateCategories()
End Sub)
End Sub
Private Sub m_onlineGames_DownloadFailed(message As String) Handles m_onlineGames.DownloadFailed
Dispatcher.BeginInvoke(Sub() ctlOnlineGameList.MarkAsFailed(message))
End Sub
Private Sub PopulateCategories()
ctlBrowseFilter.Populate((From cat In m_onlineGames.Categories Select cat.Title).ToArray())
End Sub
Private Sub ctlBrowseFilter_CategoryChanged(category As String) Handles ctlBrowseFilter.CategoryChanged
SetDescriptionVisible(False)
PopulateGames(category)
End Sub
Private Sub PopulateGames(category As String)
m_onlineGames.PopulateGameList(category, ctlOnlineGameList)
End Sub
Private Sub m_onlineGames_GotUpdateData(data As UpdatesData) Handles m_onlineGames.GotUpdateData
RaiseEvent GotUpdateData(data)
End Sub
Private Sub ctlOnlineGameList_ShowGameDescription(data As GameListItemData, control As GameListItem) Handles ctlOnlineGameList.ShowGameDescription
ctlGameDescription.Populate(data, control)
SetDescriptionVisible(True)
End Sub
Private Sub SetDescriptionVisible(visible As Boolean)
Dim gameListVisibility As Windows.Visibility = If(visible, Windows.Visibility.Collapsed, Windows.Visibility.Visible)
Dim descriptionVisibility As Windows.Visibility = If(visible, Windows.Visibility.Visible, Windows.Visibility.Collapsed)
lblRecent.Visibility = gameListVisibility
ctlGameList.Visibility = gameListVisibility
ctlGameDescription.Visibility = descriptionVisibility
End Sub
Private Sub ctlGameDescription_Close() Handles ctlGameDescription.Close
SetDescriptionVisible(False)
ctlOnlineGameList.UnselectCurrentItem()
End Sub
Public Property DownloadFolder As String
Get
Return ctlOnlineGameList.DownloadFolder
End Get
Set(value As String)
ctlOnlineGameList.DownloadFolder = value
Refresh()
End Set
End Property
Private Sub Refresh()
If m_initialised Then
PopulateGames(ctlBrowseFilter.Category)
End If
End Sub
Public Property ShowSandpit As Boolean
Get
Return m_onlineGames.ShowSandpit
End Get
Set(value As Boolean)
m_onlineGames.ShowSandpit = value
RedownloadGameData()
End Set
End Property
Public Property ShowAdult As Boolean
Get
Return m_onlineGames.ShowAdult
End Get
Set(value As Boolean)
m_onlineGames.ShowAdult = value
RedownloadGameData()
End Set
End Property
Private Sub RedownloadGameData()
If m_initialised Then
ctlOnlineGameList.IsDownloading = True
m_onlineGames.StartDownloadGameData()
End If
End Sub
Public Function DownloadingCount() As Integer
Return ctlOnlineGameList.DownloadingCount()
End Function
Public Sub CancelDownloads()
ctlOnlineGameList.CancelDownloads()
End Sub
Private Sub lblGetGames_Initialized(sender As Object, e As EventArgs) Handles lblGetGames.Initialized
lblGetGames.Content = T("LauncherGetGames")
End Sub
Private Sub lblRecent_Initialized(sender As Object, e As EventArgs) Handles lblRecent.Initialized
lblRecent.Content = T("LauncherRecent")
End Sub
End Class
| 6,301
|
https://github.com/Vizzuality/mangrove-atlas/blob/master/src/containers/blog/post/index.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
mangrove-atlas
|
Vizzuality
|
TSX
|
Code
| 109
| 376
|
import Image from 'next/image';
import { usePostTags } from 'hooks/blog';
export const Post = ({
post,
}: {
post: {
id: number;
title: { rendered: string };
yoast_head_json: { og_image: { url: string }[] };
};
}) => {
const { data } = usePostTags({ id: post.id });
return (
<div className="flex items-center">
<Image
alt={post.title.rendered}
className="h-[114px] w-28 rounded-2xl object-cover"
src={post.yoast_head_json.og_image[0].url}
width={112}
height={114}
/>
<div className="flex flex-col space-y-2.5 p-4">
<div className="flex flex-wrap gap-2">
{data?.map((tag, i) => {
return (
<div
key={i}
className="flex w-fit items-center whitespace-nowrap rounded-2xl bg-brand-400 py-1 px-3 text-xs font-semibold uppercase text-white"
>
{tag.name}
</div>
);
})}
</div>
<h5 className="text-left text-2lg font-light">{post.title.rendered}</h5>
</div>
</div>
);
};
export default Post;
| 16,644
|
https://github.com/AndrinPelican/ugd/blob/master/ugd/help_function/util_statistic.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
ugd
|
AndrinPelican
|
Python
|
Code
| 177
| 532
|
'''
Utility functions for statistic:
Graph statistic and evaluation of quartiles.
'''
import numpy as np
from ugd.help_function.util import check_symmetric
def get_quantile(true_val, sim_values):
numb_lower = 0
for value in sim_values:
if value < true_val:
numb_lower += 1
if value == true_val:
numb_lower += 0.5
quant = numb_lower / sim_values.__len__()
return quant
def get_normalized_numb_graphs_same_as_observed(true_val, sim_values):
numb_same = 0
for value in sim_values:
if value == true_val:
numb_same += 1
normalized_numb_graphs_same_as_observed = numb_same / sim_values.__len__()
return normalized_numb_graphs_same_as_observed
def get_default_stat(adj_m):
# reciprocity statistic count number of bidirectional arrows (for directed networks)
def reciprocity(adj_m, var_dict):
return np.trace(adj_m.dot(adj_m)) / 2
# transitivity statistic count number triads for a undirected network
def transitivity(adj_m, var_dict):
return np.trace(adj_m.dot(adj_m.dot(adj_m))) / 3 / 2 # /2 due to both direction of the triad
# decide which one to return:
if check_symmetric(adj_m):
return transitivity
else:
return reciprocity
def crossarrow_count(adj_m, var_dict, test_border):
key, from_value, to_value = test_border
count = 0;
n = adj_m.shape[0]
for i in range(n):
for j in range(n):
if adj_m[i, j] == 1 and var_dict[i][key] == from_value and var_dict[j][key] == to_value:
count += 1
return count
| 39,215
|
https://github.com/xbwen/bugu-mongo/blob/master/bugu-mongo-core/src/main/java/com/bugull/mongo/geo/GeoQuery.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
bugu-mongo
|
xbwen
|
Java
|
Code
| 285
| 875
|
/*
* Copyright (c) www.bugull.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.bugull.mongo.geo;
import com.bugull.mongo.BuguDao;
import com.bugull.mongo.BuguQuery;
import com.bugull.mongo.utils.MapperUtil;
import com.bugull.mongo.utils.Operator;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
/**
* Convenient class for creating geometry queries.
*
* @author Frank Wen(xbwen@hotmail.com)
*/
public class GeoQuery<T> extends BuguQuery<T> {
public GeoQuery(BuguDao<T> dao){
super(dao);
}
public GeoQuery<T> nearSphere(String key, Point point){
DBObject geometry = new BasicDBObject();
geometry.put(Operator.GEOMETRY, MapperUtil.toDBObject(point, true));
append(key, Operator.NEAR_SPHERE, geometry);
return this;
}
/**
*
* @param key
* @param point
* @param maxDistance maximum meters
* @return
*/
public GeoQuery<T> nearSphere(String key, Point point, double maxDistance){
DBObject geometry = new BasicDBObject();
geometry.put(Operator.GEOMETRY, MapperUtil.toDBObject(point, true));
geometry.put(Operator.MAX_DISTANCE, maxDistance);
append(key, Operator.NEAR_SPHERE, geometry);
return this;
}
/**
*
* @param key
* @param point
* @param maxDistance maximum meters
* @param minDistance minimum meters
* @return
*/
public GeoQuery<T> nearSphere(String key, Point point, double maxDistance, double minDistance){
DBObject geometry = new BasicDBObject();
geometry.put(Operator.GEOMETRY, MapperUtil.toDBObject(point, true));
geometry.put(Operator.MAX_DISTANCE, maxDistance);
geometry.put(Operator.MIN_DISTANCE, minDistance);
append(key, Operator.NEAR_SPHERE, geometry);
return this;
}
public GeoQuery<T> geoWithin(String key, GeoJSON geoJson){
DBObject geometry = new BasicDBObject();
geometry.put(Operator.GEOMETRY, MapperUtil.toDBObject(geoJson, true));
append(key, Operator.GEO_WITHIN, geometry);
return this;
}
public GeoQuery<T> geoIntersects(String key, GeoJSON geoJson){
DBObject geometry = new BasicDBObject();
geometry.put(Operator.GEOMETRY, MapperUtil.toDBObject(geoJson, true));
append(key, Operator.GEO_INTERSECTS, geometry);
return this;
}
}
| 9,607
|
https://github.com/thebeline/phroute/blob/master/src/Yaprouter/Route.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
phroute
|
thebeline
|
PHP
|
Code
| 655
| 1,806
|
<?php namespace Yaprouter\Yaprouter;
class Route extends AbstractParsedRouteData {
const EVENTS = 'events';
/**
* Miscellaneous Constants
*/
const PREFIX = 'prefix';
/**
* Constants for common HTTP methods
*/
const ANY = 'ANY';
const GET = 'GET';
const HEAD = 'HEAD';
const POST = 'POST';
const PUT = 'PUT';
const PATCH = 'PATCH';
const DELETE = 'DELETE';
const OPTIONS = 'OPTIONS';
private $httpMethod = '';
private $handler;
private $options = []; // not yet
private $event_handlers = [];
private $isStatic;
protected $routeString;
protected $routeParameters;
protected $routeParts;
public function __construct($httpMethod, $routeString, $handler, array $options = []) {
if (!self::validateHttpMethod($httpMethod))
throw new \Exception("Invalid HTTP Method $httpMethod.");
$this->httpMethod = $httpMethod;
$this->handler = $handler;
$routeData = RouteParser::parseRouteString($routeString);
$this->routeString = $routeData->getRouteString();
$this->routeParameters = $routeData->getRouteParameters();
$this->routeParts = $routeData->getRouteParts();
$this->isStatic = (count($this->routeParts) < 2) && empty($this->routeParts[0][RouteParser::PART_NAME]);
$this->setOptions($options);
}
public function getHandler() {
return $this->handler;
}
public function getEventHandlers($event_name) {
$handlers = isset($this->event_handlers[$event_name]) ? $this->event_handlers[$event_name] : [];
switch ($event_name) {
case '':
// no cases yet
break;
}
return $handlers;
}
public function isStatic() {
return (bool) $this->isStatic;
}
protected function setEventHandlers(array $events) {
foreach ($events as $event_name => $event_handlers) {
foreach ((array) $event_handlers as $handler) {
if (is_array($handler)) {
$priority = (int) (isset($handler[1]) ? $handler[1] : 0);
$this->event_handlers[$event_name][$priority][] = $handler[0];
} else {
$this->event_handlers[$event_name][0][] = $handler;
}
}
}
}
/**
* Set Parameters
*
* Set default Values and if Required
*
* @param mixed[] $parameters
*
* @return void
*
* @access protected
*
* @author Michael Mulligan <mike@belineperspectives.com>
*/
protected function setParameters(array $parameters) {
// not yet implemented
}
protected function setOptions(array $options) {
if (isset($options[self::EVENTS])) {
$this->setEventHandlers($options[self::EVENTS]);
unset($options[self::EVENTS]);
}
}
public function mapMatchedParameters(array $matches) {
$parameters = [];
foreach ($this->routeParameters as $name => $position)
if (isset($matches[$position]))
$parameters[$name] = $matches[$position];
return (array) $parameters;
}
/**
* Filter Request Parameters
*
* Request Parameter sanitation:
* * Decode provided value
* * Loads default values
* * Performs Parameter<>Parameter Maps (no)
* * Checks presence of required parameters
*
* @param mixed[] $parameters Parameters found from RouteUri of the request.
*
* @return mixed[]
*
* @access public
*
* @author Michael Mulligan <mike@belineperspectives.com>
*/
public function applyDefaultParameterValues($parameters) {
foreach ($this->requestParameters as $name => $meta) {
if (!isset($parameters[$name]) && isset($meta['value']))
$parameters[$name] = $meta['value'];
if (empty($parameters[$name]) && !empty($meta['required']))
throw new \InvalidArgumentException("Missing required parameter.");
}
return $parameters;
}
/**
* Filter Route Parameters
*
* Route Parameter sanitation:
* * Loads default values
* * Merges defaults with provided values
* * Performs Parameter<>Parameter Maps // when?
* * Checks presence of required parameters
* * // Should encode // We should pass both of these through the RouteParser
* * The result of this function should be an array of strings
*
* @param mixed[] $parameters Parameters to be a part of the RouteUri format.
*
* @return mixed[]
*
* @access public
*
* @author Michael Mulligan <mike@belineperspectives.com>
*/
public function filterRoutePrameters(array $parameters) {
}
/**
* Map Route Parameter
*
* If the function requires a parameter named 'user', but the
* URI stores it under 'username':
*
* 'username' = $route->mapRouteParameter('user');
*
* @param string $from Parameter name the handler would expect
*
* @return string Parameter name the RouteURI would expect
*
* @access public
*
* @author Michael Mulligan <mike@belineperspectives.com>
*/
public function mapRouteParameter($from) {
return $to;
}
/**
* Map Request Parameter
*
* If the function requires a parameter named 'user', but the
* URI stores it under 'username':
*
* 'user' = $route->mapRequestParameter('username');
*
* @param string $from Parameter name the RouteURI would expect
*
* @return string Parameter name the Handler would expect
*
* @access public
*
* @author Michael Mulligan <mike@belineperspectives.com>
*/
public function mapRequestParameter($from) {
return $to;
}
public static function validateHttpMethod($method) {
return in_array($method, self::httpMethods());
}
/**
* @return array
*/
public static function httpMethods() {
return [
self::ANY,
self::GET,
self::POST,
self::PUT,
self::PATCH,
self::DELETE,
self::HEAD,
self::OPTIONS,
];
}
public static function trim($route) {
return trim($route, '/');
}
}
| 12,959
|
https://github.com/tanaka-takayoshi/csharp-grammar-sample-for-linqpd/blob/master/CSharp CheatSheet/4-2 Switch.linq
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
csharp-grammar-sample-for-linqpd
|
tanaka-takayoshi
|
C#
|
Code
| 66
| 295
|
<Query Kind="Program" />
void Main()
{
var dayOfWeek = DayOfWeek.Thursday;
string text;
switch (dayOfWeek)
{
case DayOfWeek.Monday:
text = "月";
break;
case DayOfWeek.Tuesday:
text = "火";
break;
case DayOfWeek.Wednesday:
text = "水";
break;
case DayOfWeek.Thursday:
text = "木";
break;
case DayOfWeek.Friday:
text = "金";
break;
case DayOfWeek.Saturday:
text = "土";
break;
case DayOfWeek.Sunday:
text = "日";
break;
default:
throw new ArgumentOutOfRangeException();
}
text.Dump();
//なお、日付を表すDateTime型のインスタンスからカレントカルチャの曜日の省略名を得る場合はこのように書ける
$"{DateTime.Now:ddd}".Dump();
}
| 8,028
|
https://github.com/yazhenchua/PlayFab-Samples/blob/master/Samples/Win32/ThunderRumble/Common/StarfieldScreen.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
PlayFab-Samples
|
yazhenchua
|
C++
|
Code
| 304
| 1,075
|
//--------------------------------------------------------------------------------------
// StarfieldScreen.cpp
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "Managers.h"
#include "ScreenManager.h"
#include "StarfieldScreen.h"
#include "Starfield.h"
#include "Game.h"
using namespace ThunderRumble;
using namespace DirectX;
static const float starsParallaxPeriod = 30.0f;
static const float starsParallaxAmplitude = 2048.0f;
StarfieldScreen::StarfieldScreen() : GameScreen(),
m_starfield(nullptr),
m_movement(0.0f)
{
m_transitionPosition = 0.0f;
}
StarfieldScreen::~StarfieldScreen()
{
}
void StarfieldScreen::LoadContent()
{
m_title = Managers::Get<ContentManager>()->LoadTexture(L"Assets\\Textures\\title.png");
m_movement = 0.0f;
SimpleMath::Vector2 starfieldPosition;
starfieldPosition.x = cos(m_movement / starsParallaxPeriod) * starsParallaxAmplitude;
starfieldPosition.y = sin(m_movement / starsParallaxPeriod) * starsParallaxAmplitude;
m_starfield = std::make_unique<Starfield>(starfieldPosition);
Reset();
}
void StarfieldScreen::UnloadContent()
{
if (m_starfield)
{
m_starfield = nullptr;
}
}
void StarfieldScreen::Reset()
{
if (m_starfield)
{
m_movement = 0.0f;
SimpleMath::Vector2 starfieldPosition;
starfieldPosition.x = cos(m_movement / starsParallaxPeriod) * starsParallaxAmplitude;
starfieldPosition.y = sin(m_movement / starsParallaxPeriod) * starsParallaxAmplitude;
m_starfield->Reset(starfieldPosition);
}
}
// Updates the background screen. Unlike most screens, this should not transition off even if it has been covered by another screen: it is
// supposed to be covered, after all! This overload forces the coveredByOtherScreen parameter to false in order to stop the base
// Update method wanting to transition off.
void StarfieldScreen::Update(float totalTime, float elapsedTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
UNREFERENCED_PARAMETER(coveredByOtherScreen);
GameScreen::Update(totalTime, elapsedTime, otherScreenHasFocus, false);
}
void StarfieldScreen::Draw(float totalTime, float elapsedTime)
{
UNREFERENCED_PARAMETER(totalTime);
if (m_starfield)
{
// update the parallax m_movement
m_movement += elapsedTime;
SimpleMath::Vector2 starfieldPosition;
starfieldPosition.x = cos(m_movement / starsParallaxPeriod) * starsParallaxAmplitude;
starfieldPosition.y = sin(m_movement / starsParallaxPeriod) * starsParallaxAmplitude;
// draw the stars
m_starfield->Draw(starfieldPosition);
}
// draw the title texture
if (m_title.Texture)
{
auto renderManager = Managers::Get<RenderManager>();
auto renderContext = renderManager->GetRenderContext(BlendMode::NonPremultiplied);
float viewportWidth = static_cast<float>(TheGame->GetWindowWidth());
float viewportHeight = static_cast<float>(TheGame->GetWindowHeight());
float scale = GetScaleMultiplierForViewport(viewportWidth, viewportHeight);
SimpleMath::Vector2 titlePosition = SimpleMath::Vector2(viewportWidth / 2.0f, (viewportHeight / 2.0f) - (200.f * scale));
titlePosition.y -= pow(TransitionPosition(), 2) * titlePosition.y;
XMVECTORF32 color = { 1.0f, 1.0f, 1.f, TransitionAlpha() };
renderContext->Begin();
renderContext->Draw(m_title, titlePosition, 0, scale, color);
renderContext->End();
}
}
| 47,454
|
https://github.com/AjayGhalay/ticdesign/blob/master/ticDesign/src/main/java/ticwear/design/widget/ViewPropertiesHelper.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
ticdesign
|
AjayGhalay
|
Java
|
Code
| 206
| 474
|
/*
* Copyright (c) 2016 Mobvoi Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ticwear.design.widget;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by tankery on 2/18/16.
*
* Helper to get view properties.
*/
class ViewPropertiesHelper {
static int getAdjustedHeight(View v) {
if (clipToPadding(v)) {
return v.getHeight() - v.getPaddingBottom() - v.getPaddingTop();
} else {
return v.getHeight();
}
}
static int getCenterYPos(View v) {
int padding = clipToPadding(v) ? v.getPaddingTop() : 0;
return v.getTop() + padding + getAdjustedHeight(v) / 2;
}
private static boolean clipToPadding(View v) {
return !(v instanceof ViewGroup) || ((ViewGroup) v).getClipToPadding();
}
static int getTop(View v) {
return clipToPadding(v)? v.getTop() + v.getPaddingTop() : v.getTop();
}
static int getBottom(View v) {
return clipToPadding(v)? v.getBottom() - v.getPaddingBottom() : v.getBottom();
}
}
| 39,107
|
https://github.com/deepcloudlabs/dcl202-2021-mar-01/blob/master/study-primitive-types/src/com/example/StudyChar.java
|
Github Open Source
|
Open Source
|
MIT
| null |
dcl202-2021-mar-01
|
deepcloudlabs
|
Java
|
Code
| 32
| 118
|
package com.example;
public class StudyChar {
public static void main(String[] args) {
char c = 'a'; // 2-Byte, Unicode, Integral Type (unsigned int)
System.out.println("c="+(char)(c+0));
System.out.println("c="+(char)(c+1));
char d = '\u20BA';
System.out.println("d="+d);
}
}
| 8,295
|
https://github.com/microsoft/frontend-appsells/blob/master/src/components/MainPanel.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
frontend-appsells
|
microsoft
|
JavaScript
|
Code
| 146
| 489
|
import React from 'react';
import LedgersWidget from '../ledgers.js-react-widget/LedgersWidget';
import NoEthereumWalletComponent from './NoEthereumWalletComponent';
import ErrorComponent from './ErrorComponent';
import FeatureComponent from './FeatureComponent';
class MainPanel extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div className="ui grid">
<div className="row centered">
<NoEthereumWalletComponent />
</div>
<div className="row centered">
<ErrorComponent />
</div>
<div className="row centered">
<LedgersWidget />
</div>
<div className="row centered" style={{marginTop: "100px"}}>
<div className="four wide column">
<div className="ui center aligned segment basic">
<FeatureComponent which="free"
authLabel="Login to Use"
payLayble=""
useLabel="Use Feature"
subLabel="(access forever)"
showCost={false} />
</div>
</div>
<div className="four wide column">
<div className="ui center aligned segment basic">
<FeatureComponent which="paid"
authLabel="Login to Use"
payLabel="Add Feature"
useLabel="Use Feature"
subLabel="(access forever)"
showCost={true} />
</div>
</div>
<div className="four wide column">
<div className="ui center aligned segment basic">
<FeatureComponent which="subscription"
authLabel="Login to Use"
payLabel="Subscribe Feature"
useLabel="Use Feature"
subLabel="(2 minute access)"
showCost={true} />
</div>
</div>
</div>
</div>
);
}
}
export default MainPanel;
| 18,971
|
https://github.com/runpengl/tesla-node-api/blob/master/src/middlewares/convert-error.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
tesla-node-api
|
runpengl
|
JavaScript
|
Code
| 25
| 66
|
import {newError} from "../errors"
export var convertError = [null,
function error(err) {
if ('status' in err) {
err = newError(err)
}
return Promise.reject(err)
}
]
| 29,434
|
https://github.com/mHealthKenya/ushauri_api/blob/master/models/clinic.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ushauri_api
|
mHealthKenya
|
JavaScript
|
Code
| 48
| 191
|
const sequelize = require("../db_config");
const Sequelize = require("sequelize");
const Clinic = sequelize.sequelize.define(
"tbl_clinic", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: Sequelize.TEXT,
status: Sequelize.TEXT,
created_by: Sequelize.INTEGER,
updated_by: Sequelize.INTEGER,
}, {
timestamps: true,
paranoid: true,
underscored: true,
freezeTableName: true,
tableName: "tbl_clinic"
}
);
exports.Clinic = Clinic;
| 49,054
|
https://github.com/mathijsco/DBTestSetManager/blob/master/src/DatabaseTestSetManager.Lib/DataHandlers/DataValidators/DateTimeOffsetDataValidator.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
DBTestSetManager
|
mathijsco
|
C#
|
Code
| 43
| 122
|
using System;
namespace DatabaseTestSetManager.Lib.DataHandlers.DataValidators
{
public class DateTimeOffsetDataValidator : IDataValidator
{
public bool Validate(string input)
{
DateTimeOffset n;
return input == null || DateTimeOffset.TryParse(input, out n);
}
public object Parse(string input)
{
if (input == null) return null;
return DateTimeOffset.Parse(input);
}
}
}
| 15,933
|
https://github.com/zhangkn/iOS14Header/blob/master/System/Library/PrivateFrameworks/SpotlightServices.framework/SPResultSuggestion.h
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
iOS14Header
|
zhangkn
|
C
|
Code
| 79
| 256
|
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:52:17 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/SpotlightServices.framework/SpotlightServices
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <SearchFoundation/SFSearchSuggestion.h>
@class SFSearchResult;
@interface SPResultSuggestion : SFSearchSuggestion {
SFSearchResult* _originalResult;
}
@property (nonatomic,retain) SFSearchResult * originalResult; //@synthesize originalResult=_originalResult - In the implementation block
-(id)initWithResult:(id)arg1 ;
-(Class)classForKeyedArchiver;
-(id)description;
-(SFSearchResult *)originalResult;
-(void)setOriginalResult:(SFSearchResult *)arg1 ;
@end
| 10,181
|
https://github.com/joseroberto/docker-ejbca/blob/master/dbinit.sh
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
docker-ejbca
|
joseroberto
|
Shell
|
Code
| 90
| 357
|
#!/bin/bash
mkdir -p /etc/ejbca/
if [ ! -f /etc/ejbca/dbinit ]; then
# fix the javax.xml.parsers.FactoryConfigurationError error
echo "Copying /jboss-modules.jar ==> ${JBOSS_HOME}/jboss-modules.jar"
\cp /opt/jboss-modules.jar ${JBOSS_HOME}/jboss-modules.jar
echo "This is the first launch - will init ssl certs, db parameters..."
echo " Will use external database, from specified parameters"
echo "# ------------- Database configuration ------------------------" > $EJBCA_HOME/conf/database.properties
echo "database.name=$DB_NAME" >> $EJBCA_HOME/conf/database.properties
echo "database.url=$DB_URL" >> $EJBCA_HOME/conf/database.properties
echo "database.driver=$DB_DRIVER" >> $EJBCA_HOME/conf/database.properties
echo "database.username=$DB_USER" >> $EJBCA_HOME/conf/database.properties
echo "database.password=$DB_PASSWORD" >> $EJBCA_HOME/conf/database.properties
# create flag file
touch /etc/ejbca/dbinit;
else
echo "DB Already initialized, no need to reinit"
fi
| 1,907
|
https://github.com/FedML-AI/FedML/blob/master/android/app/src/main/java/ai/fedml/ui/adapter/FileItem.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
FedML
|
FedML-AI
|
Java
|
Code
| 25
| 72
|
package ai.fedml.ui.adapter;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class FileItem {
private int fileIcon;
private String fileName;
private String fileSize;
private String fileLastModifiedTime;
}
| 40,586
|
https://github.com/reejit/spotify_download_bot/blob/master/command_hanlders/helpers/spotdl.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
spotify_download_bot
|
reejit
|
Python
|
Code
| 75
| 331
|
import os
import subprocess
from telegram import Update
from telegram.ext import CallbackContext
def create_download_list_from_link(link: str, link_type: str, list_path: str):
subprocess.run(
[
'spotdl',
f'--{link_type}',
link,
"--write-to",
list_path
],
)
def download_from_list(list_path: str, download_path: str):
process = subprocess.Popen(
[
'spotdl',
'--list', list_path,
"-f", download_path,
"--overwrite", "skip"
],
stdout=subprocess.PIPE
)
process.wait()
subprocess.run(['rm', list_path])
def send_songs_from_directory(
directory_path: str,
update: Update,
context: CallbackContext):
directory = os.listdir(directory_path)
for file in directory:
result = context.bot.send_audio(
chat_id=update.effective_chat.id,
audio=open(f'{directory_path}/{file}', 'rb')
)
subprocess.run(['rm', '-r', directory_path])
| 31,895
|
https://github.com/alfazzafashion/image-js/blob/master/node_modules/jsdoc-type-pratt-parser/src/parslets/IntersectionParslet.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
image-js
|
alfazzafashion
|
TypeScript
|
Code
| 59
| 187
|
import { composeParslet } from './Parslet'
import { Precedence } from '../Precedence'
import { assertRootResult } from '../assertTypes'
export const intersectionParslet = composeParslet({
name: 'intersectionParslet',
accept: type => type === '&',
precedence: Precedence.INTERSECTION,
parseInfix: (parser, left) => {
parser.consume('&')
const elements = []
do {
elements.push(parser.parseType(Precedence.INTERSECTION))
} while (parser.consume('&'))
return {
type: 'JsdocTypeIntersection',
elements: [assertRootResult(left), ...elements]
}
}
})
| 8,244
|
https://github.com/CanadianSolar/CASSYS/blob/master/CASSYS Interface/UF_AddModuleOptions.vba
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
CASSYS
|
CanadianSolar
|
Visual Basic
|
Code
| 305
| 760
|
VERSION 5.00
Begin {C62A69F0-16DC-11CE-9E98-00AA00574A4F} UF_AddModuleOptions
Caption = "CASSYS - Add New PV Modules"
ClientHeight = 2055
ClientLeft = 45
ClientTop = 375
ClientWidth = 8310
OleObjectBlob = "UF_AddModuleOptions.frx":0000
StartUpPosition = 1 'CenterOwner
End
Attribute VB_Name = "UF_AddModuleOptions"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Dim numberOfPan As Integer ' Number of PAN files selected by the user
Private Sub DefineNewModuleButton_Click()
Me.Hide
UF_AddPVModule.Show
End Sub
'Since 1.5.2, added batch import of PAN files; this function returns the number of files selected by the user
Public Function getNumberOfPan() As Integer
getNumberOfPan = numberOfPan
End Function
Public Sub ImportPANFileButton_Click()
Dim isImportSuccessful As Integer
Dim FOpen As Variant
Dim dupModuleRepeat As Integer ' Used to remember user choice for duplicate PAN files: 0 = not initialized, 1 = overwrite, 2 = skip
dupModuleRepeat = 0
Dim numberOfOverwritten As Integer
Dim numberOfSkipped As Integer
Dim numberOfAdded As Integer
FOpen = Application.GetOpenFilename(Title:="Please choose a .PAN file to import", FileFilter:="PAN Files(*.PAN),*.PAN;.pan," & "All Files (*.*),*.*", MultiSelect:=True)
numberOfPan = 1
numberOfOverwritten = 0
numberOfSkipped = 0
numberOfAdded = 0
' If user has pressed the Cancel button, exit gracefully
If IsArray(FOpen) = False Then
Unload Me
Exit Sub
End If
While numberOfPan <= UBound(FOpen)
If FOpen(numberOfPan) <> False Then
isImportSuccessful = ParsePANFile(FOpen(numberOfPan), dupModuleRepeat)
numberOfPan = numberOfPan + 1
If isImportSuccessful = -1 Then
numberOfOverwritten = numberOfOverwritten + 1
ElseIf isImportSuccessful = 0 Then
numberOfSkipped = numberOfSkipped + 1
ElseIf isImportSuccessful = 1 Then
numberOfAdded = numberOfAdded + 1
End If
Else
Exit Sub
End If
Wend
' Give feedback to users, how many pv modules are succesfully proceesed
Call MsgBox(numberOfPan - 1 & " Pan files requested for import." & Chr(10) & numberOfOverwritten & " Overwritten" & Chr(10) & numberOfAdded & " Added" & Chr(10) & numberOfSkipped & " Skipped")
Unload Me
End Sub
| 23,131
|
https://github.com/ermshiperete/keyman-developer-online/blob/master/frontend/src/app/model/git-hub-pull-request.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
keyman-developer-online
|
ermshiperete
|
TypeScript
|
Code
| 42
| 118
|
export class GitHubPullRequest {
public keyboardId: string;
public pullRequest: number;
public url: string;
public action: string;
public constructor(
keyboardId: string,
pullRequest: number,
url: string,
action: string,
) {
this.keyboardId = keyboardId;
this.pullRequest = pullRequest;
this.url = url;
this.action = action;
}
}
| 32,936
|
https://github.com/harana-oss/scala-stripe/blob/master/core/jvm/src/main/scala/com/outr/stripe/balance/BalanceEntry.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
scala-stripe
|
harana-oss
|
Scala
|
Code
| 12
| 46
|
package com.outr.stripe.balance
import com.outr.stripe.Money
case class BalanceEntry(currency: String, amount: Money, sourceTypes: SourceType)
| 49,746
|
https://github.com/JBIMat/django-deep-link/blob/master/django_deep_link/urls.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
django-deep-link
|
JBIMat
|
Python
|
Code
| 18
| 65
|
from django.urls import path
from .views import AppDownloadView
app_name = "django-deep-link"
urlpatterns = [
path("<uuid:code>/", AppDownloadView.as_view(), name="deep-link"),
]
| 37,459
|
https://github.com/hellaxe/nylas-ruby/blob/master/lib/nylas/version.rb
|
Github Open Source
|
Open Source
|
MIT
| null |
nylas-ruby
|
hellaxe
|
Ruby
|
Code
| 9
| 31
|
# frozen_string_literal: true
module Nylas
VERSION = "5.1.0"
end
| 45
|
https://github.com/Q-Angelo/SpringBoot-Course/blob/master/chapter8/chapter8-2/src/main/java/com/may/rabbitmq/consumer/message/OrderConsumerMessage.java
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
SpringBoot-Course
|
Q-Angelo
|
Java
|
Code
| 38
| 161
|
package com.may.rabbitmq.consumer.message;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;
@Component
public class OrderConsumerMessage implements ChannelAwareMessageListener {
@Override
public void onMessage(Message message, Channel channel) throws Exception {
String msg = new String(message.getBody());
System.out.println("----------- Message -----------");
System.out.println(msg);
}
}
| 22,316
|
https://github.com/LonghronShen/MMDX/blob/master/MikuMikuDanceCore/Misc/MMDVertex.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
MMDX
|
LonghronShen
|
C#
|
Code
| 143
| 547
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#if XNA
using Microsoft.Xna.Framework;
#elif SlimDX
using SlimDX;
#endif
namespace MikuMikuDance.Core.Misc
{
/// <summary>
/// MMD頂点データ(法線付き)
/// </summary>
public class MMDVertexNm
{
/// <summary>
/// 位置
/// </summary>
public Vector3 Position;
/// <summary>
/// ボーンウェイト
/// </summary>
public Vector2 BlendWeights;
/// <summary>
/// 影響ボーン1
/// </summary>
public int BlendIndexX;
/// <summary>
/// 影響ボーン2
/// </summary>
public int BlendIndexY;
/// <summary>
/// 法線
/// </summary>
public Vector3 Normal;
}
/// <summary>
/// MMD頂点データ(法線、テクスチャ付き)
/// </summary>
public class MMDVertexNmTx : MMDVertexNm
{
/// <summary>
/// テクスチャ座標
/// </summary>
public Vector2 TextureCoordinate;
}
/// <summary>
/// MMD頂点データ(法線、テクスチャ、頂点カラー付き)
/// </summary>
public class MMDVertexNmTxVc : MMDVertexNmTx
{
/// <summary>
/// 頂点カラー
/// </summary>
public Vector4 VertexColor;
}
/// <summary>
/// MMD頂点データ(法線、頂点カラー付き)
/// </summary>
public class MMDVertexNmVc : MMDVertexNm
{
/// <summary>
/// 頂点カラー
/// </summary>
public Vector4 VertexColor;
}
}
| 34,778
|
https://github.com/SenseTW/sensetw/blob/master/sensemap/src/components/SVGIcon/Copy/index.tsx
|
Github Open Source
|
Open Source
|
MIT-0
| 2,021
|
sensetw
|
SenseTW
|
TypeScript
|
Code
| 79
| 323
|
import * as React from 'react';
import SVGIcon, { Props } from '../';
// tslint:disable:max-line-length
class Copy extends React.PureComponent<Props> {
render() {
return (
<SVGIcon {...this.props}>
<title>icon / copy</title>
<g id="icon-/-copy" stroke="none" fill="currentColor" fillRule="evenodd">
<path d="M17,2 L5,2 C3.9,2 3,2.9 3,4 L3,18 L5,18 L5,4 L17,4 L17,2 Z M19.1333333,6 L8.86666667,6 C7.84,6 7,6.8 7,7.77777778 L7,20.2222222 C7,21.2 7.84,22 8.86666667,22 L19.1333333,22 C20.16,22 21,21.2 21,20.2222222 L21,7.77777778 C21,6.8 20.16,6 19.1333333,6 Z M19,20 L9,20 L9,8 L19,8 L19,20 Z" />
</g>
</SVGIcon>
);
}
}
export default Copy;
| 25,509
|
https://github.com/marcelocmedeiros/EstudandoC/blob/master/EstruturaDeRepeticao/Exercicios/Exerc023.c
|
Github Open Source
|
Open Source
|
MIT
| null |
EstudandoC
|
marcelocmedeiros
|
C
|
Code
| 54
| 145
|
#include <stdio.h>
int main(void) {
int num;
printf("Informe uma numero inteiro positivo: \n>");
scanf("%d", &num);
while (num <=0 )
{
printf("Informe uma numero inteiro positivo: \n>");
scanf("%d", &num);
}
for (int i = 1; i <= num; i++)
{
if (num % i == 0)
{
printf("%d-> ", i);
}
}
return 0;
}
| 48,489
|
https://github.com/vinhch/NHibernatePostgre/blob/master/NHibernatePostgre/Repositories/Products/IProductRepository.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
NHibernatePostgre
|
vinhch
|
C#
|
Code
| 13
| 49
|
using NHibernatePostgre.Domains;
namespace NHibernatePostgre.Repositories
{
public interface IProductRepository : IRepository<Product>
{
}
}
| 44,676
|
https://github.com/abdulrehman97/ynz/blob/master/wp-content/plugins/amazon-auto-links/template/preview/template.php
|
Github Open Source
|
Open Source
|
GPL-2.0-only, GPL-2.0-or-later, GPL-1.0-or-later, Apache-2.0, LicenseRef-scancode-unknown-license-reference
| 2,020
|
ynz
|
abdulrehman97
|
PHP
|
Code
| 200
| 560
|
<?php
/*
* Available variables:
*
* $aOptions - the plugin options
* $aProducts - the fetched product links
* $aArguments - the user defined unit arguments such as image size and count etc.
*/
?>
<?php if ( empty( $aProducts ) ) : ?>
<div><p><?php _e( 'No products found.', 'amazon-auto-links' ); ?></p></div>
<?php endif; ?>
<?php if ( isset( $aProducts[ 'Error' ][ 'Message' ], $aProducts[ 'Error' ][ 'Code' ] ) ) : ?>
<div class="error">
<p>
<?php echo $aProducts[ 'Error' ][ 'Code' ] . ': '. $aProducts[ 'Error' ][ 'Message' ]; ?>
</p>
</div>
<?php return; ?>
<?php endif; ?>
<div class="products-container">
<?php foreach( $aProducts as $_aProduct ) : ?>
<div class="product-container">
<h4 class="product-title">
<a href="<?php echo esc_url( $_aProduct[ 'product_url' ] ); ?>" title="<?php echo $_aProduct[ 'text_description' ]; ?>" target="_blank" rel="nofollow">
<?php echo $_aProduct[ 'title' ]; ?>
</a>
</h4>
<div class="product-thumbnail" style="width:<?php echo $aArguments['image_size']; ?>px;">
<a href="<?php echo esc_url( $_aProduct[ 'product_url' ] ); ?>" title="<?php echo $_aProduct['text_description']; ?>" target="_blank" rel="nofollow">
<img src="<?php echo $_aProduct[ 'thumbnail_url' ]; ?>" style="max-width:<?php echo $aArguments['image_size'];?>px;" alt="<?php echo $_aProduct[ 'text_description' ]; ?>" />
</a>
</div>
<div class="product-description">
<?php echo $_aProduct[ 'formatted_rating' ]; ?>
<?php echo $_aProduct[ 'description' ]; ?>
</div>
</div>
<?php endforeach; ?>
</div>
| 9,691
|
https://github.com/jeesd/jeesd-vue/blob/master/src/api/login.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
jeesd-vue
|
jeesd
|
JavaScript
|
Code
| 160
| 516
|
import api from './index'
import { axios } from '@/utils/request'
import qs from 'qs'
/**
* login func
* parameter: {
* username: '',
* password: '',
* remember_me: true,
* captcha: '12345'
* }
* @param parameter
* @returns {*}
*/
export function login (parameter) {
let grant_type = 'password'
let scope = 'auth'
let username = parameter.username
let password = parameter.password
return axios({
url: '/auth/oauth/token',
method: 'post',
data: qs.stringify({"username":username,"password":password,"grant_type":grant_type,"scope":scope}),
headers: {
'Authorization': 'Basic amVlc2Q6ZTEwYWRjMzk0OWJhNTlhYmJlNTZlMDU3ZjIwZjg4M2U=',
'Content-Type' : 'application/x-www-form-urlencoded;charset=utf-8'
}
})
}
export function getSmsCaptcha (parameter) {
return axios({
url: api.SendSms,
method: 'post',
data: parameter
})
}
export function getInfo () {
return axios({
url: '/user/info',
method: 'get',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
})
}
export function logout () {
return axios({
url: '/auth/logout',
method: 'post',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
})
}
/**
* get user 2step code open?
* @param parameter {*}
*/
export function get2step (parameter) {
return axios({
url: api.twoStepCode,
method: 'post',
data: parameter
})
}
| 46,171
|
https://github.com/Usm-Mlk/dealer-buildearth/blob/master/components/services/index.js
|
Github Open Source
|
Open Source
|
MIT
| null |
dealer-buildearth
|
Usm-Mlk
|
JavaScript
|
Code
| 258
| 1,249
|
import React from 'react';
import {CommonContent, CommonFooter, CommonHeader, LatestPost, NavLogo} from "components/commons";
import {Navigation} from "components/home/components";
const ServicesHomePage = () => {
const serviceContent = (
<>
<div className="row mt-5">
<div className="col-md-6">
<div className="marketing">
<img
className="img-fluid marketing-icon"
src="https://buildearth.s3.us-east-2.amazonaws.com/img/services/Marketing+Icon.svg"
alt="Marketing"
/>
<h1 className="marketing-heading">Marketing</h1>
</div>
</div>
<div className="col-md-6 small-screen-marketing">
<div className="marketing">
<img
className="img-fluid marketing-icon"
src="https://buildearth.s3.us-east-2.amazonaws.com/img/services/Real+Estate+Icon.svg"
alt="Marketing"
/>
<h1 className="marketing-heading">Real Estate</h1>
</div>
</div>
</div>
<div className="row mt-5">
<div className="col-md-6">
<div className="marketing">
<img
className="img-fluid marketing-icon"
src="https://buildearth.s3.us-east-2.amazonaws.com/img/services/Construction+Icon.svg"
alt="Marketing"
/>
<h1 className="marketing-heading">Construction</h1>
</div>
</div>
<div className="col-md-6 small-screen-marketing">
<div className="marketing">
<img
className="img-fluid marketing-icon"
src="https://buildearth.s3.us-east-2.amazonaws.com/img/services/Sell+Icon.svg"
alt="Marketing"
/>
<h1 className="marketing-heading">Selling</h1>
</div>
</div>
</div>
<div className="row mt-5">
<div className="col-md-6">
<div className="marketing">
<img
className="img-fluid marketing-icon"
src="https://buildearth.s3.us-east-2.amazonaws.com/img/services/Consultanncy+Icon.svg"
alt="Marketing"
/>
<h1 className="marketing-heading">Consultancy</h1>
</div>
</div>
<div className="col-md-6 small-screen-marketing">
<div className="marketing">
<img
className="img-fluid marketing-icon"
src="https://buildearth.s3.us-east-2.amazonaws.com/img/services/Buying+Icon.svg"
alt="Marketing"
/>
<h1 className="marketing-heading">Buying</h1>
</div>
</div>
</div>
</>
);
return (
<React.Fragment>
<NavLogo className={true} />
<Navigation />
<CommonHeader title="Services" />
<div id="full-page">
<CommonContent
{...{
classes: "what-section",
paragraph: `
A paragraph is a series of related sentences developing a central idea, called the topic.
Try to think about paragraphs in terms of thematic unity: a paragraph is a sentence or a
group of sentences that supports one central, unified idea. Paragraphs add one idea at a
time to your broader argument.
`,
beforeColorText: "What",
colorText: "We",
afterColorText: "Do?",
otherHTMLContent: serviceContent,
}}
/>
<div className="container make-section">
<div className="row">
<div className="col-md-12">
<img
className="img-fluid"
src="https://buildearth.s3.us-east-2.amazonaws.com/img/services/Qoute.svg"
alt="Quote"
/>
<h2 className="make-heading">
We Don't Make
<span className="make-heading-bold">Houses,</span>
We Make
<span className="make-heading-bold">
Homes.
<img
className="img-fluid left-quote"
src="https://buildearth.s3.us-east-2.amazonaws.com/img/services/Mark+Left.svg"
alt="Left quote"
/>
</span>
</h2>
</div>
</div>
</div>
<LatestPost />
<CommonFooter />
</div>
</React.Fragment>
);
};
export default ServicesHomePage;
| 40,957
|
https://github.com/gitter-badger/guard/blob/master/guard-server/src/main/java/com/demkada/guard/server/commons/model/InternalScope.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
guard
|
gitter-badger
|
Java
|
Code
| 126
| 386
|
package com.demkada.guard.server.commons.model;
/*
* Copyright 2019 DEMKADA.
*
* 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.
*
* @author <a href="mailto:kad@demkada.com">Kad D.</a>
*/
public enum InternalScope {
GUARD_READ_CLIENTS,
GUARD_CREATE_CLIENTS,
GUARD_UPDATE_CLIENTS,
GUARD_DELETE_CLIENTS,
GUARD_READ_USERS,
GUARD_CREATE_USERS,
GUARD_UPDATE_USERS,
GUARD_DELETE_USERS,
GUARD_READ_SCOPES,
GUARD_CREATE_SCOPES,
GUARD_UPDATE_SCOPES,
GUARD_CREATE_CONSENTS,
GUARD_READ_CONSENTS,
GUARD_DELETE_CONSENTS,
GUARD_READ_AUDIT_TRAILS,
GUARD_READ_AUTHENTICATION_HISTORY,
GUARD_GENERATE_USER_TOKEN
}
| 370
|
https://github.com/kirubakaranthirumal/crm/blob/master/app/Http/Controllers/old/LoginController_17-5-16_11-37-am.php
|
Github Open Source
|
Open Source
|
MIT
| null |
crm
|
kirubakaranthirumal
|
PHP
|
Code
| 236
| 1,158
|
<?php
namespace App\Http\Controllers;
use Session;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class LoginController extends Controller{
public function index(){
if(!empty(session()->get('userId'))){
header('Location:admin/dashboard');
exit;
}
else{
return view('auth.login');
}
}
public function store(Request $request){
$inputArray = array();
$inputArray = $request->all();
if((!empty($inputArray['email'])) && (!empty($inputArray['password']))){
$results = SELF::LoginPost("http://192.168.1.15:8080/cgwfollowon/crmlogin",$inputArray);
}
$responseArray = array();
if(!empty($results)){
$responseArray = json_decode($results);
}
if((!empty($responseArray->status)) && ($responseArray->status == "200")){
if((!empty($responseArray->userName)) && (!empty($responseArray->userId)) && (!empty($responseArray->email))){
session()->put('userId', $responseArray->userId);
session()->put('userName', $responseArray->userName);
session()->put('email', $responseArray->email);
//print"<pre>";
//print_r(session()->get('email'));
//exit;
header('Location:admin/dashboard');
exit;
}
}
return view('auth.login');
}
public function LoginPost($url,$params){
$json_string = '';
$fields = array(
"email" => $params['email'],
"password" => $params['password']
);
$json_string = json_encode($fields);
$service_url = $url;
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept-Language: en_US')
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_string);
$curl_response = curl_exec($curl);
curl_close($curl);
return $curl_response;
}
public function logout(){
//Session::forget('userId');
//Session::forget('userName');
//Session::forget('email');
//echo session()->get('userId');
//echo session()->get('userName');
//echo session()->get('email');
Session::flush();
echo session()->get('userId');
echo session()->get('userName');
echo session()->get('email');
echo "here";
exit;
header('Location:login_user');
exit;
}
/**
* Show a user edit page
*
* @param $id
*
* @return \Illuminate\View\View
*/
public function edit($id){
$user = User::findOrFail($id);
$roles = Role::lists('title', 'id');
return view('admin.users.edit', compact('user', 'roles'));
}
/**
* Update our user information
*
* @param Request $request
* @param $id
*
* @return \Illuminate\Http\RedirectResponse
*/
public function update(Request $request, $id){
return redirect()->route('users.index')->withMessage(trans('quickadmin::admin.users-controller-successfully_updated'));
}
/**
* Destroy specific user
*
* @param $id
*
* @return \Illuminate\Http\RedirectResponse
*/
public function destroy($id)
{
$user = User::findOrFail($id);
User::destroy($id);
return redirect()->route('users.index')->withMessage(trans('quickadmin::admin.users-controller-successfully_deleted'));
}
}
| 32,889
|
https://github.com/mavanmanen/Mavanmanen.StreamDeckSharp/blob/master/src/Mavanmanen.StreamDeckSharp/PropertyInspector/PropertyInspectorItemBase.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
Mavanmanen.StreamDeckSharp
|
mavanmanen
|
C#
|
Code
| 77
| 178
|
using System;
namespace Mavanmanen.StreamDeckSharp.PropertyInspector
{
public abstract class PropertyInspectorItemBase : Attribute
{
internal string Label { get; }
internal string Type { get; }
internal bool Required { get; }
/// <summary>
///
/// </summary>
/// <param name="label">The label to display in the property inspector</param>
/// <param name="type"></param>
/// <param name="required">If the input is required or not.</param>
protected PropertyInspectorItemBase(string label, string type, bool required)
{
Label = label;
Type = type;
Required = required;
}
}
}
| 10,086
|
https://github.com/gaswelder/ethyl/blob/master/tests/erc20.js
|
Github Open Source
|
Open Source
|
MIT
| null |
ethyl
|
gaswelder
|
JavaScript
|
Code
| 329
| 1,259
|
const { Compiler, Blockchain } = require("../src");
const { assert } = require("chai");
// after(() => process.exit(0));
const ipc = "ipc://./data/geth.ipc";
const rpc = "http://localhost:8545";
const local = Blockchain.at(ipc);
const remote = Blockchain.at(rpc);
describe("ERC20", async function() {
const comp = new Compiler();
let ERC20, god, alice, bob, coin;
before(async () => {
ERC20 = await comp.compile("tests/TokenERC20");
god = await local.user();
alice = await remote.user();
bob = await remote.userFromMnemonic(
"science truck gospel alone trust effort scorpion laundry habit champion magic uncover",
2
);
await god.give(alice, 50000);
coin = await god
.deploy(ERC20, [100, "Testcoin", "TST"])
.then(tr => tr.contract());
});
it("reading basic properties", async function() {
assert.equal((await god.read(coin, "name")).toString(), "Testcoin");
assert.equal((await god.read(coin, "symbol")).toString(), "TST");
});
it("balances", async function() {
assert.equal(
(await god.read(coin, "balanceOf", [god.address()])).toString(),
"100000000000000000000"
);
assert.equal(
(await alice.read(coin, "balanceOf", [alice.address()])).toString(),
"0"
);
assert.equal(
(await god.read(coin, "balanceOf", [alice.address()])).toString(),
"0"
);
});
it("direct transfer", async function() {
const r = await god.call(coin, "transfer", [alice.address(), 1]);
const events = await r.logs();
assert.isNotEmpty(events);
assert.equal(events[0].name(), "Transfer");
const godBalance = () => god.read(coin, "balanceOf", [god.address()]);
const aliceBalance = () => alice.read(coin, "balanceOf", [alice.address()]);
assert.equal((await godBalance()).toString(), "99999999999999999999");
assert.equal((await aliceBalance()).toString(), "1");
await alice
.call(coin, "transfer", [god.address(), 1])
.then(tr => tr.success());
assert.equal((await godBalance()).toString(), "100000000000000000000");
assert.equal((await aliceBalance()).toString(), "0");
});
it("approval", async function() {
const coin = await god
.deploy(ERC20, [100, "Testcoin2", "TS2"])
.then(tr => tr.contract());
await god
.call(coin, "transfer", [alice.address(), 40])
.then(tr => tr.success());
assert.equal(
(await alice.read(coin, "balanceOf", [alice.address()])).toString(),
"40"
);
assert.equal(
(await bob.read(coin, "balanceOf", [bob.address()])).toString(),
"0"
);
it("fail without approval", async function() {
try {
await god
.call(coin, "transferFrom", [alice.address(), bob.address(), 5])
.then(tr => tr.success());
throw "1";
} catch (e) {
if (e == "1") {
throw new Error("transferFrom should have failed");
}
}
});
it("ok with approval", async function() {
await alice
.call(coin, "approve", [god.address(), 6])
.then(tr => tr.success());
assert.equal(
(
await god.read(coin, "allowance", [alice.address(), god.address()])
).toString(),
"6"
);
await god
.call(coin, "transferFrom", [alice.address(), bob.address(), 5])
.then(tr => tr.success());
assert.equal(
(
await god.read(coin, "allowance", [alice.address(), god.address()])
).toString(),
"1"
);
assert.equal(
(await bob.read(coin, "balanceOf", [bob.address()])).toString(),
"5"
);
});
});
});
| 41,820
|
https://github.com/matsumoto4510/AmiTemplate-PHP/blob/master/public/inc/foot.php
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
AmiTemplate-PHP
|
matsumoto4510
|
PHP
|
Code
| 6
| 25
|
<?php include ($inc_path."/inc/tags.php") ?>
</body>
</html>
| 2,890
|
https://github.com/Bnjorogedev/pyspotify-client/blob/master/pyspotify/auth/authorization.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
pyspotify-client
|
Bnjorogedev
|
Python
|
Code
| 12
| 44
|
from collections import namedtuple
Authorization = namedtuple('Authorization',
['access_token', 'token_type', 'expires_in', 'scope', 'refresh_token'])
| 3,673
|
https://github.com/cabbibo/volume/blob/master/app/shaders/marker.vert
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,015
|
volume
|
cabbibo
|
GLSL
|
Code
| 95
| 245
|
#version 330 core
uniform mat4 uModel;
uniform mat4 uViewProjection;
uniform mat4 uModelViewProjection;
uniform mat4 uNormalMatrix;
uniform mat4 uInverseModel;
uniform vec3 uRepelPosition;
in vec3 aPosition;
in vec3 aNormal;
in vec2 aUV;
in vec3 aTangent;
out vec3 vPosition;
out vec3 vNormal;
out vec2 vUV;
void main() {
// Pass some variables to the fragment shader
vec3 pos = vec3(uModel * vec4(aPosition, 1.0));
vPosition = pos;
vUV = aUV;
// If scaled not uniformly,
// this will screw up ( i think ... )
vNormal = vec3(uNormalMatrix * vec4(aNormal, 0.0));
gl_Position = uModelViewProjection * vec4( aPosition, 1.0);
}
| 30,000
|
https://github.com/kibet-gilbert/co1_metaanalysis/blob/master/code/tools/arlequin/arlecore_linux/Rfunctions/haplotypeDistMatrix.r
|
Github Open Source
|
Open Source
|
CC-BY-3.0
| 2,021
|
co1_metaanalysis
|
kibet-gilbert
|
R
|
Code
| 350
| 1,214
|
################################################################################
# haplotypeDistMatrix function - (matrix)
#
# Author: Heidi Lischer
# Date: 10.2008
################################################################################
haplotypeDistMatrix <- function(xmlText, Labels, timeAttr, outfile=outfiles){
# convert string data (half matrix) to a numeric matrix ----------------------
# split string -------
tagData2 <- as.character(xmlText)
tagData3 <- strsplit(tagData2, "\n")
tagMatrix <- as.matrix(as.data.frame(tagData3))
tagMatrix <- subset(tagMatrix, tagMatrix[,1] != "") #trim empty lines
tagMatrix <- gsub(" + ", " ", tagMatrix) # trim white space
Data <- strsplit(tagMatrix, " ")
Row <- length(Data)
# to numeric matrix ----------
Matrix <- as.matrix(as.data.frame(Data[1]))
Matrix <- subset(Matrix, Matrix[,1] != "")
Matrix <- rbind(Matrix, matrix(NA, ncol=1, nrow=(Row-1)))
numericList <- as.numeric(Matrix)
numericMatrix <- t(as.matrix(numericList))
for(n in 2:(Row)){
nextrow <- as.matrix(as.data.frame(Data[n]))
nextrow <- subset(nextrow, nextrow[,1] != "")
nextrow <- rbind(nextrow, matrix(NA, ncol=1, nrow=(Row-n)))
numericList <- as.numeric(nextrow)
numericMatrix <- rbind(numericMatrix, t(as.matrix(numericList)))
}
# graphic---------------------------------------------------------------------
# Mirror matrix (left-right)
mirror.matrix <- function(x) {
xx <- as.data.frame(x);
xx <- rev(xx);
xx <- as.matrix(xx);
xx;
}
# Rotate matrix 270 clockworks
rotate270.matrix <- function(x) {
mirror.matrix(t(x))
}
DistanceMatrix <- rotate270.matrix(numericMatrix)
nCol <- ncol(DistanceMatrix)
nRow <- nrow(DistanceMatrix)
# draw matrix plot---------------
ColorRamp <- colorRampPalette(c("white", "steelblue1", "blue3"))
outfileGraphic <- paste(outfile, "hapDistMatrix ", timeAttr, ".png", sep="")
#save graphic
png(outfileGraphic, width=1300, height=1300, res=144)
smallplot <- c(0.874, 0.9, 0.18, 0.83)
bigplot <- c(0.13, 0.85, 0.14, 0.87)
old.par <- par(no.readonly = TRUE)
#draw legend --------------------------------
par(plt = smallplot)
# get legend values
Min <- min(DistanceMatrix, na.rm=TRUE)
Max <- max(DistanceMatrix, na.rm=TRUE)
binwidth <- (Max - Min) / 64
y <- seq(Min + binwidth/2, Max - binwidth/2, by = binwidth)
z <- matrix(y, nrow = 1, ncol = length(y))
image(1, y, z, col = ColorRamp(64),xlab="", ylab="", axes=FALSE)
# adjust axis if only one value exists
if(Min == Max){
axis(side=4, las = 2, cex.axis=0.8, at=Min, labels=round(Min, 2))
} else {
axis(side=4, las = 2, cex.axis=0.8)
}
box()
mtext(text="Number of pairwise differences", side=4,line=2.2,font=2)
#draw main graphic ------------------------------
par(new = TRUE, plt = bigplot)
image(c(1:nCol), c(1:nRow), DistanceMatrix, col=ColorRamp(64),
main="Haplotype distance matrix", xlab="Haplotype",
ylab="Haplotype", axes=FALSE)
cexAxis <- 0.8
if(nCol > 56) {
cexAxis <- 0.7
}
axis(1, at = c(1:nCol),labels=c(Labels[1:ncol(Labels)]),
cex.axis=cexAxis, las=2)
axis(2, at = c(1:nRow), labels=c(Labels[ncol(Labels):1]),
cex.axis=cexAxis, las=2)
box()
par(old.par) #reset graphic parameters
dev.off()
return(numericMatrix) #return matrix values
}
| 27,372
|
https://github.com/Mu-L/cloudopt-next/blob/master/plugins/cloudopt-next-jooq/src/main/kotlin/net/cloudopt/next/jooq/pool/HikariCPPool.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
cloudopt-next
|
Mu-L
|
Kotlin
|
Code
| 187
| 497
|
/*
* Copyright 2017-2021 Cloudopt
*
* 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
*
* https://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 net.cloudopt.next.jooq.pool
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import net.cloudopt.next.core.ConfigManager
import java.sql.Connection
import java.sql.SQLException
import javax.sql.DataSource
/*
* @author: Cloudopt
* @Time: 2018/2/6
* @Description: Hikaricp helper
*/
class HikariCPPool : ConnectionPool {
private val datasourceConfig: MutableMap<String, Any> = ConfigManager.init("datasource")
private val config = HikariConfig()
init {
config.jdbcUrl = datasourceConfig.get("jdbcUrl") as String
config.username = datasourceConfig.get("username") as String
config.password = datasourceConfig.get("password") as String
config.driverClassName = datasourceConfig.get("driverClassName") as String
datasourceConfig.keys.forEach { key ->
config.addDataSourceProperty(key, datasourceConfig.get(key))
}
}
@Throws(SQLException::class)
override fun getConnection(): Connection {
return getDatasource().connection
}
override fun getDatasource(): DataSource {
return HikariDataSource(config)
}
}
| 3,740
|
https://github.com/cf-container-networking/bosh/blob/master/src/bosh-director/lib/bosh/director/legacy_deployment_helper.rb
|
Github Open Source
|
Open Source
|
LGPL-2.1-only, LicenseRef-scancode-other-permissive, LGPL-2.1-or-later, LGPL-2.0-or-later, LicenseRef-scancode-unicode-mappings, Artistic-2.0, LGPL-3.0-only, LicenseRef-scancode-warranty-disclaimer, GPL-3.0-or-later, GPL-2.0-or-later, GPL-3.0-only, MPL-1.1, Artistic-1.0, GPL-1.0-or-later, MIT, LicenseRef-scancode-public-domain-disclaimer, Artistic-1.0-Perl, BSD-3-Clause, LicenseRef-scancode-unknown-license-reference, GPL-2.0-only, Apache-2.0, Ruby, LicenseRef-scancode-public-domain, BSD-2-Clause
| 2,019
|
bosh
|
cf-container-networking
|
Ruby
|
Code
| 10
| 51
|
module Bosh::Director
module LegacyDeploymentHelper
def ignore_cloud_config?(manifest_hash)
manifest_hash.has_key?('networks')
end
end
end
| 13,481
|
https://github.com/java110/MicroCommunity/blob/master/service-community/src/main/java/com/java110/community/bmo/activitiesType/impl/GetActivitiesTypeBMOImpl.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
MicroCommunity
|
java110
|
Java
|
Code
| 92
| 446
|
package com.java110.community.bmo.activitiesType.impl;
import com.java110.community.bmo.activitiesType.IGetActivitiesTypeBMO;
import com.java110.dto.activitiesType.ActivitiesTypeDto;
import com.java110.intf.community.IActivitiesTypeInnerServiceSMO;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service("getActivitiesTypeBMOImpl")
public class GetActivitiesTypeBMOImpl implements IGetActivitiesTypeBMO {
@Autowired
private IActivitiesTypeInnerServiceSMO activitiesTypeInnerServiceSMOImpl;
/**
* @param activitiesTypeDto
* @return 订单服务能够接受的报文
*/
public ResponseEntity<String> get(ActivitiesTypeDto activitiesTypeDto) {
int count = activitiesTypeInnerServiceSMOImpl.queryActivitiesTypesCount(activitiesTypeDto);
List<ActivitiesTypeDto> activitiesTypeDtos = null;
if (count > 0) {
activitiesTypeDtos = activitiesTypeInnerServiceSMOImpl.queryActivitiesTypes(activitiesTypeDto);
} else {
activitiesTypeDtos = new ArrayList<>();
}
ResultVo resultVo = new ResultVo((int) Math.ceil((double) count / (double) activitiesTypeDto.getRow()), count, activitiesTypeDtos);
ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK);
return responseEntity;
}
}
| 9,306
|
https://github.com/jre233kei/slim/blob/master/src/vm/system_ruleset.cpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
slim
|
jre233kei
|
C++
|
Code
| 705
| 2,786
|
/*
* system_ruleset.cpp - default System Ruleset
*
* Copyright (c) 2008, Ueda Laboratory LMNtal Group
* <lmntal@ueda.info.waseda.ac.jp> All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the Ueda Laboratory LMNtal Group nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $Id: system_ruleset.c,v 1.8 2008/09/29 05:23:40 taisuke Exp $
*/
#include "atomlist.hpp"
#include "functor.h"
#include "lmntal.h"
#include "membrane.hpp"
#include "react_context.hpp"
#include "rule.hpp"
#include "symbol.h"
/* prototypes */
/* delete out proxies connected each other */
static BOOL delete_redundant_outproxies(LmnReactCxtRef rc, LmnMembraneRef mem,
LmnRuleRef rule) {
AtomListEntryRef ent;
LmnSymbolAtomRef o0;
ent = mem->get_atomlist(LMN_OUT_PROXY_FUNCTOR);
if (!ent)
return FALSE;
EACH_ATOM(o0, ent, ({
LmnSymbolAtomRef o1;
if (o0->get_functor() == LMN_RESUME_FUNCTOR)
continue;
if (LMN_ATTR_IS_DATA(o0->get_attr(1)))
return FALSE;
o1 = (LmnSymbolAtomRef)o0->get_link(1);
if (o1->get_functor() == LMN_OUT_PROXY_FUNCTOR) {
LmnSymbolAtomRef i0;
LmnSymbolAtomRef i1;
LmnMembraneRef m0;
LmnMembraneRef m1;
i0 = (LmnSymbolAtomRef)o0->get_link(0);
i1 = (LmnSymbolAtomRef)o1->get_link(0);
m0 = LMN_PROXY_GET_MEM(i0);
m1 = LMN_PROXY_GET_MEM(i1);
if (m0 == m1) {
ent->remove(o0); /* for efficiency */
ent->remove(o1);
lmn_delete_atom(o0);
lmn_delete_atom(o1);
lmn_mem_unify_atom_args(m0, i0, 1, i1, 1);
ent->remove(i0);
ent->remove(i1);
if (rc->has_mode(REACT_MEM_ORIENTED)) {
((MemReactContext *)rc)->memstack_push(m0);
}
return TRUE;
}
}
}));
return FALSE;
}
/* delete in proxies connected each other */
static BOOL delete_redundant_inproxies(LmnReactCxtRef rc, LmnMembraneRef mem,
LmnRuleRef rule) {
AtomListEntryRef ent;
LmnSymbolAtomRef o0;
ent = mem->get_atomlist(LMN_OUT_PROXY_FUNCTOR);
if (!ent)
return FALSE;
EACH_ATOM(o0, ent, ({
LmnSymbolAtomRef i0, i1;
if (o0->get_functor() == LMN_RESUME_FUNCTOR)
continue;
i0 = (LmnSymbolAtomRef)o0->get_link(0);
if (LMN_ATTR_IS_DATA(i0->get_attr(1)))
return FALSE;
i1 = (LmnSymbolAtomRef)i0->get_link(1);
if (i1->get_functor() == LMN_IN_PROXY_FUNCTOR) {
LmnSymbolAtomRef o1 =
(LmnSymbolAtomRef)i1->get_link(0);
ent->remove(o0);
ent->remove(o1);
lmn_delete_atom(o0);
lmn_delete_atom(o1);
lmn_mem_unify_atom_args(mem, o0, 1, o1, 1);
ent->remove(i0);
ent->remove(i1);
return TRUE;
}
}));
return FALSE;
}
static BOOL mem_eq(LmnReactCxtRef rc, LmnMembraneRef mem, LmnRuleRef rule) {
AtomListEntryRef ent;
LmnSymbolAtomRef op;
ent = mem->get_atomlist(LMN_MEM_EQ_FUNCTOR);
if (!ent)
return FALSE;
EACH_ATOM(op, ent, ({
LmnMembraneRef mem0, mem1;
LmnSymbolAtomRef out0, in0, out1, in1, ret, result_atom;
LmnSymbolAtomRef temp0, temp1;
LmnLinkAttr out_attr0, out_attr1, ret_attr;
out_attr0 = op->get_attr(0);
if (LMN_ATTR_IS_DATA(out_attr0))
return FALSE;
out0 = (LmnSymbolAtomRef)op->get_link(0);
if (out0->get_functor() != LMN_OUT_PROXY_FUNCTOR) {
return FALSE;
}
in0 = (LmnSymbolAtomRef)out0->get_link(0);
out_attr1 = op->get_attr(1);
if (LMN_ATTR_IS_DATA(out_attr1)) {
return FALSE;
}
out1 = (LmnSymbolAtomRef)op->get_link(1);
if (out1->get_functor() != LMN_OUT_PROXY_FUNCTOR) {
return FALSE;
}
in1 = (LmnSymbolAtomRef)out1->get_link(0);
mem0 = LMN_PROXY_GET_MEM(in0);
mem1 = LMN_PROXY_GET_MEM(in1);
/* roots of mem0 and mem1, connected to their outside proxies,
are temporarily set to unary atoms with the same functor */
temp0 = lmn_mem_newatom(mem, LMN_TRUE_FUNCTOR);
ret = (LmnSymbolAtomRef)op->get_link(0);
ret_attr = op->get_attr(0);
temp0->set_link(0, ret);
temp0->set_attr(0, ret_attr);
ret->set_link(LMN_ATTR_GET_VALUE(ret_attr), temp0);
ret->set_attr(LMN_ATTR_GET_VALUE(ret_attr), LMN_ATTR_MAKE_LINK(0));
temp1 = lmn_mem_newatom(mem, LMN_TRUE_FUNCTOR);
ret = (LmnSymbolAtomRef)op->get_link(1);
ret_attr = op->get_attr(1);
temp1->set_link(0, ret);
temp1->set_attr(0, ret_attr);
ret->set_link(LMN_ATTR_GET_VALUE(ret_attr), temp1);
ret->set_attr(LMN_ATTR_GET_VALUE(ret_attr), LMN_ATTR_MAKE_LINK(0));
if ((mem0)->equals(mem1)) {
result_atom = lmn_mem_newatom(mem, LMN_TRUE_FUNCTOR);
} else {
result_atom = lmn_mem_newatom(mem, LMN_FALSE_FUNCTOR);
}
lmn_mem_unify_atom_args(mem, temp0, 0, op, 2);
lmn_mem_unify_atom_args(mem, temp1, 0, op, 3);
ret = (LmnSymbolAtomRef)op->get_link(4);
ret_attr = op->get_attr(4);
if (LMN_ATTR_IS_DATA(ret_attr)) {
result_atom->set_link(0, ret);
result_atom->set_attr(0, ret_attr);
} else {
result_atom->set_link(0, ret);
result_atom->set_attr(0, ret_attr);
ret->set_link(LMN_ATTR_GET_VALUE(ret_attr), result_atom);
ret->set_attr(LMN_ATTR_GET_VALUE(ret_attr), LMN_ATTR_MAKE_LINK(0));
}
lmn_mem_delete_atom(mem, op, LMN_ATTR_MAKE_LINK(0));
lmn_mem_delete_atom(mem, temp0, LMN_ATTR_MAKE_LINK(0));
lmn_mem_delete_atom(mem, temp1, LMN_ATTR_MAKE_LINK(0));
return TRUE;
}));
return FALSE;
}
/* -------------------------------------------------------------- */
void init_default_system_ruleset() {
lmn_add_system_rule(new LmnRule(delete_redundant_outproxies, ANONYMOUS));
lmn_add_system_rule(new LmnRule(delete_redundant_inproxies, ANONYMOUS));
lmn_add_system_rule(new LmnRule(mem_eq, ANONYMOUS));
}
| 4,711
|
https://github.com/allenfancy/com.allen.enhance/blob/master/com.allen.enhance.tomcat/src/main/java/org/com/allen/enhance/tomcat/servlet/StaticResourceProcessor.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
com.allen.enhance
|
allenfancy
|
Java
|
Code
| 30
| 88
|
package org.com.allen.enhance.tomcat.servlet;
/**
* @author allen.wu
*/
public class StaticResourceProcessor {
public void process(Request request, Response response) {
try {
response.sendStaticResource();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 13,505
|
https://github.com/LukeBillo/project-votestorm/blob/master/ProjectVotestorm.UnitTests/PollControllerTests/GivenThatPollsCanBeRetrievedAndSeveralPollsExist.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
project-votestorm
|
LukeBillo
|
C#
|
Code
| 120
| 621
|
using System.Linq;
using System.Threading.Tasks;
using Bogus;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using NUnit.Framework;
using ProjectVotestorm.Controllers;
using ProjectVotestorm.Data.Models.Http;
using ProjectVotestorm.Data.Repositories;
using ProjectVotestorm.Data.Utils;
using ProjectVotestorm.UnitTests.Helpers;
namespace ProjectVotestorm.UnitTests.PollControllerTests
{
[TestFixture]
public class GivenThatPollsCanBeRetrievedAndSeveralPollsExist
{
private OkObjectResult _response;
private PollResponse _expectedPollResponse;
[OneTimeSetUp]
public async Task WhenThePollControllerGetMethodIsInvokedWithAnExistingPollId()
{
var mockPollIdGenerator = new Mock<IPollIdGenerator>();
var mockPollRepository = new Mock<IPollRepository>();
var mockPolls = FakerHelpers.PollFaker.Generate(5);
mockPollRepository.Setup(repository => repository.Read(It.IsAny<string>()))
.ReturnsAsync((string id) => mockPolls.FirstOrDefault(poll => poll.Id == id));
var pollController = new PollController(mockPollIdGenerator.Object, mockPollRepository.Object, new NullLogger<PollController>());
_expectedPollResponse = new Faker().PickRandom(mockPolls);
_response = (OkObjectResult) await pollController.GetPoll(_expectedPollResponse.Id);
}
[Test]
public void ThenTheStatusCodeIs200Ok()
{
Assert.That(_response.StatusCode, Is.EqualTo(200));
}
[Test]
public void ThenTheCorrectPollIsReturned()
{
var pollResponse = (PollResponse) _response.Value;
Assert.That(pollResponse.Id, Is.EqualTo(_expectedPollResponse.Id));
Assert.That(pollResponse.Prompt, Is.EqualTo(_expectedPollResponse.Prompt));
Assert.That(pollResponse.PollType, Is.EqualTo(_expectedPollResponse.PollType));
Assert.That(pollResponse.Options, Is.EqualTo(_expectedPollResponse.Options));
Assert.That(pollResponse.IsActive, Is.EqualTo(_expectedPollResponse.IsActive));
Assert.That(pollResponse.AdminIdentity, Is.EqualTo(_expectedPollResponse.AdminIdentity));
}
}
}
| 13,093
|
https://github.com/pavlukha/react-web/blob/master/components/Layout/sidebar.js
|
Github Open Source
|
Open Source
|
MIT
| null |
react-web
|
pavlukha
|
JavaScript
|
Code
| 36
| 107
|
import React from "react";
import Image from "next/image";
const Sidebar = () => (
<div id="sidebar">
<Image src="/img/banner.png" width={300} height={140} />
<div style={{ height: 15 }}></div>
<Image src="/img/banners.png" width={300} height={544} />
</div>
);
export default Sidebar;
| 35,161
|
https://github.com/bovisp/training-tracker/blob/master/resources/assets/js/components/notifications/types/LogbookEntryAdded.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
training-tracker
|
bovisp
|
Vue
|
Code
| 59
| 229
|
<template>
<div>
<p>{{ notification.data.creatorName }} added a <a @click.prevent="$emit('view')">logbook entry</a> to {{ isOwner }} lesson package <a :href="`${urlBase}/users/${notification.data.userlessonUserId}/userlessons/${notification.data.userlessonId}`">"{{ notification.data.userlessonName }}"</a> under the objective "{{ notification.data.objectiveName }}"</p>
</div>
</template>
<script>
export default {
props: {
notification: {
required: true,
type: Object
}
},
computed: {
isOwner () {
return this.notification.data.creatorId === this.notification.data.userlessonUserId ? 'their' : `${this.notification.data.creatorName}'s`
}
}
}
</script>
| 40,789
|
https://github.com/juanpicado/remirror/blob/master/packages/@remirror/preset-list/src/list-item-extension.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
remirror
|
juanpicado
|
TypeScript
|
Code
| 88
| 302
|
import {
ApplySchemaAttributes,
convertCommand,
extensionDecorator,
KeyBindings,
NodeExtension,
NodeExtensionSpec,
} from '@remirror/core';
import { liftListItem, sinkListItem, splitListItem } from '@remirror/pm/schema-list';
/**
* Creates the node for a list item.
*/
@extensionDecorator({})
export class ListItemExtension extends NodeExtension {
get name() {
return 'listItem' as const;
}
createNodeSpec(extra: ApplySchemaAttributes): NodeExtensionSpec {
return {
attrs: extra.defaults(),
content: 'paragraph block*',
defining: true,
draggable: false,
parseDOM: [{ tag: 'li', getAttrs: extra.parse }],
toDOM: (node) => ['li', extra.dom(node), 0],
};
}
createKeymap(): KeyBindings {
return {
Enter: convertCommand(splitListItem(this.type)),
Tab: convertCommand(sinkListItem(this.type)),
'Shift-Tab': convertCommand(liftListItem(this.type)),
};
}
}
| 18,498
|
https://github.com/rosiecowling/specialist-publisher/blob/master/app/models/service_standard_report.rb
|
Github Open Source
|
Open Source
|
MIT
| null |
specialist-publisher
|
rosiecowling
|
Ruby
|
Code
| 34
| 175
|
class ServiceStandardReport < Document
FORMAT_SPECIFIC_FIELDS = %i(
assessment_date
result
stage
).freeze
attr_accessor(*FORMAT_SPECIFIC_FIELDS)
def initialize(params = {})
super(params, FORMAT_SPECIFIC_FIELDS)
end
def taxons
[DIGITAL_SERVICE_STANDARD_TAXON_ID]
end
def self.title
"Service Standard Report"
end
def primary_publishing_organisation
"af07d5a5-df63-4ddc-9383-6a666845ebe9"
end
end
| 24,053
|
https://github.com/palaxi00/palaxi00.github.io/blob/master/Codeeval/nice_angles.py
|
Github Open Source
|
Open Source
|
MIT
| null |
palaxi00.github.io
|
palaxi00
|
Python
|
Code
| 21
| 96
|
import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
mins,secs = divmod(float(test)*3600,60)
degr,mins = divmod(mins,60)
print ("%d.%02d'%02d\"" % (degr,mins,secs))
| 46,413
|
https://github.com/Daramkun/ProjectLiqueur/blob/master/Daramkun.Liqueur.Core/Graphics/IVertexBuffer.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
ProjectLiqueur
|
Daramkun
|
C#
|
Code
| 96
| 235
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Daramkun.Liqueur.Graphics
{
[Flags]
public enum FlexibleVertexFormat
{
PositionXY = 1 << 0,
PositionXYZ = 1 << 1,
Diffuse = 1 << 2,
Normal = 1 << 3,
TextureUV1 = 1 << 4,
TextureUV2 = 1 << 5,
TextureUV3 = 1 << 6,
TextureUV4 = 1 << 7,
}
public interface IVertexBuffer<T> : IDisposable where T : struct
{
int Length { get; }
int TotalBytesize { get; }
object Handle { get; }
FlexibleVertexFormat FVF { get; }
T [] Vertices { get; set; }
}
}
| 9,879
|
https://github.com/Jimbly/timezone-mock/blob/master/tests/test-vs-local.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
timezone-mock
|
Jimbly
|
JavaScript
|
Code
| 369
| 1,163
|
var assert = require('assert');
var timezone_mock = require('../');
//////////////////////////////////////////////////////////////////////////
// Test that the mocked date behaves exactly the same as the system date when
// mocking the same timezone.
// JE: 2017-05-26, Node 6.9.1: This test seems to fail when specifying non-
// existent dates (undefined behavior anyway), not sure if this was working
// before or not.
if (!new timezone_mock._Date().toString().match(/\(PDT\)|\(PST\)|\(Pacific Daylight Time\)|\(Pacific Standard Time\)/)) {
// Because we only have timezone info for a couple timezones, we can only test
// this if the timezone we're mocking is the same as the system timezone.
// In theory this could be extended to be able to test any timezone for which
// we have timezone data.
assert.ok(false, 'These tests only work if the local system timezone is Pacific');
}
timezone_mock.register('US/Pacific');
// function test(d) {
// var ret = [];
// ret.push(d.getTimezoneOffset());
// ret.push(d.getHours());
// d.setTime(new Date('2015-03-08T02:30:11.000Z').getTime());
// ret.push(d.getTimezoneOffset());
// ret.push(d.getHours());
// d.setTime(new Date('2015-03-07T02:30:11.000Z').getTime());
// ret.push(d.getTimezoneOffset());
// ret.push(d.getHours());
// d.setTime(new Date('2015-03-09T02:30:11.000Z').getTime());
// ret.push(d.getTimezoneOffset());
// ret.push(d.getHours());
// return ret;
// }
var orig = new timezone_mock._Date();
var mock = new Date();
function pad2(v) {
return ('0' + v).slice(-2);
}
var ts = new Date('2013-01-01T00:00:00.000Z').getTime();
var was_ok = true;
var last = ts;
var end = ts + 5*365*24*60*60*1000;
var ok;
function check(label) {
function check2(fn) {
if (orig[fn]() !== mock[fn]()) {
ok = false;
if (was_ok) {
console.log(' ' + fn + ' (' + label + ')', orig[fn](), mock[fn]());
}
}
}
check2('getTimezoneOffset');
check2('getHours');
check2('getTime');
}
for (; ts < end; ts += 13*60*1000) {
orig.setTime(ts);
mock.setTime(ts);
assert.equal(orig.toISOString(), mock.toISOString());
ok = true;
check('setTime');
var test = new timezone_mock._Date(ts);
orig = new timezone_mock._Date('2015-01-01');
mock = new Date('2015-01-01');
orig.setFullYear(test.getUTCFullYear());
mock.setFullYear(test.getUTCFullYear());
orig.setMinutes(test.getUTCMinutes());
mock.setMinutes(test.getUTCMinutes());
orig.setHours(test.getUTCHours());
mock.setHours(test.getUTCHours());
check('setFullYear/Minutes/Hours');
orig.setDate(test.getUTCDate());
mock.setDate(test.getUTCDate());
check('setDate');
var str = test.getUTCFullYear() + '-' + pad2(test.getUTCMonth() + 1) + '-' + pad2(test.getUTCDate()) + ' ' +
pad2(test.getUTCHours()) + ':' + pad2(test.getUTCMinutes()) + ':' + pad2(test.getUTCSeconds());
orig = new timezone_mock._Date(str);
mock = new Date(str);
check('constructor ' + str);
if (was_ok !== ok) {
console.log((ok ? 'OK ' : 'NOT OK') + ' - ' + ts + ' (' + (ts - last) + ') ' + orig.toISOString() +
' (' + orig.toLocaleString() + ')');
last = ts;
was_ok = ok;
}
}
| 42,954
|
https://github.com/alex-vincent/runelite/blob/master/runescape-client/src/main/java/Bounds.java
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| null |
runelite
|
alex-vincent
|
Java
|
Code
| 291
| 1,247
|
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("lb")
@Implements("Bounds")
public class Bounds {
@ObfuscatedName("t")
@ObfuscatedGetter(
intValue = -1245223283
)
public int field3941;
@ObfuscatedName("q")
@ObfuscatedGetter(
intValue = -1231090535
)
public int field3942;
@ObfuscatedName("i")
@ObfuscatedGetter(
intValue = 850119981
)
public int field3943;
@ObfuscatedName("a")
@ObfuscatedGetter(
intValue = 1784600163
)
public int field3944;
public Bounds(int var1, int var2, int var3, int var4) {
this.method5680(var1, var2);
this.method5671(var3, var4);
}
public Bounds(int var1, int var2) {
this(0, 0, var1, var2);
}
@ObfuscatedName("t")
@ObfuscatedSignature(
signature = "(III)V",
garbageValue = "-1347027473"
)
public void method5680(int var1, int var2) {
this.field3941 = var1;
this.field3942 = var2;
}
@ObfuscatedName("q")
@ObfuscatedSignature(
signature = "(III)V",
garbageValue = "1026297832"
)
public void method5671(int var1, int var2) {
this.field3943 = var1;
this.field3944 = var2;
}
@ObfuscatedName("i")
@ObfuscatedSignature(
signature = "(Llb;Llb;I)V",
garbageValue = "1818261206"
)
public void method5667(Bounds var1, Bounds var2) {
this.method5666(var1, var2);
this.method5664(var1, var2);
}
@ObfuscatedName("a")
@ObfuscatedSignature(
signature = "(Llb;Llb;B)V",
garbageValue = "53"
)
void method5666(Bounds var1, Bounds var2) {
var2.field3941 = this.field3941;
var2.field3943 = this.field3943;
if(this.field3941 < var1.field3941) {
var2.field3943 -= var1.field3941 - this.field3941;
var2.field3941 = var1.field3941;
}
if(var2.method5668() > var1.method5668()) {
var2.field3943 -= var2.method5668() - var1.method5668();
}
if(var2.field3943 < 0) {
var2.field3943 = 0;
}
}
@ObfuscatedName("l")
@ObfuscatedSignature(
signature = "(Llb;Llb;I)V",
garbageValue = "1703752617"
)
void method5664(Bounds var1, Bounds var2) {
var2.field3942 = this.field3942;
var2.field3944 = this.field3944;
if(this.field3942 < var1.field3942) {
var2.field3944 -= var1.field3942 - this.field3942;
var2.field3942 = var1.field3942;
}
if(var2.method5669() > var1.method5669()) {
var2.field3944 -= var2.method5669() - var1.method5669();
}
if(var2.field3944 < 0) {
var2.field3944 = 0;
}
}
@ObfuscatedName("b")
@ObfuscatedSignature(
signature = "(B)I",
garbageValue = "97"
)
int method5668() {
return this.field3941 + this.field3943;
}
@ObfuscatedName("e")
@ObfuscatedSignature(
signature = "(S)I",
garbageValue = "2048"
)
int method5669() {
return this.field3942 + this.field3944;
}
public String toString() {
return null;
}
}
| 31,683
|
https://github.com/fremontmj/Blot/blob/master/app/clients/index.js
|
Github Open Source
|
Open Source
|
CC0-1.0
| 2,022
|
Blot
|
fremontmj
|
JavaScript
|
Code
| 160
| 414
|
var client;
var config = require("config");
var ensure = require("helper/ensure");
// Register new clients here
var clients = {
git: require("./git"),
};
// If we have specified the required
// configuration to run the Dropbox app
if (
config.dropbox.app.key &&
config.dropbox.app.secret &&
config.dropbox.full.key &&
config.dropbox.full.secret
) {
clients.dropbox = require("./dropbox");
}
// If we have the require creds to run
// the google drive app
if (config.google.drive.key && config.google.drive.secret) {
clients['google-drive'] = require("./google-drive");
}
// Demo local client
if (config.environment === "development") {
clients.local = require("./local");
}
// Verify that each client has the correct
// signature before exposing them to Blot.
for (var i in clients) {
client = clients[i];
// Required properties
ensure(client.display_name, "string");
ensure(client.description, "string");
ensure(client.disconnect, "function");
ensure(client.remove, "function");
ensure(client.write, "function");
if (client.site_routes) ensure(client.site_routes, "function");
if (client.dashboard_routes) ensure(client.dashboard_routes, "function");
// This is used as an identifier in the DB
// e.g. a blog's client will be set to this value
client.name = i;
}
module.exports = clients;
| 28,041
|
https://github.com/cakebin/smush/blob/master/server/routes/api_user.go
|
Github Open Source
|
Open Source
|
MIT
| null |
smush
|
cakebin
|
Go
|
Code
| 660
| 2,205
|
package routes
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/cakebin/smush/server/services/db"
)
/*---------------------------------
Response Data
----------------------------------*/
type UserGetAllResponseData struct {
Users []*db.User `json:"users"`
}
// UserGetResponseData is the data we send back
// after a successfully getting all user's info
type UserGetResponseData struct {
User *db.UserProfileView `json:"user"`
UserCharacters []*db.UserCharacterView `json:"userCharacters"`
}
// UserUpdateResponseData is the data we send
// back after a successfully creating a new user
type UserUpdateResponseData struct {
User *db.UserProfileView `json:"user"`
UserCharacters []*db.UserCharacterView `json:"userCharacters"`
}
// UserUpdateDefaultUserCharacterResponseData is the data we send back
// after successfully updating a user's default user character
type UserUpdateDefaultUserCharacterResponseData struct {
User *db.UserProfileView `json:"user"`
UserCharacters []*db.UserCharacterView `json:"userCharacters"`
}
/*---------------------------------
Router
----------------------------------*/
// UserRouter is responsible for serving "/api/user"
// Basically, connecting to our Postgres DB for all
// of the CRUD operations for our "User" models
type UserRouter struct {
Services *Services
UserCharacterRouter *UserCharacterRouter
}
func (r *UserRouter) ServeHTTP(res http.ResponseWriter, req *http.Request) {
var head string
head, req.URL.Path = ShiftPath(req.URL.Path)
// Delegate to sub routers first
switch head {
case "character":
r.UserCharacterRouter.ServeHTTP(res, req)
// Otherwise, handle the user specific requests
default:
switch req.Method {
// GET Request Handlers
case http.MethodGet:
switch head {
case "get":
r.handleGetByID(res, req)
case "getall":
r.handleGetAll(res, req)
default:
http.Error(res, fmt.Sprintf("Unsupported GET path %s", head), http.StatusBadRequest)
return
}
// POST Request Handlers
case http.MethodPost:
switch head {
case "update_profile":
r.handleUpdateProfile(res, req)
case "update_default_user_character":
r.handleUpdateDefaultUserCharacter(res, req)
default:
http.Error(res, fmt.Sprintf("Unsupport POST path %s", head), http.StatusBadRequest)
return
}
// Unsupported Method Response
default:
http.Error(res, fmt.Sprintf("Unsupported Method type %s", req.Method), http.StatusBadRequest)
}
}
}
// NewUserRouter makes a new api/user router and hooks up its services
func NewUserRouter(routerServices *Services) *UserRouter {
router := new(UserRouter)
router.Services = routerServices
router.UserCharacterRouter = NewUserCharacterRouter(routerServices)
return router
}
/*---------------------------------
Handlers
----------------------------------*/
func (r *UserRouter) handleGetByID(res http.ResponseWriter, req *http.Request) {
var head string
head, req.URL.Path = ShiftPath(req.URL.Path)
userID, err := strconv.ParseInt(head, 10, 64)
if err != nil {
http.Error(res, fmt.Sprintf("Invalid user id: %s", head), http.StatusBadRequest)
return
}
// Get the basic user profile information
userProfileView, err := r.Services.Database.GetUserProfileViewByUserID(userID)
if err != nil {
http.Error(res, fmt.Sprintf("Error getting user with userID %d: %s", userID, err.Error()), http.StatusInternalServerError)
return
}
// Also get the user's saved characters
userCharViews, err := r.Services.Database.GetUserCharacterViewsByUserID(userID)
if err != nil {
http.Error(res, fmt.Sprintf("Error getting user's saved characters with userID %d: %s", userID, err.Error()), http.StatusInternalServerError)
return
}
response := &Response{
Success: true,
Error: nil,
Data: UserGetResponseData{
User: userProfileView,
UserCharacters: userCharViews,
},
}
res.Header().Set("Content-Type", "application/json")
json.NewEncoder(res).Encode(response)
}
func (r *UserRouter) handleGetAll(res http.ResponseWriter, req *http.Request) {
users, err := r.Services.Database.GetAllUsers()
if err != nil {
http.Error(res, fmt.Sprintf("Error getting all users: %s", err.Error()), http.StatusInternalServerError)
return
}
response := &Response{
Success: true,
Error: nil,
Data: UserGetAllResponseData{
Users: users,
},
}
res.Header().Set("Content-Type", "application/json")
json.NewEncoder(res).Encode(response)
}
func (r *UserRouter) handleUpdateProfile(res http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
userProfileUpdate := new(db.UserProfileUpdate)
err := decoder.Decode(userProfileUpdate)
if err != nil {
http.Error(res, fmt.Sprintf("Invalid JSON request: %s", err.Error()), http.StatusBadRequest)
return
}
userID, err := r.Services.Database.UpdateUserProfile(userProfileUpdate)
if err != nil {
http.Error(res, fmt.Sprintf("Error updating user in database: %s", err.Error()), http.StatusInternalServerError)
return
}
userProfileView, err := r.Services.Database.GetUserProfileViewByUserID(userID)
userCharViews, err := r.Services.Database.GetUserCharacterViewsByUserID(userID)
if err != nil {
http.Error(res, fmt.Sprintf("Error fetching user character views in database after updating user_character: %s", err.Error()), http.StatusInternalServerError)
return
}
response := &Response{
Success: true,
Error: nil,
Data: UserUpdateResponseData{
User: userProfileView,
UserCharacters: userCharViews,
},
}
res.Header().Set("Content-Type", "application/json")
json.NewEncoder(res).Encode(response)
}
func (r *UserRouter) handleUpdateDefaultUserCharacter(res http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
userDefaultUserCharUpdate := new(db.UserDefaultUserCharacterUpdate)
err := decoder.Decode(userDefaultUserCharUpdate)
if err != nil {
http.Error(res, fmt.Sprintf("Invalid JSON request: %s", err.Error()), http.StatusBadRequest)
return
}
userID, err := r.Services.Database.UpdateUserDefaultUserCharacter(userDefaultUserCharUpdate)
if err != nil {
http.Error(res, fmt.Sprintf("Error updating user default character in database: %s", err.Error()), http.StatusInternalServerError)
return
}
userProfileView, err := r.Services.Database.GetUserProfileViewByUserID(userID)
if err != nil {
http.Error(res, fmt.Sprintf("Error getting user in database after updating default user character: %s", err.Error()), http.StatusInternalServerError)
return
}
userCharViews, err := r.Services.Database.GetUserCharacterViewsByUserID(userID)
if err != nil {
http.Error(res, fmt.Sprintf("Error fetching user character views in database after updating user_character: %s", err.Error()), http.StatusInternalServerError)
return
}
response := &Response{
Success: true,
Error: nil,
Data: UserUpdateDefaultUserCharacterResponseData{
User: userProfileView,
UserCharacters: userCharViews,
},
}
res.Header().Set("Content-Type", "application/json")
json.NewEncoder(res).Encode(response)
}
| 30,812
|
https://github.com/fazilvk786/igbot/blob/master/node_modules/instagram-private-api/dist/feeds/thread-items.feed.d.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
igbot
|
fazilvk786
|
TypeScript
|
Code
| 24
| 59
|
import { AbstractFeed } from './abstract.feed';
export declare class ThreadItemsFeed extends AbstractFeed<any> {
threadId: any;
constructor(session: any, threadId: any, limit: any);
get(): any;
}
| 21,761
|
https://github.com/tbeu/OpenHPL/blob/master/OpenHPL/Icons/Governor.mo
|
Github Open Source
|
Open Source
|
BSD-Source-Code
| 2,021
|
OpenHPL
|
tbeu
|
Modelica
|
Code
| 36
| 161
|
within OpenHPL.Icons;
partial class Governor "Governor icon"
annotation (
Icon(coordinateSystem(preserveAspectRatio = false), graphics={ Bitmap(extent = {{-60, -60}, {60, 60}}, origin = {2, 0}, rotation = 360,
fileName="modelica://OpenHPL/Resources/Images/governor.svg"),
Text(lineColor={28,108,200},
extent={{-150,100},{150,60}},
textString="%name",
textStyle={TextStyle.Bold})}),
Diagram(coordinateSystem(preserveAspectRatio = false)));
end Governor;
| 6,986
|
https://github.com/chiao45/DataTransferKit/blob/master/packages/Operators/test/tstCenterDistributor.cpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,020
|
DataTransferKit
|
chiao45
|
C++
|
Code
| 781
| 2,209
|
//---------------------------------------------------------------------------//
/*
Copyright (c) 2012, Stuart R. Slattery
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
*: Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
*: Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
*: Neither the name of the University of Wisconsin - Madison nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//---------------------------------------------------------------------------//
/*!
* \file tstCenterDistributor.cpp
* \author Stuart R. Slattery
* \brief Center distributor tests.
*/
//---------------------------------------------------------------------------//
#include <cmath>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <vector>
#include <DTK_CenterDistributor.hpp>
#include "Teuchos_Array.hpp"
#include "Teuchos_ArrayRCP.hpp"
#include "Teuchos_CommHelpers.hpp"
#include "Teuchos_DefaultComm.hpp"
#include "Teuchos_Ptr.hpp"
#include "Teuchos_RCP.hpp"
#include "Teuchos_UnitTestHarness.hpp"
//---------------------------------------------------------------------------//
// HELPER FUNCTIONS
//---------------------------------------------------------------------------//
// Get the default communicator.
Teuchos::RCP<const Teuchos::Comm<int>> getDefaultComm()
{
#ifdef HAVE_MPI
return Teuchos::DefaultComm<int>::getComm();
#else
return Teuchos::rcp( new Teuchos::SerialComm<int>() );
#endif
}
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( CenterDistributor, dim_2_test )
{
Teuchos::RCP<const Teuchos::Comm<int>> comm = getDefaultComm();
int rank = comm->getRank();
int size = comm->getSize();
int inverse_rank = size - rank - 1;
int dim = 2;
int num_src_points = 10;
int num_src_coords = dim * num_src_points;
Teuchos::Array<double> src_coords( num_src_coords );
for ( int i = 0; i < num_src_points; ++i )
{
src_coords[dim * i] = 1.0 * i;
src_coords[dim * i + 1] = 2.0 * rank;
}
int num_tgt_points = 2;
int num_tgt_coords = dim * num_tgt_points;
Teuchos::Array<double> tgt_coords( num_tgt_coords );
tgt_coords[0] = 4.9;
tgt_coords[1] = 2.0 * inverse_rank;
tgt_coords[2] = 11.4;
tgt_coords[3] = 2.0 * inverse_rank;
double radius = 1.5;
Teuchos::Array<double> tgt_decomp_src;
DataTransferKit::CenterDistributor<2> distributor(
comm, src_coords(), tgt_coords(), radius, tgt_decomp_src );
int num_import = 6;
TEST_EQUALITY( num_import, distributor.getNumImports() );
TEST_EQUALITY( dim * distributor.getNumImports(), tgt_decomp_src.size() );
for ( int i = 0; i < num_import; ++i )
{
TEST_EQUALITY( tgt_decomp_src[dim * i], 4.0 + i );
TEST_EQUALITY( tgt_decomp_src[dim * i + 1], 2.0 * inverse_rank );
}
Teuchos::Array<double> src_data( num_src_points );
for ( int i = 0; i < num_src_points; ++i )
{
src_data[i] = i * inverse_rank;
}
Teuchos::Array<double> tgt_data( distributor.getNumImports() );
Teuchos::ArrayView<const double> src_view = src_data();
distributor.distribute( src_view, tgt_data() );
for ( int i = 0; i < num_import; ++i )
{
TEST_EQUALITY( tgt_data[i], ( 4.0 + i ) * rank );
}
}
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( CenterDistributor, dim_3_test )
{
Teuchos::RCP<const Teuchos::Comm<int>> comm = getDefaultComm();
int rank = comm->getRank();
int size = comm->getSize();
int inverse_rank = size - rank - 1;
int dim = 3;
int num_src_points = 10;
int num_src_coords = dim * num_src_points;
Teuchos::Array<double> src_coords( num_src_coords );
for ( int i = 0; i < num_src_points; ++i )
{
src_coords[dim * i] = 1.0 * i;
src_coords[dim * i + 1] = 2.0 * rank;
src_coords[dim * i + 2] = 2.0 * rank;
}
int num_tgt_points = 2;
int num_tgt_coords = dim * num_tgt_points;
Teuchos::Array<double> tgt_coords( num_tgt_coords );
tgt_coords[0] = 4.9;
tgt_coords[1] = 2.0 * inverse_rank;
tgt_coords[2] = 2.0 * inverse_rank;
tgt_coords[3] = 11.4;
tgt_coords[4] = 2.0 * inverse_rank;
tgt_coords[5] = 2.0 * inverse_rank;
double radius = 1.5;
Teuchos::Array<double> tgt_decomp_src;
DataTransferKit::CenterDistributor<3> distributor(
comm, src_coords(), tgt_coords(), radius, tgt_decomp_src );
int num_import = 6;
TEST_EQUALITY( num_import, distributor.getNumImports() );
TEST_EQUALITY( dim * distributor.getNumImports(), tgt_decomp_src.size() );
for ( int i = 0; i < num_import; ++i )
{
TEST_EQUALITY( tgt_decomp_src[dim * i], 4.0 + i );
TEST_EQUALITY( tgt_decomp_src[dim * i + 1], 2.0 * inverse_rank );
TEST_EQUALITY( tgt_decomp_src[dim * i + 2], 2.0 * inverse_rank );
}
Teuchos::Array<double> src_data( num_src_points );
for ( int i = 0; i < num_src_points; ++i )
{
src_data[i] = i * inverse_rank;
}
Teuchos::Array<double> tgt_data( distributor.getNumImports() );
Teuchos::ArrayView<const double> src_view = src_data();
distributor.distribute( src_view, tgt_data() );
for ( int i = 0; i < num_import; ++i )
{
TEST_EQUALITY( tgt_data[i], ( 4.0 + i ) * rank );
}
}
//---------------------------------------------------------------------------//
// end tstCenterDistributor.cpp
//---------------------------------------------------------------------------//
| 11,831
|
https://github.com/lwardzala/Business-Rules-Reasoning-System/blob/master/Source/Reasoning.MongoDb/Repositories/ReasoningTaskRepository.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Business-Rules-Reasoning-System
|
lwardzala
|
C#
|
Code
| 149
| 569
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using MongoDB.Driver;
using Reasoning.Core.Contracts;
using Reasoning.MongoDb.Configuration;
using Reasoning.MongoDb.Models;
namespace Reasoning.MongoDb.Repositories
{
public class ReasoningTaskRepository : RepositoryBase<ReasoningTask>, IReasoningTaskRepository
{
public ReasoningTaskRepository(IMongoDatabaseSettings settings) : base(settings, settings.ReasoningTaskCollectionName)
{
}
public async Task<long> CountAsync(Expression<Func<IReasoningTask, bool>> filter)
{
var filterConverted = Expression.Lambda<Func<ReasoningTask, bool>>(filter.Body, filter.Parameters);
return await collection.CountDocumentsAsync(filterConverted);
}
public void Create(IReasoningTask document) =>
collection.InsertOneAsync((ReasoningTask)document);
public async Task<IList<IReasoningTask>> GetAsync(Expression<Func<IReasoningTask, bool>> filter, int batchSize = 100)
{
var filterConverted = Expression.Lambda<Func<ReasoningTask, bool>>(filter.Body, filter.Parameters);
return (await collection.Find(filterConverted, new FindOptions() { BatchSize = batchSize }).ToListAsync()).ToList<IReasoningTask>();
}
public async Task<IReasoningTask> GetAsync(string id)
{
return await collection.Find(doc => doc.Id == id).FirstOrDefaultAsync();
}
public Task<DeleteResult> RemoveAsync(IReasoningTask document) =>
collection.DeleteOneAsync(doc => doc.Id == document.Id);
public Task<DeleteResult> RemoveAsync(string id) =>
collection.DeleteOneAsync(doc => doc.Id == id);
public void Update(string id, IReasoningTask document) =>
collection.ReplaceOne(doc => doc.Id == id, (ReasoningTask)document);
public Task<ReplaceOneResult> UpdateAsync(string id, IReasoningTask document) =>
collection.ReplaceOneAsync(doc => doc.Id == id, (ReasoningTask)document);
}
}
| 21,283
|
https://github.com/HerrB92/obp/blob/master/OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalInheritanceRefEdChildEntity.java
|
Github Open Source
|
Open Source
|
MIT
| null |
obp
|
HerrB92
|
Java
|
Code
| 201
| 670
|
package org.hibernate.envers.test.entities.onetomany.detached;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.envers.Audited;
/**
* Entity for {@link org.hibernate.envers.test.integration.onetomany.detached.JoinColumnBidirectionalListWithInheritance} test.
* Owned child side of the relation.
* @author Adam Warski (adam at warski dot org)
*/
@Entity
@Table(name = "ListJoinColBiInhRefEdChild")
@DiscriminatorValue("2")
@Audited
public class ListJoinColumnBidirectionalInheritanceRefEdChildEntity extends ListJoinColumnBidirectionalInheritanceRefEdParentEntity {
private String childData;
public ListJoinColumnBidirectionalInheritanceRefEdChildEntity() { }
public ListJoinColumnBidirectionalInheritanceRefEdChildEntity(Integer id, String parentData, ListJoinColumnBidirectionalInheritanceRefIngEntity owner, String childData) {
super(id, parentData, owner);
this.childData = childData;
}
public ListJoinColumnBidirectionalInheritanceRefEdChildEntity(String parentData, ListJoinColumnBidirectionalInheritanceRefIngEntity owner, String childData) {
super(parentData, owner);
this.childData = childData;
}
public String getChildData() {
return childData;
}
public void setChildData(String childData) {
this.childData = childData;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
ListJoinColumnBidirectionalInheritanceRefEdChildEntity that = (ListJoinColumnBidirectionalInheritanceRefEdChildEntity) o;
//noinspection RedundantIfStatement
if (childData != null ? !childData.equals(that.childData) : that.childData != null) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (childData != null ? childData.hashCode() : 0);
return result;
}
public String toString() {
return "ListJoinColumnBidirectionalInheritanceRefEdChildEntity(id = " + getId() +
", parentData = " + getParentData() + ", childData = " + childData + ")";
}
}
| 27,623
|
https://github.com/odorizzi28/GitC/blob/master/Treinamento HBSIS/05-08-19-09-08-19/ExercicioValidacao/View/ucNumero.xaml.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
GitC
|
odorizzi28
|
C#
|
Code
| 112
| 501
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ExercicioValidacao.View
{
/// <summary>
/// Interaction logic for ucNumero.xaml
/// </summary>
public partial class ucNumero : UserControl
{
public ucNumero()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string fone = tbxFone.Text;
Regex regexFone = new Regex(@"^\(?\d{2}\(?\d{2}\)?[\s-]?[\s9]?\d{4}-?\d{4}$");
if (regexFone.IsMatch(fone))
{
labelFone.Content = "Fone Valido!";
}
else
{
labelFone.Content = "Fone Inválido!";
}
string email = tbxEmail.Text;
Regex regexEmail = new Regex(@"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$");
if (regexEmail.IsMatch(email))
{
labelEmail.Content = "Email Valido!";
}
else
{
labelEmail.Content = "Email Inválido!";
}
}
}
}
| 45,171
|
https://github.com/TalkingData/rxloop-immer/blob/master/jest.config.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
rxloop-immer
|
TalkingData
|
JavaScript
|
Code
| 8
| 47
|
module.exports = {
testURL: 'http://localhost/',
testMatch: ['**/?*.(spec|test|e2e).(j|t)s?(x)']
};
| 47,941
|
https://github.com/TimothyRHuertas/turicreate/blob/master/src/unity/python/turicreate/visualization/plot.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
turicreate
|
TimothyRHuertas
|
Python
|
Code
| 178
| 963
|
from __future__ import print_function as _
from __future__ import division as _
from __future__ import absolute_import as _
import logging as _logging
import json as _json
class Plot(object):
def __init__(self, _proxy=None):
if (_proxy):
self.__proxy__ = _proxy
else:
self.__proxy__ = None
def show(self):
import sys
import os
if sys.platform != 'darwin' and sys.platform != 'linux2':
raise NotImplementedError('Visualization is currently supported only on macOS and Linux.')
self.__proxy__.get('call_function', {'__function_name__': 'show'})
def save_vega(self, filepath, include_data=True):
spec = _json.loads(self.__proxy__.get('call_function', {'__function_name__': 'get_spec'}))
if(include_data):
data = _json.loads(self.__proxy__.get('call_function', {'__function_name__': 'get_data'}))["data_spec"]
for x in range(0, len(spec["vega_spec"]["data"])):
if(spec["vega_spec"]["data"][x]["name"] == "source_2"):
spec["vega_spec"]["data"][x] = data
break;
with open(filepath, 'w') as fp:
_json.dump(spec, fp)
def get_data(self):
return _json.loads(self.__proxy__.get('call_function', {'__function_name__': 'get_data'}))
def get_vega(self, include_data=True):
if(include_data):
spec = _json.loads(self.__proxy__.get('call_function', {'__function_name__': 'get_spec'}))
data = _json.loads(self.__proxy__.get('call_function', {'__function_name__': 'get_data'}))["data_spec"]
for x in range(0, len(spec["vega_spec"]["data"])):
if(spec["vega_spec"]["data"][x]["name"] == "source_2"):
spec["vega_spec"]["data"][x] = data
break;
return spec
else:
return _json.loads(self.__proxy__.get('call_function', {'__function_name__': 'get_spec'}))
def _repr_javascript_(self):
from IPython.core.display import display, HTML
vega_spec = self.get_vega(True)["vega_spec"]
vega_html = '<html lang="en"><head><script src="https://cdnjs.cloudflare.com/ajax/libs/vega/3.0.8/vega.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/vega-embed/3.0.0-rc7/vega-embed.js"></script></head><body><div id="vis"></div><script>var vega_json = '+_json.dumps(_json.dumps(vega_spec)).replace("'", "'")+'; var vega_json_parsed = JSON.parse(vega_json); vegaEmbed("#vis", vega_json_parsed);</script></body></html>'
display(HTML('<html><body><iframe style="border:0;margin:0" width="'+str(vega_spec["width"]+200)+'" height="'+str(vega_spec["height"]+200)+'" srcdoc='+"'"+vega_html+"'"+' src="demo_iframe_srcdoc.htm"><p>Your browser does not support iframes.</p></iframe></body></html>'))
| 22,180
|
https://github.com/yoshuawuyts/spec-rust/blob/master/src/submodule/internal.rs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
spec-rust
|
yoshuawuyts
|
Rust
|
Code
| 9
| 25
|
pub(crate) fn print() {
println!("for internal use only!")
}
| 49,467
|
https://github.com/nagaremono/shop-service-v2/blob/master/prisma/generated/type-graphql/resolvers/crud/Product/ProductCrudResolver.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
shop-service-v2
|
nagaremono
|
TypeScript
|
Code
| 585
| 2,138
|
import * as TypeGraphQL from "type-graphql";
import graphqlFields from "graphql-fields";
import { GraphQLResolveInfo } from "graphql";
import { AggregateProductArgs } from "./args/AggregateProductArgs";
import { CreateManyProductArgs } from "./args/CreateManyProductArgs";
import { CreateProductArgs } from "./args/CreateProductArgs";
import { DeleteManyProductArgs } from "./args/DeleteManyProductArgs";
import { DeleteProductArgs } from "./args/DeleteProductArgs";
import { FindFirstProductArgs } from "./args/FindFirstProductArgs";
import { FindManyProductArgs } from "./args/FindManyProductArgs";
import { FindUniqueProductArgs } from "./args/FindUniqueProductArgs";
import { GroupByProductArgs } from "./args/GroupByProductArgs";
import { UpdateManyProductArgs } from "./args/UpdateManyProductArgs";
import { UpdateProductArgs } from "./args/UpdateProductArgs";
import { UpsertProductArgs } from "./args/UpsertProductArgs";
import { transformFields, getPrismaFromContext, transformCountFieldIntoSelectRelationsCount } from "../../../helpers";
import { Product } from "../../../models/Product";
import { AffectedRowsOutput } from "../../outputs/AffectedRowsOutput";
import { AggregateProduct } from "../../outputs/AggregateProduct";
import { ProductGroupBy } from "../../outputs/ProductGroupBy";
@TypeGraphQL.Resolver(_of => Product)
export class ProductCrudResolver {
@TypeGraphQL.Query(_returns => Product, {
nullable: true
})
async product(@TypeGraphQL.Ctx() ctx: any, @TypeGraphQL.Info() info: GraphQLResolveInfo, @TypeGraphQL.Args() args: FindUniqueProductArgs): Promise<Product | null> {
const { _count } = transformFields(
graphqlFields(info as any)
);
return getPrismaFromContext(ctx).product.findUnique({
...args,
...(_count && transformCountFieldIntoSelectRelationsCount(_count)),
});
}
@TypeGraphQL.Query(_returns => Product, {
nullable: true
})
async findFirstProduct(@TypeGraphQL.Ctx() ctx: any, @TypeGraphQL.Info() info: GraphQLResolveInfo, @TypeGraphQL.Args() args: FindFirstProductArgs): Promise<Product | null> {
const { _count } = transformFields(
graphqlFields(info as any)
);
return getPrismaFromContext(ctx).product.findFirst({
...args,
...(_count && transformCountFieldIntoSelectRelationsCount(_count)),
});
}
@TypeGraphQL.Query(_returns => [Product], {
nullable: false
})
async products(@TypeGraphQL.Ctx() ctx: any, @TypeGraphQL.Info() info: GraphQLResolveInfo, @TypeGraphQL.Args() args: FindManyProductArgs): Promise<Product[]> {
const { _count } = transformFields(
graphqlFields(info as any)
);
return getPrismaFromContext(ctx).product.findMany({
...args,
...(_count && transformCountFieldIntoSelectRelationsCount(_count)),
});
}
@TypeGraphQL.Mutation(_returns => Product, {
nullable: false
})
async createProduct(@TypeGraphQL.Ctx() ctx: any, @TypeGraphQL.Info() info: GraphQLResolveInfo, @TypeGraphQL.Args() args: CreateProductArgs): Promise<Product> {
const { _count } = transformFields(
graphqlFields(info as any)
);
return getPrismaFromContext(ctx).product.create({
...args,
...(_count && transformCountFieldIntoSelectRelationsCount(_count)),
});
}
@TypeGraphQL.Mutation(_returns => AffectedRowsOutput, {
nullable: false
})
async createManyProduct(@TypeGraphQL.Ctx() ctx: any, @TypeGraphQL.Info() info: GraphQLResolveInfo, @TypeGraphQL.Args() args: CreateManyProductArgs): Promise<AffectedRowsOutput> {
const { _count } = transformFields(
graphqlFields(info as any)
);
return getPrismaFromContext(ctx).product.createMany({
...args,
...(_count && transformCountFieldIntoSelectRelationsCount(_count)),
});
}
@TypeGraphQL.Mutation(_returns => Product, {
nullable: true
})
async deleteProduct(@TypeGraphQL.Ctx() ctx: any, @TypeGraphQL.Info() info: GraphQLResolveInfo, @TypeGraphQL.Args() args: DeleteProductArgs): Promise<Product | null> {
const { _count } = transformFields(
graphqlFields(info as any)
);
return getPrismaFromContext(ctx).product.delete({
...args,
...(_count && transformCountFieldIntoSelectRelationsCount(_count)),
});
}
@TypeGraphQL.Mutation(_returns => Product, {
nullable: true
})
async updateProduct(@TypeGraphQL.Ctx() ctx: any, @TypeGraphQL.Info() info: GraphQLResolveInfo, @TypeGraphQL.Args() args: UpdateProductArgs): Promise<Product | null> {
const { _count } = transformFields(
graphqlFields(info as any)
);
return getPrismaFromContext(ctx).product.update({
...args,
...(_count && transformCountFieldIntoSelectRelationsCount(_count)),
});
}
@TypeGraphQL.Mutation(_returns => AffectedRowsOutput, {
nullable: false
})
async deleteManyProduct(@TypeGraphQL.Ctx() ctx: any, @TypeGraphQL.Info() info: GraphQLResolveInfo, @TypeGraphQL.Args() args: DeleteManyProductArgs): Promise<AffectedRowsOutput> {
const { _count } = transformFields(
graphqlFields(info as any)
);
return getPrismaFromContext(ctx).product.deleteMany({
...args,
...(_count && transformCountFieldIntoSelectRelationsCount(_count)),
});
}
@TypeGraphQL.Mutation(_returns => AffectedRowsOutput, {
nullable: false
})
async updateManyProduct(@TypeGraphQL.Ctx() ctx: any, @TypeGraphQL.Info() info: GraphQLResolveInfo, @TypeGraphQL.Args() args: UpdateManyProductArgs): Promise<AffectedRowsOutput> {
const { _count } = transformFields(
graphqlFields(info as any)
);
return getPrismaFromContext(ctx).product.updateMany({
...args,
...(_count && transformCountFieldIntoSelectRelationsCount(_count)),
});
}
@TypeGraphQL.Mutation(_returns => Product, {
nullable: false
})
async upsertProduct(@TypeGraphQL.Ctx() ctx: any, @TypeGraphQL.Info() info: GraphQLResolveInfo, @TypeGraphQL.Args() args: UpsertProductArgs): Promise<Product> {
const { _count } = transformFields(
graphqlFields(info as any)
);
return getPrismaFromContext(ctx).product.upsert({
...args,
...(_count && transformCountFieldIntoSelectRelationsCount(_count)),
});
}
@TypeGraphQL.Query(_returns => AggregateProduct, {
nullable: false
})
async aggregateProduct(@TypeGraphQL.Ctx() ctx: any, @TypeGraphQL.Info() info: GraphQLResolveInfo, @TypeGraphQL.Args() args: AggregateProductArgs): Promise<AggregateProduct> {
return getPrismaFromContext(ctx).product.aggregate({
...args,
...transformFields(graphqlFields(info as any)),
});
}
@TypeGraphQL.Query(_returns => [ProductGroupBy], {
nullable: false
})
async groupByProduct(@TypeGraphQL.Ctx() ctx: any, @TypeGraphQL.Info() info: GraphQLResolveInfo, @TypeGraphQL.Args() args: GroupByProductArgs): Promise<ProductGroupBy[]> {
const { _count, _avg, _sum, _min, _max } = transformFields(
graphqlFields(info as any)
);
return getPrismaFromContext(ctx).product.groupBy({
...args,
...Object.fromEntries(
Object.entries({ _count, _avg, _sum, _min, _max }).filter(([_, v]) => v != null)
),
});
}
}
| 1,221
|
https://github.com/b-cube/bcube-triplestore/blob/master/ttl/6f/6f1270255193f3eb0100afcbacf7e4d9ec6edfd7_triples.ttl
|
Github Open Source
|
Open Source
|
MIT
| null |
bcube-triplestore
|
b-cube
|
Turtle
|
Code
| 281
| 1,899
|
@prefix bcube: <http://purl.org/BCube/#> .
@prefix bibo: <http://purl.org/ontology/bibo/#> .
@prefix dc: <http://purl.org/dc/elements/1.1/> .
@prefix dcat: <http://www.w3.org/TR/vocab-dcat/#> .
@prefix dcterms: <http://purl.org/dc/terms/> .
@prefix esip: <http://purl.org/esip/#> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix vcard: <http://www.w3.org/TR/vcard-rdf/#> .
@prefix xml: <http://www.w3.org/XML/1998/namespace> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
<urn:uuid:11bafe4b-ab4d-4a5f-8972-4d4e6926ac2e> owl:a foaf:Organization ;
foaf:name "Southern California Coastal Water Resources Project" .
<urn:uuid:2f8878fa-50df-4895-a044-d3c49a9b3210> bcube:dateCreated "2015-11-02T19:58:44.003Z" ;
bcube:hasMetadataRecord <urn:uuid:6ea38d78-4823-4f5e-bd70-b716bb7299c1> ;
bcube:lastUpdated "2015-11-02T19:58:44.003Z" ;
dc:conformsTo <urn:uuid:561eeb18-f81e-4fd8-af24-83ea1ff5c557>,
<urn:uuid:8866b6ec-96af-4602-9969-0dbeeb224b4f>,
<urn:uuid:d8a59566-e3ef-48c3-bd63-33277c002954> ;
dc:description "See http://www.sccwrp.org" ;
dc:spatial "POLYGON ((-120.41465 32.54267,-120.41465 34.45845,-117.16117 34.45845,-117.16117 32.54267,-120.41465 32.54267))" ;
dcterms:publisher <urn:uuid:11bafe4b-ab4d-4a5f-8972-4d4e6926ac2e> ;
dcterms:references <urn:uuid:5e865d99-3b05-4731-9289-ef8a68110b2f> ;
dcterms:title "SCCWRP Pilot Project 1994" ;
esip:eastBound "-117.16117"^^xsd:float ;
esip:northBound "34.45845"^^xsd:float ;
esip:southBound "32.54267"^^xsd:float ;
esip:startDate "1994-01-01"^^xsd:date ;
esip:westBound "-120.41465"^^xsd:float ;
owl:a dcat:Dataset .
<urn:uuid:30c303f9-a325-4b74-9246-025137dcb4ea> bcube:HTTPStatusCodeValue 200 ;
bcube:HTTPStatusFamilyCode 200 ;
bcube:HTTPStatusFamilyType "Success message" ;
bcube:atTime "2015-11-02T19:58:44.003Z" ;
bcube:hasConfidence "Good" ;
bcube:hasUrlSource "Harvested" ;
bcube:reasonPhrase "OK" ;
bcube:validatedOn "2015-11-02T19:58:44.003Z" ;
dc:identifier "urn:sha:f88a6c9cfcc7edb676e138b56b932ce1895ffb20cb305c105116b68f" ;
owl:a bcube:Url ;
vcard:hasUrl "http://pubs.usgs.gov/ds/2006/182/source_metadata/SCCWRP94/SCCWRP94.xml" .
<urn:uuid:33781400-d2fd-4ae3-8bc6-8d6d5def4c3f> bcube:HTTPStatusCodeValue 200 ;
bcube:HTTPStatusFamilyCode 200 ;
bcube:HTTPStatusFamilyType "Success message" ;
bcube:atTime "2015-11-02T19:58:44.003Z" ;
bcube:hasConfidence "Good" ;
bcube:hasUrlSource "Harvested" ;
bcube:reasonPhrase "OK" ;
bcube:validatedOn "2015-11-02T19:58:44.003Z" ;
dc:identifier "urn:sha:67cc721062f827f85ecf79d8dd696b69ff31bfa40aeeb08372bc81b3" ;
owl:a bcube:Url ;
vcard:hasUrl "http://www.sccwrp.org" .
<urn:uuid:561eeb18-f81e-4fd8-af24-83ea1ff5c557> bcube:hasType "place" ;
bcube:hasValue "California" ;
dc:partOf "Geographic Names Information System" ;
owl:a bcube:thesaurusSubset .
<urn:uuid:5e865d99-3b05-4731-9289-ef8a68110b2f> dcterms:references <urn:uuid:33781400-d2fd-4ae3-8bc6-8d6d5def4c3f> ;
owl:a bibo:WebPage .
<urn:uuid:6ea38d78-4823-4f5e-bd70-b716bb7299c1> a "FGDC:CSDGM" ;
bcube:dateCreated "2015-11-02T19:58:44.003Z" ;
bcube:lastUpdated "2015-11-02T19:58:44.003Z" ;
bcube:originatedFrom <urn:uuid:30c303f9-a325-4b74-9246-025137dcb4ea> ;
owl:a dcat:CatalogRecord ;
foaf:primaryTopic <urn:uuid:2f8878fa-50df-4895-a044-d3c49a9b3210> .
<urn:uuid:8866b6ec-96af-4602-9969-0dbeeb224b4f> bcube:hasType "theme" ;
bcube:hasValue "Marine Sediment",
"Sedimentary Composition",
"Sedimentary Textures" ;
dc:partOf "NASA/Global Change Master Directory (GCMD) Earth Science Keyword. Version 5.3.3" ;
owl:a bcube:thesaurusSubset .
<urn:uuid:d8a59566-e3ef-48c3-bd63-33277c002954> bcube:hasType "theme" ;
bcube:hasValue "GeoscientificInformation",
"Location",
"Oceans and Estuaries" ;
dc:partOf "ISO 19115 Topic Category" ;
owl:a bcube:thesaurusSubset .
| 17,851
|
https://github.com/syedomair/ct_client_admin/blob/master/src/AppBundle/Resources/views/Admin/dashboard.html.twig
|
Github Open Source
|
Open Source
|
MIT
| null |
ct_client_admin
|
syedomair
|
Twig
|
Code
| 1,755
| 6,731
|
{% extends 'base.html.twig' %}
{% block stylesheets %}
<link href="{{ asset('bundles/app/css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ asset('bundles/app/css/bootstrap-responsice.min.css') }}" rel="stylesheet">
<link href="{{ asset('bundles/app/css/fullcalendar.css') }}" rel="stylesheet">
<link href="{{ asset('bundles/app/css/matrix-style.css') }}" rel="stylesheet">
<link href="{{ asset('bundles/app/css/matrix-media.css') }}" rel="stylesheet">
<link href="{{ asset('bundles/app/font-awesome/css/font-awesome.css') }}" rel="stylesheet">
<link href="{{ asset('bundles/app/css/jquery.gritter.css') }}" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,800' rel='stylesheet' type='text/css'>
{% endblock %}
{% block body %}
<body>
{% block header %}
{% include('AppBundle:Base:header.html.twig') %}
{% endblock %}
{% block side_bar %}
{% include('AppBundle:Base:side_bar.html.twig') %}
{% endblock %}
<!--main-container-part-->
<div id="content">
<!--breadcrumbs-->
<div id="content-header">
<div id="breadcrumb"> <a href="index.html" title="Go to Home" class="tip-bottom"><i class="icon-home"></i> Home</a></div>
</div>
<!--End-breadcrumbs-->
{#
<!--Action boxes-->
<div class="container-fluid">
<div class="quick-actions_homepage">
<ul class="quick-actions">
<li class="bg_lb"> <a href="index.html"> <i class="icon-dashboard"></i> <span class="label label-important">20</span> My Dashboard </a> </li>
<li class="bg_lg span3"> <a href="charts.html"> <i class="icon-signal"></i> Charts</a> </li>
<li class="bg_ly"> <a href="widgets.html"> <i class="icon-inbox"></i><span class="label label-success">101</span> Widgets </a> </li>
<li class="bg_lo"> <a href="tables.html"> <i class="icon-th"></i> Tables</a> </li>
<li class="bg_ls"> <a href="grid.html"> <i class="icon-fullscreen"></i> Full width</a> </li>
<li class="bg_lo span3"> <a href="form-common.html"> <i class="icon-th-list"></i> Forms</a> </li>
<li class="bg_ls"> <a href="buttons.html"> <i class="icon-tint"></i> Buttons</a> </li>
<li class="bg_lb"> <a href="interface.html"> <i class="icon-pencil"></i>Elements</a> </li>
<li class="bg_lg"> <a href="calendar.html"> <i class="icon-calendar"></i> Calendar</a> </li>
<li class="bg_lr"> <a href="error404.html"> <i class="icon-info-sign"></i> Error</a> </li>
</ul>
</div>
<!--End-Action boxes-->
#}
<!--Chart-box-->
<div class="row-fluid">
<div class="widget-box">
<div class="widget-title bg_lg"><span class="icon"><i class="icon-signal"></i></span>
<h5>Site Analytics</h5>
</div>
<div class="widget-content" >
<div class="row-fluid">
<div class="span9">
<div class="chart"></div>
</div>
<div class="span3">
<ul class="site-stats">
<li class="bg_lh"><i class="icon-user"></i> <strong>2540</strong> <small>Total Users</small></li>
<li class="bg_lh"><i class="icon-plus"></i> <strong>120</strong> <small>New Users </small></li>
<li class="bg_lh"><i class="icon-shopping-cart"></i> <strong>656</strong> <small>Total Shop</small></li>
<li class="bg_lh"><i class="icon-tag"></i> <strong>9540</strong> <small>Total Orders</small></li>
<li class="bg_lh"><i class="icon-repeat"></i> <strong>10</strong> <small>Pending Orders</small></li>
<li class="bg_lh"><i class="icon-globe"></i> <strong>8540</strong> <small>Online Orders</small></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!--End-Chart-box-->
{#
<hr/>
<div class="row-fluid">
<div class="span6">
<div class="widget-box">
<div class="widget-title bg_ly" data-toggle="collapse" href="#collapseG2"><span class="icon"><i class="icon-chevron-down"></i></span>
<h5>Latest Posts</h5>
</div>
<div class="widget-content nopadding collapse in" id="collapseG2">
<ul class="recent-posts">
<li>
<div class="user-thumb"> <img width="40" height="40" alt="User" src="img/demo/av1.jpg"> </div>
<div class="article-post"> <span class="user-info"> By: john Deo / Date: 2 Aug 2012 / Time:09:27 AM </span>
<p><a href="#">This is a much longer one that will go on for a few lines.It has multiple paragraphs and is full of waffle to pad out the comment.</a> </p>
</div>
</li>
<li>
<div class="user-thumb"> <img width="40" height="40" alt="User" src="img/demo/av2.jpg"> </div>
<div class="article-post"> <span class="user-info"> By: john Deo / Date: 2 Aug 2012 / Time:09:27 AM </span>
<p><a href="#">This is a much longer one that will go on for a few lines.It has multiple paragraphs and is full of waffle to pad out the comment.</a> </p>
</div>
</li>
<li>
<div class="user-thumb"> <img width="40" height="40" alt="User" src="img/demo/av4.jpg"> </div>
<div class="article-post"> <span class="user-info"> By: john Deo / Date: 2 Aug 2012 / Time:09:27 AM </span>
<p><a href="#">This is a much longer one that will go on for a few lines.Itaffle to pad out the comment.</a> </p>
</div>
<li>
<button class="btn btn-warning btn-mini">View All</button>
</li>
</ul>
</div>
</div>
<div class="widget-box">
<div class="widget-title"> <span class="icon"><i class="icon-ok"></i></span>
<h5>To Do list</h5>
</div>
<div class="widget-content">
<div class="todo">
<ul>
<li class="clearfix">
<div class="txt"> Luanch This theme on Themeforest <span class="by label">Alex</span></div>
<div class="pull-right"> <a class="tip" href="#" title="Edit Task"><i class="icon-pencil"></i></a> <a class="tip" href="#" title="Delete"><i class="icon-remove"></i></a> </div>
</li>
<li class="clearfix">
<div class="txt"> Manage Pending Orders <span class="date badge badge-warning">Today</span> </div>
<div class="pull-right"> <a class="tip" href="#" title="Edit Task"><i class="icon-pencil"></i></a> <a class="tip" href="#" title="Delete"><i class="icon-remove"></i></a> </div>
</li>
<li class="clearfix">
<div class="txt"> MAke your desk clean <span class="by label">Admin</span></div>
<div class="pull-right"> <a class="tip" href="#" title="Edit Task"><i class="icon-pencil"></i></a> <a class="tip" href="#" title="Delete"><i class="icon-remove"></i></a> </div>
</li>
<li class="clearfix">
<div class="txt"> Today we celebrate the theme <span class="date badge badge-info">08.03.2013</span> </div>
<div class="pull-right"> <a class="tip" href="#" title="Edit Task"><i class="icon-pencil"></i></a> <a class="tip" href="#" title="Delete"><i class="icon-remove"></i></a> </div>
</li>
<li class="clearfix">
<div class="txt"> Manage all the orders <span class="date badge badge-important">12.03.2013</span> </div>
<div class="pull-right"> <a class="tip" href="#" title="Edit Task"><i class="icon-pencil"></i></a> <a class="tip" href="#" title="Delete"><i class="icon-remove"></i></a> </div>
</li>
</ul>
</div>
</div>
</div>
<div class="widget-box">
<div class="widget-title"> <span class="icon"><i class="icon-ok"></i></span>
<h5>Progress Box</h5>
</div>
<div class="widget-content">
<ul class="unstyled">
<li> <span class="icon24 icomoon-icon-arrow-up-2 green"></span> 81% Clicks <span class="pull-right strong">567</span>
<div class="progress progress-striped ">
<div style="width: 81%;" class="bar"></div>
</div>
</li>
<li> <span class="icon24 icomoon-icon-arrow-up-2 green"></span> 72% Uniquie Clicks <span class="pull-right strong">507</span>
<div class="progress progress-success progress-striped ">
<div style="width: 72%;" class="bar"></div>
</div>
</li>
<li> <span class="icon24 icomoon-icon-arrow-down-2 red"></span> 53% Impressions <span class="pull-right strong">457</span>
<div class="progress progress-warning progress-striped ">
<div style="width: 53%;" class="bar"></div>
</div>
</li>
<li> <span class="icon24 icomoon-icon-arrow-up-2 green"></span> 3% Online Users <span class="pull-right strong">8</span>
<div class="progress progress-danger progress-striped ">
<div style="width: 3%;" class="bar"></div>
</div>
</li>
</ul>
</div>
</div>
<div class="widget-box">
<div class="widget-title bg_lo" data-toggle="collapse" href="#collapseG3" > <span class="icon"> <i class="icon-chevron-down"></i> </span>
<h5>News updates</h5>
</div>
<div class="widget-content nopadding updates collapse in" id="collapseG3">
<div class="new-update clearfix"><i class="icon-ok-sign"></i>
<div class="update-done"><a title="" href="#"><strong>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</strong></a> <span>dolor sit amet, consectetur adipiscing eli</span> </div>
<div class="update-date"><span class="update-day">20</span>jan</div>
</div>
<div class="new-update clearfix"> <i class="icon-gift"></i> <span class="update-notice"> <a title="" href="#"><strong>Congratulation Maruti, Happy Birthday </strong></a> <span>many many happy returns of the day</span> </span> <span class="update-date"><span class="update-day">11</span>jan</span> </div>
<div class="new-update clearfix"> <i class="icon-move"></i> <span class="update-alert"> <a title="" href="#"><strong>Maruti is a Responsive Admin theme</strong></a> <span>But already everything was solved. It will ...</span> </span> <span class="update-date"><span class="update-day">07</span>Jan</span> </div>
<div class="new-update clearfix"> <i class="icon-leaf"></i> <span class="update-done"> <a title="" href="#"><strong>Envato approved Maruti Admin template</strong></a> <span>i am very happy to approved by TF</span> </span> <span class="update-date"><span class="update-day">05</span>jan</span> </div>
<div class="new-update clearfix"> <i class="icon-question-sign"></i> <span class="update-notice"> <a title="" href="#"><strong>I am alwayse here if you have any question</strong></a> <span>we glad that you choose our template</span> </span> <span class="update-date"><span class="update-day">01</span>jan</span> </div>
</div>
</div>
</div>
<div class="span6">
<div class="widget-box widget-chat">
<div class="widget-title bg_lb"> <span class="icon"> <i class="icon-comment"></i> </span>
<h5>Chat Option</h5>
</div>
<div class="widget-content nopadding collapse in" id="collapseG4">
<div class="chat-users panel-right2">
<div class="panel-title">
<h5>Online Users</h5>
</div>
<div class="panel-content nopadding">
<ul class="contact-list">
<li id="user-Alex" class="online"><a href=""><img alt="" src="img/demo/av1.jpg" /> <span>Alex</span></a></li>
<li id="user-Linda"><a href=""><img alt="" src="img/demo/av2.jpg" /> <span>Linda</span></a></li>
<li id="user-John" class="online new"><a href=""><img alt="" src="img/demo/av3.jpg" /> <span>John</span></a><span class="msg-count badge badge-info">3</span></li>
<li id="user-Mark" class="online"><a href=""><img alt="" src="img/demo/av4.jpg" /> <span>Mark</span></a></li>
<li id="user-Maxi" class="online"><a href=""><img alt="" src="img/demo/av5.jpg" /> <span>Maxi</span></a></li>
</ul>
</div>
</div>
<div class="chat-content panel-left2">
<div class="chat-messages" id="chat-messages">
<div id="chat-messages-inner"></div>
</div>
<div class="chat-message well">
<button class="btn btn-success">Send</button>
<span class="input-box">
<input type="text" name="msg-box" id="msg-box" />
</span> </div>
</div>
</div>
</div>
<div class="widget-box">
<div class="widget-title"><span class="icon"><i class="icon-user"></i></span>
<h5>Our Partner (Box with Fix height)</h5>
</div>
<div class="widget-content nopadding fix_hgt">
<ul class="recent-posts">
<li>
<div class="user-thumb"> <img width="40" height="40" alt="User" src="img/demo/av1.jpg"> </div>
<div class="article-post"> <span class="user-info">John Deo</span>
<p>Web Desginer & creative Front end developer</p>
</div>
</li>
<li>
<div class="user-thumb"> <img width="40" height="40" alt="User" src="img/demo/av2.jpg"> </div>
<div class="article-post"> <span class="user-info">John Deo</span>
<p>Web Desginer & creative Front end developer</p>
</div>
</li>
<li>
<div class="user-thumb"> <img width="40" height="40" alt="User" src="img/demo/av4.jpg"> </div>
<div class="article-post"> <span class="user-info">John Deo</span>
<p>Web Desginer & creative Front end developer</p>
</div>
</ul>
</div>
</div>
<div class="accordion" id="collapse-group">
<div class="accordion-group widget-box">
<div class="accordion-heading">
<div class="widget-title"> <a data-parent="#collapse-group" href="#collapseGOne" data-toggle="collapse"> <span class="icon"><i class="icon-magnet"></i></span>
<h5>Accordion Example 1</h5>
</a> </div>
</div>
<div class="collapse in accordion-body" id="collapseGOne">
<div class="widget-content"> It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end. </div>
</div>
</div>
<div class="accordion-group widget-box">
<div class="accordion-heading">
<div class="widget-title"> <a data-parent="#collapse-group" href="#collapseGTwo" data-toggle="collapse"> <span class="icon"><i class="icon-magnet"></i></span>
<h5>Accordion Example 2</h5>
</a> </div>
</div>
<div class="collapse accordion-body" id="collapseGTwo">
<div class="widget-content">And is full of waffle to It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.</div>
</div>
</div>
<div class="accordion-group widget-box">
<div class="accordion-heading">
<div class="widget-title"> <a data-parent="#collapse-group" href="#collapseGThree" data-toggle="collapse"> <span class="icon"><i class="icon-magnet"></i></span>
<h5>Accordion Example 3</h5>
</a> </div>
</div>
<div class="collapse accordion-body" id="collapseGThree">
<div class="widget-content"> Waffle to It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just </div>
</div>
</div>
</div>
<div class="widget-box collapsible">
<div class="widget-title"> <a data-toggle="collapse" href="#collapseOne"> <span class="icon"><i class="icon-arrow-right"></i></span>
<h5>Toggle, Open by default, </h5>
</a> </div>
<div id="collapseOne" class="collapse in">
<div class="widget-content"> This box is opened by default, paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end. </div>
</div>
<div class="widget-title"> <a data-toggle="collapse" href="#collapseTwo"> <span class="icon"><i class="icon-remove"></i></span>
<h5>Toggle, closed by default</h5>
</a> </div>
<div id="collapseTwo" class="collapse">
<div class="widget-content"> This box is now open </div>
</div>
<div class="widget-title"> <a data-toggle="collapse" href="#collapseThree"> <span class="icon"><i class="icon-remove"></i></span>
<h5>Toggle, closed by default</h5>
</a> </div>
<div id="collapseThree" class="collapse">
<div class="widget-content"> This box is now open </div>
</div>
</div>
<div class="widget-box">
<div class="widget-title">
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#tab1">Tab1</a></li>
<li><a data-toggle="tab" href="#tab2">Tab2</a></li>
<li><a data-toggle="tab" href="#tab3">Tab3</a></li>
</ul>
</div>
<div class="widget-content tab-content">
<div id="tab1" class="tab-pane active">
<p>And is full of waffle to It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.multiple paragraphs and is full of waffle to pad out the comment.</p>
<img src="img/demo/demo-image1.jpg" alt="demo-image"/></div>
<div id="tab2" class="tab-pane"> <img src="img/demo/demo-image2.jpg" alt="demo-image"/>
<p>And is full of waffle to It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.multiple paragraphs and is full of waffle to pad out the comment.</p>
</div>
<div id="tab3" class="tab-pane">
<p>And is full of waffle to It has multiple paragraphs and is full of waffle to pad out the comment. Usually, you just wish these sorts of comments would come to an end.multiple paragraphs and is full of waffle to pad out the comment. </p>
<img src="img/demo/demo-image3.jpg" alt="demo-image"/></div>
</div>
</div>
</div>
</div>
#}
</div>
</div>
<!--end-main-container-part-->
{% block footer %}
{% include('AppBundle:Base:footer.html.twig') %}
{% endblock %}
</body>
{% endblock %}
{% block javascripts %}
<script src="{{ asset('bundles/app/js/excanvas.min.js') }}"></script>
<script src="{{ asset('bundles/app/js/jquery.min.js') }}"></script>
<script src="{{ asset('bundles/app/js/jquery.ui.custom.js') }}"></script>
<script src="{{ asset('bundles/app/js/bootstrap.min.js') }}"></script>
<script src="{{ asset('bundles/app/js/jquery.flot.min.js') }}"></script>
<script src="{{ asset('bundles/app/js/jquery.flot.resize.min.js') }}"></script>
<script src="{{ asset('bundles/app/js/jquery.peity.min.js') }}"></script>
<script src="{{ asset('bundles/app/js/fullcalendar.min.js') }}"></script>
<script src="{{ asset('bundles/app/js/matrix.js') }}"></script>
<script src="{{ asset('bundles/app/js/matrix.dashboard.js') }}"></script>
<script src="{{ asset('bundles/app/js/jquery.gritter.min.js') }}"></script>
<script src="{{ asset('bundles/app/js/matrix.interface.js') }}"></script>
<script src="{{ asset('bundles/app/js/matrix.chat.js') }}"></script>
<script src="{{ asset('bundles/app/js/jquery.validate.js') }}"></script>
<script src="{{ asset('bundles/app/js/matrix.form_validation.js') }}"></script>
<script src="{{ asset('bundles/app/js/jquery.wizard.js') }}"></script>
<script src="{{ asset('bundles/app/js/jquery.uniform.js') }}"></script>
<script src="{{ asset('bundles/app/js/select2.min.js') }}"></script>
<script src="{{ asset('bundles/app/js/matrix.popover.js') }}"></script>
<script src="{{ asset('bundles/app/js/jquery.dataTables.min.js') }}"></script>
<script src="{{ asset('bundles/app/js/matrix.tables.js') }}"></script>
<script type="text/javascript">
// This function is called from the pop-up menus to transfer to
// a different page. Ignore if the value returned is a null string:
function goPage (newURL) {
// if url is empty, skip the menu dividers and reset the menu selection to default
if (newURL != "") {
// if url is "-", it is this page -- reset the menu:
if (newURL == "-" ) {
resetMenu();
}
// else, send page to designated URL
else {
document.location.href = newURL;
}
}
}
// resets the menu selection upon entry to this page:
function resetMenu() {
document.gomenu.selector.selectedIndex = 2;
}
</script>
{% endblock %}
| 33,351
|
https://github.com/consulo/consulo-jakartaee/blob/master/javaee-api/src/main/java/com/intellij/javaee/model/xml/ejb/RemoveMethod.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
consulo-jakartaee
|
consulo
|
Java
|
Code
| 198
| 485
|
/*
* Copyright 2000-2007 JetBrains s.r.o.
*
* 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.
*/
// Generated on Mon Mar 20 14:03:07 MSK 2006
// DTD/Schema : http://java.sun.com/xml/ns/javaee
package com.intellij.javaee.model.xml.ejb;
import javax.annotation.Nonnull;
import com.intellij.javaee.model.xml.JavaeeDomModelElement;
import com.intellij.util.xml.GenericDomValue;
/**
* http://java.sun.com/xml/ns/javaee:remove-methodType interface.
*/
public interface RemoveMethod extends JavaeeDomModelElement {
/**
* Returns the value of the bean-method child.
* @return the value of the bean-method child.
*/
@Nonnull
NamedMethod getBeanMethod();
/**
* Returns the value of the retain-if-exception child.
* <pre>
* <h3>Type http://java.sun.com/xml/ns/javaee:true-falseType documentation</h3>
* This simple type designates a boolean with only two
* permissible values
* - true
* - false
* </pre>
* @return the value of the retain-if-exception child.
*/
GenericDomValue<Boolean> getRetainIfException();
}
| 15,663
|
https://github.com/wolfman199311/laravel_react.js/blob/master/app/Http/Controllers/API/PluginController.php
|
Github Open Source
|
Open Source
|
MIT
| null |
laravel_react.js
|
wolfman199311
|
PHP
|
Code
| 34
| 166
|
<?php
namespace App\Http\Controllers\API;
use App\Company;
use App\Http\Controllers\Controller;
use App\Level;
use App\UserLevel;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
class PluginController extends Controller
{
public function __construct()
{
}
public function rss(Request $request)
{
return file_get_contents('http://news.care-steps.com/~api/papers/636688ac-33a3-4342-b37e-a99f5b267568/rss');
}
}
| 16,807
|
https://github.com/blakehagen/blake-site/blob/master/src/components/TopBar/topBar.module.scss
|
Github Open Source
|
Open Source
|
MIT
| null |
blake-site
|
blakehagen
|
SCSS
|
Code
| 103
| 371
|
.headerWrapper {
background: #FFF;
border-bottom: 1px solid #EEE;
height: 50px;
width: 100%;
max-width: 1100px;
display: flex;
align-items: center;
justify-content: flex-end;
position: sticky;
top: 0;
z-index: 999;
}
.navContainer {
height: 100%;
margin-right: 20px;
display: flex;
align-items: center;
cursor: default;
.initials {
font-family: 'merriweather', serif;
font-weight: 100;
font-size: 22px;
letter-spacing: 2px;
color: #368DC0;
display: flex;
align-items: center;
padding-right: 22px;
border-right: 1px solid #DDD;
span {
font-weight: 900;
}
}
.icon {
height: 100%;
margin-left: 22px;
margin-top: 2px;
display: flex;
align-items: center;
}
a {
text-decoration: none;
color: #656565;
&:active {
text-decoration: none;
color: #656565;
}
&:visited {
text-decoration: none;
color: #656565;
}
}
}
| 26,880
|
https://github.com/13human/scala-cgdk/blob/master/src/main/scala/model/TileType.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,015
|
scala-cgdk
|
13human
|
Scala
|
Code
| 258
| 738
|
package model
/**
* Тип тайла.
*/
sealed trait TileType
object TileType {
/**
* Пустой тайл.
*/
case object EMPTY extends TileType
/**
* Тайл с прямым вертикальным участком дороги.
*/
case object VERTICAL extends TileType
/**
* Тайл с прямым горизонтальным участком дороги.
*/
case object HORIZONTAL extends TileType
/**
* Тайл выполняющий роль сочленения двух других тайлов: справа и снизу от данного тайла.
*/
case object LEFT_TOP_CORNER extends TileType
/**
* Тайл выполняющий роль сочленения двух других тайлов: слева и снизу от данного тайла.
*/
case object RIGHT_TOP_CORNER extends TileType
/**
* Тайл выполняющий роль сочленения двух других тайлов: справа и сверху от данного тайла.
*/
case object LEFT_BOTTOM_CORNER extends TileType
/**
* Тайл выполняющий роль сочленения двух других тайлов: слева и сверху от данного тайла.
*/
case object RIGHT_BOTTOM_CORNER extends TileType
/**
* Тайл выполняющий роль сочленения трёх других тайлов: слева снизу и сверху от данного тайла.
*/
case object LEFT_HEADED_T extends TileType
/**
* Тайл выполняющий роль сочленения трёх других тайлов: справа снизу и сверху от данного тайла.
*/
case object RIGHT_HEADED_T extends TileType
/**
* Тайл выполняющий роль сочленения трёх других тайлов: слева справа и сверху от данного тайла.
*/
case object TOP_HEADED_T extends TileType
/**
* Тайл выполняющий роль сочленения трёх других тайлов: слева справа и снизу от данного тайла.
*/
case object BOTTOM_HEADED_T extends TileType
/**
* Тайл выполняющий роль сочленения четырёх других тайлов: со всех сторон от данного тайла.
*/
case object CROSSROADS extends TileType
/**
* Тип тайла пока не известен.
*/
case object UNKNOWN extends TileType
}
| 1,358
|
https://github.com/Kinnara/ModernWpf/blob/master/samples/SamplesCommon/SamplePages/SamplePage5.xaml.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
ModernWpf
|
Kinnara
|
C#
|
Code
| 15
| 45
|
namespace SamplesCommon.SamplePages
{
public partial class SamplePage5
{
public SamplePage5()
{
InitializeComponent();
}
}
}
| 47,021
|
https://github.com/westmelon/leetcode/blob/master/src/main/java/com/neo/sword2offer/q24/App.java
|
Github Open Source
|
Open Source
|
MIT
| null |
leetcode
|
westmelon
|
Java
|
Code
| 63
| 178
|
package com.neo.sword2offer.q24;
import com.neo.struct.ListNode;
public class App {
public static void main(String[] args) {
ListNode head = new ListNode("a");
ListNode b = new ListNode("b");
ListNode c = new ListNode("c");
ListNode d = new ListNode("d");
ListNode e = new ListNode("e");
head.next = b;
b.next = c;
c.next = d;
d.next = e;
Solution solution = new Solution();
ListNode reserve = solution.reserve(head);
System.out.println(1);
}
}
| 20,406
|
https://github.com/the-gophers/kind-knative/blob/master/Makefile
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
kind-knative
|
the-gophers
|
Makefile
|
Code
| 759
| 2,945
|
GOPATH := $(shell go env GOPATH)
GOARCH := $(shell go env GOARCH)
GOOS := $(shell go env GOOS)
GOPROXY := $(shell go env GOPROXY)
ifeq ($(GOPROXY),)
GOPROXY := https://proxy.golang.org
endif
export GOPROXY
ROOT_DIR :=$(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))
APP = go-action
PACKAGE = github.com/the-gophers/$(APP)
DATE ?= $(shell date +%FT%T%z)
VERSION ?= $(shell git rev-list -1 HEAD)
SHORT_VERSION ?= $(shell git rev-parse --short HEAD)
GOBIN ?= $(HOME)/go/bin
GOFMT = gofmt
GO = go
PKGS = $(or $(PKG),$(shell $(GO) list ./... | grep -vE "^$(PACKAGE)/templates/"))
TOOLSBIN = $(ROOT_DIR)/tools/bin
GO_INSTALL = $(ROOT_DIR)/scripts/go_install.sh
KNATIVE_VERSION := 0.18.2
KOURIER_VERSION := 0.18.1
IMAGE := dev.local/the-gophers/knative-go
TAG := dev
# Active module mode, as we use go modules to manage dependencies
export GO111MODULE=on
V = 0
Q = $(if $(filter 1,$V),,@)
.PHONY: all
all: fmt lint tidy build test
## --------------------------------------
## Tooling Binaries
## --------------------------------------
GOLINT_VER := v1.31.0
GOLINT_BIN := golangci-lint
GOLINT := $(TOOLSBIN)/$(GOLINT_BIN)-$(GOLINT_VER)
$(GOLINT): ; $(info $(M) buiding $(GOLINT))
GOBIN=$(TOOLSBIN) $(GO_INSTALL) github.com/golangci/golangci-lint/cmd/golangci-lint $(GOLINT_BIN) $(GOLINT_VER)
GOVERALLS_VER := v0.0.7
GOVERALLS_BIN := goveralls
GOVERALLS := $(TOOLSBIN)/$(GOVERALLS_BIN)-$(GOVERALLS_VER)
$(GOVERALLS): ; $(info $(M) buiding $(GOVERALLS))
GOBIN=$(TOOLSBIN) $(GO_INSTALL) github.com/mattn/goveralls $(GOVERALLS_BIN) $(GOVERALLS_VER)
KUBECTL_VER := v1.19.1
KUBECTL_BIN := kubectl
KUBECTL := $(TOOLSBIN)/$(KUBECTL_BIN)-$(KUBECTL_VER)
$(KUBECTL):
mkdir -p $(TOOLSBIN)
rm -f "$(KUBECTL)*"
curl -fsL https://storage.googleapis.com/kubernetes-release/release/$(KUBECTL_VER)/bin/$(GOOS)/$(GOARCH)/kubectl -o $(KUBECTL)
ln -sf "$(KUBECTL)" "$(TOOLSBIN)/$(KUBECTL_BIN)"
chmod +x "$(TOOLSBIN)/$(KUBECTL_BIN)" "$(KUBECTL)"
KUSTOMIZE_VER := v3.5.4
KUSTOMIZE_BIN := kustomize
KUSTOMIZE := $(TOOLSBIN)/$(KUSTOMIZE_BIN)-$(KUSTOMIZE_VER)
$(KUSTOMIZE):
GOBIN=$(TOOLSBIN) $(GO_INSTALL) sigs.k8s.io/kustomize/kustomize/v3 $(KUSTOMIZE_BIN) $(KUSTOMIZE_VER)
ENVSUBST_VER := master
ENVSUBST_BIN := envsubst
ENVSUBST := $(TOOLSBIN)/$(ENVSUBST_BIN)
$(ENVSUBST):
GOBIN=$(TOOLSBIN) $(GO_INSTALL) github.com/drone/envsubst/cmd/envsubst $(ENVSUBST_BIN) $(ENVSUBST_VER)
## --------------------------------------
## Tilt / Kind
## --------------------------------------
build: lint tidy ; $(info $(M) buiding ./bin/$(APP))
$Q $(GO) build -ldflags "-X $(PACKAGE)/cmd.GitCommit=$(VERSION)" -o ./bin/$(APP)
.PHONY: lint
lint: $(GOLINT) ; $(info $(M) running golanci-lint…) @ ## Run golangci-lint
$(Q) $(GOLINT) run ./...
.PHONY: fmt
fmt: ; $(info $(M) running gofmt…) @ ## Run gofmt on all source files
@ret=0 && for d in $$($(GO) list -f '{{.Dir}}' ./...); do \
$(GOFMT) -l -w $$d/*.go || ret=$$? ; \
done ; exit $$ret
.PHONY: vet
vet: ; $(info $(M) running vet…) @ ## Run vet
$Q $(GO) vet ./...
.PHONY: tidy
tidy: ; $(info $(M) running tidy…) @ ## Run tidy
$Q $(GO) mod tidy
.PHONY: build-debug
build-debug: ; $(info $(M) buiding debug...)
$Q $(GO) build -o ./bin/$(APP) -tags debug
.PHONY: test
test: ; $(info $(M) running go test…)
$(Q) $(GO) test ./... -tags=noexit
.PHONY: test-cover
test-cover: $(GOVERALLS) ; $(info $(M) running go test…)
$(Q) $(GO) test -tags=noexit -race -covermode atomic -coverprofile=profile.cov ./...
$(Q) $(GOVERALLS) -coverprofile=profile.cov -service=github
.PHONY: ci
ci: fmt lint vet tidy test-cover
.PHONE: test-e2e
test-e2e: deploy-knative
## --------------------------------------
## Tilt / Kind
## --------------------------------------
.PHONY: kind-create
kind-create: ; $(info $(M) create knative kind cluster if needed…)
./scripts/kind-without-local-registry.sh
.PHONY: tilt-up
tilt-up: $(KUSTOMIZE) kind-create deploy-knative ; $(info $(M) start tilt and build kind cluster if needed…)
tilt up
.PHONY: kind-reset
kind-reset: ; $(info $(M) delete local kind cluster…)
kind delete cluster --name=knative || true
.PHONY: kind-deploy-app
kind-deploy-app: $(KUSTOMIZE) $(KUBECTL) $(ENVSUBST) docker-build ; $(info $(M) deploying knative app…)
kind load docker-image --name knative $(IMAGE):$(TAG)
IMAGE=$(IMAGE) TAG=$(TAG) $(ENVSUBST) < ./config/image-patch-template.yml > ./test/config/image-patch.yml
$(KUSTOMIZE) build ./test/config | $(KUBECTL) apply -f -
$(KUBECTL) wait ksvc helloworld-go --all --timeout=-1s --for=condition=Ready
## --------------------------------------
## KNative
## --------------------------------------
.PHONY: deploy-knative
deploy-knative: deploy-knative-serving deploy-kourier ; $(info $(M) deploying knative…)
.PHONY: deploy-knative-serving
deploy-knative-serving: $(KUBECTL) ; $(info $(M) deploying knative serving CRDs and core components…)
$(KUBECTL) apply -f https://github.com/knative/serving/releases/download/v$(KNATIVE_VERSION)/serving-crds.yaml
$(KUBECTL) apply -f https://github.com/knative/serving/releases/download/v$(KNATIVE_VERSION)/serving-core.yaml
$(KUBECTL) wait deployment --all --timeout=-1s --for=condition=Available -n knative-serving
.PHONY: deploy-kourier
deploy-kourier: $(KUBECTL) ; $(info $(M) deploying kourier components…)
$(KUBECTL) apply -f https://github.com/knative/net-kourier/releases/download/v$(KOURIER_VERSION)/kourier.yaml
$(KUBECTL) wait deployment --all --timeout=-1s --for=condition=Available -n kourier-system
# deployment for net-kourier gets deployed to namespace knative-serving
$(KUBECTL) wait deployment --all --timeout=-1s --for=condition=Available -n knative-serving
$(KUBECTL) patch configmap -n knative-serving config-domain -p "{\"data\": {\"127.0.0.1.nip.io\": \"\"}}"
$(KUBECTL) apply -f ./config/kourier-listen.yml
$(KUBECTL) patch configmap/config-network -n knative-serving --type merge --patch '{"data":{"ingress.class":"kourier.ingress.networking.knative.dev"}}'
$(KUBECTL) patch configmap/config-deployment -n knative-serving --type merge --patch '{"data":{"registriesSkippingTagResolving":"dev.local"}}'
.PHONY: status-knative
status-knative: $(KUBECTL) ; $(info $(M) getting knative status…)
$(KUBECTL) get pods -n knative-serving
$(KUBECTL) get pods -n kourier-system
$(KUBECTL) get svc kourier-ingress -n kourier-system
.PHONY: deploy-knative-helloworld
deploy-knative-helloworld: $(KUBECTL) ; $(info $(M) deploying helloworld…)
$(KUBECTL) apply -f ./config/knative-helloworld.yml
$(KUBECTL) wait ksvc hello --all --timeout=-1s --for=condition=Ready
curl $$($(KUBECTL) get ksvc hello -o jsonpath='{.status.url}')
.PHONY: helloworld-url
helloworld-url: $(KUBECTL)
$(Q) $(KUBECTL) get ksvc hello -o jsonpath='{.status.url}'
.PHONY: dev-url
dev-url: $(KUBECTL)
$(Q) $(KUBECTL) get ksvc helloworld-go -o jsonpath='{.status.url}'
## --------------------------------------
## Docker
## --------------------------------------
.PHONY: docker-build
docker-build: ; $(info $(M) docker build…)
docker build . -t $(IMAGE):$(TAG)
.PHONY: docker-push
docker-push: ; $(info $(M) docker push…)
docker push $(IMAGE):$(TAG)
## --------------------------------------
## Test
## --------------------------------------
.PHONY: test-e2e
test-e2e: kind-deploy-app ; $(info $(M) deploying to kind and running tests…)
curl $$($(KUBECTL) get ksvc helloworld-go -o jsonpath='{.status.url}')
| 19,068
|
https://github.com/saltyrtc/saltyrtc-client-js/blob/master/src/signaling/handoverstate.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
saltyrtc-client-js
|
saltyrtc
|
TypeScript
|
Code
| 200
| 430
|
/**
* Copyright (C) 2016-2018 Threema GmbH
*
* This software may be modified and distributed under the terms
* of the MIT license. See the `LICENSE.md` file for details.
*/
export class HandoverState {
private _local: boolean;
private _peer: boolean;
constructor() {
this.reset();
}
public get local(): boolean {
return this._local;
}
public set local(state: boolean) {
const wasBoth = this.both;
this._local = state;
if (!wasBoth && this.both && this.onBoth !== undefined) {
this.onBoth();
}
}
public get peer(): boolean {
return this._peer;
}
public set peer(state: boolean) {
const wasBoth = this.both;
this._peer = state;
if (!wasBoth && this.both && this.onBoth !== undefined) {
this.onBoth();
}
}
/**
* Return true if both peers have finished the handover.
*/
public get both(): boolean {
return this._local === true && this._peer === true;
}
/**
* Return true if any peer has finished the handover.
*/
public get any(): boolean {
return this._local === true || this._peer === true;
}
/**
* Reset handover state.
*/
public reset() {
this._local = false;
this._peer = false;
}
/**
* Callback that is called when both local and peer have done the
* handover.
*/
public onBoth: () => void;
}
| 22,627
|
https://github.com/hyorek/IMIESHPERE/blob/master/application/controleurs/addEventControler.php
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
IMIESHPERE
|
hyorek
|
PHP
|
Code
| 98
| 232
|
<?php
class addEventController {
public function addEvent() {
require_once ("/application/models/addEventModel.php");
$addEvent = new addEventModel ();
require_once ("/application/views/IMIE/addEvent.php");
if (isset ( $_POST ['nameEvent'] ) && isset ( $_POST ['streeNumber'] ) && isset ( $_POST ['addressEvent'] ) && isset ( $_POST ['villeEvent'] ) && isset ( $_POST ['codePostal'] ) && isset ( $_POST ['place'] ) && isset ( $_POST ['dateStart'] ) && isset ( $_POST ['prixAll'] ) && isset ( $_POST ['descEvent'] ) && isset ( $_POST ['dateEnd'] ) && isset ( $_POST ['nbPlace'] ) && isset ( $_POST ['place'] )) {
$reqaddEvent = $addEvent->getaddEvent ();
}
}
}
?>
| 41,183
|
https://github.com/selarassolusindo/sia2/blob/master/application/modules/t01_package/models/T01_package_model.php
|
Github Open Source
|
Open Source
|
MIT
| null |
sia2
|
selarassolusindo
|
PHP
|
Code
| 259
| 1,460
|
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class T01_package_model extends CI_Model
{
public $table = 't01_package';
public $id = 'idprice';
public $order = 'ASC';
function __construct()
{
parent::__construct();
$this->db = $this->load->database('TAMU', true);
}
// get all
function get_all()
{
$this->db->order_by($this->id, $this->order);
return $this->db->get($this->table)->result();
}
// get data by id
function get_by_id($id)
{
$this->db->where($this->id, $id);
return $this->db->get($this->table)->row();
}
// get total rows
function total_rows($q = NULL) {
$this->db->like('idprice', $q);
$this->db->or_like('PackageName', $q);
$this->db->or_like('PackageCode', $q);
$this->db->or_like('SN3LN', $q);
$this->db->or_like('SN6LN', $q);
$this->db->or_like('SNELN', $q);
$this->db->or_like('PN1LN', $q);
$this->db->or_like('PN1DN', $q);
$this->db->or_like('SN3C', $q);
$this->db->or_like('SN3CP', $q);
$this->db->or_like('SN6C', $q);
$this->db->or_like('SN6CP', $q);
$this->db->or_like('SNEC', $q);
$this->db->or_like('SNECP', $q);
$this->db->or_like('PN3C', $q);
$this->db->or_like('PN3CP', $q);
$this->db->or_like('PN6C', $q);
$this->db->or_like('PN6CP', $q);
$this->db->or_like('PNEC', $q);
$this->db->or_like('PNECP', $q);
$this->db->or_like('created_at', $q);
$this->db->or_like('updated_at', $q);
$this->db->from($this->table);
return $this->db->count_all_results();
}
// get data with limit and search
function get_limit_data($limit, $start = 0, $q = NULL) {
$this->db->order_by($this->id, $this->order);
$this->db->like('idprice', $q);
$this->db->or_like('PackageName', $q);
$this->db->or_like('PackageCode', $q);
$this->db->or_like('SN3LN', $q);
$this->db->or_like('SN6LN', $q);
$this->db->or_like('SNELN', $q);
$this->db->or_like('PN1LN', $q);
$this->db->or_like('PN1DN', $q);
$this->db->or_like('SN3C', $q);
$this->db->or_like('SN3CP', $q);
$this->db->or_like('SN6C', $q);
$this->db->or_like('SN6CP', $q);
$this->db->or_like('SNEC', $q);
$this->db->or_like('SNECP', $q);
$this->db->or_like('PN3C', $q);
$this->db->or_like('PN3CP', $q);
$this->db->or_like('PN6C', $q);
$this->db->or_like('PN6CP', $q);
$this->db->or_like('PNEC', $q);
$this->db->or_like('PNECP', $q);
$this->db->or_like('created_at', $q);
$this->db->or_like('updated_at', $q);
$this->db->limit($limit, $start);
return $this->db->get($this->table)->result();
}
// insert data
function insert($data)
{
$this->db->insert($this->table, $data);
}
// update data
function update($id, $data)
{
$this->db->where($this->id, $id);
$this->db->update($this->table, $data);
}
// delete data
function delete($id)
{
$this->db->where($this->id, $id);
$this->db->delete($this->table);
}
// get data by name
function getByCode($code)
{
$this->db->where('PackageCode', $code);
return $this->db->get($this->table)->row();
}
}
/* End of file T01_package_model.php */
/* Location: ./application/models/T01_package_model.php */
/* Please DO NOT modify this information : */
/* Generated by Harviacode Codeigniter CRUD Generator 2021-04-01 10:15:08 */
/* http://harviacode.com */
| 17,862
|
https://github.com/bnomei/kirby3-stopwatch/blob/master/vendor/composer/autoload_psr4.php
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
kirby3-stopwatch
|
bnomei
|
PHP
|
Code
| 40
| 181
|
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Symfony\\Contracts\\Service\\' => array($vendorDir . '/symfony/service-contracts'),
'Symfony\\Component\\Stopwatch\\' => array($vendorDir . '/symfony/stopwatch'),
'Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
'Kirby\\' => array($vendorDir . '/getkirby/composer-installer/src'),
'Bnomei\\' => array($baseDir . '/classes'),
);
| 39,884
|
https://github.com/manacespereira/upstart-weather-ui/blob/master/src/pages/HomePage/components/Weather/styles.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
upstart-weather-ui
|
manacespereira
|
TypeScript
|
Code
| 15
| 40
|
import styled from 'styled-components';
export const Container = styled.div`
button {
margin-top: 15px;
}
`;
| 18,762
|
https://github.com/Huxx0804/gibbon_lib/blob/master/gibbon/maps/_building_map.py
|
Github Open Source
|
Open Source
|
MIT
| null |
gibbon_lib
|
Huxx0804
|
Python
|
Code
| 211
| 808
|
import uuid
import json
import pandas as pd
import numpy as np
from gibbon.utility import Convert
class Buildings:
def __init__(self, sensor, path=None):
self.sensor = sensor
self.df = None
self.selected = None
if path:
self.load_dataframe(path)
def load_dataframe(self, path):
buildings = list()
with open(path, 'r', encoding='utf-8') as f:
data = json.load(f)
features = data['features']
for f in features:
try:
floors = f['properties']['Floor']
coords = f['geometry']['coordinates'][0][0][:-1]
building = {'coords': coords, 'floors': floors}
buildings.append(building)
except Exception as e:
pass
uids = [uuid.uuid4() for i in range(len(buildings))]
df = pd.DataFrame(buildings, index=uids)
f = np.vectorize(lambda a, b: np.average(np.array(a), axis=0).tolist()[b])
df['lng'], df['lat'] = f(df['coords'], 0), f(df['coords'], 1)
self.df = df
def create(self):
def f(lnglats):
return [Convert.lnglat_to_mercator(ll, self.sensor.origin) for ll in lnglats]
if self.df is not None:
selected = self.df[
(self.df['lng'] > self.sensor.llbounds[0][0]) &
(self.df['lng'] < self.sensor.llbounds[1][0]) &
(self.df['lat'] > self.sensor.llbounds[0][1]) &
(self.df['lat'] < self.sensor.llbounds[1][1])
]
selected['position'] = selected['coords'].apply(f)
selected['height'] = selected['floors'] * 3000
self.selected = selected
@property
def extrusion(self):
return [
{
'tp': 'extrude',
'l': data['position'],
'h': data['height']
} for i, data in self.selected.iterrows()
]
def dump_extrusion(self, path):
with open(path, 'w', encoding='utf-8') as f:
json.dump(self.extrusion, f)
if __name__ == '__main__':
from gibbon.maps import MapSensor
path = r'F:\02_projects\YangDaShiTouBiao\geojson\Changsha.geojson'
path_out = r'F:\02_projects\YangDaShiTouBiao\geojson\YangDaShiTouBiao.json'
origin = [113.058780, 28.201170]
radius = 2000
sensor = MapSensor(origin, radius)
bmap = Buildings(sensor, path)
print(bmap.df)
bmap.create()
bmap.dump_extrusion(path_out)
| 41,746
|
https://github.com/ucd-library/wine-price-extraction/blob/master/ark_87287/d7c889/d7c889-008/rotated.r
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
wine-price-extraction
|
ucd-library
|
R
|
Code
| 3
| 86
|
r=358.90
https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7c889/media/images/d7c889-008/svc:tesseract/full/full/358.90/default.jpg Accept:application/hocr+xml
| 32,578
|
https://github.com/goldmansachs/reladomo/blob/master/reladomo/src/main/java/com/gs/fw/common/mithra/attribute/calculator/arithmeticCalculator/TimestampDayOfMonthCalculator.java
|
Github Open Source
|
Open Source
|
Apache-2.0, BSD-3-Clause, MIT, LicenseRef-scancode-public-domain
| 2,023
|
reladomo
|
goldmansachs
|
Java
|
Code
| 237
| 837
|
/*
Copyright 2016 Goldman Sachs.
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.gs.fw.common.mithra.attribute.calculator.arithmeticCalculator;
import com.gs.fw.common.mithra.attribute.CalculatedIntegerAttribute;
import com.gs.fw.common.mithra.attribute.TimestampAttribute;
import com.gs.fw.common.mithra.finder.Operation;
import com.gs.fw.common.mithra.finder.SqlQuery;
import com.gs.fw.common.mithra.finder.ToStringContext;
import com.gs.fw.common.mithra.finder.integer.IntegerEqOperation;
import org.joda.time.DateTime;
import java.sql.Timestamp;
public class TimestampDayOfMonthCalculator extends SingleAttributeNumericCalculator<TimestampAttribute>
{
public TimestampDayOfMonthCalculator(TimestampAttribute timestampAttribute)
{
super(timestampAttribute);
}
@Override
public String getFullyQualifiedCalculatedExpression(SqlQuery query)
{
int conversion;
if(attribute.requiresConversionFromUtc())
{
conversion = TimestampAttribute.CONVERT_TO_UTC;
}
else if(attribute.requiresConversionFromDatabaseTime())
{
conversion = TimestampAttribute.CONVERT_TO_DATABASE;
}
else
{
conversion = TimestampAttribute.CONVERT_NONE;
}
return "(" + query.getDatabaseType().getSqlExpressionForTimestampDayOfMonth(attribute.getFullyQualifiedLeftHandExpression(query), conversion, query.getTimeZone()) + ")";
}
@Override
public int intValueOf(Object o)
{
Timestamp timestamp = this.attribute.valueOf(o);
DateTime time = new DateTime(timestamp.getTime());
return time.getDayOfMonth();
}
@Override
public int getScale()
{
return 0;
}
@Override
public int getPrecision()
{
return 2;
}
@Override
public void appendToString(ToStringContext toStringContext)
{
toStringContext.append("dayOfMonth(");
this.attribute.zAppendToString(toStringContext);
toStringContext.append(")");
}
@Override
public Operation optimizedIntegerEq(int value, CalculatedIntegerAttribute intAttribute)
{
return new IntegerEqOperation(intAttribute, value);
}
public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj.getClass().equals(this.getClass()))
{
return this.attribute.equals(((TimestampDayOfMonthCalculator)obj).attribute);
}
return false;
}
public int hashCode()
{
return 0x56781234 ^ this.attribute.hashCode();
}
}
| 41,702
|
https://github.com/matesglobal-spec/freshexport.com.au/blob/master/application/views/index.php
|
Github Open Source
|
Open Source
|
MIT, LicenseRef-scancode-unknown-license-reference
| 2,019
|
freshexport.com.au
|
matesglobal-spec
|
PHP
|
Code
| 1,003
| 5,330
|
<!-- =====Quick view ============================ -->
<!--<div class="product-view-modal modal fade bd-example-modal-lg-product-1" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="row">
<div class="product-gallery col-12 col-md-12 col-lg-6">
<div class="row">
<div class="col-md-12 product-slier-details">
<div id="product-view-model" class="product-view owl-carousel owl-theme">
<div class="item">
<img src="<?=base_url()?>assets/img/product-img/pro13-a.jpg" class="img-fluid" alt="Product Img">
</div>
<div class="item">
<img src="<?=base_url()?>assets/img/product-img/pro13-b.jpg" class="img-fluid" alt="Product Img">
</div>
</div>
</div>
</div>
</div>
<div class="col-6 col-12 col-md-12 col-lg-6">
<div class="product-details-gallery">
<div class="list-group">
<h4 class="list-group-item-heading product-title">
Product Name3695
</h4>
<div class="media">
<div class="media-left media-middle">
<div class="rating">
<a href="#"><i class="fa fa-star active-color" aria-hidden="true"></i></a>
<a href="#"><i class="fa fa-star active-color" aria-hidden="true"></i></a>
<a href="#"><i class="fa fa-star active-color" aria-hidden="true"></i></a>
<a href="#"><i class="fa fa-star-o" aria-hidden="true"></i></a>
<a href="#"><i class="fa fa-star-o" aria-hidden="true"></i></a>
</div>
</div>
<div class="media-body">
<p>3.7/5 <span class="product-ratings-text"> -1747 Ratings</span></p>
</div>
</div>
</div>
<div class="list-group content-list">
<p><i class="fa fa-dot-circle-o" aria-hidden="true"></i> 100% Original product</p>
<p><i class="fa fa-dot-circle-o" aria-hidden="true"></i> Manufacturer Warranty</p>
</div>
<table class="table table-responsive">
<tr>
<th>Product Name</th>
<th>Price</th>
<th>Quality</th>
<th>Availability</th>
<th>Place</th>
</tr>
<tr>
<td><a href="">Pro68</a></td>
<td>$10</td>
<td>G-D</td>
<td>in stock</td>
<td>Perth</td>
</tr>
<tr>
<td><a href="">Pro54</a></td>
<td>$12</td>
<td>G-C</td>
<td>2-Remaining</td>
<td>Brisbane</td>
</tr>
<tr>
<td><a href="">Pro354</a></td>
<td>$20</td>
<td>G-B</td>
<td>sold out</td>
<td>Adelaide</td>
</tr>
<tr>
<td><a href="">Pro24</a></td>
<td>$25</td>
<td>G-A</td>
<td>1-Remaining</td>
<td>Sydney</td>
</tr>
</table>
</div>
<div class="product-store row">
</div>
</div>
</div>
</div>
</div>
</div>-->
<!-- =====Quick view ============================ -->
<section class="wd-service">
<div class="container-fluid custom-width">
<div class="row">
<div class="col-md-12 col-lg-4 col-xl-4 wow fadeIn animated" data-wow-delay="0.2s">
<ul class="list-unstyled">
<a href="<?=base_url()?>compare">
<li class="media">
<img class="d-flex mr-3" src="<?=base_url()?>assets/img/compare-icon.png" alt="compare-icon">
<div class="media-body">
<h5 class="wd-service-title mt-0 mb-1">Lets Compare</h5>
<p>Choose your product with price comparisons make your best deal today</p>
</div>
</li>
</a>
</ul>
</div>
<div class="col-md-12 col-lg-4 col-xl-4 wow fadeIn animated" data-wow-delay="0.4s">
<ul class="list-unstyled">
<a href="<?=base_url()?>review">
<li class="media">
<img class="d-flex mr-3" src="<?=base_url()?>assets/img/review-icon.png" alt="compare-icon">
<div class="media-body">
<h5 class="wd-service-title mt-0 mb-1">Take Review</h5>
<p>Choose your product with price comparisons make your best deal today</p>
</div>
</li>
</a>
</ul>
</div>
<div class="col-md-12 col-lg-4 col-xl-4 wow fadeIn animated" data-wow-delay="0.6s">
<ul class="list-unstyled">
<a href="<?=base_url()?>vendor">
<li class="media">
<img class="d-flex mr-3" src="<?=base_url()?>assets/img/store-icon.png" alt="compare-icon">
<div class="media-body">
<h5 class="wd-service-title mt-0 mb-1">Choose Multi-Vendor Store</h5>
<p>Choose your product with price comparisons make your best deal today</p>
</div>
</li>
</a>
</ul>
</div>
</div>
</div>
</section>
<section id="recent-product" class="recent-pro-2">
<div class="container-fluid custom-width">
<div class="row">
<div class="col-md-12 text-center">
<h2 class="recent-product-title">Recent Products</h2>
</div>
<?php foreach ($products as $key => $product) { ?>
<div class="col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2 wow fadeIn animated" data-wow-delay="100ms">
<div class="recent-product-box">
<div class="recent-product-img">
<a href="<?=base_url()?>home/single/<?=$product->id;?>"><img src="<?=base_url()?>uploads/products/<?=$product->imgpath;?>" class="img-fluid" alt="recent-product img"></a>
<span class="badge badge-secondary wd-badge text-uppercase">New</span>
<div class="recent-product-info">
<div class="d-flex justify-content-between" style="text-align:center;">
<div class="recent-price">
<center><?=$this->db->get_where('subsubcategories', array('status'=>1, 'id'=>$product->subsubid))->row()->name;?> <br> $<?=$product->currentPrice;?></center>
</div>
</div>
<div class="recente-product-content">
</div>
<div class="recent-product-meta-link">
<a href="<?=base_url()?>home/single/<?=$product->id;?>"><i class="fa fa-star active-color" aria-hidden="true"></i><strong>4.5</strong></a>
<a href="#"><i class="fa fa-comments-o" aria-hidden="true"></i>145</a>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
<div class="row">
<div class="col-xs-4 col-sm-4 col-md-4 text-center" style="text-align:center"></div>
<div class="col-xs-4 col-sm-4 col-md-4 text-center" style="text-align:center">
<center>
<?=$links;?>
</center>
</div>
<div class="col-xs-4 col-sm-4 col-md-4 text-center" style="text-align:center"></div>
</div>
</div>
</section>
<section id="amazon-review">
<div class="container-fluid custom-width">
<div class="amazon-review-box-area">
<div class="row m0 justify-content-center ">
<div class="col-md-12 p0 ">
<div class="amazon-review-title">
<h6>Best review of the week</h6>
</div>
</div>
<div class="col-12 col-md-6 col-lg-4 p0 amazon-review-box wow fadeIn animated" data-wow-delay="0.2s">
<div class="media">
<div class="row">
<div class="col-sm-4 col-md-5">
<img class="img-fluid" src="<?=base_url()?>assets/img/product-img/pro.jpg" alt="Generic placeholder image">
</div>
<div class="col-sm-8 col-md-7 p0 d-flex align-items-center">
<div class="amazon-review-box-content">
<div class="rating">
<a href="#"><i class="fa fa-star active-color" aria-hidden="true"></i></a>
<a href="#"><i class="fa fa-star active-color" aria-hidden="true"></i></a>
<a href="#"><i class="fa fa-star active-color" aria-hidden="true"></i></a>
<a href="#"><i class="fa fa-star active-color" aria-hidden="true"></i></a>
<a href="#"><i class="fa fa-star active-color" aria-hidden="true"></i></a>
</div>
<h6 class="amazon-review-box-title">ProductName584</h6>
<p class="amazon-review-content">IMPRESSIVE SOUND QUALITY IS THE ULTIOAL & assive noise isolating, NOT active noise cancellation(ANC).</p>
<div class="price">
</div>
<a href="<?=base_url()?>home/single" class="btn btn-primary amazon-details">Details <i class="fa fa-arrow-right" aria-hidden="true"></i></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="offer-time">
<div class="container-fluid custom-width">
<div class="row">
<div class="col-12 col-md-12 col-lg-12 col-xl-6 wow fadeInLeft animated" data-wow-delay="300ms">
<div class="offer-time-box">
<div class="row">
<div class="col-sm-5 col-md-6">
<img src="<?=base_url()?>assets/img/product-img/pro16.jpg" alt="offer img" class="offer-img">
</div>
<div class="col-sm-7 col-md-6 d-flex align-items-center">
<div class="offer-content">
<p class="offer-brand-name">Fruits</p>
<h2 class="offer-title">SALE 75% <span>OFF</span></h2>
<p class="offer-price">At $199 - Only for today</p>
<div class='countdown' data-date="2018-12-31"></div>
<div class="offer-btn offer-btn-primary">
<a href="#" class="btn btn-primary wd-shop-btn">
Go to <img src="<?=base_url()?>assets/img/offer-ebay-btn.png" alt="">
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-12 col-md-12 col-lg-12 col-xl-6 wow fadeInRight animated" data-wow-delay="300ms">
<div class="offer-time-box">
<div class="row">
<div class="col-sm-5 col-md-6">
<img src="<?=base_url()?>assets/img/product-img/pro17.jpg" alt="offer img" class="offer-img">
</div>
<div class="col-sm-7 col-md-6 d-flex align-items-center">
<div class="offer-content">
<p class="offer-brand-name">Vegetables</p>
<h2 class="offer-title">SALE 75% <span>OFF</span></h2>
<p class="offer-price">At $199 - Only for today</p>
<div class='countdown' data-date="2018-12-31"></div>
<div class="offer-btn offer-btn-green">
<a href="#" class="btn btn-primary green-btn">
Go to <img src="<?=base_url()?>assets/img/offer-ebay-btn1.png" alt="">
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- =========================
Blog Section
============================== -->
<section id="wd-news">
<div class="container-fluid custom-width">
<div class="row">
<div class="col-md-12 text-center">
<h2 class="news-title">Weekly Top News</h2>
</div>
<?php foreach ($blogsPost as $key => $post) { ?>
<div class="col-12 col-sm-6 col-md-6 col-lg-6 col-xl-3 wow fadeIn animated" data-wow-delay="300ms">
<div class="wd-news-box">
<figure class="figure">
<figcaption></figcaption>
<img src="<?=base_url()?>assets/img/blog/<?=$post['imgpath'];?>" class="figure-img img-fluid rounded" alt="news-img">
<div class="wd-news-info">
<div class="figure-caption"><a href="<?=base_url();?>single_blog/<?=$post['id'];?>"><?=$post['title'];?></a></div>
<p class="wd-news-content"><?=$post['descriptions'];?></p>
<a href="<?=base_url();?>single_blog/<?=$post['id'];?>" class="badge badge-light wd-news-more-btn">Read More <i class="fa fa-arrow-right" aria-hidden="true"></i></a>
</div>
<span class="angle-right-to-left"></span>
</figure>
</div>
</div>
<?php } ?>
<!--<div class="col-12 col-sm-6 col-md-6 col-lg-6 col-xl-3 wow fadeIn animated" data-wow-delay="600ms">
<div class="wd-news-box">
<figure class="figure">
<figcaption></figcaption>
<img src="<?=base_url()?>assets/img/blog/news-img-2.jpg" class="figure-img img-fluid rounded" alt="news-img">
<div class="wd-news-info">
<div class="figure-caption"><a href="single_blog.php">Top 10 affiliate themes and templates you get from ThemeIM</a></div>
<p class="wd-news-content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perspiciatis esse eligendi consectetur dicta minus placeat natus tempora dignissim</p>
<a href="" class="badge badge-light wd-news-more-btn">Read More <i class="fa fa-arrow-right" aria-hidden="true"></i></a>
</div>
<span class="angle-left-to-right"></span>
</figure>
</div>
</div>
<div class="col-12 col-sm-6 col-md-6 col-lg-6 col-xl-3 wow fadeIn animated" data-wow-delay="900ms">
<div class="wd-news-box">
<figure class="figure">
<figcaption></figcaption>
<img src="<?=base_url()?>assets/img/blog/news-img-3.jpg" class="figure-img img-fluid rounded" alt="news-img">
<div class="wd-news-info">
<div class="figure-caption"><a href="single_blog.php">Make pixel perfect design and development from ThemeIM</a></div>
<p class="wd-news-content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perspiciatis esse eligendi consectetur dicta minus placeat natus tempora dignissim</p>
<a href="single_blog.php" class="badge badge-light wd-news-more-btn">Read More <i class="fa fa-arrow-right" aria-hidden="true"></i></a>
</div>
<span class="angle-right-to-left"></span>
</figure>
</div>
</div>
<div class="col-12 col-sm-6 col-md-6 col-lg-6 col-xl-3 wow fadeIn animated" data-wow-delay="1200ms">
<div class="wd-news-box">
<figure class="figure">
<figcaption></figcaption>
<img src="<?=base_url()?>assets/img/blog/news-img-4.jpg" class="figure-img img-fluid rounded" alt="news-img">
<div class="wd-news-info">
<div class="figure-caption"><a href="single_blog.php">Best US top catagories affiliate product list from BLURB Theme</a></div>
<p class="wd-news-content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perspiciatis esse eligendi consectetur dicta minus placeat natus tempora dignissim</p>
<a href="single_blog.php" class="badge badge-light wd-news-more-btn">Read More <i class="fa fa-arrow-right" aria-hidden="true"></i></a>
</div>
<span class="angle-left-to-right"></span>
</figure>
</div>
</div>-->
</div>
</div>
</section>
| 8,922
|
https://github.com/j-u-p-iter/form-base/blob/master/src/packages/form-base/modules/reducers/createFormBaseReducer.js
|
Github Open Source
|
Open Source
|
MIT
| null |
form-base
|
j-u-p-iter
|
JavaScript
|
Code
| 177
| 482
|
import invariant from 'invariant';
import { formBaseActions } from '../actions';
import { formBaseRowActions } from '../actions';
const updateState = (state, formType, dataToUpdate) => ({
...state,
[formType]: { ...state[formType], ...dataToUpdate },
});
const setState = (state, formType, stateToSet) => ({
...state,
[formType]: stateToSet,
});
const actionsRunner = {
[formBaseActions.INIT_FORM]: (state, { type, data }) => {
return state;
},
[formBaseActions.SUBMIT_FORM]: (state, { formType }) => {
return updateState(state, formType, { errors: [] });
},
[formBaseActions.RESET_FORM]: (state, { formType }, initialState) => {
return setState(state, formType, initialState[formType]);
},
[formBaseActions.SUBMIT_FORM_WITH_SUCCESS]: (state, { formType, result }) => {
return updateState(state, formType, { result });
},
[formBaseActions.SUBMIT_FORM_WITH_ERRORS]: (state, { formType, errors }) => {
return updateState(state, formType, { errors });
},
[formBaseRowActions.CHANGE_FIELD]: (state, { formType, name, value }) => {
return updateState(state, formType, { [name]: value });
},
};
const createFormBaseReducer = initialState => {
invariant(initialState, 'Initial state should be passed.');
const formBaseReducer = (state = initialState, { type, payload }) => {
const actionRunner = actionsRunner[type];
return actionRunner ? actionRunner(state, payload, initialState) : state;
};
return formBaseReducer;
};
export default createFormBaseReducer;
| 49,711
|
https://github.com/BigCatBrother/TableViewUnfold/blob/master/TableViewCell_openAndClosedemo/ViewController.m
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
TableViewUnfold
|
BigCatBrother
|
Objective-C
|
Code
| 628
| 3,283
|
//
// ViewController.m
// TableViewCell_openAndClosedemo
//
// Created by qianfeng on 15/11/25.
// Copyright © 2015年 qianfeng. All rights reserved.
//
#import "ViewController.h"
#import "MyTableViewCell.h"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
UITableView *_tableView;
NSMutableArray *_origionArr;
NSArray *_arr0;
NSArray *_arr1;
NSArray *_arr2;
NSInteger selectSection;// 第一次选中的section
NSInteger oldSection; // 旧的section
}
@end
@implementation ViewController
#define RGBACOLOR(r,g,b,a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
- (void)viewDidLoad {
[super viewDidLoad];
[self initData];
[self makeTableView];
}
-(void)initData{
self.view.backgroundColor =[UIColor redColor];
_origionArr =[[NSMutableArray alloc] initWithCapacity:0];
selectSection =0;
oldSection = 0;
// 展示数据源
_arr0 =@[@"数据源0",@"数据源1",@"数据源2",@"数据源3"];
_arr1 =@[@"数据源4",@"数据源5",@"数据源6",@"数据源7"];
_arr2 =@[@"数据源8",@"数据源9",@"数据源10",@"数据源11"];
[_origionArr addObject:_arr0];
[_origionArr addObject:_arr1];
[_origionArr addObject:_arr2];
}
-(void)makeTableView{
_tableView =[[UITableView alloc] initWithFrame:CGRectMake(0,64,self.view.frame.size.width, self.view.frame.size.height)];
_tableView.backgroundColor =[UIColor whiteColor];
_tableView.delegate =self;
_tableView . sectionFooterHeight = 1.0;
_tableView.dataSource =self;
[self.view addSubview:_tableView];
UIView *footView = [[UIView alloc] init];
_tableView.tableFooterView = footView;
}
#pragma mark - TableView Delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return _origionArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
// 这个地方要全部加载进去 要不然单独刷新某Section时会崩溃 使用`heightForRowAtIndexPath`代理方法来控制展开与关闭
NSArray *array =[_origionArr objectAtIndex:section];
return array.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 55;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
CGFloat result = 0;
UIScrollView *scrollView=(UIScrollView*)[self.view viewWithTag:selectSection+1000];
if(selectSection == indexPath.section) {
if(scrollView.contentOffset.y ==40){
result = 0;
}else{
result = 30;
}
}else{
result = 0;
}
return result;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
CGFloat headerHeight = 55;
UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, headerHeight)];
[headerView setBackgroundColor:[UIColor whiteColor]];
// 选择头View
UIView *selectView =[[UIView alloc] initWithFrame:CGRectMake(10, 15, SCREEN_WIDTH-20,40)];
selectView.layer.masksToBounds=YES;
selectView.layer.cornerRadius =3.0f;
selectView.tag =7000+section;
[headerView addSubview:selectView];
if(selectSection !=section){
selectView.layer.borderColor =RGBACOLOR(187, 187, 187, 1).CGColor;
selectView.layer.borderWidth=1.0f;
}else{
selectView.layer.borderColor =RGBACOLOR(29, 187, 214, 1).CGColor;
selectView.layer.borderWidth=1.0f;
}
// 图片背景
UIView *imageBackView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
if(selectSection!=section){
imageBackView.backgroundColor =RGBACOLOR(187, 187, 187, 1);
}else{
imageBackView.backgroundColor =RGBACOLOR(29, 187, 214, 1);
}
[selectView addSubview:imageBackView];
// 动画scrollView
UIScrollView *imageScroll =[[UIScrollView alloc] initWithFrame:CGRectMake(0,0,40, 40)];
imageScroll.contentSize =CGSizeMake(40,40*2);
imageScroll.bounces =NO;
imageScroll.pagingEnabled =YES;
imageScroll.tag =section+1000;
imageScroll.backgroundColor =[UIColor clearColor];
[selectView addSubview:imageScroll];
NSArray *imageArr =@[[UIImage imageNamed:@"pluse"],[UIImage imageNamed:@"minus"]];
for (NSInteger i=0; i<2; i++) {
UIImageView *imageView =[[UIImageView alloc] initWithFrame:CGRectMake(0,i*40,40,40)];
imageView.backgroundColor =[UIColor clearColor];
imageView.image =imageArr[i];
[imageScroll addSubview:imageView];
}
if(selectSection==section){
imageScroll.contentOffset=CGPointMake(0,40);
}else{
imageScroll.contentOffset=CGPointMake(0,0);
}
UILabel* sectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(55, 10, SCREEN_WIDTH - 80, 20)];
[sectionLabel setBackgroundColor:[UIColor clearColor]];
[sectionLabel setTextColor:RGBACOLOR(29, 187, 214, 1)];
[sectionLabel setFont:[UIFont systemFontOfSize:17]];
sectionLabel.text = [NSString stringWithFormat:@"Section %ld 号",(long)section];
[selectView addSubview:sectionLabel];
UITapGestureRecognizer *tapGes =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapgesDown:)];
[selectView addGestureRecognizer:tapGes];
return headerView;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
return [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
return 0;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell* cell = nil;
NSString* cellIdentifier = [NSString stringWithFormat:@"courseDetailCells_%d_%d",(int)indexPath.section,(int)indexPath.row];
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
MyTableViewCell* myCell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
[cell setBackgroundColor:[UIColor whiteColor]];
[myCell setIndexPath:indexPath];
cell = myCell;
cell.clipsToBounds = YES;
}
return cell;
}
#pragma mark - 手势方法
-(void)tapgesDown:(UITapGestureRecognizer*)tapges{
// NSLog(@"====%ld",tapges.view.tag);
oldSection = selectSection;
selectSection = tapges.view.tag-7000;
// NSLog(@"selectSection==%ld",(long)selectSection);
NSInteger oldCount = [[_origionArr objectAtIndex:oldSection] count];
NSInteger selectedCount = [[_origionArr objectAtIndex:selectSection] count];
// 改变背景边框
UIView *selectView =(UIView*)[self.view viewWithTag:selectSection+7000];
UIView *oldView =(UIView*)[self.view viewWithTag:oldSection+7000];
oldView.layer.borderColor =RGBACOLOR(187, 187, 187, 1).CGColor;
oldView.layer.borderWidth=1.0f;
selectView.layer.borderColor =RGBACOLOR(29, 187, 214, 1).CGColor;
selectView.layer.borderWidth=1.0f;
// 刷新indexpath row的标准方式
if(oldSection != selectSection){
NSMutableArray* oldIndexPathArray = [NSMutableArray arrayWithCapacity:0];
for (int i = 0; i < oldCount; i++) {
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:oldSection];
[oldIndexPathArray addObject:indexPath];
}
NSMutableArray* selectedIndexPathArray = [NSMutableArray arrayWithCapacity:0];
for (int i = 0; i < selectedCount; i++) {
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:selectSection];
[selectedIndexPathArray addObject:indexPath];
}
NSMutableArray* rowsArray = [NSMutableArray arrayWithCapacity:0];
[rowsArray addObjectsFromArray:oldIndexPathArray];
[rowsArray addObjectsFromArray:selectedIndexPathArray];
[_tableView reloadRowsAtIndexPaths:rowsArray withRowAnimation:UITableViewRowAnimationBottom];
[NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(chnageScrollView) userInfo: nil repeats:NO];
}else{
// NSLog(@">>>");
NSMutableArray* oldIndexPathArray = [NSMutableArray arrayWithCapacity:0];
for (int i = 0; i < oldCount; i++) {
NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:oldSection];
[oldIndexPathArray addObject:indexPath];
}
[_tableView reloadRowsAtIndexPaths:oldIndexPathArray withRowAnimation:UITableViewRowAnimationBottom];
[NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(chnageScrollView) userInfo: nil repeats:NO];
}
}
-(void)chnageScrollView{
UIScrollView *scrollView=(UIScrollView*)[self.view viewWithTag:selectSection+1000];
UIScrollView *scrollView2=(UIScrollView*)[self.view viewWithTag:oldSection+1000];
if(oldSection !=selectSection){
scrollView2.contentOffset =CGPointMake(0,40);
scrollView.contentOffset = CGPointMake(0, 0);
[UIView animateWithDuration:0.3f animations:^{
scrollView.contentOffset =CGPointMake(0,40);
scrollView2.contentOffset =CGPointMake(0,0);
}];
}else{
if(scrollView2.contentOffset.y ==40){
[UIView animateWithDuration:0.3f animations:^{
scrollView2.contentOffset =CGPointMake(0,0);
}];
}else{
[UIView animateWithDuration:0.3f animations:^{
scrollView2.contentOffset =CGPointMake(0,40);
}];
}
}
}
@end
| 22,678
|
https://github.com/JunkieLand/spark-tools/blob/master/src/main/scala/it/trenzalore/tools/utils/spark/SparkUtils.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
spark-tools
|
JunkieLand
|
Scala
|
Code
| 95
| 371
|
package it.trenzalore.tools.utils.spark
import org.apache.spark.sql.{ Column, DataFrame, Dataset, Encoders, SparkSession }
import org.apache.spark.sql.types.StructType
import org.apache.spark.storage.StorageLevel
import org.apache.spark.sql.functions.col
import scala.reflect.runtime.universe.TypeTag
object SparkUtils {
object implicits {
implicit class StructTypeEnhanced(st: StructType) {
lazy val columns: Seq[Column] = st.fieldNames.map(col)
}
implicit class DataframeEnhanced(df: DataFrame) {
def to[T <: Product: TypeTag]: Dataset[T] = {
import df.sparkSession.implicits._
df.select(columnsOf[T]: _*).as[T]
}
}
implicit class DatasetEnhanced[T](ds: Dataset[T]) {
def persistIf(condition: Boolean, storageLevel: StorageLevel): Dataset[T] = {
if (condition)
ds.persist(storageLevel)
else
ds
}
}
}
import implicits._
def schemaOf[T <: Product: TypeTag]: StructType = Encoders.product[T].schema
def columnsOf[T <: Product: TypeTag]: Seq[Column] = schemaOf[T].columns
}
| 2,178
|
https://github.com/maki-nage/makinage/blob/master/makinage/driver/app_sink.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
makinage
|
maki-nage
|
Python
|
Code
| 376
| 1,097
|
from typing import Callable
from collections import namedtuple
import queue
import asyncio
import rx
import rx.operators as ops
from rx.core.notification import OnNext, OnError
from rx.scheduler import NewThreadScheduler
from rx.scheduler.eventloop import AsyncIOThreadSafeScheduler
from cyclotron import Component
def QObservable(q):
def on_subscribe(observer, scheduler):
while(True):
i = q.get()
if isinstance(i, OnNext):
observer.on_next(i.value)
q.task_done()
elif isinstance(i, OnError):
observer.on_error(i.exception)
break
else:
observer.on_completed()
break
return rx.create(on_subscribe)
def create_controllable_sink(sink_id: str,
operator: Callable[[rx.Observable], rx.Observable],
sink: rx.Observable,
) -> rx.Observable:
"""Creates a controllable sink from a sink operator
The sink operator must subscribe to its provided observable. All items are
emitted on a thread dedicated to this operator. So it can do
blocking calls without issues on the makinage eventloop.
Args:
- sink_id: The observable identifier used in the feedback loop.
- operator: The connector logic to isolate.
- sink: A function that subscribes to an observable.
"""
q = queue.Queue()
index = 0
lifecycle = QObservable(q).pipe(
ops.subscribe_on(NewThreadScheduler()),
operator,
ops.ignore_elements(),
ops.observe_on(AsyncIOThreadSafeScheduler(asyncio.get_event_loop())),
)
def push_item(q, sink_id):
def _push_item(i):
nonlocal index
q.put_nowait(i)
if isinstance(i, OnNext):
index += 1
if index == 500:
index = 0
return (sink_id, q.qsize())
return None
return ops.map(_push_item)
feedback = sink.pipe(
ops.materialize(),
push_item(q, sink_id),
ops.filter(lambda i: i is not None)
)
return rx.merge(lifecycle, feedback)
Sink = namedtuple('Sink', ['connector'])
Source = namedtuple('Source', ['feedback'])
# Sink items
Create = namedtuple('Create', ['id', 'operator', 'observable'])
Create.__doc__ = "Creates a new application defined sink."
Create.id.__doc__ = "The id of the sink."
Create.operator.__doc__ = "The function implemententing the sink logic, as an operator."
Create.observable.__doc__ = "The observable that will feed the sink."
# Source items
Feedback = namedtuple('Feedback', ['id', 'observable'])
Feedback.__doc__ = "The feedback loop of a sink."
Feedback.id.__doc__ = "The id of the sink."
Feedback.observable.__doc__ = "The feedback observable, emitting (id, qsize) items."
def make_driver():
def driver(sink):
""" Application sink driver.
This is a driver implementation where the logic is pushed by
the application. This allows to write connectors in a more flexible way
than writing a driver per connector.
The Sink connector stream emits the following items: Create
The Source feedback stream emits the following items: Feedback
"""
def on_subscribe(observer, scheduler):
def on_next(i):
if type(i) is Create:
observer.on_next(
Feedback(
i.id,
create_controllable_sink(
i.id,
i.operator,
i.observable,
)
)
)
else:
observer.on_error("app sink unknown command: {}".format(i))
disposable = sink.connector.subscribe(
on_next=on_next,
on_error=observer.on_error,
on_completed=observer.on_completed)
return disposable
return Source(
feedback=rx.create(on_subscribe),
)
return Component(call=driver, input=Sink)
| 50,157
|
https://github.com/onap/aai-traversal/blob/master/aai-traversal/src/test/java/org/onap/aai/rest/search/OwningEntityfromServiceInstance.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
aai-traversal
|
onap
|
Java
|
Code
| 263
| 946
|
/**
* ============LICENSE_START=======================================================
* org.onap.aai
* ================================================================================
* Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.aai.rest.search;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
import java.util.Map;
public class OwningEntityfromServiceInstance extends QueryTest {
public OwningEntityfromServiceInstance () throws AAIException, NoEdgeRuleFoundException {
super();
}
@Test
public void run() {
super.run();
}
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
// Set up the test graph
Vertex service_instance = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "service-instance-1");
Vertex owning_entity = graph.addVertex(T.label, "owning-entity", T.id, "2", "aai-node-type", "owning-entity", "owning-entity-id", "owning-entity-id-1", "owning-entity-name", "owning-entity-name1");
// adding extra vertices and edges which shouldn't be picked.
Vertex service_instance2 = graph.addVertex(T.label, "service-instance", T.id, "3", "aai-node-type", "service-instance", "service-instance-id", "service-instance-2");
Vertex owning_entity2 = graph.addVertex(T.label, "owning-entity", T.id, "4", "aai-node-type", "owning-entity", "owning-entity-id", "owning-entity-id-2", "owning-entity-name", "owning-entity-name2");
GraphTraversalSource g = graph.traversal();
rules.addEdge(g, owning_entity, service_instance);
rules.addEdge(g, owning_entity2, service_instance2);
expectedResult.add(owning_entity);
}
@Override
protected String getQueryName() {
return "owning-entity-fromService-instance";
}
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
g.has("service-instance-id", "service-instance-1");
}
@Override
protected void addParam(Map<String, Object> params) {
return;
}
}
| 6,454
|
https://github.com/chuong9x/DynamoNodeModelsEssentials/blob/master/src/Essentials/NodeModelsEssentialsFunctions/NodeModelsEssentialsFunctions.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
DynamoNodeModelsEssentials
|
chuong9x
|
C#
|
Code
| 917
| 2,401
|
using System;
using System.Collections.Generic;
using Autodesk.DesignScript.Runtime; // needed to add flags like [IsVisibleDynamoLibrary(false)]
using Autodesk.DesignScript.Geometry;
using Autodesk.DesignScript.Interfaces;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
namespace NodeModelsEssentials.Functions
{
[IsVisibleInDynamoLibrary(false)]
public class NodeModelsEssentialsFunctions
{
public static double Multiply(double a, double b)
{
return a * b;
}
public static double Add(double a, double b)
{
return a + b;
}
public static double Subtract(double a, double b)
{
return a - b;
}
public static double Divide(double a, double b)
{
return a / b;
}
public static double Sum(double a, double b, double c, double d)
{
return a + b + c + d;
}
/// <summary>
/// Appends a the provided text to a file.
/// </summary>
/// <param name="FilePath">The path of the file to write to.</param>
/// <param name="Text">The string to write.</param>
public static void WriteLineToFilePath(string FilePath, string Text)
{
using (StreamWriter outputFile = new StreamWriter(FilePath, true))
{
outputFile.WriteLine(Text);
outputFile.Close();
}
}
/// <summary>
/// Replaces the contents of a file.
/// </summary>
/// <param name="FilePath">The path of the file to write to.</param>
/// <param name="Text">The string to write.</param>
public static void WriteToFilePath(string FilePath, string Text)
{
using (StreamWriter outputFile = new StreamWriter(FilePath, true))
{
outputFile.Write(Text);
outputFile.Close();
}
}
public static string ConcatenateThree(string a, string b, string c)
{
return string.Join(", ", new List<string>{ a, b, c });
}
public static string Error(string text)
{
if (text == "ERROR1")
{
throw new ArgumentException("ERROR1 raised ArgumentException.");
} else if (text == "ERROR2")
{
throw new Exception("A sample Exception by ERROR2.");
}
return "Error response";
}
public static string Timeout(int sleepDuration = 1000, int timeoutDuration = 3000)
{
var taskWasCompleted = false; // wether the C# Task was completed before timeout or not
Thread taskThread = null; // reference the thread in which we call Edge.js to abort in case of timeout
try
{
taskWasCompleted = Task.Run(() =>
{
taskThread = Thread.CurrentThread;
Thread.Sleep(sleepDuration);
//var client = GetClientConnection(Project);
//var propertyWatch = client.GetProperyWatch(Name);
//propertyValue = propertyWatch.Value;
}).Wait(timeoutDuration);
}
catch (Exception e)
{
throw new Exception(e.Message);
// TODO: throw HFDM.js.NET errors (accessible in JSON as e.InnerException.InnerException.Message);
}
if (!taskWasCompleted && taskThread != null)
{
// Abort taskThread and throw exception
taskThread.Abort();
throw new Exception("The request timed out (" + timeoutDuration + "ms).");
}
return "Timeout message - " + sleepDuration + " - " + timeoutDuration ;
}
public static string GetDate()
{
return DateTime.Now.ToString("yyMMdd H:mm:ss");
}
public static object GetItem(List<object> list, int index)
{
return 2;
// if(list.Count <= index)
// return list[index];
// return null;
}
/// <summary>
/// A simple node to create a surface from four points.
/// </summary>
public static Surface SurfaceFrom4Points(Point point1, Point point2, Point point3, Point point4)
{
Line line1 = Line.ByStartPointEndPoint(point1, point2);
Line line2 = Line.ByStartPointEndPoint(point3, point4);
List<Curve> curves = new List<Curve> { line1, line2 };
Surface surf = Surface.ByLoft(curves);
// Remember to DISPOSE geometry elements created in the node
// but not returned by it!
line1.Dispose();
line2.Dispose();
return surf;
}
/// <summary>
/// Given a surface, returns a grid of UV tangent planes.
/// </summary>
public static List<List<Plane>> UVPlanesOnSurface(Surface surface, int uCount, int vCount)
{
List<List<Plane>> planes = new List<List<Plane>>();
double du = 1.0 / (uCount - 1);
double dv = 1.0 / (vCount - 1);
Point point = null;
Vector normal = null;
Vector tangent = null;
for (double v = 0; v <= 1.0; v += dv)
{
List<Plane> pls = new List<Plane>();
for (double u = 0; u <= 1; u += du)
{
point = surface.PointAtParameter(u, v);
normal = surface.NormalAtParameter(u, v);
tangent = surface.TangentAtUParameter(u, v);
Plane p = Plane.ByOriginNormalXAxis(point, normal, tangent);
pls.Add(p);
}
planes.Add(pls);
}
// Remember to dispose unreturned geometry objects
point.Dispose();
normal.Dispose();
tangent.Dispose();
return planes;
}
/// <summary>
/// Given some size parameters, returns a lofted surface with random bumps.
/// </summary>
public static Surface WobblySurface(
double baseX, double baseY, double baseZ,
double width, double length, double maxHeight,
int uCount, int vCount)
{
double dx = width / (uCount - 1);
double dy = length / (vCount - 1);
Random rnd = new Random();
List<Curve> curves = new List<Curve>();
List<Point> pts = null;
for (double y = baseY; y <= baseY + length; y += dy)
{
pts = new List<Point>();
for (double x = baseX; x <= baseX + width; x += dx)
{
pts.Add(Point.ByCoordinates(x, y, baseZ + maxHeight * rnd.NextDouble()));
}
curves.Add(NurbsCurve.ByPoints(pts));
}
Surface surface = Surface.ByLoft(curves);
return surface;
}
}
[IsVisibleInDynamoLibrary(false)]
public class MyMesh : IGraphicItem
{
#region private members
private static double counter;
private Point point = Point.ByCoordinates(0, 2, 0);
#endregion
#region properties
public Point Point { get { return point; } }
#endregion
private MyMesh(double x, double y, double z)
{
point = Point.ByCoordinates(x, y, z);
}
public static MyMesh Create(double x = 0, double y = 0, double z = 0)
{
counter++;
return new MyMesh(x, y, z);
}
//public static MyMesh Create([DefaultArgumentAttribute("Point.ByCoordinates(0,0,0);")]Point point)
//{
// return new MyMesh(point.X, point.Y, point.Z);
//}
#region IGraphicItem interface
/// <summary>
/// The Tessellate method in the IGraphicItem interface allows
/// you to specify what is drawn when dynamo's visualization is
/// updated.
/// </summary>
[IsVisibleInDynamoLibrary(false)]
public void Tessellate(IRenderPackage package, TessellationParameters parameters)
{
// This example contains information to draw a point
package.AddPointVertex(point.X, point.Y, point.Z);
package.AddPointVertexColor(255, 0, 0, 255);
package.AddPointVertex(0, 1, 1);
package.AddPointVertexColor(255, 0, 0, 255);
package.AddPointVertex(0, 2, 2 + counter / 10.0);
package.AddPointVertexColor(255, 0, 0, 255);
package.AddPointVertex(0, 3, 3 + counter / 10.0);
package.AddPointVertexColor(255, 0, 0, 255);
package.AddPointVertex(0, 4, 4 + counter / 10.0);
package.AddPointVertexColor(255, 0, 0, 255);
}
#endregion
public override string ToString()
{
return string.Format("HelloDynamoZeroTouch:{0},{1},{2}", point.X, point.Y, point.Z);
}
}
}
| 25,121
|
https://github.com/anishdhakal54/newpooshak/blob/master/resources/views/emails/order-updated.blade.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
newpooshak
|
anishdhakal54
|
Blade
|
Code
| 64
| 244
|
@component('mail::layout')
{{-- Header --}}
@slot('header')
@component('mail::header', ['url' => config('app.url')])
<img src="{{ asset('img/poosak.png') }}" alt="" width="150px">
@endcomponent
@endslot
** The Order #{{$content['id']}} has been {{$content['value']}},Please check the following link for details **
@component('mail::button', ['url' => "{{trans('app.url')}}".'/dashboard/order' ,'color' => 'red'])
Check Order
@endcomponent
<div style="display: inline-block"> Or <a href="{{trans('app.url')}}">Visit Our Store</a></div>
@slot('footer')
@component('mail::footer')
© {{ date('Y') }} {{ config('app.name') }}. All rights reserved.
@endcomponent
@endslot
@endcomponent
| 16,440
|
https://github.com/bigstar18/prjs/blob/master/prj/bank/web-pingan-b2bic/src/main/java/cn/com/agree/eteller/generic/nnatp/impl/Tools.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,016
|
prjs
|
bigstar18
|
Java
|
Code
| 317
| 968
|
package cn.com.agree.eteller.generic.nnatp.impl;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import cn.com.agree.eteller.generic.utils.CommonType;
public class Tools {
public static final String NOT_SELECT_LABEL = "全部";
public static final String NOT_SELECT_ID = "";
public static final String BASEPATH = "config/";
public static final String POSTFIX = ".properties";
public static CommonType[] loadConfigFromFile(String filename, int flag) {
List list = new ArrayList();
if (flag == 1) {
list.add(new CommonType("", "全部"));
}
FileReader fr = null;
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(Tools.class.getClassLoader().getResourceAsStream("config/" + filename + ".properties")));
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
int e = line.indexOf("=");
if (e != -1) {
String id = line.substring(0, e);
String value = line.substring(e + 1);
list.add(new CommonType(id, value));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
if (br != null) {
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
if (br != null) {
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
CommonType[] ct = (CommonType[]) list.toArray(new CommonType[0]);
return ct;
}
public static String getInit(String filename, String name) {
String pwd_method = null;
Properties p = new Properties();
File f = new File("config/" + filename + ".properties");
InputStream in = null;
try {
in = new FileInputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
p.load(in);
pwd_method = p.getProperty(name);
} catch (IOException e) {
e.printStackTrace();
}
return pwd_method;
}
}
| 5,259
|
https://github.com/lsst-sims/smtn-006/blob/master/software/validation/dec_vs_mag.py
|
Github Open Source
|
Open Source
|
CC-BY-4.0
| 2,017
|
smtn-006
|
lsst-sims
|
Python
|
Code
| 352
| 1,351
|
"""
This script queries the CatSim database for all bright stars in
0 < ra < 20 and then returns density plots of declination versus
magnitude.
"""
import numpy as np
import matplotlib.pyplot as plt
from lsst.sims.catalogs.generation.db import DBObject
import time
if __name__ == "__main__":
# grid step size in magnitude and declination
# can be set to whatever the user wants
dmag = 0.1
ddec = 0.1
t_start = time.time()
output_file_name = "mag_vs_dec.eps"
db = DBObject(database='LSSTCATSIM', host='localhost',
port=51433, driver='mssql+pymssql')
cmd = "SELECT catalogid, ra, decl, umag_noatm, gmag_noatm, rmag_noatm, "
cmd += "imag_noatm, zmag_noatm, ymag_noatm, residual "
cmd += "FROM bright_stars WHERE ra < 20.0 and ra > 0.0"
query_dtype = np.dtype([('id', long),
('ra', float), ('dec', float),
('u', float), ('g', float), ('r', float),
('i', float), ('z', float), ('y', float),
('residual', float)])
u_grid = {}
g_grid = {}
r_grid = {}
i_grid = {}
z_grid = {}
y_grid = {}
results = db.get_arbitrary_chunk_iterator(cmd, dtype=query_dtype,
chunk_size=100000)
total_stars = 0
for chunk in results:
print 'chunk ',time.time()-t_start,total_stars
for line in chunk:
total_stars += 1
dec_int = int(round(line[2]/ddec))
for grid_dict, mag_dex in \
zip((u_grid, g_grid, r_grid, i_grid, z_grid, y_grid),
(3, 4, 5, 6, 7, 8)):
mag_int = int(round(line[mag_dex]/dmag))
dict_key = '%s_%s' % (dec_int, mag_int)
if dict_key in grid_dict:
grid_dict[dict_key][2] += 1
else:
grid_dict[dict_key] = [ddec*dec_int, dmag*mag_int, 1]
plt.figsize = (30, 30)
for i_fig, (grid_dict, name) in \
enumerate(zip((u_grid, g_grid, r_grid, i_grid, z_grid, y_grid),
('u', 'g', 'r', 'i', 'z', 'y'))):
plt.subplot(3, 2, i_fig+1)
x_list = []
y_list = []
color_list = []
for key in grid_dict:
x_list.append(grid_dict[key][0])
y_list.append(grid_dict[key][1])
color_list.append(grid_dict[key][2])
x_list = np.array(x_list)
y_list = np.array(y_list)
color_list = np.array(color_list)
color_dex = np.argsort(color_list)
plt.scatter(x_list[color_dex], y_list[color_dex],
c=np.log10(color_list[color_dex]), s=5,
cmap=plt.cm.gist_ncar, edgecolor='')
plt.colorbar()
if i_fig==0:
plt.xlabel('Dec')
plt.ylabel('magnitude')
if len(x_list)>2:
xmax = x_list.max()
xmin = x_list.min()
ymax = y_list.max()
ymin = y_list.min()
plt.text(xmax-0.2*(xmax-xmin), ymax-0.1*(ymax-ymin), name, fontsize=15)
dx = 0.1*(xmax-xmin)
dy = 0.1*(ymax-ymin)
xticks = np.arange(-90.0, 90.0, 5.0)
xformat = ['%d' % xticks[ii] if ii%10==0 else '' for ii in range(len(xticks))]
yticks = np.arange(np.floor(ymin),np.ceil(ymax),(np.ceil(ymax)-np.floor(ymin))*0.1)
yformat = ['%.1f' % yticks[ii] if ii%3==0 else '' for ii in range(len(yticks))]
plt.xticks(xticks, xformat, fontsize=15)
plt.yticks(yticks, yformat, fontsize=15)
plt.tight_layout()
plt.savefig(output_file_name)
plt.close()
print 'that took ',time.time()-t_start
print 'total stars ',total_stars
| 36,767
|
https://github.com/hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism/blob/master/Variant Programs/1-2/6/commemorate/GalaTape.java
|
Github Open Source
|
Open Source
|
MIT
| null |
Dataset2-HowToDetectAdvancedSourceCodePlagiarism
|
hjc851
|
Java
|
Code
| 28
| 75
|
package commemorate;
public abstract class GalaTape {
protected double beginning;
protected java.lang.String update;
public double opportunity() {
return this.beginning;
}
public java.lang.String know() {
return this.update;
}
}
| 8,217
|
https://github.com/DSCI-310/Group-2/blob/master/src/modeling.r
|
Github Open Source
|
Open Source
|
MIT
| null |
Group-2
|
DSCI-310
|
R
|
Code
| 334
| 1,133
|
"Fits a k-nn model on the pre-processed training data from the Cleveland Heart Disease dataset (https://archive-beta.ics.uci.edu/ml/datasets/heart+disease) Saves the model as a rds file.
Usage: src/modeling.r --train=<train> --test=<test> --out_dir=<out_dir>
Options:
--train=<train> Path (including filename) to training data (which needs to be saved as a csv file)
--test=<test> Path (including filename) to testing data (which needs to be saved as a csv file)
--out_dir=<out_dir> Path to directory where the serialized model should be written
" -> doc
library(tidyverse)
library(tidymodels)
library(ggplot2)
library(GGally)
library(docopt)
library(rlang)
library(group2)
# source("R/accuracy_plot.r")
set.seed(4)
opt <- docopt(doc)
main <- function(train, test, out_dir) {
# Perform Cross Validation
training_data <- read.csv(train)
training_data$diagnosis <- as.factor(training_data$diagnosis)
hd_vfold <- vfold_cv(training_data, v = 5, strata = diagnosis)
recipe <- recipe(diagnosis ~ ., data = training_data) %>%
step_scale(all_predictors()) %>%
step_center(all_predictors())
# Create Classifier and Tuning
knn_spec <- nearest_neighbor(weight_func = "rectangular", neighbors = tune()) %>%
set_engine("kknn") %>%
set_mode("classification")
k_vals <- tibble(neighbors = seq(from = 1, to = 100, by = 5))
knn_results <- workflow() %>%
add_recipe(recipe) %>%
add_model(knn_spec) %>%
tune_grid(resamples = hd_vfold, grid = k_vals) %>%
collect_metrics()
accuracies <- knn_results %>%
filter(.metric == "accuracy")
accuracy_vs_k <- accuracy_plot(accuracies)
try({
dir.create(out_dir, recursive = TRUE)
})
ggsave(paste0(out_dir, "/accuracy_plot.png"),
accuracy_vs_k,
width = 8,
height = 10)
# Prediction and Training
knn_spec <- nearest_neighbor(weight_func = "rectangular", neighbors = 12) %>%
set_engine("kknn") %>%
set_mode("classification")
knn_fit <- workflow() %>%
add_recipe(recipe) %>%
add_model(knn_spec) %>%
fit(data = training_data)
# Load and Wrangle test data
test_data <- read.csv(test)
test_data$diagnosis <- as.factor(test_data$diagnosis)
hd_predictions <- predict(knn_fit, test_data) %>%
bind_cols(test_data)
hd_predictions %>%
metrics(truth = diagnosis, estimate = .pred_class) %>%
filter(.metric == "accuracy")
# Assess Model Accuracy
confusion_mat <- hd_predictions %>%
conf_mat(truth = diagnosis, estimate = .pred_class)
Truth <- factor(c(0, 0, 1, 1))
Prediction <- factor(c(0, 1, 0, 1))
Y <- c(9, 31, 27, 8)
df <- data.frame(Truth, Prediction, Y)
confusion_mat_plot <- ggplot(data = df, mapping = aes(x = Truth, y = Prediction)) +
geom_tile(aes(fill = Y), colour = "white") +
geom_text(aes(label = sprintf("%1.0f", Y)), vjust = 1, colour="white") +
theme_bw()
ggsave(paste0(out_dir, "/confusion_matrix.png"),
confusion_mat_plot,
width = 8,
height = 10)
}
main(opt[["--train"]], opt[["--test"]], opt[["--out_dir"]])
| 37,677
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.