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/huaweicloud/huaweicloud-sdk-java-v3/blob/master/services/bssintl/src/main/java/com/huaweicloud/sdk/bssintl/v2/model/ListResourceTypesResponse.java
Github Open Source
Open Source
Apache-2.0
2,023
huaweicloud-sdk-java-v3
huaweicloud
Java
Code
259
920
package com.huaweicloud.sdk.bssintl.v2.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.huaweicloud.sdk.core.SdkResponse; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Consumer; /** * Response Object */ public class ListResourceTypesResponse extends SdkResponse { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "total_count") private Integer totalCount; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "resource_types") private List<ResourceTypes> resourceTypes = null; public ListResourceTypesResponse withTotalCount(Integer totalCount) { this.totalCount = totalCount; return this; } /** * 总数。 * @return totalCount */ public Integer getTotalCount() { return totalCount; } public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } public ListResourceTypesResponse withResourceTypes(List<ResourceTypes> resourceTypes) { this.resourceTypes = resourceTypes; return this; } public ListResourceTypesResponse addResourceTypesItem(ResourceTypes resourceTypesItem) { if (this.resourceTypes == null) { this.resourceTypes = new ArrayList<>(); } this.resourceTypes.add(resourceTypesItem); return this; } public ListResourceTypesResponse withResourceTypes(Consumer<List<ResourceTypes>> resourceTypesSetter) { if (this.resourceTypes == null) { this.resourceTypes = new ArrayList<>(); } resourceTypesSetter.accept(this.resourceTypes); return this; } /** * 资源类型信息列表,具体请参见表3。 * @return resourceTypes */ public List<ResourceTypes> getResourceTypes() { return resourceTypes; } public void setResourceTypes(List<ResourceTypes> resourceTypes) { this.resourceTypes = resourceTypes; } @Override public boolean equals(java.lang.Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ListResourceTypesResponse that = (ListResourceTypesResponse) obj; return Objects.equals(this.totalCount, that.totalCount) && Objects.equals(this.resourceTypes, that.resourceTypes); } @Override public int hashCode() { return Objects.hash(totalCount, resourceTypes); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ListResourceTypesResponse {\n"); sb.append(" totalCount: ").append(toIndentedString(totalCount)).append("\n"); sb.append(" resourceTypes: ").append(toIndentedString(resourceTypes)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
50,861
https://github.com/akrabat/project365-photos-website/blob/master/node_modules/sprintf-kit/modifiers/f.js
Github Open Source
Open Source
ISC, MIT
2,023
project365-photos-website
akrabat
JavaScript
Code
27
66
"use strict"; module.exports = function (value /*, placeholder, argIndex, args*/) { try { return String(isNaN(value) ? parseFloat(value) : Number(value)); } catch (e) { return "<invalid>"; } };
45,933
https://github.com/cloudwalkph/aai-tracker-web/blob/master/public/js/drawchart.js
Github Open Source
Open Source
MIT
null
aai-tracker-web
cloudwalkph
JavaScript
Code
766
3,030
function drawChart(container, data, title) { nv.addGraph(function() { var chart = nv.models.pieChart() .x(function(d) { return d.key }) .y(function(d) { return d.values }) .color(['#532400', '#f37f20', '#c76819', '#9f530c', '#7a3d00']) .showLabels(true) .labelSunbeamLayout(true) .labelsOutside(true) .labelThreshold(.05) .title(title) .titleOffset(23) .noData('There is no data coming from the server yet'); var chartData = d3.nest() .key(function(d) { return d.label }) .rollup(function(d) { return d3.sum(d, function(g) { return g.answer }); }).entries(data); d3.select(container) .datum(chartData) .transition().duration(350) .call(chart); d3.selectAll('.nv-legend') .attr('transform', 'translate(-50, 0)') .attr('text-align', 'center'); nv.utils.windowResize(chart.update); chart.pie.dispatch.on("elementClick", function(e) { window.keySelected = e.data.key; showHitsModal(e.data.key); }); return chart; }); } function showHitsModal(dataKey) { var hitsTable = $('#hitsTable'); var loadingHits = $('.loading-hits'); hitsTable.hide(); loadingHits.show(); $('.answersModal').modal('show'); var eventId = $('#eventId').val(), locationId = $('#locationId').val(); var url = '/api/v1/events/hits/' + eventId + '/locations/' + locationId + '/answer/' + dataKey; fetch(url).then(function(res) { if (res.status !== 200) { console.log('Looks like there was a problem. Status Code: ' + res.status); return; } res.json().then((function(json) { console.log('fetch', json.data); hitsTable.show(); loadingHits.hide(); hitsTable.DataTable({ data: json.data, columns: [ {title: 'UUID', data: 'uuid', visible: false}, {title: 'Image', data: 'image', render: function(data, type, full, meta) { return '<a href="#" data-featherlight="' + data + '"><img src="'+data+'" class="hit-image"></a>' }}, {title: 'Name', data: 'name'}, {title: 'Email', data: 'email'}, {title: 'Contact #', data: 'contact_number'}, {title: 'Date', data: 'hit_date'} ] }); })) }); } function drawTimeChart(container, data) { nv.addGraph(function() { var chart = nv.models.lineWithFocusChart() .color(['#aa7c00']) .showLegend(false); var customTimeFormat = d3.time.format.multi([ ["%-I:%M %p", function(d) { return d.getMinutes(); }], ["%-I %p", function(d) { return d.getHours(); }], ["%b %-d", function(d) { return d.getDate() != 1; }], ["%b %-d", function(d) { return d.getMonth(); }], ["%Y", function() { return true; }] ]); chart.xScale(d3.time.scale()); chart.xAxis .showMaxMin(false) .axisLabel('Time') .tickFormat(function(d) { return customTimeFormat(new Date(d * 1000)); }); chart.x2Axis .showMaxMin(false) .axisLabel('Time') .tickFormat(function(d) { return customTimeFormat(new Date(d * 1000)); }); chart.yAxis .tickFormat(d3.format("d")); chart.y2Axis .tickFormat(d3.format("d")); d3.select(container) .datum(data) .transition().duration(500) .call(chart); nv.utils.windowResize(chart.update); return chart; }); } function drawChartAdvance(container, data) { var svg = d3.select(container) .append("g"); var chartData = d3.nest() .key(function(d) { return d.label }) .rollup(function(d) { return d3.sum(d, function(g) { return g.answer }); }).entries(data); console.log(chartData); svg.append("g") .attr("class", "slices"); svg.append("g") .attr("class", "labels"); svg.append("g") .attr("class", "lines"); var width = 200, height = 300, radius = Math.min(width, height) / 2; var pie = d3.layout.pie() .sort(null) .value(function(d) { return d.values; }); var arc = d3.svg.arc() .outerRadius(radius * 0.8) .innerRadius(radius * 0.4); var outerArc = d3.svg.arc() .innerRadius(radius * 0.9) .outerRadius(radius * 0.9); svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); var key = function(d){ return d.data.key; }; var color = d3.scale.category20(); // .domain(["Male", "Female"]); //.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); change(chartData); function mergeWithFirstEqualZero(first, second){ var secondSet = d3.set(); second.forEach(function(d) { secondSet.add(d.key); }); var onlyFirst = first .filter(function(d){ return !secondSet.has(d.label) }) .map(function(d) { return {key: d.label, values: 0}; }); return d3.merge([ second, onlyFirst ]) .sort(function(a,b) { return d3.ascending(a.key, b.key); }); } function change(data) { var duration = +2500; var data0 = svg.select(".slices").selectAll("path.slice") .data().map(function(d) { return d.data }); if (data0.length == 0) data0 = data; var was = mergeWithFirstEqualZero(data, data0); var is = mergeWithFirstEqualZero(data0, data); /* ------- SLICE ARCS -------*/ var slice = svg.select(".slices").selectAll("path.slice") .data(pie(was), key); slice.enter() .insert("path") .attr("class", "slice") .style("fill", function(d) { return color(d.data.key); }) .each(function(d) { this._current = d; }); slice = svg.select(".slices").selectAll("path.slice") .data(pie(is), key); slice .transition().duration(duration) .attrTween("d", function(d) { var interpolate = d3.interpolate(this._current, d); var _this = this; return function(t) { _this._current = interpolate(t); return arc(_this._current); }; }); slice = svg.select(".slices").selectAll("path.slice") .data(pie(data), key); slice .exit().transition().delay(duration).duration(0) .remove(); /* ------- TEXT LABELS -------*/ var text = svg.select(".labels").selectAll("text") .data(pie(was), key); text.enter() .append("text") .attr("dy", ".35em") .style("opacity", 0) .text(function(d) { return d.data.key; }) .each(function(d) { this._current = d; }); function midAngle(d){ return d.startAngle + (d.endAngle - d.startAngle)/2; } text = svg.select(".labels").selectAll("text") .data(pie(is), key); text.transition().duration(duration) .style("opacity", function(d) { return d.data.values == 0 ? 0 : 1; }) .attrTween("transform", function(d) { var interpolate = d3.interpolate(this._current, d); var _this = this; return function(t) { var d2 = interpolate(t); _this._current = d2; var pos = outerArc.centroid(d2); pos[0] = radius * (midAngle(d2) < Math.PI ? 1 : -1); return "translate("+ pos +")"; }; }) .styleTween("text-anchor", function(d){ var interpolate = d3.interpolate(this._current, d); return function(t) { var d2 = interpolate(t); return midAngle(d2) < Math.PI ? "start":"end"; }; }); text = svg.select(".labels").selectAll("text") .data(pie(data), key); text .exit().transition().delay(duration) .remove(); /* ------- SLICE TO TEXT POLYLINES -------*/ var polyline = svg.select(".lines").selectAll("polyline") .data(pie(was), key); polyline.enter() .append("polyline") .style("opacity", 0) .each(function(d) { this._current = d; }); polyline = svg.select(".lines").selectAll("polyline") .data(pie(is), key); polyline.transition().duration(duration) .style("opacity", function(d) { return d.data.value == 0 ? 0 : .5; }) .attrTween("points", function(d){ this._current = this._current; var interpolate = d3.interpolate(this._current, d); var _this = this; return function(t) { var d2 = interpolate(t); _this._current = d2; var pos = outerArc.centroid(d2); pos[0] = radius * 0.95 * (midAngle(d2) < Math.PI ? 1 : -1); return [arc.centroid(d2), outerArc.centroid(d2), pos]; }; }); polyline = svg.select(".lines").selectAll("polyline") .data(pie(data), key); polyline .exit().transition().delay(duration) .remove(); } }
24,674
https://github.com/khemx3/esdapi/blob/master/src/app/api/books.py
Github Open Source
Open Source
MIT
null
esdapi
khemx3
Python
Code
145
502
from typing import List from app.api import crud from app.api.models import BookDB, BookSchema from fastapi import APIRouter, HTTPException, Path router = APIRouter() @router.post("/", response_model=BookDB, status_code=201) async def create_book(payload: BookSchema): note_id = await crud.post(payload) response_object = { "id": note_id, "title": payload.title, "description": payload.description, "price": payload.price } return response_object @router.get("/{id}/", response_model=BookDB) async def read_book(id: int = Path(..., gt=0),): note = await crud.get(id) if not note: raise HTTPException(status_code=404, detail="Note not found") return note @router.get("/", response_model=List[BookDB]) async def read_all_books(): return await crud.get_all() @router.put("/{id}/", response_model=BookDB) async def update_book(payload: BookSchema, id: int = Path(..., gt=0),): note = await crud.get(id) if not note: raise HTTPException(status_code=404, detail="Note not found") note_id = await crud.put(id, payload) response_object = { "id": note_id, "title": payload.title, "description": payload.description, "price": payload.price } return response_object @router.delete("/{id}/", response_model=BookDB) async def delete_book(id: int = Path(..., gt=0)): note = await crud.get(id) if not note: raise HTTPException(status_code=404, detail="Note not found") await crud.delete(id) return note
38,253
https://github.com/KyuBlade/Omega-Project/blob/master/Omega/src/com/team/omega/core/renderer/PlayerRenderer.java
Github Open Source
Open Source
Apache-2.0
null
Omega-Project
KyuBlade
Java
Code
66
265
package com.team.omega.core.renderer; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.esotericsoftware.spine.Skeleton; import com.esotericsoftware.spine.SkeletonRenderer; import com.esotericsoftware.spine.SkeletonRendererDebug; public class PlayerRenderer implements Renderer { private SpriteBatch batch; private SkeletonRenderer renderer; private SkeletonRendererDebug debugRenderer; public PlayerRenderer(SpriteBatch batch) { this.batch = batch; renderer = new SkeletonRenderer(); debugRenderer = new SkeletonRendererDebug(); } @Override public void preRender() { } @Override public void render(float delta) { } public void render(Skeleton skeleton, float delta) { renderer.draw(batch, skeleton); debugRenderer.draw(skeleton); } }
3,931
https://github.com/ChristianJHughes/VisualBlackjack/blob/master/CardConcepts/CardConcepts/Hand.cs
Github Open Source
Open Source
MIT
2,015
VisualBlackjack
ChristianJHughes
C#
Code
266
635
using System; using System.Collections.Generic; using System.Text; namespace CardConcepts { //Class for constructing a player's hand of cards. public class Hand { //A list of the cards in the hand. private List<Card> h; public Hand() { h = new List<Card>(); } /// <summary> /// Returns a list of all the cards in private field h, and resets h to an empty list. /// </summary> /// <returns>A list of all the cards in private field h.</returns> public List<Card> surrenderCards() { List<Card> discardHand = new List<Card>(); foreach (Card c in h) { discardHand.Add(c); } h.Clear(); return discardHand; } /// <summary> /// Adds a card to the hand/ /// </summary> /// <param name="c">The card to be added to the hand.</param> public void add(Card c) { h.Add(c); } /// <summary> /// Returns the Blackjack score of the current hand. /// </summary> /// <returns>The Blackjack score of the current hand.</returns> public int BJscore() { int preAceScore = 0; int numberOfAces = 0; int withAceScore = 0; foreach (Card c in h) { if (c.BJvalue() != 1) { preAceScore += c.BJvalue(); } else { numberOfAces++; } } for (int j = 0; j <= numberOfAces; j++) { withAceScore = (preAceScore + ((numberOfAces - j) * 11) + j); if (withAceScore <= 21) { return withAceScore; } } return withAceScore; } /// <summary> /// Returns a string that lists the cards in the hand. /// </summary> /// <returns>A string that lists the cards in the hand.</returns> public override string ToString() { string ans = ""; foreach (Card c in h) { ans = ans + c.ToString() + "\n"; } return ans; } } }
36,769
https://github.com/CSB5/OPERA-MS/blob/master/bin/cluster_info.pl
Github Open Source
Open Source
MIT
2,022
OPERA-MS
CSB5
Perl
Code
890
4,446
#!/usr/bin/perl use warnings; use Statistics::Basic qw(:all); use Switch; my ($assembly_dir, $bin_dir) = @ARGV; my %contig_to_bin; my %contig_to_illumina_assembly;#for each opera-ms contigs identify the contig and their sizes that were used => allows to compute the illumina N50 and assembly size => allows to indentify the size of gaps as well my %bin_info = (); analyze_scaffold("$assembly_dir/intermediate_files/opera_long_read/scaffolds.scaf", \%contig_to_illumina_assembly); #Get the contigs in bin analyze_bin("$bin_dir", \%contig_to_bin, \%bin_info); #Get contig info analyze_contig_info("$assembly_dir/contig_info.txt", \%contig_to_bin, \%bin_info, \%contig_to_illumina_assembly); #Get checkm info #analyze_checkm("$bin_dir/eval.dat", \%bin_info); #Get mash information analyze_mash("$bin_dir/mash.dist", \%bin_info); #Get the kraken info #analyze_kraken("$assembly_dir/kraken/", "species", \%bin_info); #analyze_kraken("$assembly_dir/kraken/", "genus", \%bin_info); print_info(\%bin_info); sub print_info{ my ($bin_info) = @_; my @col_order = ( "CLUSTER_ID", # "SHORT_READ_COV", "LONG_READ_COV", # #"COMLETENESS", #"CONTAMINATION", # "SPECIES", "SIMILARITY", "CLUSTER_SIZE", "NB_CONTIG", "LONGEST_CONTIG", # #"ILLUMINA_N90", #"CONTIG_SIZE", "N50", "L50", #"NG50", "N90", "L90", #"NG90", # "SHORT_READ_NB_CONTIG", "SHORT_READ_LONGEST_CONTIG", "SHORT_READ_N50", "SHORT_READ_L50", #"FRAQ_READ", #"ILLU_S_ABUND", #"ILLU_G_ABUND", #"LONG_S_ABUND", #"LONG_G_ABUND" ); print "" . join("\t", @col_order) . "\n"; $bin_info->{"unclustered"}->{"SPECIES"} = "NA"; $bin_info->{"unclustered"}->{"SIMILARITY"} = "NA"; foreach $bin (sort {$bin_info->{$b}->{"N50"} <=> $bin_info->{$a}->{"N50"}} keys %{$bin_info}){ print $bin; foreach $info (@col_order){ next if($info eq "CLUSTER_ID"); print "\t" . $bin_info->{$bin}->{$info}; #print STDERR $bin . "\t" .$info . "\n"; } print "\n"; } } sub analyze_scaffold{ my ($scaffold_file, $contig_to_illumina_assembly) = @_; my %contig_name = (); open(FILE, "$scaffold_file.cname"); while(<FILE>){ chop $_; ($scaff_name, $c_name) = split(/\t/, $_); $contig_name{$scaff_name} = $c_name; } close(FILE); # #open(FILE, "sed 's/scaffold/contig/' $scaffold_file |"); open(FILE, $scaffold_file); my $opera_contig = ""; while(<FILE>){ chop $_; @line = split(/\t/, $_); if ($line[0] =~ />(.*)/){ $opera_scaff = $1; $opera_contig = $contig_name{$opera_scaff}; #print STDERR " *** $opera_contig\n";<STDIN>; #$opera_contig = ">".$1; $contig_to_illumina_assembly->{$opera_contig} = []; } else{ $illumina_contig_length = $line[2]; #print STDERR " *** $illumina_contig_length\n";<STDIN>; push(@{$contig_to_illumina_assembly->{$opera_contig}}, $illumina_contig_length); #print STDERR " *** $opera_contig $illumina_contig_length " . "[" . join(" " , @{$contig_to_illumina_assembly->{$opera_contig}}). "]\n";<STDIN>; } } close(FILE); } sub analyze_mash{ my ($mash_file, $bin_info) = @_; print STDERR " Analyze mash bin comparison from $mash_file\n"; open(FILE, "sort -k3,3 -n $mash_file |"); while(<FILE>){ @line = split(/\t/, $_); #Get the bin $str = $line[1]; @str_tab = split(/\//, $str); $bin = $str_tab[@str_tab-1]; @str_tab = split(/\./, $bin); $bin_id = join("\.", @str_tab[0..@str_tab-2]); if($bin_info->{$bin_id}->{"SPECIES"} eq "NA"){ #print STDERR " *** " . "@str_tab" . " " . $bin_id . "\n";#<STDIN>; $similarity = $line[2]; #Get the species $str = $line[0]; @str_tab = split(/\//, $str); $file = $str_tab[@str_tab-1]; @str_tab = split(/\__/, $file); $species = $str_tab[0]; next if(index($species, "multispecies") != -1); $bin_info->{$bin_id}->{"SPECIES"} = $species; $bin_info->{$bin_id}->{"SIMILARITY"} = sprintf("%.6f", 1-$similarity) if($similarity ne "NA"); } } close(FILE); } sub analyze_kraken{ my ($kraken_file, $bin_info) = @_; print STDERR " Analyze kraken abundance from $kraken_file\n"; if(-e $kraken_file){ } } sub analyze_checkm{ my ($checkm_file, $bin_info) = @_; print STDERR " Analyze checkm evaluation in $checkm_file\n"; if(-e $checkm_file){ open(FILE, $checkm_file); <FILE>; <FILE>; <FILE>; while(<FILE>){ @line = split(/\s+/, $_); last if(@line < 14); $bin = $line[1]; #print STDERR " *** " . $bin . "\n"; $bin_info->{$bin}->{"COMLETENESS"} = $line[7]; $bin_info->{$bin}->{"CONTAMINATION"} = $line[8]; } close(FILE); } } sub analyze_contig_info{ my ($contig_info_file, $contig_to_bin, $bin_info, $illumina_contig_length) = @_; open(FILE, $contig_info_file); <FILE>; while(<FILE>){ chop $_; my ($contig, $contig_size, $contig_short_read_cov, $contig_long_read_cov, $contig_cluster, $contig_species, $nb_strain, $ref) = split(/\t/, $_); #print STDERR " *** $contig\n";<STDIN>; $bin = "UN_BINNED"; $bin = $contig_to_bin->{$contig} if(exists $contig_to_bin->{$contig}); next if($contig_size < 500); #OPERA ASSEMBLY push(@{$bin_info->{$bin}->{"CONTIG_SIZE"}}, $contig_size); $bin_info->{$bin}->{"CLUSTER_SIZE"} += $contig_size; #ORIGINAL ILLUMINA ASSEMBLY push(@{$bin_info->{$bin}->{"SHORT_READ_CONTIG_SIZE"}}, @{$illumina_contig_length->{$contig}}); $bin_info->{$bin}->{"SHORT_READ_ASSEMBLY_SIZE"} += sum($illumina_contig_length->{$contig}); #print STDERR " *** $contig " . "[" . join(" " , @{$illumina_contig_length->{$contig}}). "]\n";<STDIN>; # $bin_info->{$bin}->{"SHORT_READ_COV"} += $contig_short_read_cov * $contig_size; $bin_info->{$bin}->{"LONG_READ_COV"} += $contig_long_read_cov * $contig_size; #print STDERR $bin . "\t" . $contig . "\t" . $contig_size . "\n"; } close(FILE); my @sort_tab = ();my $assembly_size; foreach $bin (keys %{$bin_info}){ $assembly_size = $bin_info->{$bin}->{"CLUSTER_SIZE"}; #print STDERR $bin . "\t" . $assembly_size . "\n";<STDIN>; #next; $bin_info->{$bin}->{"SHORT_READ_COV"} = sprintf("%.2f", $bin_info->{$bin}->{"SHORT_READ_COV"} / $assembly_size); $bin_info->{$bin}->{"LONG_READ_COV"} = sprintf("%.2f", $bin_info->{$bin}->{"LONG_READ_COV"} / $assembly_size); @sort_tab = sort {$b <=> $a} @{$bin_info->{$bin}->{"CONTIG_SIZE"}}; $n50_pos = compute_Nx(50, $assembly_size, \@sort_tab); $n90_pos = compute_Nx(90, $assembly_size, \@sort_tab); # $bin_info->{$bin}->{"LONGEST_CONTIG"} = $sort_tab[0]; $bin_info->{$bin}->{"NB_CONTIG"} = @sort_tab+0; $bin_info->{$bin}->{"N50"} = $sort_tab[$n50_pos]; $bin_info->{$bin}->{"L50"} = $n50_pos+1; $bin_info->{$bin}->{"N90"} = $sort_tab[$n90_pos]; $bin_info->{$bin}->{"L90"} = $n90_pos+1; # #For ILLUMINA ONLY ASSEMBLY $assembly_size = $bin_info->{$bin}->{"SHORT_READ_ASSEMBLY_SIZE"}; #print STDERR " *** assembly size $assembly_size\n";<STDIN>; @sort_tab = sort {$b <=> $a} @{$bin_info->{$bin}->{"SHORT_READ_CONTIG_SIZE"}}; $n50_pos = compute_Nx(50, $assembly_size, \@sort_tab); $n90_pos = compute_Nx(90, $assembly_size, \@sort_tab); # $bin_info->{$bin}->{"SHORT_READ_LONGEST_CONTIG"} = $sort_tab[0]; $bin_info->{$bin}->{"SHORT_READ_NB_CONTIG"} = @sort_tab+0; $bin_info->{$bin}->{"SHORT_READ_N50"} = $sort_tab[$n50_pos]; $bin_info->{$bin}->{"SHORT_READ_L50"} = $n50_pos+1; $bin_info->{$bin}->{"SHORT_READ_N90"} = $sort_tab[$n90_pos]; #$bin_info->{$bin}->{"ILLUMINA_N90_CONTIG"} = $n90_pos+1; # } } sub analyze_bin{ my ($bin_dir, $contig_to_bin, $bin_info) = @_; opendir(DIR, $bin_dir); my @all_bin = readdir(DIR); close(DIR); foreach $bin (@all_bin){ if($bin =~ m /(.+)\.fa/){ $bin_id = $1; #if(index($bin, ".fa") != -1){ $bin_info->{$bin_id} = init_bin(); open(FILE, "$bin_dir/$bin"); while(<FILE>){ chop $_; $name = $_; if($name =~ m />(.+)/){ #print STDERR $name . " " . $bin . "\n";<STDIN>; $name = $1; #print STDERR " *** $name $bin_id\n";<STDIN>; $contig_to_bin->{$name} = $bin_id; } } close(FILE); } } } sub init_bin{ my %genome_init = ("SPECIES", "NA", "SIMILARITY", "NA", # "CLUSTER_SIZE", 0, "LONGEST_CONTIG", "NA", "CONTIG_SIZE", [], "NB_CONTIG", "NA", "N50", "NA", "L50", "NA", "NG50", "NA", "N90", "NA", "L90", "NA", "NG90", "NA", # "SHORT_READ_ASSEMBLY_SIZE", 0, "SHORT_READ_LONGEST_CONTIG", "NA", "SHORT_READ_CONTIG_SIZE", [], "SHORT_READ_NB_CONTIG", NA, "SHORT_READ_N50", "NA", "SHORT_READ_L50", "NA", #"ILLUMINA_N50_CONTIG", "NA", #"ILLUMINA_NG50", "NA", "SHORT_READ_N90", "NA", #"ILLUMINA_N90_CONTIG", "NA", #"ILLUMINA_NG90", "NA", # "SHORT_READ_COV", 0, "LONG_READ_COV", 0, # "FRAQ_READ", "NA", "COMLETENESS", "NA", "CONTAMINATION", "NA", "KRAKEN_SPECIES_ABUNDANCE", "NA", "KRAKEN_GENUS_ABUNDANCE", "NA" ); return \%genome_init; } sub compute_Nx{ my ($x, $length, $ptr_tab) = @_; my $nb_x_base = $length * ($x / 100); my $total = 0; my $i = 0; for($i = 0; $total < $nb_x_base; $i++){ $total += $ptr_tab->[$i]; } return $i -1; } sub sum{ my ($array) = @_; my $res = 0; foreach $s (@{$array}){ $res += $s; } return $res; } #/home/bertrandd/PROJECT_LINK/OPERA_LG/META_GENOMIC_HYBRID_ASSEMBLY/OPERA-MS-DEV/OPERA-MS/utils/perl /home/bertrandd/PROJECT_LINK/OPERA_LG/META_GENOMIC_HYBRID_ASSEMBLY/OPERA-MS-DEV/OPERA-MS//bin/cluster_info.pl /mnt/projects/lich/backup/IOMICS/ANALYSIS/ASSEMBLY_9.0/TLL44/ /mnt/projects/lich/backup/IOMICS/ANALYSIS/ASSEMBLY_9.0/TLL44//opera_ms_clusters > /mnt/projects/lich/backup/IOMICS/ANALYSIS/ASSEMBLY_9.0/TLL44//opera_ms_clusters/../cluster_info.txt
50,590
https://github.com/KOSASIH/fhe-toolkit-macos/blob/master/Documentation/HElib/html/search/variables_3.js
Github Open Source
Open Source
MIT
2,021
fhe-toolkit-macos
KOSASIH
JavaScript
Code
6
173
var searchData= [ ['e_1244',['e',['../classhelib_1_1_recrypt_data.html#a0d3b37785a0bf499c5d51ae43fa40442',1,'helib::RecryptData']]], ['ea_1245',['ea',['../classhelib_1_1_context.html#a8319e609dbde819ac81130b035711fee',1,'helib::Context::ea()'],['../classhelib_1_1_recrypt_data.html#ae0199b0be0a64b8ca3ed11add68a422a',1,'helib::RecryptData::ea()']]] ];
26,219
https://github.com/OrangePeelFX/Python-Tutorial/blob/master/Scripts/003_hackerrank/Python/p041.py
Github Open Source
Open Source
MIT
null
Python-Tutorial
OrangePeelFX
Python
Code
29
98
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Problem 041 Eye and Identity Source : https://www.hackerrank.com/challenges/np-eye-and-identity/problem """ import numpy as np np.set_printoptions(sign=' ') n, m = map(int, input().split()) print(np.eye(n, m))
40,519
https://github.com/BryanApellanes/bamsdo/blob/master/bam.net.schema.org/Schema.Org/Things/FAQPage.cs
Github Open Source
Open Source
MIT
null
bamsdo
BryanApellanes
C#
Code
27
83
using Bam.Net.Schema.Org.DataTypes; namespace Bam.Net.Schema.Org.Things { ///<summary>A FAQPage is a WebPage presenting one or more "Frequently asked questions" (see also QAPage).</summary> public class FAQPage: WebPage { } }
40,515
https://github.com/SpellFang/React-materialUI-to-do-list/blob/master/src/commonComponents/index.js
Github Open Source
Open Source
MIT
null
React-materialUI-to-do-list
SpellFang
JavaScript
Code
64
157
export { default as AlertDialog } from "./AlertDialog/AlertDialog"; export { default as AddProjectDialog } from "./AddProjectDialog/AddProjectDialog"; export { default as AddTask } from "./AddTask/AddTask"; export { default as CustomizedToolTip } from "./CustomizedToolTip/CustomizedToolTip"; export { default as AddQuickTaskDialog } from "./AddQuickTaskDialog/AddQuickTaskDialog"; export { default as ProjectTreeWindow } from "./ProjectTreeWindow/ProjectTreeWindow"; export { default as CustomizedPopper } from "./CustomizedPopper/CustomizedPopper"; export { default as TimeLineWindow } from "./TimeLineWindow/TimeLineWindow";
5,920
https://github.com/B-Reif/bevy_proto/blob/master/src/lib.rs
Github Open Source
Open Source
Apache-2.0, MIT
2,022
bevy_proto
B-Reif
Rust
Code
359
936
#![warn(missing_docs)] //! Serializable entity configuration for the Bevy game engine. //! //! This crate provides several abstractions for specifying serializable entities and components: //! - The [`ProtoComponent`](components::ProtoComponent) trait provides methods to load components from assets. //! - The [`ProtoDeserializer`](data::ProtoDeserializer) trait describes component deserialization. //! - [`ProtoPlugin`](plugin::ProtoPlugin) provides configuration for asset loading. //! //! # Examples //! //! Define a serialized prototype: //! ```yaml //! # assets/prototypes/simple-enemy.yaml //! name: "Simple Enemy" //! components: //! - type: Enemy //! - type: Attack //! value: //! damage: 10 //! ``` //! //! Implement `ProtoComponent` for the component types: //! ``` //! use bevy::prelude::*; //! use bevy_proto::prelude::*; //! use serde::{Deserialize, Serialize}; //! //! #[derive(Clone, Serialize, Deserialize, ProtoComponent, Component)] //! struct Enemy; //! //! #[derive(Clone, Serialize, Deserialize, ProtoComponent, Component)] //! struct Attack { //! damage: u16 //! } //! ``` //! //! Add the plugin: //! ``` //! use bevy::prelude::*; //! use bevy_proto::prelude::*; //! //! fn main() { //! App::new() //! .add_plugins(DefaultPlugins) //! //! .add_plugin(ProtoPlugin { //! options: Some(ProtoDataOptions { //! // You can also change the prototype directories here //! directories: vec![String::from("assets/prototypes")], //! // And specify whether you want the prototype files to be recursively loaded //! recursive_loading: false, //! // You can also update the allowed extensions within those directories //! extensions: Some(vec!["yaml", "json"]), //! ..ProtoDataOptions::default() //! }) //! }); //! } //! ``` //! //! Finally, spawn a prototype with a system: //! //! ``` //! use bevy::prelude::*; //! use bevy_proto::prelude::*; //! //! fn spawn_enemy(mut commands: Commands, data: Res<ProtoData>, asset_server: Res<AssetServer>) { //! let proto = data.get_prototype("Simple Enemy").expect("Prototype doesn't exist!"); //! //! // Spawns in our "Simple Enemy" Prototype //! proto.spawn(&mut commands, &data, &asset_server); //! } //! //! ``` //! extern crate bevy_proto_derive; mod components; pub use bevy_proto_derive::ProtoComponent; pub use components::ProtoComponent; mod plugin; pub use plugin::ProtoPlugin; mod prototype; pub use prototype::{deserialize_templates_list, Prototype, Prototypical}; pub mod data; #[macro_use] mod utils; pub mod prelude { //! Includes all public types and the macro to derive [`ProtoComponent`](super::components::ProtoComponent). pub use super::components::ProtoComponent; pub use super::data::*; pub use super::plugin::ProtoPlugin; pub use super::prototype::{Prototype, Prototypical}; pub use bevy_proto_derive::*; } #[cfg(doctest)] mod test_readme { macro_rules! external_doc_test { ($x:expr) => { #[doc = $x] extern "C" {} }; } external_doc_test!(include_str!("../README.md")); }
45,889
https://github.com/lemonce3/observer/blob/master/src/router/file.js
Github Open Source
Open Source
MIT
null
observer
lemonce3
JavaScript
Code
83
247
const Router = require('koa-router'); const router = module.exports = new Router(); const store = {}; router.post('/file', async ctx => { const { hash } = ctx.query; let data = Buffer.from([]); await new Promise((resolve) => { ctx.req.on('data', chunk => { data = Buffer.concat([data, chunk], data.length + chunk.length); }); ctx.req.on('end', () => { store[hash] = { blob: data, type: ctx.headers['content-type'], _time: Date.now() }; resolve(); }); }); ctx.body = 0; }); router.get('/file/:hash', ctx => { const file = store[ctx.params.hash]; ctx.type = file.type; ctx.body = file.blob; });
49,967
https://github.com/fleetbase/fleetops-api/blob/master/src/Listeners/HandleOrderCanceled.php
Github Open Source
Open Source
MIT
2,023
fleetops-api
fleetbase
PHP
Code
97
397
<?php namespace Fleetbase\FleetOps\Listeners; use Fleetbase\FleetOps\Events\OrderCanceled; use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Notifications\OrderCanceled as OrderCanceledNotification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; class HandleOrderCanceled implements ShouldQueue { use InteractsWithQueue; /** * Handle the event. * * @param object $event * @return void */ public function handle(OrderCanceled $event) { /** @var \Fleetbase\FleetOps\Models\Order $order */ $order = $event->getModelRecord(); $location = $order->getLastLocation(); // update order activity $order->setStatus('canceled'); $order->createActivity('Order canceled', 'Order was canceled', $location, $order->status); if ($order->isIntegratedVendorOrder()) { $order->facilitator->provider()->callback('onCanceled', $order); } // notify driver assigned order was canceled if ($order->hasDriverAssigned) { /** @var \Fleetbase\Models\Driver */ $driver = Driver::where('uuid', $order->driver_assigned_uuid)->withoutGlobalScopes()->first(); if ($driver) { $driver->notify(new OrderCanceledNotification($order)); } } } }
48,587
https://github.com/afelipeg0808/ecommerce-site/blob/master/imports/ui/reducers/postsReducer.js
Github Open Source
Open Source
MIT
2,020
ecommerce-site
afelipeg0808
JavaScript
Code
75
228
/** @format */ import { GET_LATESTS_GUEST_POSTS, GET_LATESTS_AUTH_POSTS } from "../actions/posts"; import { Posts } from "../../api/schemas"; const postsInitState = { posts: [] }; const postsReducer = (state = postsInitState, action) => { let fetchedPosts; switch (action.type) { case GET_LATESTS_GUEST_POSTS: fetchedPosts = Posts.find({}, { limit: 4 }).fetch(); return { ...state, posts: fetchedPosts }; case GET_LATESTS_AUTH_POSTS: fetchedPosts = Posts.find({}, { limit: 4 }).fetch(); return { ...state, posts: fetchedPosts }; default: return state; } }; export default postsReducer;
45,097
https://github.com/celeron55/buildat/blob/master/src/client/state.cpp
Github Open Source
Open Source
Apache-2.0
2,019
buildat
celeron55
C++
Code
1,428
5,785
// http://www.apache.org/licenses/LICENSE-2.0 // Copyright 2014 Perttu Ahola <celeron55@gmail.com> #include "core/log.h" #include "client/state.h" #include "client/app.h" #include "client/config.h" #include "interface/tcpsocket.h" #include "interface/packet_stream.h" #include "interface/sha1.h" #include "interface/fs.h" #include "lua_bindings/replicate.h" #include <c55/string_util.h> #include <cereal/archives/portable_binary.hpp> #include <cereal/types/string.hpp> #include <Node.h> #include <Scene.h> #include <MemoryBuffer.h> #include <SmoothedTransform.h> #include <cstring> #include <fstream> #include <deque> #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif // Without this some of the network functions are not found on mingw #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif #include <windows.h> #include <winsock2.h> #include <ws2tcpip.h> #ifdef _MSC_VER #pragma comment(lib, "ws2_32.lib") #endif typedef int socklen_t; #else #include <sys/socket.h> #endif #define MODULE "__state" namespace magic = Urho3D; using magic::Node; using magic::Component; using magic::SmoothedTransform; extern client::Config g_client_config; namespace client { struct CState: public State { sp_<interface::TCPSocket> m_socket; std::deque<char> m_socket_buffer; interface::PacketStream m_packet_stream; sp_<app::App> m_app; ss_ m_remote_cache_path; ss_ m_tmp_path; sm_<ss_, ss_> m_file_hashes; // name -> hash set_<ss_> m_waiting_files; // name bool m_tell_after_all_files_transferred_requested = false; // Connecting is possible only once. After that has happened, the whole // state has to be recreated for making a new connection. // In actuality the whole client application has to be recreated because // otherwise unwanted Lua state remains. bool m_connected = false; sm_<ss_, std::function<void(const ss_ &, const ss_ &)>> m_packet_handlers; CState(sp_<app::App> app): m_socket(interface::createTCPSocket()), m_app(app), m_remote_cache_path(g_client_config.get<ss_>("cache_path")+"/remote"), m_tmp_path(g_client_config.get<ss_>("cache_path")+"/tmp") { // Create directory for cached files interface::fs::create_directories(m_remote_cache_path); interface::fs::create_directories(m_tmp_path); setup_packet_handlers(); } void update() { if(m_socket->wait_data(0)){ read_socket(); handle_socket_buffer(); } } bool connect_host_port(const ss_ &address, const ss_ &port, ss_ *error) { if(m_connected){ log_i(MODULE, "client::State: Cannot re-use state for new connection"); if(error) *error = "Cannot re-use state for new connection"; return false; } bool ok = m_socket->connect_fd(address, port); if(ok){ log_i(MODULE, "client::State: Connect succeeded (%s:%s)", cs(address), cs(port)); m_connected = true; } else { log_i(MODULE, "client::State: Connect failed (%s:%s)", cs(address), cs(port)); if(error) *error = "Connect failed"; } return ok; } bool connect(const ss_ &address, ss_ *error) { if(address.empty()){ if(error) *error = "Cannot connect to empty address"; return false; } ss_ host; ss_ port; c55::Strfnd f(address); if(address[0] == '['){ f.next("["); host = f.next("]"); f.next(":"); port = f.next(""); } else { host = f.next(":"); port = f.next(""); } if(host == ""){ if(error) *error = "Cannot connect to empty host"; return false; } if(port == ""){ port = "20000"; } return connect_host_port(host, port, error); } void send_packet(const ss_ &name, const ss_ &data) { log_v(MODULE, "send_packet(): name=%s", cs(name)); m_packet_stream.output(name, data, [&](const ss_ &packet_data){ m_socket->send_fd(packet_data); }); } ss_ get_file_path(const ss_ &name, ss_ *dst_file_hash) { auto it = m_file_hashes.find(name); if(it == m_file_hashes.end()) return ""; const ss_ &file_hash = it->second; ss_ file_hash_hex = interface::sha1::hex(file_hash); ss_ path = m_remote_cache_path+"/"+file_hash_hex; if(dst_file_hash != nullptr) *dst_file_hash = file_hash; return path; } ss_ get_file_content(const ss_ &name) { ss_ file_hash; ss_ path = get_file_path(name, &file_hash); std::ifstream f(path); if(!f.good()) throw Exception(ss_()+"Could not open file: "+path); std::string file_content((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); ss_ file_hash2 = interface::sha1::calculate(file_content); if(file_hash != file_hash2){ log_e(MODULE, "Opened file differs in hash: \"%s\": " "requested %s, actual %s", cs(name), cs(interface::sha1::hex(file_hash)), cs(interface::sha1::hex(file_hash2))); throw Exception(ss_()+"Invalid file content: "+path); } return file_content; } void read_socket() { int fd = m_socket->fd(); char buf[100000]; ssize_t r = recv(fd, buf, 100000, 0); if(r == -1) throw Exception(ss_()+"Receive failed: "+strerror(errno)); if(r == 0){ log_w(MODULE, "Peer disconnected"); return; } log_d(MODULE, "Received %zu bytes", r); m_socket_buffer.insert(m_socket_buffer.end(), buf, buf + r); } void handle_socket_buffer() { m_packet_stream.input(m_socket_buffer, [&](const ss_ &name, const ss_ &data){ try { handle_packet(name, data); } catch(std::exception &e){ log_w(MODULE, "Exception on handling packet: %s", e.what()); } }); } void setup_packet_handlers(); void handle_packet(const ss_ &packet_name, const ss_ &data) { auto it = m_packet_handlers.find(packet_name); if(it == m_packet_handlers.end()){ // Pass forward m_app->handle_packet(packet_name, data); } else { // Use handler auto &handler = it->second; handler(packet_name, data); } } }; void CState::setup_packet_handlers() { m_packet_handlers["core:run_script"] = [this](const ss_ &packet_name, const ss_ &data) { log_i(MODULE, "Asked to run script:\n----\n%s\n----", cs(data)); if(m_app) m_app->run_script(data); }; m_packet_handlers["core:announce_file"] = [this](const ss_ &packet_name, const ss_ &data) { ss_ file_name; ss_ file_hash; std::istringstream is(data, std::ios::binary); { cereal::PortableBinaryInputArchive ar(is); ar(file_name); ar(file_hash); } m_file_hashes[file_name] = file_hash; ss_ file_hash_hex = interface::sha1::hex(file_hash); log_v(MODULE, "Server announces file: %s %s", cs(file_hash_hex), cs(file_name)); // Check if we already have this file ss_ path = m_remote_cache_path+"/"+file_hash_hex; std::ifstream ifs(path, std::ios::binary); bool cached_is_ok = false; if(ifs.good()){ std::string content((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); ss_ content_hash = interface::sha1::calculate(content); if(content_hash == file_hash){ // We have it; no need to ask this file log_i(MODULE, "%s %s: cached", cs(file_hash_hex), cs(file_name)); cached_is_ok = true; } else { // Our copy is broken, re-request it log_i(MODULE, "%s %s: Our copy is broken (has hash %s)", cs(file_hash_hex), cs(file_name), cs(interface::sha1::hex(content_hash))); } } if(cached_is_ok){ // Let Lua resource wrapper know that this happened so it can update // the copy made for Urho3D's resource cache m_app->file_updated_in_cache(file_name, file_hash, path); } else { // We don't have it; request this file log_i(MODULE, "%s %s: requesting", cs(file_hash_hex), cs(file_name)); std::ostringstream os(std::ios::binary); { cereal::PortableBinaryOutputArchive ar(os); ar(file_name); ar(file_hash); } send_packet("core:request_file", os.str()); m_waiting_files.insert(file_name); } }; m_packet_handlers["core:tell_after_all_files_transferred"] = [this](const ss_ &packet_name, const ss_ &data) { if(m_waiting_files.empty()){ send_packet("core:all_files_transferred", ""); } else { m_tell_after_all_files_transferred_requested = true; } }; m_packet_handlers["core:file_content"] = [this](const ss_ &packet_name, const ss_ &data) { ss_ file_name; ss_ file_hash; ss_ file_content; std::istringstream is(data, std::ios::binary); { cereal::PortableBinaryInputArchive ar(is); ar(file_name); ar(file_hash); ar(file_content); } if(m_waiting_files.count(file_name) == 0){ log_w(MODULE, "Received file was not requested: %s %s", cs(interface::sha1::hex(file_hash)), cs(file_name)); return; } m_waiting_files.erase(file_name); ss_ file_hash2 = interface::sha1::calculate(file_content); if(file_hash != file_hash2){ log_w(MODULE, "Requested file differs in hash: \"%s\": " "requested %s, actual %s", cs(file_name), cs(interface::sha1::hex(file_hash)), cs(interface::sha1::hex(file_hash2))); return; } ss_ file_hash_hex = interface::sha1::hex(file_hash); ss_ path = g_client_config.get<ss_>("cache_path")+"/remote/"+ file_hash_hex; log_i(MODULE, "Saving %s to %s", cs(file_name), cs(path)); std::ofstream of(path, std::ios::binary); of<<file_content; if(m_tell_after_all_files_transferred_requested){ if(m_waiting_files.empty()){ send_packet("core:all_files_transferred", ""); m_tell_after_all_files_transferred_requested = false; } } // Let Lua resource wrapper know that this happened so it can update // the copy made for Urho3D's resource cache m_app->file_updated_in_cache(file_name, file_hash, path); }; m_packet_handlers["replicate:create_node"] = [this](const ss_ &packet_name, const ss_ &data) { // For a reference implementation of this kind of network // synchronization, see Urho3D's Network/Connection.cpp magic::Scene *scene = m_app->get_scene(); magic::MemoryBuffer msg(data.c_str(), data.size()); uint node_id = msg.ReadNetID(); Node *node = scene->GetNode(node_id); if(node && node_id == 1){ // This is the scene } else if(node){ log_w(MODULE, "replicate:create_node: Node %i (old name=\"%s\")" " already exists. This could be due to a node having been" " accidentally created on the client side without mode=LOCAL." " If a node seems to mysteriously disappear, this is the" " reason.", node_id, node->GetName().CString()); } else { log_v(MODULE, "Creating node %i", node_id); // Add to the root level; it may be moved as we receive the parent // attribute node = scene->CreateChild(node_id, magic::REPLICATED); node->CreateComponent<SmoothedTransform>(magic::LOCAL); } // Read initial attributes node->ReadDeltaUpdate(msg); // Skip transition to first position SmoothedTransform *transform = node->GetComponent<SmoothedTransform>(); if(transform) transform->Update(1.0f, 0.0f); // Read initial user variables uint num_vars = msg.ReadVLE(); while(num_vars){ auto key = msg.ReadStringHash(); node->SetVar(key, msg.ReadVariant()); num_vars--; } // Read components uint num_c = msg.ReadVLE(); while(num_c){ num_c--; auto type = msg.ReadStringHash(); uint c_id = msg.ReadNetID(); Component *c = scene->GetComponent(c_id); if(!c || c->GetType() != type || c->GetNode() != node){ if(c){ log_w(MODULE, "replicate:create_node: Component %i already" " exists. This could be due to a component having" " been accidentally created on the client side" " without mode=LOCAL." " If a component seems to mysteriously disappear," " this is the reason.", c_id); c->Remove(); } log_v(MODULE, "Creating component %i", c_id); c = node->CreateComponent(type, magic::REPLICATED, c_id); if(!c){ log_e(MODULE, "Could not create component %i", c_id); return; } } c->ReadDeltaUpdate(msg); c->ApplyAttributes(); } lua_State *L = m_app->get_lua(); lua_bindings::replicate::on_node_created(L, node_id); }; m_packet_handlers["replicate:create_component"] = [this](const ss_ &packet_name, const ss_ &data) { log_w("TODO: %s", cs(packet_name)); }; m_packet_handlers["replicate:latest_node_data"] = [this](const ss_ &packet_name, const ss_ &data) { magic::Scene *scene = m_app->get_scene(); magic::MemoryBuffer msg(data.c_str(), data.size()); uint node_id = msg.ReadNetID(); Node *node = scene->GetNode(node_id); if(node){ log_d(MODULE, "Updating node %i (LatestDataUpdate)", node_id); node->ReadLatestDataUpdate(msg); } else { log_w(MODULE, "Out-of-order node data ignored for %i", node_id); // Note: Network/Connection.cpp would buffer this } }; m_packet_handlers["replicate:latest_component_data"] = [this](const ss_ &packet_name, const ss_ &data) { magic::Scene *scene = m_app->get_scene(); magic::MemoryBuffer msg(data.c_str(), data.size()); uint c_id = msg.ReadNetID(); Component *c = scene->GetComponent(c_id); if(c){ log_d(MODULE, "Updating component %i (LatestDataUpdate)", c_id); c->ReadLatestDataUpdate(msg); c->ApplyAttributes(); } else { log_w(MODULE, "Out-of-order component data ignored for %i", c_id); // Note: Network/Connection.cpp would buffer this } }; m_packet_handlers["replicate:node_delta_update"] = [this](const ss_ &packet_name, const ss_ &data) { magic::Scene *scene = m_app->get_scene(); magic::MemoryBuffer msg(data.c_str(), data.size()); uint node_id = msg.ReadNetID(); Node *node = scene->GetNode(node_id); if(node){ log_d(MODULE, "Updating node %i (DeltaUpdate)", node_id); node->ReadDeltaUpdate(msg); } else { log_w(MODULE, "Out-of-order node data ignored for %i", node_id); // Note: Network/Connection.cpp would NOT buffer this } // Read user variables uint num_vars = msg.ReadVLE(); while(num_vars){ auto key = msg.ReadStringHash(); node->SetVar(key, msg.ReadVariant()); num_vars--; } }; m_packet_handlers["replicate:component_delta_update"] = [this](const ss_ &packet_name, const ss_ &data) { log_w(MODULE, "TODO: %s", cs(packet_name)); // Note: Network/Connection.cpp would NOT buffer this }; m_packet_handlers["replicate:remove_node"] = [this](const ss_ &packet_name, const ss_ &data) { log_w(MODULE, "TODO: %s", cs(packet_name)); }; m_packet_handlers["replicate:remove_component"] = [this](const ss_ &packet_name, const ss_ &data) { log_w(MODULE, "TODO: %s", cs(packet_name)); }; m_packet_handlers[""] = [this](const ss_ &packet_name, const ss_ &data) { }; } State* createState(sp_<app::App> app) { return new CState(app); } } // vim: set noet ts=4 sw=4:
25,474
https://github.com/brattpurrie/Typescript-demo/blob/master/build/server.js
Github Open Source
Open Source
MIT
2,018
Typescript-demo
brattpurrie
JavaScript
Code
86
183
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var express_1 = __importDefault(require("express")); var controllers_1 = require("./controllers"); // Create a new express application instance var app = express_1.default(); // The port the express app will listen on var port = 3000; // mount the controller app.use('/welcome', controllers_1.WelcomeController); // serve the application at port app.listen(port, function () { console.log("Listening at http://localhost:" + port + "/"); });
25,026
https://github.com/shiver-me-timbers/smt-cloudformation-parent/blob/master/smt-cloudformation-objects/src/main/java/shiver/me/timbers/aws/inspector/AssessmentTarget.java
Github Open Source
Open Source
Apache-2.0
2,019
smt-cloudformation-parent
shiver-me-timbers
Java
Code
190
1,163
package shiver.me.timbers.aws.inspector; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; /** * AssessmentTarget * <p> * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-inspector-assessmenttarget.html * */ @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonPropertyOrder({ "AssessmentTargetName", "ResourceGroupArn" }) public class AssessmentTarget { /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-inspector-assessmenttarget.html#cfn-inspector-assessmenttarget-assessmenttargetname * */ @JsonProperty("AssessmentTargetName") @JsonPropertyDescription("http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-inspector-assessmenttarget.html#cfn-inspector-assessmenttarget-assessmenttargetname") private CharSequence assessmentTargetName; /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-inspector-assessmenttarget.html#cfn-inspector-assessmenttarget-resourcegrouparn * */ @JsonProperty("ResourceGroupArn") @JsonPropertyDescription("http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-inspector-assessmenttarget.html#cfn-inspector-assessmenttarget-resourcegrouparn") private CharSequence resourceGroupArn; /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-inspector-assessmenttarget.html#cfn-inspector-assessmenttarget-assessmenttargetname * */ @JsonIgnore public CharSequence getAssessmentTargetName() { return assessmentTargetName; } /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-inspector-assessmenttarget.html#cfn-inspector-assessmenttarget-assessmenttargetname * */ @JsonIgnore public void setAssessmentTargetName(CharSequence assessmentTargetName) { this.assessmentTargetName = assessmentTargetName; } public AssessmentTarget withAssessmentTargetName(CharSequence assessmentTargetName) { this.assessmentTargetName = assessmentTargetName; return this; } /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-inspector-assessmenttarget.html#cfn-inspector-assessmenttarget-resourcegrouparn * */ @JsonIgnore public CharSequence getResourceGroupArn() { return resourceGroupArn; } /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-inspector-assessmenttarget.html#cfn-inspector-assessmenttarget-resourcegrouparn * */ @JsonIgnore public void setResourceGroupArn(CharSequence resourceGroupArn) { this.resourceGroupArn = resourceGroupArn; } public AssessmentTarget withResourceGroupArn(CharSequence resourceGroupArn) { this.resourceGroupArn = resourceGroupArn; return this; } @Override public String toString() { return new ToStringBuilder(this).append("assessmentTargetName", assessmentTargetName).append("resourceGroupArn", resourceGroupArn).toString(); } @Override public int hashCode() { return new HashCodeBuilder().append(assessmentTargetName).append(resourceGroupArn).toHashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other instanceof AssessmentTarget) == false) { return false; } AssessmentTarget rhs = ((AssessmentTarget) other); return new EqualsBuilder().append(assessmentTargetName, rhs.assessmentTargetName).append(resourceGroupArn, rhs.resourceGroupArn).isEquals(); } }
27,517
https://github.com/U3DC/Planetaria/blob/master/Assets/Planetaria/Code/RuntimeCode/World/CubePlanetarium.cs
Github Open Source
Open Source
MIT-0
2,020
Planetaria
U3DC
C#
Code
419
1,084
using System; using System.Collections.Generic; using System.Linq; // TODO: Linq affects garbage collector (which affects virtual reality) using UnityEngine; namespace Planetaria { public class CubePlanetarium : WorldPlanetarium { public CubePlanetarium(int resolution) { material = new Material(Shader.Find("Mobile/Skybox")); textures = new Texture2D[6]; List<NormalizedCartesianCoordinates> positions = new List<NormalizedCartesianCoordinates>(); for (int index = 0; index < directions.Length; ++index) { List<Vector2> uvs = get_texture_uvs(resolution); positions.AddRange(uvs.Select(uv => (NormalizedCartesianCoordinates) new CubeUVCoordinates(uv.x, uv.y, index))); Texture2D texture = new Texture2D(resolution, resolution); material.SetTexture(directions[index], texture); } pixel_centroids = positions.ToArray(); } public override void set_pixels(Color32[] colors) { int pixels = colors.Length/directions.Length; int pixel_start = 0; Color32[] subarray = new Color32[pixels]; for (int index = 0; index < directions.Length; ++index) { Array.Copy(colors, pixel_start, subarray, 0, pixels); textures[index].SetPixels32(subarray); pixel_start += pixels; } } public override Color32[] get_pixels(NormalizedCartesianCoordinates[] positions) { Color32[] colors = new Color32[positions.Length]; for (int index = 0; index < positions.Length; ++index) { CubeUVCoordinates uv = positions[index]; int scale = textures[0].width; // assumes width/height are same and six textures are equal dimensions colors[index] = textures[uv.texture_index].GetPixel(uv.uv.x.scale(scale), uv.uv.y.scale(scale)); } return colors; } #if UNITY_EDITOR public override void save(string file_name) { WorldPlanetarium.save_material(material, file_name); // TODO: save subasset for (int face = 0; face < directions.Length; ++face) { WorldPlanetarium.save_texture(textures[face], file_name, directions[face]); } } public static optional<CubePlanetarium> load(string file_name) { optional<Material> material = WorldPlanetarium.load_material(file_name); if (!material.exists) { return new optional<CubePlanetarium>(); } int size = material.data.GetTexture(directions[0]).width; CubePlanetarium result = new CubePlanetarium(size); result.material = material.data; for (int face = 0; face < directions.Length; ++face) { Texture2D texture = (Texture2D) material.data.GetTexture(directions[face]); result.textures[face] = texture; } return result; } #endif private Texture2D[] textures; private static readonly string[] directions = { "_RightTex", "_LeftTex", "_UpTex", "_DownTex", "_FrontTex", "_BackTex" }; } } // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE.
42,165
https://github.com/Prakhar-100/DjangoProject/blob/master/Webllistoerp/attendance/admin.py
Github Open Source
Open Source
MIT
null
DjangoProject
Prakhar-100
Python
Code
19
112
from django.contrib import admin from .models import AttendanceModel, AttendanceData, DatewiseData, UserDayoffData, TimeSheetData, HolidayData admin.site.register(AttendanceModel) admin.site.register(AttendanceData) admin.site.register(DatewiseData) admin.site.register(UserDayoffData) admin.site.register(TimeSheetData) admin.site.register(HolidayData)
3,773
https://github.com/godotengine/godot/blob/master/modules/gdscript/tests/scripts/analyzer/features/out_of_order.gd
Github Open Source
Open Source
LicenseRef-scancode-free-unknown, MIT, CC-BY-4.0, OFL-1.1, Bison-exception-2.2, CC0-1.0, LicenseRef-scancode-nvidia-2002, LicenseRef-scancode-other-permissive, GPL-3.0-only, LicenseRef-scancode-unknown-license-reference, Unlicense, BSL-1.0, Apache-2.0, BSD-3-Clause, LicenseRef-scancode-public-domain, LicenseRef-scancode-unicode, BSD-2-Clause, FTL, GPL-3.0-or-later, Bitstream-Vera, Zlib, MPL-2.0, MIT-Modern-Variant
2,023
godot
godotengine
GDScript
Code
147
404
func test(): print("v1: ", v1) print("v1 is String: ", v1 is String) print("v2: ", v2) print("v2 is bool: ", v2 is bool) print("c1: ", c1) print("c1 is int: ", c1 is int) print("c2: ", c2) print("c2 is int: ", c2 is int) print("E1.V1: ", E1.V1) print("E1.V2: ", E1.V2) print("E2.V: ", E2.V) print("EV1: ", EV1) print("EV2: ", EV2) print("EV3: ", EV3) var v1 := InnerA.new().fn() class InnerA extends InnerAB: func fn(p2 := E1.V2) -> String: return "%s, p2=%s" % [super.fn(), p2] class InnerAB: func fn(p1 := c1) -> String: return "p1=%s" % p1 var v2 := f() func f() -> bool: return true const c1 := E1.V1 enum E1 { V1 = E2.V + 2, V2 = V1 - 1 } enum E2 {V = 2} const c2 := EV2 enum { EV1 = 42, UNUSED = EV3, EV2 } enum { EV3 = EV1 + 1 }
46,077
https://github.com/HalcyonGrid/whip-server/blob/master/whip/PushReplicationService.cpp
Github Open Source
Open Source
Apache-2.0
2,018
whip-server
HalcyonGrid
C++
Code
358
1,505
#include "StdAfx.h" #include "PushReplicationService.h" #include "AppLog.h" #include <string> #include <algorithm> PushReplicationService::PushReplicationService() : _ioService(), _connected(false), _connectionMonitor(_ioService), _sending(false) { } PushReplicationService::~PushReplicationService() { //dtor means we should already be stopped, but in the //case of a startup exception, this isn't true if (! _stop) { this->stop(); } } void PushReplicationService::start() { _stop = false; _serviceThread = boost::thread(boost::bind(&PushReplicationService::run, this)); } void PushReplicationService::run() { _work.reset(new boost::asio::io_service::work(_ioService)); this->resetConnectionMonitor(1); _ioService.run(); } void PushReplicationService::resetConnectionMonitor(int interval) { if (_stop) return; _connectionMonitor.expires_from_now(boost::posix_time::seconds(interval)); _connectionMonitor.async_wait(boost::bind(&PushReplicationService::onCheckConnection, this)); } void PushReplicationService::onCheckConnection() { if (_stop) return; //look up the slave endpoint std::string slaveHpp(whip::Settings::instance().replicationSlave()); if (slaveHpp != "") { boost::asio::ip::tcp::endpoint ep(whip::Settings::ParseHostPortPairToTcpEndpoint(slaveHpp)); if (ep != _replicationSlaveEndpoint) { this->endpointChanged(ep); } else { if (! _connected) { //slave didnt change, but we need to connect this->makeConnection(); } else { this->resetConnectionMonitor(); } } } else { if (_connected) _replSlave->close(); this->resetConnectionMonitor(); } } void PushReplicationService::endpointChanged(boost::asio::ip::tcp::endpoint newEp) { _replicationSlaveEndpoint = newEp; if (_connected) { _replSlave->close(); this->resetConnectionMonitor(); } else { this->makeConnection(); } } void PushReplicationService::makeConnection() { SAFELOG(AppLog::instance().out() << "[REPL] Connecting to push replication slave " << _replicationSlaveEndpoint << std::endl); _replSlave.reset(new RemoteAssetService(_replicationSlaveEndpoint, _ioService)); _replSlave->setSafekillCallback(boost::bind(&PushReplicationService::onSafeKillConnection, this, _1)); _replSlave->connect(boost::bind(&PushReplicationService::onServiceConnectionStatus, this, _1, _2)); } void PushReplicationService::onSafeKillConnection(RemoteAssetService::ptr assetSvc) { _connected = false; _sending = false; std::queue<Asset::ptr> empty; std::swap(_waitingAssets, empty); } void PushReplicationService::onServiceConnectionStatus(RemoteAssetService::ptr ras, bool success) { if (success) { SAFELOG(AppLog::instance().out() << "[REPL] Connected to push replication slave " << _replicationSlaveEndpoint << std::endl); _connected = true; } else { SAFELOG(AppLog::instance().error() << "[REPL] Connection to push replication slave " << _replicationSlaveEndpoint << " failed" << std::endl); } this->resetConnectionMonitor(); } void PushReplicationService::queueAssetForPush(Asset::ptr asset) { _ioService.post(boost::bind(&PushReplicationService::doQueueAssetForPush, this, asset)); } void PushReplicationService::doQueueAssetForPush(Asset::ptr asset) { if (! _connected || _stop) return; if (_sending) { if (_waitingAssets.size() > MAX_QUEUE_SIZE) { return; } _waitingAssets.push(asset); } else { this->doPutAsset(asset); } } void PushReplicationService::doPutAsset(Asset::ptr asset) { if (_stop) return; _sending = true; _replSlave->putAsset(asset, boost::bind(&PushReplicationService::onAfterAssetPut, this, _1, _2, _3)); } void PushReplicationService::onAfterAssetPut(Asset::ptr asset, RASError error, std::string data) { _sending = false; if (error) { SAFELOG(AppLog::instance().error() << "[REPL] Push replication failed asset: " << data << std::endl); } this->pushNextWaitingAsset(); } void PushReplicationService::pushNextWaitingAsset() { if (_connected && !_stop) { if (_waitingAssets.size() > 0) { Asset::ptr asset(_waitingAssets.front()); _waitingAssets.pop(); this->doPutAsset(asset); } } } void PushReplicationService::stop() { _ioService.post(boost::bind(&PushReplicationService::doStop, this)); _serviceThread.join(); } void PushReplicationService::doStop() { _stop = true; _work.reset(); if (_connected) _replSlave->close(); }
2,916
https://github.com/571821151/MyBLE-master/blob/master/app/src/main/java/com/clj/blexy/ControlActivity.java
Github Open Source
Open Source
Apache-2.0
null
MyBLE-master
571821151
Java
Code
864
4,009
/* * Copyright (cly) 2019. */ package com.clj.blexy; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattService; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.clj.blexy.Fragment.ControlFragment; import com.clj.blexy.Fragment.SetPositionFragment; import com.clj.blexy.Fragment.SettingFragment; import com.clj.blexy.comm.BleUtils; import com.clj.blexy.comm.Observer; import com.clj.blexy.comm.ObserverManager; import com.clj.fastble.BleManager; import com.clj.fastble.callback.BleNotifyCallback; import com.clj.fastble.callback.BleWriteCallback; import com.clj.fastble.data.BleDevice; import com.clj.fastble.exception.BleException; import com.clj.fastble.utils.HexUtil; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class ControlActivity extends AppCompatActivity implements View.OnClickListener, Observer { private static final String TAG = ControlActivity.class.getSimpleName(); public static final String KEY_DATA = "key_data"; private BleDevice bleDevice; private List<Fragment> fragments = new ArrayList<>(); private int currentPage = 0; private LinearLayout btn_left; private LinearLayout btn_right; private ImageView imageView_left; private ImageView imageView_right; private TextView tv_back; private LinearLayout layout_bottom; private BluetoothGattCharacteristic characteristicWrite; private BluetoothGattCharacteristic characteristicNotify; private UUID serviceUUID; private UUID writeUUID; private UUID notifyUUID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_main); serviceUUID = UUID.fromString("6e40fff0-b5a3-f393-e0a9-e50e24dcca9e"); writeUUID = UUID.fromString("6e40fff2-b5a3-f393-e0a9-e50e24dcca9e"); notifyUUID = UUID.fromString("6e40fff1-b5a3-f393-e0a9-e50e24dcca9e"); btn_left = findViewById(R.id.btn_control_left); btn_left.setOnClickListener(this); btn_right = findViewById(R.id.btn_control_right); btn_right.setOnClickListener(this); imageView_left = findViewById(R.id.view_left); imageView_right = findViewById(R.id.view_right); layout_bottom = findViewById(R.id.layout_bottom); tv_back = findViewById(R.id.tv_back); tv_back.setOnClickListener(this); imageView_head = findViewById(R.id.img1); imageView_leg_one = findViewById(R.id.img3); imageView_leg_two = findViewById(R.id.img4); ObserverManager.getInstance().addObserver(this); initPage(); } private void initPage() { prepareFragment(); changePage(0); Thread thread = new Thread(new Runnable() { @Override public void run() { try { writeBleMessage(BleUtils.LENGTH_DETECT); Thread.sleep(14000); runOnUiThread(new Runnable() { @Override public void run() { writeBleMessage(BleUtils.READ_RIGHT); //自动挂掉 // onDestroy(); } }); } catch (InterruptedException e) { Log.e(TAG, "run: ", e); } } }); thread.start(); bleDevice = getIntent().getParcelableExtra(KEY_DATA); startNotify(); if (bleDevice != null) { BluetoothGatt gatt = BleManager.getInstance().getBluetoothGatt(bleDevice); if (gatt == null) return; // Toast.makeText(this, gatt.getServices().size(), Toast.LENGTH_SHORT).show(); for (BluetoothGattService service : gatt.getServices()) { if (service.getUuid().toString().contains("fff0")) { serviceUUID = service.getUuid(); for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) { int charaProp = characteristic.getProperties(); if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { Toast.makeText(this, characteristic.getUuid().toString(), Toast.LENGTH_SHORT).show(); characteristicNotify = characteristic; UUID uuid = characteristic.getUuid(); if (uuid.toString().contains("fff2")) { writeUUID = uuid; } if (uuid.toString().contains("fff1")) { notifyUUID = uuid; } } // if ((charaProp | BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0) { // Toast.makeText(this, characteristic.getUuid().toString(), Toast.LENGTH_SHORT).show(); // characteristicWrite = characteristic; // writeUUID = characteristic.getUuid(); // // } // writeBleMessage("0x10"); // break; } } } } } public Integer source_degree_left = 0; public Integer source_degree_right = 0; private ImageView imageView_head; private ImageView imageView_leg_one; private ImageView imageView_leg_two; float source_x, source_y; /** * 设置左边图片动画 * * @param todegeree */ public void setDegree_left(int todegeree) { RotateAnimation rotateAni = new RotateAnimation(source_degree_left, todegeree, Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0.5f); //设置动画执行的时间,单位是毫秒 rotateAni.setDuration(100); // 设置动画重复次数 // -1或者Animation.INFINITE表示无限重复,正数表示重复次数,0表示不重复只播放一次 rotateAni.setRepeatCount(0); rotateAni.setFillAfter(true); // 启动动画 imageView_head.startAnimation(rotateAni); source_degree_left = todegeree; } //设置右边图片动画 public void setDegree_right(int todegeree) { RotateAnimation rotateAni = new RotateAnimation(source_degree_right, todegeree, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0.5f); //设置动画执行的时间,单位是毫秒 rotateAni.setDuration(100); // 设置动画重复次数 // -1或者Animation.INFINITE表示无限重复,正数表示重复次数,0表示不重复只播放一次 rotateAni.setRepeatCount(0); rotateAni.setFillAfter(true); // 启动动画 imageView_leg_one.startAnimation(rotateAni); source_degree_right = todegeree; double rect_angle = -todegeree * Math.PI / 180; int width = imageView_leg_one.getWidth(); float x_position = (float) Math.cos(rect_angle) * width; float y_position = (float) Math.sin(rect_angle) * width; TranslateAnimation translateAni = new TranslateAnimation(source_x, x_position - width, source_y, -y_position); Log.d(TAG, "setDegree_right: source_x" + source_x + "x_position" + x_position + "source_y" + source_y + "y_position" + y_position); source_x = -width + x_position; source_y = -y_position; //设置动画执行的时间,单位是毫秒 translateAni.setDuration(100); translateAni.setFillAfter(true); // 设置动画重复次数 // -1或者Animation.INFINITE表示无限重复,正数表示重复次数,0表示不重复只播放一次 translateAni.setRepeatCount(0); // 启动动画 imageView_leg_two.startAnimation(translateAni); } public void disconnect() { for (int i = 0; i < 4; i++) BleUtils.writeBleCode(this, BleUtils.RELEASE_CODE); } public void writeBleMessage(String hex) { BleManager.getInstance().write( bleDevice, serviceUUID.toString(), writeUUID.toString(), HexUtil.hexStringToBytes(hex), new BleWriteCallback() { @Override public void onWriteSuccess(final int current, final int total, final byte[] justWrite) { runOnUiThread(new Runnable() { @Override public void run() { // Toast.makeText(ControlActivity.this, "" + HexUtil.formatHexString(justWrite, true), Toast.LENGTH_SHORT).show(); } }); } @Override public void onWriteFailure(final BleException exception) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(ControlActivity.this, "" + "write failure" + exception.getDescription(), Toast.LENGTH_SHORT).show(); } }); } }); } public void startNotify() { BleManager.getInstance().notify( bleDevice, serviceUUID.toString(), notifyUUID.toString(), new BleNotifyCallback() { @Override public void onNotifySuccess() { } @Override public void onNotifyFailure(BleException exception) { Toast.makeText(ControlActivity.this, "Notify failure", Toast.LENGTH_SHORT).show(); } @Override public void onCharacteristicChanged(byte[] data) { String str = HexUtil.formatHexString(data); Toast.makeText(ControlActivity.this, "Notified " + str, Toast.LENGTH_SHORT).show(); } }); } public void changePage(int page) { currentPage = page; updateFragment(page); } private void prepareFragment() { fragments.add(new ControlFragment()); fragments.add(new SettingFragment()); fragments.add(new SetPositionFragment()); for (Fragment fragment : fragments) { getSupportFragmentManager().beginTransaction().add(R.id.fragment_main, fragment).hide(fragment).commit(); } } @Override protected void onDestroy() { super.onDestroy(); ObserverManager.getInstance().deleteObserver(this); } private void updateFragment(int position) { if (position > fragments.size() - 1) { return; } for (int i = 0; i < fragments.size(); i++) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out); Fragment fragment = fragments.get(i); if (i == position) { transaction.show(fragment); if (i == 2) layout_bottom.setVisibility(View.INVISIBLE); else layout_bottom.setVisibility(View.VISIBLE); } else { transaction.hide(fragment); } transaction.commit(); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_control_left: changePage(0); changeBtnImage(); break; case R.id.btn_control_right: changePage(1); changeBtnImage(); break; case R.id.tv_back: Intent intent = new Intent(); //把返回数据存入Intent intent.putExtra("result", "My name is ChenLingYun"); //设置返回数据 this.setResult(RESULT_OK, intent); //关闭Activity this.finish(); break; } } private void changeBtnImage() { Log.d(TAG, "changeBtnImage: " + currentPage); switch (currentPage) { case 0: btn_left.setBackgroundResource(R.mipmap.brown_back); btn_right.setBackgroundResource(R.mipmap.white_back); imageView_left.setImageResource(R.mipmap.control_w); imageView_right.setImageResource(R.mipmap.mode_g); break; case 1: btn_left.setBackgroundResource(R.mipmap.white_back); btn_right.setBackgroundResource(R.mipmap.brown_back); imageView_left.setImageResource(R.mipmap.control); imageView_right.setImageResource(R.mipmap.mode); break; } } @Override public void disConnected(BleDevice bleDevice) { Intent intent = new Intent(); //把返回数据存入Intent intent.putExtra("result", "My name is linjiqin"); //设置返回数据 this.setResult(RESULT_OK, intent); //关闭Activity this.finish(); } /** * 设置主面板动画 * * @param leftPercent * @param rightPercent */ public void setMainAnime(int leftPercent, int rightPercent) { int degeree = leftPercent * ControlFragment.MAX_DEGEREE; setDegree_left(degeree); degeree = rightPercent * ControlFragment.MAX_DEGEREE; setDegree_right(degeree); } }
10,846
https://github.com/chrisgorgo/beam/blob/master/sdks/java/core/src/main/java/org/apache/beam/sdk/values/SchemaVerification.java
Github Open Source
Open Source
Apache-2.0
null
beam
chrisgorgo
Java
Code
929
2,520
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.values; import java.io.Serializable; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.beam.sdk.annotations.Experimental; import org.apache.beam.sdk.schemas.Schema; import org.apache.beam.sdk.schemas.Schema.FieldType; import org.apache.beam.sdk.schemas.Schema.LogicalType; import org.apache.beam.sdk.schemas.Schema.TypeName; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Maps; import org.joda.time.Instant; import org.joda.time.base.AbstractInstant; @Experimental public abstract class SchemaVerification implements Serializable { static List<Object> verifyRowValues(Schema schema, List<Object> values) { List<Object> verifiedValues = Lists.newArrayListWithCapacity(values.size()); if (schema.getFieldCount() != values.size()) { throw new IllegalArgumentException( String.format( "Field count in Schema (%s) (%d) and values (%s) (%d) must match", schema.getFieldNames(), schema.getFieldCount(), values, values.size())); } for (int i = 0; i < values.size(); ++i) { Object value = values.get(i); Schema.Field field = schema.getField(i); if (value == null) { if (!field.getType().getNullable()) { throw new IllegalArgumentException( String.format("Field %s is not nullable", field.getName())); } verifiedValues.add(null); } else { verifiedValues.add(verifyFieldValue(value, field.getType(), field.getName())); } } return verifiedValues; } public static Object verifyFieldValue(Object value, FieldType type, String fieldName) { if (TypeName.ARRAY.equals(type.getTypeName())) { return verifyArray(value, type.getCollectionElementType(), fieldName); } else if (TypeName.ITERABLE.equals(type.getTypeName())) { return verifyIterable(value, type.getCollectionElementType(), fieldName); } if (TypeName.MAP.equals(type.getTypeName())) { return verifyMap(value, type.getMapKeyType(), type.getMapValueType(), fieldName); } else if (TypeName.ROW.equals(type.getTypeName())) { return verifyRow(value, fieldName); } else if (TypeName.LOGICAL_TYPE.equals(type.getTypeName())) { return verifyLogicalType(value, type.getLogicalType(), fieldName); } else { return verifyPrimitiveType(value, type.getTypeName(), fieldName); } } private static Object verifyLogicalType(Object value, LogicalType logicalType, String fieldName) { // TODO: this isn't guaranteed to clone the object. return logicalType.toInputType(logicalType.toBaseType(value)); } private static List<Object> verifyArray( Object value, FieldType collectionElementType, String fieldName) { boolean collectionElementTypeNullable = collectionElementType.getNullable(); if (!(value instanceof List)) { throw new IllegalArgumentException( String.format( "For field name %s and array type expected List class. Instead " + "class type was %s.", fieldName, value.getClass())); } List<Object> valueList = (List<Object>) value; List<Object> verifiedList = Lists.newArrayListWithCapacity(valueList.size()); for (Object listValue : valueList) { if (listValue == null) { if (!collectionElementTypeNullable) { throw new IllegalArgumentException( String.format( "%s is not nullable in Array field %s", collectionElementType, fieldName)); } verifiedList.add(null); } else { verifiedList.add(verifyFieldValue(listValue, collectionElementType, fieldName)); } } return verifiedList; } private static Iterable<Object> verifyIterable( Object value, FieldType collectionElementType, String fieldName) { boolean collectionElementTypeNullable = collectionElementType.getNullable(); if (!(value instanceof Iterable)) { throw new IllegalArgumentException( String.format( "For field name %s and iterable type expected class extending Iterable. Instead " + "class type was %s.", fieldName, value.getClass())); } Iterable<Object> valueList = (Iterable<Object>) value; for (Object listValue : valueList) { if (listValue == null) { if (!collectionElementTypeNullable) { throw new IllegalArgumentException( String.format( "%s is not nullable in Array field %s", collectionElementType, fieldName)); } } else { verifyFieldValue(listValue, collectionElementType, fieldName); } } return valueList; } private static Map<Object, Object> verifyMap( Object value, FieldType keyType, FieldType valueType, String fieldName) { boolean valueTypeNullable = valueType.getNullable(); if (!(value instanceof Map)) { throw new IllegalArgumentException( String.format( "For field name %s and map type expected Map class. Instead " + "class type was %s.", fieldName, value.getClass())); } Map<Object, Object> valueMap = (Map<Object, Object>) value; Map<Object, Object> verifiedMap = Maps.newHashMapWithExpectedSize(valueMap.size()); for (Entry<Object, Object> kv : valueMap.entrySet()) { if (kv.getValue() == null) { if (!valueTypeNullable) { throw new IllegalArgumentException( String.format("%s is not nullable in Map field %s", valueType, fieldName)); } verifiedMap.put(verifyFieldValue(kv.getKey(), keyType, fieldName), null); } else { verifiedMap.put( verifyFieldValue(kv.getKey(), keyType, fieldName), verifyFieldValue(kv.getValue(), valueType, fieldName)); } } return verifiedMap; } private static Row verifyRow(Object value, String fieldName) { if (!(value instanceof Row)) { throw new IllegalArgumentException( String.format( "For field name %s expected Row type. " + "Instead class type was %s.", fieldName, value.getClass())); } // No need to recursively validate the nested Row, since there's no way to build the // Row object without it validating. return (Row) value; } private static Object verifyPrimitiveType(Object value, TypeName type, String fieldName) { if (type.isDateType()) { return verifyDateTime(value, fieldName); } else { switch (type) { case BYTE: if (value instanceof Byte) { return value; } break; case BYTES: if (value instanceof ByteBuffer) { return ((ByteBuffer) value).array(); } else if (value instanceof byte[]) { return (byte[]) value; } break; case INT16: if (value instanceof Short) { return value; } break; case INT32: if (value instanceof Integer) { return value; } break; case INT64: if (value instanceof Long) { return value; } break; case DECIMAL: if (value instanceof BigDecimal) { return value; } break; case FLOAT: if (value instanceof Float) { return value; } break; case DOUBLE: if (value instanceof Double) { return value; } break; case STRING: if (value instanceof String) { return value; } break; case BOOLEAN: if (value instanceof Boolean) { return value; } break; default: // Shouldn't actually get here, but we need this case to satisfy linters. throw new IllegalArgumentException( String.format("Not a primitive type for field name %s: %s", fieldName, type)); } throw new IllegalArgumentException( String.format( "For field name %s and type %s found incorrect class type %s", fieldName, type, value.getClass())); } } private static Instant verifyDateTime(Object value, String fieldName) { // We support the following classes for datetimes. if (value instanceof AbstractInstant) { return ((AbstractInstant) value).toInstant(); } else { throw new IllegalArgumentException( String.format( "For field name %s and DATETIME type got unexpected class %s ", fieldName, value.getClass())); } } }
2,616
https://github.com/qaximalee/blaze-persistence/blob/master/integration/entity-view-spring/src/main/java/com/blazebit/persistence/integration/view/spring/impl/EntityViewConfigurationProducer.java
Github Open Source
Open Source
Apache-2.0, LicenseRef-scancode-unknown-license-reference
2,019
blaze-persistence
qaximalee
Java
Code
152
371
/* * Copyright 2014 - 2019 Blazebit. * * 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.blazebit.persistence.integration.view.spring.impl; import com.blazebit.persistence.view.EntityViews; import com.blazebit.persistence.view.spi.EntityViewConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Set; /** * @author Moritz Becker * @since 1.2.0 */ @Configuration public class EntityViewConfigurationProducer { private final EntityViewConfiguration configuration = EntityViews.createDefaultConfiguration(); public EntityViewConfigurationProducer(Set<Class<?>> entityViewClasses) { for (Class<?> entityViewClass : entityViewClasses) { configuration.addEntityView(entityViewClass); } } @Bean public EntityViewConfiguration getEntityViewConfiguration() { return configuration; } }
17,651
https://github.com/fossabot/PermissionManager/blob/master/app/src/main/java/permission/auron/com/samplepermissionhelper/ActivityMultiplePermission.java
Github Open Source
Open Source
MIT
2,019
PermissionManager
fossabot
Java
Code
288
1,285
package permission.auron.com.samplepermissionhelper; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.provider.MediaStore; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.Toolbar; import com.google.android.material.floatingactionbutton.FloatingActionButton; import permission.auron.com.permissionhelper.ActivityManagePermission; import permission.auron.com.permissionhelper.PermissionResult; import permission.auron.com.permissionhelper.utils.PermissionUtils; import permission.auron.com.samplemarshmallowpermissionhelper.R; import permission.auron.com.samplepermissionhelper.checkPermission.ActivityCheckPermission; public class ActivityMultiplePermission extends ActivityManagePermission { private static final int REQUEST_IMAGE_CAPTURE = 1; private ImageView imageView; private FloatingActionButton floatingActionButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.image); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle(R.string.app_name); getSupportActionBar().setSubtitle(R.string.askMultiPermission); floatingActionButton = findViewById(R.id.fab); floatingActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sampleAskMultiplePermission(); } }); } private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); imageView.setImageBitmap(imageBitmap); } } private void sampleAskMultiplePermission() { String[] permissionAsk = {PermissionUtils.Manifest_CAMERA, PermissionUtils.Manifest_WRITE_EXTERNAL_STORAGE}; askCompactPermissions(permissionAsk, new PermissionResult() { @Override public void permissionGranted() { //permission granted //replace with your action dispatchTakePictureIntent(); } @Override public void permissionDenied() { //permission denied //replace with your action } @Override public void permissionForeverDenied() { showDialog(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.ask_single_activity: this.finish(); return true; case R.id.ask_multi_activity: this.finish(); return true; case R.id.ask_single_fragment: startActivity(new Intent(ActivityMultiplePermission.this, ActivityContainer.class)); return true; // case R.id.ask_annotation : // startActivity(new Intent(ActivityMultiplePermission.this, ActivityAnnotation.class)); work in progress ;-) // return true; case R.id.check_permission: startActivity(new Intent(ActivityMultiplePermission.this, ActivityCheckPermission.class)); return true; default: return super.onOptionsItemSelected(item); } } private void showDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(ActivityMultiplePermission.this, R.style.AppCompatAlertDialogStyle); builder.setTitle(R.string.attention); builder.setMessage(R.string.messageperm); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { openSettingsApp(ActivityMultiplePermission.this); } }); builder.setNegativeButton("Cancel", null); builder.show(); } }
13,560
https://github.com/SciFiFarms/Technocore-Farmbot-Web-App/blob/master/frontend/plants/grid/grid_input.tsx
Github Open Source
Open Source
MIT
null
Technocore-Farmbot-Web-App
SciFiFarms
TypeScript
Code
237
917
import React from "react"; import { PlantGridKey, GridInputProps, InputCellProps, PlantGridLabelData, } from "./interfaces"; import { Col, Row } from "../../ui"; import { t } from "../../i18next_wrapper"; import { UseCurrentLocation } from "../../tools/tool_slot_edit_components"; export const LABELS = ( itemType: "points" | "plants", ): Record<PlantGridKey, PlantGridLabelData> => ({ startX: { label: t("Starting X"), regular_icon: "fa-arrow-right", swapped_icon: "fa-arrow-down", }, startY: { label: t("starting Y"), regular_icon: "fa-arrow-down", swapped_icon: "fa-arrow-right", }, spacingH: { label: t("Spacing (MM)"), regular_icon: "fa-arrows-h", swapped_icon: "fa-arrows-v", }, spacingV: { label: t("Spacing (MM)"), regular_icon: "fa-arrows-v", swapped_icon: "fa-arrows-h", }, numPlantsH: { label: itemType == "points" ? t("# of points") : t("# of plants"), regular_icon: "fa-arrows-h", swapped_icon: "fa-arrows-v", }, numPlantsV: { label: itemType == "points" ? t("# of points") : t("# of plants"), regular_icon: "fa-arrows-v", swapped_icon: "fa-arrows-h", }, }); export function InputCell(props: InputCellProps) { const { gridKey, onChange, grid, xy_swap, preview } = props; const { label, regular_icon, swapped_icon } = LABELS(props.itemType)[gridKey]; return <Col xs={5}> <label> <i className={`fa ${xy_swap ? swapped_icon : regular_icon}`} /> {t(label)} </label> <input name={gridKey} value={grid[gridKey]} onBlur={preview} onChange={e => { const number = parseInt(e.currentTarget.value, 10); !isNaN(number) && onChange(gridKey, number); }} /> </Col>; } const pairs: [PlantGridKey, PlantGridKey][] = [ ["startX", "startY"], ["numPlantsH", "numPlantsV"], ["spacingH", "spacingV"], ]; export function GridInput(props: GridInputProps) { return <div className="grid-input"> {pairs.map(([left, right]) => <Row key={left + right}> <InputCell itemType={props.itemType} xy_swap={props.xy_swap} gridKey={left} onChange={props.onChange} preview={props.preview} grid={props.grid} /> <InputCell itemType={props.itemType} xy_swap={props.xy_swap} gridKey={right} onChange={props.onChange} preview={props.preview} grid={props.grid} /> {left == "startX" && <UseCurrentLocation botPosition={props.botPosition} onChange={props.onUseCurrentPosition} />} </Row>)} </div>; }
26,491
https://github.com/laanito/tuqan/blob/master/Image/docs/examples/axis_direction.php
Github Open Source
Open Source
MIT
null
tuqan
laanito
PHP
Code
124
435
<?php /** * Usage example for Image_Graph. * * Main purpose: * Axis direction * * Other: * None specific * * $Id: axis_direction.php,v 1.1 2006-08-31 08:36:07 jmartinez Exp $ * * @package Image_Graph * @author Jesper Veggerby <pear.nosey@veggerby.dk> */ require_once 'Image/Graph.php'; // create the graph $Graph =& Image_Graph::factory('graph', array(600, 300)); // add a TrueType font $Font =& $Graph->addNew('font', 'Verdana'); // set the font size to 11 pixels $Font->setSize(10); $Graph->setFont($Font); // setup the plotarea, legend and their layout $Graph->add( Image_Graph::vertical( Image_Graph::factory('title', array('Changing Axis Direction', 12)), Image_Graph::horizontal( $Plotarea1 = Image_Graph::factory('plotarea'), $Plotarea2 = Image_Graph::factory('plotarea'), 50 ), 5 ) ); $Dataset =& Image_Graph::factory('random', array(10, 2, 15, true)); $Plot1 =& $Plotarea1->addNew('line', array(&$Dataset)); $Plot1->setLineColor('red'); $Plot2 =& $Plotarea2->addNew('line', array(&$Dataset)); $Plot2->setLineColor('red'); $AxisY =& $Plotarea2->getAxis('y'); $AxisY->setInverted(true); // output the Graph $Graph->done(); ?>
18,345
https://github.com/line/rules_apple_line/blob/master/.gitignore
Github Open Source
Open Source
Apache-2.0, LicenseRef-scancode-unknown-license-reference
2,022
rules_apple_line
line
Ignore List
Code
3
16
.DS_Store *.swp /bazel-*
44,154
https://github.com/xaman/Filmgoer/blob/master/app/src/main/java/com/martinchamarro/filmgoer/presentation/movies/MoviesRankingsScreenService.kt
Github Open Source
Open Source
Apache-2.0
null
Filmgoer
xaman
Kotlin
Code
160
626
package com.martinchamarro.filmgoer.presentation.movies import android.content.Context import android.content.Intent import android.util.Log import android.view.View import android.widget.ImageView import com.martinchamarro.filmgoer.R import com.martinchamarro.filmgoer.presentation.model.ServiceState.* import io.mattcarroll.hover.Content import io.mattcarroll.hover.HoverMenu import io.mattcarroll.hover.HoverView import io.mattcarroll.hover.window.HoverMenuService import java.util.* class MoviesRankingsScreenService : HoverMenuService() { companion object { var state = NOT_INITIALIZED const val TAG = "MoviesRankingsService" fun startIfNeeded(context: Context) { if (state == NOT_INITIALIZED) { state = RUNNING context.startService(Intent(context, MoviesRankingsScreenService::class.java)) } } } override fun onHoverMenuLaunched(intent: Intent, hoverView: HoverView) { hoverView.setMenu(createHoverMenu()) hoverView.collapse() Log.d(TAG, "Launched!") } override fun onHoverMenuExitingByUserRequest() { super.onHoverMenuExitingByUserRequest() state = KILLED Log.d(TAG, "Exited!") } private fun createHoverMenu(): HoverMenu = SingleSectionHoverMenu(applicationContext) private class SingleSectionHoverMenu(private val context: Context) : HoverMenu() { private val section = Section(SectionId("1"), createTabView(), createScreen()) private fun createTabView(): View { val imageView = ImageView(context) imageView.setImageResource(R.drawable.tab_background) imageView.scaleType = ImageView.ScaleType.CENTER_INSIDE return imageView } private fun createScreen(): Content = MoviesRankingsScreen(context, "Screen 1") override fun getId(): String = "singlesectionmenu" override fun getSectionCount() = 1 override fun getSection(index: Int) = section override fun getSection(sectionId: SectionId) = section override fun getSections(): List<Section> = Collections.singletonList(section) } }
20,265
https://github.com/devwithpug/TIME-TO-TRAVEL/blob/master/TimeToTravel/src/term/project/repository/Repository.java
Github Open Source
Open Source
MIT
null
TIME-TO-TRAVEL
devwithpug
Java
Code
36
119
package term.project.repository; import java.sql.SQLException; import java.util.List; public interface Repository<T, K>{ // CREATE T create(T entity) throws SQLException; // READ T getOneById(K id) throws SQLException; List<T> getAll() throws SQLException; // DELETE void delete(K id) throws SQLException; }
39,901
https://github.com/aj-michael/Digital-Systems/blob/master/Lab4-Part2-RAMwithHyperTerminalDisplay/RAMAddressUpdate.v
Github Open Source
Open Source
MIT
2,015
Digital-Systems
aj-michael
Verilog
Code
63
146
`timescale 1ns / 1ps ////////////////////////////////////////////////////////////////////////////////// // Company: Rose-Hulman Institute of Technology // Engineer: Adam Michael // Date: 10/15/2015 // Summary: Updates the address into the RAM ////////////////////////////////////////////////////////////////////////////////// module RAMAddressUpdate(Clock, NextAddress, Reset, RAMaddress); input Clock, NextAddress, Reset; output reg [5:0] RAMaddress; always @ (posedge Clock or posedge Reset) if (Reset == 1) RAMaddress <= 0; else if (NextAddress) RAMaddress <= RAMaddress + 1; endmodule
2,665
https://github.com/Neos21/json-db-manager/blob/master/server/src/constants.ts
Github Open Source
Open Source
MIT
null
json-db-manager
Neos21
TypeScript
Code
100
423
import path from 'path'; import dotenv from 'dotenv'; dotenv.config(); // エントリポイントよりも先に読み込まれるようなので `.env` を使用する箇所で都度呼ぶことにする /** * 環境変数を取得する * * @param variableName 環境変数名 * @returns 環境変数の値 * @throws 環境変数の値がない場合はエラーとする */ function getEnvironmentVariable(variableName) { const environmentVariable = process.env[variableName]; if(environmentVariable == null || String(environmentVariable).trim() === '') throw new Error(`Environment Variable [${variableName}] Does Not Exist`); return environmentVariable; } /** * 定数 */ const constants = { /** ログインユーザ名 */ userName: getEnvironmentVariable('USERNAME'), /** ログインパスワード */ password: getEnvironmentVariable('PASSWORD'), /** DB ディレクトリのパス */ dbDirectoryPath: (() => { // プロジェクトルートからの相対パスとして環境変数の値を利用する // スラッシュ `/` 始まりの値を渡せば手前の `__dirname`・`../../` は無視されフルパスとして解決される const environmentVariable = getEnvironmentVariable('DB_DIRECTORY_PATH'); return path.resolve(__dirname, '../../', environmentVariable); })() }; export default constants;
8,605
https://github.com/communityus-llc/bepu-physics-for-unity-ecs/blob/master/Assets/BEPUphysics/Constraints/Collision/ContactPenetrationConstraint.cs
Github Open Source
Open Source
MIT
2,021
bepu-physics-for-unity-ecs
communityus-llc
C#
Code
1,311
3,477
using BEPUphysics.Entities; using BEPUphysics.CollisionTests; using BEPUphysics.Settings; using BEPUutilities; using System; using BEPUutilities.DataStructures; namespace BEPUphysics.Constraints.Collision { /// <summary> /// Computes the forces necessary to keep two entities from going through each other at a contact point. /// </summary> public class ContactPenetrationConstraint : SolverUpdateable { internal Contact contact; ///<summary> /// Gets the contact associated with this penetration constraint. ///</summary> public Contact Contact { get { return contact; } } internal float accumulatedImpulse; //float linearBX, linearBY, linearBZ; internal float angularAX, angularAY, angularAZ; internal float angularBX, angularBY, angularBZ; private float softness; private float bias; private float linearAX, linearAY, linearAZ; private Entity entityA, entityB; private bool entityADynamic, entityBDynamic; //Inverse effective mass matrix internal float velocityToImpulse; private ContactManifoldConstraint contactManifoldConstraint; internal Vector3 ra, rb; ///<summary> /// Constructs a new penetration constraint. ///</summary> public ContactPenetrationConstraint() { isActive = false; } ///<summary> /// Configures the penetration constraint. ///</summary> ///<param name="contactManifoldConstraint">Owning manifold constraint.</param> ///<param name="contact">Contact associated with the penetration constraint.</param> public void Setup(ContactManifoldConstraint contactManifoldConstraint, Contact contact) { this.contactManifoldConstraint = contactManifoldConstraint; this.contact = contact; isActive = true; entityA = contactManifoldConstraint.EntityA; entityB = contactManifoldConstraint.EntityB; } ///<summary> /// Cleans up the constraint. ///</summary> public void CleanUp() { accumulatedImpulse = 0; contactManifoldConstraint = null; contact = null; entityA = null; entityB = null; isActive = false; } /// <summary> /// Gets the total normal impulse applied by this penetration constraint to maintain the separation of the involved entities. /// </summary> public float NormalImpulse { get { return accumulatedImpulse; } } ///<summary> /// Gets the relative velocity between the associated entities at the contact point along the contact normal. ///</summary> public float RelativeVelocity { get { float lambda = 0; if (entityA != null) { lambda = entityA.linearVelocity.X * linearAX + entityA.linearVelocity.Y * linearAY + entityA.linearVelocity.Z * linearAZ + entityA.angularVelocity.X * angularAX + entityA.angularVelocity.Y * angularAY + entityA.angularVelocity.Z * angularAZ; } if (entityB != null) { lambda += -entityB.linearVelocity.X * linearAX - entityB.linearVelocity.Y * linearAY - entityB.linearVelocity.Z * linearAZ + entityB.angularVelocity.X * angularBX + entityB.angularVelocity.Y * angularBY + entityB.angularVelocity.Z * angularBZ; } return lambda; } } ///<summary> /// Performs the frame's configuration step. ///</summary> ///<param name="dt">Timestep duration.</param> public override void Update(float dt) { entityADynamic = entityA != null && entityA.isDynamic; entityBDynamic = entityB != null && entityB.isDynamic; //Set up the jacobians. linearAX = -contact.Normal.X; linearAY = -contact.Normal.Y; linearAZ = -contact.Normal.Z; //linearBX = -linearAX; //linearBY = -linearAY; //linearBZ = -linearAZ; //angular A = Ra x N if (entityA != null) { Vector3.Subtract(ref contact.Position, ref entityA.position, out ra); angularAX = (ra.Y * linearAZ) - (ra.Z * linearAY); angularAY = (ra.Z * linearAX) - (ra.X * linearAZ); angularAZ = (ra.X * linearAY) - (ra.Y * linearAX); } //Angular B = N x Rb if (entityB != null) { Vector3.Subtract(ref contact.Position, ref entityB.position, out rb); angularBX = (linearAY * rb.Z) - (linearAZ * rb.Y); angularBY = (linearAZ * rb.X) - (linearAX * rb.Z); angularBZ = (linearAX * rb.Y) - (linearAY * rb.X); } //Compute inverse effective mass matrix float entryA, entryB; //these are the transformed coordinates float tX, tY, tZ; if (entityADynamic) { tX = angularAX * entityA.inertiaTensorInverse.M11 + angularAY * entityA.inertiaTensorInverse.M21 + angularAZ * entityA.inertiaTensorInverse.M31; tY = angularAX * entityA.inertiaTensorInverse.M12 + angularAY * entityA.inertiaTensorInverse.M22 + angularAZ * entityA.inertiaTensorInverse.M32; tZ = angularAX * entityA.inertiaTensorInverse.M13 + angularAY * entityA.inertiaTensorInverse.M23 + angularAZ * entityA.inertiaTensorInverse.M33; entryA = tX * angularAX + tY * angularAY + tZ * angularAZ + entityA.inverseMass; } else entryA = 0; if (entityBDynamic) { tX = angularBX * entityB.inertiaTensorInverse.M11 + angularBY * entityB.inertiaTensorInverse.M21 + angularBZ * entityB.inertiaTensorInverse.M31; tY = angularBX * entityB.inertiaTensorInverse.M12 + angularBY * entityB.inertiaTensorInverse.M22 + angularBZ * entityB.inertiaTensorInverse.M32; tZ = angularBX * entityB.inertiaTensorInverse.M13 + angularBY * entityB.inertiaTensorInverse.M23 + angularBZ * entityB.inertiaTensorInverse.M33; entryB = tX * angularBX + tY * angularBY + tZ * angularBZ + entityB.inverseMass; } else entryB = 0; //If we used a single fixed softness value, then heavier objects will tend to 'squish' more than light objects. //In the extreme case, very heavy objects could simply fall through the ground by force of gravity. //To see why this is the case, consider that a given dt, softness, and bias factor correspond to an equivalent spring's damping and stiffness coefficients. //Imagine trying to hang objects of different masses on the fixed-strength spring: obviously, heavier ones will pull it further down. //To counteract this, scale the softness value based on the effective mass felt by the constraint. //Larger effective masses should correspond to smaller softnesses so that the spring has the same positional behavior. //Fortunately, we're already computing the necessary values: the raw, unsoftened effective mass inverse shall be used to compute the softness. float effectiveMassInverse = entryA + entryB; float updateRate = 1 / dt; softness = CollisionResponseSettings.Softness * effectiveMassInverse * updateRate; velocityToImpulse = -1 / (softness + effectiveMassInverse); //Bounciness and bias (penetration correction) if (contact.PenetrationDepth >= 0) { bias = MathHelper.Min( MathHelper.Max(0, contact.PenetrationDepth - CollisionDetectionSettings.AllowedPenetration) * CollisionResponseSettings.PenetrationRecoveryStiffness * updateRate, CollisionResponseSettings.MaximumPenetrationRecoverySpeed); if (contactManifoldConstraint.materialInteraction.Bounciness > 0) { //Target a velocity which includes a portion of the incident velocity. float bounceVelocity = -RelativeVelocity; if (bounceVelocity > 0) { var lowThreshold = CollisionResponseSettings.BouncinessVelocityThreshold * 0.3f; var velocityFraction = MathHelper.Clamp((bounceVelocity - lowThreshold) / (CollisionResponseSettings.BouncinessVelocityThreshold - lowThreshold + Toolbox.Epsilon), 0, 1); var bouncinessVelocity = velocityFraction * bounceVelocity * contactManifoldConstraint.materialInteraction.Bounciness; bias = MathHelper.Max(bouncinessVelocity, bias); } } } else { //The contact is actually separated right now. Allow the solver to target a position that is just barely in collision. //If the solver finds that an accumulated negative impulse is required to hit this target, then no work will be done. bias = contact.PenetrationDepth * updateRate; //This implementation is going to ignore bounciness for now. //Since it's not being used for CCD, these negative-depth contacts //only really occur in situations where no bounce should occur. //if (contactManifoldConstraint.materialInteraction.Bounciness > 0) //{ // //Target a velocity which includes a portion of the incident velocity. // //The contact isn't colliding currently, but go ahead and target the post-bounce velocity. // //The bias is added to the bounce velocity to simulate the object continuing to the surface and then bouncing off. // float relativeVelocity = -RelativeVelocity; // if (relativeVelocity > CollisionResponseSettings.BouncinessVelocityThreshold) // bias = relativeVelocity * contactManifoldConstraint.materialInteraction.Bounciness + bias; //} } } /// <summary> /// Performs any pre-solve iteration work that needs exclusive /// access to the members of the solver updateable. /// Usually, this is used for applying warmstarting impulses. /// </summary> public override void ExclusiveUpdate() { //Warm starting #if !WINDOWS Vector3 linear = new Vector3(); Vector3 angular = new Vector3(); #else Vector3 linear, angular; #endif linear.X = accumulatedImpulse * linearAX; linear.Y = accumulatedImpulse * linearAY; linear.Z = accumulatedImpulse * linearAZ; if (entityADynamic) { angular.X = accumulatedImpulse * angularAX; angular.Y = accumulatedImpulse * angularAY; angular.Z = accumulatedImpulse * angularAZ; entityA.ApplyLinearImpulse(ref linear); entityA.ApplyAngularImpulse(ref angular); } if (entityBDynamic) { linear.X = -linear.X; linear.Y = -linear.Y; linear.Z = -linear.Z; angular.X = accumulatedImpulse * angularBX; angular.Y = accumulatedImpulse * angularBY; angular.Z = accumulatedImpulse * angularBZ; entityB.ApplyLinearImpulse(ref linear); entityB.ApplyAngularImpulse(ref angular); } } /// <summary> /// Computes and applies an impulse to keep the colliders from penetrating. /// </summary> /// <returns>Impulse applied.</returns> public override float SolveIteration() { //Compute relative velocity float lambda = (RelativeVelocity - bias + softness * accumulatedImpulse) * velocityToImpulse; //Clamp accumulated impulse float previousAccumulatedImpulse = accumulatedImpulse; accumulatedImpulse = MathHelper.Max(0, accumulatedImpulse + lambda); lambda = accumulatedImpulse - previousAccumulatedImpulse; //Apply the impulse #if !WINDOWS Vector3 linear = new Vector3(); Vector3 angular = new Vector3(); #else Vector3 linear, angular; #endif linear.X = lambda * linearAX; linear.Y = lambda * linearAY; linear.Z = lambda * linearAZ; if (entityADynamic) { angular.X = lambda * angularAX; angular.Y = lambda * angularAY; angular.Z = lambda * angularAZ; entityA.ApplyLinearImpulse(ref linear); entityA.ApplyAngularImpulse(ref angular); } if (entityBDynamic) { linear.X = -linear.X; linear.Y = -linear.Y; linear.Z = -linear.Z; angular.X = lambda * angularBX; angular.Y = lambda * angularBY; angular.Z = lambda * angularBZ; entityB.ApplyLinearImpulse(ref linear); entityB.ApplyAngularImpulse(ref angular); } return Math.Abs(lambda); } protected internal override void CollectInvolvedEntities(RawList<Entity> outputInvolvedEntities) { //This should never really have to be called. if (entityA != null) outputInvolvedEntities.Add(entityA); if (entityB != null) outputInvolvedEntities.Add(entityB); } } }
14,104
https://github.com/darinfranklin/RegexForAccordance/blob/master/RegexForAccordance/BXSearchFieldFormatter.h
Github Open Source
Open Source
MIT
2,022
RegexForAccordance
darinfranklin
Objective-C
Code
39
120
// // BXSearchFieldFormatter.h // RegexForAccordance // // Created by Darin Franklin on 9/1/14. // Copyright (c) 2014 Darin Franklin. All rights reserved. // #import <Foundation/Foundation.h> #import "BXTextLanguage.h" @interface BXSearchFieldFormatter : NSFormatter @property BOOL leftToRightOverride; - (NSString *)stripLRO:(NSString *)string; @end
33,343
https://github.com/phstudy/zetasketch/blob/master/java/com/google/zetasketch/ValueType.java
Github Open Source
Open Source
Apache-2.0
2,022
zetasketch
phstudy
Java
Code
306
848
/* * Copyright 2018 Google LLC * * 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 com.google.zetasketch; import com.google.auto.value.AutoValue; import com.google.errorprone.annotations.Immutable; import com.google.protos.zetasketch.Aggregator.AggregatorStateProto; import com.google.protos.zetasketch.Aggregator.AggregatorStateProtoOrBuilder; import com.google.protos.zetasketch.Aggregator.DefaultOpsType; import com.google.protos.zetasketch.CustomValueType; import java.util.Optional; /** Represents the value type and associated operations that were used to create an aggregator. */ @AutoValue @Immutable public abstract class ValueType { public static final ValueType UNKNOWN = forNumber(0); /** Returns the number associated with this type. */ public abstract int getNumber(); /** * Returns the {@link DefaultOpsType.Id} for this type, if it represents one of those values. * Otherwise, returns {@link DefaultOpsType.Id#UNKNOWN}. */ public final DefaultOpsType.Id asDefaultOpsType() { return Optional.ofNullable(DefaultOpsType.Id.forNumber(getNumber())) .orElse(DefaultOpsType.Id.UNKNOWN); } public final AggregatorStateProto.Builder copyToBuilder( AggregatorStateProto.Builder stateBuilder) { if (getNumber() == 0) { return stateBuilder.clearValueType(); } return stateBuilder.setValueType(getNumber()); } public static ValueType forStandardType(DefaultOpsType.Id opsType) { return new AutoValue_ValueType(opsType.getNumber()); } public static ValueType forCustomType(CustomValueType.Id customType) { return new AutoValue_ValueType(customType.getNumber()); } public static ValueType forNumber(int number) { return new AutoValue_ValueType(number); } public static ValueType forStateProto(AggregatorStateProtoOrBuilder proto) { return forNumber(proto.getValueType()); } @Override public final String toString() { int number = getNumber(); if (number == 0) { return "UNKNOWN"; } final DefaultOpsType.Id defaultId = DefaultOpsType.Id.forNumber(number); if (defaultId != null) { return "DefaultOpsType.Id." + defaultId.name(); } final CustomValueType.Id customId = CustomValueType.Id.forNumber(number); if (customId != null) { return "CustomValueType.Id." + customId.name(); } return "<unnamed custom value type " + number + ">"; } ValueType() {} }
46,924
https://github.com/SJTU-IPADS/fgnn-artifacts/blob/master/samgraph/common/cuda/pre_sampler.cc
Github Open Source
Open Source
Apache-2.0
2,022
fgnn-artifacts
SJTU-IPADS
C++
Code
464
1,806
/* * Copyright 2022 Institute of Parallel and Distributed Systems, Shanghai Jiao Tong University * * 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. * */ #include "pre_sampler.h" #include "../profiler.h" #include "../common.h" #include "../constant.h" #include "../logging.h" #include "cuda_loops.h" #include "cuda_engine.h" #include "cuda_device.h" #include <cstring> #ifdef __linux__ #include <parallel/algorithm> #else #include <algorithm> #endif #include "../timer.h" namespace samgraph { namespace common { namespace cuda { PreSampler* PreSampler::singleton = nullptr; PreSampler::PreSampler(size_t num_nodes, size_t num_step) : _num_nodes(num_nodes), _num_step(num_step) { Timer t_init; freq_table = static_cast<Id64Type*>(Device::Get(CPU())->AllocDataSpace(CPU(), sizeof(Id64Type)*num_nodes)); #pragma omp parallel for num_threads(RunConfig::omp_thread_num) for (size_t i = 0; i < _num_nodes; i++) { auto nid_ptr = reinterpret_cast<IdType*>(&freq_table[i]); *nid_ptr = i; *(nid_ptr + 1) = 0; } Profiler::Get().LogInit(kLogInitL3PresampleInit, t_init.Passed()); } PreSampler::~PreSampler() { Device::Get(CPU())->FreeDataSpace(CPU(), freq_table); } void PreSampler::DoPreSample(){ auto sampler_ctx = GPUEngine::Get()->GetSamplerCtx(); auto sampler_device = Device::Get(sampler_ctx); auto cpu_device = Device::Get(CPU()); for (int e = 0; e < RunConfig::presample_epoch; e++) { for (size_t i = 0; i < _num_step; i++) { Timer t0; auto task = DoShuffle(); switch (RunConfig::cache_policy) { case kCacheByPreSample: DoGPUSample(task); break; case kCacheByPreSampleStatic: DoGPUSampleAllNeighbour(task); break; default: CHECK(0); } double sample_time = t0.Passed(); size_t num_inputs = task->input_nodes->Shape()[0]; Timer t1; IdType* input_nodes = static_cast<IdType*>(cpu_device->AllocWorkspace(CPU(), sizeof(IdType)*num_inputs)); sampler_device->CopyDataFromTo( task->input_nodes->Data(), 0, input_nodes, 0, num_inputs * sizeof(IdType), task->input_nodes->Ctx(), CPU()); double copy_time = t1.Passed(); Timer t2; #pragma omp parallel for num_threads(RunConfig::omp_thread_num) for (size_t i = 0; i < num_inputs; i++) { auto freq_ptr = reinterpret_cast<IdType*>(&freq_table[input_nodes[i]]); *(freq_ptr+1) += 1; } cpu_device->FreeWorkspace(CPU(), input_nodes); double count_time = t2.Passed(); Profiler::Get().LogInitAdd(kLogInitL3PresampleSample, sample_time); Profiler::Get().LogInitAdd(kLogInitL3PresampleCopy, copy_time); Profiler::Get().LogInitAdd(kLogInitL3PresampleCount, count_time); } } Timer ts; #ifdef __linux__ __gnu_parallel::sort(freq_table, &freq_table[_num_nodes], std::greater<Id64Type>()); #else std::sort(freq_table, &freq_table[_num_nodes], std::greater<Id64Type>()); #endif double sort_time = ts.Passed(); Profiler::Get().LogInit(kLogInitL3PresampleSort, sort_time); Timer t_reset; GPUEngine::Get()->GetShuffler()->Reset(); Profiler::Get().ResetStepEpoch(); Profiler::Get().LogInit(kLogInitL3PresampleReset, t_reset.Passed()); } TensorPtr PreSampler::GetFreq() { auto ranking_freq = Tensor::Empty(DataType::kI32, {_num_nodes}, CPU(), ""); auto ranking_freq_ptr = static_cast<IdType*>(ranking_freq->MutableData()); for (size_t i = 0; i < _num_nodes; i++) { auto nid_ptr = reinterpret_cast<IdType*>(&freq_table[i]); ranking_freq_ptr[i] = *(nid_ptr + 1); } return ranking_freq; } TensorPtr PreSampler::GetRankNode() { auto ranking_nodes = Tensor::Empty(DataType::kI32, {_num_nodes}, CPU(), ""); auto ranking_nodes_ptr = static_cast<IdType*>(ranking_nodes->MutableData()); Timer t_prepare_rank; #pragma omp parallel for num_threads(RunConfig::omp_thread_num) for (size_t i = 0; i < _num_nodes; i++) { auto nid_ptr = reinterpret_cast<IdType*>(&freq_table[i]); ranking_nodes_ptr[i] = *(nid_ptr); } Profiler::Get().LogInit(kLogInitL3PresampleGetRank, t_prepare_rank.Passed()); return ranking_nodes; } void PreSampler::GetRankNode(TensorPtr& ranking_nodes) { auto ranking_nodes_ptr = static_cast<IdType*>(ranking_nodes->MutableData()); Timer t_prepare_rank; #pragma omp parallel for num_threads(RunConfig::omp_thread_num) for (size_t i = 0; i < _num_nodes; i++) { auto nid_ptr = reinterpret_cast<IdType*>(&freq_table[i]); ranking_nodes_ptr[i] = *(nid_ptr); } Profiler::Get().LogInit(kLogInitL3PresampleGetRank, t_prepare_rank.Passed()); } } } }
16,168
https://github.com/noelevans/sandpit/blob/master/bayesian_methods_for_hackers/price_is_right_ch05.py
Github Open Source
Open Source
MIT
2,023
sandpit
noelevans
Python
Code
408
1,580
import matplotlib.pyplot as plt import numpy as np import pymc as pm import scipy.stats as stats import scipy.optimize as sop def main(): plt.subplot(311) x = np.linspace(0, 60000, 200) sp1 = plt.fill_between(x, 0, stats.norm.pdf(x, 35000, 7500), color="#348ABD", lw=3, alpha=0.6, label="historical total prices") p1 = plt.Rectangle((0, 0), 1, 1, fc=sp1.get_facecolor()[0]) plt.legend([p1], [sp1.get_label()]) plt.subplot(312) x = np.linspace(0, 10000, 200) sp2 = plt.fill_between(x, 0, stats.norm.pdf(x, 3000, 500), color="#A60628", lw=3, alpha=0.6, label="snowblower price guess") p2 = plt.Rectangle((0, 0), 1, 1, fc=sp2.get_facecolor()[0]) plt.legend([p2], [sp2.get_label()]) plt.subplot(313) x = np.linspace(0, 25000, 200) sp3 = plt.fill_between(x, 0, stats.norm.pdf(x, 12000, 3000), color="#7A68A6", lw=3, alpha=0.6, label="Trip price guess") plt.autoscale(tight=True) p3 = plt.Rectangle((0, 0), 1, 1, fc=sp3.get_facecolor()[0]) plt.legend([p3], [sp3.get_label()]) plt.show() data_mu = [3e3, 12e3] data_std = [5e2, 3e3] mu_prior = 35e3 std_prior = 75e2 true_price = pm.Normal("true_price", mu_prior, 1.0 / std_prior ** 2) prize_1 = pm.Normal("first_prize", data_mu[0], 1.0 / data_std[0] ** 2) prize_2 = pm.Normal("second_prize", data_mu[1], 1.0 / data_std[1] ** 2) price_estimate = prize_1 + prize_2 # A potential fn is used to constrain a model @pm.potential def error(true_price=true_price, price_estimate=price_estimate): return pm.normal_like(true_price, price_estimate, 1 / (3e3) ** 2) mcmc = pm.MCMC([true_price, prize_1, prize_2, price_estimate, error]) mcmc.sample(50000, 10000) price_trace = mcmc.trace("true_price")[:] x = np.linspace(5000, 40000) plt.plot(x, stats.norm.pdf(x, 35000, 7500), c="k", lw=2, label="prior dist. of suite price") _hist = plt.hist(price_trace, bins=35, normed=True, histtype="stepfilled") plt.title("Posterior of the true price estimate") plt.vlines(mu_prior, 0, 1.1 * np.max(_hist[0]), label="prior's mean", linestyles="--") plt.vlines(price_trace.mean(), 0, 1.1 * np.max(_hist[0]), label="posterior's mean", linestyles="-.") plt.legend(loc="upper left") plt.show() def showdown_loss(guess, true_price, risk=80000): loss = np.zeros_like(true_price) ix = true_price < guess loss[~ix] = np.abs(guess - true_price[~ix]) close_mask = [abs(true_price - guess) <= 250] loss[close_mask] = -2 * true_price[close_mask] loss[ix] = risk return loss guesses = np.linspace(5000, 50000, 70) risks = np.linspace(30000, 150000, 6) expected_loss = lambda guess, risk: showdown_loss(guess, price_trace, risk).mean() for _p in risks: results = [expected_loss(_g, _p) for _g in guesses] plt.plot(guesses, results, label="%d" % _p) plt.title("Expected loss of different guesses, \n" + "various risk-levels of overestimating") plt.legend(loc="upper left", title="Risk parameter") plt.xlabel("price bid") plt.ylabel("expected loss") plt.xlim(5000, 30000) plt.show() ax = plt.subplot(111) for _p in risks: _color = ax._get_lines.color_cycle.next() _min_results = sop.fmin(expected_loss, 15000, args=(_p,), disp=False) _results = [expected_loss(_g, _p) for _g in guesses] plt.plot(guesses, _results, color=_color) plt.scatter(_min_results, 0, s=60, color=_color, label="%d" % _p) plt.vlines(_min_results, 0, 120000, color=_color, linestyles="--") print "minimum at risk %d: %.2f" % (_p, _min_results) plt.title("Expected loss & Bayes actions of different guesses, \n \ various risk-levels of overestimating") plt.legend(loc="upper left", scatterpoints=1, title="Bayes action at risk:") plt.xlabel("price guess") plt.ylabel("expected loss") plt.xlim(7000, 30000) plt.ylim(-1000, 80000) plt.show() if __name__ == '__main__': main()
2,906
https://github.com/heiseish/SIA/blob/master/js/model/query/deleteTask.js
Github Open Source
Open Source
MIT
null
SIA
heiseish
JavaScript
Code
41
116
//@flow 'use-strict'; import firebase from '../'; const defectRef = firebase.database().ref('defects/'); export const deleteTask = (id: string) => { return new Promise((response,reject) => { if (id === undefined || id === null) reject({message: 'Error deleting defects!'}) else defectRef.child(id).remove().then(() => response()) }) }
44,725
https://github.com/TomSputz/BetterDiscordApp/blob/master/client/src/ui/components/bd/RemoteCard.vue
Github Open Source
Open Source
MIT
null
BetterDiscordApp
TomSputz
Vue
Code
137
575
/** * BetterDiscord Remote Card Component * Copyright (c) 2015-present Jiiks/JsSucks - https://github.com/Jiiks / https://github.com/JsSucks * All rights reserved. * https://betterdiscord.net * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ <template> <div class="bd-remoteCard"> <div class="bd-flexRow bd-flex"> <div class="bd-remoteCardTitle bd-flexGrow">{{item.name}} v{{item.version}} by {{item.author}}</div> <div class="bd-remoteCardLikes">{{item.rating}}</div> </div> <div class="bd-flexRow bd-flex" :style="{marginTop: '10px'}"> <div class="bd-remoteCardThumb" :style="{backgroundImage: `url(${resolveThumb()})`}"></div> <div class="bd-remoteCardInfoContainer bd-flex bd-flexCol bd-flexGrow"> <div class="bd-remoteCardInfoBox bd-flex bd-flexGrow bd-flexCol"> <div class="bd-remoteCardInfo">{{item.installs}} Installs</div> <div class="bd-remoteCardInfo">{{item.activeUsers}} Active Users</div> <div class="bd-remoteCardInfo">Updated: Some time ago</div> </div> </div> </div> <div class="bd-flexRow bd-flex bd-flexGrow"> <div class="bd-flexGrow bd-remoteCardTags">{{item.tags.join(', ')}}</div> <div class="bd-buttonGroup"> <div class="bd-button">Install</div> <div class="bd-button">Preview</div> <div class="bd-button">Source</div> </div> </div> </div> </template> <script> export default { props: ['item'], data() { return {} }, methods: { resolveThumb() { return `${this.item.repository.rawUri}/${this.item.files.previews[0].thumb}`; } } } </script>
9,593
https://github.com/ajvarela/amadeus-exploit/blob/master/fm/models/paper_JSS/evaluation_performance/CVE-2008-1092.afm
Github Open Source
Open Source
MIT
2,022
amadeus-exploit
ajvarela
Adobe Font Metrics
Code
133
639
# vul_description: Buffer overflow in msjet40.dll before 4.0.9505.0 in Microsoft Jet Database Engine allows remote attackers to execute arbitrary code via a crafted Word file, as exploited in the wild in March 2008. NOTE: as of 20080513, Microsoft has stated that this is the same issue as CVE_2007_6026. %Relationships CVE_2008_1092: types sources exploits microsoft [configs]; types: application; sources: nvd; exploits: [direct] [indirect]; configs: rc0; rc0: rc0_microsoft; microsoft: microsoft_word; rc0_microsoft: [1,1] {rc0_microsoft_windows__xp rc0_microsoft_windows__2003__server rc0_microsoft_windows__2000}; microsoft_word: microsoft_word_version microsoft_word_update; rc0_microsoft_windows__2003__server: rc0_microsoft_windows__2003__server_version; microsoft_word_version: [1,1] {microsoft_word_version_2003 microsoft_word_version_2003__sp3 microsoft_word_version_2007__sp1 microsoft_word_version_2007 microsoft_word_version_2000 microsoft_word_version_2002}; microsoft_word_update: [1,1] {microsoft_word_update_sp3 microsoft_word_update_any microsoft_word_update_sp2}; rc0_microsoft_windows__2003__server_version: rc0_microsoft_windows__2003__server_version_sp1; %Constraints microsoft_word REQUIRES application; microsoft_word_version_2003 REQUIRES microsoft_word_update_sp2; microsoft_word_version_2003 IMPLIES (rc0); microsoft_word_version_2003__sp3 REQUIRES microsoft_word_update_any; microsoft_word_version_2003__sp3 IMPLIES (rc0); microsoft_word_version_2007__sp1 REQUIRES microsoft_word_update_any; microsoft_word_version_2007__sp1 IMPLIES (rc0); microsoft_word_version_2007 REQUIRES microsoft_word_update_any; microsoft_word_version_2007 IMPLIES (rc0); microsoft_word_version_2000 REQUIRES microsoft_word_update_sp3; microsoft_word_version_2000 IMPLIES (rc0); microsoft_word_version_2002 REQUIRES microsoft_word_update_sp3; microsoft_word_version_2002 IMPLIES (rc0);
28,985
https://github.com/entrotech/deployapp/blob/master/Sabio.Web/Scripts/sabio.services.languageproficiency.js
Github Open Source
Open Source
MIT
null
deployapp
entrotech
JavaScript
Code
228
622
sabio.services.languageProficiency = sabio.services.languageProficiency || {}; // Create - GET - activeID sabio.services.languageProficiency.readById = function (id, onSuccess, onError) { // var url = "/api/languageproficiency/" + id; var settings = { cache: false ,contentType: "application/x-www-form-urlencoded; charset=UTF-8" , dataType: "json" , type: "GET" , success: onSuccess , error: onError }; $.ajax(url, settings); } // Create - POST - submit new entry sabio.services.languageProficiency.create = function (data, onSuccess, onError) { var url = "/api/languageproficiency/"; var settings = { cache: false , success: onSuccess , error: onError , contentType: "json" , dataType: "json" , data: data , type: "POST" }; $.ajax(url, settings); } // Create - PUT - update entry sabio.services.languageProficiency.update = function (id, data, onSuccess, onError) { var url = "/api/languageproficiency/" + id; var settings = { cache: false , contentType: "json" , dataType: "json" , data: data , type: "PUT" , success: onSuccess , error: onError }; $.ajax(url, settings); } // Create - DELETE - delete entry sabio.services.languageProficiency.delete = function (id, onSuccess, onError) { var url = "/api/languageproficiency/" + id; var settings = { cache: false , dataType: "json" , type: "DELETE" , success: onSuccess , error: onError }; $.ajax(url, settings); } // Index - GET - get all entries sabio.services.languageProficiency.read = function (onSuccess, onError) { var url = "/api/languageproficiency/"; var settings = { cache: false , dataType: "json" , type: "GET" , success: onSuccess , error: onError }; $.ajax(url, settings); }
28,649
https://github.com/powerpuffpenguin/webpc/blob/master/view/src/app/core/navigation/navigation.service.ts
Github Open Source
Open Source
MIT
2,022
webpc
powerpuffpenguin
TypeScript
Code
94
272
import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class NavigationService { private fullscreen_ = new BehaviorSubject<boolean>(false) get fullscreenObservable(): Observable<boolean> { return this.fullscreen_ } get fullscreen(): boolean { return this.fullscreen_.value } set fullscreen(val: boolean) { if (val == this.fullscreen_.value) { return } this.fullscreen_.next(val) } private target_ = new BehaviorSubject<string>('') get targetObservable(): Observable<string> { return this.target_ } get target(): string { return this.target_.value } set target(val: string) { if (typeof val !== "string") { return } if (val == this.target_.value) { return } this.target_.next(val) } }
32,679
https://github.com/isabella232/match/blob/master/packages/match-components/src/radio-group/radio.tsx
Github Open Source
Open Source
Apache-2.0, LicenseRef-scancode-unknown-license-reference
2,021
match
isabella232
TSX
Code
231
919
import { useField } from "formik"; import * as PropTypes from "prop-types"; import * as React from "react"; import { useUIDSeed } from "react-uid"; import { marginPropTypes } from "@twilio-labs/match-props"; import { RadioSize } from "./constants"; import { StyledRadio, StyledRadioWrapper, HiddenRadio, StyledRadioLabel, StyledRadioAdditional, StyledRadioTextWrapper, } from "./styles"; import type { RadioProps } from "./types"; export const Radio = React.forwardRef<HTMLInputElement, RadioProps>( ( { size, additional, required, name, label, value, disabled, readOnly, validate: validateOverride, noValidate, margin, marginY, marginX, marginRight, marginLeft, marginBottom, marginTop, ...props }, ref ) => { const seed = useUIDSeed(); const validate = (value: string) => { if (noValidate) return; if (validateOverride) return validateOverride(value); if (required && !value) { return "This field is required"; } }; const [field, meta] = useField({ name, disabled, value, type: "radio", validate, ...props, }); const hasError = meta.touched && Boolean(meta.error); return ( <StyledRadioWrapper margin={margin} marginY={marginY} marginX={marginX} marginRight={marginRight} marginLeft={marginLeft} marginBottom={marginBottom} marginTop={marginTop} radioSize={size} > <div> <StyledRadio hasError={hasError} disabled={disabled} readOnly={readOnly} checked={field.checked} radioSize={size} > <HiddenRadio type="radio" ref={ref} id={seed(`${name}_input`)} aria-labelledby={seed(`${name}_label`)} aria-describedby={ Boolean(additional) ? seed(`${name}_additional`) : undefined } aria-invalid={hasError} aria-disabled={disabled} disabled={Boolean(disabled || readOnly)} {...field} {...props} /> </StyledRadio> </div> <StyledRadioTextWrapper> <StyledRadioLabel id={seed(`${name}_label`)} htmlFor={seed(`${name}_input`)} > {label} </StyledRadioLabel> {Boolean(additional) && ( <StyledRadioAdditional id={seed(`${name}_additional`)}> {additional} </StyledRadioAdditional> )} </StyledRadioTextWrapper> </StyledRadioWrapper> ); } ); Radio.displayName = "Radio"; Radio.propTypes = { ...marginPropTypes, name: PropTypes.string.isRequired, label: PropTypes.string.isRequired, value: PropTypes.string.isRequired, size: PropTypes.oneOf(Object.values(RadioSize)), disabled: PropTypes.bool, readOnly: PropTypes.bool, required: PropTypes.bool, additional: PropTypes.string, validate: PropTypes.func, noValidate: PropTypes.bool, }; Radio.defaultProps = { size: RadioSize.NORMAL, };
5,216
https://github.com/aem/jsx-playground/blob/master/assets/example1-compiled.js
Github Open Source
Open Source
MIT
2,017
jsx-playground
aem
JavaScript
Code
18
41
/* @jsx console.log */ const getContent = () => { return console.log('null', { arg1: true }) } getContent()
4,627
https://github.com/hill84/bookworm-react/blob/master/src/components/forms/profileForm.tsx
Github Open Source
Open Source
MIT
2,018
bookworm-react
hill84
TypeScript
Code
1,461
5,700
import MomentUtils from '@date-io/moment'; import Avatar from '@material-ui/core/Avatar'; import CircularProgress from '@material-ui/core/CircularProgress'; import FormControl from '@material-ui/core/FormControl'; import FormHelperText from '@material-ui/core/FormHelperText'; import Input from '@material-ui/core/Input'; import InputLabel from '@material-ui/core/InputLabel'; import MenuItem from '@material-ui/core/MenuItem'; import Select from '@material-ui/core/Select'; import TextField from '@material-ui/core/TextField'; import { DatePicker, LocalizationProvider } from '@material-ui/pickers'; import classnames from 'classnames'; import { storage } from 'firebase'; import moment from 'moment'; import 'moment/locale/it'; import React, { ChangeEvent, FC, FormEvent, Fragment, ReactText, useCallback, useContext, useEffect, useRef, useState } from 'react'; import { storageRef, userRef } from '../../config/firebase'; import icon from '../../config/icons'; import { continents, europeanCountries, italianProvinces, languages, northAmericanCountries } from '../../config/lists'; import { app, calcAge, getInitials, urlRegex, validateImg } from '../../config/shared'; import SnackbarContext, { SnackbarContextModel } from '../../context/snackbarContext'; import UserContext from '../../context/userContext'; import '../../css/profileForm.css'; import { IsCurrent, UserContextModel, UserModel } from '../../types'; const min: Record<string, number> = { birth_date: new Date().setFullYear(new Date().getFullYear() - 120) }; const max: Record<string, number> = { birth_date: new Date().setFullYear(new Date().getFullYear() - 14) }; interface ProfileFormProps { user: UserModel; } interface StateModel { imgLoading: boolean; imgPreview: string; imgProgress: number; loading: boolean; changes: boolean; saved: boolean; errors: Record<string, ReactText | null>; isEditingSocial: boolean; } const initialState: StateModel = { imgLoading: false, imgPreview: '', imgProgress: 0, loading: false, changes: false, saved: false, errors: {}, isEditingSocial: false, }; const ProfileForm: FC<ProfileFormProps> = ({ user: _user }: ProfileFormProps) => { const { isAdmin, user: contextUser } = useContext<UserContextModel>(UserContext); const { openSnackbar } = useContext<SnackbarContextModel>(SnackbarContext); const [user, setUser] = useState<UserModel>(_user); const [imgLoading, setImgLoading] = useState<boolean>(initialState.imgLoading); const [imgPreview, setImgPreview] = useState<string>(user.photoURL); const [imgProgress, setImgProgress] = useState<number>(initialState.imgProgress); const [loading, setLoading] = useState<boolean>(initialState.loading); const [changes, setChanges] = useState<boolean>(initialState.changes); const [saved, setSaved] = useState<boolean>(initialState.saved); const [errors, setErrors] = useState<Record<string, ReactText | null>>(initialState.errors); const [isEditingSocial, setIsEditingSocial] = useState<boolean>(initialState.isEditingSocial); const is = useRef<IsCurrent>(false); useEffect(() => { is.current = true; return () => { is.current = false }; }, []); const luid: string | undefined = contextUser?.uid; const uid: string = user?.uid; const setChange = useCallback((name: string, value: string): void => { setUser({ ...user, [name]: value }); if (errors[name]) setErrors({ ...errors, [name]: null }); setSaved(false); setChanges(true); }, [errors, user]); const onChange = (e: ChangeEvent<HTMLInputElement>): void => { e.persist(); const { name, value } = e.target; setChange(name, value); }; const onChangeSelect = (e: ChangeEvent<{ name?: string; value: unknown }>): void => { e.persist(); const { name, value } = e.target; if (!name) return; setChange(name, value as string); }; const onChangeDate = useCallback((name: string) => (date: Date | null): void => { const value = String(date); setChange(name, value); }, [setChange]); const onSetDatePickerError = (name: string, reason: string): void => { const errorMessages: Record<string, string> = { disableFuture: 'Data futura non valida', disablePast: 'Data passata non valida', invalidDate: 'Data non valida', minDate: `Data non valida prima del ${new Date(min[name]).toLocaleDateString()}`, maxDate: `Data non valida oltre il ${new Date(max[name]).toLocaleDateString()}` }; setErrors(errors => ({ ...errors, [name]: errorMessages[reason] })); }; const validate = (user: UserModel) => { const errors: Record<string, string> = {}; if (!user.displayName) errors.displayName = 'Inserisci un nome utente'; if (new Date(user.birth_date).getTime() > new Date().getTime()) { errors.birth_date = 'Data di nascita non valida'; } else if (calcAge(user.birth_date) < 13) { errors.birth_date = 'Età minima 14 anni'; } else if (calcAge(user.birth_date) > 119) { errors.birth_date = 'E chi sei.. Matusalemme?'; } if (user.city?.length > 150) errors.city = 'Lunghezza massima 150 caratteri'; if (user.website && !user.website.match(urlRegex)) errors.website = 'URL non valido'; if (user.youtube?.includes('youtube.com')) errors.youtube = 'Rimuovi "https://www.youtube.com/channel/"'; if (user.instagram?.includes('instagram.com')) errors.instagram = 'Rimuovi "https://www.instagram.com/"'; if (user.twitch?.includes('twitch.tv')) errors.twitch = 'Rimuovi "https://www.twitch.tv/"'; if (user.facebook?.includes('facebook.com')) errors.facebook = 'Rimuovi "https://www.facebook.com/"'; return errors; }; const onImageChange = (e: ChangeEvent<HTMLInputElement>): void => { e.preventDefault(); const file: File | undefined = e.target.files?.[0]; if (file) { const error: string | undefined = validateImg(file, 1); if (!error) { setImgLoading(true); setErrors({ ...errors, upload: null }); const uploadTask: storage.UploadTask = storageRef.child(`users/${uid}/avatar`).put(file); const unsubUploadTask: Function = uploadTask.on('state_changed', (snap: storage.UploadTaskSnapshot): void => { setImgProgress((snap.bytesTransferred / snap.totalBytes) * 100); }, (err: Error): void => { // console.warn(`Upload error: ${error.message}`); setErrors({ ...errors, upload: err.message }); setImgLoading(false); setImgProgress(0); openSnackbar(err.message, 'error'); }, (): void => { // console.log('upload completed'); uploadTask.then((snap: storage.UploadTaskSnapshot): void => { snap.ref.getDownloadURL().then((url: string): void => { if (is.current) { setImgLoading(false); setImgPreview(url); setChanges(true); setSaved(false); openSnackbar('Immagine caricata', 'success'); } }); }); unsubUploadTask(); }); } else { setErrors({ ...errors, upload: error }); openSnackbar(error, 'error'); setTimeout((): void => { setErrors({ ...errors, upload: null }); }, 2000); } } }; const onSubmit = (e: FormEvent<HTMLFormElement>): void => { e.preventDefault(); const errors: Record<string, string | number> = validate(user); setErrors(errors); if (Object.keys(errors).length === 0) { setLoading(true); setIsEditingSocial(false); userRef(uid).set({ ...user, photoURL: imgPreview || '', sex: user.sex || '', birth_date: user.birth_date || '', city: user.city || '', country: user.country || '' }).then((): void => { if (is.current) { setImgProgress(0); setChanges(false); setSaved(true); openSnackbar('Modifiche salvate', 'success'); // setRedirectToReferrer(true); } }).catch((err: Error): void => { openSnackbar(err.message, 'error'); }).finally((): void => { setLoading(false); }); } else openSnackbar('Ricontrolla i dati inseriti', 'error'); }; const onToggleSocial = (): void => setIsEditingSocial(isEditingSocial => !isEditingSocial); const menuItemsMap = (arr: Record<string, string>[]) => arr.map(({ name, nativeName, id }: Record<string, string>) => ( <MenuItem value={name} title={nativeName} key={id}> {name} </MenuItem> )); // if (!user) return null; return ( <Fragment> {loading && <div aria-hidden='true' className='loader'><CircularProgress /></div>} <div className='container sm' ref={is}> <div className='row basic-profile'> <div className='col-auto'> <div className={classnames('upload-avatar', errors.upload ? 'error' : imgProgress === 100 ? 'success' : null)}> <Avatar className='avatar' src={imgPreview} alt={user.displayName}>{!imgPreview && getInitials(user.displayName)}</Avatar> {imgLoading ? ( <div aria-hidden='true' className='loader'><CircularProgress /></div> ) : ( <div className='overlay'> <span title="Carica un'immagine">+</span> <input type='file' accept='image/*' className='upload' onChange={onImageChange}/> </div> )} </div> </div> <div className='col'> <div className='username'>{user.displayName || 'Innominato'}</div> <div className='email'>{user.email}</div> </div> </div> <div>&nbsp;</div> <form onSubmit={onSubmit} noValidate> <div className='form-group'> <FormControl className='input-field' margin='normal' fullWidth> <InputLabel error={Boolean(errors.displayName)} htmlFor='displayName'>Nome e cognome</InputLabel> <Input id='displayName' name='displayName' type='text' placeholder='es: Mario Rossi' value={user.displayName || ''} readOnly={!isAdmin} onChange={onChange} error={Boolean(errors.displayName)} /> {!isAdmin && ( user.displayName && ( <FormHelperText className='message'> Per modificare il <span className='hide-sm'>nominativo</span><span className='show-sm'>nome</span> scrivi a <a href={`mailto:${app.email}?subject=Biblo: modifica nominativo utente`}>{app.email}</a>. </FormHelperText> ) )} {errors.displayName && ( <FormHelperText className='message error'> {errors.displayName} </FormHelperText> )} </FormControl> </div> <div className='row'> <div className='col form-group'> <FormControl className='select-field' margin='normal' fullWidth> <InputLabel error={Boolean(errors.sex)} htmlFor='sex'>Sesso</InputLabel> <Select id='sex' placeholder='es: Femmina' name='sex' value={user.sex || ''} onChange={onChangeSelect} error={Boolean(errors.sex)}> <MenuItem key='m' value='m'>Uomo</MenuItem> <MenuItem key='f' value='f'>Donna</MenuItem> <MenuItem key='x' value='x'>Altro</MenuItem> </Select> {errors.sex && <FormHelperText className='message error'>{errors.sex}</FormHelperText>} </FormControl> </div> <div className='col form-group'> <LocalizationProvider dateAdapter={MomentUtils} dateLibInstance={moment} locale='it'> <DatePicker className='date-picker' cancelText='Annulla' leftArrowIcon={icon.chevronLeft} rightArrowIcon={icon.chevronRight} inputFormat='DD/MM/YYYY' // invalidDateMessage='Data non valida' minDate={min.birth_date} maxDate={max.birth_date} // minDateMessage='Chi sei? ...Matusalemme?' // maxDateMessage='Età minima 14 anni' label='Data di nascita' // autoOk value={user.birth_date ? new Date(user.birth_date) : null} onChange={onChangeDate('birth_date')} onError={reason => onSetDatePickerError('birth_date', reason || '')} renderInput={props => ( <TextField {...props} margin='normal' fullWidth helperText={errors.birth_date} /> )} /> </LocalizationProvider> </div> </div> <div className='form-group'> <FormControl className='select-field' margin='normal' fullWidth> <InputLabel htmlFor='languages'>{`Lingue conosciute ${user.languages?.length > 1 ? ` (${user.languages.length})` : ''}`}</InputLabel> <Select id='languages' placeholder='es: Italiano, Spagnolo' name='languages' value={user.languages || []} onChange={onChangeSelect} multiple> {menuItemsMap(languages)} </Select> </FormControl> </div> <div className='row'> <div className='col form-group'> <FormControl className='select-field' margin='normal' fullWidth> <InputLabel htmlFor='continent'>Continente</InputLabel> <Select id='continent' placeholder='es: Europa' name='continent' value={user.continent || ''} onChange={onChangeSelect}> {menuItemsMap(continents)} </Select> </FormControl> </div> {(user.continent === 'Europa' || user.continent === 'Nordamerica') && ( <div className='col form-group'> <FormControl className='select-field' margin='normal' fullWidth> <InputLabel htmlFor='nation'>Nazione</InputLabel> <Select id='nation' placeholder='es: Italia' name='country' value={user.country || ''} onChange={onChangeSelect}> {user.continent === 'Europa' && menuItemsMap(europeanCountries)} {user.continent === 'Nordamerica' && menuItemsMap(northAmericanCountries)} </Select> </FormControl> </div> )} </div> <div className='form-group'> {user.country && user.country === 'Italia‎' ? ( <FormControl className='select-field' margin='normal' fullWidth> <InputLabel htmlFor='city'>Provincia</InputLabel> <Select id='city' placeholder='es: Torino' name='city' value={user.city || ''} onChange={onChangeSelect}> {menuItemsMap(italianProvinces)} </Select> </FormControl> ) : ( <FormControl className='input-field' margin='normal' fullWidth> <InputLabel error={Boolean(errors.city)} htmlFor='city'>Città</InputLabel> <Input id='city' name='city' type='text' placeholder='es: New York' value={user.city || ''} onChange={onChange} error={Boolean(errors.city)} /> {errors.city && <FormHelperText className='message error'>{errors.city}</FormHelperText>} </FormControl> )} </div> {isEditingSocial ? ( <> <div className='form-group'> <FormControl className='input-field' margin='normal' fullWidth> <InputLabel error={Boolean(errors.website)} htmlFor='website'>Sito internet o blog</InputLabel> <Input id='website' name='website' type='url' placeholder={`es: ${app.url}`} value={user.website || ''} onChange={onChange} error={Boolean(errors.website)} /> {errors.website && <FormHelperText className='message error'>{errors.website}</FormHelperText>} </FormControl> </div> <div className='form-group'> <FormControl className='input-field' margin='normal' fullWidth> <InputLabel error={Boolean(errors.youtube)} htmlFor='youtube'>Canale Youtube</InputLabel> <Input id='youtube' name='youtube' type='url' autoComplete='https://www.youtube.com/channel/' placeholder='es: bibloSpace' value={user.youtube || ''} onChange={onChange} error={Boolean(errors.youtube)} /> {errors.youtube && <FormHelperText className='message error'>{errors.youtube}</FormHelperText>} </FormControl> </div> <div className='form-group'> <FormControl className='input-field' margin='normal' fullWidth> <InputLabel error={Boolean(errors.instagram)} htmlFor='instagram'>Profilo Instagram</InputLabel> <Input id='instagram' name='instagram' type='url' autoComplete='https://www.instagram.com/' placeholder='es: bibloSpace' value={user.instagram || ''} onChange={onChange} error={Boolean(errors.instagram)} /> {errors.instagram && <FormHelperText className='message error'>{errors.instagram}</FormHelperText>} </FormControl> </div> <div className='form-group'> <FormControl className='input-field' margin='normal' fullWidth> <InputLabel error={Boolean(errors.twitch)} htmlFor='twitch'>Canale Twitch</InputLabel> <Input id='twitch' name='twitch' type='url' autoComplete='https://www.twitch.tv/' placeholder='es: bibloSpace' value={user.twitch || ''} onChange={onChange} error={Boolean(errors.twitch)} /> {errors.twitch && <FormHelperText className='message error'>{errors.twitch}</FormHelperText>} </FormControl> </div> <div className='form-group'> <FormControl className='input-field' margin='normal' fullWidth> <InputLabel error={Boolean(errors.facebook)} htmlFor='facebook'>Pagina Facebook</InputLabel> <Input id='facebook' name='facebook' type='url' autoComplete='https://www.facebook.com/' placeholder='es: bibloSpace' value={user.facebook || ''} onChange={onChange} error={Boolean(errors.facebook)} /> {errors.facebook && <FormHelperText className='message error'>{errors.facebook}</FormHelperText>} </FormControl> </div> </> ) : ( <div className='info-row'> <button type='button' className='btn flat rounded centered' onClick={onToggleSocial}> {(user.website || user.youtube || user.instagram || user.twitch || user.facebook) ? 'Modifica' : 'Aggiungi'} profili social </button> </div> )} <div>&nbsp;</div> {luid === uid && ( <FormHelperText className='message'> Per cancellare l&apos;account scrivi a <a href={`mailto:${app.email}?subject=Biblo: cancellazione account utente`}>{app.email}</a>. </FormHelperText> )} </form> </div> <div className='footer no-gutter'> <button type='button' className={classnames('btn', 'btn-footer', saved && !changes ? 'success' : 'primary')} disabled={!changes} onClick={onSubmit as (e: FormEvent) => void} > {saved ? 'Modifiche salvate' : 'Salva le modifiche'} </button> </div> </Fragment> ); }; export default ProfileForm;
31,450
https://github.com/honux77/prostar/blob/master/week4/random.cs
Github Open Source
Open Source
MIT
2,014
prostar
honux77
C#
Code
22
57
using System; class Test { static void Main(string[] args) { Random r = new Random(); int x = r.Next(1,10); Console.WriteLine(x); } }
27,196
https://github.com/siouan/frontend-gradle-plugin/blob/master/src/main/java/org/siouan/frontendgradleplugin/infrastructure/gradle/TaskLoggerConfigurer.java
Github Open Source
Open Source
Apache-2.0
2,022
frontend-gradle-plugin
siouan
Java
Code
216
592
package org.siouan.frontendgradleplugin.infrastructure.gradle; import javax.annotation.Nonnull; import org.gradle.api.Task; import org.gradle.api.logging.LogLevel; import org.gradle.api.logging.LoggingManager; import org.siouan.frontendgradleplugin.infrastructure.gradle.adapter.GradleLoggerAdapter; /** * Class injecting in the bean registry a logger forwarding messages to the logger of a Gradle task. * * @since 2.0.0 */ public class TaskLoggerConfigurer { private final FrontendExtension extension; private final GradleLoggerAdapter gradleLoggerAdapter; private final GradleSettings gradleSettings; public TaskLoggerConfigurer(final FrontendExtension extension, final GradleLoggerAdapter gradleLoggerAdapter, final GradleSettings gradleSettings) { this.extension = extension; this.gradleLoggerAdapter = gradleLoggerAdapter; this.gradleSettings = gradleSettings; } public void initLoggerAdapter(@Nonnull final Task task) { task .getLogger() .debug("Configuring logger for task '{}': verboseModeEnabled={}", task.getName(), extension.getVerboseModeEnabled().get()); gradleLoggerAdapter.init(task.getLogger(), resolveLogLevel(task), extension.getVerboseModeEnabled().get(), '[' + task.getName() + "] "); } /** * Resolves the logging level currently active for a given task. This method allows to deal with Gradle's * limitations when we need to get the applicable logging level for a task. Actually Gradle does not populate * automatically the level in the task's {@link LoggingManager} with the level from the command line by default, and * the only way to get it is to look at the start parameter. * * @param task Task. * @return Logging level. */ @Nonnull private LogLevel resolveLogLevel(@Nonnull final Task task) { LogLevel loggingLevel = task.getLogging().getLevel(); if (loggingLevel != null) { return loggingLevel; } loggingLevel = gradleSettings.getProjectLogLevel(); if (loggingLevel != null) { return loggingLevel; } return gradleSettings.getCommandLineLogLevel(); } }
32,165
https://github.com/marcelometal/dotfiles-1/blob/master/fish/config.fish
Github Open Source
Open Source
MIT
2,014
dotfiles-1
marcelometal
Fish
Code
230
939
# Path to your oh-my-fish. set fish_path $HOME/.config/fish # Theme set fish_theme robbyrussell # Which plugins would you like to load? (plugins can be found in ~/.oh-my-fish/plugins/*) # Custom plugins may be added to ~/.oh-my-fish/custom/plugins/ # Example format: set fish_plugins autojump bundler set fish_plugins rvm python # Path to your custom folder (default path is $FISH/custom) #set fish_custom $HOME/dotfiles/oh-my-fish # Load oh-my-fish configuration. . $fish_path/oh-my-fish.fish function fish_title;end set fish_color_error ff8a00 set -g __fish_git_prompt_show_informative_status 1 set -g __fish_git_prompt_hide_untrackedfiles 1 set -g __fish_git_prompt_color_branch magenta bold set -g __fish_git_prompt_showupstream "informative" set -g __fish_git_prompt_char_upstream_ahead "↑" set -g __fish_git_prompt_char_upstream_behind "↓" set -g __fish_git_prompt_char_upstream_prefix "" set -g __fish_git_prompt_char_stagedstate "●" set -g __fish_git_prompt_char_dirtystate "✚" set -g __fish_git_prompt_char_untrackedfiles "…" set -g __fish_git_prompt_char_conflictedstate "✖" set -g __fish_git_prompt_char_cleanstate "✔" set -g __fish_prompt_color_date red light set -g __fish_git_prompt_color_dirtystate blue light set -g __fish_git_prompt_color_stagedstate yellow set -g __fish_git_prompt_color_invalidstate red set -g __fish_git_prompt_color_untrackedfiles $fish_color_normal set -g __fish_git_prompt_color_cleanstate green bold set -g VIRTUALFISH_COMPAT_ALIASES # uncomment for virtualenvwrapper-style commands source $fish_function_path/virtual.fish # optional plugins source $fish_function_path/auto_activation.fish source $fish_function_path/global_requirements.fish source $fish_function_path/projects.fish setenv EDITOR mvim set fish_greeting set -x GOPATH $HOME/dev/go if test -d /usr/local/Cellar/go/1.2.1/libexec/bin set -gx PATH $PATH /usr/local/Cellar/go/1.2.1/libexec/bin $GOPATH/bin end if test -d /usr/lib/node_modules/bower/bin set -gx PATH /usr/lib/node_modules/bower/bin $PATH end set -gx PROJECT_HOME ~/dev set -x PIP_REQUIRE_VIRTUALENV 1 set -x PIP_RESPECT_VIRTUALENV 1 set -x PIP_LOG_FILE '~/.cache/pip-log.txt' set -x PIP_DOWNLOAD_CACHE '~/.cache/pip_cache' if test $HOMEBREW set -x VIRTUALENVWRAPPER_PYTHON /usr/local/bin/python end set -gx fish_function_path $fish_function_path ~/.config/fish/bundles/functions/ fish_bundle "heynemann/git-support-fish-bundle"
20,439
https://github.com/MartenCatcher/mongo-rust-driver/blob/master/src/lib.rs
Github Open Source
Open Source
MIT, Apache-2.0
2,020
mongo-rust-driver
MartenCatcher
Rust
Code
312
874
//! This crate is a pure Rust MongoDB driver. It follows the //! [MongoDB driver API and feature specifications](https://github.com/mongodb/specifications). //! //! To connect to a MongoDB database, pass a MongoDB connection string to //! [`Client::with_uri_str`](struct.Client.html#method.with_uri_str): //! //! ```rust //! # use mongors::{Client, error::Result}; //! # //! # fn make_client() -> Result<Client> { //! let client = Client::with_uri_str("mongodb://localhost:27017/")?; //! # Ok(client) //! # } //! ``` //! Alternately, create an instance of [`ClientOptions`](options/struct.ClientOptions.html) and pass //! it to [`Client::with_options`](struct.Client.html#method.with_options): //! //! ```rust //! # use mongors::{ //! # error::Result, //! # options::{StreamAddress, ClientOptions}, //! # Client, //! # }; //! # //! # fn make_client() -> Result<Client> { //! let options = ClientOptions::builder() //! .hosts(vec![ //! StreamAddress { //! hostname: "localhost".into(), //! port: Some(27017), //! } //! ]) //! .build(); //! //! let client = Client::with_options(options)?; //! # Ok(client) //! # } //! ``` //! //! Operations can be performed by obtaining a [`Database`](struct.Database.html) or //! [`Collection`](struct.Collection.html) from the [`Client`](struct.Client.html): //! //! ```rust //! # use mongors::{Client, error::Result}; //! # use mongors::doc; //! # //! # fn do_stuff() -> Result<()> { //! # let client = Client::with_uri_str("mongodb://localhost:27017")?; //! # //! let db = client.database("some_db"); //! for coll_name in db.list_collection_names(None)? { //! println!("collection: {}", coll_name); //! } //! //! let coll = db.collection("some-coll"); //! let result = coll.insert_one(doc! { "x": 1 }, None)?; //! println!("{:#?}", result); //! //! # Ok(()) //! # } //! ``` #![allow(unused_variables)] #![cfg_attr( feature = "cargo-clippy", allow( clippy::unreadable_literal, clippy::cognitive_complexity, clippy::float_cmp ) )] #[macro_use] pub mod options; // #[macro_use] pub mod bson; pub mod util; mod bson_util; mod client; mod cmap; mod coll; mod collation; mod concern; mod cursor; mod db; pub mod error; pub mod event; mod is_master; mod operation; pub mod results; mod sdam; mod selection_criteria; mod srv; #[cfg(test)] mod test; #[cfg(test)] #[macro_use] extern crate derive_more; pub use self::bson::{Bson, Document}; pub use crate::{ client::Client, coll::{Collection, Namespace}, cursor::Cursor, db::Database, };
5,659
https://github.com/faithhub/incare/blob/master/app/Http/Controllers/Auth/RegisterController.php
Github Open Source
Open Source
MIT
null
incare
faithhub
PHP
Code
293
936
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Mail\RegistrationMail; use App\Providers\RouteServiceProvider; use App\Models\User; use Illuminate\Foundation\Auth\RegistersUsers; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Validator; class RegisterController extends Controller { /* |-------------------------------------------------------------------------- | Register Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users as well as their | validation and creation. By default this controller uses a trait to | provide this functionality without requiring any additional code. | */ use RegistersUsers; /** * Where to redirect users after registration. * * @var string */ // protected $redirectTo = RouteServiceProvider::REG; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest'); } public function redirectTo() { Session::flash('success', 'Successfully Registered'); Auth::logout(); return '/login'; // $role = Auth::user()->type; // switch ($role) { // case '1': // return '/employer'; // break; // case '2': // return '/care-giver'; // break; // case '3': // return '/admin'; // break; // default: // return '/logout'; // break; // } } /** * Get a validator for an incoming registration request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'first_name' => ['required', 'string', 'max:255'], 'last_name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'password' => ['required', 'string', 'min:8', 'confirmed', 'max:16', 'regex:/[a-z]/', 'regex:/[A-Z]/', 'regex:/[0-9]/', 'regex:/[@$!%*#?&+-]/'], 'type' => ['required'], 'policy' => ['required'], 'terms' => ['required'], ]); } /** * Create a new user instance after a valid registration. * * @param array $data * @return \App\Models\User */ protected function create(array $data) { //dd($data['email']); Mail::to($data['email'])->send(new RegistrationMail($data)); Session::flash('success', 'Registered Successfully'); $user = User::create([ 'first_name' => $data['first_name'], 'last_name' => $data['last_name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), 'type' => $data['type'], 'wallet' => 0, 'plan_end_date' => Carbon::now()->addMonth(1), ]); // dd($user->id); //return redirect('login'); return $user; } }
10,737
https://github.com/nullcc/ts-interface-keys-transformer/blob/master/transformer.ts
Github Open Source
Open Source
MIT
2,020
ts-interface-keys-transformer
nullcc
TypeScript
Code
704
2,356
import * as path from 'path'; import * as _ from 'lodash'; import * as ts from 'typescript'; export default (program: ts.Program): ts.TransformerFactory<ts.SourceFile> => { return (ctx: ts.TransformationContext) => { return (sourceFile: ts.SourceFile): ts.SourceFile => { const visitor = (node: ts.Node): ts.Node => { return ts.visitEachChild(visitNode(node, program), visitor, ctx); }; return <ts.SourceFile> ts.visitEachChild(visitNode(sourceFile, program), visitor, ctx); }; }; } interface Property { name: string; modifiers: string[]; optional: boolean; type: string; elementKeys?: string[]; elementType?: any; } const symbolMap = new Map<string, ts.Symbol>(); const visitNode = (node: ts.Node, program: ts.Program): ts.Node => { // collect all top level symbols in the source file if (node.kind === ts.SyntaxKind.SourceFile) { node['locals'].forEach((symbol: ts.Symbol, key: string) => { if (!symbolMap.has(key)) { symbolMap.set(key, symbol); } }); } const typeChecker = program.getTypeChecker(); if (!isKeysCallExpression(node, typeChecker)) { return node; } if (!node.typeArguments) { return ts.createArrayLiteral([]); } const type = typeChecker.getTypeFromTypeNode(node.typeArguments[0]); let properties: Property[] = []; const symbols = typeChecker.getPropertiesOfType(type); symbols.forEach(symbol => { properties = [ ...properties, ...getSymbolProperties(symbol, [], symbolMap) ]; }); return ts.createArrayLiteral(properties.map(property => ts.createRegularExpressionLiteral(JSON.stringify(property)))); }; const getSymbolProperties = (symbol: ts.Symbol, outerLayerProperties: Property[], symbolMap: Map<string, ts.Symbol>): Property[] => { let properties: Property[] = []; const propertyPathElements = JSON.parse(JSON.stringify(outerLayerProperties.map(property => property))); const propertyName = symbol.escapedName; propertyPathElements.push(propertyName); /* please note: due to interface or type can be a intersection types (e.g. A & B) * or a union types (e.g. A | B), these types have no "valueDeclaration" property. * We must traverse the "symbol.declarations" to collect "questionToken" of all sub types */ const optional = _.some(symbol.declarations, (declaration: ts.PropertyDeclaration) => { return !!declaration.questionToken; }); const modifiers: string[] = []; symbol.declarations.forEach((declaration: any) => { if (declaration.modifiers) { declaration.modifiers.forEach((modifier: ts.Token<ts.SyntaxKind.ReadonlyKeyword>) => { modifiers.push(getModifierType(modifier)); }); } }); const property: Property = { name: propertyPathElements.join('.'), modifiers, optional, type: getPropertyType(symbol.valueDeclaration ? symbol.valueDeclaration['type'] : symbol['type']), }; if (symbol.valueDeclaration && symbol.valueDeclaration['type'].kind === ts.SyntaxKind.ArrayType) { // array: [] const elementType = getPropertyType(symbol.valueDeclaration['type'].elementType); if (symbol.valueDeclaration['type'].elementType.members) { property.elementKeys = _.flattenDeep(symbol.valueDeclaration['type'].elementType.members.map((member: any) => { return getSymbolProperties(member.symbol, [], symbolMap); })); } else if (symbol['typeArguments']) { property.elementKeys = _.flattenDeep(symbol['typeArguments'][0].members.map((member: any) => { return getSymbolProperties(member.symbol, [], symbolMap); })); } else { const members = symbolMap.has(elementType) ? (symbolMap.get(elementType)!['declarations'][0] as any).members : []; if (members && members.length > 0) { property.elementKeys = _.flattenDeep(members.map((member: any) => { return getSymbolProperties(member.symbol, [], symbolMap); })); } else { property.elementType = elementType; } } } else if (symbol.valueDeclaration && symbol.valueDeclaration['type']['typeArguments']) { // for Array<xxx> let type; if (symbol.valueDeclaration['type']['typeArguments'][0].typeName) { type = symbol.valueDeclaration['type']['typeArguments'][0].typeName.escapedText; } const members = symbolMap.has(type) ? (symbolMap.get(type)!['declarations'][0] as any).members : symbol.valueDeclaration['type']['typeArguments'][0].members; property.elementKeys = _.flattenDeep(members.map((member: any) => { return getSymbolProperties(member.symbol, [], symbolMap); })); } properties.push(property); const propertiesOfSymbol = _getPropertiesOfSymbol(symbol, propertyPathElements, symbolMap); properties = [ ...properties, ...propertiesOfSymbol, ]; return properties; }; const isOutermostLayerSymbol = (symbol: any): boolean => { return symbol.valueDeclaration && symbol.valueDeclaration.symbol.valueDeclaration.type.members; }; const isInnerLayerSymbol = (symbol: any): boolean => { return symbol.valueDeclaration && symbol.valueDeclaration.symbol.valueDeclaration.type.typeName; }; const _getPropertiesOfSymbol = (symbol: ts.Symbol, propertyPathElements: Property[], symbolMap: Map<string, ts.Symbol>): Property[] => { if (!isOutermostLayerSymbol(symbol) && !isInnerLayerSymbol(symbol)) { return []; } let properties: Property[] = []; let members: any; if ((<any>symbol.valueDeclaration).type.symbol) { members = (<any>symbol.valueDeclaration).type.members.map((member: any) => member.symbol); } else { const propertyTypeName = (<any>symbol.valueDeclaration).type.typeName.escapedText; const propertyTypeSymbol = symbolMap.get(propertyTypeName); if (propertyTypeSymbol) { if (propertyTypeSymbol.members) { members = propertyTypeSymbol.members; } else { members = (<any>propertyTypeSymbol).exportSymbol.members; } } } if (members) { members.forEach((member: any) => { properties = [ ...properties, ...getSymbolProperties(member, propertyPathElements, symbolMap), ]; }); } return properties; }; const getPropertyType = (symbol: any): string => { if (symbol.intrinsicName) { return symbol.intrinsicName; } if (symbol.types) { return symbol.types.map((token: any) => getPropertyType(token)); } switch (symbol.kind) { case ts.SyntaxKind.ArrayType: return 'array'; case ts.SyntaxKind.StringKeyword: return 'string'; case ts.SyntaxKind.NumberKeyword: return 'number'; case ts.SyntaxKind.BooleanKeyword: return 'boolean'; case ts.SyntaxKind.FunctionType: return 'Function'; case ts.SyntaxKind.TypeReference: return symbol.typeName.escapedText; case ts.SyntaxKind.AnyKeyword: return 'any'; case ts.SyntaxKind.NullKeyword: return 'null'; case ts.SyntaxKind.ObjectKeyword: return 'object'; case ts.SyntaxKind.TypeLiteral: return 'object'; case ts.SyntaxKind.UnionType: return symbol.types.map((token: any) => getPropertyType(token)); case ts.SyntaxKind.IntersectionType: return symbol.types.map((token: any) => getPropertyType(token)); default: return 'unknown'; } }; const getModifierType = (modifier: ts.Token<ts.SyntaxKind>): string => { switch (modifier.kind) { case ts.SyntaxKind.ReadonlyKeyword: return 'readonly'; default: return 'unknown'; } } const indexTs = path.join(__dirname, './index.ts'); const isKeysCallExpression = (node: ts.Node, typeChecker: ts.TypeChecker): node is ts.CallExpression => { if (!ts.isCallExpression(node)) { return false; } const signature = typeChecker.getResolvedSignature(node); if (typeof signature === 'undefined') { return false; } const { declaration } = signature; return !!declaration && !ts.isJSDocSignature(declaration) && (path.join(declaration.getSourceFile().fileName) === indexTs) && !!declaration.name && declaration.name.getText() === 'keys'; };
1,553
https://github.com/YXDsimon/Cpp-Concurrency-in-Action-2ed/blob/master/code/parallel_quick_sort.hpp
Github Open Source
Open Source
Apache-2.0
2,020
Cpp-Concurrency-in-Action-2ed
YXDsimon
C++
Code
60
255
#include <list> #include <algorithm> #include <future> #include <utility> template<typename T> std::list<T> parallel_quick_sort(std::list<T> v) { if (v.empty()) return v; std::list<T> res; res.splice(res.begin(), v, v.begin()); const T& firstVal = *res.begin(); auto it = std::partition(v.begin(), v.end(), [&](const T& x) { return x < firstVal; }); std::list<T> low; low.splice(low.end(), v, v.begin(), it); std::future<std::list<T>> l(std::async(&parallel_quick_sort<T>, std::move(low))); auto r(parallel_quick_sort(std::move(v))); res.splice(res.end(), r); res.splice(res.begin(), l.get()); return res; }
33,522
https://github.com/thestormforge/redskyops-controller/blob/master/api/apps/v1alpha1/requests.go
Github Open Source
Open Source
Apache-2.0
2,019
redskyops-controller
thestormforge
Go
Code
141
403
/* Copyright 2021 GramLabs, 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 v1alpha1 import ( "strings" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" ) // DefaultCostWeights returns resource weightings for recognized special names. func DefaultCostWeights(name string) corev1.ResourceList { switch strings.Map(toName, name) { case "cost": return corev1.ResourceList{ corev1.ResourceCPU: resource.MustParse("17"), corev1.ResourceMemory: resource.MustParse("3"), } case "cpu-requests", "cpu": return corev1.ResourceList{ corev1.ResourceCPU: resource.MustParse("1"), } case "memory-requests", "memory": return corev1.ResourceList{ corev1.ResourceMemory: resource.MustParse("1"), } default: return nil } }
31,239
https://github.com/madewithfelt/betamax/blob/master/lib/src/http/http_interceptor.dart
Github Open Source
Open Source
MIT
2,021
betamax
madewithfelt
Dart
Code
102
241
import 'dart:async'; import 'package:http/io_client.dart'; import 'http_intercepted_types.dart'; abstract class HttpInterceptor { /// [correlator] is a value generated by the client for each request-response, /// exchange, and is used to associate the request with the response. /// /// Returns an [OverrideResponse] if the interceptor wishes to halt the /// regular network call, and return an alternate response. FutureOr<OverrideResponse?> interceptRequest( InterceptedBaseRequest request, String correlator, ); /// [correlator] is a value generated by the client for each request-response, /// exchange, and is used to associate the request with the response. void interceptStreamedResponse( InterceptedIOStreamedResponse response, String correlator, ); } class OverrideResponse { OverrideResponse(this.streamedResponse); final IOStreamedResponse streamedResponse; }
7,850
https://github.com/XPixelGroup/BasicSR/blob/master/basicsr/losses/basic_loss.py
Github Open Source
Open Source
Apache-2.0
2,023
BasicSR
XPixelGroup
Python
Code
914
2,767
import torch from torch import nn as nn from torch.nn import functional as F from basicsr.archs.vgg_arch import VGGFeatureExtractor from basicsr.utils.registry import LOSS_REGISTRY from .loss_util import weighted_loss _reduction_modes = ['none', 'mean', 'sum'] @weighted_loss def l1_loss(pred, target): return F.l1_loss(pred, target, reduction='none') @weighted_loss def mse_loss(pred, target): return F.mse_loss(pred, target, reduction='none') @weighted_loss def charbonnier_loss(pred, target, eps=1e-12): return torch.sqrt((pred - target)**2 + eps) @LOSS_REGISTRY.register() class L1Loss(nn.Module): """L1 (mean absolute error, MAE) loss. Args: loss_weight (float): Loss weight for L1 loss. Default: 1.0. reduction (str): Specifies the reduction to apply to the output. Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean'. """ def __init__(self, loss_weight=1.0, reduction='mean'): super(L1Loss, self).__init__() if reduction not in ['none', 'mean', 'sum']: raise ValueError(f'Unsupported reduction mode: {reduction}. Supported ones are: {_reduction_modes}') self.loss_weight = loss_weight self.reduction = reduction def forward(self, pred, target, weight=None, **kwargs): """ Args: pred (Tensor): of shape (N, C, H, W). Predicted tensor. target (Tensor): of shape (N, C, H, W). Ground truth tensor. weight (Tensor, optional): of shape (N, C, H, W). Element-wise weights. Default: None. """ return self.loss_weight * l1_loss(pred, target, weight, reduction=self.reduction) @LOSS_REGISTRY.register() class MSELoss(nn.Module): """MSE (L2) loss. Args: loss_weight (float): Loss weight for MSE loss. Default: 1.0. reduction (str): Specifies the reduction to apply to the output. Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean'. """ def __init__(self, loss_weight=1.0, reduction='mean'): super(MSELoss, self).__init__() if reduction not in ['none', 'mean', 'sum']: raise ValueError(f'Unsupported reduction mode: {reduction}. Supported ones are: {_reduction_modes}') self.loss_weight = loss_weight self.reduction = reduction def forward(self, pred, target, weight=None, **kwargs): """ Args: pred (Tensor): of shape (N, C, H, W). Predicted tensor. target (Tensor): of shape (N, C, H, W). Ground truth tensor. weight (Tensor, optional): of shape (N, C, H, W). Element-wise weights. Default: None. """ return self.loss_weight * mse_loss(pred, target, weight, reduction=self.reduction) @LOSS_REGISTRY.register() class CharbonnierLoss(nn.Module): """Charbonnier loss (one variant of Robust L1Loss, a differentiable variant of L1Loss). Described in "Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution". Args: loss_weight (float): Loss weight for L1 loss. Default: 1.0. reduction (str): Specifies the reduction to apply to the output. Supported choices are 'none' | 'mean' | 'sum'. Default: 'mean'. eps (float): A value used to control the curvature near zero. Default: 1e-12. """ def __init__(self, loss_weight=1.0, reduction='mean', eps=1e-12): super(CharbonnierLoss, self).__init__() if reduction not in ['none', 'mean', 'sum']: raise ValueError(f'Unsupported reduction mode: {reduction}. Supported ones are: {_reduction_modes}') self.loss_weight = loss_weight self.reduction = reduction self.eps = eps def forward(self, pred, target, weight=None, **kwargs): """ Args: pred (Tensor): of shape (N, C, H, W). Predicted tensor. target (Tensor): of shape (N, C, H, W). Ground truth tensor. weight (Tensor, optional): of shape (N, C, H, W). Element-wise weights. Default: None. """ return self.loss_weight * charbonnier_loss(pred, target, weight, eps=self.eps, reduction=self.reduction) @LOSS_REGISTRY.register() class WeightedTVLoss(L1Loss): """Weighted TV loss. Args: loss_weight (float): Loss weight. Default: 1.0. """ def __init__(self, loss_weight=1.0, reduction='mean'): if reduction not in ['mean', 'sum']: raise ValueError(f'Unsupported reduction mode: {reduction}. Supported ones are: mean | sum') super(WeightedTVLoss, self).__init__(loss_weight=loss_weight, reduction=reduction) def forward(self, pred, weight=None): if weight is None: y_weight = None x_weight = None else: y_weight = weight[:, :, :-1, :] x_weight = weight[:, :, :, :-1] y_diff = super().forward(pred[:, :, :-1, :], pred[:, :, 1:, :], weight=y_weight) x_diff = super().forward(pred[:, :, :, :-1], pred[:, :, :, 1:], weight=x_weight) loss = x_diff + y_diff return loss @LOSS_REGISTRY.register() class PerceptualLoss(nn.Module): """Perceptual loss with commonly used style loss. Args: layer_weights (dict): The weight for each layer of vgg feature. Here is an example: {'conv5_4': 1.}, which means the conv5_4 feature layer (before relu5_4) will be extracted with weight 1.0 in calculating losses. vgg_type (str): The type of vgg network used as feature extractor. Default: 'vgg19'. use_input_norm (bool): If True, normalize the input image in vgg. Default: True. range_norm (bool): If True, norm images with range [-1, 1] to [0, 1]. Default: False. perceptual_weight (float): If `perceptual_weight > 0`, the perceptual loss will be calculated and the loss will multiplied by the weight. Default: 1.0. style_weight (float): If `style_weight > 0`, the style loss will be calculated and the loss will multiplied by the weight. Default: 0. criterion (str): Criterion used for perceptual loss. Default: 'l1'. """ def __init__(self, layer_weights, vgg_type='vgg19', use_input_norm=True, range_norm=False, perceptual_weight=1.0, style_weight=0., criterion='l1'): super(PerceptualLoss, self).__init__() self.perceptual_weight = perceptual_weight self.style_weight = style_weight self.layer_weights = layer_weights self.vgg = VGGFeatureExtractor( layer_name_list=list(layer_weights.keys()), vgg_type=vgg_type, use_input_norm=use_input_norm, range_norm=range_norm) self.criterion_type = criterion if self.criterion_type == 'l1': self.criterion = torch.nn.L1Loss() elif self.criterion_type == 'l2': self.criterion = torch.nn.MSELoss() elif self.criterion_type == 'fro': self.criterion = None else: raise NotImplementedError(f'{criterion} criterion has not been supported.') def forward(self, x, gt): """Forward function. Args: x (Tensor): Input tensor with shape (n, c, h, w). gt (Tensor): Ground-truth tensor with shape (n, c, h, w). Returns: Tensor: Forward results. """ # extract vgg features x_features = self.vgg(x) gt_features = self.vgg(gt.detach()) # calculate perceptual loss if self.perceptual_weight > 0: percep_loss = 0 for k in x_features.keys(): if self.criterion_type == 'fro': percep_loss += torch.norm(x_features[k] - gt_features[k], p='fro') * self.layer_weights[k] else: percep_loss += self.criterion(x_features[k], gt_features[k]) * self.layer_weights[k] percep_loss *= self.perceptual_weight else: percep_loss = None # calculate style loss if self.style_weight > 0: style_loss = 0 for k in x_features.keys(): if self.criterion_type == 'fro': style_loss += torch.norm( self._gram_mat(x_features[k]) - self._gram_mat(gt_features[k]), p='fro') * self.layer_weights[k] else: style_loss += self.criterion(self._gram_mat(x_features[k]), self._gram_mat( gt_features[k])) * self.layer_weights[k] style_loss *= self.style_weight else: style_loss = None return percep_loss, style_loss def _gram_mat(self, x): """Calculate Gram matrix. Args: x (torch.Tensor): Tensor with shape of (n, c, h, w). Returns: torch.Tensor: Gram matrix. """ n, c, h, w = x.size() features = x.view(n, c, w * h) features_t = features.transpose(1, 2) gram = features.bmm(features_t) / (c * h * w) return gram
13,715
https://github.com/pm-Architect/Aviary/blob/master/Parrot/Controls/pDateTime.cs
Github Open Source
Open Source
MIT
2,018
Aviary
pm-Architect
C#
Code
297
1,007
using System; using System.Windows; using System.Windows.Media; //using MahApps.Metro.Controls; using Xceed.Wpf.Toolkit; using Wind.Containers; namespace Parrot.Controls { public class pDateTime : pControl { public DateTimePicker Element; public pDateTime(string InstanceName) { //Set Element info setup Element = new DateTimePicker(); Element.Name = InstanceName; Type = "PickDateTime"; //Set "Clear" appearance to all elements Element.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); Element.BorderBrush = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); Element.BorderThickness = new Thickness(0); } public void SetDate(DateTime date, int mode, string format) { Element.ShowButtonSpinner = false; Element.AllowSpin = true; Element.AllowTextInput = true; Element.ButtonSpinnerLocation = Location.Left; Element.Value = date; Element.Format = DateTimeFormat.Custom; if (mode > 0) { //Element.FormatString = DateStructures(mode); } else { //Element.FormatString = format; } } private string DateStructures(int type) { switch (type) { case 1: return "dddd, MMMM dd, yyyy ( hh:mm:ss tt )"; case 2: return "mmmm/ dd/ yyyy, hh:mm:ss tt"; case 3: return "yyyy/ mmmm/ yyyy/ dd, HH:mm:ss"; case 4: return "D"; case 5: return "d"; case 6: return "yyyy-MM-dd"; case 7: return "hh:mm tt"; case 8: return "hh: mm: s tt"; case 9: return "HH:mm:ss"; default: return "dddd, MMMM dd, yyyy ( hh:mm:ss tt )"; } } public override void SetFill() { Element.Background = Graphics.WpfFill; } public override void SetStroke() { Element.BorderThickness = new Thickness(Graphics.StrokeWeight[0], Graphics.StrokeWeight[1], Graphics.StrokeWeight[2], Graphics.StrokeWeight[3]); Element.BorderBrush = new SolidColorBrush(Graphics.StrokeColor.ToMediaColor()); } public override void SetSize() { if (Graphics.Width < 1) { Element.Width = double.NaN; } else { Element.Width = Graphics.Width; } if (Graphics.Height < 1) { Element.Height = double.NaN; } else { Element.Height = Graphics.Height; } } public override void SetMargin() { Element.Margin = new Thickness(Graphics.Margin[0], Graphics.Margin[1], Graphics.Margin[2], Graphics.Margin[3]); } public override void SetPadding() { Element.Padding = new Thickness(Graphics.Padding[0], Graphics.Padding[1], Graphics.Padding[2], Graphics.Padding[3]); } public override void SetFont() { Element.Foreground = new SolidColorBrush(Graphics.FontObject.FontColor.ToMediaColor()); Element.FontFamily = Graphics.FontObject.ToMediaFont().Family; Element.FontSize = Graphics.FontObject.Size; Element.FontStyle = Graphics.FontObject.ToMediaFont().Italic; Element.FontWeight = Graphics.FontObject.ToMediaFont().Bold; } } }
6,315
https://github.com/savannah521/extract/blob/master/src/main/java/org/icij/extract/redis/ConnectionManagerFactory.java
Github Open Source
Open Source
LicenseRef-scancode-unknown-license-reference, MIT
2,017
extract
savannah521
Java
Code
285
697
package org.icij.extract.redis; import org.icij.task.Options; import org.icij.task.annotation.Option; import org.redisson.config.Config; import org.redisson.connection.ConnectionManager; import org.redisson.connection.SingleConnectionManager; /** * Factory for creating a Redis client. * * @author Matthew Caruana Galizia <mcaruana@icij.org> * @since 1.0.0-beta */ @Option(name = "redisAddress", description = "Set the Redis backend address. Defaults to 127.0.0.1:6379.", parameter = "address") @Option(name = "redisTimeout", description = "The client timeout for Redis operations.", parameter = "timeout") public class ConnectionManagerFactory { private String address = null; private int timeout = -1; /** * Create a new connection manager by query the given set of options. * * @param options options containing connection parameters * @return a new connection manager */ public ConnectionManagerFactory withOptions(final Options<String> options) { withAddress(options.get("redisAddress").value().orElse(null)); options.get("redisTimeout").parse().asInteger().ifPresent(this::withTimeout); return this; } /** * Set the Redis server address. Uses {@literal 127.0.0.1:6379} by default. * * @param address the Redis server address * @return chainable factory */ private ConnectionManagerFactory withAddress(final String address) { this.address = address; return this; } /** * Set the connection timeout. Uses a 60-second timeout by default. * * @param timeout the timeout in milliseconds * @return chainable factory */ private ConnectionManagerFactory withTimeout(final int timeout) { this.timeout = timeout; return this; } /** * Create a new connection manager for a single server using the supplied address. * * @return a new connection manager */ public ConnectionManager create() { final String address = null == this.address ? "127.0.0.1:6379" : this.address; final int timeout = this.timeout < 0 ? 60 * 1000 : this.timeout; // TODO: support all the other types supported by the ConnectionManagerFactory. // TODO: Create a hash of config options so that only one manager is used per unique server. This should // improve contention. return new SingleConnectionManager(new Config() .useSingleServer() .setAddress(address) .setTimeout(timeout), new Config()); } }
30,696
https://github.com/Jingyan95/cmssw/blob/master/L1Trigger/TrackFindingTracklet/python/ProducerKF_cff.py
Github Open Source
Open Source
Apache-2.0
2,022
cmssw
Jingyan95
Python
Code
62
384
import FWCore.ParameterSet.Config as cms from L1Trigger.TrackTrigger.ProducerSetup_cff import TrackTriggerSetup from L1Trigger.TrackerTFP.Producer_cfi import TrackerTFPProducer_params from L1Trigger.TrackerTFP.ProducerES_cff import TrackTriggerDataFormats from L1Trigger.TrackerTFP.ProducerLayerEncoding_cff import TrackTriggerLayerEncoding from L1Trigger.TrackerTFP.KalmanFilterFormats_cff import TrackTriggerKalmanFilterFormats from L1Trigger.TrackFindingTracklet.ChannelAssignment_cff import ChannelAssignment from L1Trigger.TrackFindingTracklet.ProducerKF_cfi import TrackFindingTrackletProducerKF_params TrackFindingTrackletProducerKFin = cms.EDProducer( 'trklet::ProducerKFin', TrackFindingTrackletProducerKF_params ) TrackFindingTrackletProducerKF = cms.EDProducer( 'trackerTFP::ProducerKF', TrackFindingTrackletProducerKF_params ) TrackFindingTrackletProducerTT = cms.EDProducer( 'trklet::ProducerTT', TrackFindingTrackletProducerKF_params ) TrackFindingTrackletProducerAS = cms.EDProducer( 'trklet::ProducerAS', TrackFindingTrackletProducerKF_params ) TrackFindingTrackletProducerKFout = cms.EDProducer( 'trklet::ProducerKFout', TrackFindingTrackletProducerKF_params )
49,001
https://github.com/clickclack2015/multibit-hd/blob/master/mbhd-swing/src/main/java/org/multibit/hd/ui/export/TransactionConverter.java
Github Open Source
Open Source
MIT
2,021
multibit-hd
clickclack2015
Java
Code
256
929
package org.multibit.hd.ui.export; import com.googlecode.jcsv.writer.CSVEntryConverter; import org.multibit.hd.core.config.Configurations; import org.multibit.hd.core.dto.TransactionData; import java.text.DateFormat; import java.text.SimpleDateFormat; /** * Convert WalletTableData into single fields for use in a CSV file. */ public class TransactionConverter implements CSVEntryConverter<TransactionData> { DateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy HH:mm", Configurations.currentConfiguration.getLocale()); @Override public String[] convertEntry(TransactionData transactionData) { String[] columns = new String[14]; // Date columns[0] = transactionData.getDate() == null ? "" : dateFormatter.format(transactionData.getDate().toDate()); // Status columns[1] = transactionData.getStatus() == null ? "" : transactionData.getStatus().getStatus().toString(); // Type columns[2] = transactionData.getType() == null ? "" : transactionData.getType().toString(); // Description columns[3] = transactionData.getDescription() == null ? "" : transactionData.getDescription(); // Note columns[4] = transactionData.getNote() == null ? "" : transactionData.getNote(); // Amount in LTC columns[5] = transactionData.getAmountCoin() == null ? "" : transactionData.getAmountCoin().toString(); // Fiat currency columns[6] = ""; // Fiat amount columns[7] = ""; if (transactionData.getAmountFiat() != null) { if (transactionData.getAmountFiat().getCurrency().isPresent()) { columns[6] = transactionData.getAmountFiat().getCurrency().get().getCurrencyCode(); } if (transactionData.getAmountFiat().getAmount() != null && transactionData.getAmountFiat().getAmount().isPresent()){ // Ensure we use plain string to avoid "E-05" columns[7] = transactionData.getAmountFiat().getAmount().get().stripTrailingZeros().toPlainString(); } } // Exchange rate columns[8] = ""; if (transactionData.getAmountFiat() != null && transactionData.getAmountFiat().getRate() != null && transactionData.getAmountFiat().getRate().isPresent()) { columns[8] = transactionData.getAmountFiat().getRate().get(); } // Exchange rate provider columns[9] = ""; if (transactionData.getAmountFiat() != null && transactionData.getAmountFiat().getExchangeName() != null && transactionData.getAmountFiat().getExchangeName().isPresent()) { columns[9] = transactionData.getAmountFiat().getExchangeName().get(); } // Miner's fee columns[10] = ""; if (transactionData.getMiningFee() != null && transactionData.getMiningFee().isPresent()) { columns[10] = transactionData.getMiningFee().get().toString(); } // Client fee columns[11] = ""; if (transactionData.getClientFee() != null && transactionData.getClientFee().isPresent()) { columns[11] = transactionData.getClientFee().get().toString(); } // Coinbase columns[12] = Boolean.toString(transactionData.isCoinBase()); // Transaction hash columns[13] = transactionData.getTransactionId(); return columns; } }
18,410
https://github.com/openshift/origin/blob/master/vendor/github.com/openshift/apiserver-library-go/pkg/admission/imagepolicy/rules/accept.go
Github Open Source
Open Source
Apache-2.0
2,023
origin
openshift
Go
Code
383
1,141
package rules import ( "k8s.io/klog/v2" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" imagepolicy "github.com/openshift/apiserver-library-go/pkg/admission/imagepolicy/apis/imagepolicy/v1" ) type Accepter interface { Covers(metav1.GroupResource) bool Accepts(*ImagePolicyAttributes) bool } // mappedAccepter implements the Accepter interface for a map of group resources and accepters type mappedAccepter map[metav1.GroupResource]Accepter func (a mappedAccepter) Covers(gr metav1.GroupResource) bool { _, ok := a[gr] return ok } // Accepts returns true if no Accepter is registered for the group resource in attributes, // or if the registered Accepter also returns true. func (a mappedAccepter) Accepts(attr *ImagePolicyAttributes) bool { accepter, ok := a[attr.Resource] if !ok { return true } return accepter.Accepts(attr) } type executionAccepter struct { rules []imagepolicy.ImageExecutionPolicyRule covers metav1.GroupResource defaultReject bool integratedRegistryMatcher RegistryMatcher } // NewExecutionRuleseAccepter creates an Accepter from the provided rules. func NewExecutionRulesAccepter(rules []imagepolicy.ImageExecutionPolicyRule, integratedRegistryMatcher RegistryMatcher) (Accepter, error) { mapped := make(mappedAccepter) for _, rule := range rules { over, selectors, err := imageConditionInfo(&rule.ImageCondition) if err != nil { return nil, err } rule.ImageCondition.MatchImageLabelSelectors = selectors for gr := range over { a, ok := mapped[gr] if !ok { a = &executionAccepter{ covers: gr, integratedRegistryMatcher: integratedRegistryMatcher, } mapped[gr] = a } byResource := a.(*executionAccepter) byResource.rules = append(byResource.rules, rule) } } for _, a := range mapped { byResource := a.(*executionAccepter) if len(byResource.rules) > 0 { // if all rules are reject, the default behavior is allow allReject := true for _, rule := range byResource.rules { if !rule.Reject { allReject = false break } } byResource.defaultReject = !allReject } } return mapped, nil } func (r *executionAccepter) Covers(gr metav1.GroupResource) bool { return r.covers == gr } func (r *executionAccepter) Accepts(attrs *ImagePolicyAttributes) bool { if attrs.Resource != r.covers { return true } anyMatched := false for _, rule := range r.rules { klog.V(5).Infof("image policy checking rule %q", rule.Name) if attrs.ExcludedRules.Has(rule.Name) && !rule.IgnoreNamespaceOverride { klog.V(5).Infof("skipping because rule is excluded by namespace annotations\n") continue } // if we don't have a resolved image and we're supposed to skip the rule if that happens, // continue here. Otherwise, the reject option is impossible to reason about. if attrs.Image == nil && rule.SkipOnResolutionFailure { klog.V(5).Infof("skipping because image is not resolved and skip on failure is true\n") continue } matches := matchImageCondition(&rule.ImageCondition, r.integratedRegistryMatcher, attrs) klog.V(5).Infof("Rule %q(reject=%t) applies to image %v: %t", rule.Name, rule.Reject, attrs.Name, matches) if matches { if rule.Reject { return false } anyMatched = true } } return anyMatched || !r.defaultReject }
36,367
https://github.com/thompsonplyler/Top-Down-RPG/blob/master/node_modules/phaser/src/gameobjects/particles/typedefs/RandomZoneSourceCallback.js
Github Open Source
Open Source
MIT
2,021
Top-Down-RPG
thompsonplyler
JavaScript
Code
18
55
/** * @callback Phaser.Types.GameObjects.Particles.RandomZoneSourceCallback * @since 3.0.0 * * @param {Phaser.Math.Vector2} point - A point to modify. */
50,848
https://github.com/dsbrown1331/bcprefs/blob/master/plotting_scripts/degradation/demo_analysis_lengths.py
Github Open Source
Open Source
MIT
null
bcprefs
dsbrown1331
Python
Code
31
127
import pickle demo_files = ['demonstrations/cartpole20.p','demonstrations/cartpole5.p', 'demonstrations/cartpole2.p'] for dfile in demo_files: demos = pickle.load( open( dfile, "rb" ) ) print("loaded demos", dfile, len(demos)) dlengths = [] for s,a in demos: dlengths.append(len(s)) print(dlengths)
19,398
https://github.com/ksquareincmx/zanma-ui/blob/master/src/styles/typography.tsx
Github Open Source
Open Source
MIT
2,019
zanma-ui
ksquareincmx
TypeScript
Code
23
55
export enum FontWeight { LIGHT = 300, REGULAR = 400, MEDIUM = 500, SEMI_BOLD = 600, BOLD = 700, BOLDER = 800, }
24,993
https://github.com/midnightmonster/recess/blob/master/.gitignore
Github Open Source
Open Source
MIT
2,009
recess
midnightmonster
Ignore List
Code
10
43
*.cache *.settings .project .buildpath *.db data/temp/compiled/* data/temp/*.* .svn /apps/ /plugins/
39,868
https://github.com/action-is-hope/starter-kits/blob/master/gatsby/setup-test-env.ts
Github Open Source
Open Source
MIT
null
starter-kits
action-is-hope
TypeScript
Code
23
76
// Had type issues and rather than include these in the test files I opted for // this: https://github.com/testing-library/jest-dom/issues/123#issuecomment-545410178 import "@testing-library/jest-dom"; import "@testing-library/jest-dom/extend-expect";
4,151
https://github.com/unball/ieee-very-small/blob/master/software/include/unball/strategy/initial_goalkeeper.hpp
Github Open Source
Open Source
MIT
2,021
ieee-very-small
unball
C++
Code
55
202
/** * @file initial_goalkeeper.hpp * @author Icaro da Costa Mota * @date 22/10/2015 * * @attention Copyright (C) 2015 UnBall Robot Soccer Team * * @brief */ #ifndef UNBALL_INITIAL_GOALKEEPER_H_ #define UNBALL_INITIAL_GOALKEEPER_H_ #include <unball/strategy/player.hpp> #include <unball/strategy/goals.hpp> class InitialGoalkeeper : public Player { public: InitialGoalkeeper(); void buildPotentialFields(int robot_number); private: static float const OFFSET; }; #endif // UNBALL_INITIAL_GOALKEEPER_H_
3,594
https://github.com/nyanzebra/TinyOS/blob/master/os/tst/CMakeLists.txt
Github Open Source
Open Source
2,017
TinyOS
nyanzebra
CMake
Code
291
1,282
cmake_minimum_required(VERSION 3.9) enable_testing() # Cmake module path (if exists) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/../cmake) # We probably don't want this to run on every build. option(COVERALLS "Generate coveralls data" OFF) if (COVERALLS) include(Coveralls) endif() set(UNIX_COMPILER "g++") set(OSX_COMPILER "clang++") set(MSVC_COMPILER "msvc") set(CXX_WARNING_LEVEL "-Wall") # add modules later... set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O0 -std=c++1z -ftest-coverage -fprofile-arcs ${CXX_WARNING_LEVEL}" CACHE STRING "CXX flags" FORCE) set(CMAKE_CXX_STANDARD "17" CACHE STRING "Default standard CXX") set(CMAKE_CXX_EXTENSIONS OFF CACHE BOOL "Default disallow extensions") set(CMAKE_CXX_COMPILE_FEATURES "${CMAKE_CXX_COMPILE_FEATURES} CXX_STD_17" CACHE STRING "Default CXX compile features") set(CMAKE_CXX_STANDARD_REQUIRED OFF CACHE BOOL "Default standard not required") if(APPLE) message("setting compiler to clang") set(CMAKE_CXX_COMPILER "${OSX_COMPILER}" CACHE STRING "Default CXX compiler") elseif(UNIX) message("setting compiler to g++") set(CMAKE_CXX_COMPILER "${UNIX_COMPILER}" CACHE STRING "Default CXX compiler") elseif(MSVC or WIN32) message("setting compiler to msvc") set(CMAKE_CXX_COMPILER "${MSVC_COMPILER}" CACHE STRING "Default CXX compiler") endif() file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-src) file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-build) # Download and unpack googletest at configure time configure_file(CMakeLists.txt.in ${CMAKE_BINARY_DIR}/googletest-download/CMakeLists.txt) execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . RESULT_VARIABLE result WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download ) if(result) message(FATAL_ERROR "CMake step for googletest failed: ${result}") endif() execute_process(COMMAND ${CMAKE_COMMAND} --build . RESULT_VARIABLE result WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download ) if(result) message(FATAL_ERROR "Build step for googletest failed: ${result}") endif() # Prevent overriding the parent project's compiler/linker # settings on Windows set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) # Add googletest directly to our build. This defines # the gtest and gtest_main targets. add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src ${CMAKE_BINARY_DIR}/googletest-build EXCLUDE_FROM_ALL) # The gtest/gtest_main targets carry header search path # dependencies automatically when using CMake 2.8.11 or # later. Otherwise we have to add them here ourselves. if (CMAKE_VERSION VERSION_LESS 2.8.11) include_directories("${gtest_SOURCE_DIR}/include") endif() set(CMAKE_SOURCE_DIR "${CMAKE_SOURCE_DIR}/../") get_filename_component(ABSOLUTE_PATH "${CMAKE_SOURCE_DIR}" ABSOLUTE) message("${ABSOLUTE_PATH}") file(GLOB SRCS ${ABSOLUTE_PATH}/tst/*.cpp) file(GLOB KERNEL_HEADERS ${ABSOLUTE_PATH}/kern/*.hpp) include_directories("${ABSOLUTE_PATH}/kern/") set(SRCS ${SRCS} ${KERNEL_HEADERS}) message("Sources: ${SRCS}") add_executable(testos ${SRCS}) target_link_libraries(testos gtest_main) if (COVERALLS) # Create the coveralls target. coveralls_setup( "${SRCS}" # The source files. ON # If we should upload. ) endif() add_test(testos ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/testos)
31,129
https://github.com/nyorain/tokonoma/blob/master/include/tkn/callable.hpp
Github Open Source
Open Source
MIT
2,021
tokonoma
nyorain
C++
Code
582
1,789
#pragma once #include <utility> #include <functional> #include <memory> #include <nytl/functionTraits.hpp> #include <dlg/dlg.hpp> namespace tkn { template<typename Sig> class Callable; template<typename Sig, typename F> class CallableImpl; template<typename Ret, typename... Args> class Callable<Ret(Args...)> { public: using Destructor = void(*)(Callable&); using CallImpl = Ret(*)(Callable&, Args...); // Usually not created directly, use CallableImpl inline Callable(Destructor destructor, CallImpl callImpl) : destructor_(destructor), callImpl_(callImpl) { dlg_assert(callImpl_); } inline ~Callable() { // when destructor_ is unset, the derived class either needs no destructor // or was already called if(destructor_) { (*destructor_)(*this); } } inline Ret operator()(Args... args) { return (*callImpl_)(*this, std::forward<Args>(args)...); } protected: // in-object vtable Destructor destructor_; const CallImpl callImpl_; }; template<typename Ret, typename... Args> class Callable<Ret(Args...) const> { public: using Destructor = void(*)(Callable&); using CallImpl = Ret(*)(const Callable&, Args...); // Usually not created directly, use CallableImpl inline Callable(Destructor destructor, CallImpl callImpl) : destructor_(destructor), callImpl_(callImpl) { dlg_assert(callImpl_); } inline ~Callable() { // when destructor_ is unset, the derived class either needs no destructor // or was already called if(destructor_) { (*destructor_)(*this); } } inline Ret operator()(Args... args) const { return (*callImpl_)(*this, std::forward<Args>(args)...); } protected: // in-object vtable Destructor destructor_; const CallImpl callImpl_; }; template<typename F, typename Ret, typename... Args> class CallableImpl<Ret(Args...), F> : public Callable<Ret(Args...)> { public: using Base = Callable<Ret(Args...)>; static constexpr auto needsDestructor = !std::is_trivially_destructible_v<F>; F obj; inline CallableImpl(F xobj) : Base(needsDestructor ? &destructorImpl : nullptr, &callImpl), obj(std::move(xobj)) { } inline ~CallableImpl() { // NOTE: when needsDestructor is false, this isn't needed, as destructor_ // will already be nullptr. But compilers can't seem to optimize for it, // so always setting this to null here makes sure they can properly optimize // out the if-branch in our base classes destructor this->destructor_ = nullptr; } private: static Ret callImpl(Base& callable, Args... args) { // This will usually not generate any runtime code. auto& self = static_cast<CallableImpl&>(callable); // At least for lambdas (that are only used here), this is likely // to be inlined. return std::invoke(self.obj, std::forward<Args>(args)...); } static void destructorImpl(Base& callable) { auto& self = static_cast<CallableImpl&>(callable); self.~CallableImpl(); } }; template<typename F, typename Ret, typename... Args> class CallableImpl<Ret(Args...) const, F> : public Callable<Ret(Args...) const> { public: using Base = Callable<Ret(Args...) const>; static constexpr auto needsDestructor = !std::is_trivially_destructible_v<F>; F obj; inline CallableImpl(F xobj) : Base(needsDestructor ? &destructorImpl : nullptr, &callImpl), obj(std::move(xobj)) { } inline ~CallableImpl() { this->destructor_ = nullptr; } private: static Ret callImpl(const Base& callable, Args... args) { // This will usually not generate any runtime code. auto& self = static_cast<const CallableImpl&>(callable); // At least for lambdas (that are only used here), this is likely // to be inlined. return std::invoke(self.obj, std::forward<Args>(args)...); } static void destructorImpl(Base& callable) { auto& self = static_cast<CallableImpl&>(callable); self.~CallableImpl(); } }; template<typename F> CallableImpl(F) -> CallableImpl<typename nytl::FunctionTraits<F>::Signature, F>; // UniqueCallable: allocating wrapper around CallableImpl. // Calling a UniqueCallable object should (given that the compiler optimizes // everything as far as possible) just have the overhead of one additional // load and a function pointer call. template<typename Sig> class UniqueCallable; template<typename Ret, typename... Args> class UniqueCallable<Ret(Args...)> : public std::unique_ptr<Callable<Ret(Args...)>> { public: using Sig = Ret(Args...); UniqueCallable() = default; template<typename F> UniqueCallable(F f) { auto& ptr = static_cast<std::unique_ptr<Callable<Ret(Args...)>>&>(*this); ptr = std::make_unique<CallableImpl<Sig, F>>(std::move(f)); } inline Ret operator()(Args... args) { return (*this)(std::forward<Args>(args)...); } }; template<typename Ret, typename... Args> class UniqueCallable<Ret(Args...) const> : public std::unique_ptr<Callable<Ret(Args...) const>> { public: using Sig = Ret(Args...) const; UniqueCallable() = default; template<typename F> UniqueCallable(F f) { auto& ptr = static_cast<std::unique_ptr<Callable<Ret(Args...) const>>&>(*this); ptr = std::make_unique<CallableImpl<Sig, F>>(std::move(f)); } inline Ret operator()(Args... args) const { const Callable<Sig>& impl = *(*this); return impl(std::forward<Args>(args)...); } }; } // namespace tkn
29,749
https://github.com/pandaengine/qingmvc/blob/master/src/cache/file/FileCache.php
Github Open Source
Open Source
Apache-2.0
2,018
qingmvc
pandaengine
PHP
Code
321
1,805
<?php namespace qing\cache\file; use qing\cache\Cache; use qing\filesystem\MK; /** * File 缓存驱动 * host为缓存目录|一个键值对应一个缓存文件 * * @author xiaowang <736523132@qq.com> * @copyright Copyright (c) 2013 http://qingmvc.com * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 */ class FileCache extends Cache{ /** * 缓存文件目录 * * @name cacheDir * @var string */ public $host=''; /** * 写入时的锁类型 * LOCK_EX 独占锁 * * @var number */ public $lockMode=LOCK_EX; /** * 编码要保存的数据|把过期时间等数据信息也缓存 * * @param string $value 数据值 * @param string $expire 过期时间/秒 * @return return string */ protected function encodeValue($value,$expire){ //数据信息|过期时间等等|总是以数组存储 $encodeValue=array(); $encodeValue['expire'] =(int)$expire; $encodeValue['addtime']=time(); $encodeValue['value'] =$value; $content=var_export($encodeValue,true); $content="<?php\n return ".$content.";\n?>"; return $content; } /** * 解码数据 * filemtime|文件修改时间 * * @param string $encodeValue 已编码的数据 * @param string $filename 缓存文件 * @return return string */ protected function decodeValue($encodeValue,$filename){ if(!is_array($encodeValue)){ return false; } $expire =(int)$encodeValue['expire']; $value =$encodeValue['value']; if($expire===0){ //不限制有效时间|直接返回 return $value; } $addtime=(int)$encodeValue['addtime']; //$addtime=filemtime($filename); if(time()>($addtime+$expire)){ //缓存已经过期|返回false //当前时间>文件修改时间/上一次缓存时间+有效时间 return false; } return $value; } /** * 取得缓存文件名 */ protected function getCacheFile($key){ return $this->host.DS.$this->prefix.$key.PHP_EXT; } /** * 链接初始化|连接操作 * 创建缓存文件目录 */ protected function connect(){ //缓存文件目录 if(!$this->host){ //#默认目录 $this->host=APP_RUNTIME.DS.'~cache.file'; } MK::dir($this->host); $this->host=realpath($this->host); return null; } /** * @param $key=filename 要取出的文件名 * @see \qing\cache\Cache::get() */ public function get($key){ $filename=$this->getCacheFile($key); if(!is_file($filename)){ //值不存在返回false return false; } $value=include $filename; return $this->decodeValue($value,$filename); } /** * 写入缓存|一个文件对应一个键值数据 * * @param $key 要存入的文件名 * @param $value 要存入的数据|string|int|array * @param $expire 过期时间|有效期秒|60s|60s之后过期 */ public function set($key,$value,$expire=0){ $filename=$this->getCacheFile($key); //编码数据 $value=$this->encodeValue($value,$expire); try{ //#先创建子目录 MK::dir(dirname($filename)); /* //w只写。打开并清空文件的内容;如果文件不存在,则创建新文件。 $fp=fopen($filename,"w"); //fwrite是原子性的?一次写入则可以保证数据一致性? fwrite($fp,$value); fclose($fp); */ //LOCK_EX在写入时获得一个独占锁。|其他线程不可读也不可写|避免读到脏数据 file_put_contents($filename,$value,$this->lockMode); }catch (\Exception $e){ throw $e; } return true; } /** * 删除对应文件 * @param $key 键值 */ public function delete($key){ $filename=$this->getCacheFile($key); if(is_file($filename)){ return unlink($filename); }else{ return false; } } /** * 清除所有文件 * * @see \qing\cache\Cache ::clear() */ public function clear(){ //链接初始化 $cacheDir=$this->host; foreach (scandir($cacheDir) as $k=>$v){ $fileName=$cacheDir.DS.$v; if(!is_file($fileName)){//包括 . .. continue; } if(!unlink($fileName)){ return false; } } return true; } /** * 获取所有数据 * * @see \qing\cache\Cache::getAll() */ public function getAll(){ $cacheDir=$this->cacheDir; $data=array(); foreach (scandir($cacheDir) as $file){ if(in_array($file,['.','..'])){//包括 . .. continue; } $key=substr($file,0,-4); $data[$key]=$this->get($key); } return $data; } } ?>
25,583
https://github.com/kleberfsobrinho/web-moderno/blob/master/16-react/exercicios/src/index.js
Github Open Source
Open Source
MIT
null
web-moderno
kleberfsobrinho
JavaScript
Code
63
233
import React from 'react'; import ReactDOM from 'react-dom' // const elemento = <h1>React</h1> // import Primeiro from './componentes/Primeiro' // import BomDia from './componentes/BomDia' // import Multi, { BoaNoite } from './componentes/Multiplos' // import Saudacao from './componentes/Saudacao' import Pai from './componentes/Pai' import Filho from './componentes/Filho' ReactDOM.render( <div> <Pai nome="João" sobrenome="Silva"> <Filho nome="Pedro"/> {/* <Filho nome="Paulo" sobrenome="Silva"/> <Filho nome="Carla" sobrenome="Silva"/> */} </Pai> </div> , document.getElementById('root'))
41,280
https://github.com/devhyun637/prolog/blob/master/backend/src/documentation/adoc/filter.adoc
Github Open Source
Open Source
MIT
2,022
prolog
devhyun637
AsciiDoc
Code
13
71
[[filter]] == 필터 === 필터 목록 조회 ==== Request include::{snippets}/filter/list/http-request.adoc[] ==== Response include::{snippets}/filter/list/http-response.adoc[]
47,868
https://github.com/baumhaus-project/cgal/blob/master/Nef_3/archive/triangulation/include/CGAL/polygon_triangulation_is_valid_2.h
Github Open Source
Open Source
CC0-1.0
2,021
cgal
baumhaus-project
C
Code
325
1,050
#ifndef POLYGON_TRIANGULATION_IS_VALID_2_H #define POLYGON_TRIANGULATION_IS_VALID_2_H #include <map> #include <list> #undef _DEBUG #define _DEBUG 17 #include <CGAL/Nef_2/debug.h> namespace CGAL { template <class Traits> struct Less_xy_segment_2 { template <class Segment_2> bool operator()( const Segment_2& s, const Segment_2& r) { typedef typename Traits::Compare_xy_2 Compare_xy_2; Compare_xy_2 compare_xy_2; return ((compare_xy_2( s.source(), r.source()) == EQUAL) ? (compare_xy_2( s.target(), r.target()) == SMALLER) : (compare_xy_2( s.source(), r.source()) == SMALLER)); } }; template <class Traits> class Segment_lexicographically_xy_ordered_2 { typedef typename Traits::Point_2 Point_2; typedef typename Traits::Compare_xy_2 Compare_xy_2; public: //Segment_lexicographically_xy_ordered_2() : p(), q() {} Segment_lexicographically_xy_ordered_2( const Point_2& pi, const Point_2& qi) { Compare_xy_2 compare_xy_2; if( compare_xy_2( pi, qi) == SMALLER) { p = pi; q = qi; } else { p = qi; q = pi; } } Point_2 source() const { return p; } Point_2 target() const { return q; } private: Point_2 p, q; }; template <class BoundaryIterator, class TriangleIterator, class Traits> bool is_polygon_triangulation_valid_2( BoundaryIterator boundary_begin, BoundaryIterator boundary_end, TriangleIterator triangle_begin, TriangleIterator triangle_end, const Traits& traits) { typedef typename BoundaryIterator::value_type Circulator; typedef Segment_lexicographically_xy_ordered_2<Traits> Segment_2; typedef std::map< Segment_2, int, Less_xy_segment_2<Traits> > Counter; typedef typename Counter::iterator Counter_iterator; Counter counter; // count the number of faces incident to every edge for( TriangleIterator ti = triangle_begin; ti != triangle_end; ++ti) { counter[Segment_2( ti->vertex(0), ti->vertex(1))]++; counter[Segment_2( ti->vertex(1), ti->vertex(2))]++; counter[Segment_2( ti->vertex(2), ti->vertex(0))]++; } // check that boundary edges have only one incident face // and increment their incident faces counter by one BoundaryIterator bi = boundary_begin; Circulator c(*bi), cprev(c), cend(c); cprev--; CGAL_For_all( c, cend) { // outer boundary Segment_2 s( *cprev, *c); if( counter[s] != 1) return false; counter[s]++; cprev = c; } for( ++bi; bi != boundary_end; ++bi) { Circulator c(*bi), cprev(c), cend(c); cprev--; CGAL_For_all( c, cend) { // inner boundary Segment_2 s( *c, *cprev); if( counter[s] != 1) return false; counter[s]++; cprev = c; } } // verify that every edge has then two incident faces for( Counter_iterator ci = counter.begin(); ci != counter.end(); ++ci) { if( ci->second != 2) return false; } return true; } } #endif // POLYGON_TRIANGULATION_IS_VALID_2_H
47,907
https://github.com/ilyabukalov/keeper-contracts/blob/master/scripts/maven.sh
Github Open Source
Open Source
Apache-2.0
null
keeper-contracts
ilyabukalov
Shell
Code
44
142
#!/bin/bash ## Generating web3j stubs shopt -s nullglob # Avoid literal evaluation if not files mkdir ./tmp/ for file in artifacts/*.development.json do tmpFile=$(basename $file) tmpFile=${tmpFile//.development/} cp $file ./tmp/${tmpFile} web3j truffle generate --javaTypes ./tmp/${tmpFile} -o src/main/java -p com.oceanprotocol.keeper.contracts done rm -rf ./tmp/ mvn clean install
34,466
https://github.com/Z-dip/Hyperskill--Java-SQL-JS-HTML-CSS--Problems/blob/master/Java/Collections/Set Removing elements/main.java
Github Open Source
Open Source
MIT
2,020
Hyperskill--Java-SQL-JS-HTML-CSS--Problems
Z-dip
Java
Code
93
257
import java.util.*; class SetUtils { public static Set<Integer> getSetFromString(String str) { // write your code here Set<Integer> set = new TreeSet<>(); String[] strArray = str.split(" "); for (int i = 0; i < strArray.length; i++) { set.add(Integer.valueOf(strArray[i])); } return set; } public static void removeAllNumbersGreaterThan10(Set<Integer> set) { set.removeIf(integer -> integer > 10); } } /* Do not change code below */ public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String numbers = scanner.nextLine(); Set<Integer> set = SetUtils.getSetFromString(numbers); SetUtils.removeAllNumbersGreaterThan10(set); set.forEach(e -> System.out.print(e + " ")); } }
30,525
https://github.com/Sitcode-Zoograf/storyboard/blob/master/storyboard/api/v1/projects.py
Github Open Source
Open Source
Apache-2.0
null
storyboard
Sitcode-Zoograf
Python
Code
721
2,339
# Copyright (c) 2013 Mirantis 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. from oslo_config import cfg from pecan.decorators import expose from pecan import response from pecan import rest from pecan.secure import secure from six.moves.urllib.parse import unquote from wsme import types as wtypes import wsmeext.pecan as wsme_pecan from storyboard._i18n import _ from storyboard.api.auth import authorization_checks as checks from storyboard.api.v1.search import search_engine from storyboard.api.v1 import validations from storyboard.api.v1 import wmodels from storyboard.common import decorators from storyboard.common import exception as exc from storyboard.db.api import projects as projects_api CONF = cfg.CONF SEARCH_ENGINE = search_engine.get_engine() class ProjectsController(rest.RestController): """REST controller for Projects. At this moment it provides read-only operations. """ _custom_actions = {"search": ["GET"]} validation_post_schema = validations.PROJECTS_POST_SCHEMA validation_put_schema = validations.PROJECTS_PUT_SCHEMA @decorators.db_exceptions @secure(checks.guest) @wsme_pecan.wsexpose(wmodels.Project, int) def get_one_by_id(self, project_id): """Retrieve information about the given project. :param project_id: Project ID. """ project = projects_api.project_get(project_id) if project: return wmodels.Project.from_db_model(project) else: raise exc.NotFound(_("Project %s not found") % project_id) @decorators.db_exceptions @secure(checks.guest) @wsme_pecan.wsexpose(wmodels.Project, wtypes.text) def get_one_by_name(self, project_name): """Retrieve information about the given project. :param name: Project name. """ project = projects_api.project_get_by_name(project_name) if project: return wmodels.Project.from_db_model(project) else: raise exc.NotFound(_("Project %s not found") % project_name) @decorators.db_exceptions @secure(checks.guest) @wsme_pecan.wsexpose([wmodels.Project], int, int, int, wtypes.text, wtypes.text, int, int, wtypes.text, wtypes.text) def get(self, marker=None, offset=None, limit=None, name=None, description=None, project_group_id=None, subscriber_id=None, sort_field='id', sort_dir='asc'): """Retrieve a list of projects. Example:: curl https://my.example.org/api/v1/projects :param marker: The resource id where the page should begin. :param offset: The offset to start the page at. :param limit: The number of projects to retrieve. :param name: A string to filter the name by. :param description: A string to filter the description by. :param project_group_id: The ID of a project group to which the projects must belong. :param subscriber_id: The ID of a subscriber to filter results by. :param sort_field: The name of the field to sort on. :param sort_dir: Sort direction for results (asc, desc). """ # Boundary check on limit. if limit is not None: limit = max(0, limit) # Resolve the marker record. marker_project = None if marker is not None: marker_project = projects_api.project_get(marker) projects = \ projects_api.project_get_all(marker=marker_project, offset=offset, limit=limit, name=name, description=description, project_group_id=project_group_id, subscriber_id=subscriber_id, sort_field=sort_field, sort_dir=sort_dir) project_count = \ projects_api.project_get_count(name=name, description=description, project_group_id=project_group_id, subscriber_id=subscriber_id) # Apply the query response headers. if limit: response.headers['X-Limit'] = str(limit) response.headers['X-Total'] = str(project_count) if marker_project: response.headers['X-Marker'] = str(marker_project.id) if offset is not None: response.headers['X-Offset'] = str(offset) return [wmodels.Project.from_db_model(p) for p in projects] @decorators.db_exceptions @secure(checks.superuser) @wsme_pecan.wsexpose(wmodels.Project, body=wmodels.Project) def post(self, project): """Create a new project. .. note:: This command is only available to Admin users. Example:: curl https://my.example.org/api/v1/projects \\ -H 'Authorization: Bearer MY_ACCESS_TOKEN' \\ -H 'Content-Type: application/json;charset=UTF-8' \\ --data-binary '{"name":"test-project",\\ "description":"A test project"}' :param project: A project within the request body. """ result = projects_api.project_create(project.as_dict()) return wmodels.Project.from_db_model(result) @decorators.db_exceptions @secure(checks.superuser) @wsme_pecan.wsexpose(wmodels.Project, int, body=wmodels.Project) def put(self, project_id, project): """Modify this project. .. note:: This command is only available to Admin users. Example:: curl https://my.example.org/api/v1/projects/10 -X PUT \\ -H 'Authorization: Bearer MY_ACCESS_TOKEN' \\ -H 'Content-Type: application/json;charset=UTF-8' \\ --data-binary '{"name":"test-project-update",\\ "description":"An updated test project"}' :param project_id: An ID of the project. :param project: A project within the request body. """ result = projects_api.project_update(project_id, project.as_dict(omit_unset=True)) if result: return wmodels.Project.from_db_model(result) else: raise exc.NotFound(_("Project %s not found") % project_id) def _is_int(self, s): try: int(s) return True except ValueError: return False @decorators.db_exceptions @secure(checks.guest) @wsme_pecan.wsexpose([wmodels.Project], wtypes.text, wtypes.text, int, int, int) def search(self, q="", marker=None, offset=None, limit=None): """The search endpoint for projects. Example:: curl https://my.example.org/api/v1/projects/search?q=cloud :param q: The query string. :return: List of Projects matching the query. """ projects = SEARCH_ENGINE.projects_query(q=q, marker=marker, offset=offset, limit=limit) return [wmodels.Project.from_db_model(project) for project in projects] @expose() def _route(self, args, request): if request.method == 'GET' and len(args) > 0: # It's a request by a name or id something = unquote(args[0]) if something == "search": # Request to a search endpoint return super(ProjectsController, self)._route(args, request) if self._is_int(something): # Get by id return self.get_one_by_id, args else: # Get by name return self.get_one_by_name, ["/".join(args)] # Use default routing for all other requests return super(ProjectsController, self)._route(args, request)
13,362
https://github.com/lkwr/react-bootstrap-icons/blob/master/src/icons/arrow-repeat.js
Github Open Source
Open Source
MIT
2,022
react-bootstrap-icons
lkwr
JavaScript
Code
131
469
import React, { forwardRef } from 'react'; import PropTypes from 'prop-types'; const ArrowRepeat = forwardRef(({ color, size, ...rest }, ref) => { return ( <svg ref={ref} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width={size} height={size} fill={color} {...rest} > <path d="M11.534 7h3.932a.25.25 0 0 1 .192.41l-1.966 2.36a.25.25 0 0 1-.384 0l-1.966-2.36a.25.25 0 0 1 .192-.41zm-11 2h3.932a.25.25 0 0 0 .192-.41L2.692 6.23a.25.25 0 0 0-.384 0L.342 8.59A.25.25 0 0 0 .534 9z" /> <path fillRule="evenodd" d="M8 3c-1.552 0-2.94.707-3.857 1.818a.5.5 0 1 1-.771-.636A6.002 6.002 0 0 1 13.917 7H12.9A5.002 5.002 0 0 0 8 3zM3.1 9a5.002 5.002 0 0 0 8.757 2.182.5.5 0 1 1 .771.636A6.002 6.002 0 0 1 2.083 9H3.1z" /> </svg> ); }); ArrowRepeat.propTypes = { color: PropTypes.string, size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; ArrowRepeat.defaultProps = { color: 'currentColor', size: '1em', }; export default ArrowRepeat;
27,484
https://github.com/kotofun/Snowshoe/blob/master/src/chains/comment.js
Github Open Source
Open Source
MIT
null
Snowshoe
kotofun
JavaScript
Code
64
219
import {when, merge, set} from 'cerebral/operators'; import {tags, parts} from '../constants'; import uuid from 'uuid'; export const commentChanged = [ merge(tags.comment, { body: tags.valueProp }) ]; export const commentSubmitted = [ when(tags.draftCommentText), { true: [ () => ({[parts.uuid]: uuid(), [parts.timestamp]: Date.now()}), merge(tags.newComment, { comment_id: tags.uuidProp, body: tags.draftCommentText, parentId: tags.activeChunkId, created_at: tags.timestamp, commentator: { nickname: 'Snowshoe' } }), set(tags.draftCommentText, '') ], false: [] } ];
26,464
https://github.com/hofstadter-io/hof-starter-kit/blob/master/dsl/app/default/templates/packages/server/src/database/seeds/user.js
Github Open Source
Open Source
BSD-3-Clause
2,018
hof-starter-kit
hofstadter-io
JavaScript
Code
146
538
import bcrypt from 'bcryptjs'; import { returnId, truncateTables } from '../../sql/helpers'; import { decamelizeKeys } from "humps"; {{#each DslContext.modules as |MOD|}} {{#getdsl (concat3 "modules." MOD ".module") true}}{{#with . as |MODULE|}} {{#if MODULE.seeds}} import {{camelT MOD}}Seed, { clear as {{camelT MOD}}Clear } from '../../modules/{{kebab MOD}}/db/seeds'; {{/if}} {{/with}}{{/getdsl}} {{/each}} import data from '../../../../../user-files/design/seeds/users.json'; const users = data.users; export async function seed(knex, Promise) { console.log("cleaning modules") // clean modules first {{#each DslContext.modules as |MOD|}} {{#getdsl (concat3 "modules." MOD ".module") true}}{{#with . as |MODULE|}} {{#if MODULE.seeds}} await {{camelT MOD}}Clear(knex, Promise); {{/if}} {{/with}}{{/getdsl}} {{/each}} console.log("cleaning users") // then clean users await truncateTables(knex, Promise, [ 'user', 'auth_apikey', 'auth_certificate', 'auth_facebook', 'auth_google', 'auth_github', 'auth_linkedin' ]); console.log("SEEDING users") for (let user of users) { var id = await returnId(knex('user')).insert({ username: user.username, email: user.email, password_hash: await bcrypt.hash(user.password, 12), role: user.role, is_active: user.isActive }); if (user.apikey) { await knex('auth_apikey').insert({ user_id: id[0], apikey: user.apikey, }) } } }
3,636
https://github.com/MikeyZat/next-js-starter-pack/blob/master/pages/about.tsx
Github Open Source
Open Source
MIT
2,020
next-js-starter-pack
MikeyZat
TSX
Code
9
18
import { About } from 'components/About'; export default About;
10,534
https://github.com/MartinJSoles/Madjic.Edi/blob/master/Madjic.Edi.Dom/Segments/IK5.vb
Github Open Source
Open Source
MIT
2,021
Madjic.Edi
MartinJSoles
Visual Basic
Code
547
1,673
Namespace Segments '''<summary>Implementation Transaction Set Response Trailer</summary> '''<remarks>To acknowledge acceptance or rejection and report implementation errors in a transaction set</remarks> Partial Friend Class IK5_Obj Inherits Segment Implements IK5, Transactions.Transaction999.Transaction999.Segments.Loop1000.IK5 Private Shared ReadOnly _Rules As SyntaxRule() = {New SyntaxRuleAllRequired({1})} Public Sub New() MyBase.New("IK5") Elements.AddRange({CType(Nothing, DataElements.Element717), CType(Nothing, DataElements.Element618), CType(Nothing, DataElements.Element618), CType(Nothing, DataElements.Element618), CType(Nothing, DataElements.Element618), CType(Nothing, DataElements.Element618)}) SyntaxRules.AddRange(_Rules) Initialize() End Sub Partial Private Sub Initialize() End Sub Friend Property IK501 As String Implements IK5.IK501, Transactions.Transaction999.Transaction999.Segments.Loop1000.IK5.IK501 Get Return If(Elements(0) IsNot Nothing, CType(Elements(0), DataElements.Element717).Value, Nothing) End Get Set(value As String) If Elements(0) Is Nothing AndAlso value IsNot Nothing Then Elements(0) = New DataElements.Element717 End If If Elements(0) IsNot Nothing Then CType(Elements(0), DataElements.Element717).Value = value End If End Set End Property Friend Property IK502 As String Implements IK5.IK502, Transactions.Transaction999.Transaction999.Segments.Loop1000.IK5.IK502 Get Return If(Elements(1) IsNot Nothing, CType(Elements(1), DataElements.Element618).Value, Nothing) End Get Set(value As String) If Elements(1) Is Nothing AndAlso value IsNot Nothing Then Elements(1) = New DataElements.Element618 End If If Elements(1) IsNot Nothing Then CType(Elements(1), DataElements.Element618).Value = value End If End Set End Property Friend Property IK503 As String Implements IK5.IK503, Transactions.Transaction999.Transaction999.Segments.Loop1000.IK5.IK503 Get Return If(Elements(2) IsNot Nothing, CType(Elements(2), DataElements.Element618).Value, Nothing) End Get Set(value As String) If Elements(2) Is Nothing AndAlso value IsNot Nothing Then Elements(2) = New DataElements.Element618 End If If Elements(2) IsNot Nothing Then CType(Elements(2), DataElements.Element618).Value = value End If End Set End Property Friend Property IK504 As String Implements IK5.IK504, Transactions.Transaction999.Transaction999.Segments.Loop1000.IK5.IK504 Get Return If(Elements(3) IsNot Nothing, CType(Elements(3), DataElements.Element618).Value, Nothing) End Get Set(value As String) If Elements(3) Is Nothing AndAlso value IsNot Nothing Then Elements(3) = New DataElements.Element618 End If If Elements(3) IsNot Nothing Then CType(Elements(3), DataElements.Element618).Value = value End If End Set End Property Friend Property IK505 As String Implements IK5.IK505, Transactions.Transaction999.Transaction999.Segments.Loop1000.IK5.IK505 Get Return If(Elements(4) IsNot Nothing, CType(Elements(4), DataElements.Element618).Value, Nothing) End Get Set(value As String) If Elements(4) Is Nothing AndAlso value IsNot Nothing Then Elements(4) = New DataElements.Element618 End If If Elements(4) IsNot Nothing Then CType(Elements(4), DataElements.Element618).Value = value End If End Set End Property Friend Property IK506 As String Implements IK5.IK506, Transactions.Transaction999.Transaction999.Segments.Loop1000.IK5.IK506 Get Return If(Elements(5) IsNot Nothing, CType(Elements(5), DataElements.Element618).Value, Nothing) End Get Set(value As String) If Elements(5) Is Nothing AndAlso value IsNot Nothing Then Elements(5) = New DataElements.Element618 End If If Elements(5) IsNot Nothing Then CType(Elements(5), DataElements.Element618).Value = value End If End Set End Property Friend Shared Function FromGenericSegment(source As GenericSegment, reader As EdiReader.SegmentReader) As IK5 Dim rval As New IK5_Obj With rval If source.Elements.Count > 0 Then .IK501 = source.ToStringValue(0) End If If source.Elements.Count > 1 Then .IK502 = source.ToStringValue(1) End If If source.Elements.Count > 2 Then .IK503 = source.ToStringValue(2) End If If source.Elements.Count > 3 Then .IK504 = source.ToStringValue(3) End If If source.Elements.Count > 4 Then .IK505 = source.ToStringValue(4) End If If source.Elements.Count > 5 Then .IK506 = source.ToStringValue(5) End If End With Return rval End Function End Class '''<summary>Implementation Transaction Set Response Trailer</summary> '''<remarks>To acknowledge acceptance or rejection and report implementation errors in a transaction set</remarks> Public Interface IK5 Inherits ISegment '''<summary>Transaction Set Acknowledgment Code</summary> '''<remarks></remarks> Property IK501 As String '''<summary>Implementation Transaction Set Syntax Error Code</summary> '''<remarks></remarks> Property IK502 As String '''<summary>Implementation Transaction Set Syntax Error Code</summary> '''<remarks></remarks> Property IK503 As String '''<summary>Implementation Transaction Set Syntax Error Code</summary> '''<remarks></remarks> Property IK504 As String '''<summary>Implementation Transaction Set Syntax Error Code</summary> '''<remarks></remarks> Property IK505 As String '''<summary>Implementation Transaction Set Syntax Error Code</summary> '''<remarks></remarks> Property IK506 As String End Interface End NameSpace
41,316
https://github.com/vincentxavier/nbtutor/blob/master/src/app/store/selectors.ts
Github Open Source
Open Source
BSD-3-Clause
2,022
nbtutor
vincentxavier
TypeScript
Code
10
33
import * as VisualizationSelectors from './selectors/visualization.selectors'; export { VisualizationSelectors, };
38,266
https://github.com/olasundell/solitairesolver/blob/master/src/main/java/se/atrosys/solitaire/card/Suit.java
Github Open Source
Open Source
Apache-2.0
2,014
solitairesolver
olasundell
Java
Code
36
137
package se.atrosys.solitaire.card; public enum Suit { SPADES(Color.BLACK), HEARTS(Color.RED), DIAMONDS(Color.RED), CLUBS(Color.BLACK); private final Color color; Suit(Color color) { this.color = color; } public Color getColor() { return color; } public char shortName() { return this.name().charAt(0); } }
28,654
https://github.com/sky5454/ext-saladict/blob/master/src/content/components/DictPanel/DictPanelStandalone.tsx
Github Open Source
Open Source
MIT
2,019
ext-saladict
sky5454
TypeScript
Code
95
366
import React, { FC, ReactNode } from 'react' import { SALADICT_PANEL } from '@/_helpers/saladict' export interface DictPanelStandaloneProps { width: string height: string withAnimation: boolean darkMode: boolean colors: React.CSSProperties panelCSS?: string menuBar: ReactNode mtaBox: ReactNode dictList: ReactNode waveformBox: ReactNode } export const DictPanelStandalone: FC<DictPanelStandaloneProps> = props => { return ( <React.Fragment> {props.panelCSS ? <style>{props.panelCSS}</style> : null} <div className={ `dictPanel-Root ${SALADICT_PANEL}` + (props.withAnimation ? ' isAnimate' : '') } style={{ ...props.colors, width: props.width, height: props.height, '--panel-width': props.width, '--panel-max-height': props.height }} > <div className="dictPanel-Head">{props.menuBar}</div> <div className="dictPanel-Body fancy-scrollbar"> {props.mtaBox} {props.dictList} </div> {props.waveformBox} </div> </React.Fragment> ) } export default DictPanelStandalone
26,472
https://github.com/antonpetkoff/fuzzy-inference/blob/master/inference/system.py
Github Open Source
Open Source
MIT
null
fuzzy-inference
antonpetkoff
Python
Code
229
923
import numpy as np import skfuzzy as fuzz from skfuzzy import control as ctrl from functools import reduce from inference.utils import get_consequent_variable_names class InferenceSystem: def __init__(self, definitions): self.definitions = definitions consequent_variable_names = get_consequent_variable_names(self.definitions) print('consequent_variable_names: {}'.format(consequent_variable_names)) self.variables = InferenceSystem.__define_variables( definitions=self.definitions, consequent_names=consequent_variable_names ) print('variables: {}'.format(self.variables)) self.rules = InferenceSystem.__define_rules(self.definitions, self.variables) print('rules: {}'.format(self.rules)) self.system = ctrl.ControlSystem(rules=self.rules) print() def get_required_inputs(self) -> list: return set(map(lambda antecedent: antecedent.label, self.system.antecedents)) def evaluate(self, inputs: object): required_inputs = self.get_required_inputs() if set(inputs.keys()) != required_inputs: raise ValueError('required inputs: {}; given: {}'.format( required_inputs, set(inputs.keys()) )) self.simulation = ctrl.ControlSystemSimulation(self.system) self.simulation.inputs(inputs) self.simulation.compute() # TODO: defuzzify return self.simulation.output def visualize_rules(self): self.system.view_n() # input('Press ENTER to hide rule visualization') def visualize_result(self): for name in self.variables: self.variables[name].view(sim=self.simulation) # input('Press ENTER to hide result visualization') @staticmethod def __define_variables(definitions: object, consequent_names: set = set()): variables = {} for name, props in definitions['variables'].items(): universe = np.arange(*props['crisp_universe']) variables[name] = ctrl.Consequent( universe=universe, label=name ) if name in consequent_names else ctrl.Antecedent( universe=universe, label=name ) fuzzy_values = props['fuzzy_values'] variables[name].automf( number=len(fuzzy_values), names=fuzzy_values ) return variables @staticmethod def __define_rules(definitions: object, variables: object): rules = [] for rule in definitions['rules']: def reduce_or(disjunction): def get_variable(expr): variable_name, variable_value = expr return variables[variable_name][variable_value] return reduce( lambda a, b: a | b, map(get_variable, disjunction) ) def reduce_and(conjunction): return reduce( lambda a, b: a & b, map(reduce_or, conjunction) ) # build a clause in conjunctive normal form antecedent=reduce_and(conjunction=rule['if']) consequent_name, consequent_value = rule['then'] consequent=variables[consequent_name][consequent_value] rule = ctrl.Rule( antecedent=antecedent, consequent=consequent ) rules.append(rule) return rules
21,854
https://github.com/altcointrading/XChange/blob/master/xchange-bitkonan/src/main/java/org/knowm/xchange/bitkonan/dto/marketdata/BitKonanTrade.java
Github Open Source
Open Source
MIT
2,017
XChange
altcointrading
Java
Code
84
268
package org.knowm.xchange.bitkonan.dto.marketdata; import java.math.BigDecimal; import java.util.Date; import com.fasterxml.jackson.annotation.JsonProperty; public class BitKonanTrade { private final BigDecimal total; private final BigDecimal btc; private final BigDecimal usd; private final Date time; public BitKonanTrade(@JsonProperty("total") BigDecimal total, @JsonProperty("btc") BigDecimal btc, @JsonProperty("usd") BigDecimal usd, @JsonProperty("time") Date time) { this.total = total; this.btc = btc; this.usd = usd; this.time = time; } public BigDecimal getTotal() { return total; } public BigDecimal getBtc() { return btc; } public BigDecimal getUsd() { return usd; } public Date getTime() { return time; } }
28,501
https://github.com/dltxio/v2.getpaidinbitcoin.com.au/blob/master/src/components/VerificationTracker/VerifyID.js
Github Open Source
Open Source
Apache-2.0
null
v2.getpaidinbitcoin.com.au
dltxio
JavaScript
Code
279
778
import React, { useContext, useState } from "react"; import useSWR from "swr"; import { Alert, Button } from "react-bootstrap"; import { AuthContext } from "components/auth/Auth"; import Verify from "../../utils/Verify"; const statuses = { NOT_STARTED: 0, STARTED: 1, SUBMITTED: 2, VERIFIED: 3, REJECTED: 4, CANCELLED: 5 }; const statusAlerts = { [statuses.STARTED]: { children: "An SMS has been sent to your mobile number with instructions to proceed with your verification process." }, [statuses.SUBMITTED]: { children: "Your verification information has been received and is currently being processed." }, [statuses.VERIFIED]: { children: "Congratulations, your ID Verification is now complete." }, [statuses.REJECTED]: { children: "Your ID Verification has failed. Please contact customer support.", variant: "danger" }, [statuses.CANCELLED]: { children: "ID Verification has been cancelled", varian: "danger" } }; const VerifyID = () => { const { user, setVerified, setSkipKYC } = useContext(AuthContext); const { data: userAddress } = useSWR(`/user/${user.id}/address`); const [idVerificationStatus, setIdVerificationStatus] = useState(); const alert = statusAlerts[idVerificationStatus]; const showAlert = alert; const handleSkipKYC = () => { setSkipKYC(true); setVerified(true); }; return ( <div> <p> <b>ID Verification</b> </p> <Alert variant="primary"> As an AUSTRAC registered exchange provider of Australian Dollars into Bitcoin, we are required to complete a short ID Verification process before we can provide any exchange services. This verification is a one-time process and your details are not stored. Please have your documents ready. </Alert> {showAlert && <Alert variant={alert.varian ? alert.varian : "primary"} {...alert} />} <div className={userAddress[0].isCustodial ? "d-flex mt-2" : "mt-2"}> <div className="mr-auto"> <Verify setIdVerificationStatus={setIdVerificationStatus} statuses={statuses} user={user} /> </div> <div > {userAddress && userAddress[0].isCustodial && ( <Button onClick={handleSkipKYC} style={{ width: "200px", height: "50px", backgroundColor: "rgb(0, 69, 216)" }} > Skip KYC </Button> )} </div> </div> </div> ); }; export default VerifyID;
31,137
https://github.com/vimalathithanr/Twitter-Client/blob/master/app/src/main/java/com/codepath/tweets/tweets/TwitterClient.java
Github Open Source
Open Source
Apache-2.0
null
Twitter-Client
vimalathithanr
Java
Code
224
845
package com.codepath.tweets.tweets; import org.scribe.builder.api.Api; import org.scribe.builder.api.TwitterApi; import android.content.Context; import com.codepath.oauth.OAuthBaseClient; import com.codepath.tweets.tweets.models.Tweet; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; public class TwitterClient extends OAuthBaseClient { public static final Class<? extends Api> REST_API_CLASS = TwitterApi.class; // Change this public static final String REST_URL = "https://api.twitter.com/1.1"; // Change this, base API URL public static final String REST_CONSUMER_KEY = "Zv9AYS0ItwWnlLKycg5Yhu43W"; // Change this public static final String REST_CONSUMER_SECRET = "XS47igUvjujmFRjBZz0hh1c3iaOKeh3BLSUb5cRQmgD2IFbXHy"; // Change this public static final String REST_CALLBACK_URL = "oauth://cpsimpletweets"; // Change this (here and in manifest) int since_id = 1; int page = 1; public TwitterClient(Context context) { super(context, REST_API_CLASS, REST_URL, REST_CONSUMER_KEY, REST_CONSUMER_SECRET, REST_CALLBACK_URL); } public void addPage(int pageFromTimeline) { page = pageFromTimeline; } public void getHomeTimeline(AsyncHttpResponseHandler handler) { String apiUrl = getApiUrl("statuses/home_timeline.json"); RequestParams params = new RequestParams(); params.put("count", 25); params.put("page", page); params.put("since_id", since_id); getClient().get(apiUrl, params, handler); } public void postTweet(AsyncHttpResponseHandler handler) { Tweet tweet = new Tweet(); String status = tweet.getComposeTweet(); String apiUrl = getApiUrl("statuses/update.json"); RequestParams params = new RequestParams(); params.put("status", status); getClient().post(apiUrl, params, handler); } public void getMentionsTimeline(AsyncHttpResponseHandler handler) { String apiUrl = getApiUrl("statuses/mentions_timeline.json"); RequestParams params = new RequestParams(); params.put("page", page); params.put("count", 25); getClient().get(apiUrl, params, handler); } public void getUserTimeline(String screenName, AsyncHttpResponseHandler handler) { String apiUrl = getApiUrl("statuses/user_timeline.json"); RequestParams params = new RequestParams(); params.put("page", page); params.put("count", 25); params.put("screen_name", screenName); getClient().get(apiUrl, params, handler); } public void getUserInfo(AsyncHttpResponseHandler handler) { String apiUrl = getApiUrl("account/verify_credentials.json"); getClient().get(apiUrl, null, handler); } }
7,406
https://github.com/desec-io/desec-stack/blob/master/www/webapp/src/components/Field/RecordCDS.vue
Github Open Source
Open Source
MIT
2,023
desec-stack
desec-io
Vue
Code
14
43
<script> import RecordDS from './RecordDS.vue'; export default { name: 'RecordCDS', extends: RecordDS, }; </script>
1,162
https://github.com/gurupunskill/auto-park/blob/master/sou/app/src/main/java/com/autopark/sou/SettingsActivity.java
Github Open Source
Open Source
MIT
null
auto-park
gurupunskill
Java
Code
47
175
package com.autopark.sou; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class SettingsActivity extends AppCompatActivity { public static final String KEY_SERVER_ADDR = "edit_server_address"; public static final String KEY_SERVER_PORT = "edit_server_port"; public static final String KEY_SLOT_ID = "edit_slot_id"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); } }
50,273
https://github.com/EzekielWachira/Social-App-Frontend/blob/master/src/pages/Authentication/Register.vue
Github Open Source
Open Source
MIT
2,020
Social-App-Frontend
EzekielWachira
Vue
Code
355
1,287
<template> <div class="flex flex-center q-pt-lg"> <q-form class="register-form " @submit.prevent="register"> <q-card class="register-card"> <q-toolbar class="text-white q-mb-sm" style="background: radial-gradient(circle, #47c5ff 0%, #12d108 100%)"> <q-toolbar-title>Register an account</q-toolbar-title> <q-space/> <q-icon name="person_add" size="30px"/> </q-toolbar> <!-- <q-card-section class="text-center">--> <!-- <div class="text-h6 text-positive">Register an account</div>--> <!-- </q-card-section>--> <q-card-section> <q-input outlined autofocus dense hint="First and Last name" v-model="formData.name" :rules="[ val => val.length > 0 || 'Name is required' ]" > <template v-slot:prepend> <q-icon name="person"/> </template> <template v-slot:append v-if="formData.name.length > 0"> <q-icon name="close" @click="formData.name = ''"/> </template> </q-input> </q-card-section> <q-card-section> <q-input outlined dense type="email" hint="example@example.com" v-model="formData.email" :rules="[ val => val.length > 0 || 'Email is required' ]" > <template v-slot:prepend> <q-icon name="mail"/> </template> </q-input> </q-card-section> <q-card-section> <q-input outlined dense :type="isPassword ? 'password' : 'text'" v-model="formData.password" hint="min character 6" :rules="[ val => val.length > 0 || 'Password is required', val => val.length >= 6 || 'Should not be less than 6 character' ]" > <template v-slot:prepend> <q-icon name="lock"/> </template> <template v-slot:append v-if="formData.password.length > 0"> <q-icon :name="isPassword ? 'visibility' : 'visibility_off' " @click="isPassword = !isPassword"/> </template> </q-input> </q-card-section> <q-card-section> <q-input outlined dense type="password" v-model="formData.password_confirmation" hint="min characters 6" :rules="[ val => val.length > 0 || 'Password is required', val => val === formData.password || 'Two password do not match', val => val.length >= 6 || 'Should not be less than 6 character' ]" > <template v-slot:prepend> <q-icon name="lock"/> </template> </q-input> </q-card-section> <q-card-section class="q-pt-none"> <q-checkbox color="positive" v-model="acceptTerms" label="I Accept terms and Conditions" /> </q-card-section> <q-card-actions align="right"> <q-btn label="Sign Up" class="q-px-md q-mr-sm q-mb-sm text-white" style="background: radial-gradient(circle, #47c5ff 0%, #12d108 100%)" type="submit" :disable="formData.name === '' || formData.email === '' || formData.password === '' || formData.password_confirmation === '' || formData.password_confirmation !== formData.password || acceptTerms === false" flat /> </q-card-actions> </q-card> </q-form> </div> </template> <script> import User from 'src/Api/User' import Csrf from 'src/Api/Csrf' export default { name: 'Register.vue', data: () => ({ formData: { name: '', email: '', password: '', password_confirmation: '' }, isPassword: true, acceptTerms: false }), methods: { register () { Csrf.getCookie().then(() => { }) User.register(this.formData) .then(() => { this.$router.push('/login') }).catch(error => { console.log(error) }) } } } </script> <style scoped lang="scss"> .register-form{ width: 500px; min-width: 100px; } @media only screen and (max-width: 520px) { .register-form{ width: 90%; } } </style>
27,376
https://github.com/lukehb/137-clustering/blob/master/src/main/java/onethreeseven/clustering/command/DBScanCommand.java
Github Open Source
Open Source
MIT
null
137-clustering
lukehb
Java
Code
338
1,026
package onethreeseven.clustering.command; import com.beust.jcommander.Parameter; import onethreeseven.clustering.algorithm.DBScan; import onethreeseven.clustering.model.Cluster; import onethreeseven.clustering.model.DBScanCluster; import java.util.Collection; import java.util.Iterator; import java.util.function.Consumer; /** * Commands for {@link DBScan} * @author Luke Bermingham */ public class DBScanCommand extends AbstractClusteringCommand { @Parameter(names = {"-m", "--minPts"}, description = "The minimum number of points to expand a cluster.") private int minPts; @Parameter(names = {"-e", "--eps"}, description = "The proximity of points in space to be considered part of the same cluster.") private double epsMetres; private double[][] points2d; private Consumer<Double> progressListener; public void setProgressListener(Consumer<Double> progressListener) { this.progressListener = progressListener; } @Override protected Cluster[] doClustering() { Collection<DBScanCluster> col = DBScan.run2d(points2d, epsMetres, minPts, progressListener); DBScanCluster[] arr = new DBScanCluster[col.size()]; Iterator<DBScanCluster> iter = col.iterator(); int i = 0; while(iter.hasNext()){ arr[i] = iter.next(); i++; } return arr; } @Override protected boolean clusterShouldBeVisibleOnLoad(Cluster cluster) { return !(cluster instanceof DBScanCluster) || !((DBScanCluster) cluster).IsNoise(); } @Override protected String getUsage() { return "dbscan -e 3.14 -m 2"; } @Override protected boolean parametersValid() { this.points2d = getPointsToCluster(); if(points2d.length < 2){ System.err.println("There must be more than two points to perform clustering"); return false; } if(minPts < 1 || minPts > points2d.length){ System.err.println("In dbscan minPts must be greater than 1 and less than then number of points, " + "was passed: " + minPts); return false; } if(epsMetres < 0){ System.err.println("In dbscan epsilon must be greater than zero, " + "was passed: " + epsMetres); return false; } return true; } @Override public boolean shouldStoreRerunAlias() { return false; } @Override public String generateRerunAliasBasedOnParams() { return null; } @Override public String getCategory() { return "Mining"; } @Override public String getCommandName() { return "dbscan"; } @Override public String[] getOtherCommandNames() { return new String[0]; } @Override public String getDescription() { return "Runs DB-Scan clustering on all selected entities with coordinates."; } @Override protected String getClusterLayerName() { return "DB-Scan Clusters"; } @Override protected String getClusterPrefix(Cluster cluster) { if(cluster instanceof DBScanCluster){ if(((DBScanCluster) cluster).IsNoise()){ return "NOISE-"; } } return "Cluster-"; } @Override protected double[] getClusterAnnotationCartesianCoord(Cluster cluster) { if(cluster instanceof DBScanCluster){ if(!cluster.getPoints2d().isEmpty()){ int midIdx = (int) (cluster.getPoints2d().size()-1 * 0.5); return cluster.getPoints2d().get(midIdx); } } return null; } }
18,801
https://github.com/Squarespace/mongo-java-driver/blob/master/src/main/org/bson/io/Bits.java
Github Open Source
Open Source
Apache-2.0
2,019
mongo-java-driver
Squarespace
Java
Code
1,100
1,990
/* * Copyright (c) 2008-2014 MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bson.io; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; /** * Utility class for reading values from an input stream. */ public class Bits { /** * Reads bytes from the input stream and puts them into the given byte buffer. The equivalent of calling {@link * #readFully(java.io.InputStream, byte[], int, int)} with an offset of zero and a length equal to the length of the buffer. * * @param in the input stream to read from * @param b the buffer into which the data is read. * @throws IOException if there's an error reading from the {@code in} */ public static void readFully(InputStream in, byte[] b) throws IOException { readFully(in, b, b.length); } /** * Reads bytes from the input stream and puts them into the given byte buffer. The equivalent of calling {@link * #readFully(java.io.InputStream, byte[], int, int)} with an offset of zero. * * @param in the input stream to read from * @param b the buffer into which the data is read. * @param length the maximum number of bytes to read. * @throws IOException if there's an error reading from the {@code in} */ public static void readFully(InputStream in, byte[] b, int length) throws IOException { readFully(in, b, 0, length); } /** * Reads bytes from the input stream and puts them into the given byte buffer. * * @param in the input stream to read from * @param b the buffer into which the data is read. * @param startOffset the start offset in array {@code b} at which the data is written. * @param length the maximum number of bytes to read. * @throws IOException if there's an error reading from the {@code in} * @see java.io.InputStream#read(byte[], int, int) */ public static void readFully(InputStream in, byte[] b, int startOffset, int length) throws IOException { if (b.length < length + startOffset) { throw new IllegalArgumentException("Buffer is too small"); } int offset = startOffset; int toRead = length; while ( toRead > 0 ){ int bytesRead = in.read( b, offset , toRead ); if ( bytesRead < 0 ) throw new EOFException(); toRead -= bytesRead; offset += bytesRead; } } /** * Reads and returns a single integer value from the input stream. * * @param in the input stream to read from * @return the integer value * @throws IOException if there's an error reading from the {@code in} */ public static int readInt(InputStream in) throws IOException { return readInt(in, new byte[4]); } /** * Reads and returns a single integer value from the input stream. * * @param in the input stream to read from * @param data the buffer to write the input stream bytes into * @return the integer value * @throws IOException if there's an error reading from the {@code in} */ public static int readInt(InputStream in, byte[] data) throws IOException { readFully(in, data, 4); return readInt(data); } /** * Reads and returns a single integer value from the buffer. The equivalent of calling {@link #readInt(byte[], int)} with an offset of * zero. * * @param data the buffer to read from * @return the integer value */ public static int readInt(byte[] data) { return readInt(data, 0); } /** * Reads and returns a single integer value from the buffer. * * @param data the buffer to read from * @param offset the position to start reading from the buffer * @return the integer value */ public static int readInt(byte[] data, int offset) { int x = 0; x |= ( 0xFF & data[offset+0] ) << 0; x |= ( 0xFF & data[offset+1] ) << 8; x |= ( 0xFF & data[offset+2] ) << 16; x |= ( 0xFF & data[offset+3] ) << 24; return x; } /** * Reads and returns a single big-endian integer value * * @param data the buffer to read from * @param offset the position to start reading from the buffer * @return the integer value */ public static int readIntBE(byte[] data, int offset) { int x = 0; x |= ( 0xFF & data[offset+0] ) << 24; x |= ( 0xFF & data[offset+1] ) << 16; x |= ( 0xFF & data[offset+2] ) << 8; x |= ( 0xFF & data[offset+3] ) << 0; return x; } /** * Reads and returns a single long value from the input stream. * * @param in the input stream to read from * @return the long value * @throws IOException if there's an error reading from the {@code in} */ public static long readLong(InputStream in) throws IOException { return readLong(in, new byte[8]); } /** * Reads and returns a single long value from the input stream. * * @param in the input stream to read from * @param data the buffer to write the input stream bytes into * @return the long value * @throws IOException if there's an error reading from the {@code in} */ public static long readLong(InputStream in, byte[] data) throws IOException { readFully(in, data, 8); return readLong(data); } /** * Reads and returns a single long value from the buffer. The equivalent of called {@link #readLong(byte[], int)} with an offset of * zero. * * @param data the buffer to read from * @return the long value */ public static long readLong(byte[] data) { return readLong(data, 0); } /** * Reads and returns a single long value from the buffer. * * @param data the buffer to read from * @param offset the position to start reading from the buffer * @return the long value */ public static long readLong(byte[] data, int offset) { long x = 0; x |= ( 0xFFL & data[offset+0] ) << 0; x |= ( 0xFFL & data[offset+1] ) << 8; x |= ( 0xFFL & data[offset+2] ) << 16; x |= ( 0xFFL & data[offset+3] ) << 24; x |= ( 0xFFL & data[offset+4] ) << 32; x |= ( 0xFFL & data[offset+5] ) << 40; x |= ( 0xFFL & data[offset+6] ) << 48; x |= ( 0xFFL & data[offset+7] ) << 56; return x; } }
40,210
https://github.com/yoyo2003/pjsip4net/blob/master/pjsip4net.Core/Configuration/CoreComponentConfigurator.cs
Github Open Source
Open Source
Apache-2.0
2,021
pjsip4net
yoyo2003
C#
Code
21
84
using pjsip4net.Core.Interfaces; namespace pjsip4net.Core.Configuration { public class CoreComponentConfigurator : IConfigureComponents { public void Configure(IContainer container) { container.RegisterAsSingleton<IEventsProvider, EventsProvider>(); } } }
27,625
https://github.com/dwpsoft/cognito-local/blob/master/jest.config.js
Github Open Source
Open Source
MIT
2,022
cognito-local
dwpsoft
JavaScript
Code
17
86
module.exports = { roots: ["<rootDir>/src"], setupFiles: ["jest-date-mock"], setupFilesAfterEnv: ["<rootDir>/setupTests.ts"], transform: { "^.+\\.ts$": "esbuild-jest", }, testMatch: ["**/*.test.ts"], };
21,375
https://github.com/intuit/QuickBooks-V3-PHP-SDK/blob/master/src/Data/IPPPaymentStatusEnum.php
Github Open Source
Open Source
Apache-2.0, LicenseRef-scancode-unknown-license-reference
2,023
QuickBooks-V3-PHP-SDK
intuit
PHP
Code
196
523
<?php namespace QuickBooksOnline\API\Data; /** * @xmlNamespace http://schema.intuit.com/finance/v3 * @xmlType string * @xmlName IPPPaymentStatusEnum * @var IPPPaymentStatusEnum * @xmlDefinition Product: ALL Description: Enumeration of payable status for an invoice, as follows: A pending invoice is not yet approved/final/sent; not yet payable by customer. A payable invoice is now payable. Partial payments may have been received, but money still remains to be paid. No claim is made about due vs. overdue, past due etc... A paid invoice has been paid in full. No amount remains to be paid. */ class IPPPaymentStatusEnum { /** * Initializes this object, optionally with pre-defined property values * * Initializes this object and it's property members, using the dictionary * of key/value pairs passed as an optional argument. * * @param dictionary $keyValInitializers key/value pairs to be populated into object's properties * @param boolean $verbose specifies whether object should echo warnings */ public function __construct($keyValInitializers=array(), $verbose=FALSE) { foreach($keyValInitializers as $initPropName => $initPropVal) { if (property_exists('IPPPaymentStatusEnum',$initPropName) || property_exists('QuickBooksOnline\API\Data\IPPPaymentStatusEnum',$initPropName)) { $this->{$initPropName} = $initPropVal; } else { if ($verbose) echo "Property does not exist ($initPropName) in class (".get_class($this).")"; } } } /** * @xmlType value * @var string */ public $value; } // end class IPPPaymentStatusEnum
31,329
https://github.com/devmobile-vulog/flutter-mapbox-gl/blob/master/lib/src/annotation_manager.dart
Github Open Source
Open Source
BSD-2-Clause
2,022
flutter-mapbox-gl
devmobile-vulog
Dart
Code
1,061
3,510
part of mapbox_gl; abstract class AnnotationManager<T extends Annotation> { final MapboxMapController controller; final _idToAnnotation = <String, T>{}; final _idToLayerIndex = <String, int>{}; /// Called if a annotation is tapped final void Function(T)? onTap; /// base id of the manager. User [layerdIds] to get the actual ids. final String id; List<String> get layerIds => [for (int i = 0; i < allLayerProperties.length; i++) _makeLayerId(i)]; /// If disabled the manager offers no interaction for the created symbols final bool enableInteraction; /// implemented to define the layer properties List<LayerProperties> get allLayerProperties; /// used to spedicy the layer and annotation will life on /// This can be replaced by layer filters a soon as they are implemented final int Function(T)? selectLayer; /// get the an annotation by its id T? byId(String id) => _idToAnnotation[id]; Set<T> get annotations => _idToAnnotation.values.toSet(); AnnotationManager(this.controller, {this.onTap, this.selectLayer, required this.enableInteraction}) : id = getRandomString() { for (var i = 0; i < allLayerProperties.length; i++) { final layerId = _makeLayerId(i); controller.addGeoJsonSource(layerId, buildFeatureCollection([]), promoteId: "id"); controller.addLayer(layerId, layerId, allLayerProperties[i]); } if (onTap != null) { controller.onFeatureTapped.add(_onFeatureTapped); } controller.onFeatureDrag.add(_onDrag); } /// This function can be used to rebuild all layers after their properties /// changed Future<void> _rebuildLayers() async { for (var i = 0; i < allLayerProperties.length; i++) { final layerId = _makeLayerId(i); await controller.removeLayer(layerId); await controller.addLayer(layerId, layerId, allLayerProperties[i]); } } _onFeatureTapped(dynamic id, Point<double> point, LatLng coordinates) { final annotation = _idToAnnotation[id]; if (annotation != null) { onTap!(annotation); } } String _makeLayerId(int layerIndex) => "${id}_$layerIndex"; Future<void> _setAll() async { if (selectLayer != null) { final featureBuckets = [for (final _ in allLayerProperties) <T>[]]; for (final annotation in _idToAnnotation.values) { final layerIndex = selectLayer!(annotation); _idToLayerIndex[annotation.id] = layerIndex; featureBuckets[layerIndex].add(annotation); } for (var i = 0; i < featureBuckets.length; i++) { await controller.setGeoJsonSource( _makeLayerId(i), buildFeatureCollection( [for (final l in featureBuckets[i]) l.toGeoJson()])); } } else { await controller.setGeoJsonSource( _makeLayerId(0), buildFeatureCollection( [for (final l in _idToAnnotation.values) l.toGeoJson()])); } } /// Adds a multiple annotations to the map. This much faster than calling add /// multiple times Future<void> addAll(Iterable<T> annotations) async { for (var a in annotations) { _idToAnnotation[a.id] = a; } await _setAll(); } /// add a single annotation to the map Future<void> add(T annotation) async { _idToAnnotation[annotation.id] = annotation; await _setAll(); } /// Removes multiple annotations from the map Future<void> removeAll(Iterable<T> annotations) async { for (var a in annotations) { _idToAnnotation.remove(a.id); } await _setAll(); } /// Remove a single annotation form the map Future<void> remove(T annotation) async { _idToAnnotation.remove(annotation.id); await _setAll(); } /// Removes all annotations from the map Future<void> clear() async { _idToAnnotation.clear(); await _setAll(); } /// Fully dipose of all the the resouces managed by the annotation manager. /// The manager cannot be used after this has been called Future<void> dispose() async { _idToAnnotation.clear(); await _setAll(); for (var i = 0; i < allLayerProperties.length; i++) { await controller.removeLayer(_makeLayerId(i)); await controller.removeSource(_makeLayerId(i)); } } _onDrag(dynamic id, {required Point<double> point, required LatLng origin, required LatLng current, required LatLng delta, required DragEventType eventType}) { final annotation = byId(id); if (annotation != null) { annotation.translate(delta); set(annotation); } } /// Set an existing anntotation to the map. Use this to do a fast update for a /// single annotation Future<void> set(T anntotation) async { assert(_idToAnnotation.containsKey(anntotation.id), "you can only set existing annotations"); _idToAnnotation[anntotation.id] = anntotation; final oldLayerIndex = _idToLayerIndex[anntotation.id]; final layerIndex = selectLayer != null ? selectLayer!(anntotation) : 0; if (oldLayerIndex != layerIndex) { // if the annotation has to be moved to another layer/source we have to // set all await _setAll(); } else { await controller.setGeoJsonFeature( _makeLayerId(layerIndex), anntotation.toGeoJson()); } } } class LineManager extends AnnotationManager<Line> { LineManager(MapboxMapController controller, {void Function(Line)? onTap, bool enableInteraction = true}) : super( controller, onTap: onTap, enableInteraction: enableInteraction, selectLayer: (Line line) => line.options.linePattern == null ? 0 : 1, ); static const _baseProperties = LineLayerProperties( lineJoin: [Expressions.get, 'lineJoin'], lineOpacity: [Expressions.get, 'lineOpacity'], lineColor: [Expressions.get, 'lineColor'], lineWidth: [Expressions.get, 'lineWidth'], lineGapWidth: [Expressions.get, 'lineGapWidth'], lineOffset: [Expressions.get, 'lineOffset'], lineBlur: [Expressions.get, 'lineBlur'], ); @override List<LayerProperties> get allLayerProperties => [ _baseProperties, _baseProperties.copyWith( LineLayerProperties(linePattern: [Expressions.get, 'linePattern'])), ]; } class FillManager extends AnnotationManager<Fill> { FillManager( MapboxMapController controller, { void Function(Fill)? onTap, bool enableInteraction = true, }) : super( controller, onTap: onTap, enableInteraction: enableInteraction, selectLayer: (Fill fill) => fill.options.fillPattern == null ? 0 : 1, ); @override List<LayerProperties> get allLayerProperties => const [ FillLayerProperties( fillOpacity: [Expressions.get, 'fillOpacity'], fillColor: [Expressions.get, 'fillColor'], fillOutlineColor: [Expressions.get, 'fillOutlineColor'], ), FillLayerProperties( fillOpacity: [Expressions.get, 'fillOpacity'], fillColor: [Expressions.get, 'fillColor'], fillOutlineColor: [Expressions.get, 'fillOutlineColor'], fillPattern: [Expressions.get, 'fillPattern'], ) ]; } class CircleManager extends AnnotationManager<Circle> { CircleManager( MapboxMapController controller, { void Function(Circle)? onTap, bool enableInteraction = true, }) : super( controller, enableInteraction: enableInteraction, onTap: onTap, ); @override List<LayerProperties> get allLayerProperties => const [ CircleLayerProperties( circleRadius: [Expressions.get, 'circleRadius'], circleColor: [Expressions.get, 'circleColor'], circleBlur: [Expressions.get, 'circleBlur'], circleOpacity: [Expressions.get, 'circleOpacity'], circleStrokeWidth: [Expressions.get, 'circleStrokeWidth'], circleStrokeColor: [Expressions.get, 'circleStrokeColor'], circleStrokeOpacity: [Expressions.get, 'circleStrokeOpacity'], ) ]; } class SymbolManager extends AnnotationManager<Symbol> { SymbolManager( MapboxMapController controller, { void Function(Symbol)? onTap, bool iconAllowOverlap = false, bool textAllowOverlap = false, bool iconIgnorePlacement = false, bool textIgnorePlacement = false, bool enableInteraction = true, }) : _iconAllowOverlap = iconAllowOverlap, _textAllowOverlap = textAllowOverlap, _iconIgnorePlacement = iconIgnorePlacement, _textIgnorePlacement = textIgnorePlacement, super( controller, enableInteraction: enableInteraction, onTap: onTap, ); bool _iconAllowOverlap; bool _textAllowOverlap; bool _iconIgnorePlacement; bool _textIgnorePlacement; /// For more information on what this does, see https://docs.mapbox.com/help/troubleshooting/optimize-map-label-placement/#label-collision Future<void> setIconAllowOverlap(bool value) async { _iconAllowOverlap = value; await _rebuildLayers(); } /// For more information on what this does, see https://docs.mapbox.com/help/troubleshooting/optimize-map-label-placement/#label-collision Future<void> setTextAllowOverlap(bool value) async { _textAllowOverlap = value; await _rebuildLayers(); } /// For more information on what this does, see https://docs.mapbox.com/help/troubleshooting/optimize-map-label-placement/#label-collision Future<void> setIconIgnorePlacement(bool value) async { _iconIgnorePlacement = value; await _rebuildLayers(); } /// For more information on what this does, see https://docs.mapbox.com/help/troubleshooting/optimize-map-label-placement/#label-collision Future<void> setTextIgnorePlacement(bool value) async { _textIgnorePlacement = value; await _rebuildLayers(); } @override List<LayerProperties> get allLayerProperties => [ SymbolLayerProperties( iconSize: [Expressions.get, 'iconSize'], iconImage: [Expressions.get, 'iconImage'], iconRotate: [Expressions.get, 'iconRotate'], iconOffset: [Expressions.get, 'iconOffset'], iconAnchor: [Expressions.get, 'iconAnchor'], iconOpacity: [Expressions.get, 'iconOpacity'], iconColor: [Expressions.get, 'iconColor'], iconHaloColor: [Expressions.get, 'iconHaloColor'], iconHaloWidth: [Expressions.get, 'iconHaloWidth'], iconHaloBlur: [Expressions.get, 'iconHaloBlur'], // note that web does not support setting this in a fully data driven // way this is a upstream issue textFont: kIsWeb ? null : [ Expressions.caseExpression, [Expressions.has, 'fontNames'], [Expressions.get, 'fontNames'], [ Expressions.literal, ["Open Sans Regular", "Arial Unicode MS Regular"] ], ], textField: [Expressions.get, 'textField'], textSize: [Expressions.get, 'textSize'], textMaxWidth: [Expressions.get, 'textMaxWidth'], textLetterSpacing: [Expressions.get, 'textLetterSpacing'], textJustify: [Expressions.get, 'textJustify'], textAnchor: [Expressions.get, 'textAnchor'], textRotate: [Expressions.get, 'textRotate'], textTransform: [Expressions.get, 'textTransform'], textOffset: [Expressions.get, 'textOffset'], textOpacity: [Expressions.get, 'textOpacity'], textColor: [Expressions.get, 'textColor'], textHaloColor: [Expressions.get, 'textHaloColor'], textHaloWidth: [Expressions.get, 'textHaloWidth'], textHaloBlur: [Expressions.get, 'textHaloBlur'], symbolSortKey: [Expressions.get, 'zIndex'], iconAllowOverlap: _iconAllowOverlap, iconIgnorePlacement: _iconIgnorePlacement, textAllowOverlap: _textAllowOverlap, textIgnorePlacement: _textIgnorePlacement, ) ]; }
19,446
https://github.com/bluzelle/bzapi/blob/master/database/db_dispatch.hpp
Github Open Source
Open Source
Apache-2.0
null
bzapi
bluzelle
C++
Code
258
844
// // Copyright (C) 2019 Bluzelle // // 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. // #pragma once #include <database/db_dispatch_base.hpp> namespace bzapi { // fills in header, sends and tracks outgoing database requests // handles incoming database responses // applies collation policy and forwards acceptable responses // handles response timeout and resend class db_dispatch : public db_dispatch_base, public std::enable_shared_from_this<db_dispatch> { public: db_dispatch(std::shared_ptr<bzn::asio::io_context_base> io_context); void has_uuid(std::shared_ptr<swarm_base> swarm, uuid_t uuid, std::function<void(db_error)> callback) override; void create_uuid(std::shared_ptr<swarm_base> swarm, uuid_t uuid, uint64_t max_size, bool random_evict, std::function<void(db_error)> callback) override; void send_message_to_swarm(std::shared_ptr<swarm_base> swarm, uuid_t uuid, database_msg& msg, send_policy policy, db_response_handler_t handler) override; private: using nonce_t = uint64_t; struct msg_info { std::shared_ptr<swarm_base> swarm; std::shared_ptr<bzn_envelope> request; send_policy policy; uint64_t responses_required; std::shared_ptr<bzn::asio::steady_timer_base> retry_timer; std::shared_ptr<bzn::asio::steady_timer_base> timeout_timer; std::map<uuid_t, database_response> responses; db_response_handler_t handler; }; const std::shared_ptr<bzn::asio::io_context_base> io_context; nonce_t next_nonce = 1; std::map<nonce_t, msg_info> messages; void setup_request_policy(msg_info& info, send_policy policy, nonce_t nonce); void handle_request_timeout(const boost::system::error_code& ec, nonce_t nonce); bool handle_swarm_response(const bzn_envelope& response); bool handle_swarm_error(const bzn_envelope& response); bool qualify_response(msg_info& info, const uuid_t& sender) const; bool responses_are_equal(const database_response& r1, const database_response& r2) const; void setup_client_timeout(nonce_t nonce, msg_info& info); void register_swarm_handler(std::shared_ptr<swarm_base> swarm); }; }
15,297
https://github.com/spiralhalo/canvas/blob/master/src/main/resources/assets/canvas/shaders/pipeline/diffuse.glsl
Github Open Source
Open Source
Apache-2.0
2,021
canvas
spiralhalo
GLSL
Code
288
1,035
#include frex:shaders/api/context.glsl #include frex:shaders/api/world.glsl #include canvas:basic_light_config /****************************************************** canvas:shaders/pipeline/diffuse.glsl ******************************************************/ #if DIFFUSE_SHADING_MODE != DIFFUSE_MODE_NONE varying float pv_diffuse; #endif /** * Formula mimics vanilla lighting for plane-aligned quads and is vaguely * consistent with Phong lighting ambient + diffuse for others. */ float p_diffuseBaked(vec3 normal) { mat3 normalModelMatrix = frx_normalModelMatrix(); // TODO: encode as constants here and below vec3 lv1 = normalize(vec3(0.1, 1.0, -0.3)); // in nether underside is lit like top vec3 secondaryVec = frx_isSkyDarkened() ? vec3(-0.1, -1.0, 0.3) : vec3(-0.1, 1.0, 0.3); vec3 lv2 = normalize(secondaryVec); float l1 = max(0.0, dot(lv1, normal)); float l2 = max(0.0, dot(lv2, normal)); return 0.4 + min(0.6, l1 + l2); } // for testing - not a good way to do it float p_diffuseSky(vec3 normal) { float f = dot(frx_skyLightVector(), normal); f = f > 0.0 ? 0.4 * f : 0.2 * f; return 0.6 + frx_skyLightTransitionFactor() * f; } /** * Offers results similar to vanilla in GUI, assumes a fixed transform. * Vanilla GUI light setup looks like this: * * light(GL_LIGHT0, GL_POSITION, -0.96104145, -0.078606814, -0.2593495, 0 * light(GL_LIGHT0, GL_DIFFUSE, getBuffer(0.6F, 0.6F, 0.6F, 1.0F)); * light(GL_LIGHT0, GL_AMBIENT, getBuffer(0.0F, 0.0F, 0.0F, 1.0F)); * light(GL_LIGHT0, GL_SPECULAR, getBuffer(0.0F, 0.0F, 0.0F, 1.0F)); * * light(GL_LIGHT1, GL_POSITION, -0.26765957, -0.95667744, 0.100838766, 0 * light(GL_LIGHT1, GL_DIFFUSE, getBuffer(0.6F, 0.6F, 0.6F, 1.0F)); * light(GL_LIGHT1, GL_AMBIENT, getBuffer(0.0F, 0.0F, 0.0F, 1.0F)); * light(GL_LIGHT1, GL_SPECULAR, getBuffer(0.0F, 0.0F, 0.0F, 1.0F)); * * glShadeModel(GL_FLAT); * glLightModel(GL_LIGHT_MODEL_AMBIENT, 0.4F, 0.4F, 0.4F, 1.0F); */ float p_diffuseGui(vec3 normal) { normal = normalize(gl_NormalMatrix * normal); float light = 0.4 + 0.6 * clamp(dot(normal.xyz, vec3(-0.96104145, -0.078606814, -0.2593495)), 0.0, 1.0) + 0.6 * clamp(dot(normal.xyz, vec3(-0.26765957, -0.95667744, 0.100838766)), 0.0, 1.0); return min(light, 1.0); } float p_diffuse (vec3 normal) { return frx_isGui() ? p_diffuseGui(normal) : p_diffuseBaked(normal); //return frx_isGui() ? p_diffuseGui(normal) : p_diffuseSky(normal); }
27,264
https://github.com/afshin70/FormFactory/blob/master/FormFactory.Examples.Shared/Examples/AutoCompleteExample.cs
Github Open Source
Open Source
MIT
2,022
FormFactory
afshin70
C#
Code
69
226
using System.Collections.Generic; using System.Globalization; using System.Linq; using FormFactory.Attributes; namespace FormFactory.Examples.Shared.Examples { public class AutoCompleteExample { [Required] [Display(Prompt = "Type to find your location")] public string Location { get; set; } public IEnumerable<string> Location_suggestions() { return CultureInfo.GetCultures(CultureTypes.SpecificCultures) .Select(c => c.Name).Distinct(); } [Required] [Display(Name = "What is your home country?", Prompt = "Type to find your location")] [System.ComponentModel.Description("AJAX suggestions using [SuggestionsUrl(\"...someurl...\")]")] [SuggestionsUrl("/home/CountrySuggestions")] public string CountryViaAjax { get; set; } } }
23,430