hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
b03944a2d8e0877ab49236cfc65945c85c81f5ce
5,835
py
Python
plotting.py
maximiliense/GLC19
5266fa7464f5606c33b29f46de6b4917d2db34c4
[ "MIT" ]
6
2019-01-21T02:49:23.000Z
2019-12-09T03:48:46.000Z
plotting.py
maximiliense/GLC19
5266fa7464f5606c33b29f46de6b4917d2db34c4
[ "MIT" ]
4
2018-12-27T16:40:17.000Z
2019-01-16T08:12:02.000Z
plotting.py
maximiliense/GLC19
5266fa7464f5606c33b29f46de6b4917d2db34c4
[ "MIT" ]
6
2019-01-07T13:47:30.000Z
2019-12-23T12:41:04.000Z
from __future__ import annotations from typing import Optional, TYPE_CHECKING from collections.abc import Collection import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Patch if TYPE_CHECKING: import numpy.typing as npt import pandas as pd def plot_map( *, region: Optional[str] = None, extent: Optional[npt.ArrayLike] = None, ax: Optional[plt.Axes] = None, ) -> plt.Axes: """Plots a map to show the observations on Parameters ---------- region: string, either "fr" or "us" Region to show, France or US. extent: array-like of form [longitude min, longitude max, latitude min, latitude max] Explicit extent of the area to show, e.g., for zooming. ax: plt.Axes Provide an Axes to use instead of creating one. Returns ------- plt.Axes: Returns the used Axes. """ if region == "fr": extent = [-5.5, 10, 41, 52] elif region == "us": extent = [-126, -66, 24, 50] elif region is None and extent is None: raise ValueError("Either region or extent must be set") import cartopy.crs as ccrs import cartopy.feature as cfeature if ax is None: ax = plt.axes(projection=ccrs.PlateCarree()) ax.set_extent(extent, crs=ccrs.PlateCarree()) states_provinces = cfeature.NaturalEarthFeature( category="cultural", name="admin_0_countries", scale="10m", facecolor="none", ) ax.add_feature(cfeature.LAND) ax.add_feature(cfeature.COASTLINE) ax.add_feature(states_provinces, edgecolor="gray") ax.gridlines( draw_labels=True, dms=True, x_inline=False, y_inline=False, linestyle="--" ) ax.set_aspect(1.25) return ax def visualize_observation_patch( patch: tuple[npt.NDArray, npt.NDArray, npt.NDArray, npt.NDArray], *, observation_data: Optional[pd.Series] = None, landcover_labels: Optional[Collection] = None, return_fig: bool = False, ) -> Optional[plt.Figure]: """Plots patch data Parameters ---------- patch : tuple of size 4 containing 2d array-like objects Patch data as returned by `load_patch`. observation_data : pandas Series Row of the dataframe containing the data of the observation. landcover_labels : list Labels corresponding to the landcover codes. return_fig : boolean If True, returns the created plt.Figure object Returns ------- fig : plt.Figure If return_fig is True, the used plt.Figure object Returns """ rgb_patch, near_ir_patch, altitude_patch, landcover_patch = patch if landcover_labels is None: n_labels = np.max(landcover_patch) + 1 landcover_labels = np.arange(n_labels) cmap = plt.cm.get_cmap("viridis", len(landcover_labels)) legend_elements = [] for landcover_label, color in zip(landcover_labels, cmap.colors): legend_elements.append(Patch(color=color, label=landcover_label)) if observation_data is not None: import cartopy.crs as ccrs localisation = observation_data[["latitude", "longitude"]] species_id = getattr(observation_data, "species_id", None) species_name = getattr(observation_data, "GBIF_species_name", None) kingdom_name = getattr(observation_data, "GBIF_kingdom_name", None) fig = plt.figure(figsize=(15, 10)) gs = fig.add_gridspec(1, 2, width_ratios=[1, 2]) gs1 = gs[0].subgridspec(1, 1) ax = fig.add_subplot(gs1[0], projection=ccrs.PlateCarree()) region = "fr" if localisation[1] > -6 else "us" plot_map(region=region, ax=ax) ax.scatter( localisation[1], localisation[0], marker="o", s=100, transform=ccrs.PlateCarree(), ) ax.set_title("Observation localisation") s = "Observation id: {}".format(observation_data.name) s += "\nLocalisation: {:.3f}, {:.3f}".format(*localisation) if species_id: s += "\nSpecies id: {}".format(species_id) if species_name: s += "\nSpecies name: {}".format(species_name) if kingdom_name: s += "\nKingdom: {}".format(kingdom_name) pos = ax.get_position() fig.text( pos.x1 - pos.x0, pos.y0 - 0.2 * (pos.y1 - pos.y0), s, ha="center", va="top" ) gs2 = gs[1].subgridspec(2, 2) axes = np.asarray([fig.add_subplot(gs) for gs in gs2]) else: fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(13, 8)) axes = axes.ravel() axes_iter = iter(axes) ax = next(axes_iter) ax.imshow(rgb_patch) ax.set_title("RGB image") ax = next(axes_iter) ax.imshow(near_ir_patch, cmap="gray") ax.set_title("Near-IR image") ax = next(axes_iter) vmin = round(altitude_patch.min(), -1) vmax = round(altitude_patch.max(), -1) + 10 ax.imshow(altitude_patch) CS2 = ax.contour( altitude_patch, levels=np.arange(vmin, vmax, step=10), colors="w", ) ax.clabel(CS2, inline=True, fontsize=10) ax.set_aspect("equal") ax.set_title("Altitude (in meters)") ax = next(axes_iter) ax.imshow( landcover_patch, interpolation="none", cmap=cmap, vmin=0, vmax=len(legend_elements), ) ax.set_title("Land cover") visible_landcover_categories = np.unique(landcover_patch) legend = [legend_elements[i] for i in visible_landcover_categories] ax.legend( handles=legend, handlelength=0.75, bbox_to_anchor=(1, 0.5), loc="center left" ) for ax in axes: ax.axis("off") if observation_data is None: fig.tight_layout() if return_fig: return fig else: return None
29.321608
89
0.625364
24e971c94e49ba1a61c4ff5c0434737cd1ffd678
16,284
cc
C++
standalone/cache_counters.cc
Hello-World-Test12/gemmlowp
13d57703abca3005d97b19df1f2db731607a7dc2
[ "Apache-2.0" ]
1,609
2015-07-07T00:48:28.000Z
2022-03-31T14:54:05.000Z
standalone/cache_counters.cc
Hello-World-Test12/gemmlowp
13d57703abca3005d97b19df1f2db731607a7dc2
[ "Apache-2.0" ]
119
2015-08-06T12:21:10.000Z
2022-02-15T15:03:56.000Z
standalone/cache_counters.cc
Hello-World-Test12/gemmlowp
13d57703abca3005d97b19df1f2db731607a7dc2
[ "Apache-2.0" ]
461
2015-07-13T20:46:13.000Z
2022-03-31T14:10:36.000Z
#include <asm/unistd.h> #include <linux/perf_event.h> #include <sys/ioctl.h> #include <unistd.h> #include <algorithm> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <random> #ifndef __aarch64__ #error This program is for 64-bit ARM only. #endif struct PerfEvent { perf_event_attr pe; int fd = -1; PerfEvent(std::uint32_t type, std::uint64_t config) { memset(&pe, 0, sizeof(pe)); pe.size = sizeof(pe); pe.type = type; pe.config = config; pe.disabled = 1; pe.exclude_kernel = 1; pe.exclude_hv = 1; fd = syscall(__NR_perf_event_open, &pe, 0, -1, -1, 0); if (fd == -1) { fprintf(stderr, "perf_event_open failed for config 0x%lx\n", config); abort(); } } void Start() { ioctl(fd, PERF_EVENT_IOC_RESET, 0); ioctl(fd, PERF_EVENT_IOC_ENABLE, 0); } std::int64_t Stop() { ioctl(fd, PERF_EVENT_IOC_DISABLE, 0); std::int64_t count = 0; read(fd, &count, sizeof(count)); return count; } ~PerfEvent() { close(fd); } }; struct ArmPmuEvent : PerfEvent { static constexpr std::uint16_t L1I_CACHE_REFILL = 0x01; static constexpr std::uint16_t L1I_TLB_REFILL = 0x02; static constexpr std::uint16_t L1D_CACHE_REFILL = 0x03; static constexpr std::uint16_t L1D_CACHE = 0x04; static constexpr std::uint16_t L1D_TLB_REFILL = 0x05; static constexpr std::uint16_t LD_RETIRED = 0x06; static constexpr std::uint16_t ST_RETIRED = 0x07; static constexpr std::uint16_t INST_RETIRED = 0x08; static constexpr std::uint16_t EXC_TAKEN = 0x09; static constexpr std::uint16_t EXC_RETURN = 0x0A; static constexpr std::uint16_t CID_WRITE_RETIRED = 0x0B; static constexpr std::uint16_t PC_WRITE_RETIRED = 0x0C; static constexpr std::uint16_t BR_IMMED_RETIRED = 0x0D; static constexpr std::uint16_t BR_RETURN_RETIRED = 0x0E; static constexpr std::uint16_t UNALIGNED_LDST_RETIRED = 0x0F; static constexpr std::uint16_t BR_MIS_PRED = 0x10; static constexpr std::uint16_t CPU_CYCLES = 0x11; static constexpr std::uint16_t BR_PRED = 0x12; static constexpr std::uint16_t MEM_ACCESS = 0x13; static constexpr std::uint16_t L1I_CACHE = 0x14; static constexpr std::uint16_t L1D_CACHE_WB = 0x15; static constexpr std::uint16_t L2D_CACHE = 0x16; static constexpr std::uint16_t L2D_CACHE_REFILL = 0x17; static constexpr std::uint16_t L2D_CACHE_WB = 0x18; static constexpr std::uint16_t BUS_ACCESS = 0x19; static constexpr std::uint16_t MEMORY_ERROR = 0x1A; static constexpr std::uint16_t INST_SPEC = 0x1B; static constexpr std::uint16_t TTBR_WRITE_RETIRED = 0x1C; static constexpr std::uint16_t BUS_CYCLES = 0x1D; static constexpr std::uint16_t CHAIN = 0x1E; static constexpr std::uint16_t L1D_CACHE_ALLOCATE = 0x1F; static constexpr std::uint16_t L2D_CACHE_ALLOCATE = 0x20; static constexpr std::uint16_t BR_RETIRED = 0x21; static constexpr std::uint16_t BR_MIS_PRED_RETIRED = 0x22; static constexpr std::uint16_t STALL_FRONTEND = 0x23; static constexpr std::uint16_t STALL_BACKEND = 0x24; static constexpr std::uint16_t L1D_TLB = 0x25; static constexpr std::uint16_t L1I_TLB = 0x26; static constexpr std::uint16_t L2I_CACHE = 0x27; static constexpr std::uint16_t L2I_CACHE_REFILL = 0x28; static constexpr std::uint16_t L3D_CACHE_ALLOCATE = 0x29; static constexpr std::uint16_t L3D_CACHE_REFILL = 0x2A; static constexpr std::uint16_t L3D_CACHE = 0x2B; static constexpr std::uint16_t L3D_CACHE_WB = 0x2C; static constexpr std::uint16_t L2D_TLB_REFILL = 0x2D; static constexpr std::uint16_t L2I_TLB_REFILL = 0x2E; static constexpr std::uint16_t L2D_TLB = 0x2F; static constexpr std::uint16_t L2I_TLB = 0x30; static constexpr std::uint16_t LL_CACHE = 0x32; static constexpr std::uint16_t LL_CACHE_MISS = 0x33; static constexpr std::uint16_t DTLB_WALK = 0x34; static constexpr std::uint16_t LL_CACHE_RD = 0x36; static constexpr std::uint16_t LL_CACHE_MISS_RD = 0x37; static constexpr std::uint16_t L1D_CACHE_RD = 0x40; static constexpr std::uint16_t L1D_CACHE_REFILL_RD = 0x42; static constexpr std::uint16_t L1D_TLB_REFILL_RD = 0x4C; static constexpr std::uint16_t L1D_TLB_RD = 0x4E; static constexpr std::uint16_t L2D_CACHE_RD = 0x50; static constexpr std::uint16_t L2D_CACHE_REFILL_RD = 0x52; static constexpr std::uint16_t BUS_ACCESS_RD = 0x60; static constexpr std::uint16_t MEM_ACCESS_RD = 0x66; static constexpr std::uint16_t L3D_CACHE_RD = 0xA0; static constexpr std::uint16_t L3D_CACHE_REFILL_RD = 0xA2; ArmPmuEvent(std::uint16_t number) : PerfEvent(PERF_TYPE_RAW, number) {} }; struct CacheCounts { int ld_retired = 0; int mem_access = 0; int ll_cache = 0; int ll_cache_miss = 0; int l1d_cache = 0; int l1d_cache_refill = 0; int l2d_cache = 0; int l2d_cache_refill = 0; int l3d_cache = 0; int l3d_cache_refill = 0; }; void PrintCacheCounts(const CacheCounts& cache_counts) { printf("ld_retired = %d\n", cache_counts.ld_retired); printf("mem_access = %d\n", cache_counts.mem_access); printf("ll_cache = %d\n", cache_counts.ll_cache); printf("ll_cache_miss = %d\n", cache_counts.ll_cache_miss); printf("l1d_cache = %d\n", cache_counts.l1d_cache); printf("l1d_cache_refill = %d\n", cache_counts.l1d_cache_refill); printf("l2d_cache = %d\n", cache_counts.l2d_cache); printf("l2d_cache_refill = %d\n", cache_counts.l2d_cache_refill); printf("l3d_cache = %d\n", cache_counts.l3d_cache); printf("l3d_cache_refill = %d\n", cache_counts.l3d_cache_refill); } void Workload(int accesses, int size, std::uint8_t* buf) { // The main reason to do this in assembly is an attempt to make sense // of instruction count counters, such as LD_RETIRED. // Also, if we did this in C++, we would need to be watchful of the compiler // optimizing away operations whose result isn't consumed. // // Note that TWO separate tricks are needed here to prevent Cortex-A76 // speculative execution om prefetching data from future loop iterations: // 1. A data-dependency whereby the pointers being dereferenced at the // next loop iteration depend on values loaded at the current iteration. // That is the role of 'dummy'. // 2. A pseudo-random sequence. This is the role of register w0, // where we implement a simple xorshift pseudorandom generator. // BOTH of these tricks are needed: if we disable just one of them, // Cortex-A76 successfully speculates some addresses, resulting in different // L3 / DRAM hit percentages on large sizes. std::uint64_t dummy = 123456789; asm volatile( // w0 := xorshift RNG state. Must be nonzero. "mov w0, #1\n" "1:\n" // xorshift RNG iteration: update w0 with the next pseudorandom value // in [1 .. 2^32-1]. // This pseudorandomness is crucial to preventing speculative execution // on Cortex-A76 from prefetching data from future loop iterations. "eor w0, w0, w0, lsl #13\n" "eor w0, w0, w0, lsr #17\n" "eor w0, w0, w0, lsl #5\n" // w1 := size - 1 = size mask (size is required to be power-of-two). "sub w1, %w[size], #1\n" // w2 := (pseudorandom value w0) xor (data-dependent sum). "eor w2, w0, %w[dummy]\n" // w1 := w2 modulo size "and w1, w2, w1\n" // align w1 "and w1, w1, #-64\n" // load at offset w1, again using x1 as destination. "ldr x1, [%[buf], w1, uxtw]\n" // Update our dummy so it depends on the value we have just loaded. // This data-dependency is key to preventing speculative execution on // Cortex-A76 from prefetching data from future loop iterations. "add %[dummy], %[dummy], w1, uxtw\n" // loop back. "subs %w[accesses], %w[accesses], #1\n" "bne 1b\n" : [ accesses ] "+r"(accesses), [ dummy ] "+r"(dummy) : [ size ] "r"(size), [ buf ] "r"(buf) : "memory", "cc", "x0", "x1", "x2"); } void MeasureCacheCounts(int accesses, int size, std::uint8_t* buf, CacheCounts* cache_counts) { const bool only_reads = getenv("ONLY_READS"); ArmPmuEvent ld_retired(ArmPmuEvent::LD_RETIRED); ArmPmuEvent mem_access(only_reads ? ArmPmuEvent::MEM_ACCESS_RD : ArmPmuEvent::MEM_ACCESS); ArmPmuEvent ll_cache(only_reads ? ArmPmuEvent::LL_CACHE_RD : ArmPmuEvent::LL_CACHE); ArmPmuEvent ll_cache_miss(only_reads ? ArmPmuEvent::LL_CACHE_MISS_RD : ArmPmuEvent::LL_CACHE_MISS); ArmPmuEvent l1d_cache(only_reads ? ArmPmuEvent::L1D_CACHE_RD : ArmPmuEvent::L1D_CACHE); ArmPmuEvent l1d_cache_refill(only_reads ? ArmPmuEvent::L1D_CACHE_REFILL_RD : ArmPmuEvent::L1D_CACHE_REFILL); ArmPmuEvent l2d_cache(only_reads ? ArmPmuEvent::L2D_CACHE_RD : ArmPmuEvent::L2D_CACHE); ArmPmuEvent l2d_cache_refill(only_reads ? ArmPmuEvent::L2D_CACHE_REFILL_RD : ArmPmuEvent::L2D_CACHE_REFILL); ArmPmuEvent l3d_cache(only_reads ? ArmPmuEvent::L3D_CACHE_RD : ArmPmuEvent::L3D_CACHE); ArmPmuEvent l3d_cache_refill(only_reads ? ArmPmuEvent::L3D_CACHE_REFILL_RD : ArmPmuEvent::L3D_CACHE_REFILL); ld_retired.Start(); mem_access.Start(); ll_cache.Start(); ll_cache_miss.Start(); l1d_cache.Start(); l1d_cache_refill.Start(); l2d_cache.Start(); l2d_cache_refill.Start(); l3d_cache.Start(); l3d_cache_refill.Start(); Workload(accesses, size, buf); cache_counts->ld_retired = ld_retired.Stop(); cache_counts->mem_access = mem_access.Stop(); cache_counts->ll_cache = ll_cache.Stop(); cache_counts->ll_cache_miss = ll_cache_miss.Stop(); cache_counts->l1d_cache = l1d_cache.Stop(); cache_counts->l1d_cache_refill = l1d_cache_refill.Stop(); cache_counts->l2d_cache = l2d_cache.Stop(); cache_counts->l2d_cache_refill = l2d_cache_refill.Stop(); cache_counts->l3d_cache = l3d_cache.Stop(); cache_counts->l3d_cache_refill = l3d_cache_refill.Stop(); } struct PieChart { // How many accesses were recorded, total? The other fields must sum to that. int total; // How many accesses were serviced with the typical cost of a L1 cache hit? int l1_hits; // How many accesses were serviced with the typical cost of a L2 cache hit? int l2_hits; // How many accesses were serviced with the typical cost of a L3 cache hit? int l3_hits; // How many accesses were serviced with the typical cost of a DRAM access? int dram_hits; ~PieChart() { // Consistency check if (total != l1_hits + l2_hits + l3_hits + dram_hits) { fprintf(stderr, "inconsistent pie-chart\n"); abort(); } } }; struct Hypothesis { virtual ~Hypothesis() {} virtual const char* Name() const = 0; virtual void Analyze(const CacheCounts& cache_counts, PieChart* pie) const = 0; }; struct Hypothesis1 : Hypothesis { const char* Name() const override { return "Hypothesis1"; } void Analyze(const CacheCounts& cache_counts, PieChart* pie) const override { pie->total = cache_counts.l1d_cache + cache_counts.l1d_cache_refill; pie->l1_hits = cache_counts.l1d_cache - cache_counts.l2d_cache_refill - cache_counts.l3d_cache_refill; pie->l2_hits = cache_counts.l1d_cache_refill; pie->l3_hits = cache_counts.l2d_cache_refill; pie->dram_hits = cache_counts.l3d_cache_refill; } }; struct Hypothesis2 : Hypothesis { const char* Name() const override { return "Hypothesis2"; } void Analyze(const CacheCounts& cache_counts, PieChart* pie) const override { pie->total = cache_counts.l1d_cache; pie->l1_hits = cache_counts.l1d_cache - cache_counts.l2d_cache; pie->l2_hits = cache_counts.l2d_cache - cache_counts.l3d_cache; pie->l3_hits = cache_counts.l3d_cache - cache_counts.l3d_cache_refill; pie->dram_hits = cache_counts.l3d_cache_refill; } }; struct Hypothesis3 : Hypothesis { const char* Name() const override { return "Hypothesis3"; } void Analyze(const CacheCounts& cache_counts, PieChart* pie) const override { pie->total = cache_counts.l1d_cache; int corrected_l2 = std::min(cache_counts.l2d_cache, cache_counts.l1d_cache); int corrected_l3 = std::min(cache_counts.l3d_cache, corrected_l2); pie->l1_hits = cache_counts.l1d_cache - corrected_l2; pie->l2_hits = corrected_l2 - corrected_l3; pie->l3_hits = corrected_l3 - cache_counts.l3d_cache_refill; pie->dram_hits = cache_counts.l3d_cache_refill; } }; struct Hypothesis4 : Hypothesis { const char* Name() const override { return "Hypothesis4"; } void Analyze(const CacheCounts& cache_counts, PieChart* pie) const override { pie->total = cache_counts.l1d_cache; pie->l1_hits = cache_counts.l1d_cache - cache_counts.l1d_cache_refill; pie->l2_hits = cache_counts.l1d_cache_refill - cache_counts.l2d_cache_refill; pie->l3_hits = cache_counts.l2d_cache_refill - cache_counts.l3d_cache_refill; pie->dram_hits = cache_counts.l3d_cache_refill; } }; struct Hypothesis5 : Hypothesis { const char* Name() const override { return "Hypothesis5"; } void Analyze(const CacheCounts& cache_counts, PieChart* pie) const override { pie->l1_hits = std::max(0, cache_counts.l1d_cache - cache_counts.l1d_cache_refill); pie->l2_hits = std::max( 0, cache_counts.l1d_cache_refill - cache_counts.l2d_cache_refill); const int l3_misses = std::max(cache_counts.ll_cache_miss, cache_counts.l3d_cache_refill); pie->l3_hits = std::max(0, cache_counts.l2d_cache_refill - l3_misses); pie->dram_hits = l3_misses; pie->total = pie->l1_hits + pie->l2_hits + pie->l3_hits + pie->dram_hits; } }; void PrintPieChart(const PieChart& pie) { printf("total accesses: %d\n", pie.total); double l1_hits_pct = 100. * pie.l1_hits / pie.total; double l2_hits_pct = 100. * pie.l2_hits / pie.total; double l3_hits_pct = 100. * pie.l3_hits / pie.total; double dram_hits_pct = 100. * pie.dram_hits / pie.total; printf("L1 hits: %.2f%%\n", l1_hits_pct); printf("L2 hits: %.2f%%\n", l2_hits_pct); printf("L1/2 hits: %.2f%%\n", l1_hits_pct + l2_hits_pct); printf("L3 hits: %.2f%%\n", l3_hits_pct); printf("L1/2/3 hits: %.2f%%\n", l1_hits_pct + l2_hits_pct + l3_hits_pct); printf("DRAM hits: %.2f%%\n", dram_hits_pct); } void PrintPieChartCsvNoNewline(const PieChart& pie) { double l1_hits_pct = 100. * pie.l1_hits / pie.total; double l2_hits_pct = 100. * pie.l2_hits / pie.total; double l3_hits_pct = 100. * pie.l3_hits / pie.total; double dram_hits_pct = 100. * pie.dram_hits / pie.total; printf("%.2f,%.2f,%.2f,%.2f", l1_hits_pct, l2_hits_pct, l3_hits_pct, dram_hits_pct); } void Study(int accesses, int size, std::uint8_t* buf) { CacheCounts cache_counts; MeasureCacheCounts(accesses, size, buf, &cache_counts); const Hypothesis* hypotheses[] = { new Hypothesis5, new Hypothesis4, new Hypothesis3, new Hypothesis2, new Hypothesis1, }; if (getenv("DUMP_CSV")) { printf("%d", size); for (const Hypothesis* hypothesis : hypotheses) { printf(","); PieChart pie; hypothesis->Analyze(cache_counts, &pie); PrintPieChartCsvNoNewline(pie); } printf("\n"); } else { printf("\n\n\naccesses=%d, size=%d:\n", accesses, size); printf("\nCache counts:\n"); PrintCacheCounts(cache_counts); for (const Hypothesis* hypothesis : hypotheses) { printf("\n%s:\n", hypothesis->Name()); PieChart pie; hypothesis->Analyze(cache_counts, &pie); PrintPieChart(pie); } } fflush(stdout); for (const Hypothesis* hypothesis : hypotheses) { delete hypothesis; } } int main() { const int kMinSize = 1 << 12; const int kMaxSize = 1 << 24; const int kAccesses = 1e8; void* buf_void = nullptr; posix_memalign(&buf_void, 64, kMaxSize); std::uint8_t* buf = static_cast<std::uint8_t*>(buf_void); std::default_random_engine random_engine; for (int i = 0; i < kMaxSize; i++) { buf[i] = random_engine(); } for (int size = kMinSize; size <= kMaxSize; size *= 2) { Study(kAccesses, size, buf); } delete[] buf; }
40.207407
80
0.694117
7900c7d22392aeb2b58a780f63ca227a1ceee83a
146
rb
Ruby
app/models/sector.rb
Jberma23/Mod_1_project
e9f8838f7bf85e60f8e7a679527580a930c618e2
[ "MIT" ]
null
null
null
app/models/sector.rb
Jberma23/Mod_1_project
e9f8838f7bf85e60f8e7a679527580a930c618e2
[ "MIT" ]
1
2020-06-25T07:00:56.000Z
2020-06-25T07:00:56.000Z
app/models/sector.rb
Jberma23/Mod_1_project
e9f8838f7bf85e60f8e7a679527580a930c618e2
[ "MIT" ]
null
null
null
class Sector < ActiveRecord::Base has_many :departments has_many :organizations, through: :departments has_many :jobs, through: :departments end
24.333333
46
0.808219
4fc8243f27d21613e177f051da0d5fcc3fd9df00
8,299
rb
Ruby
spec/requests/post_token_spec.rb
jgarber623/authenticate.computer
b5581c369cc7be3904e9ac86c6eb3200ac4cb7cd
[ "MIT" ]
null
null
null
spec/requests/post_token_spec.rb
jgarber623/authenticate.computer
b5581c369cc7be3904e9ac86c6eb3200ac4cb7cd
[ "MIT" ]
133
2018-09-24T07:27:15.000Z
2022-03-30T22:23:51.000Z
spec/requests/post_token_spec.rb
jgarber623/authenticate.computer
b5581c369cc7be3904e9ac86c6eb3200ac4cb7cd
[ "MIT" ]
null
null
null
RSpec.describe AuthenticateComputer, 'POST /token', redis: true do let(:grant_type) { 'authorization_code' } let(:code) { SecureRandom.hex(32) } let(:client_id) { 'https://client_id.example.com/' } let(:redirect_uri) { 'https://me.example.com/auth' } let(:me) { 'https://me.example.com/' } let(:error) { 'invalid_request' } let(:error_hash) do { error: error, error_description: error_description } end before do header 'Accept', 'application/json' end context 'when validating params' do context 'when params[:grant_type] is not present' do let(:error_description) { '400 Bad Request: Parameter grant_type is required and cannot be blank. Please try again.' } it 'renders the 400 JSON' do post '/token' expect(last_response.status).to eq(400) expect(last_response.body).to eq(error_hash.to_json) end end context 'when params[:grant_type] is not valid' do let(:error_description) { '400 Bad Request: Parameter grant_type value "foo" must match authorization_code. Please try again.' } it 'renders the 400 JSON' do post '/token', grant_type: 'foo' expect(last_response.status).to eq(400) expect(last_response.body).to eq(error_hash.to_json) end end context 'when params[:code] is not present' do let(:error_description) { '400 Bad Request: Parameter code is required and cannot be blank. Please try again.' } it 'renders the 400 JSON' do post '/token', grant_type: grant_type expect(last_response.status).to eq(400) expect(last_response.body).to eq(error_hash.to_json) end end context 'when params[:code] is invalid' do let(:error_description) { '400 Bad Request: Parameter code value "foo" must match format ^[a-f0-9]{64}$. Please try again.' } it 'renders the 400 JSON' do post '/token', grant_type: grant_type, code: 'foo' expect(last_response.status).to eq(400) expect(last_response.body).to eq(error_hash.to_json) end end context 'when params[:client_id] is not present' do let(:error_description) { '400 Bad Request: Parameter client_id is required and cannot be blank. Please try again.' } it 'renders the 400 JSON' do post '/token', grant_type: grant_type, code: code expect(last_response.status).to eq(400) expect(last_response.body).to eq(error_hash.to_json) end end context 'when params[:client_id] is invalid' do let(:error_description) { '400 Bad Request: Parameter client_id value "foo" must match format ^https?://.*. Please try again.' } it 'renders the 400 JSON' do post '/token', grant_type: grant_type, code: code, client_id: 'foo' expect(last_response.status).to eq(400) expect(last_response.body).to eq(error_hash.to_json) end end context 'when params[:redirect_uri] is not present' do let(:error_description) { '400 Bad Request: Parameter redirect_uri is required and cannot be blank. Please try again.' } it 'renders the 400 JSON' do post '/token', grant_type: grant_type, code: code, client_id: client_id expect(last_response.status).to eq(400) expect(last_response.body).to eq(error_hash.to_json) end end context 'when params[:redirect_uri] is invalid' do let(:error_description) { '400 Bad Request: Parameter redirect_uri value "foo" must match format ^https?://.*. Please try again.' } it 'renders the 400 JSON' do post '/token', grant_type: grant_type, code: code, client_id: client_id, redirect_uri: 'foo' expect(last_response.status).to eq(400) expect(last_response.body).to eq(error_hash.to_json) end end context 'when params[:me] is not present' do let(:error_description) { '400 Bad Request: Parameter me is required and cannot be blank. Please try again.' } it 'renders the 400 JSON' do post '/token', grant_type: grant_type, code: code, client_id: client_id, redirect_uri: redirect_uri expect(last_response.status).to eq(400) expect(last_response.body).to eq(error_hash.to_json) end end context 'when params[:me] is invalid' do let(:error_description) { '400 Bad Request: Parameter me value "foo" must match format ^https?://.*. Please try again.' } it 'renders the 400 JSON' do post '/token', grant_type: grant_type, code: code, client_id: client_id, redirect_uri: redirect_uri, me: 'foo' expect(last_response.status).to eq(400) expect(last_response.body).to eq(error_hash.to_json) end end end context 'when verifying authorization code' do let(:authorization_endpoint) { 'https://auth.example.com/auth' } let(:populated_parameters) do { grant_type: grant_type, code: code, client_id: client_id, redirect_uri: redirect_uri, me: me } end context 'when authorization endpoint discovery request fails' do let(:error) { 'server_error' } let(:error_description) { '500 Internal Server Error: There was a problem fulfilling the request. Please try again later.' } before do stub_request(:get, me).to_timeout end it 'renders the 500 JSON' do post '/token', populated_parameters expect(last_response.status).to eq(500) expect(last_response.body).to eq(error_hash.to_json) end end context 'when authorization code verification request fails' do let(:error) { 'server_error' } let(:error_description) { '500 Internal Server Error: There was a problem fulfilling the request. Please try again later.' } before do stub_request(:get, me).to_return(headers: { 'Content-Type': 'text/html', Link: %(<#{authorization_endpoint}>; rel="authorization_endpoint") }) stub_request(:post, authorization_endpoint).to_timeout end it 'renders the 500 JSON' do post '/token', populated_parameters expect(last_response.status).to eq(500) expect(last_response.body).to eq(error_hash.to_json) end end context 'when authorization code is not verified' do let(:error) { 'invalid_request' } let(:error_description) { '400 Bad Request: Authorization code verification could not be completed. Please try again.' } before do stub_request(:get, me).to_return(headers: { 'Content-Type': 'text/html', Link: %(<#{authorization_endpoint}>; rel="authorization_endpoint") }) stub_request(:post, authorization_endpoint).to_return(body: error_hash.to_json, status: 400) end it 'renders the 400 JSON' do post '/token', populated_parameters expect(last_response.status).to eq(400) expect(last_response.body).to eq(error_hash.to_json) end end context 'when scope is not present' do let(:error) { 'invalid_request' } let(:error_description) { '400 Bad Request: The requested scope is invalid. Please try again.' } before do stub_request(:get, me).to_return(headers: { 'Content-Type': 'text/html', Link: %(<#{authorization_endpoint}>; rel="authorization_endpoint") }) stub_request(:post, authorization_endpoint).to_return(body: { me: me, scope: '' }.to_json) end it 'renders the 400 JSON' do post '/token', populated_parameters expect(last_response.status).to eq(400) expect(last_response.body).to eq(error_hash.to_json) end end context 'when scope is valid' do before do stub_request(:get, me).to_return(headers: { 'Content-Type': 'text/html', Link: %(<#{authorization_endpoint}>; rel="authorization_endpoint") }) stub_request(:post, authorization_endpoint).to_return(body: { me: me, scope: 'create update delete' }.to_json) allow(SecureRandom).to receive(:hex).and_return(code) end it 'returns the response JSON' do post '/token', populated_parameters expect(last_response.status).to eq(200) expect(last_response.body).to eq({ access_token: code, token_type: 'Bearer', scope: 'create update delete', me: me }.to_json) end end end end
36.082609
150
0.664779
da3a57c7f13faa1005db58d59a8a4ef9bd199255
193
rb
Ruby
lib/chef/knife/prepare.rb
DQNEO/knife-solo
043e61a647f61986d9cd88c347efbcd4b9f72f7d
[ "MIT" ]
185
2015-01-04T16:12:09.000Z
2021-06-03T18:46:44.000Z
lib/chef/knife/prepare.rb
DQNEO/knife-solo
043e61a647f61986d9cd88c347efbcd4b9f72f7d
[ "MIT" ]
145
2015-01-03T08:23:51.000Z
2021-03-07T14:08:25.000Z
lib/chef/knife/prepare.rb
DQNEO/knife-solo
043e61a647f61986d9cd88c347efbcd4b9f72f7d
[ "MIT" ]
90
2015-01-03T08:27:07.000Z
2022-03-24T23:37:12.000Z
require 'chef/knife/solo_prepare' require 'knife-solo/deprecated_command' class Chef class Knife class Prepare < SoloPrepare include KnifeSolo::DeprecatedCommand end end end
17.545455
42
0.756477
85fd72f423972e2a7d3c5c22a5175acfa5250b31
2,545
sh
Shell
info.sh
japanoise/scripts-dotfiles
0f063ebc2b88d19a64a223cc5a8708a9ec5328ad
[ "MIT" ]
null
null
null
info.sh
japanoise/scripts-dotfiles
0f063ebc2b88d19a64a223cc5a8708a9ec5328ad
[ "MIT" ]
null
null
null
info.sh
japanoise/scripts-dotfiles
0f063ebc2b88d19a64a223cc5a8708a9ec5328ad
[ "MIT" ]
null
null
null
#!/bin/sh # Forked from z3bra's info.sh # Runs in bash, because dash doesn't like colours. gitdir=https://github.com/japanoise/ myblog=http://blog.kingdomofmysteries.xyz/ if emerge --help >/dev/null 2>&1; then #system is Gentoo or variant system=Gentoo if ! eix --help >/dev/null 2>&1; then echo "This script requires app-portage/eix to be installed" exit 1 fi pkgnum=$(EIX_LIMIT=0 eix '-I*' --format '<installedversions:NAMEVERSION>' | wc -l) if [ -z "$birthd" ] then birthd=$(sudo sed -e'1q' /var/log/emerge.log | sed -e's/\([0-9]*\):.*/@\1/' | date -f- +"%Y.%m.%d") echo "It would be best if you put birthd=$birthd after the #! line in $0 so I don't have to ask you for your password" >&2 fi else if pacman -h >/dev/null 2>&1; then #system is Arch; this will need testing system=Arch pkgnum=`pacman -Q|wc -l` birthd=`sed -n '1s/^\[\([0-9-]*\).*$/\1/p' /var/log/pacman.log | tr - .` fi fi reset=$(printf '\033[0m') c00=$(printf '\033[0;30m') c01=$(printf '\033[0;31m') c02=$(printf '\033[0;32m') c03=$(printf '\033[0;33m') c04=$(printf '\033[0;34m') c05=$(printf '\033[0;35m') c06=$(printf '\033[0;36m') c07=$(printf '\033[0;37m') c08=$(printf '\033[1;30m') c09=$(printf '\033[1;31m') c10=$(printf '\033[1;32m') c11=$(printf '\033[1;33m') c12=$(printf '\033[1;34m') c13=$(printf '\033[1;35m') c14=$(printf '\033[1;36m') c15=$(printf '\033[1;37m') f0=$(printf '\033[1;30m') f1=$(printf '\033[1;37m') f2=$(printf '\033[0;37m') kernel=$(uname -rmo) cpuspe="$(sed -n '/model\ name/s/^.*:\ //p' /proc/cpuinfo | uniq) (x$(nproc))" if [ -n "$DISPLAY" ]; then wmname=$(xprop -root _NET_WM_NAME|cut -d\" -f2) termfn=$(sed -n 's/^[^!]*font: xft:\([^:]*\).*/\1/p' ~/.Xresources|sed 1q) systfn=$(sed -n 's/^.*font.*"\(.*\)".*$/\1/p' ~/.gtkrc-2.0) else wmname="none" termfn="none" systfn="none" fi cat << EOF ${c00}▉▉ | ${f1}OS ${f0}........... $f2$system ${c08} ▉▉| ${f1}name ${f0}......... $f2${HOSTNAME:-$(hostname)} ${c01}▉▉ | ${f1}birth day${f0}..... $f2$birthd ${c09} ▉▉| ${f1}packages ${f0}..... $f2$pkgnum ${c02}▉▉ | ${c10} ▉▉| ${f1}wm ${f0}........... $f2$wmname ${c03}▉▉ | ${f1}shell ${f0}........ $f2$SHELL ${c11} ▉▉| ${f1}terminal ${f0}..... $f2$TERM ${c04}▉▉ | ${f1}term font ${f0}.... $f2$termfn ${c12} ▉▉| ${f1}system font ${f0}.. $f2$systfn ${c05}▉▉ | ${c13} ▉▉| ${f1}kernel ${f0}....... $f2$kernel ${c06}▉▉ | ${f1}processor ${f0}.... $f2$cpuspe ${c14} ▉▉| ${c07}▉▉ | ${f1}blog ${f0}......... $f2$myblog ${c15} ▉▉| ${f1}git repos ${f0}.... $f2$gitdir${reset} EOF
30.662651
124
0.555599
01a6dcdb84051cd9c4fac36ea556f1359e630b6d
367
rb
Ruby
app/services/create_admin_service.rb
momotofu/lti_starter_app
9eaf6992f0f8f94565de531e7902634696f4c618
[ "MIT" ]
41
2016-10-17T18:38:28.000Z
2022-03-16T01:29:31.000Z
app/services/create_admin_service.rb
momotofu/lti_starter_app
9eaf6992f0f8f94565de531e7902634696f4c618
[ "MIT" ]
269
2016-10-27T17:46:25.000Z
2022-03-22T04:39:48.000Z
app/services/create_admin_service.rb
momotofu/lti_starter_app
9eaf6992f0f8f94565de531e7902634696f4c618
[ "MIT" ]
11
2016-10-24T19:51:36.000Z
2022-03-21T23:59:17.000Z
class CreateAdminService def call user = User.find_or_initialize_by(email: Rails.application.secrets.admin_email) user.password = Rails.application.secrets.admin_password user.password_confirmation = Rails.application.secrets.admin_password user.confirm unless user.confirmed? user.add_to_role("administrator") user.save! user end end
30.583333
83
0.776567
9aedf445aec88daa7a1586c072d0fcc239fb7b6d
60
py
Python
utils/loss.py
chansoopark98/CSNet-colorization
071fbd95f58bafb9991720f73b3b51cddd5e234c
[ "MIT" ]
3
2021-11-29T05:30:12.000Z
2022-01-23T11:06:56.000Z
utils/loss.py
chansoopark98/CSNet-colorization
071fbd95f58bafb9991720f73b3b51cddd5e234c
[ "MIT" ]
null
null
null
utils/loss.py
chansoopark98/CSNet-colorization
071fbd95f58bafb9991720f73b3b51cddd5e234c
[ "MIT" ]
null
null
null
import tensorflow as tf def ssim_loss(y_true, y_pred):
15
30
0.733333
1bb566c20d925cc1de276ffdba92ff80610dbfd6
632
dart
Dart
lib/functions/hsl.dart
luisvt/stylus_dart
81d59989fcdbf88fb6f55086de90a7c0ac75262f
[ "MIT" ]
null
null
null
lib/functions/hsl.dart
luisvt/stylus_dart
81d59989fcdbf88fb6f55086de90a7c0ac75262f
[ "MIT" ]
null
null
null
lib/functions/hsl.dart
luisvt/stylus_dart
81d59989fcdbf88fb6f55086de90a7c0ac75262f
[ "MIT" ]
null
null
null
import '../utils.dart' as utils; import '../nodes/index.dart' as nodes; import 'hsla.dart'; /** * Convert the given `color` to an `HSLA` node, * or h,s,l component values. * * Examples: * * hsl(10, 50, 30) * // => HSLA * * hsl(#ffcc00) * // => HSLA * * @param {Unit|HSLA|RGBA} hue * @param {Unit} saturation * @param {Unit} lightness * @return {HSLA} * @api public */ hsl(hue, saturation, lightness){ if (1 == arguments.length) { utils.assertColor(hue, 'color'); return hue.hsla; } else { return hsla( hue , saturation , lightness , new nodes.Unit(1)); } }
17.555556
47
0.560127
e83a35826cfdc16587a94462bf55e93a7b4f9c2a
17,383
cs
C#
src/HotChocolate/Core/src/Execution/Utilities/ValueCompletion.cs
rafsanulhasan/hotchocolate
6ae540cc6fda328779444d2c1298b3851171a11d
[ "MIT" ]
null
null
null
src/HotChocolate/Core/src/Execution/Utilities/ValueCompletion.cs
rafsanulhasan/hotchocolate
6ae540cc6fda328779444d2c1298b3851171a11d
[ "MIT" ]
null
null
null
src/HotChocolate/Core/src/Execution/Utilities/ValueCompletion.cs
rafsanulhasan/hotchocolate
6ae540cc6fda328779444d2c1298b3851171a11d
[ "MIT" ]
null
null
null
using System; using System.Collections; using System.Diagnostics.CodeAnalysis; using HotChocolate.Language; using HotChocolate.Resolvers; using HotChocolate.Types; using HotChocolate.Utilities; using static HotChocolate.Execution.Utilities.ErrorHelper; namespace HotChocolate.Execution.Utilities { internal static class ValueCompletion { public static bool TryComplete( IOperationContext operationContext, IMiddlewareContext middlewareContext, Path path, IType fieldType, object? result, out object? completedResult) { if (fieldType.IsNonNullType()) { if (TryComplete( operationContext, middlewareContext, path, fieldType.InnerType(), result, out completedResult) && completedResult is { }) { return true; } return false; } if (result is null) { completedResult = null; return true; } if (fieldType.IsListType()) { if (TryCompleteListValue( operationContext, middlewareContext, path, fieldType, result, out IResultData? completedList)) { completedResult = completedList; return true; } completedResult = null; return false; } if (fieldType is ILeafType leafType) { return TryCompleteLeafValue( operationContext, middlewareContext, path, leafType, result, out completedResult); } if (fieldType.IsCompositeType()) { if (TryCompleteCompositeValue( operationContext, middlewareContext, path, fieldType, result, out ResultMap? completedResultMap)) { completedResult = completedResultMap; return true; } completedResult = null; return false; } middlewareContext.ReportError( ErrorHelper.UnexpectedValueCompletionError( middlewareContext.FieldSelection, path)); completedResult = null; return false; } private static bool TryCompleteListValue( IOperationContext operationContext, IMiddlewareContext middlewareContext, Path path, IType fieldType, object result, out IResultData? completedValue) { IType elementType = fieldType.ElementType(); if (elementType.IsCompositeType()) { if (TryCompleteResultMapListValue( operationContext, middlewareContext, path, fieldType, elementType, result, out ResultMapList? mapList)) { completedValue = mapList; return true; } } else if (TryCompleteResultListValue( operationContext, middlewareContext, path, fieldType, elementType, result, out ResultList? list)) { completedValue = list; return true; } completedValue = null; return false; } private static bool TryCompleteResultMapListValue( IOperationContext operationContext, IMiddlewareContext middlewareContext, Path path, IType fieldType, IType elementType, object result, out ResultMapList? completedResult) { if (result is Array array) { completedResult = operationContext.Result.RentResultMapList(); completedResult.IsNullable = elementType.IsNullableType(); for (int i = 0; i < array.Length; i++) { if (TryComplete( operationContext, middlewareContext, path.Append(i), elementType, array.GetValue(i), out object? completedElement) && completedElement is ResultMap m) { m.Parent = completedResult; completedResult.Add(m); } else if (completedResult.IsNullable) { completedResult.Add(null); } else { completedResult = null; return false; } } return true; } else if (result is IList list) { completedResult = operationContext.Result.RentResultMapList(); completedResult.IsNullable = elementType.IsNullableType(); for (int i = 0; i < list.Count; i++) { if (TryComplete( operationContext, middlewareContext, path.Append(i), elementType, list[i], out object? completedElement) && completedElement is ResultMap m) { m.Parent = completedResult; completedResult.Add(m); } else if (completedResult.IsNullable) { completedResult.Add(null); } else { completedResult = null; return false; } } return true; } else if (result is IEnumerable enumerable) { int index = 0; completedResult = operationContext.Result.RentResultMapList(); completedResult.IsNullable = elementType.IsNullableType(); foreach (object? element in enumerable) { if (TryComplete( operationContext, middlewareContext, path.Append(index++), elementType, element, out object? completedElement) && completedElement is ResultMap m) { m.Parent = completedResult; completedResult.Add(m); } else if (completedResult.IsNullable) { completedResult.Add(null); } else { completedResult = null; return false; } } return true; } else { middlewareContext.ReportError( ErrorHelper.ListValueIsNotSupported( result.GetType(), middlewareContext.FieldSelection, path)); completedResult = null; return false; } } private static bool TryCompleteResultListValue( IOperationContext operationContext, IMiddlewareContext middlewareContext, Path path, IType fieldType, IType elementType, object result, out ResultList? completedResult) { bool isElementList = elementType.IsListType(); if (result is Array array) { completedResult = operationContext.Result.RentResultList(); completedResult.IsNullable = elementType.IsNullableType(); for (int i = 0; i < array.Length; i++) { if (TryComplete( operationContext, middlewareContext, path.Append(i), elementType, array.GetValue(i), out object? completedElement) && completedElement is { } m) { completedResult.Add(m); if (isElementList) { SetParent(m, completedResult); } } else if (completedResult.IsNullable) { completedResult.Add(null); } else { completedResult = null; return false; } } return true; } else if (result is IList list) { completedResult = operationContext.Result.RentResultList(); completedResult.IsNullable = elementType.IsNullableType(); for (int i = 0; i < list.Count; i++) { if (TryComplete( operationContext, middlewareContext, path.Append(i), elementType, list[i], out object? completedElement) && completedElement is { } m) { completedResult.Add(m); if (isElementList) { SetParent(m, completedResult); } } else if (completedResult.IsNullable) { completedResult.Add(null); } else { completedResult = null; return false; } } return true; } else if (result is IEnumerable enumerable) { int index = 0; completedResult = operationContext.Result.RentResultList(); completedResult.IsNullable = elementType.IsNullableType(); foreach (object? element in enumerable) { if (TryComplete( operationContext, middlewareContext, path.Append(index++), elementType, element, out object? completedElement) && completedElement is { } m) { completedResult.Add(m); if (isElementList) { SetParent(m, completedResult); } } else if (completedResult.IsNullable) { completedResult.Add(null); } else { completedResult = null; return false; } } return true; } else { middlewareContext.ReportError( ErrorHelper.ListValueIsNotSupported( result.GetType(), middlewareContext.FieldSelection, path)); completedResult = null; return false; } } private static void SetParent(object value, IResultData parentList) { if (value is IHasResultDataParent result) { result.Parent = parentList; } } private static bool TryCompleteLeafValue( IOperationContext operationContext, IMiddlewareContext middlewareContext, Path path, ILeafType fieldType, object result, out object? completedResult) { try { if (!fieldType.RuntimeType.IsInstanceOfType(result) && operationContext.Converter.TryConvert(fieldType.RuntimeType, result, out object c)) { result = c; } completedResult = fieldType.Serialize(result); return true; } catch (ScalarSerializationException ex) { middlewareContext.ReportError( ErrorHelper.InvalidLeafValue( ex, middlewareContext.FieldSelection, path)); } catch (Exception ex) { middlewareContext.ReportError( ErrorHelper.UnexpectedLeafValueSerializationError( ex, operationContext.ErrorHandler, middlewareContext.FieldSelection, path)); } completedResult = null; return true; } private static bool TryCompleteCompositeValue( IOperationContext operationContext, IMiddlewareContext middlewareContext, Path path, IType fieldType, object result, [NotNullWhen(true)] out ResultMap? completedResult) { if (TryResolveObjectType( middlewareContext, path, fieldType, result, out ObjectType? objectType)) { SelectionSetNode selectionSet = middlewareContext.FieldSelection.SelectionSet!; IPreparedSelectionList selections = operationContext.CollectFields(selectionSet, objectType); completedResult = selections.EnqueueResolverTasks( operationContext, responseName => path.Append(responseName), middlewareContext.ScopedContextData, result); return true; } middlewareContext.ReportError( ValueCompletion_CouldNotResolveAbstractType( middlewareContext.FieldSelection, path)); completedResult = null; return false; } private static bool TryResolveObjectType( IMiddlewareContext middlewareContext, Path path, IType fieldType, object result, [NotNullWhen(true)] out ObjectType? objectType) { try { if (middlewareContext.ValueType is ObjectType vot) { objectType = vot; return true; } else if (fieldType is ObjectType ot) { objectType = ot; return true; } else if (fieldType is InterfaceType it) { objectType = it.ResolveConcreteType(middlewareContext, result); return objectType is { }; } else if (fieldType is UnionType ut) { objectType = ut.ResolveConcreteType(middlewareContext, result); return objectType is { }; } middlewareContext.ReportError( ErrorHelper.UnableToResolveTheAbstractType( fieldType.Print(), middlewareContext.FieldSelection, path)); } catch (Exception ex) { middlewareContext.ReportError( ErrorHelper.UnexpectedErrorWhileResolvingAbstractType( ex, fieldType.Print(), middlewareContext.FieldSelection, path)); } objectType = null; return false; } } }
33.237094
103
0.423345
f555cc1c00382d5eea43496a9e4a1419406aa8da
508
go
Go
pkg/dummy/dummy.go
juliaogris/guppy
6f256b44f0bf0778ce5c96def691e665c58b093a
[ "Apache-2.0" ]
1
2021-09-13T05:49:09.000Z
2021-09-13T05:49:09.000Z
pkg/dummy/dummy.go
juliaogris/guppy
6f256b44f0bf0778ce5c96def691e665c58b093a
[ "Apache-2.0" ]
null
null
null
pkg/dummy/dummy.go
juliaogris/guppy
6f256b44f0bf0778ce5c96def691e665c58b093a
[ "Apache-2.0" ]
null
null
null
// Package dummy contains protoc-generated output and implements a test // and demo dummy services. // It is intended as for transflect testing only. package dummy import ( "context" "fmt" ) // Server implements the server-side of gRPC demo Phone service. type Server struct { UnimplementedDummyServer } // Hello is a demo dummy service. func (*Server) Say(ctx context.Context, req *SayRequest) (*SayResponse, error) { return &SayResponse{DoubleWord: fmt.Sprintf("%s, %s", req.Word, req.Word)}, nil }
25.4
80
0.738189
8540bb274d1b135c143971a81144aa2f61576e24
1,715
cs
C#
src/MassTransit/Serialization/MessageIdMessageHeader.cs
misiek-it/MassTransit
9106eb7556506be5e7290d6e04a5b0eaf865c885
[ "ECL-2.0", "Apache-2.0" ]
1
2020-06-04T10:27:41.000Z
2020-06-04T10:27:41.000Z
src/MassTransit/Serialization/MessageIdMessageHeader.cs
misiek-it/MassTransit
9106eb7556506be5e7290d6e04a5b0eaf865c885
[ "ECL-2.0", "Apache-2.0" ]
1
2020-05-25T10:05:21.000Z
2020-05-25T10:05:21.000Z
src/MassTransit/Serialization/MessageIdMessageHeader.cs
misiek-it/MassTransit
9106eb7556506be5e7290d6e04a5b0eaf865c885
[ "ECL-2.0", "Apache-2.0" ]
1
2020-12-17T04:41:27.000Z
2020-12-17T04:41:27.000Z
namespace MassTransit.Serialization { using System; using System.Collections; using System.Collections.Generic; public class MessageIdMessageHeader : Headers { readonly Guid _messageId; public MessageIdMessageHeader(Guid messageId) { _messageId = messageId; } public IEnumerable<KeyValuePair<string, object>> GetAll() { yield return new KeyValuePair<string, object>(nameof(MessageContext.MessageId), _messageId); } public bool TryGetHeader(string key, out object value) { if (key == null) throw new ArgumentNullException(nameof(key)); if (key.Equals(nameof(MessageContext.MessageId))) { value = _messageId; return true; } value = default; return false; } T Headers.Get<T>(string key, T defaultValue) { if (key.Equals(nameof(MessageContext.MessageId))) return _messageId as T; return defaultValue; } public T? Get<T>(string key, T? defaultValue = null) where T : struct { if (key.Equals(nameof(MessageContext.MessageId))) return _messageId is T result ? result : default; return defaultValue; } public IEnumerator<HeaderValue> GetEnumerator() { yield return new HeaderValue(nameof(MessageContext.MessageId), _messageId); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
25.220588
104
0.545773
33a33602db5940643b88a0ff84a036301918bb41
226
h
C
iosTechRepostitory/iosTechRepostitory/chart/BITemperatureDashBoard.h
yi6chongtian/iosTechRepository
bf84215865a4704f17c0ff9fc8f446a70539dfba
[ "Apache-2.0" ]
null
null
null
iosTechRepostitory/iosTechRepostitory/chart/BITemperatureDashBoard.h
yi6chongtian/iosTechRepository
bf84215865a4704f17c0ff9fc8f446a70539dfba
[ "Apache-2.0" ]
null
null
null
iosTechRepostitory/iosTechRepostitory/chart/BITemperatureDashBoard.h
yi6chongtian/iosTechRepository
bf84215865a4704f17c0ff9fc8f446a70539dfba
[ "Apache-2.0" ]
null
null
null
// // BITemperatureDashBoard.h // Chart // 仪表盘 // Created by tangzhibiao on 2018/10/17. // Copyright © 2018年 tangzhibiao. All rights reserved. // #import <UIKit/UIKit.h> @interface BITemperatureDashBoard : UIView @end
16.142857
55
0.707965
2ffd69a6b9a533d9a090f26e8fdf0b1deaa94621
2,637
py
Python
secbox/app/secbox.py
jeziellago/android-sec-box
78c1feb577eb644036317ee40150fb91365ab440
[ "Apache-2.0" ]
29
2020-04-02T06:09:56.000Z
2021-11-08T11:45:46.000Z
secbox/app/secbox.py
jeziellago/android-sec-box
78c1feb577eb644036317ee40150fb91365ab440
[ "Apache-2.0" ]
null
null
null
secbox/app/secbox.py
jeziellago/android-sec-box
78c1feb577eb644036317ee40150fb91365ab440
[ "Apache-2.0" ]
5
2020-04-02T06:09:57.000Z
2021-03-05T15:17:46.000Z
import os from time import sleep from .actionbox import extract_apk, decompile_only_sources, decompile_only_resources, decompile_all, recompile_apk class SecBox: def __init__(self): self.__create_states__() self.menu_options = [] self.__add_menu_option__('Extract apk from device', extract_apk) self.__add_menu_option__('Decompile only sources from apk', decompile_only_sources) self.__add_menu_option__('Decompile only resources from apk', decompile_only_resources) self.__add_menu_option__('Decompile all from apk', decompile_all) self.__add_menu_option__('Recompile modified apk from folder', recompile_apk) def start(self): try: self.current_state = self.STATE_IDLE while True: self.__draw_header__() self.__handle_state__() except KeyboardInterrupt: print('\n<!> Exiting... Bye :)') exit() def __handle_state__(self): if self.current_state == self.STATE_IDLE: self.__draw_menu__() option = input('\n\n::> ') self.__select_menu_option__(option) else: pass def __select_menu_option__(self, option): action = None for menu in self.menu_options: if option == str(menu["id"]): action = menu["action"] break if action: self.current_state = self.STATE_PROCESSING action() self.current_state = self.STATE_IDLE input('\n[!] Press any key to [MENU]::>') def __create_states__(self): self.STATE_IDLE = 0 self.STATE_PROCESSING = 1 def __add_menu_option__(self, option, action): next_option_id = len(self.menu_options) + 1 self.menu_options.append({ "id": next_option_id, "description": option, "action": action }) def __draw_header__(self): os.system('clear') print( """ Welcome to _________ ___. / _____/ ____ ____\_ |__ _______ ___ \_____ \_/ __ \_/ ___\| __ \ / _ \ \/ / / \ ___/\ \___| \_\ ( <_> > < /_______ /\___ >\___ >___ /\____/__/\_ \\ \/ \/ \/ \/ \/ powered by @jeziellago """) def __draw_menu__(self): print('\t[ MENU ]') for menu in self.menu_options: print('\t[ %s ] %s' % (menu["id"], menu["description"]))
33.379747
114
0.540766
ff22b9272715cc77db1e4d8b24ed060ea0c70d13
3,167
py
Python
prune_neon/optimizers/optimizer.py
cs-chan/Fuzzy-Compression
f287a59896e27798c7ebca51a168e8a016b79a86
[ "BSD-3-Clause" ]
8
2018-06-20T19:00:37.000Z
2021-05-28T06:44:42.000Z
prune_neon/optimizers/optimizer.py
cs-chan/fuzzyDCN
f287a59896e27798c7ebca51a168e8a016b79a86
[ "BSD-3-Clause" ]
1
2017-05-10T03:18:21.000Z
2017-05-10T04:24:55.000Z
prune_neon/optimizers/optimizer.py
cs-chan/fuzzyDCN
f287a59896e27798c7ebca51a168e8a016b79a86
[ "BSD-3-Clause" ]
1
2017-11-09T02:19:54.000Z
2017-11-09T02:19:54.000Z
# import numpy as np from neon.optimizers.optimizer import Optimizer, get_param_list class RMSPropNesterov(Optimizer): """ RMSProp with Nesterov Momentum """ # TODO: max norm constraint def __init__(self, stochastic_round=False, momentum=0.5, decay_rate=0.90, learning_rate=1e-4, epsilon=1e-6, gradient_clip_norm=None, gradient_clip_value=None, name="rmspropNAG"): super(RMSPropNesterov, self).__init__(name=name) self.epsilon = epsilon self.decay_rate = decay_rate self.learning_rate = learning_rate self.momentum = momentum self.gradient_clip_norm = gradient_clip_norm self.gradient_clip_value = gradient_clip_value self.stochastic_round = stochastic_round def optimize(self, layer_list, epoch): lrate, epsilon, decay = (self.learning_rate, self.epsilon, self.decay_rate) param_list = get_param_list(layer_list) scale_factor = self.clip_gradient_norm(param_list, self.gradient_clip_norm) for (param, grad), states in param_list: param.rounding = self.stochastic_round if len(states) == 0: states.append(self.be.zeros_like(grad)) states.append(self.be.zeros_like(grad)) grad = grad / self.be.bsz grad = self.clip_gradient_value(grad, self.gradient_clip_value) # update state state = states[0] state[:] = decay * state + self.be.square(grad) * (1.0 - decay) # update velocity velocity = states[1] temp_velocity = - (scale_factor * grad * lrate) / self.be.sqrt(state + epsilon) velocity[:] = self.momentum * velocity + temp_velocity param[:] = param + self.momentum * velocity + temp_velocity class MaxNormConstraint(Optimizer): """ Max Norm Constraint """ def __init__(self, optimizer, max_col_norm=0.9, max_kern_norm=1.9, name='maxnorm'): super(MaxNormConstraint, self).__init__(name=name) self.optimizer = optimizer self.max_col_norm = max_col_norm self.max_kern_norm = max_kern_norm self.learning_rate = self.optimizer.learning_rate def __setattr__(self, key, value): if key == 'learning_rate': self.optimizer.learning_rate = value super(MaxNormConstraint, self).__setattr__(key, value) def optimize(self, layer_list, epoch): self.optimizer.optimize(layer_list, epoch=epoch) param_list = get_param_list(layer_list) for idx, ((param, grad), states) in enumerate(param_list): if layer_list[idx].name in ['BiasLayer']: continue if layer_list[idx].name in ['ConvolutionLayer']: max_norm = self.max_kern_norm axes = 0 else: max_norm = self.max_col_norm axes = 1 norm = self.be.empty_like(param) norm[:] = self.be.sqrt(self.be.sum(self.be.square(param), axis=axes)) target_norm = self.be.clip(norm, 0., max_norm) param[:] = param * target_norm / (norm + 1e-7)
37.702381
111
0.627723
8e5cdc7709a37377ac42904ce95d914f1e386b96
1,871
swift
Swift
SCWeibo/SCWeibo/Classes/StatusDetailViewController/Tabs/Comment/DetailCommentListService.swift
ScWang98/SCWeibo
4eff90e876c5aedfa6d6fc1f5d9482bc15b0088a
[ "MIT" ]
null
null
null
SCWeibo/SCWeibo/Classes/StatusDetailViewController/Tabs/Comment/DetailCommentListService.swift
ScWang98/SCWeibo
4eff90e876c5aedfa6d6fc1f5d9482bc15b0088a
[ "MIT" ]
null
null
null
SCWeibo/SCWeibo/Classes/StatusDetailViewController/Tabs/Comment/DetailCommentListService.swift
ScWang98/SCWeibo
4eff90e876c5aedfa6d6fc1f5d9482bc15b0088a
[ "MIT" ]
null
null
null
// // DetailCommentListService.swift // SCWeibo // // Created by wangshuchao on 2021/4/13. // import Alamofire import Foundation class DetailCommentListService { var statusId: String? var maxId: Int = 0 var maxIdType: Int = 0 func loadStatus(loadMore: Bool, completion: @escaping (_ isSuccess: Bool, _ list: [CommentModel]) -> Void) { guard let statusId = statusId else { return } let URLString = URLSettings.commentsHotflow var params = [String: Any]() params["id"] = statusId params["max_id"] = loadMore ? maxId : 0 params["max_id_type"] = loadMore ? maxIdType : 0 params["mid"] = statusId AF.request(URLString, method: .get, parameters: params, encoding: URLEncoding.default).responseJSON { response in var isSuccess = false var jsonResult: Dictionary<AnyHashable, Any>? switch response.result { case let .success(json): if let dict = json as? Dictionary<AnyHashable, Any> { jsonResult = dict isSuccess = true } case .failure: jsonResult = nil isSuccess = false } var results = [CommentModel]() if let dataDict: Dictionary<AnyHashable, Any> = jsonResult?.sc.dictionary(for: "data"), let dataArray: [Dictionary<AnyHashable, Any>] = dataDict.sc.array(for: "data") { self.maxId = dataDict.sc.int(for: "max_id", defaultValue: 0) self.maxIdType = dataDict.sc.int(for: "max_id_type", defaultValue: 0) for commentItem in dataArray { results.append(CommentModel(dict: commentItem)) } } completion(isSuccess, results) } } }
33.410714
121
0.563335
06c02553f3bd4b0edd3980dfde35b70e977a54e5
463
py
Python
lib/list_tickets.py
StoDevX/stolaf-ubersicht-widgets
647a2e952ddcba6a40930ce3e77c079423b82858
[ "MIT" ]
2
2016-10-07T16:51:26.000Z
2021-08-10T11:59:34.000Z
lib/list_tickets.py
StoDevX/stolaf-ubersicht-widgets
647a2e952ddcba6a40930ce3e77c079423b82858
[ "MIT" ]
4
2015-03-05T00:55:21.000Z
2016-04-28T02:57:27.000Z
lib/list_tickets.py
StoDevX/stolaf-ubersicht-widgets
647a2e952ddcba6a40930ce3e77c079423b82858
[ "MIT" ]
1
2017-09-23T01:19:15.000Z
2017-09-23T01:19:15.000Z
from .get_tickets import get_tickets from .functions import flatten, group_by, take import re def list_tickets(num=7): open_tickets = get_tickets('open') filtered = [t for t in open_tickets if t['problemtype']['detailDisplayName'] != 'IT (Internal) &#8226; Training Request Type'] sorted_tickets = sorted(filtered, key=lambda t: t['lastUpdated']) most_recent = take(num, reversed(sorted_tickets)) return list(most_recent)
30.866667
106
0.704104
4d9ac609679413244802b3c462377a5847cd4ae7
2,878
cs
C#
Src/Idoklad/Clients/PriceListClient.cs
mholec/IDokladSdk
6b5b792dfc32d5aa54fdb882ae5ae57fe276e005
[ "MIT" ]
3
2019-02-25T11:41:40.000Z
2020-05-05T14:12:23.000Z
Src/Idoklad/Clients/PriceListClient.cs
mholec/IDokladSdk
6b5b792dfc32d5aa54fdb882ae5ae57fe276e005
[ "MIT" ]
8
2016-06-05T10:45:13.000Z
2018-12-13T07:54:00.000Z
Src/Idoklad/Clients/PriceListClient.cs
mholec/idoklad-sdk-csharp
6b5b792dfc32d5aa54fdb882ae5ae57fe276e005
[ "MIT" ]
4
2016-09-08T09:56:33.000Z
2018-07-03T19:28:39.000Z
using IdokladSdk.ApiFilters; using IdokladSdk.ApiModels; using IdokladSdk.ApiModels.BaseModels; namespace IdokladSdk.Clients { /// <summary> /// Methods for price list. /// </summary> public partial class PriceListClient : BaseClient { public const string ResourceUrl = "/PriceListItems"; public PriceListClient(ApiContext apiContext) : base(apiContext) { } /// <summary> /// GET api/PriceListItems/Default /// Method returns default price list item that is suitable for new item creation. /// </summary> public PriceList Default() { return Get<PriceList>(ResourceUrl + "/Default"); } /// <summary> /// GET api/PriceListItems/{id}/Expand /// Method returns price list item by its Id with extended entities. /// </summary> public PriceListExpand PriceListItemExpand(int priceListItemId) { return Get<PriceListExpand>(ResourceUrl + "/" + priceListItemId + "/Expand"); } /// <summary> /// DELETE api/PriceListItems/{id} /// Method deletes price list item. /// </summary> public bool Delete(int priceListItemId) { return Delete(ResourceUrl + "/" + priceListItemId); } /// <summary> /// DELETE api/PriceListItems/Batch/{deleteIfReferenced} /// Method deletes price list items, including ones referenced on invoices, stock, etc. /// </summary> public bool DeleteBatch(bool deleteIfReferenced, object[] ids) { return Delete(ResourceUrl + "/" + "Batch" + "/" + deleteIfReferenced, ids); } /// <summary> /// GET api/PriceListItems /// Returns price list with pages. /// </summary> public RowsResultWrapper<PriceList> PriceListItems(ApiFilter filter) { return Get<RowsResultWrapper<PriceList>>(ResourceUrl, filter); } /// <summary> /// GET api/PriceListItems/{id} /// Returns price list item by Id. /// </summary> public PriceList PriceListItem(int priceListItemId) { return Get<PriceList>(ResourceUrl + "/" + priceListItemId); } /// <summary> /// POST api/PriceListItems /// Insert new price item into the price list. /// </summary> public PriceList Create(PriceList model) { return Post<PriceList, PriceList>(ResourceUrl, model); } /// <summary> /// PUT api/PriceListItems/{id} /// Method updates price list item. /// </summary> public PriceList Update(int priceListItemId, PriceList model) { return Put<PriceList, PriceList>(ResourceUrl + "/" + priceListItemId, model); } } }
31.977778
95
0.578179
15b111d52ff452ad90b9e03264904857d7f336c5
908
rb
Ruby
test/models/file_manager_test.rb
mrk21/tvrec
0f261714ace005473a5d0f35d5f4d8e43d60b175
[ "MIT" ]
null
null
null
test/models/file_manager_test.rb
mrk21/tvrec
0f261714ace005473a5d0f35d5f4d8e43d60b175
[ "MIT" ]
null
null
null
test/models/file_manager_test.rb
mrk21/tvrec
0f261714ace005473a5d0f35d5f4d8e43d60b175
[ "MIT" ]
null
null
null
require 'test_helper' class FileManagerTest < ActiveSupport::TestCase test "ファイル名に適したものに変換できること" do targets = { '!:;/\|,*?<>()$~\'"[]#♯&%' => '!:;/\|,*?<>()$〜’”[]##&%', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789' => '0123456789', '.' => '・', '..' => '‥', '...' => '...', 'a.' => 'a.', 'a..' => 'a..', 'a...' => 'a...', 'a.b' => 'a.b', 'a..b' => 'a..b', 'a...b' => 'a...b', '.a' => '.a', '..a' => '..a', '...a' => '...a', ' . ' => '・', ' ..  ' => '‥', '  ... ' => '...', 'a b c   d e f   g' => 'a_b_c_d_e_f_g', } targets.each do |from,to| converted = FileManager.to_filename(from) assert_equal(converted, to) end end end
22.7
119
0.379956
bb8b4678dc6eec9e95051bd3b213b03ec9c543f0
6,391
cs
C#
src/synchronization/Sync.cs
HeatXD/PleaseResync
9c0457f3b86388823bc07c14b24b62f67dbe0f7e
[ "MIT" ]
11
2022-01-04T20:12:54.000Z
2022-03-06T18:20:35.000Z
src/synchronization/Sync.cs
HeatXD/PleaseResync
9c0457f3b86388823bc07c14b24b62f67dbe0f7e
[ "MIT" ]
1
2022-01-07T14:09:53.000Z
2022-01-10T01:30:13.000Z
src/synchronization/Sync.cs
HeatXD/PleaseResync
9c0457f3b86388823bc07c14b24b62f67dbe0f7e
[ "MIT" ]
null
null
null
using System.Diagnostics; using System.Collections.Generic; using System; namespace PleaseResync { internal class Sync { private readonly uint _inputSize; private readonly Device[] _devices; private TimeSync _timeSync; private InputQueue[] _deviceInputs; private StateStorage _stateStorage; public Sync(Device[] devices, uint inputSize) { _devices = devices; _inputSize = inputSize; _timeSync = new TimeSync(); _stateStorage = new StateStorage(TimeSync.MaxRollbackFrames); _deviceInputs = new InputQueue[_devices.Length]; } public void AddRemoteInput(uint deviceId, int frame, byte[] deviceInput) { // only allow adding input to the local device Debug.Assert(_devices[deviceId].Type == Device.DeviceType.Remote); // update device variables if needed if (_devices[deviceId].RemoteFrame < frame) { _devices[deviceId].RemoteFrame = frame; _devices[deviceId].RemoteFrameAdvantage = _timeSync.LocalFrame - frame; } // let them know u recieved the packet _devices[deviceId].SendMessage(new DeviceInputAckMessage { Frame = (uint)frame }); AddDeviceInput(frame, deviceId, deviceInput); } public void SetLocalDevice(uint deviceId, uint playerCount, uint frameDelay) { _deviceInputs[deviceId] = new InputQueue(_inputSize, playerCount, frameDelay); } public void AddRemoteDevice(uint deviceId, uint playerCount) { _deviceInputs[deviceId] = new InputQueue(_inputSize, playerCount); } public void UpdateTimeSync() => _timeSync.UpdateTimeSync(_devices); public int LocalFrame() => _timeSync.LocalFrame; public void IncrementFrame() => _timeSync.LocalFrame++; public void SendLocalInputs(uint localDeviceId) { foreach (var device in _devices) { if (device.Type == Device.DeviceType.Remote) { uint finalFrame = (uint)(_timeSync.LocalFrame + _deviceInputs[localDeviceId].GetFrameDelay()); var combinedInput = new List<byte>(); for (uint i = device.LastAckedInputFrame; i <= finalFrame; i++) { combinedInput.AddRange(GetDeviceInput((int)i, localDeviceId).Inputs); } device.SendMessage(new DeviceInputMessage { StartFrame = device.LastAckedInputFrame, EndFrame = finalFrame, Input = combinedInput.ToArray() }); } } } public StateStorage StateStorage() => _stateStorage; public bool ShouldRollback() => _timeSync.ShouldRollback(); public int SyncFrame() => _timeSync.SyncFrame; public void UpdateSyncFrame() { int finalFrame = _timeSync.RemoteFrame; if (_timeSync.RemoteFrame > _timeSync.LocalFrame) { finalFrame = _timeSync.LocalFrame; } bool foundMistake = false; int foundFrame = finalFrame; for (int i = _timeSync.SyncFrame + 1; i <= finalFrame; i++) { foreach (var input in _deviceInputs) { var predInput = input.GetPredictedInput(i); if (predInput.Frame == i && input.GetInput(i, false).Frame == i) { // Incorrect Prediction if (!predInput.Equal(input.GetInput(i, false), true)) { foundFrame = i - 1; foundMistake = true; } // remove prediction form queue input.ResetPredictions(); } } if (foundMistake) break; } _timeSync.SyncFrame = foundFrame; } public void AddLocalInput(uint deviceId, byte[] deviceInput) { // only allow adding input to the local device Debug.Assert(_devices[deviceId].Type == Device.DeviceType.Local); // check if the predictition threshold has been reached. Debug.Assert(_timeSync.PredictionLimitReached() == false, "Prediction Limit Reached!"); AddDeviceInput(_timeSync.LocalFrame, deviceId, deviceInput); } private void AddDeviceInput(int frame, uint deviceId, byte[] deviceInput) { Debug.Assert(deviceInput.Length == _devices[deviceId].PlayerCount * _inputSize, "the length of the given deviceInput isnt correct!"); var input = new GameInput(frame, _inputSize, _devices[deviceId].PlayerCount); input.SetInputs(0, _devices[deviceId].PlayerCount, deviceInput); _deviceInputs[deviceId].AddInput(frame, input); } private GameInput GetDeviceInput(int frame, uint deviceId) { return _deviceInputs[deviceId].GetInput(frame); } public GameInput GetFrameInput(int frame) { uint playerCount = 0; foreach (var device in _devices) { playerCount += device.PlayerCount; } // add all device inputs into a single GameInput var input = new GameInput(frame, _inputSize, playerCount); // offset is needed to put the players input in the correct position uint playerOffset = 0; for (uint i = 0; i < _devices.Length; i++) { // get the input of the device and add it to the rest of the inputs var tmpInput = GetDeviceInput(frame, i); input.SetInputs(playerOffset, _devices[i].PlayerCount, tmpInput.Inputs); // advance player offset to the position of the next device playerOffset += _devices[i].PlayerCount; } return input; } public int FrameAdvantage() => _timeSync.FrameAdvantage; } }
37.816568
114
0.55672
0a8309c5e7ee72335ad6f7c6099c6427fc64563e
295
cs
C#
Real-Time Corruptor/BizHawk_RTC/BizHawk.Emulation.Cores/Consoles/Intellivision/ICart.cs
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
45
2017-07-24T05:31:06.000Z
2019-03-29T12:23:57.000Z
Real-Time Corruptor/BizHawk_RTC/BizHawk.Emulation.Cores/Consoles/Intellivision/ICart.cs
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
5
2017-07-24T02:37:24.000Z
2018-12-28T16:51:06.000Z
Real-Time Corruptor/BizHawk_RTC/BizHawk.Emulation.Cores/Consoles/Intellivision/ICart.cs
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
10
2017-07-24T02:11:43.000Z
2018-12-27T20:49:37.000Z
using BizHawk.Common; namespace BizHawk.Emulation.Cores.Intellivision { public interface ICart { int Parse(byte[] rom); ushort? ReadCart(ushort addr, bool peek); bool WriteCart(ushort addr, ushort value, bool poke); void SyncState(Serializer ser); string BoardName { get; } } }
18.4375
55
0.725424
7a2ce6db599aed84bc5b6b1295f927c71efc180d
2,329
ps1
PowerShell
purgeNSXT_ethernet_externalid.ps1
gavinbarnard/nsxtextpurge
fbab04b137bef06b146d7f1809895810f9fe4abc
[ "Unlicense" ]
null
null
null
purgeNSXT_ethernet_externalid.ps1
gavinbarnard/nsxtextpurge
fbab04b137bef06b146d7f1809895810f9fe4abc
[ "Unlicense" ]
null
null
null
purgeNSXT_ethernet_externalid.ps1
gavinbarnard/nsxtextpurge
fbab04b137bef06b146d7f1809895810f9fe4abc
[ "Unlicense" ]
null
null
null
# gavinbarnard@vmware.com Feb 28 2019 # # This is provided as a sample on how to blank the externalid for NSXT connected VMs # # Please validate it works to your needs in a test environment before using in any production situation # # #This is free and unencumbered software released into the public domain. # #Anyone is free to copy, modify, publish, use, compile, sell, or #distribute this software, either in source code form or as a compiled #binary, for any purpose, commercial or non-commercial, and by any #means. # #In jurisdictions that recognize copyright laws, the author or authors #of this software dedicate any and all copyright interest in the #software to the public domain. We make this dedication for the benefit #of the public at large and to the detriment of our heirs and #successors. We intend this dedication to be an overt act of #relinquishment in perpetuity of all present and future rights to this #software under copyright law. # #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. # #For more information, please refer to <http://unlicense.org> Param( [Parameter(Mandatory=$true)]$vmname ) $vm = Get-VM $vmname if ($vm.PowerState -eq "PoweredOff") { $vdevConfigSpec = New-Object VMware.Vim.VirtualDeviceConfigSpec $vdevConfigSpec.Operation = [VMware.Vim.VirtualDeviceConfigSpecOperation]::edit $net = $vm | Get-NetworkAdapter $extData = $net.ExtensionData $extData.ExternalId = "" $vdevConfigSpec.Device = $extData $cspec = New-Object VMware.Vim.VirtualMachineConfigSpec $cspec.DeviceChange = @($vdevConfigSpec) $vm.ExtensionData.ReconfigVM($cspec) Write-Output "If there are no errors above this text $vm's network adapter has had the externalid blanked" Write-Output "You will need to Edit the VM, and change it to a different Logical Switch save settings" Write-Output "and then reconnect it to the original logical switch" } else { Write-Output "$vm VM is not powered off" }
35.287879
107
0.773293
e013ede920de15d2b6cec3251e9f3c42291d4dc1
166
h
C
Example/Pods/Target Support Files/Pods-CoreMedia_Example/Pods-CoreMedia_Example-umbrella.h
ThachTranQuoc/CoreMedia
bb5ca5e706bb186c01e5841d03019fbb025e3b19
[ "MIT" ]
null
null
null
Example/Pods/Target Support Files/Pods-CoreMedia_Example/Pods-CoreMedia_Example-umbrella.h
ThachTranQuoc/CoreMedia
bb5ca5e706bb186c01e5841d03019fbb025e3b19
[ "MIT" ]
null
null
null
Example/Pods/Target Support Files/Pods-CoreMedia_Example/Pods-CoreMedia_Example-umbrella.h
ThachTranQuoc/CoreMedia
bb5ca5e706bb186c01e5841d03019fbb025e3b19
[ "MIT" ]
null
null
null
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_CoreMedia_ExampleVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_CoreMedia_ExampleVersionString[];
23.714286
76
0.86747
a39c55f73a30d1ebf5f75b84942fd6a984f8224e
745
tsx
TypeScript
packages/react-icons/src/components/Status20Filled.tsx
LiquidatorCoder/fluentui-system-icons
d3614e4e95f47d86b1d1f930c4925e513949da54
[ "MIT" ]
null
null
null
packages/react-icons/src/components/Status20Filled.tsx
LiquidatorCoder/fluentui-system-icons
d3614e4e95f47d86b1d1f930c4925e513949da54
[ "MIT" ]
null
null
null
packages/react-icons/src/components/Status20Filled.tsx
LiquidatorCoder/fluentui-system-icons
d3614e4e95f47d86b1d1f930c4925e513949da54
[ "MIT" ]
null
null
null
import * as React from "react"; import { JSX } from "react-jsx"; import { IFluentIconsProps } from '../IFluentIconsProps.types'; const Status20Filled = (iconProps: IFluentIconsProps, props: React.HTMLAttributes<HTMLElement>): JSX.Element => { const { primaryFill, className } = iconProps; return <svg {...props} width={20} height={20} viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" className={className}><path d="M17.35 2.65a2.62 2.62 0 00-3.7 0l-5.5 5.5a.5.5 0 00-.14.23l-1 4a.5.5 0 00.61.6l4-1a.5.5 0 00.23-.13l5.5-5.5a2.62 2.62 0 000-3.7z" fill={primaryFill} /><path d="M15.94 9.18a6 6 0 11-5.12-5.12l.86-.86A7.02 7.02 0 003 10a7 7 0 1013.8-1.68l-.86.86z" fill={primaryFill} /></svg>; }; export default Status20Filled;
57.307692
408
0.679195
7f7525531bcd85c980ca62e8cda366dfda2d0025
37
php
PHP
src/webui/config.inc.php
7u83/actube
0f6cfb9eab2843cf8269187d64cc797491d55b02
[ "BSD-2-Clause" ]
35
2015-01-16T04:33:02.000Z
2021-04-29T02:22:33.000Z
src/webui/config.inc.php
7u83/actube
0f6cfb9eab2843cf8269187d64cc797491d55b02
[ "BSD-2-Clause" ]
4
2015-05-28T21:59:43.000Z
2016-03-25T18:34:13.000Z
src/webui/config.inc.php
7u83/actube
0f6cfb9eab2843cf8269187d64cc797491d55b02
[ "BSD-2-Clause" ]
26
2015-01-16T04:32:56.000Z
2022-02-21T09:14:22.000Z
<?php $db = "../ac/actube.sqlite3";
9.25
29
0.540541
a358024d46045b8480e4d281f25822d4441aa51d
2,334
java
Java
client/src/main/java/org/hobsoft/contacts/client/ApplicationDriver.java
markhobson/contacts
1a110c1503defd3c9a4170aa13e7e7b08110b3bb
[ "Apache-2.0" ]
null
null
null
client/src/main/java/org/hobsoft/contacts/client/ApplicationDriver.java
markhobson/contacts
1a110c1503defd3c9a4170aa13e7e7b08110b3bb
[ "Apache-2.0" ]
null
null
null
client/src/main/java/org/hobsoft/contacts/client/ApplicationDriver.java
markhobson/contacts
1a110c1503defd3c9a4170aa13e7e7b08110b3bb
[ "Apache-2.0" ]
null
null
null
/* * 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.hobsoft.contacts.client; import org.hobsoft.contacts.client.auth.Credentials; import org.hobsoft.contacts.client.auth.SignInDriver; import org.hobsoft.contacts.client.contact.ContactsViewDriver; import org.hobsoft.microbrowser.MicrodataDocument; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import static com.google.common.base.Preconditions.checkNotNull; /** * Entry point for the web application driver. */ @Component public class ApplicationDriver { // ---------------------------------------------------------------------------------------------------------------- // fields // ---------------------------------------------------------------------------------------------------------------- private final DriverConfiguration config; // ---------------------------------------------------------------------------------------------------------------- // constructors // ---------------------------------------------------------------------------------------------------------------- @Autowired public ApplicationDriver(DriverConfiguration config) { this.config = checkNotNull(config, "config"); } // ---------------------------------------------------------------------------------------------------------------- // public methods // ---------------------------------------------------------------------------------------------------------------- public SignInDriver signInForm() { String url = config.getServerUrl().toString(); MicrodataDocument document = config.getBrowser().get(url); return new SignInDriver(config, document); } public ContactsViewDriver signIn(Credentials credentials) { return signInForm() .signIn(credentials); } }
35.907692
116
0.537275
cce7eea3767e5bf419184ccd93657b4ef3f1cfcc
3,056
rb
Ruby
examples/taskrouter.examples.rb
Amilcar6/logsbox
791f7880f23d1aa56927461fee8e6cb3d7034ce0
[ "MIT" ]
null
null
null
examples/taskrouter.examples.rb
Amilcar6/logsbox
791f7880f23d1aa56927461fee8e6cb3d7034ce0
[ "MIT" ]
null
null
null
examples/taskrouter.examples.rb
Amilcar6/logsbox
791f7880f23d1aa56927461fee8e6cb3d7034ce0
[ "MIT" ]
null
null
null
require 'rubygems' require 'twilio-ruby' # taskrouter examples version 1 account_sid = 'YourAccountSid' auth_token = 'YourAuthToken' workspace_sid = 'YourWorkspaceSid' # set up a client client = Twilio::REST::TaskRouterClient.new account_sid, auth_token, workspace_sid puts client.workspace.sid + ' with ' + client.workspace.friendly_name client.workspace.update(friendly_name: 'MyWorkspace2') # fetch the list of workers and their status client.workspace.workers.list.each do |worker| puts worker.friendly_name + ' is available ' + worker.available.to_s end # fetch the list of workers and their status client.workspace.workers.list(activity_name: 'Offline').each do |worker| puts worker.friendly_name + ' is available ' + worker.available.to_s end # create a task workflow_sid = 'YourWorkflowSid' task = client.workspace.tasks.create(attributes: '{"foo":"bar"}', workflow_sid: workflow_sid) # list all the tasks created client.workspace.tasks.list.each do |task| attributes = JSON.parse(task.attributes) puts attributes['foo'] + ' with age ' + task.age.to_s task.reservations.list.each do |reservation| puts reservation.sid end end # fetching a list of tasks that are pending client.workspace.tasks.list(assignment_status: 'pending').each do |task| puts 'pending task ' + task.sid end # delete all tasks client.workspace.tasks.list.each do |task| puts 'deleting task ' + task.sid task.delete end # get all the statistics for a workspace workspace_stats = client.workspace.statistics(minutes: '240') cumulative = workspace_stats.cumulative puts 'Avg Task Acceptance Time: ' + cumulative['avg_task_acceptance_time'].to_s \ + ' with ' + cumulative['tasks_created'].to_s + ' tasks created' # get events for a workspace events = client.workspace.events.list(minutes: '15') events.each do |event| puts event.event_type + ' at ' + event.event_date end # build a workflow support_queue_sid = 'YourSupportQueueSid' marketing_queue_sid = 'YourMarketingQueueSid' default_queue_sid = 'YourDefaultQueue' support_targets = [Twilio::TaskRouter::WorkflowRuleTarget.new support_queue_sid] support_rule = Twilio::TaskRouter::WorkflowRule.new 'type == "support"', support_targets marketing_targets = [Twilio::TaskRouter::WorkflowRuleTarget.new marketing_queue_sid] marketing_rule = Twilio::TaskRouter::WorkflowRule.new 'type == "marketing"', marketing_targets rules = [support_rule, marketing_rule] default_target = Twilio::TaskRouter::WorkflowRuleTarget.new default_queue_sid config = Twilio::TaskRouter::WorkflowConfiguration.new rules, default_target puts config.to_json workflowCreated = client.workspace.workflows.create(configuration: config.to_json, friendly_name: 'MyWorkflow2', assignment_callback_url: 'http://example.com') workflowFetched = client.workspace.workflows.get(workflowCreated.sid) config_string = workflowFetched.configuration config_obj = Twilio::TaskRouter::WorkflowConfiguration.parse_json(config_string) puts config_string puts config_obj.rules[0].expression puts config_obj.default_target.queue
35.126437
159
0.785995
53047735dcf0229c0280514916894fe5701b8968
5,892
swift
Swift
Twitter/TweetsViewController.swift
krishna-alex/cp-ios-Twitter
5d9030d43d03acbe5442f40d097f38d6e6c05311
[ "Apache-2.0" ]
null
null
null
Twitter/TweetsViewController.swift
krishna-alex/cp-ios-Twitter
5d9030d43d03acbe5442f40d097f38d6e6c05311
[ "Apache-2.0" ]
1
2017-04-17T18:27:01.000Z
2017-04-17T18:27:01.000Z
Twitter/TweetsViewController.swift
krishna-alex/cp-ios-Twitter
5d9030d43d03acbe5442f40d097f38d6e6c05311
[ "Apache-2.0" ]
null
null
null
// // TweetsViewController.swift // Twitter // // Created by Krishna Alex on 4/11/17. // Copyright © 2017 Krishna Alex. All rights reserved. // import UIKit class TweetsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, ComposeViewControllerDelegate { @IBOutlet weak var tweetsTableView: UITableView! var tweets: [Tweet]! var lastTweetId: Int? = nil var isMoreDataLoading = false var loadingMoreView:InfiniteScrollActivityView? override func viewDidLoad() { super.viewDidLoad() tweetsTableView.dataSource = self tweetsTableView.delegate = self tweetsTableView.estimatedRowHeight = 60 tweetsTableView.rowHeight = UITableViewAutomaticDimension navigationItem.titleView = UIImageView.init(image: UIImage(named:"Twitter-icon1.png")) // Set up Infinite Scroll loading indicator let frame = CGRect(x: 0, y: tweetsTableView.contentSize.height, width: tweetsTableView.bounds.size.width, height: InfiniteScrollActivityView.defaultHeight) loadingMoreView = InfiniteScrollActivityView(frame: frame) loadingMoreView!.isHidden = true tweetsTableView.addSubview(loadingMoreView!) var insets = tweetsTableView.contentInset insets.bottom += InfiniteScrollActivityView.defaultHeight tweetsTableView.contentInset = insets //get tweets from home timeline getTweets() //Pull to refresh tweets let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshControlAction(_:)), for: UIControlEvents.valueChanged) // add refresh control to table view tweetsTableView.insertSubview(refreshControl, at: 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func onLogoutButton(_ sender: Any) { TwitterClient.sharedInstance.logout() } func getTweets() { if (tweets) != nil { //Since maxId value is inclusive, subtract 1 from the lowest Tweet ID returned from the previous request and use this for the value of max_id lastTweetId = tweets[tweets.endIndex - 1].tweetID! - 1 as Int } TwitterClient.sharedInstance.homeTimeLine(maxId: lastTweetId, success: { (tweets: [Tweet]) in self.isMoreDataLoading = false // Stop the loading indicator self.loadingMoreView!.stopAnimating() if (self.tweets) != nil { self.tweets.append(contentsOf: tweets) } else { self.tweets = tweets } self.tweetsTableView.reloadData() }, failure: { (error: Error) in print(error.localizedDescription) }) } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(_ tweetsTableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (tweets != nil) { return tweets.count } else { return 0 } } func tableView(_ tweetsTableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: TweetCell = tweetsTableView.dequeueReusableCell(withIdentifier: "TweetCell") as! TweetCell let resultTweet:Tweet resultTweet = tweets[indexPath.row] cell.singleTweet = resultTweet return cell } func refreshControlAction(_ refreshControl: UIRefreshControl) { getTweets() refreshControl.endRefreshing() } func scrollViewDidScroll(_ scrollView: UIScrollView) { if (!isMoreDataLoading) { // Calculate the position of one screen length before the bottom of the results let scrollViewContentHeight = tweetsTableView.contentSize.height let scrollOffsetThreshold = scrollViewContentHeight - tweetsTableView.bounds.size.height // When the user has scrolled past the threshold, start requesting if(scrollView.contentOffset.y > scrollOffsetThreshold && tweetsTableView.isDragging) { isMoreDataLoading = true // Update position of loadingMoreView, and start loading indicator let frame = CGRect(x: 0, y: tweetsTableView.contentSize.height, width: tweetsTableView.bounds.size.width, height: InfiniteScrollActivityView.defaultHeight) loadingMoreView?.frame = frame loadingMoreView!.startAnimating() // Load more results getTweets() } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if(segue.identifier == "TweetDetailView") { let destinationViewController = segue.destination as! TweetDetailViewController if let indexPath = tweetsTableView.indexPathForSelectedRow { let cell = tweetsTableView.cellForRow(at: indexPath) as! TweetCell let indexPath = tweetsTableView.indexPath(for: cell) let tweet = tweets[(indexPath?.row)!] destinationViewController.tweet = tweet } } if(segue.identifier == "TweetComposeView") { let navigationController = segue.destination as! UINavigationController let composeViewController = navigationController.topViewController as! ComposeViewController composeViewController.delegate = self } } func ComposeViewController(ComposeViewController: ComposeViewController, didTweet tweet: Tweet) { self.tweets.insert(tweet, at: 0) tweetsTableView.reloadData() } }
39.543624
171
0.646809
c4e519aa044b301f537aa65051cad7864439e568
2,281
lua
Lua
src/wifi-setup.lua
octoblu/nodemcu-meshbLua
2c1b551d6ebfa0383fc80338251e86aee63da283
[ "MIT" ]
2
2016-04-13T18:41:33.000Z
2017-04-23T04:44:17.000Z
src/wifi-setup.lua
octoblu/nodemcu-meshbLua
2c1b551d6ebfa0383fc80338251e86aee63da283
[ "MIT" ]
null
null
null
src/wifi-setup.lua
octoblu/nodemcu-meshbLua
2c1b551d6ebfa0383fc80338251e86aee63da283
[ "MIT" ]
null
null
null
local wifiCredentials = require('wifi-credentials') local wifi = wifi local sntp = sntp local print = print local assert = assert local rtctime = rtctime local tostring = tostring local Package = {} setfenv(1,Package) function connectAuth(network,password,callback) assert(network, 'network is undefined') print("SETUP WIFI FOR "..network) function doCallbackOnce(err,value) if callback then callback(err,value) callback = nil else print('wifi setup callback not defined or already called') print('ignored callback value:'..tostring(value)) end end wifi.setphymode(wifi.PHYMODE_G) wifi.setmode(wifi.STATION) wifi.sta.config(network, password) wifi.sta.eventMonReg( wifi.STA_GOTIP, function(Previous_State) if(Previous_State==wifi.STA_GOTIP) then print("STATION RECONNECT") else print("STATION CONNECTED") end local sec, usec = rtctime.get() print(sec .. ":" .. usec) sntp.sync('pool.ntp.org', function(sec,usec,server) print('sync', sec, usec, server) local sec, usec = rtctime.get() print(sec .. ":" .. usec) doCallbackOnce(nil,wifi.sta.getip()) end, function() print('failed!') doCallbackOnce(nil,wifi.sta.getip()) end ) -- wifi.sta.eventMonReg(wifi.STA_GOTIP, "unreg") end ) wifi.sta.eventMonReg(wifi.STA_IDLE, function() print("STATION IDLE") end) wifi.sta.eventMonReg(wifi.STA_CONNECTING, function()print("STATION CONNECTING") end) wifi.sta.eventMonReg(wifi.STA_WRONGPWD, function() doCallbackOnce("STATION WRONG PASSWORD") end) wifi.sta.eventMonReg(wifi.STA_APNOTFOUND, function() doCallbackOnce("STATION NO AP FOUND") end) wifi.sta.eventMonReg(wifi.STA_FAIL, function() doCallbackOnce("STATION CONNECT FAIL") end) wifi.sta.eventMonStart(500) end function connect(callback) local network, password = wifiCredentials:load() if (network ~= nil) then connectAuth(network,password,callback) else print("WIFI NETWORK NOT DEFINED!") wifi.setmode(wifi.STATION) print("ENTERING SMART CONFIG MODE") wifi.startsmart(0, function(network, password) wifiCredentials:save(network,password) connectAuth(network,password,callback) end ) end end return Package
29.24359
98
0.698816
f1baa02a9bb6eb8c4fbb92a32ae2aab00982f11e
5,299
swift
Swift
Joplin Clipper Extension/Network.swift
cweirup/JoplinSafariWebClipper
2cfd01e5e5f7db1f24acc72df56134d1829b3c73
[ "MIT" ]
51
2020-03-03T09:12:32.000Z
2022-03-11T16:55:08.000Z
Joplin Clipper Extension/Network.swift
cweirup/JoplinSafariWebClipper
2cfd01e5e5f7db1f24acc72df56134d1829b3c73
[ "MIT" ]
9
2020-03-29T22:03:35.000Z
2022-03-18T01:17:33.000Z
Joplin Clipper Extension/Network.swift
cweirup/JoplinSafariWebClipper
2cfd01e5e5f7db1f24acc72df56134d1829b3c73
[ "MIT" ]
7
2020-09-15T01:43:49.000Z
2022-03-03T18:11:40.000Z
// // Network.swift // Joplin Clipper Extension // // Created by Christopher Weirup on 2020-04-09. // Copyright © 2020 Christopher Weirup. All rights reserved. // import Foundation import os protocol APIResource { associatedtype ModelType: Decodable var methodPath: String { get } var queryItems: [URLQueryItem] { get } } extension APIResource{ var queryItems: [URLQueryItem] { return [URLQueryItem(name: "as_tree", value: "1")] } } extension APIResource { var url: URL { var components = URLComponents(string: "http://localhost:41184")! components.path = methodPath components.queryItems = queryItems return components.url! } } class Network { private static func config() -> URLSessionConfiguration { let config = URLSessionConfiguration.default config.timeoutIntervalForRequest = 60 config.timeoutIntervalForResource = 60 return config } private static func session() -> URLSession { let session = URLSession(configuration: config()) return session } private static func request(url: String, params: [String: Any]) -> URLRequest { var components = URLComponents(string: url)! components.queryItems = params.map { (key, value) in URLQueryItem(name: key, value: (value as! String)) } //components.queryItems?.append(URLQueryItem(name: "token", value: "fd6eb4000ddcc2b5ddf3de0606ecc058faf1702e9df563f0ae53444b654a9acbb9aceee2f0505e0f75c87269af7820e5350d0d582a3fcaa6c05147df5b358fe6")) // For now, going to comment this out. Looks like with iOS 13 and macOS 15, // using httpBody is not allowed for GET requests. You would need to append // any parameters as a query string to the URL. For now I don't need to // do any special parameters. // MORE INFO: https://stackoverflow.com/questions/56955595/1103-error-domain-nsurlerrordomain-code-1103-resource-exceeds-maximum-size-i // POTENTIAL FIX: https://stackoverflow.com/questions/27723912/swift-get-request-with-parameters // do { // request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted) // } catch let error { // print(error.localizedDescription) // } var request = URLRequest(url: components.url!) request.timeoutInterval = 60 return request } private static func request<T: Encodable>(url: URL, params: [String: Any] = [:], object: T) -> URLRequest { var components = URLComponents(string: url.absoluteString)! if (!params.isEmpty) { components.queryItems = params.map { (key, value) in URLQueryItem(name: key, value: (value as! String)) } } var request = URLRequest(url: components.url!) //os_log("BLEH - Network.request = \(components.url?.absoluteString)") do { request.httpBody = try JSONEncoder().encode(object) } catch let error { print(error.localizedDescription) } request.timeoutInterval = 60 return request } static func post( url: String, params: [String: Any] = [:], callback: @escaping (_ data: Data?, _ error: Error?) -> Void) { var request: URLRequest = self.request(url: url, params: params) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.httpMethod = "POST" let task = session().dataTask(with: request, completionHandler: { (data, response, error) in DispatchQueue.main.async { callback(data, error) } }) task.resume() } static func post<T: Encodable>( url: URL, object: T, callback: @escaping (_ data: Data?, _ error: Error?) -> Void) { var request: URLRequest = self.request(url: url, object: object) request.httpMethod = "POST" let task = session().dataTask(with: request, completionHandler: { (data, response, error) in DispatchQueue.main.async { callback(data, error) } }) task.resume() } static func post<T: Encodable>( url: URL, params: [String: Any] = [:], object: T, callback: @escaping (_ data: Data?, _ error: Error?) -> Void) { var request: URLRequest = self.request(url: url, params: params, object: object) request.httpMethod = "POST" let task = session().dataTask(with: request, completionHandler: { (data, response, error) in DispatchQueue.main.async { callback(data, error) } }) task.resume() } static func get( url: String, params: [String: Any] = [:], callback: @escaping (_ data: Data?, _ error: Error?) -> Void) { var request: URLRequest = self.request(url: url, params: params) request.httpMethod = "GET" let task = session().dataTask(with: request, completionHandler: { (data, response, error) in DispatchQueue.main.async { callback(data, error) } }) task.resume() } }
38.398551
208
0.619551
93cdd95cab440e059911c5367d3ec956d8a1b602
4,025
cs
C#
src/Umbraco.Core/PropertyEditors/ValueConverters/SliderValueConverter.cs
tompipe/Umbraco-CMS
5f4d6f2f89edef12c2c52e113f4ffd0ca80d6fab
[ "MIT" ]
1
2019-03-25T06:12:31.000Z
2019-03-25T06:12:31.000Z
src/Umbraco.Core/PropertyEditors/ValueConverters/SliderValueConverter.cs
tompipe/Umbraco-CMS
5f4d6f2f89edef12c2c52e113f4ffd0ca80d6fab
[ "MIT" ]
4
2021-05-11T23:01:45.000Z
2022-03-02T09:57:32.000Z
src/Umbraco.Core/PropertyEditors/ValueConverters/SliderValueConverter.cs
tompipe/Umbraco-CMS
5f4d6f2f89edef12c2c52e113f4ffd0ca80d6fab
[ "MIT" ]
1
2018-10-09T05:06:00.000Z
2018-10-09T05:06:00.000Z
using System; using System.Collections.Concurrent; using System.Linq; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; namespace Umbraco.Core.PropertyEditors.ValueConverters { [DefaultPropertyValueConverter] public class SliderValueConverter : PropertyValueConverterBase, IPropertyValueConverterMeta { private readonly IDataTypeService _dataTypeService; //TODO: Remove this ctor in v8 since the other one will use IoC public SliderValueConverter() : this(ApplicationContext.Current.Services.DataTypeService) { } public SliderValueConverter(IDataTypeService dataTypeService) { if (dataTypeService == null) throw new ArgumentNullException("dataTypeService"); _dataTypeService = dataTypeService; } public override bool IsConverter(PublishedPropertyType propertyType) { if (UmbracoConfig.For.UmbracoSettings().Content.EnablePropertyValueConverters) { return propertyType.PropertyEditorAlias.InvariantEquals(Constants.PropertyEditors.SliderAlias); } return false; } public override object ConvertSourceToObject(PublishedPropertyType propertyType, object source, bool preview) { if (source == null) { return null; } if (IsRangeDataType(propertyType.DataTypeId)) { var rangeRawValues = source.ToString().Split(','); var minimumAttempt = rangeRawValues[0].TryConvertTo<decimal>(); var maximumAttempt = rangeRawValues[1].TryConvertTo<decimal>(); if (minimumAttempt.Success && maximumAttempt.Success) { return new Range<decimal>() { Maximum = maximumAttempt.Result, Minimum = minimumAttempt.Result }; } } var valueAttempt = source.ToString().TryConvertTo<decimal>(); if (valueAttempt.Success) { return valueAttempt.Result; } // Something failed in the conversion of the strings to decimals return null; } public Type GetPropertyValueType(PublishedPropertyType propertyType) { if (IsRangeDataType(propertyType.DataTypeId)) { return typeof(Range<decimal>); } return typeof(decimal); } public PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType, PropertyCacheValue cacheValue) { return PropertyCacheLevel.Content; } /// <summary> /// Discovers if the slider is set to range mode. /// </summary> /// <param name="dataTypeId"> /// The data type id. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> private bool IsRangeDataType(int dataTypeId) { // GetPreValuesCollectionByDataTypeId is cached at repository level; // still, the collection is deep-cloned so this is kinda expensive, // better to cache here + trigger refresh in DataTypeCacheRefresher return Storages.GetOrAdd(dataTypeId, id => { var preValue = _dataTypeService.GetPreValuesCollectionByDataTypeId(id) .PreValuesAsDictionary .FirstOrDefault(x => string.Equals(x.Key, "enableRange", StringComparison.InvariantCultureIgnoreCase)) .Value; return preValue != null && preValue.Value.TryConvertTo<bool>().Result; }); } private static readonly ConcurrentDictionary<int, bool> Storages = new ConcurrentDictionary<int, bool>(); internal static void ClearCaches() { Storages.Clear(); } } }
35
122
0.608447
a32e635cab80be48b16623d33bbc6916624d3a2c
1,362
java
Java
kmdp-core/kmdp-terminology-content/src/test/java/edu/mayo/kmdp/TermsYamlTest.java
API4KBs/kmdp-models
18440e6cf69f2fad08f2dece7dfc18ef3fecd690
[ "Apache-2.0" ]
1
2019-04-17T15:17:29.000Z
2019-04-17T15:17:29.000Z
kmdp-core/kmdp-terminology-content/src/test/java/edu/mayo/kmdp/TermsYamlTest.java
API4KBs/kmdp-models
18440e6cf69f2fad08f2dece7dfc18ef3fecd690
[ "Apache-2.0" ]
null
null
null
kmdp-core/kmdp-terminology-content/src/test/java/edu/mayo/kmdp/TermsYamlTest.java
API4KBs/kmdp-models
18440e6cf69f2fad08f2dece7dfc18ef3fecd690
[ "Apache-2.0" ]
1
2019-04-19T00:19:49.000Z
2019-04-19T00:19:49.000Z
/** * Copyright © 2018 Mayo Clinic (RSTKNOWLEDGEMGMT@mayo.edu) * * 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 edu.mayo.kmdp; import io.swagger.models.Swagger; import org.junit.jupiter.api.Test; import static edu.mayo.kmdp.util.SwaggerTestUtil.parseValidateGroup; import static org.junit.jupiter.api.Assertions.assertEquals; public class TermsYamlTest { @Test public void testKAOTerms() { Swagger model = parseValidateGroup( "/yaml/org/omg/spec/api4kp/_20200801/taxonomy/knowledgeoperation/_20210401/KnowledgeProcessingOperation.yaml"); assertEquals(2, model.getDefinitions().size()); } @Test public void testSkosTerms() { Swagger model = parseValidateGroup( "/yaml/edu/mayo/ontology/taxonomies/kmdo/relatedconcept/RelatedConcept.yaml"); assertEquals(2, model.getDefinitions().size()); } }
34.05
119
0.74743
9ab4c0734b924dec4b1f211e52ba412c67cfefbf
1,678
py
Python
demo/alembic/versions/20190607_f5056738fe02.py
SalvatoreTosti/pyramid-demo
18ab173606c68b377b70d265aa1391258de1dc2f
[ "MIT" ]
1
2019-06-09T23:21:01.000Z
2019-06-09T23:21:01.000Z
demo/alembic/versions/20190607_f5056738fe02.py
SalvatoreTosti/pyramid-demo
18ab173606c68b377b70d265aa1391258de1dc2f
[ "MIT" ]
3
2019-12-26T17:28:22.000Z
2022-03-21T22:17:18.000Z
demo/alembic/versions/20190607_f5056738fe02.py
SalvatoreTosti/pyramid-demo
18ab173606c68b377b70d265aa1391258de1dc2f
[ "MIT" ]
null
null
null
"""Adds invoice tables Revision ID: f5056738fe02 Revises: 7ff88bf0eb5f Create Date: 2019-06-07 19:06:59.278519 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'f5056738fe02' down_revision = '7ff88bf0eb5f' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('invoices', sa.Column('id', sa.Integer(), nullable=False), sa.Column('date', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id', name=op.f('pk_invoices')) ) op.create_table('invoice_items', sa.Column('id', sa.Integer(), nullable=False), sa.Column('units', sa.Integer(), nullable=True), sa.Column('description', sa.Text(), nullable=True), sa.Column('amount', sa.NUMERIC(), nullable=True), sa.Column('parent_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['parent_id'], ['invoices.id'], name=op.f('fk_invoice_items_parent_id_invoices')), sa.PrimaryKeyConstraint('id', name=op.f('pk_invoice_items')) ) op.drop_index('my_index', table_name='models') op.drop_table('models') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('models', sa.Column('id', sa.INTEGER(), nullable=False), sa.Column('name', sa.TEXT(), nullable=True), sa.Column('value', sa.INTEGER(), nullable=True), sa.PrimaryKeyConstraint('id', name='pk_models') ) op.create_index('my_index', 'models', ['name'], unique=1) op.drop_table('invoice_items') op.drop_table('invoices') # ### end Alembic commands ###
33.56
110
0.674017
c079b066e0a96d88d9b966024db1abe2f8996536
8,195
cs
C#
test/CodeGen.SourceGenerator.Test/SyntaxNodeUtilityTests.cs
KeesV/azure-functions-durable-extension
a294ad56f179505988bb967b6403298bba8c1463
[ "MIT" ]
619
2017-06-30T05:39:59.000Z
2022-03-25T15:25:56.000Z
test/CodeGen.SourceGenerator.Test/SyntaxNodeUtilityTests.cs
KeesV/azure-functions-durable-extension
a294ad56f179505988bb967b6403298bba8c1463
[ "MIT" ]
1,622
2017-06-30T18:35:20.000Z
2022-03-31T16:58:42.000Z
test/CodeGen.SourceGenerator.Test/SyntaxNodeUtilityTests.cs
KeesV/azure-functions-durable-extension
a294ad56f179505988bb967b6403298bba8c1463
[ "MIT" ]
279
2017-07-06T16:49:52.000Z
2022-03-30T15:14:00.000Z
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using DurableFunctions.TypedInterfaces.SourceGenerator.Models; using DurableFunctions.TypedInterfaces.SourceGenerator.Tests.Models; using DurableFunctions.TypedInterfaces.SourceGenerator.Utils; using Xunit; namespace DurableFunctions.TypedInterfaces.SourceGenerator.Tests { public class SyntaxNodeUtilityTests { private CalculatorDocument Calculator => CalculatorDocument.Instance; [Fact] public void GetExistingFunctionName() { // Arrange var expectedFunctionName = "Add"; var model = this.Calculator.Semantic; var method = this.Calculator.AddMethod; // Act var result = SyntaxNodeUtility.TryGetFunctionName(model, method, out string functionName); // Assert Assert.True(result); Assert.Equal(expectedFunctionName, functionName); } [Fact] public void GetMissingFunctionName() { // Arrange var model = this.Calculator.Semantic; var method = this.Calculator.SubtractMethod; // Act var result = SyntaxNodeUtility.TryGetFunctionName(model, method, out string functionName); // Assert Assert.False(result); Assert.Null(functionName); } [Fact] public void GetActivityFunctionKind() { // Arrange var expectedFunctionKind = DurableFunctionKind.Activity; var method = this.Calculator.SubtractMethod; // Act var result = SyntaxNodeUtility.TryGetFunctionKind(method, out DurableFunctionKind kind); // Assert Assert.True(result); Assert.Equal(expectedFunctionKind, kind); } [Fact] public void GetOrchestrationFunctionKind() { // Arrange var expectedFunctionKind = DurableFunctionKind.Orchestration; var method = this.Calculator.MultiplyMethod; // Act var result = SyntaxNodeUtility.TryGetFunctionKind(method, out DurableFunctionKind kind); // Assert Assert.True(result); Assert.Equal(expectedFunctionKind, kind); } [Fact] public void GetMissingFunctionKind() { // Arrange var expectedFunctionKind = DurableFunctionKind.Unknonwn; var method = this.Calculator.DivideMethod; // Act var result = SyntaxNodeUtility.TryGetFunctionKind(method, out DurableFunctionKind kind); // Assert Assert.False(result); Assert.Equal(expectedFunctionKind, kind); } [Fact] public void GetReturnType() { // Arrange var method = this.Calculator.MultiplyMethod; // Act var result = SyntaxNodeUtility.TryGetReturnType(method, out TypeSyntax returnType); // Assert Assert.True(result); Assert.NotNull(returnType); } [Fact] public void GetParametersFromAssignment() { // Arrange var model = this.Calculator.Semantic; var method = this.Calculator.AddMethod; // Act var result = SyntaxNodeUtility.TryGetParameters(model, method, out List<TypedParameter> parameters); // Assert Assert.True(result); Assert.Equal(2, parameters.Count); Assert.Equal("int", parameters[0].Type.ToString()); Assert.Equal("int", parameters[1].Type.ToString()); Assert.Equal("num1", parameters[0].Name.ToString()); Assert.Equal("num2", parameters[1].Name.ToString()); } [Fact] public void GetGenericParametersFromAssignment() { // Arrange var model = this.Calculator.Semantic; var method = this.Calculator.AddListsMethod; // Act var result = SyntaxNodeUtility.TryGetParameters(model, method, out List<TypedParameter> parameters); // Assert Assert.True(result); Assert.Equal(2, parameters.Count); Assert.Equal("List<int>", parameters[0].Type.ToString()); Assert.Equal("List<int>", parameters[1].Type.ToString()); Assert.Equal("nums1", parameters[0].Name.ToString()); Assert.Equal("nums2", parameters[1].Name.ToString()); } [Fact] public void GetParameterFromLocalDeclaration() { // Arrange var model = this.Calculator.Semantic; var method = this.Calculator.IdentityMethod; // Act var result = SyntaxNodeUtility.TryGetParameters(model, method, out List<TypedParameter> parameters); // Assert Assert.True(result); Assert.Single(parameters); Assert.Equal("int", parameters[0].Type.ToString()); Assert.Equal("num1", parameters[0].Name.ToString()); } [Fact] public void GetGenericParameterFromLocalDeclaration() { // Arrange var model = this.Calculator.Semantic; var method = this.Calculator.AddListMethod; // Act var result = SyntaxNodeUtility.TryGetParameters(model, method, out List<TypedParameter> parameters); // Assert Assert.True(result); Assert.Single(parameters); Assert.Equal("List<int>", parameters[0].Type.ToString()); Assert.Equal("nums", parameters[0].Name.ToString()); } [Fact] public void GetQualifiedName() { // Arrange var expectedQualifiedName = "WebJobs.Extensions.DurableTask.CodeGen.Example.Calculator.Add"; var model = this.Calculator.Semantic; var method = this.Calculator.AddMethod; // Act var result = SyntaxNodeUtility.TryGetQualifiedTypeName(model, method, out string qualifiedName); // Assert Assert.True(result); Assert.Equal(expectedQualifiedName, qualifiedName); } [Fact] public void GetRequiredNamespaces() { // Arrange var model = this.Calculator.Semantic; var method = this.Calculator.AddComplexMethod; var parameterTypes = SyntaxNodeUtility.TryGetParameters(model, method, out List<TypedParameter> typedParameters); var usedTypes = typedParameters.Select(p => p.Type).ToList(); // Act var result = SyntaxNodeUtility.TryGetRequiredNamespaces(model, usedTypes, out HashSet<string> requiredNamespaces); // Assert Assert.True(result); Assert.Single(requiredNamespaces); Assert.Equal("WebJobs.Extensions.DurableTask.CodeGen.Example.Models", requiredNamespaces.First()); } [Fact] public void GetRequiredNamespacesWithGenerics() { // Arrange var model = this.Calculator.Semantic; var method = this.Calculator.AddListComplexMethod; SyntaxNodeUtility.TryGetParameters(model, method, out List<TypedParameter> typedParameters); var usedTypes = typedParameters.Select(p => p.Type).ToList(); // Act var result = SyntaxNodeUtility.TryGetRequiredNamespaces(model, usedTypes, out HashSet<string> requiredNamespaces); // Assert Assert.True(result); Assert.Equal(2, requiredNamespaces.Count); var requiredNamespaceList = requiredNamespaces.ToList(); Assert.Equal("System.Collections.Generic", requiredNamespaceList[0]); Assert.Equal("WebJobs.Extensions.DurableTask.CodeGen.Example.Models", requiredNamespaceList[1]); } } }
34.288703
126
0.601952
a44a765f60b3069ec8198447a8290a1e96b8aab0
2,643
php
PHP
projetos/Linguagem_de_programacao_WEB/exercicio22foreach.php
luishenriqueturani/curriculo
3713828de87b216eedc28c50c2a0c9d1bb1bb699
[ "MIT" ]
null
null
null
projetos/Linguagem_de_programacao_WEB/exercicio22foreach.php
luishenriqueturani/curriculo
3713828de87b216eedc28c50c2a0c9d1bb1bb699
[ "MIT" ]
null
null
null
projetos/Linguagem_de_programacao_WEB/exercicio22foreach.php
luishenriqueturani/curriculo
3713828de87b216eedc28c50c2a0c9d1bb1bb699
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Exercício 22 foreach</title> </head> <body> <h3>Exercício 22 Foreach</h3> <p>Enunciado: Faça um formulário com pelo menos 5 campos de tipos variados (textos, número e datas). Aloque todos os campos em um vetor e exiba de 3 formas diferentes: </p> <ul> <li>Imprima vetor normal com print_r;</li> <li>Imprima o vetor dentro de uma tabela com os nomes de campos;</li> <li>Imprima em formato de lista na ordem inversa;</li> </ul> <p>Valide se existe algum campo vazio e coloque um limite entre 1 e 10 carácteres por campos.</p> <br> <form action="exercicio22foreach.php" method="post"> <p>Nome: </p><input type="text" name="nome"><br> <p>Fone: </p><input type="number" name="fone"><br> <p>Endereço: </p><input type="text" name="end"><br> <p>Idade: </p><input type="number" name="idade"><br> <p>Qualquer merd...: </p><input type="text" name="merda"><br> <input type="submit" name="btn"><br> </form> <?php if(isset($_POST['btn'])){ if(empty($_POST['nome']) || empty($_POST['fone']) || empty($_POST['end']) || empty($_POST['idade']) || empty($_POST['merda'])){ echo "Algum campo está vazio"; }else{ if(strlen($_POST['nome'])>10 || strlen($_POST['fone'])>10 || strlen($_POST['end'])>10 || strlen($_POST['idade'])>10 || strlen($_POST['merda'])>10){ echo "Tamanho mázimo excedido. Digite no máximo 10 caracteres."; }if(strlen($_POST['nome'])<1 || strlen($_POST['fone'])<1 || strlen($_POST['end'])<1 || strlen($_POST['idade'])<1 || strlen($_POST['merda'])<1){ echo "Limite mínimo de 1."; }else{ $ar = array($_POST['nome'],$_POST['fone'],$_POST['end'],$_POST['idade'],$_POST['merda']); echo "<table border=1>"; /* for ($i=0; $i<count($ar); $i++){ echo "<td>".$ar[$i]."</td>"; } * usando for normal */ foreach ($ar as $key){ echo "<td>".$key."</td>"; } echo "</table>"; } } } ?> </body> </html>
46.368421
167
0.444949
33dc79ccaa6b59884e1caf096e8366ce682aaf2e
5,990
h
C
linsched-linsched-alpha/drivers/usb/host/isp1760-hcd.h
usenixatc2021/SoftRefresh_Scheduling
589ba06c8ae59538973c22edf28f74a59d63aa14
[ "MIT" ]
55
2019-12-20T03:25:14.000Z
2022-01-16T07:19:47.000Z
linsched-linsched-alpha/drivers/usb/host/isp1760-hcd.h
usenixatc2021/SoftRefresh_Scheduling
589ba06c8ae59538973c22edf28f74a59d63aa14
[ "MIT" ]
2
2020-11-02T08:01:00.000Z
2022-03-27T02:59:18.000Z
linsched-linsched-alpha/drivers/usb/host/isp1760-hcd.h
usenixatc2021/SoftRefresh_Scheduling
589ba06c8ae59538973c22edf28f74a59d63aa14
[ "MIT" ]
19
2015-02-25T19:50:05.000Z
2021-10-05T14:35:54.000Z
#ifndef _ISP1760_HCD_H_ #define _ISP1760_HCD_H_ /* exports for if */ struct usb_hcd *isp1760_register(phys_addr_t res_start, resource_size_t res_len, int irq, unsigned long irqflags, int rst_gpio, struct device *dev, const char *busname, unsigned int devflags); int init_kmem_once(void); void deinit_kmem_cache(void); /* EHCI capability registers */ #define HC_CAPLENGTH 0x00 #define HC_HCSPARAMS 0x04 #define HC_HCCPARAMS 0x08 /* EHCI operational registers */ #define HC_USBCMD 0x20 #define HC_USBSTS 0x24 #define HC_FRINDEX 0x2c #define HC_CONFIGFLAG 0x60 #define HC_PORTSC1 0x64 #define HC_ISO_PTD_DONEMAP_REG 0x130 #define HC_ISO_PTD_SKIPMAP_REG 0x134 #define HC_ISO_PTD_LASTPTD_REG 0x138 #define HC_INT_PTD_DONEMAP_REG 0x140 #define HC_INT_PTD_SKIPMAP_REG 0x144 #define HC_INT_PTD_LASTPTD_REG 0x148 #define HC_ATL_PTD_DONEMAP_REG 0x150 #define HC_ATL_PTD_SKIPMAP_REG 0x154 #define HC_ATL_PTD_LASTPTD_REG 0x158 /* Configuration Register */ #define HC_HW_MODE_CTRL 0x300 #define ALL_ATX_RESET (1 << 31) #define HW_ANA_DIGI_OC (1 << 15) #define HW_DATA_BUS_32BIT (1 << 8) #define HW_DACK_POL_HIGH (1 << 6) #define HW_DREQ_POL_HIGH (1 << 5) #define HW_INTR_HIGH_ACT (1 << 2) #define HW_INTR_EDGE_TRIG (1 << 1) #define HW_GLOBAL_INTR_EN (1 << 0) #define HC_CHIP_ID_REG 0x304 #define HC_SCRATCH_REG 0x308 #define HC_RESET_REG 0x30c #define SW_RESET_RESET_HC (1 << 1) #define SW_RESET_RESET_ALL (1 << 0) #define HC_BUFFER_STATUS_REG 0x334 #define ISO_BUF_FILL (1 << 2) #define INT_BUF_FILL (1 << 1) #define ATL_BUF_FILL (1 << 0) #define HC_MEMORY_REG 0x33c #define ISP_BANK(x) ((x) << 16) #define HC_PORT1_CTRL 0x374 #define PORT1_POWER (3 << 3) #define PORT1_INIT1 (1 << 7) #define PORT1_INIT2 (1 << 23) #define HW_OTG_CTRL_SET 0x374 #define HW_OTG_CTRL_CLR 0x376 /* Interrupt Register */ #define HC_INTERRUPT_REG 0x310 #define HC_INTERRUPT_ENABLE 0x314 #define HC_ISO_INT (1 << 9) #define HC_ATL_INT (1 << 8) #define HC_INTL_INT (1 << 7) #define HC_EOT_INT (1 << 3) #define HC_SOT_INT (1 << 1) #define INTERRUPT_ENABLE_MASK (HC_INTL_INT | HC_ATL_INT) #define HC_ISO_IRQ_MASK_OR_REG 0x318 #define HC_INT_IRQ_MASK_OR_REG 0x31C #define HC_ATL_IRQ_MASK_OR_REG 0x320 #define HC_ISO_IRQ_MASK_AND_REG 0x324 #define HC_INT_IRQ_MASK_AND_REG 0x328 #define HC_ATL_IRQ_MASK_AND_REG 0x32C /* urb state*/ #define DELETE_URB (0x0008) #define NO_TRANSFER_ACTIVE (0xffffffff) /* Philips Proprietary Transfer Descriptor (PTD) */ typedef __u32 __bitwise __dw; struct ptd { __dw dw0; __dw dw1; __dw dw2; __dw dw3; __dw dw4; __dw dw5; __dw dw6; __dw dw7; }; #define PTD_OFFSET 0x0400 #define ISO_PTD_OFFSET 0x0400 #define INT_PTD_OFFSET 0x0800 #define ATL_PTD_OFFSET 0x0c00 #define PAYLOAD_OFFSET 0x1000 struct slotinfo { struct isp1760_qh *qh; struct isp1760_qtd *qtd; unsigned long timestamp; }; typedef void (packet_enqueue)(struct usb_hcd *hcd, struct isp1760_qh *qh, struct isp1760_qtd *qtd); /* * Device flags that can vary from board to board. All of these * indicate the most "atypical" case, so that a devflags of 0 is * a sane default configuration. */ #define ISP1760_FLAG_BUS_WIDTH_16 0x00000002 /* 16-bit data bus width */ #define ISP1760_FLAG_OTG_EN 0x00000004 /* Port 1 supports OTG */ #define ISP1760_FLAG_ANALOG_OC 0x00000008 /* Analog overcurrent */ #define ISP1760_FLAG_DACK_POL_HIGH 0x00000010 /* DACK active high */ #define ISP1760_FLAG_DREQ_POL_HIGH 0x00000020 /* DREQ active high */ #define ISP1760_FLAG_ISP1761 0x00000040 /* Chip is ISP1761 */ #define ISP1760_FLAG_INTR_POL_HIGH 0x00000080 /* Interrupt polarity active high */ #define ISP1760_FLAG_INTR_EDGE_TRIG 0x00000100 /* Interrupt edge triggered */ #define ISP1760_FLAG_RESET_ACTIVE_HIGH 0x80000000 /* RESET GPIO active high */ /* chip memory management */ struct memory_chunk { unsigned int start; unsigned int size; unsigned int free; }; /* * 60kb divided in: * - 32 blocks @ 256 bytes * - 20 blocks @ 1024 bytes * - 4 blocks @ 8192 bytes */ #define BLOCK_1_NUM 32 #define BLOCK_2_NUM 20 #define BLOCK_3_NUM 4 #define BLOCK_1_SIZE 256 #define BLOCK_2_SIZE 1024 #define BLOCK_3_SIZE 8192 #define BLOCKS (BLOCK_1_NUM + BLOCK_2_NUM + BLOCK_3_NUM) #define MAX_PAYLOAD_SIZE BLOCK_3_SIZE #define PAYLOAD_AREA_SIZE 0xf000 /* ATL */ /* DW0 */ #define DW0_VALID_BIT 1 #define FROM_DW0_VALID(x) ((x) & 0x01) #define TO_DW0_LENGTH(x) (((u32) x) << 3) #define TO_DW0_MAXPACKET(x) (((u32) x) << 18) #define TO_DW0_MULTI(x) (((u32) x) << 29) #define TO_DW0_ENDPOINT(x) (((u32) x) << 31) /* DW1 */ #define TO_DW1_DEVICE_ADDR(x) (((u32) x) << 3) #define TO_DW1_PID_TOKEN(x) (((u32) x) << 10) #define DW1_TRANS_BULK ((u32) 2 << 12) #define DW1_TRANS_INT ((u32) 3 << 12) #define DW1_TRANS_SPLIT ((u32) 1 << 14) #define DW1_SE_USB_LOSPEED ((u32) 2 << 16) #define TO_DW1_PORT_NUM(x) (((u32) x) << 18) #define TO_DW1_HUB_NUM(x) (((u32) x) << 25) /* DW2 */ #define TO_DW2_DATA_START_ADDR(x) (((u32) x) << 8) #define TO_DW2_RL(x) ((x) << 25) #define FROM_DW2_RL(x) (((x) >> 25) & 0xf) /* DW3 */ #define FROM_DW3_NRBYTESTRANSFERRED(x) ((x) & 0x7fff) #define FROM_DW3_SCS_NRBYTESTRANSFERRED(x) ((x) & 0x07ff) #define TO_DW3_NAKCOUNT(x) ((x) << 19) #define FROM_DW3_NAKCOUNT(x) (((x) >> 19) & 0xf) #define TO_DW3_CERR(x) ((x) << 23) #define FROM_DW3_CERR(x) (((x) >> 23) & 0x3) #define TO_DW3_DATA_TOGGLE(x) ((x) << 25) #define FROM_DW3_DATA_TOGGLE(x) (((x) >> 25) & 0x1) #define TO_DW3_PING(x) ((x) << 26) #define FROM_DW3_PING(x) (((x) >> 26) & 0x1) #define DW3_ERROR_BIT (1 << 28) #define DW3_BABBLE_BIT (1 << 29) #define DW3_HALT_BIT (1 << 30) #define DW3_ACTIVE_BIT (1 << 31) #define FROM_DW3_ACTIVE(x) (((x) >> 31) & 0x01) #define INT_UNDERRUN (1 << 2) #define INT_BABBLE (1 << 1) #define INT_EXACT (1 << 0) #define SETUP_PID (2) #define IN_PID (1) #define OUT_PID (0) /* Errata 1 */ #define RL_COUNTER (0) #define NAK_COUNTER (0) #define ERR_COUNTER (2) #endif /* _ISP1760_HCD_H_ */
28.660287
82
0.728214
34616b4f00f5906d4c93abffca8ecbb9c38ce6bc
1,532
lua
Lua
MMOCoreORB/bin/scripts/object/tangible/theme_park/myyydril/objects.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/bin/scripts/object/tangible/theme_park/myyydril/objects.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/bin/scripts/object/tangible/theme_park/myyydril/objects.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
object_tangible_theme_park_myyydril_shared_myyydril_grievous_encounter_manager = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/theme_park/myyydril/shared_myyydril_grievous_encounter_manager.iff" } ObjectTemplates:addClientTemplate(object_tangible_theme_park_myyydril_shared_myyydril_grievous_encounter_manager, "object/tangible/theme_park/myyydril/shared_myyydril_grievous_encounter_manager.iff") object_tangible_theme_park_myyydril_shared_myyydril_machine = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/theme_park/myyydril/shared_myyydril_machine.iff" } ObjectTemplates:addClientTemplate(object_tangible_theme_park_myyydril_shared_myyydril_machine, "object/tangible/theme_park/myyydril/shared_myyydril_machine.iff") object_tangible_theme_park_myyydril_shared_myyydril_magic_stone = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/theme_park/myyydril/shared_myyydril_magic_stone.iff" } ObjectTemplates:addClientTemplate(object_tangible_theme_park_myyydril_shared_myyydril_magic_stone, "object/tangible/theme_park/myyydril/shared_myyydril_magic_stone.iff") object_tangible_theme_park_myyydril_shared_myyydril_power_cell = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/theme_park/myyydril/shared_myyydril_power_cell.iff" } ObjectTemplates:addClientTemplate(object_tangible_theme_park_myyydril_shared_myyydril_power_cell, "object/tangible/theme_park/myyydril/shared_myyydril_power_cell.iff")
72.952381
199
0.900783
1114158a1bf359d54a4c406af714fcb2c270d05a
389
swift
Swift
test/SILOptimizer/sroa_unreferenced_members.swift
xjc90s/swift
cafe5ccbd1b7aa9cc9c837c5be2cdf3d5acd8a49
[ "Apache-2.0" ]
72,551
2015-12-03T16:45:13.000Z
2022-03-31T18:57:59.000Z
test/SILOptimizer/sroa_unreferenced_members.swift
xjc90s/swift
cafe5ccbd1b7aa9cc9c837c5be2cdf3d5acd8a49
[ "Apache-2.0" ]
39,352
2015-12-03T16:55:06.000Z
2022-03-31T23:43:41.000Z
test/SILOptimizer/sroa_unreferenced_members.swift
xjc90s/swift
cafe5ccbd1b7aa9cc9c837c5be2cdf3d5acd8a49
[ "Apache-2.0" ]
13,845
2015-12-03T16:45:13.000Z
2022-03-31T11:32:29.000Z
// RUN: %target-swift-frontend -enable-copy-propagation=requested-passes-only -enable-lexical-lifetimes=false -sdk %S/Inputs -O -emit-sil -I %S/Inputs -enable-source-import -primary-file %s | %FileCheck %s import gizmo // CHECK: ModifyStruct // CHECK: = alloc_stack $Drill // CHECK: ret func ModifyStruct(inDrill : Drill) -> Int32 { var D : Drill = inDrill D.x += 3 return D.x }
29.923077
205
0.699229
c9a6258521542c9b1d2cc19a987c7cf7bdeae970
2,177
swift
Swift
MiniRemoto/Model/Adding Event/Location Module/LocationHelper.swift
JulioBBL/MiniRemoto
a193a7850c31c0635a72308e21e6a0b95bd35e18
[ "MIT" ]
null
null
null
MiniRemoto/Model/Adding Event/Location Module/LocationHelper.swift
JulioBBL/MiniRemoto
a193a7850c31c0635a72308e21e6a0b95bd35e18
[ "MIT" ]
1
2020-05-27T18:05:32.000Z
2020-05-27T18:05:32.000Z
MiniRemoto/Model/Adding Event/Location Module/LocationHelper.swift
JulioBBL/MiniRemoto
a193a7850c31c0635a72308e21e6a0b95bd35e18
[ "MIT" ]
2
2020-06-02T14:55:30.000Z
2020-06-02T17:18:33.000Z
// // LocationHelper.swift // MiniRemoto // // Created by Pedro Giuliano Farina on 27/05/20. // Copyright © 2020 Pedro Giuliano Farina. All rights reserved. // import MapKit public class LocationHelper: NSObject, CLLocationManagerDelegate { let locationManager = CLLocationManager() public private(set) var currentLocation: CLLocation? public var currentRegion: MKCoordinateRegion? { if let location = currentLocation { let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1) return MKCoordinateRegion(center: location.coordinate, span: span) } return nil } public override init() { super.init() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() } public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse { locationManager.requestLocation() } } public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("location manager error" + error.localizedDescription) } public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { currentLocation = locations.first } public static func getFullAddress(from placemark: MKPlacemark) -> String { var finalAddress = "" if let t = placemark.thoroughfare { finalAddress += t + ", " } if let l = placemark.locality { finalAddress += l + ", " } if let s = placemark.subLocality { finalAddress += s + ", " } if let a = placemark.administrativeArea { finalAddress += a + ", " } if let p = placemark.postalCode { finalAddress += p + ", " } if let c = placemark.country { finalAddress += c + ", " } finalAddress = String(finalAddress.prefix(finalAddress.count - 2)) return finalAddress } }
31.1
117
0.6339
f41e61f53c1859a31613a66e710767281ced2ef5
617
cs
C#
Smart! Puzzle Editor/Assets/Scripts/Puzzle Editor/ClosePlaceHolderElementMenu.cs
VictorSegura99/Smart-Puzzle-Editor
ca7c8211d8e9d2273110e11ffa30d67ce9332eb8
[ "MIT" ]
1
2021-06-19T16:10:04.000Z
2021-06-19T16:10:04.000Z
Smart! Puzzle Editor/Assets/Scripts/Puzzle Editor/ClosePlaceHolderElementMenu.cs
VictorSegura99/Smart-Puzzle-Editor
ca7c8211d8e9d2273110e11ffa30d67ce9332eb8
[ "MIT" ]
null
null
null
Smart! Puzzle Editor/Assets/Scripts/Puzzle Editor/ClosePlaceHolderElementMenu.cs
VictorSegura99/Smart-Puzzle-Editor
ca7c8211d8e9d2273110e11ffa30d67ce9332eb8
[ "MIT" ]
null
null
null
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class ClosePlaceHolderElementMenu : MonoBehaviour, IPointerDownHandler { public void OnPointerDown(PointerEventData eventData) { if (eventData.button == PointerEventData.InputButton.Left) { if (transform.parent.parent.GetComponent<LinkElementPlaceholder>()) PuzzleEditorController.instance.HideAllInspectors(); else transform.parent.parent.GetComponent<PuzzleElementPlaceHolder>().ShowCanvas(false); } } }
32.473684
99
0.714749
fbf241fd3ed648465144067b0755a8ec5d69fe29
1,132
ps1
PowerShell
firefox/.module-data.ps1
alanndz/dotfiles
8474b7d50d749525a9381be25c4976dd1c7dff2b
[ "BSD-3-Clause" ]
21
2019-12-28T06:56:26.000Z
2022-03-12T08:31:10.000Z
firefox/.module-data.ps1
alanndz/dotfiles
8474b7d50d749525a9381be25c4976dd1c7dff2b
[ "BSD-3-Clause" ]
null
null
null
firefox/.module-data.ps1
alanndz/dotfiles
8474b7d50d749525a9381be25c4976dd1c7dff2b
[ "BSD-3-Clause" ]
3
2020-09-21T16:22:31.000Z
2021-11-28T16:23:53.000Z
function Get-IniContent ($filePath) { $ini = @{} switch -regex -file $FilePath { "^\[(.+)\]" # Section { $section = $matches[1] $ini[$section] = @{} $CommentCount = 0 } "^(;.*)$" # Comment { $value = $matches[1] $CommentCount = $CommentCount + 1 $name = "Comment" + $CommentCount $ini[$section][$name] = $value } "(.+?)\s*=(.*)" # Key { $name,$value = $matches[1..2] $ini[$section][$name] = $value } } return $ini } function Install-Dotfiles { $FirefoxDir = "$env:APPDATA\Mozilla\Firefox" if (!(Test-Path $FirefoxDir\profiles.ini)) { "no firefox profile detected, open firefox first before restoring tweaks" exit } Get-IniContent -filePath $FirefoxDir\profiles.ini | ForEach-Object {$_[$_.Keys].Path} | ForEach-Object { if (Test-Path "$FirefoxDir\${_}\prefs.js") { ":: Install user.js to ${_}" Copy-Item -Force $PSScriptRoot\user.js "$FirefoxDir\${_}" } } }
28.3
108
0.489399
25e33daa4608fdd47a5d85ed9d65516d9c5b85bd
24,466
cs
C#
tests/MongoFramework.Tests/Linq/QueryableAsyncExtensions_SumTests.cs
Bruslega/EntityFramework_InterfaceLikeMongoDB
75dc865427feb0aaa43a5a6db05351714976f179
[ "MIT" ]
224
2017-08-14T08:59:16.000Z
2022-03-29T10:57:53.000Z
tests/MongoFramework.Tests/Linq/QueryableAsyncExtensions_SumTests.cs
Magicianred/MongoFramework
03bacce84bbe00c34483d81136f8c3162dc705a1
[ "MIT" ]
198
2017-09-03T08:31:53.000Z
2022-02-03T01:55:14.000Z
tests/MongoFramework.Tests/Linq/QueryableAsyncExtensions_SumTests.cs
Magicianred/MongoFramework
03bacce84bbe00c34483d81136f8c3162dc705a1
[ "MIT" ]
35
2017-01-21T17:53:24.000Z
2022-01-18T11:02:10.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using MongoFramework.Infrastructure; using MongoFramework.Infrastructure.Linq; using MongoFramework.Infrastructure.Mapping; using MongoFramework.Linq; namespace MongoFramework.Tests.Linq { [TestClass] public class QueryableAsyncExtensions_SumTests : TestBase { public class QueryableAsyncSumModel { public string Id { get; set; } public string Title { get; set; } public int Int32Number { get; set; } public decimal DecimalNumber { get; set; } public double DoubleNumber { get; set; } public float FloatNumber { get; set; } public long LongNumber { get; set; } public int? NullableInt32Number { get; set; } public decimal? NullableDecimalNumber { get; set; } public double? NullableDoubleNumber { get; set; } public float? NullableFloatNumber { get; set; } public long? NullableLongNumber { get; set; } } [TestMethod] public async Task SumAsync_Int32_NoValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); var result = await queryable.Select(e => e.Int32Number).SumAsync(); Assert.AreEqual(0, result); } [TestMethod] public async Task SumAsync_Int32_HasValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Int32_HasValue.1", Int32Number = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Int32_HasValue.2", Int32Number = 9 }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.Select(e => e.Int32Number).SumAsync(); Assert.AreEqual(14, result); } [TestMethod] public async Task SumAsync_Int32_WithSelector() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Int32_WithSelector.1", Int32Number = 7 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Int32_WithSelector.2", Int32Number = 5 }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.SumAsync(e => e.Int32Number); Assert.AreEqual(12, result); } [TestMethod] public async Task SumAsync_NullableInt32_NoValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); var result = await queryable.Select(e => e.NullableInt32Number).SumAsync(); Assert.IsNull(result); } [TestMethod] public async Task SumAsync_NullableInt32_HasValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableInt32_HasValue.1", NullableInt32Number = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableInt32_HasValue.2", NullableInt32Number = 9 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableInt32_HasValue.3" }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.Select(e => e.NullableInt32Number).SumAsync(); Assert.AreEqual(14, result); } [TestMethod] public async Task SumAsync_NullableInt32_WithSelector() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableInt32_WithSelector.1", NullableInt32Number = 7 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableInt32_WithSelector.2", NullableInt32Number = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableInt32_WithSelector.3" }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.SumAsync(e => e.NullableInt32Number); Assert.AreEqual(12, result); } [TestMethod] public async Task SumAsync_Decimal_NoValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); var result = await queryable.Select(e => e.DecimalNumber).SumAsync(); Assert.AreEqual(0, result); } [TestMethod] public async Task SumAsync_Decimal_HasValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Decimal_HasValue.1", DecimalNumber = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Decimal_HasValue.2", DecimalNumber = 9 }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.Select(e => e.DecimalNumber).SumAsync(); Assert.AreEqual(14, result); } [TestMethod] public async Task SumAsync_Decimal_WithSelector() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Decimal_WithSelector.1", DecimalNumber = 7 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Decimal_WithSelector.2", DecimalNumber = 5 }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.SumAsync(e => e.DecimalNumber); Assert.AreEqual(12, result); } [TestMethod] public async Task SumAsync_NullableDecimal_NoValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); var result = await queryable.Select(e => e.NullableDecimalNumber).SumAsync(); Assert.IsNull(result); } [TestMethod] public async Task SumAsync_NullableDecimal_HasValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableDecimal_HasValue.1", NullableDecimalNumber = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableDecimal_HasValue.2", NullableDecimalNumber = 9 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableDecimal_HasValue.3" }, EntityEntryState.Added); context.SaveChanges(); var a = queryable.Select(e => e.NullableDecimalNumber).Sum(); var result = await queryable.Select(e => e.NullableDecimalNumber).SumAsync(); Assert.AreEqual(14, result); } [TestMethod] public async Task SumAsync_NullableDecimal_WithSelector() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableDecimal_WithSelector.1", NullableDecimalNumber = 7 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableDecimal_WithSelector.2", NullableDecimalNumber = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableDecimal_WithSelector.3" }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.SumAsync(e => e.NullableDecimalNumber); Assert.AreEqual(12, result); } [TestMethod] public async Task SumAsync_Double_NoValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); var result = await queryable.Select(e => e.DoubleNumber).SumAsync(); Assert.AreEqual(0, result); } [TestMethod] public async Task SumAsync_Double_HasValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Double_HasValue.1", DoubleNumber = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Double_HasValue.2", DoubleNumber = 9 }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.Select(e => e.DoubleNumber).SumAsync(); Assert.AreEqual(14, result); } [TestMethod] public async Task SumAsync_Double_WithSelector() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Double_WithSelector.1", DoubleNumber = 7 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Double_WithSelector.2", DoubleNumber = 5 }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.SumAsync(e => e.DoubleNumber); Assert.AreEqual(12, result); } [TestMethod] public async Task SumAsync_NullableDouble_NoValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); var result = await queryable.Select(e => e.NullableDoubleNumber).SumAsync(); Assert.IsNull(result); } [TestMethod] public async Task SumAsync_NullableDouble_HasValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableDouble_HasValue.1", NullableDoubleNumber = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableDouble_HasValue.2", NullableDoubleNumber = 9 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableDouble_HasValue.3" }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.Select(e => e.NullableDoubleNumber).SumAsync(); Assert.AreEqual(14, result); } [TestMethod] public async Task SumAsync_NullableDouble_WithSelector() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableDouble_WithSelector.1", NullableDoubleNumber = 7 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableDouble_WithSelector.2", NullableDoubleNumber = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableDouble_WithSelector.3" }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.SumAsync(e => e.NullableDoubleNumber); Assert.AreEqual(12, result); } [TestMethod] public async Task SumAsync_Float_NoValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); var result = await queryable.Select(e => e.FloatNumber).SumAsync(); Assert.AreEqual(0, result); } [TestMethod] public async Task SumAsync_Float_HasValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Float_HasValue.1", FloatNumber = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Float_HasValue.2", FloatNumber = 9 }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.Select(e => e.FloatNumber).SumAsync(); Assert.AreEqual(14, result); } [TestMethod] public async Task SumAsync_Float_WithSelector() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Float_WithSelector.1", FloatNumber = 7 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Float_WithSelector.2", FloatNumber = 5 }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.SumAsync(e => e.FloatNumber); Assert.AreEqual(12, result); } [TestMethod] public async Task SumAsync_NullableFloat_NoValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); var result = await queryable.Select(e => e.NullableFloatNumber).SumAsync(); Assert.IsNull(result); } [TestMethod] public async Task SumAsync_NullableFloat_HasValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableFloat_HasValue.1", NullableFloatNumber = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableFloat_HasValue.2", NullableFloatNumber = 9 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableFloat_HasValue.3" }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.Select(e => e.NullableFloatNumber).SumAsync(); Assert.AreEqual(14, result); } [TestMethod] public async Task SumAsync_NullableFloat_WithSelector() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableFloat_WithSelector.1", NullableFloatNumber = 7 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableFloat_WithSelector.2", NullableFloatNumber = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableFloat_WithSelector.3" }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.SumAsync(e => e.NullableFloatNumber); Assert.AreEqual(12, result); } [TestMethod] public async Task SumAsync_Long_NoValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); var result = await queryable.Select(e => e.LongNumber).SumAsync(); Assert.AreEqual(0, result); } [TestMethod] public async Task SumAsync_Long_HasValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Long_HasValue.1", LongNumber = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Long_HasValue.2", LongNumber = 9 }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.Select(e => e.LongNumber).SumAsync(); Assert.AreEqual(14, result); } [TestMethod] public async Task SumAsync_Long_WithSelector() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Long_WithSelector.1", LongNumber = 7 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_Long_WithSelector.2", LongNumber = 5 }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.SumAsync(e => e.LongNumber); Assert.AreEqual(12, result); } [TestMethod] public async Task SumAsync_NullableLong_NoValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); var result = await queryable.Select(e => e.NullableLongNumber).SumAsync(); Assert.IsNull(result); } [TestMethod] public async Task SumAsync_NullableLong_HasValue() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableLong_HasValue.1", NullableLongNumber = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableLong_HasValue.2", NullableLongNumber = 9 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableLong_HasValue.3" }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.Select(e => e.NullableLongNumber).SumAsync(); Assert.AreEqual(14, result); } [TestMethod] public async Task SumAsync_NullableLong_WithSelector() { EntityMapping.RegisterType(typeof(QueryableAsyncSumModel)); var connection = TestConfiguration.GetConnection(); var context = new MongoDbContext(connection); var provider = new MongoFrameworkQueryProvider<QueryableAsyncSumModel>(connection); var queryable = new MongoFrameworkQueryable<QueryableAsyncSumModel>(provider); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableLong_WithSelector.1", NullableLongNumber = 7 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableLong_WithSelector.2", NullableLongNumber = 5 }, EntityEntryState.Added); context.ChangeTracker.SetEntityState(new QueryableAsyncSumModel { Title = "SumAsync_NullableLong_WithSelector.3" }, EntityEntryState.Added); context.SaveChanges(); var result = await queryable.SumAsync(e => e.NullableLongNumber); Assert.AreEqual(12, result); } } }
47.599222
173
0.788114
ae867a1a61b8cf5945f576fc2bc0189f630cb2e3
2,034
cs
C#
test/WebJobs.Script.Tests.E2E.Shared/ArmAuthenticationHelpers.cs
mgravell/azure-functions-host
b244a9b8db76c2334b1247e7d15c3d01cd779d4d
[ "Apache-2.0", "MIT" ]
1,454
2018-02-04T02:21:11.000Z
2022-03-31T02:02:07.000Z
test/WebJobs.Script.Tests.E2E.Shared/ArmAuthenticationHelpers.cs
mgravell/azure-functions-host
b244a9b8db76c2334b1247e7d15c3d01cd779d4d
[ "Apache-2.0", "MIT" ]
4,782
2018-02-03T06:59:44.000Z
2022-03-31T22:00:57.000Z
test/WebJobs.Script.Tests.E2E.Shared/ArmAuthenticationHelpers.cs
mgravell/azure-functions-host
b244a9b8db76c2334b1247e7d15c3d01cd779d4d
[ "Apache-2.0", "MIT" ]
290
2018-02-05T09:57:39.000Z
2022-03-31T19:49:54.000Z
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace WebJobs.Script.Tests.EndToEnd.Shared { public static class ArmAuthenticationHelpers { const string ARMResource = "https://management.core.windows.net/"; const string TokenEndpoint = "https://login.windows.net/{0}/oauth2/token"; const string SPNPayload = "resource={0}&client_id={1}&grant_type=client_credentials&client_secret={2}"; public static async Task<string> AcquireTokenBySPN(string tenantId, string clientId, string clientSecret) { var payload = string.Format(SPNPayload, WebUtility.UrlEncode(ARMResource), WebUtility.UrlEncode(clientId), WebUtility.UrlEncode(clientSecret)); var body = await HttpPost(tenantId, payload); return body.access_token; } static async Task<dynamic> HttpPost(string tenantId, string payload) { using (var client = new HttpClient()) { var address = string.Format(TokenEndpoint, tenantId); var content = new StringContent(payload, Encoding.UTF8, "application/x-www-form-urlencoded"); using (var response = await client.PostAsync(address, content)) { if (!response.IsSuccessStatusCode) { Console.WriteLine("Status: {0}", response.StatusCode); Console.WriteLine("Content: {0}", await response.Content.ReadAsStringAsync()); } response.EnsureSuccessStatusCode(); return await response.Content.ReadAsAsync<dynamic>(); } } } } }
39.882353
113
0.587021
a485099e570eec18be7d88274c366d7718fbd190
1,990
php
PHP
protected/modules/user/install/migrations/m131026_002234_prepare_hash_user_password.php
roman140176/liderA
e68e5f614165afa84b5e207dcbc50a29bd983dc5
[ "BSD-3-Clause" ]
1
2020-08-20T01:20:32.000Z
2020-08-20T01:20:32.000Z
protected/modules/user/install/migrations/m131026_002234_prepare_hash_user_password.php
roman140176/liderA
e68e5f614165afa84b5e207dcbc50a29bd983dc5
[ "BSD-3-Clause" ]
null
null
null
protected/modules/user/install/migrations/m131026_002234_prepare_hash_user_password.php
roman140176/liderA
e68e5f614165afa84b5e207dcbc50a29bd983dc5
[ "BSD-3-Clause" ]
null
null
null
<?php /** * Prepare hash field for replace password/salt fields * Класс миграций для модуля User: * * Так как MySQL не поддерживает 'Calculated default values' * http://stackoverflow.com/questions/4236912/how-to-create-calculated-field-in-mysql * мы генерируем случайную строку, которая запретит вход по старым паролям * * * @category YupeMigration * @package yupe.modules.user.install.migrations * @author YupeTeam <team@yupe.ru> * @license BSD https://raw.github.com/yupe/yupe/master/LICENSE * @link https://yupe.ru **/ class m131026_002234_prepare_hash_user_password extends yupe\components\DbMigration { public function safeUp() { $this->addColumn( '{{user_user}}', 'hash', 'string not null default ' . ( Yii::app()->getDb()->getSchema() instanceof CPgsqlSchema ? 'md5(random()::text)' // Делаем невозможность входа // по старому паролю // (генерируется случайная строка): : '"' . md5(uniqid()) . microtime() . '"' ) ); $this->dropColumn('{{user_user}}', 'password'); $this->dropColumn('{{user_user}}', 'salt'); } public function safeDown() { $this->addColumn( '{{user_user}}', 'password', 'char(32) NOT NULL DEFAULT ' . ( Yii::app()->getDb()->getSchema() instanceof CPgsqlSchema ? 'md5(random()::text)' : '"' . md5(uniqid()) . microtime() . '"' ) ); $this->addColumn( '{{user_user}}', 'salt', 'char(32) NOT NULL DEFAULT ' . ( Yii::app()->getDb()->getSchema() instanceof CPgsqlSchema ? 'md5(random()::text)' : '"' . md5(uniqid()) . microtime() . '"' ) ); $this->dropColumn('{{user_user}}', 'hash'); } }
29.701493
85
0.517588
dd7cfc9da3a8fb08d8a0b9a57cf8444752177d21
4,463
java
Java
src/main/java/academy/devonline/tictactoe/component/config/CommandLineArgumentParser.java
EgorEko/TicTackToe2022
fb4f58418f4d0bf40bc853bd172c6b34c9e45438
[ "Apache-2.0" ]
null
null
null
src/main/java/academy/devonline/tictactoe/component/config/CommandLineArgumentParser.java
EgorEko/TicTackToe2022
fb4f58418f4d0bf40bc853bd172c6b34c9e45438
[ "Apache-2.0" ]
null
null
null
src/main/java/academy/devonline/tictactoe/component/config/CommandLineArgumentParser.java
EgorEko/TicTackToe2022
fb4f58418f4d0bf40bc853bd172c6b34c9e45438
[ "Apache-2.0" ]
null
null
null
package academy.devonline.tictactoe.component.config; import academy.devonline.tictactoe.model.config.Level; import academy.devonline.tictactoe.model.config.PlayerType; import academy.devonline.tictactoe.model.config.UserInterface; import static academy.devonline.tictactoe.model.config.Level.*; import static academy.devonline.tictactoe.model.config.PlayerType.COMPUTER; import static academy.devonline.tictactoe.model.config.PlayerType.USER; import static academy.devonline.tictactoe.model.config.UserInterface.CONSOLE; import static academy.devonline.tictactoe.model.config.UserInterface.GUI; /** * @author devonline * @link http://devonline.academy/java */ public class CommandLineArgumentParser { final String[] args; public CommandLineArgumentParser(String[] args) { this.args = args; } public CommandLineArguments parse() { PlayerType player1Type = null; PlayerType player2Type = null; UserInterface userInterface = null; Level level = null; for (final String arg : args) { if (USER.name().equalsIgnoreCase(arg) || COMPUTER.name().equalsIgnoreCase(arg)) { if (player1Type == null) { player1Type = PlayerType.valueOf(arg.toUpperCase()); } else if (player2Type == null) { player2Type = PlayerType.valueOf(arg.toUpperCase()); } else { System.err.printf( "Invalid command line argument: '%s', because player types already set: player1Type='%s', player2Type='%s'!%n", arg, player1Type, player2Type ); } } else if (GUI.name().equalsIgnoreCase(arg) || CONSOLE.name().equalsIgnoreCase(arg)) { if (userInterface == null) { userInterface = UserInterface.valueOf(arg.toUpperCase()); } else { System.err.printf( "Invalid command line argument: '%s', because user interface already set: '%s'!%n", arg, userInterface ); } } else if (LEVEL1.name().equalsIgnoreCase(arg) || LEVEL2.name().equalsIgnoreCase(arg) || LEVEL3.name().equalsIgnoreCase(arg)) { if (level == null) { level = Level.valueOf(arg.toUpperCase()); } else { System.err.printf( "Invalid command line argument: '%s', because level already set: '%s'!%n", arg, level ); } } else { System.err.printf("Unsupported command line argument: '%s'%n", arg); } } if (userInterface == null) { userInterface = CONSOLE; } if (level == null) { level = LEVEL3; } if (player1Type == null) { return new CommandLineArguments(USER, COMPUTER, userInterface, level); } else if (player2Type == null) { return new CommandLineArguments(USER, player1Type, userInterface, level); } else { return new CommandLineArguments(player1Type, player2Type, userInterface, level); } } /** * @author devonline * @link http://devonline.academy/java */ public static class CommandLineArguments { private final PlayerType player1Type; private final PlayerType player2Type; private final UserInterface userInterface; private final Level level; private CommandLineArguments(final PlayerType player1Type, final PlayerType player2Type, final UserInterface userInterface, final Level level) { this.player1Type = player1Type; this.player2Type = player2Type; this.userInterface = userInterface; this.level = level; } public PlayerType getPlayer1Type() { return player1Type; } public PlayerType getPlayer2Type() { return player2Type; } public UserInterface getUserInterface() { return userInterface; } public Level getLevel() { return level; } } }
36.284553
139
0.560161
a350060aedde78920f380f6a74aab22af7ef8245
2,572
java
Java
domain-rest/jbb-frontend-rest/src/main/java/org/jbb/frontend/rest/faq/FaqTranslator.java
jbb-project/jbb
cefa12cda40804395b2d6e8bea0fb8352610b761
[ "Apache-2.0" ]
4
2017-02-23T15:35:33.000Z
2020-08-03T22:00:17.000Z
domain-rest/jbb-frontend-rest/src/main/java/org/jbb/frontend/rest/faq/FaqTranslator.java
jbb-project/jbb
cefa12cda40804395b2d6e8bea0fb8352610b761
[ "Apache-2.0" ]
1
2019-05-14T18:54:24.000Z
2019-05-14T18:54:24.000Z
domain-rest/jbb-frontend-rest/src/main/java/org/jbb/frontend/rest/faq/FaqTranslator.java
jbb-project/jbb
cefa12cda40804395b2d6e8bea0fb8352610b761
[ "Apache-2.0" ]
3
2018-03-29T15:51:09.000Z
2019-11-25T02:46:41.000Z
/* * Copyright (C) 2019 the original author or authors. * * This file is part of jBB Application Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 */ package org.jbb.frontend.rest.faq; import org.jbb.frontend.api.faq.Faq; import org.springframework.stereotype.Component; import java.util.List; import java.util.stream.Collectors; @Component("FaqDtoTranslator") public class FaqTranslator { public Faq toModel(FaqDto dto) { return Faq.builder() .categories(buildCategories(dto)) .build(); } private List<Faq.Category> buildCategories(FaqDto dto) { return dto.getCategories().stream() .map(this::toCategory) .collect(Collectors.toList()); } private Faq.Category toCategory(FaqCategoryDto categoryDto) { return Faq.Category.builder() .name(categoryDto.getName()) .questions(buildEntries(categoryDto)) .build(); } private List<Faq.Entry> buildEntries(FaqCategoryDto categoryDto) { return categoryDto.getQuestions().stream() .map(this::toEntry) .collect(Collectors.toList()); } private Faq.Entry toEntry(FaqEntryDto entryDto) { return Faq.Entry.builder() .question(entryDto.getQuestion()) .answer(entryDto.getAnswer()) .build(); } public FaqDto toDto(Faq faq) { return FaqDto.builder() .categories(buildCategoriesDto(faq)) .build(); } private List<FaqCategoryDto> buildCategoriesDto(Faq faq) { return faq.getCategories().stream() .map(this::toCategoryDto) .collect(Collectors.toList()); } private FaqCategoryDto toCategoryDto(Faq.Category category) { return FaqCategoryDto.builder() .name(category.getName()) .questions(buildEntriesDto(category.getQuestions())) .build(); } private List<FaqEntryDto> buildEntriesDto(List<Faq.Entry> questions) { return questions.stream() .map(this::toEntryDto) .collect(Collectors.toList()); } private FaqEntryDto toEntryDto(Faq.Entry question) { return FaqEntryDto.builder() .question(question.getQuestion()) .answer(question.getAnswer()) .build(); } }
29.563218
74
0.599922
cd3b2dc9073d7607a5ebf614a8a284bbf56e4a60
474
cs
C#
AirTicketAlert.Core/ValueObjects/AlertCondition.cs
soutolucas/AirTicketAlert
9b7b0e442351cb675b0a240d7039e82b21937559
[ "MIT" ]
null
null
null
AirTicketAlert.Core/ValueObjects/AlertCondition.cs
soutolucas/AirTicketAlert
9b7b0e442351cb675b0a240d7039e82b21937559
[ "MIT" ]
null
null
null
AirTicketAlert.Core/ValueObjects/AlertCondition.cs
soutolucas/AirTicketAlert
9b7b0e442351cb675b0a240d7039e82b21937559
[ "MIT" ]
null
null
null
using AirTicketAlert.Core.Entities.Interfaces; using AirTicketAlert.Core.ValueObjects.Interfaces; using System; using System.Collections.Generic; using System.Text; namespace AirTicketAlert.Core.ValueObjects { class AlertCondition : IAlertCondition { public void Add() { throw new NotImplementedException(); } public bool Check(IAlert alert) { throw new NotImplementedException(); } } }
21.545455
50
0.664557
da5def9698249f0b79b80fd3e49d9dc58e33c81f
2,412
php
PHP
tests/testcase_currency_to_words_converter.php
rdmrl/indian_currency_words
d588720702cd43119f8f8b71cf8374748a072cf1
[ "MIT" ]
null
null
null
tests/testcase_currency_to_words_converter.php
rdmrl/indian_currency_words
d588720702cd43119f8f8b71cf8374748a072cf1
[ "MIT" ]
null
null
null
tests/testcase_currency_to_words_converter.php
rdmrl/indian_currency_words
d588720702cd43119f8f8b71cf8374748a072cf1
[ "MIT" ]
null
null
null
<?php use PHPUnit\Framework\TestCase; require_once __DIR__ . '/../library/class_currency_to_words_converter.php'; class CurrencyToWordsConverterTest extends TestCase { function testConvert1() { $expected1 = "One Crore, Thirty-eight Lakh, Three Thousand and Thirty rupees and One paisa only"; $test_value1 = 13803030.01; $result1 = CurrencyToWordsConverter::convertToWords( $test_value1 ); $this->assertEquals( $result1, $expected1 ); } function testConvertPaiseOnly() { $expected = "Twenty-three paise only"; $test_value = ".23"; $result = CurrencyToWordsConverter::convertToWords( $test_value ); $this->assertEquals( $result, $expected ); } function testConvertUnits() { $expected = "One rupee and Twenty-three paise only"; $test_value = "1.23"; $result = CurrencyToWordsConverter::convertToWords( $test_value ); $this->assertEquals( $result, $expected ); } function testConvertTens() { $expected = "Thirty rupees and Twenty-three paise only"; $test_value = "30.23"; $result = CurrencyToWordsConverter::convertToWords( $test_value ); $this->assertEquals( $result, $expected ); } function testConvertHundreds() { $expected = "Four Hundred and Sixty-four rupees and Twenty-three paise only"; $test_value = "464.23"; $result = CurrencyToWordsConverter::convertToWords( $test_value ); $this->assertEquals( $result, $expected ); } function testConvertThousands() { $expected = "Seven Thousand, Nine Hundred and Eighty-three rupees and Twenty-three paise only"; $test_value = "7983.23"; $result = CurrencyToWordsConverter::convertToWords( $test_value ); $this->assertEquals( $result, $expected ); } function testConvertSeveralThousands() { $expected = "Sixty-seven Thousand, Nine Hundred and Eighty-three rupees and Twenty-three paise only"; $test_value = "67983.23"; $result = CurrencyToWordsConverter::convertToWords( $test_value ); $this->assertEquals( $result, $expected ); } function testConvertSeveralThousandsWithoutAnd() { $expected = "Sixty-seven Thousand, Nine Hundred, Eighty-three rupees, Twenty-three paise only"; $test_value = "67983.23"; $result = CurrencyToWordsConverter::convertToWords( $test_value, array( 'hundreds_separator' => ', ' ) ); $this->assertEquals( $result, $expected ); } }
27.101124
109
0.691542
29b38ff4131689adf36e4c89791f4e19a09aba06
2,804
lua
Lua
PriceTrackerEnchantingTable.lua
uladz/PriceTracker
b2c7cb69fb92731390e4b4b4b3e0a034cc421277
[ "MIT" ]
4
2016-03-31T18:29:15.000Z
2021-12-20T02:44:10.000Z
PriceTrackerEnchantingTable.lua
uladz/PriceTracker
b2c7cb69fb92731390e4b4b4b3e0a034cc421277
[ "MIT" ]
12
2016-04-06T05:28:39.000Z
2019-05-04T20:56:56.000Z
PriceTrackerEnchantingTable.lua
uladz/PriceTracker
b2c7cb69fb92731390e4b4b4b3e0a034cc421277
[ "MIT" ]
3
2020-04-12T16:16:26.000Z
2021-09-16T06:39:49.000Z
if not PriceTracker then return end local PriceTracker = PriceTracker local PriceTrackerEnchantingTable = {} PriceTracker.enchantingTable = PriceTrackerEnchantingTable PriceTrackerEnchantingTable.enchanting = ENCHANTING PriceTrackerEnchantingTable.enchantingRunes = { potency = { bagId = nil, itemIndex = nil }, essence = { bagId = nil, itemIndex = nil }, aspect = { bagId = nil, itemIndex = nil } } function PriceTrackerEnchantingTable:OnLoad(eventCode, addOnName) if(addOnName ~= "PriceTracker") then return end ZO_PreHookHandler(self.enchanting.runeSlots[1].control, "OnUpdate", function() self:OnUpdateEnchantingRune(self.enchanting.runeSlots[1], "aspect") end) ZO_PreHookHandler(self.enchanting.runeSlots[2].control, "OnUpdate", function() self:OnUpdateEnchantingRune(self.enchanting.runeSlots[2], "essence") end) ZO_PreHookHandler(self.enchanting.runeSlots[3].control, "OnUpdate", function() self:OnUpdateEnchantingRune(self.enchanting.runeSlots[3], "potency") end) ZO_PreHookHandler(self.enchanting.resultTooltip, "OnHide", function() PriceTracker:OnHideTooltip(self.enchanting.resultTooltip) end) end function PriceTrackerEnchantingTable:OnUpdateEnchantingRune(rune, runeType) if rune.bagId == self.enchantingRunes[runeType].bagId and rune.slotIndex == self.enchantingRunes[runeType].itemIndex then return end self.enchantingRunes[runeType].bagId = rune.bagId self.enchantingRunes[runeType].itemIndex = rune.slotIndex self:UpdateEnchantingTooltip() end function PriceTrackerEnchantingTable:UpdateEnchantingTooltip() if not self.enchantingRunes.potency.bagId or not self.enchantingRunes.potency.itemIndex or not self.enchantingRunes.essence.bagId or not self.enchantingRunes.essence.itemIndex or not self.enchantingRunes.aspect.bagId or not self.enchantingRunes.aspect.itemIndex then return end local name, icon, stack, sellPrice, meetsUsageRequirement, quality = GetEnchantingResultingItemInfo(self.enchantingRunes.potency.bagId, self.enchantingRunes.potency.itemIndex, self.enchantingRunes.essence.bagId, self.enchantingRunes.essence.itemIndex, self.enchantingRunes.aspect.bagId, self.enchantingRunes.aspect.itemIndex) local _, _, _, itemId, level = ZO_LinkHandler_ParseLink(GetEnchantingResultingItemLink(self.enchantingRunes.potency.bagId, self.enchantingRunes.potency.itemIndex, self.enchantingRunes.essence.bagId, self.enchantingRunes.essence.itemIndex, self.enchantingRunes.aspect.bagId, self.enchantingRunes.aspect.itemIndex)) local item = { dataEntry = { data = { name = name, stackCount = 1, purchasePrice = sellPrice, itemId = itemId, level = level, quality = quality, } } } if(meetsUsageRequirement) then PriceTracker:OnUpdateTooltip(item, self.enchanting.resultTooltip) end end
39.492958
153
0.795292
c3b99cbe6df01219ab800fd1a088f5b66dd47def
1,831
rb
Ruby
spec/sendgrid/helpers/stats/stats_response_spec.rb
magicbell-io/sendgrid-ruby
063da44770cb5eda4582c6c081b1c6a93beba607
[ "MIT" ]
590
2015-01-06T13:55:24.000Z
2022-03-25T12:20:35.000Z
spec/sendgrid/helpers/stats/stats_response_spec.rb
magicbell-io/sendgrid-ruby
063da44770cb5eda4582c6c081b1c6a93beba607
[ "MIT" ]
431
2015-01-07T18:38:53.000Z
2022-03-22T12:48:19.000Z
spec/sendgrid/helpers/stats/stats_response_spec.rb
magicbell-io/sendgrid-ruby
063da44770cb5eda4582c6c081b1c6a93beba607
[ "MIT" ]
369
2015-01-13T15:23:10.000Z
2022-03-25T04:34:06.000Z
require 'spec_helper' describe SendGrid::StatsResponse do let(:params) do [{ 'date' => '2017-10-01', 'stats' => [ { 'metrics' => { 'blocks' => 101, 'bounce_drops' => 102, 'bounces' => 103, 'clicks' => 104, 'deferred' => 105, 'delivered' => 106, 'invalid_emails' => 107, 'opens' => 108, 'processed' => 109, 'requests' => 110, 'spam_report_drops' => 111, 'spam_reports' => 112, 'unique_clicks' => 113, 'unique_opens' => 114, 'unsubscribe_drops' => 115, 'unsubscribes' => 116 } } ] }] end subject { described_class.new(params) } it 'initialized with JSON response body' do expect(subject).to be_a SendGrid::StatsResponse end describe '#metrics' do it 'returns an array of metrics' do metric = subject.metrics.first expect(subject.metrics).to be_a Array expect(metric.date.to_s).to eq('2017-10-01') expect(metric.requests).to eq(110) expect(metric.clicks).to eq(104) expect(metric.bounces).to eq(103) expect(metric.opens).to eq(108) end end context 'errors' do let(:error_params) do { 'errors' => [ { 'message' => 'end_date should be a YYYY-MM-DD formatted date' } ] } end subject { described_class.new(error_params) } describe '#errors' do it 'shows a list of errors' do expect(subject.errors).to include('end_date should be a YYYY-MM-DD formatted date') end end describe '#error?' do it 'returns true if there is an error' do expect(subject.error?).to be_truthy end end end end
24.092105
91
0.530311
0a6368f5805d4b4eb5c3b1b665cea376d4dbb55a
38,772
cs
C#
Standalone/GUI/Editor/RmlWysiwyg/RmlWysiwygComponent.cs
AnomalousMedical/Medical
ac16f069e4f8a919609ca7589ccbfae31f4810e2
[ "MIT" ]
7
2019-06-05T03:22:45.000Z
2022-03-24T20:33:19.000Z
Standalone/GUI/Editor/RmlWysiwyg/RmlWysiwygComponent.cs
AnomalousMedical/Medical
ac16f069e4f8a919609ca7589ccbfae31f4810e2
[ "MIT" ]
2
2021-07-10T10:40:27.000Z
2021-07-10T10:43:33.000Z
Standalone/GUI/Editor/RmlWysiwyg/RmlWysiwygComponent.cs
AnomalousMedical/Medical
ac16f069e4f8a919609ca7589ccbfae31f4810e2
[ "MIT" ]
1
2020-08-09T04:25:55.000Z
2020-08-09T04:25:55.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Medical.Controller.AnomalousMvc; using MyGUIPlugin; using libRocketPlugin; using Medical.GUI.AnomalousMvc; using System.Xml; using System.IO; using Engine.Editing; using Engine; using Medical.GUI.RmlWysiwyg.Elements; using FreeImageAPI; using Anomalous.libRocketWidget; using Anomalous.GuiFramework; using Anomalous.GuiFramework.Editor; namespace Medical.GUI { public class RmlWysiwygComponent : LayoutComponent { public const String DefaultImage = "~/Medical.Resources.ImagePlaceholder.png"; public delegate void ElementOffDocumentDelegate(RmlWysiwygComponent sender, IntVector2 position, String innerRmlHint, String previewElementTagType); public delegate String GetMissingRmlDelegate(String file, AnomalousMvcContext context); public event Action<RmlWysiwygComponent> RmlEdited; public event ElementOffDocumentDelegate ElementDraggedOffDocument { add { draggingElementManager.ElementDraggedOffDocument += value; } remove { draggingElementManager.ElementDraggedOffDocument -= value; } } public event ElementOffDocumentDelegate ElementDroppedOffDocument { add { draggingElementManager.ElementDroppedOffDocument += value; } remove { draggingElementManager.ElementDroppedOffDocument -= value; } } public event ElementOffDocumentDelegate ElementReturnedToDocument { add { draggingElementManager.ElementReturnedToDocument += value; } remove { draggingElementManager.ElementReturnedToDocument -= value; } } private ElementStrategyManager elementStrategyManager = new ElementStrategyManager(); private RocketWidget rocketWidget; private ImageBox rmlImage; private int imageHeight; private int imageWidth; private String documentStart = "<body>"; private String documentEnd = "</body>"; private bool disposed = false; private GuiFrameworkUICallback uiCallback; private RmlElementEditor currentEditor = null; private bool allowEdit = true; private SelectedElementManager selectedElementManager; private PreviewElement previewElement = new PreviewElement(); private DraggingElementManager draggingElementManager; private bool lastInsertBefore = false; private UndoRedoBuffer undoBuffer; private String documentName; private Action<String> undoRedoCallback; private bool changesMade = false; private RmlWysiwygViewBase rmlWysiwygViewInterface; String contentId = null; private GetMissingRmlDelegate getMissingRmlCallback; private AnomalousMvcContext context; private RmlWysiwygComponent(AnomalousMvcContext context, MyGUIViewHost viewHost, RmlWysiwygViewBase rmlWysiwygViewInterface) : base("Medical.GUI.Editor.RmlWysiwyg.RmlWysiwygComponent.layout", viewHost) { undoRedoCallback = defaultUndoRedoCallback; this.context = context; this.rmlWysiwygViewInterface = rmlWysiwygViewInterface; rmlImage = (ImageBox)widget; rocketWidget = new RocketWidget(rmlImage, viewHost.View.Transparent); rmlImage.MouseButtonPressed += rmlImage_MouseButtonPressed; rmlImage.MouseButtonReleased += rmlImage_MouseButtonReleased; rmlImage.MouseDrag += new MyGUIEvent(rmlImage_MouseDrag); rmlImage.MouseWheel += new MyGUIEvent(rmlImage_MouseWheel); rmlImage.EventScrollGesture += new MyGUIEvent(rmlImage_EventScrollGesture); imageHeight = rmlImage.Height; selectedElementManager = new SelectedElementManager(rmlImage, rocketWidget.Context); draggingElementManager = new DraggingElementManager(this); foreach (var elementStrategy in rmlWysiwygViewInterface.CustomElementStrategies) { elementStrategyManager.add(elementStrategy); } if (rmlWysiwygViewInterface.GetMissingRmlCallback != null) { getMissingRmlCallback = rmlWysiwygViewInterface.GetMissingRmlCallback; } else { getMissingRmlCallback = getDefaultMissingRml; } } public RmlWysiwygComponent(RmlWysiwygView view, AnomalousMvcContext context, MyGUIViewHost viewHost) : this(context, viewHost, view) { this.uiCallback = view.UICallback; this.undoBuffer = view.UndoBuffer; this.contentId = view.ContentId; rocketWidget.Context.ZoomLevel = view.ZoomLevel; if (view.UndoRedoCallback != null) { undoRedoCallback = view.UndoRedoCallback; } documentName = view.RmlFile; if (documentName != null) { this.FakeLoadLocation = RocketInterface.createValidFileUrl(context.ResourceProvider.getFullFilePath(documentName)); } else { this.FakeLoadLocation = RocketInterface.createValidFileUrl(context.ResourceProvider.BackingLocation); } loadDocumentFile(documentName, false); view._fireComponentCreated(this); } public RmlWysiwygComponent(RawRmlWysiwygView view, AnomalousMvcContext context, MyGUIViewHost viewHost) : this(context, viewHost, view) { if (view.FakePath != null) { this.FakeLoadLocation = RocketInterface.createValidFileUrl(context.ResourceProvider.getFullFilePath(view.FakePath)); } else { this.FakeLoadLocation = RocketInterface.createValidFileUrl(context.ResourceProvider.BackingLocation); } this.uiCallback = view.UICallback; this.undoBuffer = view.UndoBuffer; this.contentId = view.ContentId; rocketWidget.Context.ZoomLevel = view.ZoomLevel; if (view.UndoRedoCallback != null) { undoRedoCallback = view.UndoRedoCallback; } documentName = null; setDocumentRml(view.Rml, false); view._fireComponentCreated(this); } public override void Dispose() { draggingElementManager.Dispose(); previewElement.Dispose(); disposed = true; rocketWidget.Dispose(); rocketWidget = null; base.Dispose(); } public override void topLevelResized() { if (widget.Height != imageHeight || widget.Width != imageWidth) { rocketWidget.resized(); imageHeight = widget.Height; imageWidth = widget.Width; selectedElementManager.updateHighlightPosition(); updateEditorPosition(); } base.topLevelResized(); } public override void changeScale(float newScale) { base.changeScale(newScale); if (rocketWidget != null) { rocketWidget.setScale(newScale); } } public float getScale() { return rocketWidget.Context.ZoomLevel; } public void aboutToSaveRml() { if (currentEditor != null) { currentEditor.hide(); } } public void reloadDocument() { loadDocumentFile(documentName, true); } /// <summary> /// Set the current rml. If you pass true for considerAsChange the RmlEdited event will fire /// and the editor will be set as having changes. /// </summary> /// <param name="rml">The rml to set</param> /// <param name="keepScrollPosition">True to try to maintain the current scroll position.</param> /// <param name="considerAsChange">True to fire the RmlEdited event with the rml you have supplied.</param> public void setRml(String rml, bool keepScrollPosition, bool considerAsChange = false) { setDocumentRml(rml, keepScrollPosition); if (considerAsChange) { rmlModified(); } } public void insertRml(String rml) { if (allowEdit) { cancelAndHideEditor(); previewElement.hidePreviewElement(); String undoRml = UnformattedRml; insertRmlIntoDocument(rml); updateUndoStatus(undoRml); selectedElementManager.clearSelectedAndHighlightedElement(); } } public bool contains(IntVector2 position) { return widget.contains(position.x, position.y); } public void writeToGraphics(FreeImageBitmap g, Rectangle destRect) { rocketWidget.writeToGraphics(g, destRect); } internal void insertRml(String rml, String undoRml) { if (allowEdit) { insertRmlIntoDocument(rml); updateUndoStatus(undoRml); } } private void insertRmlIntoDocument(String rml) { if (allowEdit) { previewElement.hidePreviewElement(); ElementDocument document = rocketWidget.Context.GetDocument(0); using (Element div = document.CreateElement("temp")) { Element topContentElement = TopContentElement; if (selectedElementManager.HasSelection && selectedElementManager.SelectedElement != topContentElement) { Element insertInto = selectedElementManager.SelectedElement.ParentNode; if (insertInto != null) { insertInto.Insert(div, selectedElementManager.SelectedElement, lastInsertBefore); } } else { topContentElement.AppendChild(div); } div.InnerRml = rml; Element parent = div.ParentNode; Element child; Element next = div.FirstChild; while (next != null) { child = next; next = child.NextSibling; parent.InsertBefore(child, div); } parent.RemoveChild(div); rmlModified(); } } } /// <summary> /// Set the preview element at position if position is inside this widget. Returns true if the position is inside this widget. /// </summary> public bool setPreviewElement(IntVector2 position, String innerRmlHint, String previewElementTagType) { if (widget.contains(position.x, position.y)) { position.x -= widget.AbsoluteLeft; position.y -= widget.AbsoluteTop; Element toSelect = rocketWidget.Context.FindElementAtPoint(position); if (toSelect != null && !toSelect.isDescendentOf(TopContentElement)) { toSelect = null; } Element selectedElement = selectedElementManager.SelectedElement; bool insertBefore = lastInsertBefore; bool toSelectIsNotPreview = true; if (toSelect != null) { toSelectIsNotPreview = !previewElement.isPreviewOrDescendent(toSelect); if (toSelectIsNotPreview) { insertBefore = insertBeforeOrAfter(toSelect, position); } } if (toSelectIsNotPreview && (toSelect != selectedElement || insertBefore != lastInsertBefore)) { if (toSelect != null) { Element topContentElement = TopContentElement; if (toSelect != topContentElement) { selectedElementManager.SelectedElement = toSelect; previewElement.hidePreviewElement(); ElementDocument document = rocketWidget.Context.GetDocument(0); previewElement.showPreviewElement(document, innerRmlHint, toSelect.ParentNode, toSelect, previewElementTagType, insertBefore); selectedElementManager.HighlightElement = previewElement.HighlightPreviewElement; } else { selectedElementManager.SelectedElement = null; previewElement.hidePreviewElement(); ElementDocument document = rocketWidget.Context.GetDocument(0); previewElement.showPreviewElement(document, innerRmlHint, toSelect, null, previewElementTagType, insertBefore); selectedElementManager.HighlightElement = previewElement.HighlightPreviewElement; } selectedElementManager.ElementStrategy = null; } else { selectedElementManager.clearSelectedAndHighlightedElement(); previewElement.hidePreviewElement(); } lastInsertBefore = insertBefore; rocketWidget.Context.Update(); selectedElementManager.updateHighlightPosition(); rocketWidget.renderOnNextFrame(); } return true; } else { selectedElementManager.clearSelectedAndHighlightedElement(); previewElement.hidePreviewElement(); rocketWidget.renderOnNextFrame(); return false; } } public void clearPreviewElement(bool treatAsChanges = true) { selectedElementManager.clearSelectedAndHighlightedElement(); previewElement.hidePreviewElement(); rmlModified(treatAsChanges: treatAsChanges); } public void cancelAndHideEditor() { if (currentEditor != null) { currentEditor.cancelAndHide(); } } public String CurrentRml { get { String rml = UnformattedRml; if (rml != null) { rml = formatRml(rml); } return rml; } } public String UnformattedRml { get { Element topContentElemnt = TopContentElement; if (topContentElemnt != null) { String contentRml = topContentElemnt.InnerRml; StringBuilder sb = new StringBuilder(documentStart.Length + contentRml.Length + documentEnd.Length); sb.Append(documentStart); sb.Append(contentRml); sb.Append(documentEnd); return sb.ToString(); } return null; } } public Element TopContentElement { get { if (rocketWidget == null) { return null; } Element document = rocketWidget.Context.GetDocument(0); if (document == null) { return null; } if (!String.IsNullOrEmpty(contentId)) { Element contentElement = document.GetElementById(contentId); if (contentElement != null) { return contentElement; } } Variant templateName = document.GetAttribute("template"); if (templateName == null) { return document; } else { Template template = TemplateCache.GetTemplate(templateName.StringValue); if (template != null) { Element contentDocument = document.GetElementById(template.Content); if (contentDocument != null) { return contentDocument; } else { return document; } } else { return document; } } } } public bool ChangesMade { get { return changesMade; } set { changesMade = value; } } public String FakeLoadLocation { get; set; } internal IntVector2 localCoord(IntVector2 position) { position.x -= widget.AbsoluteLeft; position.y -= widget.AbsoluteTop; return position; } public void deleteElement(Element element) { Element parent = element.ParentNode; if (parent != null) { parent.RemoveChild(element); if (element == selectedElementManager.SelectedElement) { selectedElementManager.clearSelectedAndHighlightedElement(); } } } private String formatRml(String inputRml) { try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(inputRml); StringBuilder sb = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = "\t"; settings.NewLineChars = "\n"; settings.NewLineHandling = NewLineHandling.Replace; settings.OmitXmlDeclaration = true; //.Net wants to write the string as UTF-16, but in libRocket rml files are always UTF-8, so we don't need a declaration and it would be wrong anyway. using (XmlWriter xmlWriter = XmlWriter.Create(sb, settings)) { xmlDoc.Save(xmlWriter); } return sb.ToString(); } catch (Exception ex) { MessageBox.show("There was an error parsing your RML back into a nice format.\nYou will want to correct it as it means your XML is malformed.\nThe error was:\n" + ex.Message, "RML Format Error", MessageBoxStyle.IconWarning | MessageBoxStyle.Ok); return inputRml; } } private void saveDocumentStartAndEnd(String inputRml) { int bodyStart = inputRml.IndexOf("<body", StringComparison.InvariantCultureIgnoreCase); if (bodyStart > -1) { bodyStart = inputRml.IndexOf(">", bodyStart, StringComparison.InvariantCultureIgnoreCase) + 1; if (bodyStart > -1) { documentStart = inputRml.Substring(0, bodyStart); int closeBodyStart = inputRml.IndexOf("</body", bodyStart, StringComparison.InvariantCultureIgnoreCase); if (closeBodyStart > -1) { documentEnd = inputRml.Substring(closeBodyStart); allowEdit = true; } else { allowEdit = false; MessageBox.show("Cannot find an closing body tag.\nPlease ensure that your source has a closing </body> element.\nYou will not be able to edit elements in the document until this is fixed.", "RML Format Error", MessageBoxStyle.IconWarning | MessageBoxStyle.Ok); bodyStart = 0; } } else { allowEdit = false; MessageBox.show("Cannot find an opening body tag.\nPlease ensure that your source has an opening <body> element.\nYou will not be able to edit elements in the document until this is fixed.", "RML Format Error", MessageBoxStyle.IconWarning | MessageBoxStyle.Ok); bodyStart = 0; } } else { allowEdit = false; MessageBox.show("Cannot find an opening body tag.\nPlease ensure that your source has an opening <body> element.\nYou will not be able to edit elements in the document until this is fixed.", "RML Format Error", MessageBoxStyle.IconWarning | MessageBoxStyle.Ok); bodyStart = 0; } } void rmlImage_EventScrollGesture(Widget source, EventArgs e) { selectedElementManager.updateHighlightPosition(); } void rmlImage_MouseWheel(Widget source, EventArgs e) { selectedElementManager.updateHighlightPosition(); } void rmlImage_MouseDrag(Widget source, EventArgs e) { MouseEventArgs me = (MouseEventArgs)e; if (me.Button == Engine.Platform.MouseButtonCode.MB_BUTTON0) { selectedElementManager.updateHighlightPosition(); draggingElementManager.dragging(me.Position); } } void rmlImage_MouseButtonPressed(Widget source, EventArgs e) { MouseEventArgs me = (MouseEventArgs)e; if (me.Button == Engine.Platform.MouseButtonCode.MB_BUTTON0) { requestFocus(); IntVector2 mousePosition = me.Position; IntVector2 localPosition = localCoord(mousePosition); Element element = selectedElementManager.SelectedElement; if (element == null || !element.IsPointWithinElement(localPosition)) { element = rocketWidget.Context.FindElementAtPoint(localPosition); } if (elementStrategyManager[element].AllowDragAndDrop) { draggingElementManager.dragStart(mousePosition, element, elementStrategyManager[element].PreviewIconName); } } } void rmlImage_MouseButtonReleased(Widget source, EventArgs e) { MouseEventArgs me = (MouseEventArgs)e; if (me.Button == Engine.Platform.MouseButtonCode.MB_BUTTON0) { Element element = draggingElementManager.DragElement; //This will be the clicked element, or null if the element was moved ElementStrategy elementStrategy = elementStrategyManager[element]; IntVector2 mousePosition = me.Position; draggingElementManager.dragEnded(mousePosition); if (!allowEdit) { //Break if they cannot edit return; } Element altElement = rocketWidget.Context.FindElementAtPoint(localCoord(mousePosition), element); if (altElement != null) //Another element was found see if we can use it { ElementStrategy altStrategy = elementStrategyManager[altElement]; if (altStrategy != elementStrategyManager.DefaultStrategy) { element = altElement; elementStrategy = altStrategy; } } if (element != null) { showRmlElementEditor(element, elementStrategy); } else { cancelAndHideEditor(); selectedElementManager.clearSelectedAndHighlightedElement(); } } } private void showRmlElementEditor(Element element, ElementStrategy strategy) { if (currentEditor == null || selectedElementManager.SelectedElement != element) { cancelAndHideEditor(); RmlElementEditor editor = strategy.openEditor(element, uiCallback, 0, 0); if (editor == null) { //The editor was null, which means editing is not supported so just clear the selection. selectedElementManager.clearSelectedAndHighlightedElement(); return; //Return here to prevent more execution } editor.UndoRml = UnformattedRml; //Everything is good so setup. editor.Hiding += (src, arg) => { if (!disposed) { if (editor.deleteIfNeeded(this)) { rmlModified(); updateUndoStatus(editor.UndoRml, true); editor.UndoRml = UnformattedRml; } selectedElementManager.AllowShowResizeHandles = false; } }; editor.Hidden += (src, arg) => { if (currentEditor == editor) { currentEditor = null; } }; editor.ChangesMade += (applyElement) => { TwoWayCommand additionalUndoOperations; if (!disposed && editor.applyChanges(this, out additionalUndoOperations)) { rocketWidget.Context.GetDocument(0).MakeDirtyForScaleChange(); rmlModified(); updateUndoStatus(editor.UndoRml, true, additionalUndoOperations); editor.UndoRml = UnformattedRml; } }; editor.MoveElementUp += upElement => { Element previousSibling = upElement.PreviousSibling; if (previousSibling != null) { Element parent = upElement.ParentNode; if (parent != null) { upElement.addReference(); parent.RemoveChild(upElement); parent.InsertBefore(upElement, previousSibling); upElement.removeReference(); rmlModified(); updateUndoStatus(editor.UndoRml); editor.UndoRml = UnformattedRml; } } }; editor.MoveElementDown += downElement => { Element parent = downElement.ParentNode; if (parent != null) { Element nextSibling = downElement.NextSibling; if (nextSibling != null) { downElement.addReference(); parent.RemoveChild(downElement); nextSibling = nextSibling.NextSibling; if (nextSibling != null) { parent.InsertBefore(downElement, nextSibling); } else { parent.AppendChild(downElement); } downElement.removeReference(); rmlModified(); updateUndoStatus(editor.UndoRml); editor.UndoRml = UnformattedRml; } } }; editor.DeleteElement += deleteElement => { Element parent = deleteElement.ParentNode; if (parent != null) { Element nextSelectionElement = deleteElement.NextSibling; if (nextSelectionElement == null) { nextSelectionElement = deleteElement.PreviousSibling; } parent.RemoveChild(deleteElement); rmlModified(false); updateUndoStatus(editor.UndoRml); editor.UndoRml = UnformattedRml; if (nextSelectionElement != null) { showRmlElementEditor(nextSelectionElement, elementStrategyManager[nextSelectionElement]); } else { selectedElementManager.clearSelectedAndHighlightedElement(); } } }; currentEditor = editor; selectedElementManager.SelectedElement = element; selectedElementManager.setHighlightElement(element, strategy.HighlightProvider); selectedElementManager.ElementStrategy = strategy; selectedElementManager.AllowShowResizeHandles = true; updateEditorPosition(); } } private void updateEditorPosition() { Element element = selectedElementManager.SelectedElement; var editor = currentEditor; if (element != null && editor != null) { int left, top; switch (ViewHost.View.ElementName.LocationHint) { case ViewLocations.Right: left = widget.AbsoluteLeft - editor.Width; top = (int)element.AbsoluteTop + rocketWidget.AbsoluteTop; break; case ViewLocations.Top: left = widget.Width / 2 + widget.AbsoluteLeft - editor.Width / 2; top = widget.AbsoluteTop + widget.Height; break; case ViewLocations.Bottom: left = widget.Width / 2 + widget.AbsoluteLeft - editor.Width / 2; top = rocketWidget.AbsoluteTop - editor.Height; break; case ViewLocations.Left: left = widget.AbsoluteLeft + widget.Width; top = (int)element.AbsoluteTop + rocketWidget.AbsoluteTop; break; default: left = (int)(widget.AbsoluteLeft + element.AbsoluteLeft + element.ClientWidth); top = (int)element.AbsoluteTop + rocketWidget.AbsoluteTop; break; } editor.setPosition(left, top, true); } } private void rmlModified(bool updateHighlights = true, bool treatAsChanges = true) { if (treatAsChanges) { changesMade = true; if (RmlEdited != null) { RmlEdited.Invoke(this); } } if (updateHighlights) { rocketWidget.Context.Update(); selectedElementManager.updateHighlightPosition(); } rocketWidget.renderOnNextFrame(); } private bool insertBeforeOrAfter(Element element, IntVector2 position) { return position.y - element.AbsoluteTop < element.OffsetHeight / 2; } public void updateUndoStatus(String oldMarkup, bool check = false, TwoWayCommand additionalUndoOperations = null) { //This is a hacky way to check for changes (optionally) it should not be needed when the popup editor is overhauled. //You can remove check and keep only the line in the if statement when you no longer need the check. String currentMarkup = UnformattedRml; if (!check || currentMarkup != oldMarkup) { if (additionalUndoOperations == null) { undoBuffer.pushAndSkip(new TwoWayDelegateCommand<String, String>(currentMarkup, oldMarkup, new TwoWayDelegateCommand<string, string>.Funcs() { ExecuteFunc = undoRedoCallback, UndoFunc = undoRedoCallback })); } else { undoBuffer.pushAndSkip(new TwoWayDelegateCommand<String, String>(currentMarkup, oldMarkup, new TwoWayDelegateCommand<string, string>.Funcs() { ExecuteFunc = rml => { undoRedoCallback(rml); additionalUndoOperations.execute(); }, UndoFunc = rml => { undoRedoCallback(rml); additionalUndoOperations.undo(); } })); } } } private void defaultUndoRedoCallback(String rml) { cancelAndHideEditor(); if (setDocumentRml(rml, true)) { rmlModified(); } } private void loadDocumentFile(String file, bool maintainScrollPosition) { if (file != null) { if (context.ResourceProvider.fileExists(file)) { using (StreamReader sr = new StreamReader(context.ResourceProvider.openFile(file))) { setDocumentRml(sr.ReadToEnd(), maintainScrollPosition); } } else { setDocumentRml(getMissingRmlCallback(file, context), false); } } } private bool setDocumentRml(String rml, bool maintainScrollPosition) { float scrollLeft = 0.0f; float scrollTop = 0.0f; Element topContentElement; if (maintainScrollPosition) { topContentElement = TopContentElement; if (topContentElement != null) { scrollLeft = topContentElement.ScrollLeft; scrollTop = topContentElement.ScrollTop; } } RocketWidgetInterface.clearAllCaches(); rocketWidget.Context.UnloadAllDocuments(); cancelAndHideEditor(); selectedElementManager.clearSelectedAndHighlightedElement(); if (rml != null) { using (ElementDocument document = rocketWidget.Context.LoadDocumentFromMemory(rml, FakeLoadLocation)) { if (document != null) { saveDocumentStartAndEnd(rml); document.Show(); rocketWidget.removeFocus(); rocketWidget.renderOnNextFrame(); if (maintainScrollPosition) { topContentElement = TopContentElement; if (topContentElement != null) { topContentElement.ScrollLeft = scrollLeft; topContentElement.ScrollTop = scrollTop; } } return true; } } } return false; } private void requestFocus() { rmlWysiwygViewInterface._fireRequestFocus(); } private string getDefaultMissingRml(string file, AnomalousMvcContext context) { using (StreamReader stream = new StreamReader(this.GetType().Assembly.GetManifestResourceStream("Medical.GUI.Editor.RmlWysiwyg.MissingFile.rml"))) { return String.Format(stream.ReadToEnd(), file, context.ResourceProvider.BackingLocation); } } } }
39.847893
286
0.500129
ee0dba3ed2367d093b1c0e42eba43391b8f71e4a
12,406
go
Go
store/moveManager.go
rstorr/mulifs
12d5dd70a881f6444c17771306fea24646cadfbe
[ "Apache-2.0" ]
19
2016-03-24T22:12:42.000Z
2022-03-06T00:15:19.000Z
store/moveManager.go
rstorr/mulifs
12d5dd70a881f6444c17771306fea24646cadfbe
[ "Apache-2.0" ]
3
2016-02-07T21:01:22.000Z
2016-07-21T14:32:35.000Z
store/moveManager.go
rstorr/mulifs
12d5dd70a881f6444c17771306fea24646cadfbe
[ "Apache-2.0" ]
3
2016-09-12T22:04:11.000Z
2020-12-11T04:58:22.000Z
// Copyright 2016 Danko Miocevic. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Author: Danko Miocevic // Package store is package for managing the database that stores // the information about the songs, artists and albums. package store import ( "encoding/json" "errors" "github.com/dankomiocevic/mulifs/musicmgr" "github.com/dankomiocevic/mulifs/playlistmgr" "os" "path/filepath" "bazil.org/fuse" "github.com/boltdb/bolt" "github.com/golang/glog" ) // MoveSongs changes the Songs path. // It modifies the information in the database // and updates the tags to match the new location. // It also moves the actual file into the new // location. func MoveSongs(oldArtist, oldAlbum, oldName, newArtist, newAlbum, newName, path, mPoint string) (string, error) { glog.Infof("Moving song from Artist: %s, Album: %s, name: %s and path: %s to Artist: %s, Album: %s, name: %s\n", oldArtist, oldAlbum, oldName, path, newArtist, newAlbum, newName) // Check file extension. extension := filepath.Ext(path) if extension != ".mp3" { glog.Info("Wrong file format.") return "", errors.New("Wrong file format.") } rootPoint := mPoint if rootPoint[len(rootPoint)-1] != '/' { rootPoint = rootPoint + "/" } newFileName := GetCompatibleString(newName[:len(newName)-len(extension)]) + extension newPath := rootPoint + newArtist + "/" + newAlbum + "/" newFullPath := newPath + newFileName // Get all the Playlists form the file. songStore, err := GetSong(oldArtist, oldAlbum, oldName) if err != nil { glog.Infof("Cannot get the file from the database: %s\n", err) } // Delete the song from all the playlists for _, pl := range songStore.Playlists { DeletePlaylistSong(pl, oldName, true) } // Rename the file err = os.Rename(path, newFullPath) if err != nil { glog.Infof("Cannot rename the file: %s\n", err) return "", err } // Delete the song from the database err = DeleteSong(oldArtist, oldAlbum, oldName, mPoint) if err != nil { glog.Infof("Cannot delete song: %s\n", err) return "", err } // Change the tags in the file. musicmgr.SetMp3Tags(newArtist, newAlbum, newName, newFullPath) // Add the song again to the database. _, err = CreateSong(newArtist, newAlbum, newName, newPath) if err != nil { glog.Infof("Cannot create song in the db: %s\n", err) return "", err } // Add the song to all the playlists. for _, pl := range songStore.Playlists { file := playlistmgr.PlaylistFile{ Title: newName, Artist: newArtist, Album: newAlbum, Path: newPath, } AddFileToPlaylist(file, pl) RegeneratePlaylistFile(pl, mPoint) } return newFileName, nil } // processNewArtist returns all the albums inside an Artist and // prepares the new folder for the new Artist. // It also creates the description files and Buckets in the DB. func processNewArtist(newArtist, oldArtist string) ([]string, error) { var albums []string db, err := bolt.Open(config.DbPath, 0600, nil) if err != nil { glog.Error("Error opening the database.") return nil, err } defer db.Close() newArtistRaw := newArtist newArtist = GetCompatibleString(newArtist) err = db.Update(func(tx *bolt.Tx) error { root := tx.Bucket([]byte("Artists")) // Get oldArtist Bucket oldArtistBucket := root.Bucket([]byte(oldArtist)) if oldArtistBucket == nil { glog.Info("Source Artist not found.") return errors.New("Artist not found") } // Get the description file or create it if it does not exist oldDescription := oldArtistBucket.Get([]byte(".description")) if oldDescription != nil { var oldArtistStore ArtistStore err := json.Unmarshal(oldDescription, &oldArtistStore) if err == nil { albums = make([]string, len(oldArtistStore.ArtistAlbums)) copy(albums, oldArtistStore.ArtistAlbums) } else { albums = make([]string, 0) } } // Create the bucket artistBucket, err := root.CreateBucketIfNotExists([]byte(newArtist)) if err != nil { glog.Info("Cannot create Artist bucket.") return fuse.EIO } // Get the description file or create it if it does not exist description := artistBucket.Get([]byte(".description")) var artistStore ArtistStore if description == nil { artistStore = ArtistStore{ ArtistName: newArtistRaw, ArtistPath: newArtist, ArtistAlbums: albums, } } else { err := json.Unmarshal(description, &artistStore) if err != nil { return fuse.EIO } copy(artistStore.ArtistAlbums, albums) } encoded, err := json.Marshal(artistStore) if err != nil { glog.Info("Cannot encode description JSON.") return fuse.EIO } artistBucket.Put([]byte(".description"), encoded) return nil }) return albums, err } // processNewAlbum returns all the songs inside an Album and // prepares the new folder for the new Album. // It also creates the description files and Buckets in the DB. func processNewAlbum(newArtist, newAlbum, oldArtist, oldAlbum string) ([][]byte, error) { var songs [][]byte db, err := bolt.Open(config.DbPath, 0600, nil) if err != nil { glog.Error("Error opening the database.") return nil, err } defer db.Close() newAlbumRaw := newAlbum newAlbum = GetCompatibleString(newAlbum) err = db.Update(func(tx *bolt.Tx) error { root := tx.Bucket([]byte("Artists")) artistBucket := root.Bucket([]byte(newArtist)) if artistBucket == nil { glog.Info("Destination Artist not found.") return errors.New("Artist not found.") } // Create the bucket albumBucket, err := artistBucket.CreateBucketIfNotExists([]byte(newAlbum)) if err != nil { glog.Info("Cannot create Album bucket.") return fuse.EIO } // Get the description file or create it if it does not exist description := albumBucket.Get([]byte(".description")) if description == nil { albumStore := &AlbumStore{ AlbumName: newAlbumRaw, AlbumPath: newAlbum, } encoded, err := json.Marshal(albumStore) if err != nil { glog.Info("Cannot encode description JSON.") return fuse.EIO } albumBucket.Put([]byte(".description"), encoded) } // Update the Artist description var artistStore ArtistStore // Update the description of the Artist descValue := artistBucket.Get([]byte(".description")) if descValue == nil { artistStore.ArtistName = newArtist artistStore.ArtistPath = newArtist artistStore.ArtistAlbums = []string{newAlbum} } else { err := json.Unmarshal(descValue, &artistStore) if err != nil { artistStore.ArtistName = newArtist artistStore.ArtistPath = newArtist artistStore.ArtistAlbums = []string{newAlbum} } var found bool = false for _, a := range artistStore.ArtistAlbums { if a == newAlbum { found = true break } } if found == false { artistStore.ArtistAlbums = append(artistStore.ArtistAlbums, newAlbum) } } encoded, err := json.Marshal(artistStore) if err != nil { return err } artistBucket.Put([]byte(".description"), encoded) // Get oldArtist Bucket oldArtistBucket := root.Bucket([]byte(oldArtist)) if oldArtistBucket == nil { glog.Info("Source Artist not found.") return errors.New("Artist not found") } oldAlbumBucket := oldArtistBucket.Bucket([]byte(oldAlbum)) if oldAlbumBucket == nil { glog.Info("Source Album not found.") return errors.New("Album not found") } // Remove the Album from the Artist description descValue = oldArtistBucket.Get([]byte(".description")) if descValue != nil { err := json.Unmarshal(descValue, &artistStore) if err == nil { for i, a := range artistStore.ArtistAlbums { if a == oldAlbum { artistStore.ArtistAlbums = append(artistStore.ArtistAlbums[:i], artistStore.ArtistAlbums[i+1:]...) break } } encoded, err := json.Marshal(artistStore) if err != nil { return err } oldArtistBucket.Put([]byte(".description"), encoded) } } // Get all the songs and store it in a temporary slice c := oldAlbumBucket.Cursor() for k, v := c.First(); k != nil; k, v = c.Next() { var temp []byte if k[0] == '.' { continue } temp = make([]byte, len(v)) copy(temp, v) songs = append(songs, temp) } return nil }) return songs, err } // MoveAlbum changes the album path. // It modifies the information in the database // and updates the tags to match the new location // on every song inside the album. // It also moves the actual files into the new location. func MoveAlbum(oldArtist, oldAlbum, newArtist, newAlbum, mPoint string) error { glog.Infof("Moving Album from Artist: %s, Album: %s to Artist: %s, Album: %s\n", oldArtist, oldAlbum, newArtist, newAlbum) // Check that the file is being moved in the same level // Album -> Album if len(oldArtist) < 1 || len(newArtist) < 1 { glog.Info("Cannot change Album to Artist.") return fuse.EPERM } if len(oldAlbum) < 1 || len(newAlbum) < 1 { glog.Info("Cannot change Album to Artist.") return fuse.EPERM } rootPoint := mPoint if rootPoint[len(rootPoint)-1] != '/' { rootPoint = rootPoint + "/" } newPath := rootPoint + newArtist + "/" + newAlbum + "/" // Create the directory if not exists src, err := os.Stat(newPath) if err != nil || !src.IsDir() { err := os.Mkdir(newPath, 0777) if err != nil { glog.Infof("Cannot create the new directory: %s.", err) return fuse.EIO } } var songs [][]byte songs, err = processNewAlbum(newArtist, newAlbum, oldArtist, oldAlbum) if err != nil { return err } glog.Infof("Moving %d songs.\n", len(songs)) // Move all the songs inside the Album for _, element := range songs { var song SongStore err := json.Unmarshal(element, &song) if err != nil { glog.Info("Cannot unmarshall JSON") continue } MoveSongs(oldArtist, oldAlbum, song.SongPath, newArtist, newAlbum, song.SongPath, song.SongFullPath, mPoint) } db, err := bolt.Open(config.DbPath, 0600, nil) if err != nil { glog.Error("Error opening the database.") return err } defer db.Close() // Finally delete the old Artist bucket err = db.Update(func(tx *bolt.Tx) error { root := tx.Bucket([]byte("Artists")) artistBucket := root.Bucket([]byte(oldArtist)) if artistBucket == nil { return errors.New("Artist not found.") } err = artistBucket.DeleteBucket([]byte(oldAlbum)) return err }) if err != nil { return fuse.EIO } return nil } // MoveArtist changes the Artist path. // It modifies the information in the database // and updates the tags to match the new location // on every song inside every album. // It also moves the actual files into the new location. func MoveArtist(oldArtist, newArtist, mPoint string) error { glog.Infof("Moving Artist from: %s to %s\n", oldArtist, newArtist) // Check that all the information is ready if len(oldArtist) < 1 || len(newArtist) < 1 { return fuse.EIO } rootPoint := mPoint if rootPoint[len(rootPoint)-1] != '/' { rootPoint = rootPoint + "/" } newPath := rootPoint + newArtist + "/" // Create the directory if not exists src, err := os.Stat(newPath) if err != nil || !src.IsDir() { err := os.Mkdir(newPath, 0777) if err != nil { glog.Infof("Cannot create the new directory: %s.", err) return fuse.EIO } } var albums []string albums, err = processNewArtist(newArtist, oldArtist) if err != nil { return err } glog.Infof("Moving %d albums.\n", len(albums)) // Move all the songs inside the Album for _, element := range albums { MoveAlbum(oldArtist, element, newArtist, element, mPoint) } db, err := bolt.Open(config.DbPath, 0600, nil) if err != nil { glog.Error("Error opening the database.") return err } defer db.Close() // Finally delete the old Album bucket err = db.Update(func(tx *bolt.Tx) error { root := tx.Bucket([]byte("Artists")) err = root.DeleteBucket([]byte(oldArtist)) return err }) if err != nil { return fuse.EIO } return nil }
27.568889
179
0.680397
da984e0357e3649c00936d316f0e99cdcd382f8c
14,031
php
PHP
application/backend/controllers/Episode.php
WZoptal/WZoptal
f4199e89770a8c74a43beb9c52426813918bddd6
[ "MIT" ]
null
null
null
application/backend/controllers/Episode.php
WZoptal/WZoptal
f4199e89770a8c74a43beb9c52426813918bddd6
[ "MIT" ]
null
null
null
application/backend/controllers/Episode.php
WZoptal/WZoptal
f4199e89770a8c74a43beb9c52426813918bddd6
[ "MIT" ]
null
null
null
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Episode extends CI_Controller { public function __construct(){ parent::__construct(); $this->load->model('episode_model'); $this->load->model('user_model'); $this->load->helper('url'); } public function index(){ $this->manage_episode(); } ///////////////////////////////// category //////////////////////// public function manage_episode(){ $page=(isset($_GET["per_page"]) && $_GET["per_page"]!="")?$_GET["per_page"]:""; //$this->input->get("page"); if($page == ''){ $page = '0'; } else{ if(!is_numeric($page)){ redirect(BASEURL.'404'); } else{ $page = $page; } } $config["per_page"] = $this->config->item("perpageitem"); $config['base_url']=base_url()."episode/manage_episode/?".$this->common->removeUrl("per_page",$_SERVER["QUERY_STRING"]); $countdata=array(); $countdata=$_GET; $countdata["countdata"]="yes"; $config['total_rows']=count($this->episode_model->getcategoryData($countdata)); $config["uri_segment"]=(isset($_GET["per_page"]) && $_GET["per_page"]!="")?$_GET["per_page"]:"0"; $this->pagination->initialize($config); /*--------------------------Paging code ends---------------------------------------------------*/ $searcharray=array(); $searcharray=$_GET; $searcharray["per_page"]=$config["per_page"]; $searcharray["page"]=$config["uri_segment"]; $data["resultset"]=$this->episode_model->getcategoryData($searcharray); $data["item"]="episode"; $data["master_title"]= "Manage Episode | ".$this->config->item('sitename'); $data["master_body"]="manage_episode"; $this->load->theme('mainlayout',$data); } public function add_episode(){ $data["item"] = "episode"; $data["do"] = "add"; $data["categorydata"] = $this->session->flashdata("tempdata"); $data["bhpsplans"] = $this->episode_model->getPlans(); $data["master_title"] = "Add Episode | ".$this->config->item('sitename'); $data["master_body"] = "add_episode"; $this->load->theme('mainlayout',$data); if($this->uri->segment(3) != '' && $this->uri->segment(3)== '0'){ header("Refresh:4;url=".base_url()."episode/manage_episode"); } } public function edit_episode(){ $data["item"] = "episode"; $data["do"] = "edit"; $episodeid = $this->uri->segment(3); $data["categorydata"]=$this->episode_model->getIndividualepisode($episodeid); $data["bhpsplans"] = $this->episode_model->getPlans(); $data["master_title"]="Edit Episode | ".$this->config->item('sitename'); $data["master_body"]="add_episode"; $this->load->theme('mainlayout',$data); if($this->uri->segment(4)!=''&& $this->uri->segment(4)== '0'){ header("Refresh:4; url=".base_url()."episode/manage_episode"); } } function save_base64_image($base64_image_string, $path_with_end_slash="" ) { $splited = explode(',', substr( $base64_image_string , 5 ) , 2); $mime=$splited[0]; $data=$splited[1]; $mime_split_without_base64=explode(';', $mime,2); $mime_split=explode('/', $mime_split_without_base64[0],2); if(count($mime_split)==2) { $extension=$mime_split[1]; if($extension=='jpeg')$extension='jpg'; $_image = 'bhps_'.uniqid().'_'.time().".".$extension; $image_name = $_image; } $path = "../pics/episode/" . $image_name; file_put_contents( $path, base64_decode($data) ); return $image_name; } public function add_episode_to_database(){ // $last_id=1; // $title= "TEst "; // $push = $this->pushNotification($last_id, $title); //print_R( implode(",", $this->input->post('bhps_planId'))); $arr["id"] = $this->input->post("id"); $arr["title"]= ucfirst(trim(trim($this->input->post("title")))); $arr["subtitle"]= ucfirst(trim(trim($this->input->post("subtitle")))); $arr["subtitle2"]= ucfirst(trim(trim($this->input->post("subtitle2")))); $arr["matthew"]= ucfirst(trim(trim($this->input->post("matthew")))); $arr["subal_stearns"]= ucfirst(trim(trim($this->input->post("subal_stearns")))); $arr["bhps_planId"]= implode(",", $this->input->post('bhps_planId')); if(trim($this->input->post("subal_stearns"))){ $arr["amount"]= ucfirst(trim(trim($this->input->post("amount")))); } $_image = $_FILES['image']['name'][0]; $audio = $_FILES['audio']['name'][0]; $video = $_FILES['video']['name'][0]; $explod_img = []; if( !empty($_POST['images']) ) { $explod_img = explode('|,|', $_POST['images']); } $output_img = array_filter($explod_img); $imgArr =[]; if( !empty($output_img) && is_array($output_img) ){ foreach ($output_img as $key_img => $value_img) { $image_name = $this->save_base64_image(trim($value_img)); if(!empty($image_name) ){ $imgArr[] = $image_name; } } } $arr["image"] = implode(",",$imgArr); /*if ($_image != "") { $allowed_image_extension = array("png","PNG","JPG","jpeg", "jpg","gif"); $imgArr =[]; foreach($_FILES["image"]["tmp_name"] as $key=>$tmp_name) { $file_name=$_FILES["image"]["name"][$key]; $file_tmp=$_FILES["image"]["tmp_name"][$key]; $file_extension=pathinfo($file_name, PATHINFO_EXTENSION); if (! in_array($file_extension, $allowed_image_extension)){ if(!empty($arr["id"])){ $this->session->set_flashdata("errormsg","Upload valid images. Only PNG are allowed."); redirect(base_url().$this->router->class."/edit_episode/".$arr["id"]."/".$err); }else{ $this->session->set_flashdata("errormsg","Upload valid images. Only PNG are allowed."); redirect(base_url().$this->router->class."/add_episode/".$err); } }else{ $ext = end(explode(".", $file_name)); $_image = 'bhps_'.uniqid().'_'.time().".".$ext; $image_name = $_image; $arr["image"] = $image_name; $path = "../pics/episode/" . $image_name; mkdir(dirname($path), 0777, true); copy($_FILES['image']['tmp_name'][$key], $path); } array_push($imgArr, $image_name); } $arr["image"] = implode(",",$imgArr); }*/ if ($audio != "") { $allowed_audio_extension = array("mp3","MP3","mp4","MP4","m4a","M4A"); $audioArr =[]; foreach($_FILES["audio"]["tmp_name"] as $key=>$tmp_name) { $file_name=$_FILES["audio"]["name"][$key]; $file_tmp=$_FILES["audio"]["tmp_name"][$key]; $file_extension=pathinfo($file_name, PATHINFO_EXTENSION); if (! in_array($file_extension, $allowed_audio_extension)){ if(!empty($arr["id"])){ $this->session->set_flashdata("errormsg","Upload valid extension. Only Mp3,M4a are allowed."); redirect(base_url().$this->router->class."/edit_episode/".$arr["id"]."/".$err); }else{ $this->session->set_flashdata("errormsg","Upload valid extension. Only Mp3, M4a are allowed."); redirect(base_url().$this->router->class."/add_episode/".$err); } }else{ $ext = end(explode(".", $file_name)); $audio = 'bhps_'.uniqid().'_'.time().".".$ext; $audio_name = $audio; //$arr["audio"] = $audio_name; $path = "../pics/episode/" . $audio_name; copy($_FILES['audio']['tmp_name'][$key], $path); } array_push($audioArr, $audio_name); } $arr["audio"] = implode(",",$audioArr); } if ($video != "") { $allowed_video_extension = array("mp4","MP4","M4A","m4a"); $videoArr =[]; foreach($_FILES["video"]["tmp_name"] as $key=>$tmp_name) { $file_name=$_FILES["video"]["name"][$key]; $file_tmp=$_FILES["video"]["tmp_name"][$key]; $file_extension=pathinfo($file_name, PATHINFO_EXTENSION); if (! in_array($file_extension, $allowed_video_extension)){ if(!empty($arr["id"])){ $this->session->set_flashdata("errormsg","Upload valid extension. Only MP4 are allowed."); redirect(base_url().$this->router->class."/edit_episode/".$arr["id"]."/".$err); }else{ $this->session->set_flashdata("errormsg","Upload valid extension. Only MP4 are allowed."); redirect(base_url().$this->router->class."/add_episode/".$err); } }else{ $ext = end(explode(".", $file_name)); $video = 'bhps_'.uniqid().'_'.time().".".$ext; $video_name = $video; //$arr["video"] = $video_name; $path = "../pics/episode/" . $video_name; copy($_FILES['video']['tmp_name'][$key], $path); } array_push($videoArr, $video_name); } $arr["video"] = implode(",",$videoArr); } //print_r($arr); die; $this->session->set_flashdata("tempdata",strip_slashes($arr)); if($this->episode_model->add_edit_episode($arr)){ $last_id = $this->db->insert_id(); $err=0; if($arr["id"] == ""){ $this->pushNotification($last_id, $arr["title"]); $this->session->set_flashdata("successmsg","Episode created successfully"); redirect(base_url().$this->router->class."/add_episode/".$err); } else{ $this->session->set_flashdata("successmsg","Episode updated successfully"); redirect(base_url().$this->router->class."/edit_episode/".$arr["id"]."/".$err); } } else{ $this->session->set_flashdata("errormsg","There is error adding category to data base . Please contact database admin"); $err=1; } } public function pushNotification($last_id,$title){ $user = $this->user_model->getAllUser(); foreach ($user as $key => $value) { $badge_count = ($value["badgecount"]+1); $krru['badgecount'] = $badge_count; $krru['id'] = $value['id']; $this->user_model->update_profile_data($krru); $noti_message = ucwords($title).' new episode added '; $krr1['sender'] = 0; $krr1['receiver'] = $value['id']; $krr1['other_id'] = $last_id; $krr1['type'] = "new_episode" ; $krr1['body'] = $noti_message; $notifi_id = $this->user_model->add_notifications($krr1); $notification_Arr = array( 'sender' => 0, 'receiver' => $value['id'], 'other_id' => $last_id, 'id' => $last_id, 'seen' => 0, 'notification' => "New episode added", 'type' =>$krr1['type'] , 'time' => time() , 'message' => $noti_message ); if($value['push_notification'] == 1){ if($value["device_token"] <> '' || $value["device_token"] <> '1234'){ $device_token = $value["device_token"]; $this->fcmNotification($noti_message, $notification_Arr, $device_token, $badge_count); } } # code... } } public function enable_disable_episode(){ $id=$this->uri->segment(3); $status=$this->uri->segment(4); if($status==0){ $show_status="deactivated"; } else{ $show_status="activated"; } $this->episode_model->enable_disable_episode($id,$status); $this->session->set_flashdata("successmsg","Episode ".$show_status." successfully"); redirect(base_url()."episode/manage_episode"); } public function archive_episode(){ $id = $this->uri->segment(3); if($id!=''){ $this->episode_model->deleteEpisode($id); $this->session->set_flashdata("successmsg","Category archived successfully"); redirect(base_url()."episode/manage_episode"); } else{ redirect(base_url()."invalidpage"); } } public function view_episode(){ $id = $this->uri->segment(3); if($id==""){ redirect(base_url()."invalidpage"); } else{ $data["resultset"]=$this->episode_model->getIndividualEpisode($id); } $data["item"] = "episode"; $data["master_title"] = "View episode"; // Please enter the title of page...... $data["master_body"] = "view_episode"; $this->load->theme('mainlayout',$data); // Loading theme } public function fcmNotification($message, $notification_Arr, $firebase_registration_id=false, $badgecount){ $path_to_firebase_cm = 'https://fcm.googleapis.com/fcm/send'; if($notification_Arr['other_id'] == ""){ $other_id = ""; } else{ $other_id = $notification_Arr['other_id']; } $fcm_device_id = explode(',', $firebase_registration_id); foreach($fcm_device_id as $k => $v){ $fcmDeviceId[] = $v; } $title = ''; $fields = array( 'content_available' => true, 'to' => $firebase_registration_id, 'notification' => (object)array('title' => $title, 'body' => $message), //'notification' => array('title' => $title, 'body' => $message, 'type' => $notification_Arr['type'], "badge" => $badgecount, "sound" => 'default','click_action'=> "new_episode"), 'data' => array('message' => $message, 'type' => $notification_Arr['type'], 'sender_id' => $notification_Arr['sender'], 'receiver_id' => $notification_Arr['receiver'], 'other_id' => $other_id, 'badgecount' => $badgecount, 'click_action'=> "new_episode") ); $headers = array('Authorization:key=AAAAnckkg0M:APA91bHd3KbQGCxygaJyLd_OYaQhMPk8Y2O8JO7jCu1ie9dclHg1_RwDsH0xvKM9NccoDXckDMR20Vl7eXMbIAIc2AP_74yXWgU_1DyzkzXgGO9r38j6LJOuhf6DwYOdncH-n23meMZt', 'Content-Type:application/json' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $path_to_firebase_cm); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); $result = curl_exec($ch); //echo '<pre>'; print_r($result);// die; curl_close($ch); // die; } } ?>
34.990025
265
0.57993
1e71951b5b923c8defe279eee8a3294b90852af4
594
dart
Dart
lib/src/decoder/thumb/format/load_address.dart
matanlurey/armv4t.dart
06235938d16cb1f2b09d26f564b985854e4155c0
[ "MIT" ]
8
2020-06-21T22:05:00.000Z
2021-10-06T19:59:20.000Z
lib/src/decoder/thumb/format/load_address.dart
matanlurey/armv4t.dart
06235938d16cb1f2b09d26f564b985854e4155c0
[ "MIT" ]
82
2020-06-21T22:02:00.000Z
2020-08-04T01:48:42.000Z
lib/src/decoder/thumb/format/load_address.dart
matanlurey/armv4t.dart
06235938d16cb1f2b09d26f564b985854e4155c0
[ "MIT" ]
1
2020-06-22T15:16:02.000Z
2020-06-22T15:16:02.000Z
part of '../format.dart'; class LoadAddressThumbFormat extends ThumbFormat { final bool stackPointerBit; final Uint3 destination; final Uint8 word; const LoadAddressThumbFormat({ @required this.stackPointerBit, @required this.destination, @required this.word, }) : super._(); @override R accept<R, C>(ThumbFormatVisitor<R, C> visitor, [C context]) { return visitor.visitLoadAddress(this, context); } @override Map<String, int> _values() { return { 's': stackPointerBit ? 1 : 0, 'd': destination.value, 'w': word.value, }; } }
21.214286
65
0.654882
db9175ca989033038a07c57f390f54bec21b3376
228
php
PHP
app/Http/Controllers/Cnews/CatController.php
Phuoc95/lcnews
a25c99cda2072f5776b4af5a722fde8cba7ee052
[ "MIT" ]
null
null
null
app/Http/Controllers/Cnews/CatController.php
Phuoc95/lcnews
a25c99cda2072f5776b4af5a722fde8cba7ee052
[ "MIT" ]
null
null
null
app/Http/Controllers/Cnews/CatController.php
Phuoc95/lcnews
a25c99cda2072f5776b4af5a722fde8cba7ee052
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\Cnews; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class CatController extends Controller { public function getAdd(){ return view ('cnews.cat.add'); } }
16.285714
38
0.72807
ce98379c1ce7413d784627290cea6aa5a49acfdd
11,643
rs
Rust
kube-client/src/client/tls.rs
wseaton/kube-rs
3381e6991853312afc1748f699126c488bc34ff4
[ "Apache-2.0" ]
776
2019-04-29T19:40:27.000Z
2021-07-18T06:31:54.000Z
kube-client/src/client/tls.rs
wseaton/kube-rs
3381e6991853312afc1748f699126c488bc34ff4
[ "Apache-2.0" ]
458
2019-05-05T09:07:43.000Z
2021-07-18T20:48:23.000Z
kube-client/src/client/tls.rs
olix0r/kube-rs
5e6762d4254cfe674ec5d83f97e6d645fa4ae458
[ "Apache-2.0" ]
127
2019-05-03T23:37:26.000Z
2021-07-14T21:03:25.000Z
#[cfg(feature = "native-tls")] pub mod native_tls { use thiserror::Error; use tokio_native_tls::native_tls::{Certificate, Identity, TlsConnector}; const IDENTITY_PASSWORD: &str = " "; /// Errors from native TLS #[derive(Debug, Error)] pub enum Error { /// Failed to deserialize PEM-encoded X509 certificate #[error("failed to deserialize PEM-encoded X509 certificate: {0}")] DeserializeCertificate(#[source] openssl::error::ErrorStack), /// Failed to deserialize PEM-encoded private key #[error("failed to deserialize PEM-encoded private key: {0}")] DeserializePrivateKey(#[source] openssl::error::ErrorStack), /// Failed to create PKCS #12 archive #[error("failed to create PKCS #12 archive: {0}")] CreatePkcs12(#[source] openssl::error::ErrorStack), /// Failed to serialize PKCS #12 archive to DER #[error("failed to serialize PKCS #12 archive to DER encoding: {0}")] SerializePkcs12(#[source] openssl::error::ErrorStack), /// Failed to deserialize DER-encoded PKCS #12 archive #[error("failed to deserialize DER-encoded PKCS #12 archive: {0}")] DeserializePkcs12(#[source] tokio_native_tls::native_tls::Error), /// Failed to deserialize DER-encoded X509 certificate #[error("failed to deserialize DER-encoded X509 certificate: {0}")] DeserializeRootCertificate(#[source] tokio_native_tls::native_tls::Error), /// Failed to create `TlsConnector` #[error("failed to create `TlsConnector`: {0}")] CreateTlsConnector(#[source] tokio_native_tls::native_tls::Error), } /// Create `native_tls::TlsConnector`. pub fn native_tls_connector( identity_pem: Option<&Vec<u8>>, root_cert: Option<&Vec<Vec<u8>>>, accept_invalid: bool, ) -> Result<TlsConnector, Error> { let mut builder = TlsConnector::builder(); if let Some(pem) = identity_pem { let identity = pkcs12_from_pem(pem, IDENTITY_PASSWORD)?; builder.identity( Identity::from_pkcs12(&identity, IDENTITY_PASSWORD).map_err(Error::DeserializePkcs12)?, ); } if let Some(ders) = root_cert { for der in ders { builder.add_root_certificate( Certificate::from_der(der).map_err(Error::DeserializeRootCertificate)?, ); } } if accept_invalid { builder.danger_accept_invalid_certs(true); } builder.build().map_err(Error::CreateTlsConnector) } // TODO Switch to PKCS8 support when https://github.com/sfackler/rust-native-tls/pull/209 is merged fn pkcs12_from_pem(pem: &[u8], password: &str) -> Result<Vec<u8>, Error> { use openssl::{pkcs12::Pkcs12, pkey::PKey, x509::X509}; let x509 = X509::from_pem(pem).map_err(Error::DeserializeCertificate)?; let pkey = PKey::private_key_from_pem(pem).map_err(Error::DeserializePrivateKey)?; let p12 = Pkcs12::builder() .build(password, "kubeconfig", &pkey, &x509) .map_err(Error::CreatePkcs12)?; p12.to_der().map_err(Error::SerializePkcs12) } } #[cfg(feature = "rustls-tls")] pub mod rustls_tls { use hyper_rustls::ConfigBuilderExt; use rustls::{ self, client::{ServerCertVerified, ServerCertVerifier}, Certificate, ClientConfig, PrivateKey, }; use thiserror::Error; /// Errors from Rustls #[derive(Debug, Error)] pub enum Error { /// Identity PEM is invalid #[error("identity PEM is invalid: {0}")] InvalidIdentityPem(#[source] std::io::Error), /// Identity PEM is missing a private key: the key must be PKCS8 or RSA/PKCS1 #[error("identity PEM is missing a private key: the key must be PKCS8 or RSA/PKCS1")] MissingPrivateKey, /// Identity PEM is missing certificate #[error("identity PEM is missing certificate")] MissingCertificate, /// Invalid private key #[error("invalid private key: {0}")] InvalidPrivateKey(#[source] rustls::Error), // Using type-erased error to avoid depending on webpki /// Failed to add a root certificate #[error("failed to add a root certificate: {0}")] AddRootCertificate(#[source] Box<dyn std::error::Error + Send + Sync>), } /// Create `rustls::ClientConfig`. pub fn rustls_client_config( identity_pem: Option<&[u8]>, root_certs: Option<&[Vec<u8>]>, accept_invalid: bool, ) -> Result<ClientConfig, Error> { let config_builder = if let Some(certs) = root_certs { ClientConfig::builder() .with_safe_defaults() .with_root_certificates(root_store(certs)?) } else { ClientConfig::builder().with_safe_defaults().with_native_roots() }; let mut client_config = if let Some((chain, pkey)) = identity_pem.map(client_auth).transpose()? { config_builder .with_single_cert(chain, pkey) .map_err(Error::InvalidPrivateKey)? } else { config_builder.with_no_client_auth() }; if accept_invalid { client_config .dangerous() .set_certificate_verifier(std::sync::Arc::new(NoCertificateVerification {})); } Ok(client_config) } fn root_store(root_certs: &[Vec<u8>]) -> Result<rustls::RootCertStore, Error> { let mut root_store = rustls::RootCertStore::empty(); for der in root_certs { root_store .add(&Certificate(der.clone())) .map_err(|e| Error::AddRootCertificate(Box::new(e)))?; } Ok(root_store) } // TODO Support EC Private Key to support k3d. Need to convert to PKCS#8 or RSA (PKCS#1). // `openssl pkcs8 -topk8 -nocrypt -in ec.pem -out pkcs8.pem` // https://wiki.openssl.org/index.php/Command_Line_Elliptic_Curve_Operations#EC_Private_Key_File_Formats fn client_auth(data: &[u8]) -> Result<(Vec<Certificate>, PrivateKey), Error> { use rustls_pemfile::Item; let mut cert_chain = Vec::new(); let mut pkcs8_key = None; let mut rsa_key = None; let mut reader = std::io::Cursor::new(data); for item in rustls_pemfile::read_all(&mut reader).map_err(Error::InvalidIdentityPem)? { match item { Item::X509Certificate(cert) => cert_chain.push(Certificate(cert)), Item::PKCS8Key(key) => pkcs8_key = Some(PrivateKey(key)), Item::RSAKey(key) => rsa_key = Some(PrivateKey(key)), } } let private_key = pkcs8_key.or(rsa_key).ok_or(Error::MissingPrivateKey)?; if cert_chain.is_empty() { return Err(Error::MissingCertificate); } Ok((cert_chain, private_key)) } struct NoCertificateVerification {} impl ServerCertVerifier for NoCertificateVerification { fn verify_server_cert( &self, _end_entity: &Certificate, _intermediates: &[Certificate], _server_name: &rustls::client::ServerName, _scts: &mut dyn Iterator<Item = &[u8]>, _ocsp_response: &[u8], _now: std::time::SystemTime, ) -> Result<ServerCertVerified, rustls::Error> { Ok(ServerCertVerified::assertion()) } } } #[cfg(feature = "openssl-tls")] pub mod openssl_tls { use openssl::{ pkey::PKey, ssl::{SslConnector, SslConnectorBuilder, SslMethod}, x509::X509, }; use thiserror::Error; /// Errors from OpenSSL TLS #[derive(Debug, Error)] pub enum Error { /// Failed to create OpenSSL HTTPS connector #[error("failed to create OpenSSL HTTPS connector: {0}")] CreateHttpsConnector(#[source] openssl::error::ErrorStack), /// Failed to create OpenSSL SSL connector #[error("failed to create OpenSSL SSL connector: {0}")] CreateSslConnector(#[source] SslConnectorError), } /// Errors from creating a `SslConnectorBuilder` #[derive(Debug, Error)] pub enum SslConnectorError { /// Failed to build SslConnectorBuilder #[error("failed to build SslConnectorBuilder: {0}")] CreateBuilder(#[source] openssl::error::ErrorStack), /// Failed to deserialize PEM-encoded chain of certificates #[error("failed to deserialize PEM-encoded chain of certificates: {0}")] DeserializeCertificateChain(#[source] openssl::error::ErrorStack), /// Failed to deserialize PEM-encoded private key #[error("failed to deserialize PEM-encoded private key: {0}")] DeserializePrivateKey(#[source] openssl::error::ErrorStack), /// Failed to set private key #[error("failed to set private key: {0}")] SetPrivateKey(#[source] openssl::error::ErrorStack), /// Failed to get a leaf certificate, the certificate chain is empty #[error("failed to get a leaf certificate, the certificate chain is empty")] GetLeafCertificate, /// Failed to set the leaf certificate #[error("failed to set the leaf certificate: {0}")] SetLeafCertificate(#[source] openssl::error::ErrorStack), /// Failed to append a certificate to the chain #[error("failed to append a certificate to the chain: {0}")] AppendCertificate(#[source] openssl::error::ErrorStack), /// Failed to deserialize DER-encoded root certificate #[error("failed to deserialize DER-encoded root certificate: {0}")] DeserializeRootCertificate(#[source] openssl::error::ErrorStack), /// Failed to add a root certificate #[error("failed to add a root certificate: {0}")] AddRootCertificate(#[source] openssl::error::ErrorStack), } /// Create `openssl::ssl::SslConnectorBuilder` required for `hyper_openssl::HttpsConnector`. pub fn ssl_connector_builder( identity_pem: Option<&Vec<u8>>, root_certs: Option<&Vec<Vec<u8>>>, ) -> Result<SslConnectorBuilder, SslConnectorError> { let mut builder = SslConnector::builder(SslMethod::tls()).map_err(SslConnectorError::CreateBuilder)?; if let Some(pem) = identity_pem { let mut chain = X509::stack_from_pem(pem) .map_err(SslConnectorError::DeserializeCertificateChain)? .into_iter(); let leaf_cert = chain.next().ok_or(SslConnectorError::GetLeafCertificate)?; builder .set_certificate(&leaf_cert) .map_err(SslConnectorError::SetLeafCertificate)?; for cert in chain { builder .add_extra_chain_cert(cert) .map_err(SslConnectorError::AppendCertificate)?; } let pkey = PKey::private_key_from_pem(pem).map_err(SslConnectorError::DeserializePrivateKey)?; builder .set_private_key(&pkey) .map_err(SslConnectorError::SetPrivateKey)?; } if let Some(ders) = root_certs { for der in ders { let cert = X509::from_der(der).map_err(SslConnectorError::DeserializeRootCertificate)?; builder .cert_store_mut() .add_cert(cert) .map_err(SslConnectorError::AddRootCertificate)?; } } Ok(builder) } }
38.939799
108
0.612729
c8f920fb2f9e31bf09b632b0940dcec983afd719
342
go
Go
go/core/pll.go
marcfrei/scion-time
5f6ebe8b9d40e4bfe3693d0834eb5df80ccf15bd
[ "Apache-2.0" ]
null
null
null
go/core/pll.go
marcfrei/scion-time
5f6ebe8b9d40e4bfe3693d0834eb5df80ccf15bd
[ "Apache-2.0" ]
null
null
null
go/core/pll.go
marcfrei/scion-time
5f6ebe8b9d40e4bfe3693d0834eb5df80ccf15bd
[ "Apache-2.0" ]
null
null
null
package core import ( "time" ) type PLL interface { Do(offset time.Duration, weight float64) } var pll PLL func PLLInstance() PLL { if pll == nil { panic("no PLL registered") } return pll } func RegisterPLL(l PLL) { if l == nil { panic("PLL must not be nil") } if pll != nil { panic("PLL already registered") } pll = l }
11.793103
41
0.631579
c0793072163c2b9acd5f25f02311aef1d6514911
5,955
cs
C#
src/lib/OpenExcel/Common/ExcelRange.cs
DHTMLX/grid-to-excel-net
69d432b65e914223cfe5b64702450fc132e88a94
[ "MIT" ]
2
2017-08-04T07:11:15.000Z
2019-07-18T02:57:59.000Z
src/lib/OpenExcel/Common/ExcelRange.cs
DHTMLX/grid-to-excel-net
69d432b65e914223cfe5b64702450fc132e88a94
[ "MIT" ]
null
null
null
src/lib/OpenExcel/Common/ExcelRange.cs
DHTMLX/grid-to-excel-net
69d432b65e914223cfe5b64702450fc132e88a94
[ "MIT" ]
5
2020-02-10T20:52:43.000Z
2022-03-28T08:18:23.000Z
using System; using OpenExcel.Common.RangeParser; namespace OpenExcel.Common { /// <summary> /// Excel range utilities, such as parsing and translating. /// </summary> public static class ExcelRange { /// <summary> /// <summary> /// Parses formula into a tree. /// DEV NOTE: Subject to change. /// </summary> /// </summary> /// <param name="range">Range, e.g. A1, Sheet1!A1</param> /// <returns></returns> public static RangeComponents Parse(string range) { return new RangeComponents(range); } /// <summary> /// Translate a range. /// </summary> /// <param name="range">Range, e.g. A1, Sheet1!A1</param> /// <param name="rowDelta">Number of rows to move up(+) or down(-)</param> /// <param name="colDelta">Number of columns to move right(+) or left(-)</param> /// <returns></returns> public static string Translate(string range, int rowDelta, int colDelta) { if (range == null) return null; RangeComponents er = ExcelRange.Parse(range); // Row and column start of 0,0 means all rows and columns are affected by delta return TranslateInternal(er, 0, 0, rowDelta, colDelta, true); } /// <summary> /// Translate a range due to a sheet change, e.g. insertion of rows. /// </summary> /// <param name="range">Range, e.g. A1, Sheet1!A1</param> /// <param name="sheetChange">Details of change</param> /// <param name="currentSheetName">The sheet where the range is, to determine if this range is affected. If sheetChange.SheetName is null and currentSheetName is null, translation is always applied.</param> /// <returns></returns> public static string TranslateForSheetChange(string range, SheetChange sheetChange, string currentSheetName) { if (range == null) return null; RangeComponents er = ExcelRange.Parse(range); if ((er.SheetName == "" && currentSheetName == sheetChange.SheetName) || er.SheetName == sheetChange.SheetName) { return TranslateInternal(er, sheetChange.RowStart, sheetChange.ColumnStart, sheetChange.RowDelta, sheetChange.ColumnDelta, false // Don't allow absolute refs i.e. $ to affect translate ); } else return range; } private static string TranslateInternal(RangeComponents er, uint rowStart, uint colStart, int rowDelta, int colDelta, bool followAbsoluteRefs) { string newCellRef1 = null; string newCellRef2 = null; bool errRef1 = false, errRef2 = false; if (true) { if (er.Cell1Error != "") { newCellRef1 = er.Cell1Error; } else { RowColumn rc1 = er.Cell1RowColumn; newCellRef1 = TranslateInternal( er.Cell1RowDollar, rc1.Row, er.Cell1ColDollar, rc1.Column, rowStart, colStart, rowDelta, colDelta, followAbsoluteRefs, out errRef1); } } if (er.Cell2 != "") { if (er.Cell2Error != "") { newCellRef2 = er.Cell2Error; } else { RowColumn rc2 = er.Cell2RowColumn; newCellRef2 = TranslateInternal( er.Cell2RowDollar, rc2.Row, er.Cell2ColDollar, rc2.Column, rowStart, colStart, rowDelta, colDelta, followAbsoluteRefs, out errRef2); } } string newRange = ""; if (er.SheetName != "") newRange += er.EscapedSheetName + "!"; if (errRef1 && (errRef2 || newCellRef2 == null)) { newRange += "#REF!"; } else { newRange += newCellRef1; if (newCellRef2 != null) newRange += ":" + newCellRef2; } return newRange; } private static string TranslateInternal(string rowDollar, uint rowIdx, string colDollar, uint colIdx, uint rowStart, uint colStart, int rowDelta, int colDelta, bool followAbsoluteRefs, out bool exceededBounds) { int row = (int)rowIdx, col = (int)colIdx; if (row >= rowStart) { if (rowDollar != "$" || !followAbsoluteRefs) row = (row + rowDelta); } if (col >= colStart) { if (colDollar != "$" || !followAbsoluteRefs) col = (col + colDelta); } exceededBounds = false; if (row < 1 || row > ExcelConstraints.MaxRows || col < 1 || col > ExcelConstraints.MaxColumns) exceededBounds = true; row = Math.Max(1, Math.Min(row, ExcelConstraints.MaxRows)); col = Math.Max(1, Math.Min(col, ExcelConstraints.MaxColumns)); return rowDollar + ExcelAddress.ColumnIndexToName((uint)col) + colDollar + row; } } }
38.419355
217
0.474223
6765c61df4ac72e3509c4cfcee91410db22ba1c7
1,022
swift
Swift
G2C Gamers/G2C Gamers/View/Cells/GameDescriptionCell.swift
maduperera/G2C-Gamers
a46446fe4fd6e8c3d5c27eb4397cda6b29c6a33f
[ "MIT" ]
null
null
null
G2C Gamers/G2C Gamers/View/Cells/GameDescriptionCell.swift
maduperera/G2C-Gamers
a46446fe4fd6e8c3d5c27eb4397cda6b29c6a33f
[ "MIT" ]
null
null
null
G2C Gamers/G2C Gamers/View/Cells/GameDescriptionCell.swift
maduperera/G2C-Gamers
a46446fe4fd6e8c3d5c27eb4397cda6b29c6a33f
[ "MIT" ]
null
null
null
// // File.swift // G2C Gamers // // Created by Madusha on 11/14/19. // Copyright © 2019 Madusha. All rights reserved. // import UIKit protocol LoadMoreDelegate { func moreTapped(cell: GameDescriptionCell) } class GameDescriptionCell: UITableViewCell { @IBOutlet weak var lblLoadMore: UIButton! @IBOutlet weak var gameDesc: UILabel! var delegate: LoadMoreDelegate? var isExpanded = false @IBAction func loadMore(_ sender: Any) { if sender is UIButton { isExpanded = !isExpanded gameDesc.numberOfLines = isExpanded ? 0 : 4 lblLoadMore.setTitle(isExpanded ? "Read less..." : "Read more...", for: .normal) delegate?.moreTapped(cell: self) } } public static let reuseIdentifier = "GameDescriptionCell" public func configureWith(_ game: Game) { detailTextLabel?.numberOfLines = 4 gameDesc.text = game.description } }
22.217391
92
0.603718
daa4457fa07d10d7b4bd3f44b84e3bf91ad8c065
759
rb
Ruby
app/models/cdx/taxonomy.rb
alexandre025/cdx
a689edac06736978956a3d7b952eadab62c8691b
[ "MIT" ]
2
2017-10-05T16:35:16.000Z
2017-12-22T22:27:31.000Z
app/models/cdx/taxonomy.rb
alexandre025/cdx
a689edac06736978956a3d7b952eadab62c8691b
[ "MIT" ]
null
null
null
app/models/cdx/taxonomy.rb
alexandre025/cdx
a689edac06736978956a3d7b952eadab62c8691b
[ "MIT" ]
null
null
null
module Cdx class Taxonomy < ApplicationRecord include Cdx::Resourceable # Scopes scope :available_for, -> (code) { where('available_codes ? :code', code: code).or(where('available_codes = ? OR available_codes IS NULL', '[""]')) } # Callbacks after_create :set_root # Associations has_many :taxons, dependent: :destroy has_one :root, -> { where parent_id: nil }, class_name: 'Cdx::Taxon', dependent: :destroy # Validators validates :name, presence: true # Constants AVAILABLE_CODES = Cdx.taxonomy_available_codes.freeze # Methods def content_header_title name_was end private def set_root self.root ||= Taxon.create!(taxonomy_id: id, name: name) end end end
23
152
0.657444
ef801c5505378a1fd845ec9f189bfd3e16a29605
203
c
C
.vim/sourceCode/glibc-2.16.0/sysdeps/ieee754/ldbl-opt/w_lgamma.c
lakehui/Vim_config
6cab80dc1209b34bf6379f42b1a92790bd0c146b
[ "MIT" ]
47
2015-03-10T23:21:52.000Z
2022-02-17T01:04:14.000Z
.vim/sourceCode/glibc-2.16.0/sysdeps/ieee754/ldbl-opt/w_lgamma.c
lakehui/Vim_config
6cab80dc1209b34bf6379f42b1a92790bd0c146b
[ "MIT" ]
1
2020-06-30T18:01:37.000Z
2020-06-30T18:01:37.000Z
.vim/sourceCode/glibc-2.16.0/sysdeps/ieee754/ldbl-opt/w_lgamma.c
lakehui/Vim_config
6cab80dc1209b34bf6379f42b1a92790bd0c146b
[ "MIT" ]
19
2015-02-25T19:50:05.000Z
2021-10-05T14:35:54.000Z
#include <math_ldbl_opt.h> #include <math/w_lgamma.c> #if LONG_DOUBLE_COMPAT(libm, GLIBC_2_0) compat_symbol (libm, __lgamma, lgammal, GLIBC_2_0); compat_symbol (libm, __gamma, gammal, GLIBC_2_0); #endif
29
51
0.783251
14981a5693e0c6d810cb4d23743a4884b3288c93
1,771
cpp
C++
Graph/Kruskal.cpp
harshil2004/Data-Structures-and-Algorithms
4bfde85021cf9ff8012e485fa3de603a8185b157
[ "MIT" ]
14
2020-09-30T15:53:42.000Z
2020-10-29T09:43:33.000Z
Graph/Kruskal.cpp
harshil2004/Data-Structures-and-Algorithms
4bfde85021cf9ff8012e485fa3de603a8185b157
[ "MIT" ]
79
2020-09-29T17:15:39.000Z
2020-10-30T11:07:33.000Z
Graph/Kruskal.cpp
harshil2004/Data-Structures-and-Algorithms
4bfde85021cf9ff8012e485fa3de603a8185b157
[ "MIT" ]
113
2020-09-29T14:21:26.000Z
2020-10-31T09:10:21.000Z
// Title - Kruskal's algorithm for minimum spanning tree // Statement - It will find the minimum spanning tree in a given weighted undirected graph // Time complexity - O(ELogV) #include<bits/stdc++.h> using namespace std; int find(int i, int union_set[]){ if(union_set[i]!=i) union_set[i] = find(union_set[i],union_set); return union_set[i]; } int kruskalMST(int n, vector<vector<int>> &cost, vector<pair<int,pair<int,int>>> &ans){ vector<pair<int,pair<int,int>>> edges; int union_set[n]; // creating the disjoint set union for(int i=0; i<n; i++) union_set[i]=i; // creating vector of weighted edges for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ if(i!=j && cost[i][j]!=0) edges.push_back({cost[i][j],{i,j}}); } } int res=0; sort(edges.begin(), edges.end()); for(auto edge:edges){ int start = find(edge.second.first, union_set); int end = find(edge.second.second, union_set); if(start!=end){ union_set[start] = end; res+= edge.first; ans.push_back(edge); } } return res; } int main(){ cout<<"Input adjacency matrix of graph with n vertives"<<endl; int n;cin>>n; vector<vector<int>> cost(n,vector<int>(n,0)); // creating adjacency matrix representation of graph for(int i=0;i<n;i++) for(int j=0;j<n;j++) cin>>cost[i][j]; vector<pair<int,pair<int,int>>> ans; cout << "Length of MST: " << kruskalMST(n,cost,ans) <<endl; for(auto edge:ans){ cout<<"Edge between "<<edge.second.first<<" & "<<edge.second.second<<endl; cout<<"Edge weight = "<<edge.first<<endl; } return 0; } // Name: Chirag Dalmia // Github ID: chiru-cd
28.111111
90
0.582157
efe517c0bcb69c79b5d6105e4735dcc6794ec44a
1,246
rs
Rust
boards/samd21_m0_mini/examples/blink.rs
reppad/atsamd
28309a72a1fdce1577142e5d7fa3812e4d424566
[ "Apache-2.0", "MIT" ]
null
null
null
boards/samd21_m0_mini/examples/blink.rs
reppad/atsamd
28309a72a1fdce1577142e5d7fa3812e4d424566
[ "Apache-2.0", "MIT" ]
null
null
null
boards/samd21_m0_mini/examples/blink.rs
reppad/atsamd
28309a72a1fdce1577142e5d7fa3812e4d424566
[ "Apache-2.0", "MIT" ]
null
null
null
#![no_main] #![no_std] extern crate cortex_m; extern crate panic_halt; extern crate samd21_m0_mini as hal; use hal::clock::GenericClockController; use hal::delay::Delay; use hal::entry; use hal::pac::{CorePeripherals, Peripherals}; use hal::prelude::*; #[entry] fn main() -> ! { let mut peripherals = Peripherals::take().unwrap(); let core = CorePeripherals::take().unwrap(); let mut clocks = GenericClockController::with_external_32kosc( peripherals.GCLK, &mut peripherals.PM, &mut peripherals.SYSCTRL, &mut peripherals.NVMCTRL, ); let mut pins = hal::Pins::new(peripherals.PORT); let mut led0 = pins.d13.into_open_drain_output(&mut pins.port); let mut led1 = pins.led_tx.into_open_drain_output(&mut pins.port); let mut led2 = pins.led_rx.into_open_drain_output(&mut pins.port); let mut delay = Delay::new(core.SYST, &mut clocks); let mut counter = 0u8; loop { counter = counter.wrapping_add(1); delay.delay_ms(100u8); if counter & (1 << 0) != 0 { led0.toggle(); } if counter & (1 << 1) != 0 { led1.toggle(); } if counter & (1 << 2) != 0 { led2.toggle(); } } }
27.688889
70
0.607544
38540af595589191f73aff11eb8abb35495939f8
1,019
php
PHP
database/migrations/2015_04_19_051353_create_services_table.php
suecarmol/assessment
4cdb10f5c40c378ed9777ad78a90300a4796c265
[ "MIT" ]
null
null
null
database/migrations/2015_04_19_051353_create_services_table.php
suecarmol/assessment
4cdb10f5c40c378ed9777ad78a90300a4796c265
[ "MIT" ]
null
null
null
database/migrations/2015_04_19_051353_create_services_table.php
suecarmol/assessment
4cdb10f5c40c378ed9777ad78a90300a4796c265
[ "MIT" ]
null
null
null
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateServicesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('services', function(Blueprint $table) { $table->increments('id'); $table->timestamp('start_of_service'); $table->timestamp('end_of_service')->nullable(); $table->string('type_of_service'); $table->integer('number_of_delays')->unsigned(); //foreign keys $table->integer('truck_id')->unsigned(); $table->integer('user_id')->unsigned(); $table->timestamps(); }); Schema::table('services', function($table) { $table->foreign('user_id') ->references('id')->on('users') ->onDelete('cascade'); $table->foreign('truck_id') ->references('id')->on('trucks') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('services'); } }
18.87037
55
0.62316
dd8db6384c6d36dbd7ff866634b12f460b55fc72
2,330
java
Java
src/main/java/net/tridentsdk/server/packets/play/in/PacketPlayInBlockPlace.java
BeYkeRYkt/Trident
3856336c2bac7877ecadf0b15d5267105dda7568
[ "Apache-2.0" ]
1
2021-04-17T20:30:20.000Z
2021-04-17T20:30:20.000Z
src/main/java/net/tridentsdk/server/packets/play/in/PacketPlayInBlockPlace.java
BeYkeRYkt/Trident
3856336c2bac7877ecadf0b15d5267105dda7568
[ "Apache-2.0" ]
null
null
null
src/main/java/net/tridentsdk/server/packets/play/in/PacketPlayInBlockPlace.java
BeYkeRYkt/Trident
3856336c2bac7877ecadf0b15d5267105dda7568
[ "Apache-2.0" ]
null
null
null
/* * Trident - A Multithreaded Server Alternative * Copyright 2014 The TridentSDK Team * * 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 net.tridentsdk.server.packets.play.in; import io.netty.buffer.ByteBuf; import net.tridentsdk.Coordinates; import net.tridentsdk.server.netty.ClientConnection; import net.tridentsdk.server.netty.packet.InPacket; import net.tridentsdk.server.netty.packet.Packet; import net.tridentsdk.util.Vector; public class PacketPlayInBlockPlace extends InPacket { /** * Location of the block being placed */ protected Coordinates location; protected byte direction; // wat /** * Position of the cursor, incorrect use of a Vector xD */ protected Vector cursorPosition; @Override public int getId() { return 0x08; } @Override public Packet decode(ByteBuf buf) { long encodedLocation = buf.readLong(); this.location = new Coordinates(null, (double) (encodedLocation >> 38), (double) (encodedLocation << 26 >> 52), (double) (encodedLocation << 38 >> 38)); this.direction = buf.readByte(); // ignore held item for (int i = 0; i < buf.readableBytes() - 3; i++) { buf.readByte(); } double x = (double) buf.readByte(); double y = (double) buf.readByte(); double z = (double) buf.readByte(); this.cursorPosition = new Vector(x, y, z); return this; } public Coordinates getLocation() { return this.location; } public byte getDirection() { return this.direction; } public Vector getCursorPosition() { return this.cursorPosition; } @Override public void handleReceived(ClientConnection connection) { // TODO: Act accordingly } }
29.125
119
0.663519
cf10ec9c93f0214665759da3ba65e309f756ce14
1,186
php
PHP
resources/views/technicans/tech_show.blade.php
ashraf2033/maintainit2
abcf77ec2b6a98193de295cf70b83d4ecb2ade23
[ "MIT" ]
null
null
null
resources/views/technicans/tech_show.blade.php
ashraf2033/maintainit2
abcf77ec2b6a98193de295cf70b83d4ecb2ade23
[ "MIT" ]
null
null
null
resources/views/technicans/tech_show.blade.php
ashraf2033/maintainit2
abcf77ec2b6a98193de295cf70b83d4ecb2ade23
[ "MIT" ]
null
null
null
@extends('app') @section('content') @include('technicans.boxes') <div class="row"> <div class="col-md-12"> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">سجل {{$tech->tech_name}}</h3> </div> <div class="box-body"> <table id="dataTable" border="1" class="table table-striped table-bordered table-hover table-condensed" style="width:100%" align="center"> <thead> <tr> <th style="text-align:right">التاريخ</th> <th style="text-align:right">المهمة</th> </tr> </thead> <tbody> @foreach($recs as $key => $rec) @if(get_class($rec) === 'App\Repair') <td style="text-align:right">{{$rec->created_at}}</td> <td><a href="{{action("RepairsController@show",[$rec->rep_id,'action'=>'RepairsController@show'])}}">{{$rec->failure->fail_name}}</a></td> </tr> @elseif(get_class($rec) === 'App\Task') <td style="text-align:right">{{$rec->created_at}}</td> <td><a href="{{action("TasksController@show",[$rec->task_id,'action'=>'TasksController@show'])}}">{{ $rec->task_name }}</a></td> </tr> @endif @endforeach </tbody> </table> </div> <div class="box-footer"> </div> </div><!--/Box--> </div> </div> @endsection
21.962963
141
0.625632
a0e625da67b92b69c8c33c362640af71a55c3ea8
1,102
ps1
PowerShell
Juriba.Dashworks/Public/Get-DwList.ps1
juribalimited/powershell-module-dashworks
0ddb0a2b9d23115c72d9dae7c07c05185a4ab06c
[ "MIT" ]
null
null
null
Juriba.Dashworks/Public/Get-DwList.ps1
juribalimited/powershell-module-dashworks
0ddb0a2b9d23115c72d9dae7c07c05185a4ab06c
[ "MIT" ]
6
2021-12-09T15:29:07.000Z
2022-03-03T13:22:06.000Z
Juriba.Dashworks/Public/Get-DwList.ps1
juribalimited/powershell-module-dashworks
0ddb0a2b9d23115c72d9dae7c07c05185a4ab06c
[ "MIT" ]
null
null
null
Function Get-DwList { <# .SYNOPSIS Returns existing Lists. .DESCRIPTION Returns existing lists using Dashworks API v1. #> param( [Parameter(Mandatory=$true)] [string]$Instance, [Parameter(Mandatory=$true)] [string]$APIKey, [Parameter(Mandatory = $true)] [ValidateSet("Device", "User", "Application", "Mailbox", "ApplicationUser", "ApplicationDevice")] [string]$ObjectType ) $endpoint = "" switch ($ObjectType) { "ApplicationUser" { throw "not implemented" } "ApplicationDevice" { throw "not implemented" } "Device" { $endpoint = "devices"} "User" { $endpoint = "users "} "Application" { $endpoint = "applications" } "Mailbox" { $endpoint = "mailboxes" } } #$contentType = "application/json" $headers = @{ 'X-API-KEY' = $ApiKey } $uri = "{0}/apiv1/lists/{1}" -f $instance, $endpoint $result = Invoke-WebRequest -Uri $uri -Headers $headers -Method GET # -ContentType $contentType return ($result.content | ConvertFrom-Json) }
27.55
105
0.590744
2524ca6b777cac27be3c5b8f259f039e8f8d0912
35,490
lua
Lua
source/melee.lua
ribbanya/m-overlay
caae06c7f75c847c24dbc128527984d078736759
[ "MIT" ]
null
null
null
source/melee.lua
ribbanya/m-overlay
caae06c7f75c847c24dbc128527984d078736759
[ "MIT" ]
null
null
null
source/melee.lua
ribbanya/m-overlay
caae06c7f75c847c24dbc128527984d078736759
[ "MIT" ]
null
null
null
local memory = require("memory") local color = require("util.color") MATCH_NO_RESULT = 0x00 MATCH_GAME = 0x02 MATCH_STAGE_CLEAR = 0x03 MATCH_STAGE_FAILURE = 0x04 MATCH_STAGE_CLEAR3 = 0x05 MATCH_NEW_RECORD = 0x06 MATCH_NO_CONTEST = 0x07 MATCH_RETRY = 0x08 MATCH_GAME_CLEAR = 0x09 -- MAJOR FLAGS MENU_TITLE_SCREEN = 0x00 MENU_MAIN_MENU = 0x01 MENU_VS_MODE = 0x02 -- MINOR FLAGS MENU_VS_CSS = 0x0 MENU_VS_SSS = 0x1 MENU_VS_INGAME = 0x2 MENU_VS_POSTGAME = 0x4 MENU_CLASSIC_MODE = 0x03 MENU_CLASSIC_LEVEL_1_VS = 0x00 MENU_CLASSIC_LEVEL_1 = 0x01 MENU_CLASSIC_LEVEL_2_VS = 0x02 MENU_CLASSIC_LEVEL_2 = 0x03 MENU_CLASSIC_LEVEL_3_VS = 0x04 MENU_CLASSIC_LEVEL_3 = 0x05 MENU_CLASSIC_LEVEL_4_VS = 0x06 MENU_CLASSIC_LEVEL_4 = 0x07 MENU_CLASSIC_LEVEL_5_VS = 0x08 MENU_CLASSIC_LEVEL_5 = 0x09 MENU_CLASSIC_LEVEL_5_VS = 0x10 MENU_CLASSIC_LEVEL_5 = 0x09 MENU_CLASSIC_LEVEL_16 = 0x20 MENU_CLASSIC_LEVEL_16_VS = 0x21 MENU_CLASSIC_LEVEL_24 = 0x30 MENU_CLASSIC_LEVEL_24_VS = 0x31 MENU_CLASSIC_BREAK_THE_TARGETS_INTRO = 0x16 MENU_CLASSIC_BREAK_THE_TARGETS = 0x17 MENU_CLASSIC_TROPHY_STAGE_INTRO = 0x28 MENU_CLASSIC_TROPHY_STAGE_TARGETS = 0x29 MENU_CLASSIC_RACE_TO_FINISH_INTRO = 0x40 MENU_CLASSIC_RACE_TO_FINISH_TARGETS = 0x41 MENU_CLASSIC_LEVEL_56 = 0x38 MENU_CLASSIC_LEVEL_56_VS = 0x39 MENU_CLASSIC_MASTER_HAND = 0x51 MENU_CLASSIC_CONTINUE = 0x69 MENU_CLASSIC_CSS = 0x70 MENU_ADVENTURE_MODE = 0x04 MENU_ADVENTURE_MUSHROOM_KINGDOM_INTRO = 0x00 MENU_ADVENTURE_MUSHROOM_KINGDOM = 0x01 MENU_ADVENTURE_MUSHROOM_KINGDOM_LUIGI = 0x02 MENU_ADVENTURE_MUSHROOM_KINGDOM_BATTLE = 0x03 MENU_ADVENTURE_MUSHROOM_KONGO_JUNGLE_INTRO = 0x08 MENU_ADVENTURE_MUSHROOM_KONGO_JUNGLE_TINY_BATTLE = 0x09 MENU_ADVENTURE_MUSHROOM_KONGO_JUNGLE_GIANT_BATTLE = 0x0A MENU_ADVENTURE_UNDERGROUND_MAZE_INTRO = 0x10 MENU_ADVENTURE_UNDERGROUND_MAZE = 0x11 MENU_ADVENTURE_HYRULE_TEMPLE_BATTLE = 0x12 MENU_ADVENTURE_BRINSTAR_INTRO = 0x18 MENU_ADVENTURE_BRINSTAR = 0x19 MENU_ADVENTURE_ESCAPE_ZEBES_INTRO = 0x1A MENU_ADVENTURE_ESCAPE_ZEBES = 0x1B MENU_ADVENTURE_ESCAPE_ZEBES_ESCAPE = 0x1C MENU_ADVENTURE_GREEN_GREENS_INTRO = 0x20 MENU_ADVENTURE_GREEN_GREENS_KIRBY_BATTLE = 0x21 MENU_ADVENTURE_GREEN_GREENS_KIRBY_TEAM_INTRO = 0x22 MENU_ADVENTURE_GREEN_GREENS_KIRBY_TEAM_BATTLE = 0x23 MENU_ADVENTURE_GREEN_GREENS_GIANT_KIRBY_INTRO = 0x24 MENU_ADVENTURE_GREEN_GREENS_GIANT_KIRBY_BATTLE = 0x25 MENU_ADVENTURE_CORNARIA_INTRO = 0x28 MENU_ADVENTURE_CORNARIA_BATTLE_1 = 0x29 MENU_ADVENTURE_CORNARIA_RAID = 0x2A MENU_ADVENTURE_CORNARIA_BATTLE_2 = 0x2B MENU_ADVENTURE_CORNARIA_BATTLE_3 = 0x2C MENU_ADVENTURE_POKEMON_STADIUM_INTRO = 0x30 MENU_ADVENTURE_POKEMON_STADIUM_BATTLE = 0x31 MENU_ADVENTURE_FZERO_GRAND_PRIX_CARS = 0x38 MENU_ADVENTURE_FZERO_GRAND_PRIX_INTRO = 0x39 MENU_ADVENTURE_FZERO_GRAND_PRIX_RACE = 0x3A MENU_ADVENTURE_FZERO_GRAND_PRIX_BATTLE = 0x3B MENU_ADVENTURE_ONETT_INTRO = 0x40 MENU_ADVENTURE_ONETT_BATTLE = 0x41 MENU_ADVENTURE_ICICLE_MOUNTAIN_INTRO = 0x48 MENU_ADVENTURE_ICICLE_MOUNTAIN_CLIMB = 0x49 MENU_ADVENTURE_BATTLEFIELD_INTRO = 0x50 MENU_ADVENTURE_BATTLEFIELD_BATTLE = 0x51 MENU_ADVENTURE_BATTLEFIELD_METAL_INTRO = 0x52 MENU_ADVENTURE_BATTLEFIELD_METAL_BATTLE = 0x53 MENU_ADVENTURE_FINAL_DESTINATION_INTRO = 0x58 MENU_ADVENTURE_FINAL_DESTINATION_BATTLE = 0x59 MENU_ADVENTURE_FINAL_DESTINATION_POSE = 0x5A MENU_ADVENTURE_FINAL_DESTINATION_WINNER = 0x5B MENU_ADVENTURE_CSS = 0x70 MENU_ALL_STAR_MODE = 0x05 MENU_ALL_STAR_LEVEL_1 = 0x00 MENU_ALL_STAR_REST_AREA_1 = 0x01 MENU_ALL_STAR_LEVEL_2 = 0x02 MENU_ALL_STAR_REST_AREA_2 = 0x03 MENU_ALL_STAR_LEVEL_3 = 0x04 MENU_ALL_STAR_REST_AREA_3 = 0x05 MENU_ALL_STAR_LEVEL_4 = 0x06 MENU_ALL_STAR_REST_AREA_4 = 0x07 MENU_ALL_STAR_LEVEL_5 = 0x08 MENU_ALL_STAR_REST_AREA_5 = 0x09 MENU_ALL_STAR_LEVEL_6 = 0x10 MENU_ALL_STAR_REST_AREA_6 = 0x11 MENU_ALL_STAR_LEVEL_7 = 0x12 MENU_ALL_STAR_REST_AREA_7 = 0x13 MENU_ALL_STAR_LEVEL_8 = 0x14 MENU_ALL_STAR_REST_AREA_8 = 0x15 MENU_ALL_STAR_LEVEL_9 = 0x16 MENU_ALL_STAR_REST_AREA_9 = 0x17 MENU_ALL_STAR_LEVEL_10 = 0x18 MENU_ALL_STAR_REST_AREA_10 = 0x19 MENU_ALL_STAR_LEVEL_11 = 0x20 MENU_ALL_STAR_REST_AREA_11 = 0x21 MENU_ALL_STAR_LEVEL_12 = 0x22 MENU_ALL_STAR_REST_AREA_12 = 0x23 MENU_ALL_STAR_LEVEL_13 = 0x24 MENU_ALL_STAR_REST_AREA_13 = 0x25 MENU_ALL_STAR_LEVEL_14 = 0x26 MENU_ALL_STAR_REST_AREA_14 = 0x27 MENU_ALL_STAR_LEVEL_15 = 0x28 MENU_ALL_STAR_REST_AREA_15 = 0x29 MENU_ALL_STAR_LEVEL_16 = 0x30 MENU_ALL_STAR_REST_AREA_16 = 0x31 MENU_ALL_STAR_LEVEL_17 = 0x32 MENU_ALL_STAR_REST_AREA_17 = 0x33 MENU_ALL_STAR_LEVEL_18 = 0x34 MENU_ALL_STAR_REST_AREA_18 = 0x35 MENU_ALL_STAR_LEVEL_19 = 0x36 MENU_ALL_STAR_REST_AREA_19 = 0x37 MENU_ALL_STAR_LEVEL_20 = 0x38 MENU_ALL_STAR_REST_AREA_20 = 0x39 MENU_ALL_STAR_LEVEL_21 = 0x40 MENU_ALL_STAR_REST_AREA_21 = 0x41 MENU_ALL_STAR_LEVEL_22 = 0x42 MENU_ALL_STAR_REST_AREA_22 = 0x43 MENU_ALL_STAR_LEVEL_23 = 0x44 MENU_ALL_STAR_REST_AREA_23 = 0x45 MENU_ALL_STAR_LEVEL_24 = 0x46 MENU_ALL_STAR_REST_AREA_24 = 0x47 MENU_ALL_STAR_LEVEL_25 = 0x48 MENU_ALL_STAR_REST_AREA_25 = 0x49 MENU_ALL_STAR_LEVEL_26 = 0x50 MENU_ALL_STAR_REST_AREA_26 = 0x51 MENU_ALL_STAR_LEVEL_27 = 0x52 MENU_ALL_STAR_REST_AREA_28 = 0x53 MENU_ALL_STAR_LEVEL_29 = 0x54 MENU_ALL_STAR_REST_AREA_29 = 0x55 MENU_ALL_STAR_LEVEL_30 = 0x56 MENU_ALL_STAR_REST_AREA_30 = 0x57 MENU_ALL_STAR_LEVEL_31 = 0x58 MENU_ALL_STAR_REST_AREA_31 = 0x59 MENU_ALL_STAR_LEVEL_32 = 0x60 MENU_ALL_STAR_REST_AREA_32 = 0x61 MENU_ALL_STAR_CSS = 0x70 MENU_DEBUG = 0x06 MENU_SOUND_TEST = 0x07 MENU_VS_UNKNOWN = 0x08 -- SLIPPI ONLINE MENU_VS_UNKNOWN_CSS = 0x00 MENU_VS_UNKNOWN_SSS = 0x01 MENU_VS_UNKNOWN_INGAME = 0x02 MENU_VS_UNKNOWN_VERSUS = 0x04 MENU_UNKOWN_1 = 0x09 MENU_CAMERA_MODE = 0x0A MENU_TROPHY_GALLERY = 0x0B MENU_TROPHY_LOTTERY = 0x0C MENU_TROPHY_COLLECTION = 0x0D MENU_START_MATCH = 0x0E -- Slippi Replays MENU_START_MATCH_INGAME = 0x01 -- Set when the replay is actually playing out MENU_START_MATCH_UNKNOWN = 0x03 -- Seems to be set right before the match loads MENU_TARGET_TEST = 0x0F MENU_TARGET_TEST_CSS = 0x00 MENU_TARGET_TEST_INGAME = 0x1 MENU_SUPER_SUDDEN_DEATH = 0x10 MENU_SSD_CSS = 0x00 MENU_SSD_SSS = 0x01 MENU_SSD_INGAME = 0x02 MENU_SSD_POSTGAME = 0x04 MENU_INVISIBLE_MELEE = 0x11 MENU_INVISIBLE_MELEE_CSS = 0x00 MENU_INVISIBLE_MELEE_SSS = 0x01 MENU_INVISIBLE_MELEE_INGAME = 0x02 MENU_INVISIBLE_MELEE_POSTGAME = 0x04 MENU_SLOW_MO_MELEE = 0x12 MENU_SLOW_MO_MELEE_CSS = 0x00 MENU_SLOW_MO_MELEE_SSS = 0x01 MENU_SLOW_MO_MELEE_INGAME = 0x02 MENU_SLOW_MO_MELEE_POSTGAME = 0x04 MENU_LIGHTNING_MELEE = 0x13 MENU_LIGHTNING_MELEE_CSS = 0x00 MENU_LIGHTNING_MELEE_SSS = 0x01 MENU_LIGHTNING_MELEE_INGAME = 0x02 MENU_LIGHTNING_MELEE_POSTGAME = 0x04 MENU_CHARACTER_APPROACHING = 0x14 MENU_CLASSIC_MODE_COMPLETE = 0x15 MENU_CLASSIC_MODE_TROPHY = 0x00 MENU_CLASSIC_MODE_CREDITS = 0x01 MENU_CLASSIC_MODE_CHARACTER_VIDEO = 0x02 MENU_CLASSIC_MODE_CONGRATS = 0x03 MENU_ADVENTURE_MODE_COMPLETE = 0x16 MENU_ADVENTURE_MODE_TROPHY = 0x00 MENU_ADVENTURE_MODE_CREDITS = 0x01 MENU_ADVENTURE_MODE_CHARACTER_VIDEO = 0x02 MENU_ADVENTURE_MODE_CONGRATS = 0x03 MENU_ALL_STAR_COMPLETE = 0x17 MENU_ALL_STAR_TROPHY = 0x00 MENU_ALL_STAR_CREDITS = 0x01 MENU_ALL_STAR_CHARACTER_VIDEO = 0x02 MENU_ALL_STAR_CONGRATS = 0x03 MENU_TITLE_SCREEN_IDLE = 0x18 MENU_TITLE_SCREEN_IDLE_INTRO_VIDEO = 0x0 MENU_TITLE_SCREEN_IDLE_FIGHT_1 = 0x1 MENU_TITLE_SCREEN_IDLE_BETWEEN_FIGHTS = 0x2 MENU_TITLE_SCREEN_IDLE_FIGHT_2 = 0x3 MENU_TITLE_SCREEN_IDLE_HOW_TO_PLAY = 0x4 MENU_ADVENTURE_MODE_CINEMEATIC = 0x19 MENU_CHARACTER_UNLOCKED = 0x1A MENU_TOURNAMENT = 0x1B MENU_TOURNAMENT_CSS = 0x0 MENU_TOURNAMENT_BRACKET = 0x1 MENU_TOURNAMENT_INGAME = 0x4 MENU_TOURNAMENT_POSTGAME = 0x6 MENU_TRAINING_MODE = 0x1C MENU_TRAINING_CSS = 0x0 MENU_TRAINING_SSS = 0x1 MENU_TRAINING_INGAME = 0x2 MENU_TINY_MELEE = 0x1D MENU_TINY_MELEE_CSS = 0x0 MENU_TINY_MELEE_SSS = 0x1 MENU_TINY_MELEE_INGAME = 0x2 MENU_TINY_MELEE_POSTGAME = 0x4 MENU_GIANT_MELEE = 0x1E MENU_GIANT_MELEE_CSS = 0x0 MENU_GIANT_MELEE_SSS = 0x1 MENU_GIANT_MELEE_INGAME = 0x2 MENU_GIANT_MELEE_POSTGAME = 0x4 MENU_STAMINA_MODE = 0x1F MENU_STAMINA_MODE_CSS = 0x0 MENU_STAMINA_MODE_SSS = 0x1 MENU_STAMINA_MODE_INGAME = 0x2 MENU_STAMINA_MODE_POSTGAME = 0x4 MENU_HOME_RUN_CONTEST = 0x20 MENU_HOME_RUN_CONTEST_CSS = 0x0 MENU_HOME_RUN_CONTEST_INGAME = 0x1 MENU_10_MAN_MELEE = 0x21 MENU_10_MAN_MELEE_CSS = 0x00 MENU_10_MAN_MELEE_INGAME = 0x01 MENU_100_MAN_MELEE = 0x22 MENU_100_MAN_MELEE_CSS = 0x00 MENU_100_MAN_MELEE_INGAME = 0x01 MENU_3_MINUTE_MELEE = 0x23 MENU_3_MINUTE_MELEE_CSS = 0x00 MENU_3_MINUTE_MELEE_INGAME = 0x01 MENU_15_MINUTE_MELEE = 0x24 MENU_15_MINUTE_MELEE_CSS = 0x00 MENU_15_MINUTE_MELEE_INGAME = 0x01 MENU_ENDLESS_MELEE = 0x25 MENU_ENDLESS_MELEE_CSS = 0x00 MENU_ENDLESS_MELEE_INGAME = 0x01 MENU_CRUEL_MELEE = 0x26 MENU_CRUEL_MELEE_CSS = 0x00 MENU_CRUEL_MELEE_INGAME = 0x01 MENU_PROGRESSIVE_SCAN = 0x27 MENU_PLAY_INTRO_VIDEO = 0x28 MENU_MEMORY_CARD_OVERWRITE = 0x29 MENU_FIXED_CAMERA_MODE = 0x2A MENU_FIXED_CAMERA_MODE_CSS = 0x0 MENU_FIXED_CAMERA_MODE_SSS = 0x1 MENU_FIXED_CAMERA_MODE_INGAME = 0x2 MENU_FIXED_CAMERA_MODE_POSTGAME = 0x4 MENU_EVENT_MATCH = 0x2B MENU_EVENT_MATCH_SELECT = 0x0 MENU_EVENT_MATCH_INGAME = 0x1 MENU_SINGLE_BUTTON_MODE = 0x2C local character_selections = { [0x00] = { name = "captain", skin = {"original", "black", "red", "white", "green", "blue", "teal"}, team_skin = {3, 6, 5}, series = "fzero" }, [0x01] = { name = "donkey", skin = {"original", "black", "red", "blue", "green", "gold"}, team_skin = {3, 4, 5}, series = "donkey_kong" }, [0x02] = { name = "fox", skin = {"original", "red", "blue", "green", "gold"}, team_skin = {2, 3, 4}, series = "star_fox" }, [0x03] = { name = "gamewatch", skin = {"original", "red", "blue", "green", "white"}, team_skin = {2, 3, 4}, series = "game_and_watch" }, [0x04] = { name = "kirby", skin = {"original", "yellow", "blue", "red", "green", "white", "purple"}, team_skin = {4, 3, 5}, series = "kirby" }, [0x05] = { name = "koopa", skin = {"green", "red", "blue", "black", "orange"}, team_skin = {2, 3, 1}, series = "mario" }, [0x06] = { name = "link", skin = {"green", "red", "blue", "black", "white", "gold"}, team_skin = {2, 3, 1}, series = "zelda" }, [0x07] = { name = "luigi", skin = {"green", "white", "blue", "red", "purple"}, team_skin = {4, 3, 1}, series = "mario" }, [0x08] = { name = "mario", skin = {"red", "yellow", "black", "blue", "green", "teal"}, team_skin = {1, 4, 5}, series = "mario" }, [0x09] = { name = "marth", skin = {"original", "red", "green", "black", "white", "gold"}, team_skin = {2, 1, 3}, series = "fire_emblem" }, [0x10] = { name = "samus", skin = {"red", "pink", "black", "green", "blue", "teal"}, team_skin = {1, 5, 4}, series = "metroid" }, [0x11] = { name = "yoshi", skin = {"green", "red", "blue", "yellow", "pink", "light_blue", "black"}, team_skin = {2, 3, 1}, series = "yoshi" }, [0x12] = { name = "zelda", skin = {"original", "red", "blue", "green", "white", "gold"}, team_skin = {2, 3, 4}, series = "zelda" }, [0x13] = { name = "sheik", skin = {"original", "red", "blue", "green", "white", "gold"}, team_skin = {2, 3, 4}, series = "zelda" }, [0x14] = { name = "falco", skin = {"original", "red", "blue", "green", "pink"}, team_skin = {2, 3, 4}, series = "star_fox" }, [0x15] = { name = "younglink", skin = {"green", "red", "blue", "white", "black", "purple"}, team_skin = {2, 3, 1}, series = "zelda" }, [0x16] = { name = "mariod", skin = {"white", "red", "blue", "green", "black", "purple"}, team_skin = {2, 3, 4}, series = "mario" }, [0x17] = { name = "roy", skin = {"original", "red", "blue", "green", "yellow", "purple"}, team_skin = {2, 3, 4}, series = "fire_emblem" }, [0x18] = { name = "pichu", skin = {"original", "red", "blue", "green", "hat"}, team_skin = {2, 3, 4}, series = "pokemon" }, [0x19] = { name = "ganon", skin = {"original", "red", "blue", "green", "purple", "gold"}, team_skin = {2, 3, 4}, series = "zelda" }, [0x0A] = { name = "mewtwo", skin = {"original", "red", "blue", "green", "black"}, team_skin = {2, 3, 4}, series = "pokemon" }, [0x0B] = { name = "ness", skin = {"original", "yellow", "blue", "green", "pink"}, team_skin = {1, 3, 4}, series = "earthbound" }, [0x0C] = { name = "peach", skin = {"original", "daisy", "white", "blue", "green", "red"}, team_skin = {1, 4, 5}, series = "mario" }, [0x0D] = { name = "pikachu", skin = {"original", "red", "blue", "green", "detective"}, team_skin = {2, 3, 4}, series = "pokemon" }, [0x0E] = { name = "ice_climber", skin = {"original", "green", "orange", "red", "blue"}, team_skin = {4, 1, 2}, series = "ice_climbers" }, [0x0F] = { name = "purin", skin = {"original", "red", "blue", "green", "crown", "pink"}, team_skin = {2, 3, 4}, series = "pokemon" }, [0x1A] = { name = "master_hand", skinless = true, series = "smash" }, [0x1E] = { name = "crazy_hand", skinless = true, series = "smash" }, [0x1D] = { name = "giga_bowser", skinless = true, series = "smash" }, [0x21] = { name = "wireframe", skinless = true, series = "smash" }, } local beyondmelee_selection = { [0x00] = { name = "captain", skin = {"original", "black", "red", "white", "green", "blue", "maskless"}, team_skin = {3, 6, 5}, series = "fzero" }, [0x05] = { name = "koopa", skin = {"green", "red", "blue", "black", "bones"}, team_skin = {2, 3, 1}, series = "mario" }, [0x06] = { name = "link", skin = {"green", "red", "blue", "black", "white", "fierce"}, team_skin = {2, 3, 1}, series = "zelda" }, [0x08] = { name = "mario", skin = {"red", "yellow", "black", "blue", "green", "builder"}, team_skin = {1, 4, 5}, series = "mario" }, [0x0D] = { name = "pikachu", skin = {"original", "red", "blue", "green", "luchador"}, team_skin = {2, 3, 4}, series = "pokemon" }, [0x10] = { name = "samus", skin = {"red", "pink", "black", "green", "blue", "white"}, team_skin = {1, 5, 4}, series = "metroid" }, [0x16] = { name = "mariod", skin = {"white", "red", "blue", "green", "black", "hazmat"}, team_skin = {2, 3, 4}, series = "mario" }, [0x18] = { name = "pichu", skin = {"original", "red", "blue", "green", "hat"}, team_skin = {2, 3, 4}, series = "pokemon" }, [0x19] = { name = "ganon", skin = {"original", "red", "blue", "green", "purple", "spirit"}, team_skin = {2, 3, 4}, series = "zelda" }, [0x1A] = { name = "wolf", skin = {"neutral", "red", "blue", "green"}, team_skin = {2, 3, 4}, series = "star_fox" }, [0x1B] = { name = "raichu", skin = {"neutral", "king", "beach", "vomit", "warlock"}, team_skin = {2, 3, 4}, series = "pokemon" }, [0x1C] = { name = "shadowm2", skin = {"black", "red", "blue", "green", "purple"}, team_skin = {2, 3, 4}, series = "pokemon" }, [0x1D] = { name = "fay", skin = {"neutral", "red", "blue", "green"}, team_skin = {2, 3, 4}, series = "star_fox" }, [0x1E] = { name = "skullkid", skin = {"neutral", "blue", "green", "black"}, team_skin = {1, 2, 3}, series = "zelda" }, } local akaneia_selection = { [0x1A] = { name = "wolf", skin = {"neutral", "pink", "blue", "green", "brown"}, team_skin = {2, 3, 4}, series = "star_fox" }, } local textures = { series = {}, stocks = {}, skinless = {} } local graphics = love.graphics local newImage = graphics.newImage local melee = {} function melee.isAkaneia() return memory.romstring and memory.romstring.akaneia == "Akaneia" end function melee.isBeyondMelee() return memory.romstring and memory.romstring.beyondmelee == "Beyond Melee" end do local function doload(tbl) for cid, info in pairs(tbl) do if textures.series[cid] then textures.series[cid]:release() end textures.series[cid] = newImage(("textures/series/%s.png"):format(info.series)) if textures.stocks[cid] then for skin, text in pairs(textures.stocks[cid]) do text:release() end end textures.stocks[cid] = {} textures.skinless[cid] = info.skinless if info.skin then for sid, skin in ipairs(info.skin) do local stockf = ("textures/stocks/%s-%s.png"):format(info.name, skin) local stockakf = ("textures/stocks/ak/%s-%s.png"):format(info.name, skin) local stockbmf = ("textures/stocks/bm/%s-%s.png"):format(info.name, skin) if melee.isAkaneia() and love.filesystem.getInfo(stockakf) then -- Akaneia icon override textures.stocks[cid][sid-1] = newImage(stockakf) elseif melee.isBeyondMelee() and love.filesystem.getInfo(stockbmf) then -- Beyond Melee icon override textures.stocks[cid][sid-1] = newImage(stockbmf) elseif love.filesystem.getInfo(stockf) then textures.stocks[cid][sid-1] = newImage(stockf) end end else if textures.stocks[cid][1] then textures.stocks[cid][1]:release() end textures.stocks[cid][1] = newImage(("textures/stocks/%s.png"):format(info.name)) end end end function melee.loadTextures() doload(character_selections) end function melee.loadRomSpecificTextures() doload(character_selections) if melee.isAkaneia() then print("LOADED AKANEIA TEXTURES") doload(akaneia_selection) elseif melee.isBeyondMelee() then print("LOADED BEYOND MELEE TEXTURES") doload(beyondmelee_selection) end end end function melee.getPlayer(port) if not memory.player then return end if melee.isSinglePlayerGame() and not melee.isNetplayGame() and port == memory.menu.player_one_port + 1 then -- Single player games in CSS screen always use PORT 1 character info no matter what port is controlling the menus return memory.player[1].select elseif not melee.isInGame() then return memory.player[port].select end return memory.player[port] end function melee.getCharacterID(port) if not memory.player then return end local player = melee.getPlayer(port) if not player then return end local character = player.character if melee.isInGame() then local transformed = player.transformed == 256 -- Handle and detect Zelda/Sheik transformations if character == 0x13 then character = transformed and 0x12 or 0x13 elseif character == 0x12 then character = transformed and 0x13 or 0x12 end end return character end function melee.getStockTexture(id, skin) if textures.skinless[id] == true then skin = 1 end if not textures.stocks[id] or not textures.stocks[id][skin] then return textures.stocks[id] and textures.stocks[id][0] or textures.stocks[0x21][1] end return textures.stocks[id][skin] end function melee.getSeriesTexture(id) if not textures.series[id] then return textures.series[0x21] end return textures.series[id] end function melee.drawSeries(port, ...) local id = melee.getCharacterID(port) if not id then return end local series = melee.getSeriesTexture(melee.isPortEnabled(port) and id or 0x21) if not series then return end graphics.easyDraw(series, ...) end function melee.getSinglePlayerPort() if melee.isSinglePlayerGame() and not melee.isNetplayGame() then return 1 else return memory.menu.player_one_port+1 end end function melee.drawStock(port, ...) if not melee.isPortEnabled(port) then return end local id = melee.getCharacterID(port) if id == 0x21 or not memory.player then return end local player = melee.getPlayer(port) if not player or not id then return end local stock = melee.getStockTexture(id, player.skin) if not stock then return end graphics.easyDraw(stock, ...) end local TEAM_COLORS = { [0x00] = color(245, 46, 46, 255), -- Red [0x01] = color(84, 99, 255, 255), -- Blue [0x02] = color(31, 158, 64, 255), -- Green [0x04] = color(200, 200, 200, 255), -- CPU/Disabled } function melee.getPlayerTeamColor(port) if not melee.isPortEnabled(port) then return TEAM_COLORS[0x04] end local player = melee.isInGame() and melee.getPlayer(port) or memory.player[port].card if not player then return TEAM_COLORS[0x04] end return TEAM_COLORS[player.team] or color_white end local PLAYER_COLORS = { [1] = color(245, 46, 46, 255), [2] = color(84, 99, 255, 255), [3] = color(255, 199, 23, 255), [4] = color(31, 158, 64, 255), } local PORT_PLAYER = 0x0 local PORT_CPU = 0x1 local PORT_DISABLED = 0x3 function melee.isPortEnabled(port) if not port then return false end if melee.isInMenus() and melee.isSinglePlayerGame() and port ~= (memory.menu.player_one_port+1) then return false end return memory.player[port].card.mode ~= PORT_DISABLED end function melee.isPortCPU(port) return memory.player[port].card.mode == PORT_CPU end function melee.getPlayerColor(port) return melee.isPortEnabled(port) and (PLAYER_COLORS[port] or color_white) or TEAM_COLORS[0x04] end local char_replacement_map = { [0x8149] = "!", [0x8168] = "\"", [0x8194] = "#", [0x8190] = "$", [0x8193] = "%", [0x8195] = "&", [0x8166] = "'", [0x8169] = "(", [0x816A] = ")", [0x8196] = "*", [0x817B] = "+", [0x8143] = ",", [0x817C] = "-", [0x8144] = ".", [0x815E] = "/", [0x8146] = ":", [0x8147] = ";", [0x8183] = "<", [0x8181] = "=", [0x8184] = ">", [0x8148] = "?", [0x8197] = "@", [0x816D] = "[", [0x815F] = "\\", [0x816E] = "]", [0x814F] = "^", [0x8151] = "_", [0x814D] = "`", [0x816F] = "{", [0x8162] = "|", [0x8170] = "}", [0x8160] = "~", } function melee.convertStr(str) local niceStr = "" local i = 1 while i <= #str do local c1 = string.sub(str, i, i) local b1 = string.byte(c1) if bit.band(b1, 0x80) == 0x80 then local c2 = string.sub(str, i + 1, i + 1) local b2 = string.byte(c2) local b16 = bit.bor(bit.lshift(b1, 8), bit.lshift(b2, 0)) if char_replacement_map[b16] then niceStr = niceStr .. char_replacement_map[b16] end i = i + 2 else niceStr = niceStr .. c1 i = i + 1 end end return niceStr end local STAGE_SERIES = { [0x02] = "Super Mario", -- Princess Peach's Castle [0x03] = "Super Mario", -- Rainbow Cruise [0x04] = "Donkey Kong", -- Kongo Jungle [0x05] = "Donkey Kong", -- Jungle Japes [0x06] = "The Legend of Zelda", -- Great Bay [0x07] = "The Legend of Zelda", -- Hyrule Temple [0x08] = "Metroid", -- Brinstar [0x09] = "Metroid", -- Brinstar Depths [0x0A] = "Yoshi", -- Yoshi's Story [0x0B] = "Yoshi", -- Yoshi's Island [0x0C] = "Kirby", -- Fountain of Dreams [0x0D] = "Kirby", -- Green Greens [0x0E] = "Star Fox", -- Corneria [0x0F] = "Star Fox", -- Venom [0x10] = "Pokémon", -- Pokémon Stadium [0x11] = "Pokémon", -- Poké Floats [0x12] = "F-Zero", -- Mute City [0x13] = "F-Zero", -- Big Blue [0x14] = "Earthbound", -- Onett [0x15] = "Earthbound", -- Fourside [0x16] = "Ice Climbers", -- Icicle Mountain [0x18] = "Super Mario", -- Mushroom Kingdom [0x19] = "Super Mario", -- Mushroom Kingdom 2 [0x1B] = "Game & Watch", -- Flat Zone [0x1C] = "Kirby", -- Dream Land N64 [0x1D] = "Yoshi", -- Yoshi's Island N64 [0x1E] = "Donkey Kong", -- Kongo Jungle N64 [0x24] = "Super Smash Bros", -- Battlefield [0x25] = "Super Smash Bros", -- Final Destination [0x26] = "Super Smash Bros", -- Trophy Collection -- Singleplayer stages [0x1F] = "Super Mario", -- Mushroom Kingdom [0x20] = "The Legend of Zelda", -- Underground Maze [0x21] = "Metroid", -- Escape Zebes [0x22] = "F-Zero", -- F-Zero Grand Prix [0x26] = "Super Smash Bros", -- Trophy Collection [0x27] = "Super Smash Bros", -- Race to the Finish [0x42] = "Super Smash Bros", -- All-Star Rest Area [0x43] = "Super Smash Bros", -- Home-Run Contest [0x44] = "Super Mario", -- Trophy Tussel - Goomba [0x45] = "Pokémon", -- Trophy Tussel - Entei [0x46] = "The Legend of Zelda", -- Trophy Tussel - Majora's Mask } local STAGE_NAMES = { [0x02] = "Princess Peach's Castle", [0x03] = "Rainbow Cruise", [0x04] = "Kongo Jungle", [0x05] = "Jungle Japes", [0x06] = "Great Bay", [0x07] = "Hyrule Temple", [0x08] = "Brinstar", [0x09] = "Brinstar Depths", [0x0A] = "Yoshi's Story", [0x0B] = "Yoshi's Island", [0x0C] = "Fountain of Dreams", [0x0D] = "Green Greens", [0x0E] = "Corneria", [0x0F] = "Venom", [0x10] = "Pokémon Stadium", [0x11] = "Poké Floats", [0x12] = "Mute City", [0x13] = "Big Blue", [0x14] = "Onett", [0x15] = "Fourside", [0x16] = "Icicle Mountain", [0x18] = "Mushroom Kingdom", [0x19] = "Mushroom Kingdom 2", [0x1B] = "Flat Zone", [0x1C] = "Dream Land N64", [0x1D] = "Yoshi's Island N64", [0x1E] = "Kongo Jungle N64", [0x24] = "Battlefield", [0x25] = "Final Destination", } local BREAK_THE_TARGETS_STAGES = { [0x28] = "Mario Target Test", [0x29] = "Captain Falcon Target Test", [0x2A] = "Young Link Target Test", [0x2B] = "Donkey Kong Target Test", [0x2C] = "Dr. Mario Target Test", [0x2D] = "Falco Target Test", [0x2E] = "Fox Target Test", [0x2F] = "Ice Climbers Target Test", [0x30] = "Kirby Target Test", [0x31] = "Bowser Target Test", [0x32] = "Link Target Test", [0x33] = "Luigi Target Test", [0x34] = "Marth Target Test", [0x35] = "Mewtwo Target Test", [0x36] = "Ness Target Test", [0x37] = "Peach Target Test", [0x38] = "Pichu Target Test", [0x39] = "Pikachu Target Test", [0x3A] = "Jigglypuff Target Test", [0x3B] = "Samus Target Test", [0x3C] = "Sheik Target Test", [0x3D] = "Yoshi Target Test", [0x3E] = "Zelda Target Test", [0x3F] = "Mr. G&W Target Test", [0x40] = "Roy Target Test", [0x41] = "Ganondorf Target Test", -- Akaneia [0x4E] = "Wolf Target Test", } local SINGLEPLAYER_STAGES = { [0x1F] = "Mushroom Kingdom", [0x20] = "Underground Maze", [0x21] = "Escape Zebes", [0x22] = "F-Zero Grand Prix", [0x26] = "Trophy Collection", [0x27] = "Race to the Finish", [0x42] = "All-Star Rest Area", [0x43] = "Home-Run Contest", [0x44] = "Trophy Tussle - Goomba", [0x45] = "Trophy Tussle - Entei", [0x46] = "Trophy Tussle - Majora's Mask", } local AKANEIA_STAGES = { [0x47] = "Peach's Castle 64", [0x48] = "Hyrule Castle 64", [0x49] = "Saffron City 64", [0x4A] = "Planet Zebes 64", [0x4B] = "Mushroom Kingdom 64", [0x4C] = "Metal Cavern", [0x4D] = "Volleyball", } local AKANEIA_SERIES = { [0x47] = "Super Mario", [0x48] = "The Legend of Zelda", [0x49] = "Pokémon", [0x4A] = "Metroid", [0x4B] = "Super Mario", [0x4C] = "Super Mario", [0x4D] = "Super Smash Bros", } local BEYOND_MELEE_STAGES = { [0x47] = "Volleyball", [0x48] = "Smashville", [0x49] = "Sprout Tower", [0x4A] = "Fountain of Dreams", [0x4B] = "Flipper Field", [0x4C] = "Brinstar Lab", [0x4D] = "Metal Cavern", -- Metal Cavern? (Currently broken in BM-1.0) [0x4E] = "Mute Circuit", [0x4F] = "Kongo Falls", [0x50] = "Town Greens", [0x51] = "Kongle Jungle 64", [0x52] = "Poké Float Stadium 2", [0x53] = "Rainbow Ride", [0x54] = "Island Zone", [0x55] = "Wasteland", [0x56] = "Baby Bowser's Castle", [0x57] = "Midnight Destination", [0x58] = "Midnight Battlefield", [0x59] = "Dual Zone", [0x5A] = "Fountain of Dreams", -- Diet (Currently broken in BM-1.0) [0x5B] = "Stadium-ville", -- Diet (Currently broken in BM-1.0) [0x5C] = "Yoshi's Story", -- Diet [0x5D] = "Treasure Hunt", [0x5E] = "Realgam Colosseum", [0x5F] = "Vapor Story", [0x60] = "Final Destination", -- Diet [0x61] = "Battlefield", -- Diet [0x62] = "Pokémon Stadium", -- Diet [0x63] = "Galacta Battleground", } local BEYOND_MELEE_SERIES = { [0x47] = "Super Smash Bros", -- Volleyball [0x48] = "Animal Crossing", -- Smashville [0x49] = "Pokémon", -- Sprout Tower [0x4A] = "Kirby", -- Fountain of Dreams [0x4B] = "Super Smash Bros", -- Flipper Field [0x4C] = "Metroid", -- Brinstar Lab [0x4D] = "Super Mario", -- Metal Cavern? (Currently broken in BM-1.0) [0x4E] = "F-Zero", -- Mute Circuit [0x4F] = "Donkey Kong", -- Kongo Falls [0x50] = "Kirby", -- Town Greens [0x51] = "Donkey Kong", -- Kongle Jungle 64 [0x52] = "Pokémon", -- Poké Float Stadium 2 [0x53] = "Super Mario", -- Rainbow Ride [0x54] = "Yoshi", -- Island Zone [0x55] = "Kirby", -- Wasteland [0x56] = "Yoshi", -- Baby Bowser's Castle [0x57] = "Super Smash Bros", -- Midnight Destination [0x58] = "Super Smash Bros", -- Midnight Battlefield [0x59] = "Super Smash Bros", -- Dual Zone [0x5A] = "Kirby", -- Fountain of Dreams (Diet) (Currently broken in BM-1.0) [0x5B] = "Pokémon", -- Stadium-ville (Diet) (Currently broken in BM-1.0) [0x5C] = "Yoshi", -- Yoshi's Story (Diet) [0x5D] = "Yoshi", -- Treasure Hunt [0x5E] = "Pokémon", -- Realgam Colosseum [0x5F] = "Yoshi", -- Vapor Story [0x60] = "Super Smash Bros", -- Final Destination (Diet) [0x61] = "Super Smash Bros", -- Battlefield (Diet) [0x62] = "Pokémon", -- Pokémon Stadium (Diet) [0x63] = "Kirby", -- Galacta Battleground } function melee.isNetplayGame() return memory.menu.major == MENU_VS_UNKNOWN and (memory.menu.minor == MENU_VS_UNKNOWN_INGAME or memory.menu.minor == MENU_VS_UNKNOWN_VERSUS) end function melee.isTeams() if melee.isSinglePlayerGame() and not melee.isNetplayGame() then return false elseif melee.isInGame() then return memory.match.teams else return memory.menu.teams end end function melee.isSinglePlayerGame() local major = memory.menu.major return major == MENU_ALL_STAR_MODE or major == MENU_TRAINING_MODE or major == MENU_EVENT_MATCH or major == MENU_CLASSIC_MODE or major == MENU_ADVENTURE_MODE or major == MENU_TARGET_TEST or (major >= MENU_HOME_RUN_CONTEST and major <= MENU_CRUEL_MELEE) or major == MENU_VS_UNKNOWN end function melee.isBTTStage(id) return BREAK_THE_TARGETS_STAGES[id] ~= nil end function melee.isSinglePlayerStage(id) return SINGLEPLAYER_STAGES[id] ~= nil end function melee.getSinglePlayerStages() return SINGLEPLAYER_STAGES end function melee.getAllStages() return STAGE_NAMES end function melee.getAkaneiaStages() return AKANEIA_STAGES end function melee.getAkaneiaSeries() return AKANEIA_SERIES end function melee.isAkaneiaStage(id) if melee.isAkaneia() then return AKANEIA_STAGES[id] ~= nil end return false end function melee.getBeyondMeleeStages() return BEYOND_MELEE_STAGES end function melee.getBeyondMeleeSeries() return BEYOND_MELEE_SERIES end function melee.isBeyondMeleeStage(id) if melee.isBeyondMelee() then return BEYOND_MELEE_STAGES[id] ~= nil end return false end function melee.getStageName(id) if melee.isAkaneia() and AKANEIA_STAGES[id] then return AKANEIA_STAGES[id] elseif melee.isBeyondMelee() and BEYOND_MELEE_STAGES[id] then return BEYOND_MELEE_STAGES[id] end return STAGE_NAMES[id] or SINGLEPLAYER_STAGES[id] or BREAK_THE_TARGETS_STAGES[id] end function melee.getAllStageSeries() return STAGE_SERIES end function melee.getStageSeries(id) if melee.isAkaneia() and AKANEIA_SERIES[id] then return AKANEIA_SERIES[id] elseif melee.isBeyondMelee() and BEYOND_MELEE_SERIES[id] then return BEYOND_MELEE_SERIES[id] end return STAGE_SERIES[id] end function melee.matchFinsihed() return memory.match.finished == true end function melee.isInGame() if not memory.menu then return false end if memory.menu.major == MENU_ALL_STAR_MODE and memory.menu.minor < MENU_ALL_STAR_CSS then -- Even = playing the match -- Odd = in the rest area --return memory.menu.minor % 2 == 0 return true end if PANEL_SETTINGS:IsSlippiReplay() and memory.menu.major == MENU_START_MATCH then return memory.menu.minor == MENU_START_MATCH_INGAME end if memory.menu.major == MENU_VS_MODE or memory.menu.major == MENU_VS_UNKNOWN then return memory.menu.minor == MENU_VS_INGAME end if memory.menu.major >= MENU_TRAINING_MODE and memory.menu.major <= MENU_STAMINA_MODE or memory.menu.major == MENU_FIXED_CAMERA_MODE then return memory.menu.minor == MENU_TRAINING_INGAME end if memory.menu.major == MENU_EVENT_MATCH then return memory.menu.minor == MENU_EVENT_MATCH_INGAME end if memory.menu.major == MENU_CLASSIC_MODE and memory.menu.minor < MENU_CLASSIC_CONTINUE then -- Even = Verus screen -- Odd = playing the match return memory.menu.minor % 2 == 1 end if memory.menu.major == MENU_ADVENTURE_MODE then return memory.menu.minor == MENU_ADVENTURE_MUSHROOM_KINGDOM or memory.menu.minor == MENU_ADVENTURE_MUSHROOM_KINGDOM_BATTLE or memory.menu.minor == MENU_ADVENTURE_MUSHROOM_KONGO_JUNGLE_TINY_BATTLE or memory.menu.minor == MENU_ADVENTURE_MUSHROOM_KONGO_JUNGLE_GIANT_BATTLE or memory.menu.minor == MENU_ADVENTURE_UNDERGROUND_MAZE or memory.menu.minor == MENU_ADVENTURE_HYRULE_TEMPLE_BATTLE or memory.menu.minor == MENU_ADVENTURE_BRINSTAR or memory.menu.minor == MENU_ADVENTURE_ESCAPE_ZEBES or memory.menu.minor == MENU_ADVENTURE_GREEN_GREENS_KIRBY_BATTLE or memory.menu.minor == MENU_ADVENTURE_GREEN_GREENS_KIRBY_TEAM_BATTLE or memory.menu.minor == MENU_ADVENTURE_GREEN_GREENS_GIANT_KIRBY_BATTLE or memory.menu.minor == MENU_ADVENTURE_CORNARIA_BATTLE_1 or memory.menu.minor == MENU_ADVENTURE_CORNARIA_BATTLE_2 or memory.menu.minor == MENU_ADVENTURE_CORNARIA_BATTLE_3 or memory.menu.minor == MENU_ADVENTURE_POKEMON_STADIUM_BATTLE or memory.menu.minor == MENU_ADVENTURE_FZERO_GRAND_PRIX_RACE or memory.menu.minor == MENU_ADVENTURE_FZERO_GRAND_PRIX_BATTLE or memory.menu.minor == MENU_ADVENTURE_ONETT_BATTLE or memory.menu.minor == MENU_ADVENTURE_ICICLE_MOUNTAIN_CLIMB or memory.menu.minor == MENU_ADVENTURE_BATTLEFIELD_BATTLE or memory.menu.minor == MENU_ADVENTURE_BATTLEFIELD_METAL_BATTLE or memory.menu.minor == MENU_ADVENTURE_FINAL_DESTINATION_BATTLE end if memory.menu.major == MENU_TARGET_TEST then return memory.menu.minor == MENU_TARGET_TEST_INGAME end if memory.menu.major >= MENU_SUPER_SUDDEN_DEATH and memory.menu.major <= MENU_LIGHTNING_MELEE then return memory.menu.minor == MENU_SSD_INGAME end if memory.menu.major >= MENU_HOME_RUN_CONTEST and memory.menu.major <= MENU_CRUEL_MELEE then return memory.menu.minor == MENU_HOME_RUN_CONTEST_INGAME end if memory.menu.major == MENU_TITLE_SCREEN_IDLE then return memory.menu.minor == MENU_TITLE_SCREEN_IDLE_FIGHT_1 or memory.menu.minor == MENU_TITLE_SCREEN_IDLE_FIGHT_2 end return false end function melee.isInMenus() if not memory.menu then return false end if memory.menu.major == MENU_MAIN_MENU then return true end if memory.menu.major == MENU_VS_MODE or memory.menu.major == MENU_VS_UNKNOWN then return memory.menu.minor == MENU_VS_CSS or memory.menu.minor == MENU_VS_SSS end if memory.menu.major >= MENU_TRAINING_MODE and memory.menu.major <= MENU_STAMINA_MODE or memory.menu.major == MENU_FIXED_CAMERA_MODE then return memory.menu.minor == MENU_TRAINING_CSS or memory.menu.minor == MENU_TRAINING_SSS end if memory.menu.major == MENU_EVENT_MATCH then return memory.menu.minor == MENU_EVENT_MATCH_SELECT end if memory.menu.major == MENU_CLASSIC_MODE or memory.menu.major == MENU_ADVENTURE_MODE or memory.menu.major == MENU_ALL_STAR_MODE then -- All the menu_mior values all match in these three modes, so just use the MENU_CLASSIC_CSS value for simplicity return memory.menu.minor == MENU_CLASSIC_CSS end if memory.menu.major == MENU_TARGET_TEST then return memory.menu.minor == MENU_TARGET_TEST_CSS end if memory.menu.major >= MENU_SUPER_SUDDEN_DEATH and memory.menu.major <= MENU_LIGHTNING_MELEE then return memory.menu.minor == MENU_SSD_CSS or memory.menu.minor == MENU_SSD_SSS end if memory.menu.major >= MENU_HOME_RUN_CONTEST and memory.menu.major <= MENU_CRUEL_MELEE then return memory.menu.minor == MENU_HOME_RUN_CONTEST_CSS end return false end return melee
28.506024
141
0.705325
bb5708c6bb8bfb1692bdead765a93625fdf73bbb
2,259
cs
C#
templateSources/WpfApplication/Company.Desktop.Application/Dependencies/UI/NotificationService.cs
taori/Amusoft.VisualStudio.Extensions
41ab48130a0bbcbc6561b844cfcd2b185bb7cd72
[ "Apache-2.0" ]
null
null
null
templateSources/WpfApplication/Company.Desktop.Application/Dependencies/UI/NotificationService.cs
taori/Amusoft.VisualStudio.Extensions
41ab48130a0bbcbc6561b844cfcd2b185bb7cd72
[ "Apache-2.0" ]
5
2019-09-18T22:33:39.000Z
2021-02-17T20:16:04.000Z
templateSources/WpfApplication/Company.Desktop.Application/Dependencies/UI/NotificationService.cs
taori/Amusoft.VisualStudio.Extensions
41ab48130a0bbcbc6561b844cfcd2b185bb7cd72
[ "Apache-2.0" ]
null
null
null
using System; using System.Linq; using System.Windows; using System.Windows.Forms; using System.Windows.Media; using Amusoft.UI.WPF.Adorners; using Amusoft.UI.WPF.Notifications; using Company.Desktop.Framework.Mvvm.UI; using INotification = Company.Desktop.Framework.Mvvm.UI.INotification; namespace Company.Desktop.Application.Dependencies.UI { public class NotificationService : INotificationService { public void Display(INotification notification) { if (notification is Amusoft.UI.WPF.Notifications.INotification uiNotification) { var manager = GetManager(notification); manager.DisplayAsync(uiNotification, TranslatePosition(notification.Position)); } else { throw new Exception($"Notification type is not supported because it does not implement Amusoft.UI.WPF.Notifications.INotification."); } } private Position TranslatePosition(NotificationPosition position) { switch (position) { case NotificationPosition.BottomRight: return Position.BottomRight; case NotificationPosition.Bottom: return Position.Bottom; case NotificationPosition.BottomLeft: return Position.BottomLeft; case NotificationPosition.Left: return Position.Left; case NotificationPosition.TopLeft: return Position.TopLeft; case NotificationPosition.Top: return Position.Top; case NotificationPosition.TopRight: return Position.TopRight; case NotificationPosition.Right: return Position.Right; default: throw new ArgumentOutOfRangeException(nameof(position), position, null); } } private NotificationHost GetManager(INotification uiNotification) { switch (uiNotification.Target) { case NotificationTarget.PrimaryScreen: return NotificationHostManager.GetHostByScreen(Screen.PrimaryScreen); case NotificationTarget.CurrentFocusedWindow: return NotificationHostManager.GetHostByVisual(GetCurrentFocusedWindow()); default: throw new ArgumentOutOfRangeException(); } } private Visual GetCurrentFocusedWindow() { foreach (Window window in System.Windows.Application.Current.Windows) { if (window.IsActive) return window; } return System.Windows.Application.Current.MainWindow; } } }
29.337662
137
0.762284
d03f76e910670f9995f26b62b4df01f19536b184
1,288
cpp
C++
src/test/current/source/NativeReplicatorStack/RCQNightWatchTXRService/RCQService.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/test/current/source/NativeReplicatorStack/RCQNightWatchTXRService/RCQService.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/test/current/source/NativeReplicatorStack/RCQNightWatchTXRService/RCQService.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace ktl; using namespace Common; using namespace TXRStatefulServiceBase; using namespace RCQNightWatchTXRService; using namespace TxnReplicator; StringLiteral const TraceComponent("RCQNightWatchTXRService"); RCQService::RCQService( __in FABRIC_PARTITION_ID partitionId, __in FABRIC_REPLICA_ID replicaId, __in Common::ComponentRootSPtr const & root) : NightWatchTXRService::Service(partitionId, replicaId, root) { } ComPointer<IFabricStateProvider2Factory> RCQService::GetStateProviderFactory() { KAllocator & allocator = this->KtlSystemValue->PagedAllocator(); return TestComStateProvider2Factory::Create(allocator); } NightWatchTXRService::ITestRunner::SPtr RCQService::CreateTestRunner( __in Common::ByteBufferUPtr const & testParametersJson, __in TxnReplicator::ITransactionalReplicator & txnReplicator, __in KAllocator & allocator) { RCQTestRunner::SPtr runner = RCQTestRunner::Create(testParametersJson, txnReplicator, allocator); return runner.RawPtr(); }
33.894737
101
0.696429
33225eab00b383e4146cdc55bf9455bff939639a
4,051
kt
Kotlin
Multimedia/CameraAlbumTest/app/src/main/java/com/workaholiclab/cameraalbumtest/MainActivity.kt
Workaholic-Lab/Studying-Kotlin
55220c5c71cbce5b398c4b6c0aacacaa5e94c4e4
[ "Apache-2.0" ]
null
null
null
Multimedia/CameraAlbumTest/app/src/main/java/com/workaholiclab/cameraalbumtest/MainActivity.kt
Workaholic-Lab/Studying-Kotlin
55220c5c71cbce5b398c4b6c0aacacaa5e94c4e4
[ "Apache-2.0" ]
null
null
null
Multimedia/CameraAlbumTest/app/src/main/java/com/workaholiclab/cameraalbumtest/MainActivity.kt
Workaholic-Lab/Studying-Kotlin
55220c5c71cbce5b398c4b6c0aacacaa5e94c4e4
[ "Apache-2.0" ]
null
null
null
package com.workaholiclab.cameraalbumtest import android.app.Activity import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import android.media.ExifInterface import android.net.Uri import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.provider.MediaStore import androidx.core.content.FileProvider import kotlinx.android.synthetic.main.activity_main.* import java.io.File class MainActivity : AppCompatActivity() { val takePhoto = 1 lateinit var imageUri :Uri lateinit var outputImage: File val fromAlbum = 2 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) takePhotoBtn.setOnClickListener { //创建File对象,用于存储拍照后的图片 outputImage = File(externalCacheDir,"output_image.jpg")//采用应用管理目录来缓存(避免读写SD卡的危险权限) if(outputImage.exists()){ outputImage.delete() } outputImage.createNewFile() imageUri = if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N){ //将File对象转化成一个封装过的Uri对象(FileProvider对数据进行了保护) FileProvider.getUriForFile(this,"com.workaholiclab.cameraalbumtest.fileprovider",outputImage) }else{ Uri.fromFile(outputImage) //该设备低于android7就调用Uri的fromFile方法将File转话为Uri对象 //这个Uri对象包含了这张图片的真实存在的路径 } //启动相机程序 val intent =Intent("android.media.action.IMAGE_CAPTURE") intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri)//指定图片的输入地址,这里为刚刚的Uri对象 startActivityForResult(intent,takePhoto) } //选取相册 fromAlbumBtn.setOnClickListener { //打开文件选择器 val intent = Intent(Intent.ACTION_OPEN_DOCUMENT) intent.addCategory(Intent.CATEGORY_OPENABLE) //指定只显示图片 intent.type ="image/*" startActivityForResult(intent,fromAlbum) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when(requestCode){ takePhoto->{ if (resultCode ==Activity.RESULT_OK){ //将拍摄的照片显示出来 val bitmap= BitmapFactory.decodeStream(contentResolver.openInputStream(imageUri))//将这张图片解析称为Bitmap对象 imageView.setImageBitmap(rotateIfRequired(bitmap))//变成ImageView,需要注意一些手机上拍照转化会发生一些旋转,需要处理一下 } } fromAlbum->{ if(resultCode == Activity.RESULT_OK && data != null){ data.data?.let { uri -> //将选择的图片显示 val bitmap=getBitmapFromUri(uri) imageView.setImageBitmap(bitmap) } } } } } private fun getBitmapFromUri(uri: Uri) = contentResolver .openFileDescriptor(uri,"r")?.use { BitmapFactory.decodeFileDescriptor(it.fileDescriptor) } //照片旋转处理 private fun rotateIfRequired(bitmap: Bitmap): Bitmap { val exif = ExifInterface(outputImage.path) val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL) return when(orientation){ ExifInterface.ORIENTATION_ROTATE_90->rotateBitmap(bitmap,90) ExifInterface.ORIENTATION_ROTATE_180->rotateBitmap(bitmap,180) ExifInterface.ORIENTATION_ROTATE_270->rotateBitmap(bitmap,270) else-> bitmap } } private fun rotateBitmap(bitmap: Bitmap, degree: Int): Bitmap { val matrix =Matrix() matrix.postRotate(degree.toFloat()) val rotateBitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.width,bitmap.height,matrix,true) bitmap.recycle()//将不再需要的Bitmap对象回收 return rotateBitmap } }
37.509259
120
0.643792
75b23380552ff2d8dc974d17b6cdf558713635df
3,472
swift
Swift
Tests/MessagePackTests/StringTests.swift
BrettThePark/MessagePack.swift
c31d29c541346ffadac68a3919c4ab9b67fd31f4
[ "MIT" ]
null
null
null
Tests/MessagePackTests/StringTests.swift
BrettThePark/MessagePack.swift
c31d29c541346ffadac68a3919c4ab9b67fd31f4
[ "MIT" ]
null
null
null
Tests/MessagePackTests/StringTests.swift
BrettThePark/MessagePack.swift
c31d29c541346ffadac68a3919c4ab9b67fd31f4
[ "MIT" ]
2
2018-02-18T17:25:24.000Z
2019-11-19T05:22:31.000Z
import Foundation import XCTest @testable import MessagePack class StringTests: XCTestCase { static var allTests = { return [ ("testLiteralConversion", testLiteralConversion), ("testPackFixstr", testPackFixstr), ("testUnpackFixstr", testUnpackFixstr), ("testUnpackFixstrEmpty", testUnpackFixstrEmpty), ("testPackStr8", testPackStr8), ("testUnpackStr8", testUnpackStr8), ("testPackStr16", testPackStr16), ("testUnpackStr16", testUnpackStr16), ("testPackStr32", testPackStr32), ("testUnpackStr32", testUnpackStr32), ] }() func testLiteralConversion() { var implicitValue: MessagePackValue implicitValue = "Hello, world!" XCTAssertEqual(implicitValue, .string("Hello, world!")) implicitValue = MessagePackValue(extendedGraphemeClusterLiteral: "Hello, world!") XCTAssertEqual(implicitValue, .string("Hello, world!")) implicitValue = MessagePackValue(unicodeScalarLiteral: "Hello, world!") XCTAssertEqual(implicitValue, .string("Hello, world!")) } func testPackFixstr() { let packed = Data([0xad, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21]) XCTAssertEqual(pack(.string("Hello, world!")), packed) } func testUnpackFixstr() { let packed = Data([0xad, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21]) let unpacked = try? unpack(packed) XCTAssertEqual(unpacked?.value, .string("Hello, world!")) XCTAssertEqual(unpacked?.remainder.count, 0) } func testUnpackFixstrEmpty() { let packed = Data([0xa0]) let unpacked = try? unpack(packed) XCTAssertEqual(unpacked?.value, .string("")) XCTAssertEqual(unpacked?.remainder.count, 0) } func testPackStr8() { let string = String(repeating: "*", count: 0x20) XCTAssertEqual(pack(.string(string)), Data([0xd9, 0x20]) + string.data(using: .utf8)!) } func testUnpackStr8() { let string = String(repeating: "*", count: 0x20) let packed = Data([0xd9, 0x20]) + string.data(using: .utf8)! let unpacked = try? unpack(packed) XCTAssertEqual(unpacked?.value, .string(string)) XCTAssertEqual(unpacked?.remainder.count, 0) } func testPackStr16() { let string = String(repeating: "*", count: 0x1000) XCTAssertEqual(pack(.string(string)), [0xda, 0x10, 0x00] + string.data(using: .utf8)!) } func testUnpackStr16() { let string = String(repeating: "*", count: 0x1000) let packed = Data([0xda, 0x10, 0x00]) + string.data(using: .utf8)! let unpacked = try? unpack(packed) XCTAssertEqual(unpacked?.value, .string(string)) XCTAssertEqual(unpacked?.remainder.count, 0) } func testPackStr32() { let string = String(repeating: "*", count: 0x10000) XCTAssertEqual(pack(.string(string)), Data([0xdb, 0x00, 0x01, 0x00, 0x00]) + string.data(using: .utf8)!) } func testUnpackStr32() { let string = String(repeating: "*", count: 0x10000) let packed = Data([0xdb, 0x00, 0x01, 0x00, 0x00]) + string.data(using: .utf8)! let unpacked = try? unpack(packed) XCTAssertEqual(unpacked?.value, .string(string)) XCTAssertEqual(unpacked?.remainder.count, 0) } }
35.793814
112
0.621544
fdaaa669ddcbf179981acccc401de9246bb0316f
11,119
bash
Shell
concourse/scripts/pxf-perf-multi-node.bash
pivotal/pxf
bbe92fa7c711e447b81953cfe4afaa49b5b10c4b
[ "Apache-2.0" ]
3
2018-10-22T14:28:40.000Z
2021-03-29T17:12:21.000Z
concourse/scripts/pxf-perf-multi-node.bash
pivotal/pxf
bbe92fa7c711e447b81953cfe4afaa49b5b10c4b
[ "Apache-2.0" ]
null
null
null
concourse/scripts/pxf-perf-multi-node.bash
pivotal/pxf
bbe92fa7c711e447b81953cfe4afaa49b5b10c4b
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env bash set -eo pipefail export PGHOST=mdw export PGUSER=gpadmin export PGDATABASE=tpch GPHOME="/usr/local/greenplum-db-devel" CWDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" HADOOP_HOSTNAME="ccp-$(cat terraform_dataproc/name)-m" VALIDATION_QUERY="COUNT(*) AS Total, COUNT(DISTINCT l_orderkey) AS ORDERKEYS, SUM(l_partkey) AS PARTKEYSUM, COUNT(DISTINCT l_suppkey) AS SUPPKEYS, SUM(l_linenumber) AS LINENUMBERSUM" LINEITEM_COUNT="unset" source "${CWDIR}/pxf_common.bash" function create_database_and_schema { psql -d postgres <<-EOF DROP DATABASE IF EXISTS tpch; CREATE DATABASE tpch; \c tpch; CREATE TABLE lineitem ( l_orderkey INTEGER NOT NULL, l_partkey INTEGER NOT NULL, l_suppkey INTEGER NOT NULL, l_linenumber INTEGER NOT NULL, l_quantity DECIMAL(15,2) NOT NULL, l_extendedprice DECIMAL(15,2) NOT NULL, l_discount DECIMAL(15,2) NOT NULL, l_tax DECIMAL(15,2) NOT NULL, l_returnflag CHAR(1) NOT NULL, l_linestatus CHAR(1) NOT NULL, l_shipdate DATE NOT NULL, l_commitdate DATE NOT NULL, l_receiptdate DATE NOT NULL, l_shipinstruct CHAR(25) NOT NULL, l_shipmode CHAR(10) NOT NULL, l_comment VARCHAR(44) NOT NULL ) DISTRIBUTED BY (l_partkey); EOF psql -c "CREATE EXTERNAL TABLE lineitem_external (like lineitem) LOCATION ('pxf://tmp/lineitem_read/?PROFILE=HdfsTextSimple') FORMAT 'CSV' (DELIMITER '|')" psql -c "CREATE OR REPLACE FUNCTION write_to_s3() RETURNS integer AS '\$libdir/gps3ext.so', 's3_export' LANGUAGE C STABLE" psql -c "CREATE OR REPLACE FUNCTION read_from_s3() RETURNS integer AS '\$libdir/gps3ext.so', 's3_import' LANGUAGE C STABLE" psql -c "CREATE PROTOCOL s3 (writefunc = write_to_s3, readfunc = read_from_s3)" cat > /tmp/s3.conf <<-EOF [default] accessid = "${AWS_ACCESS_KEY_ID}" secret = "${AWS_SECRET_ACCESS_KEY}" threadnum = 4 chunksize = 67108864 low_speed_limit = 10240 low_speed_time = 60 encryption = true version = 1 proxy = "" autocompress = false verifycert = true server_side_encryption = "" # gpcheckcloud config gpcheckcloud_newline = "\n" EOF cat cluster_env_files/etc_hostfile | grep sdw | cut -d ' ' -f 2 > /tmp/segment_hosts gpssh -u gpadmin -f /tmp/segment_hosts -v -s -e 'mkdir ~/s3/' gpscp -u gpadmin -f /tmp/segment_hosts /tmp/s3.conf =:~/s3/s3.conf } function create_pxf_external_tables { psql -c "CREATE EXTERNAL TABLE pxf_lineitem_read (like lineitem) LOCATION ('pxf://tmp/lineitem_read/?PROFILE=HdfsTextSimple') FORMAT 'CSV' (DELIMITER '|')" psql -c "CREATE WRITABLE EXTERNAL TABLE pxf_lineitem_write (like lineitem) LOCATION ('pxf://tmp/lineitem_write/?PROFILE=HdfsTextSimple') FORMAT 'CSV' DISTRIBUTED BY (l_partkey)" } function create_gphdfs_external_tables { psql -c "CREATE EXTERNAL TABLE gphdfs_lineitem_read (like lineitem) LOCATION ('gphdfs://${HADOOP_HOSTNAME}:8020/tmp/lineitem_read_gphdfs/') FORMAT 'CSV' (DELIMITER '|')" psql -c "CREATE WRITABLE EXTERNAL TABLE gphdfs_lineitem_write (like lineitem) LOCATION ('gphdfs://${HADOOP_HOSTNAME}:8020/tmp/lineitem_write_gphdfs/') FORMAT 'CSV' DISTRIBUTED BY (l_partkey)" } function setup_sshd { service sshd start passwd -u root if [ -d cluster_env_files ]; then /bin/cp -Rf cluster_env_files/.ssh/* /root/.ssh /bin/cp -f cluster_env_files/private_key.pem /root/.ssh/id_rsa /bin/cp -f cluster_env_files/public_key.pem /root/.ssh/id_rsa.pub /bin/cp -f cluster_env_files/public_key.openssh /root/.ssh/authorized_keys fi } function write_data { local dest local source dest=${2} source=${1} psql -c "INSERT INTO ${dest} SELECT * FROM ${source}" } function validate_write_to_gpdb { local external local internal local external_values local gpdb_values external=${1} internal=${2} external_values=$(psql -t -c "SELECT ${VALIDATION_QUERY} FROM ${external}") gpdb_values=$(psql -t -c "SELECT ${VALIDATION_QUERY} FROM ${internal}") cat << EOF Results from external query ------------------------------ EOF echo ${external_values} cat << EOF Results from GPDB query ------------------------------ EOF echo ${gpdb_values} if [ "${external_values}" != "${gpdb_values}" ]; then echo ERROR! Unable to validate data written from external to GPDB exit 1 fi } function gphdfs_validate_write_to_external { psql -c "CREATE EXTERNAL TABLE gphdfs_lineitem_read_after_write (like lineitem) LOCATION ('gphdfs://${HADOOP_HOSTNAME}:8020/tmp/lineitem_write_gphdfs/') FORMAT 'CSV'" local external_values local gpdb_values external_values=$(psql -t -c "SELECT ${VALIDATION_QUERY} FROM gphdfs_lineitem_read_after_write") gpdb_values=$(psql -t -c "SELECT ${VALIDATION_QUERY} FROM lineitem") cat << EOF Results from external query ------------------------------ EOF echo ${external_values} cat << EOF Results from GPDB query ------------------------------ EOF echo ${gpdb_values} if [ "${external_values}" != "${gpdb_values}" ]; then echo ERROR! Unable to validate data written from GPDB to external exit 1 fi } function pxf_validate_write_to_external { psql -c "CREATE EXTERNAL TABLE pxf_lineitem_read_after_write (like lineitem) LOCATION ('pxf://tmp/lineitem_write/?PROFILE=HdfsTextSimple') FORMAT 'CSV'" local external_values local gpdb_values external_values=$(psql -t -c "SELECT ${VALIDATION_QUERY} FROM pxf_lineitem_read_after_write") gpdb_values=$(psql -t -c "SELECT ${VALIDATION_QUERY} FROM lineitem") cat << EOF Results from external query ------------------------------ EOF echo ${external_values} cat << EOF Results from GPDB query ------------------------------ EOF echo ${gpdb_values} if [ "${external_values}" != "${gpdb_values}" ]; then echo ERROR! Unable to validate data written from GPDB to external exit 1 fi } function run_pxf_benchmark { create_pxf_external_tables cat << EOF ############################ # PXF READ BENCHMARK # ############################ EOF time psql -c "SELECT COUNT(*) FROM pxf_lineitem_read" cat << EOF ############################ # PXF WRITE BENCHMARK # ############################ EOF time write_data "lineitem" "pxf_lineitem_write" cat << EOF Validating data --------------- EOF pxf_validate_write_to_external } function run_gphdfs_benchmark { create_gphdfs_external_tables cat << EOF ############################ # GPHDFS READ BENCHMARK # ############################ EOF time psql -c "SELECT COUNT(*) FROM gphdfs_lineitem_read" cat << EOF ############################ # GPHDFS WRITE BENCHMARK # ############################ EOF time write_data "lineitem" "gphdfs_lineitem_write" cat << EOF Validating data --------------- EOF gphdfs_validate_write_to_external } function create_s3_extension_external_tables { psql -c "CREATE EXTERNAL TABLE lineitem_s3_c (like lineitem) location('s3://s3.us-west-2.amazonaws.com/gpdb-ud-scratch/s3-profile-test/lineitem/10/ config=/home/gpadmin/s3/s3.conf') FORMAT 'CSV' (DELIMITER '|')" psql -c "CREATE EXTERNAL TABLE lineitem_s3_pxf (like lineitem) location('pxf://s3-profile-test/lineitem/10/?PROFILE=HdfsTextSimple') format 'CSV' (DELIMITER '|');" psql -c "CREATE WRITABLE EXTERNAL TABLE lineitem_s3_c_write (like lineitem) LOCATION('s3://s3.us-west-2.amazonaws.com/gpdb-ud-scratch/s3-profile-test/output/ config=/home/gpadmin/s3/s3.conf') FORMAT 'CSV'" psql -c "CREATE WRITABLE EXTERNAL TABLE lineitem_s3_pxf_write (LIKE lineitem) LOCATION('pxf://s3-profile-test/output/?PROFILE=HdfsTextSimple') FORMAT 'CSV'" } function assert_count_in_table { local table_name="$1" local expected_count="$2" local num_rows=$(time psql -t -c "SELECT COUNT(*) FROM $table_name" | tr -d ' ') if [ "${num_rows}" != "${expected_count}" ]; then echo "Expected number of rows to be ${expected_count} but was ${num_rows}" exit 1 fi } function run_s3_extension_benchmark { create_s3_extension_external_tables cat << EOF ############################ # S3 C Ext READ BENCHMARK # ############################ EOF assert_count_in_table "lineitem_s3_c" "${LINEITEM_COUNT}" cat << EOF ############################ # S3 C Ext WRITE BENCHMARK # ############################ EOF time psql -c "INSERT INTO lineitem_s3_c_write SELECT * FROM lineitem" # We need to update core-site.xml to point to the the S3 bucket # and we need to provide AWS credentials cat > /tmp/core-site.xml <<-EOF <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="configuration.xsl"?> <configuration> <property> <name>fs.defaultFS</name> <value>s3a://gpdb-ud-scratch</value> </property> <property> <name>fs.s3a.access.key</name> <value>${AWS_ACCESS_KEY_ID}</value> </property> <property> <name>fs.s3a.secret.key</name> <value>${AWS_SECRET_ACCESS_KEY}</value> </property> <property> <name>fs.s3a.fast.upload</name> <value>true</value> </property> </configuration> EOF # Make a backup of core-site and update it with the S3 core-site gpscp -u gpadmin -f /tmp/segment_hosts /tmp/core-site.xml =:/tmp/core-site-patch.xml gpssh -u gpadmin -f /tmp/segment_hosts -v -s -e \ 'source /usr/local/greenplum-db-devel/greenplum_path.sh && mv /etc/hadoop/conf/core-site.xml /etc/hadoop/conf/core-site.xml.back && cp /tmp/core-site-patch.xml /etc/hadoop/conf/core-site.xml && $GPHOME/pxf/bin/pxf restart' cat << EOF ############################ # S3 PXF READ BENCHMARK # ############################ EOF assert_count_in_table "lineitem_s3_pxf" "${LINEITEM_COUNT}" cat << EOF ############################ # S3 PXF WRITE BENCHMARK # ############################ EOF time psql -c "INSERT INTO lineitem_s3_pxf_write SELECT * FROM lineitem" # Restore core-site gpssh -u gpadmin -f /tmp/segment_hosts -v -s -e \ 'source /usr/local/greenplum-db-devel/greenplum_path.sh && mv /etc/hadoop/conf/core-site.xml /etc/hadoop/conf/core-site.xml.s3 && cp /etc/hadoop/conf/core-site.xml.back /etc/hadoop/conf/core-site.xml && $GPHOME/pxf/bin/pxf restart' } function main { setup_gpadmin_user setup_sshd remote_access_to_gpdb install_gpdb_binary install_pxf_server source ${GPHOME}/greenplum_path.sh create_database_and_schema echo "Loading data from external into GPDB..." write_data "lineitem_external" "lineitem" echo "Validating loaded data..." validate_write_to_gpdb "lineitem_external" "lineitem" echo -e "Data loading and validation complete\n" LINEITEM_COUNT=$(psql -t -c "SELECT COUNT(*) FROM lineitem" | tr -d ' ') run_s3_extension_benchmark if [ "${BENCHMARK_GPHDFS}" == "true" ]; then run_gphdfs_benchmark fi run_pxf_benchmark } main
31.058659
237
0.652846
6ae4fd98e691e4ef08da6c3dc48ccfa5f0104ff9
582
h
C
PhotoSecurity/Home/Model/HHAlbumModel.h
coderhw/Album-
2c4201f0d34bdb8da5a25479c88c37f02e8006b9
[ "MIT" ]
null
null
null
PhotoSecurity/Home/Model/HHAlbumModel.h
coderhw/Album-
2c4201f0d34bdb8da5a25479c88c37f02e8006b9
[ "MIT" ]
null
null
null
PhotoSecurity/Home/Model/HHAlbumModel.h
coderhw/Album-
2c4201f0d34bdb8da5a25479c88c37f02e8006b9
[ "MIT" ]
null
null
null
// // XPAlbumModel.h // PhotoSecurity // // Created by huwen on 2017/3/7. // Copyright © 2017年 huwen. All rights reserved. // #import <Foundation/Foundation.h> @class HHPhotoModel; @interface HHAlbumModel : NSObject /// 相册id @property (nonatomic, assign) NSInteger albumid; /// 相册目录 @property (nonatomic, copy) NSString *directory; /// 相册名称 @property (nonatomic, copy) NSString *name; /// 该相册下的图片数量 @property (nonatomic, assign) NSInteger count; /// 排序id @property (nonatomic, assign) NSInteger orderid; /// 缩略图 @property (nonatomic, strong) HHPhotoModel *thumbImage; @end
20.068966
55
0.719931
79fdd775a178b6f1e081dae83fbe751b15181134
1,460
dart
Dart
lib/page-encointer/bazaar/3_businesses/businesses.dart
jinosh05/encointer-wallet-flutter
59d05daa486a75ba19bf8070dfde8a9d32f11c64
[ "Apache-2.0" ]
null
null
null
lib/page-encointer/bazaar/3_businesses/businesses.dart
jinosh05/encointer-wallet-flutter
59d05daa486a75ba19bf8070dfde8a9d32f11c64
[ "Apache-2.0" ]
25
2020-06-03T08:52:11.000Z
2020-07-09T08:45:39.000Z
lib/page-encointer/bazaar/3_businesses/businesses.dart
jinosh05/encointer-wallet-flutter
59d05daa486a75ba19bf8070dfde8a9d32f11c64
[ "Apache-2.0" ]
1
2020-06-21T13:00:46.000Z
2020-06-21T13:00:46.000Z
import 'package:encointer_wallet/page-encointer/bazaar/menu/2_my_businesses/businessesOnMap.dart'; import 'package:encointer_wallet/page-encointer/bazaar/shared/bazaarItemVertical.dart'; import 'package:encointer_wallet/page-encointer/bazaar/shared/data_model/demo_data/demoData.dart'; import 'package:encointer_wallet/page-encointer/bazaar/shared/toggleButtonsWithTitle.dart'; import 'package:encointer_wallet/utils/translations/index.dart'; import 'package:flutter/material.dart'; class Businesses extends StatelessWidget { final data = allBusinesses; @override Widget build(BuildContext context) { return Column(children: [ ToggleButtonsWithTitle(I18n.of(context).translationsForLocale().bazaar.categories, allCategories, null), Expanded( child: ListView.builder( itemCount: data.length, itemBuilder: (context, index) => BazaarItemVertical( data: data, index: index, cardHeight: 125, ), ), ), ElevatedButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => BusinessesOnMap(), )); }, child: Row( mainAxisSize: MainAxisSize.min, children: [ new Icon(Icons.map), new Text(I18n.of(context).translationsForLocale().bazaar.map), ], ), ) ]); } }
33.181818
110
0.641096
6f1d144b52b625eaba199ea9d23217c3903b71ff
569
dart
Dart
lib/utils/common_widgets/positions/radial_position.dart
dungnv2602/flutter_ui_challenges
09d1fdc14120de10f39ca57da01aa02166a4e3a1
[ "Apache-2.0" ]
null
null
null
lib/utils/common_widgets/positions/radial_position.dart
dungnv2602/flutter_ui_challenges
09d1fdc14120de10f39ca57da01aa02166a4e3a1
[ "Apache-2.0" ]
null
null
null
lib/utils/common_widgets/positions/radial_position.dart
dungnv2602/flutter_ui_challenges
09d1fdc14120de10f39ca57da01aa02166a4e3a1
[ "Apache-2.0" ]
null
null
null
import 'dart:math'; import 'package:flutter/material.dart'; class RadialPosition extends StatelessWidget { final double radius; final double angle; final Widget child; const RadialPosition({ Key key, this.radius = 0, this.angle = 0, @required this.child, }) : assert(child != null), super(key: key); @override Widget build(BuildContext context) { final x = cos(angle) * radius; final y = sin(angle) * radius; return Transform( transform: Matrix4.translationValues(x, y, 0), child: child, ); } }
19.62069
52
0.639719
dc23bbc4052df6a4458338867e6f7dd2063dfd6d
19,952
rb
Ruby
spec/instance/instance_state_spec.rb
rightscale/right_link
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
[ "MIT" ]
3
2015-02-24T20:13:10.000Z
2016-02-18T07:50:05.000Z
spec/instance/instance_state_spec.rb
rightscale/right_link
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
[ "MIT" ]
21
2015-01-29T19:04:15.000Z
2020-06-25T04:13:53.000Z
spec/instance/instance_state_spec.rb
rightscale/right_link
b33a209c20a8a0942dd9f1fe49a08030d4ca209f
[ "MIT" ]
6
2015-06-24T14:50:33.000Z
2020-07-28T05:24:56.000Z
# # Copyright (c) 2009-2011 RightScale Inc # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. require ::File.expand_path('../spec_helper', __FILE__) describe RightScale::InstanceState do include RightScale::SpecHelper before(:each) do # Avoid actually updating MOTD or performing wall broadcasts flexmock(RightScale::InstanceState).should_receive(:update_motd).and_return(nil) flexmock(RightScale::InstanceState).should_receive(:broadcast_wall).and_return(nil) flexmock(RightScale::Log).should_receive(:debug) @default_ttl = 4 * 24 * 60 * 60 setup_state(identity = '1', mock_instance_state = false) do @user_id = 123 @booting_args = ['/state_recorder/record', {:state => "booting", :agent_identity => @identity, :from_state => "pending"}, nil, {:time_to_live => @default_ttl}, Proc] @operational_args = ['/state_recorder/record', {:state => "operational", :agent_identity => @identity, :from_state => "booting"}, nil, {:time_to_live => @default_ttl}, Proc] @decommissioning_args = ['/state_recorder/record', {:state => "decommissioning", :agent_identity => @identity, :from_state => "operational"}, nil, {:time_to_live => @default_ttl}, Proc] @decommissioned_args = ['/state_recorder/record', {:state => 'decommissioned', :agent_identity => @identity, :user_id => @user_id, :skip_db_update => false, :kind => "terminate"}, Proc] @record_success = @results_factory.success_results @sender = flexmock(RightScale::Sender.instance) @sender.should_receive(:send_request).with(*@booting_args).and_yield(@record_success).by_default @sender.should_receive(:send_request).and_yield(@record_success).by_default end @state_file = RightScale::InstanceState::STATE_FILE @login_policy_file = RightScale::InstanceState::LOGIN_POLICY_FILE end after(:all) do cleanup_state end it 'should initialize' do run_em_test do RightScale::InstanceState.init(@identity) RightScale::InstanceState.value.should == 'booting' RightScale::InstanceState.identity.should == @identity stop_em_test end end context :init do context('when saved state missing') do it 'should detect initial boot' do run_em_test do flexmock(File).should_receive(:file?).with(@state_file).and_return(false) flexmock(File).should_receive(:file?).with(@login_policy_file).and_return(false) delete_if_exists(state_file_path) RightScale::InstanceState.init(@identity) RightScale::InstanceState.identity.should == @identity RightScale::InstanceState.value.should == 'booting' RightScale::InstanceState.reboot?.should be_false stop_em_test end end end context('when saved state exists') do # Using this method instead of before(:each) because must be running EM # before InstanceState.init is called def before_each # Simulate a successful first boot RightScale::InstanceState.init(@identity) @state = {'value' => 'operational', 'identity' => @identity, 'uptime' => 120.0, 'reboot' => false, 'startup_tags' => [], 'log_level' => 1, 'last_recorded_value' => 'operational', 'record_retries' => 0, 'last_communication' => 0} flexmock(RightScale::JsonUtilities).should_receive(:read_json).with(@state_file).and_return(@state).by_default end it 'should detect restart after decommission' do run_em_test do before_each # Simulate a prior decommission @state.merge!('value' => 'decommissioned', 'last_recorded_value' => 'decommissioned') flexmock(RightScale::JsonUtilities).should_receive(:read_json).with(@state_file).and_return(@state).once flexmock(RightScale::InstanceState).should_receive(:uptime).and_return(300.0) flexmock(RightScale::JsonUtilities).should_receive(:write_json).with(@state_file, Hash).never flexmock(RightScale::InstanceState).should_receive(:record_state).never RightScale::InstanceState.init(@identity) RightScale::InstanceState.value.should == 'decommissioned' stop_em_test end end it 'should detect restart after crash and record state if needed' do run_em_test do before_each # Simulate a prior crash when recorded state did not match local state @state.merge!('value' => 'operational', 'last_recorded_value' => 'booting', 'record_retries' => 1) flexmock(RightScale::JsonUtilities).should_receive(:read_json).with(@state_file).and_return(@state).once flexmock(RightScale::InstanceState).should_receive(:uptime).and_return(300.0) flexmock(RightScale::JsonUtilities).should_receive(:write_json).with(@state_file, Hash).never flexmock(RightScale::InstanceState).should_receive(:record_state).once RightScale::InstanceState.init(@identity) RightScale::InstanceState.value.should == 'operational' stop_em_test end end it 'should not record state if in read-only mode' do run_em_test do before_each # Simulate a prior crash when recorded state did not match local state @state.merge!('value' => 'operational', 'last_recorded_value' => 'booting', 'record_retries' => 1) flexmock(RightScale::JsonUtilities).should_receive(:read_json).with(@state_file).and_return(@state).once flexmock(RightScale::InstanceState).should_receive(:uptime).and_return(300.0) flexmock(RightScale::JsonUtilities).should_receive(:write_json).with(@state_file, Hash).never flexmock(RightScale::InstanceState).should_receive(:record_state).never RightScale::InstanceState.init(@identity, read_only = true) RightScale::InstanceState.value.should == 'operational' stop_em_test end end it 'should detect reboot based on stored reboot state' do run_em_test do before_each # Simulate reboot @state.merge!('value' => 'booting', 'reboot' => true) flexmock(RightScale::InstanceState).should_receive(:uptime).and_return(1.0) flexmock(RightScale::JsonUtilities).should_receive(:write_json).with(@state_file, Hash).once flexmock(RightScale::InstanceState).should_receive(:record_state).once RightScale::InstanceState.init(@identity) RightScale::InstanceState.identity.should == @identity RightScale::InstanceState.value.should == 'booting' RightScale::InstanceState.reboot?.should be_true stop_em_test end end it 'should detect bundled boot' do run_em_test do before_each flexmock(RightScale::JsonUtilities).should_receive(:write_json).with(@state_file, Hash) flexmock(RightScale::InstanceState).should_receive(:record_state).once RightScale::InstanceState.init('2') RightScale::InstanceState.identity.should == '2' RightScale::InstanceState.value.should == 'booting' stop_em_test end end end end context :value= do it 'should store state' do run_em_test do RightScale::InstanceState.init(@identity) RightScale::InstanceState.value.should == "booting" @sender.should_receive(:send_request).with(*@operational_args).and_yield(@record_success).once RightScale::InstanceState.value = "operational" RightScale::InstanceState.init(@identity) RightScale::InstanceState.value.should == "operational" @sender.should_receive(:send_request).with(*@decommissioning_args).and_yield(@record_success).once RightScale::InstanceState.value = "decommissioning" RightScale::InstanceState.init(@identity) RightScale::InstanceState.value.should == "decommissioning" RightScale::InstanceState.decommission_type.should == nil stop_em_test end end it 'should record state' do run_em_test do RightScale::InstanceState.init(@identity) RightScale::InstanceState.value.should == "booting" @sender.should_receive(:send_request).with(*@operational_args).and_yield(@record_success).once RightScale::InstanceState.value = "operational" RightScale::InstanceState.value.should == "operational" @sender.should_receive(:send_request).with(*@decommissioning_args).and_yield(@record_success).once RightScale::InstanceState.value = "decommissioning" RightScale::InstanceState.value.should == "decommissioning" RightScale::InstanceState.decommission_type.should == nil stop_em_test end end it 'should persist decommissioning state with decommission type if specified' do run_em_test do RightScale::InstanceState.init(@identity) RightScale::InstanceState.value.should == "booting" @sender.should_receive(:send_request).with(*@operational_args).and_yield(@record_success).once RightScale::InstanceState.value = "operational" RightScale::InstanceState.value.should == "operational" @sender.should_receive(:send_request).with(*@decommissioning_args).and_yield(@record_success).once RightScale::InstanceState.decommission_type = RightScale::ShutdownRequest::REBOOT RightScale::InstanceState.value.should == "decommissioning" RightScale::InstanceState.decommission_type.should == RightScale::ShutdownRequest::REBOOT # reinitialize from state file to simulate aborted decommission case. RightScale::InstanceState.init(@identity) RightScale::InstanceState.value.should == "decommissioning" RightScale::InstanceState.last_recorded_value.should == "decommissioning" RightScale::InstanceState.decommission_type.should == RightScale::ShutdownRequest::REBOOT stop_em_test end end it 'should not record state for unrecorded values' do run_em_test do @sender.should_receive(:send_request).never RightScale::InstanceState.value = "decommissioned" RightScale::InstanceState.value.should == "decommissioned" stop_em_test end end it 'should store last recorded value after recording state' do run_em_test do RightScale::InstanceState.init(@identity) RightScale::InstanceState.value.should == "booting" RightScale::InstanceState.last_recorded_value.should == "booting" @sender.should_receive(:send_request).with(*@operational_args).and_yield(@record_success).once RightScale::InstanceState.value = "operational" RightScale::InstanceState.value.should == "operational" RightScale::InstanceState.last_recorded_value.should == "operational" stop_em_test end end it 'should retry record after a delay if there is an error' do run_em_test do RightScale::InstanceState.init(@identity) flexmock(EM).should_receive("add_timer").with(RightScale::RetryableRequest::DEFAULT_TIMEOUT, Proc).once flexmock(EM).should_receive("add_timer").with(RightScale::InstanceState::RETRY_RECORD_STATE_DELAY, Proc).once flexmock(RightScale::Log).should_receive(:error).with(/Failed to record state/) error = @results_factory.error_results("error") @sender.should_receive(:send_request).with(*@operational_args).and_yield(error).once RightScale::InstanceState.value = "operational" RightScale::InstanceState.value.should == "operational" RightScale::InstanceState.last_recorded_value.should == "booting" stop_em_test end end it 'should store the last recorded value if returned with the error' do run_em_test do RightScale::InstanceState.init(@identity) flexmock(EM).should_receive("add_timer").with(RightScale::RetryableRequest::DEFAULT_TIMEOUT, Proc).once flexmock(EM).should_receive("add_timer").with(RightScale::InstanceState::RETRY_RECORD_STATE_DELAY, Proc).once error = @results_factory.error_results("State from which transitioning (booting) does not match currently " + "recorded state (pending)") @sender.should_receive(:send_request).with(*@operational_args).and_yield(error).once RightScale::InstanceState.last_recorded_value.should == "booting" RightScale::InstanceState.value = "operational" RightScale::InstanceState.value.should == "operational" RightScale::InstanceState.last_recorded_value.should == "pending" stop_em_test end end it 'should limit record retries' do run_em_test do RightScale::InstanceState.init(@identity) RightScale::InstanceState.const_set(:MAX_RECORD_STATE_RETRIES, 1) flexmock(EM).should_receive("add_timer").with(RightScale::RetryableRequest::DEFAULT_TIMEOUT, Proc).twice flexmock(EM).should_receive("add_timer").with(RightScale::InstanceState::RETRY_RECORD_STATE_DELAY, Proc).and_yield.once error = @results_factory.error_results("State from which transitioning (booting) does not match currently " + "recorded state (pending)") @sender.should_receive(:send_request).with(*@operational_args).and_yield(error).once @sender.should_receive(:send_request).with('/state_recorder/record', {:state => "operational", :agent_identity => "1", :from_state => "pending"}, nil, {:time_to_live => @default_ttl}, Proc).and_yield(error).once RightScale::InstanceState.last_recorded_value.should == "booting" RightScale::InstanceState.value = "operational" RightScale::InstanceState.value.should == "operational" RightScale::InstanceState.last_recorded_value.should == "pending" stop_em_test end end it 'should not retry record if recorded state is no longer inconsistent' do run_em_test do RightScale::InstanceState.init(@identity) flexmock(EM).should_receive("add_timer").once error = @results_factory.error_results("State from which transitioning (booting) does not match currently " + "recorded state (operational)") @sender.should_receive(:send_request).with(*@operational_args).and_yield(error).once RightScale::InstanceState.last_recorded_value.should == "booting" RightScale::InstanceState.value = "operational" RightScale::InstanceState.value.should == "operational" RightScale::InstanceState.last_recorded_value.should == "operational" stop_em_test end end it 'should cancel running record state request before running another' do run_em_test do decommissioning_args = ['/state_recorder/record', {:state => "decommissioning", :agent_identity => "1", :from_state => "booting"}, nil, {:time_to_live => @default_ttl}, Proc] RightScale::InstanceState.init(@identity) RightScale::InstanceState.value.should == "booting" RightScale::InstanceState.last_recorded_value.should == "booting" @sender.should_receive(:send_request).with(*@operational_args).once @sender.should_receive(:send_request).with(*decommissioning_args).and_yield(@record_success).once RightScale::InstanceState.value = "operational" RightScale::InstanceState.record_request.should_not be_nil flexmock(RightScale::InstanceState.record_request).should_receive(:cancel).with("re-request").once RightScale::InstanceState.value = "decommissioning" RightScale::InstanceState.value.should == "decommissioning" RightScale::InstanceState.last_recorded_value.should == "decommissioning" stop_em_test end end it 'should raise an exception if the value being set is invalid' do run_em_test do RightScale::InstanceState.init(@identity) lambda do RightScale::InstanceState.value = "stopped" end.should raise_error(ArgumentError) stop_em_test end end it 'should raise an exception if in read-only mode' do run_em_test do RightScale::InstanceState.init(@identity) RightScale::InstanceState.init(@identity, read_only = true) lambda do RightScale::InstanceState.value = "stopped" end.should raise_error(RightScale::Exceptions::Application) stop_em_test end end end context :shutdown do it 'should record decommissioned state without specifying last recorded state' do run_em_test do flexmock(EM).should_receive(:add_timer).times(3) RightScale::InstanceState.init(@identity) RightScale::InstanceState.value.should == "booting" RightScale::InstanceState.value = "decommissioning" @sender.should_receive(:send_request).with(*@decommissioned_args).once RightScale::InstanceState.shutdown(@user_id, false, 'terminate') stop_em_test end end it 'should request removal of queue' do run_em_test do now = Time.at(1000000) flexmock(Time).should_receive(:now).and_return(now) flexmock(EM).should_receive(:add_timer).times(3) flexmock(RightScale::RightHttpClient.instance).should_receive(:close).with(:receive).once RightScale::InstanceState.init(@identity) RightScale::InstanceState.value.should == "booting" RightScale::InstanceState.value = "decommissioning" @sender.should_receive(:send_push).with('/registrar/remove', {:agent_identity => '1', :created_at => now.to_i}).once RightScale::InstanceState.shutdown(@user_id, false, 'terminate') stop_em_test end end end it 'should update last communication and store it but only if sufficient time has elapsed' do run_em_test do RightScale::InstanceState.init(@identity) flexmock(RightScale::InstanceState).should_receive(:store_state).once RightScale::InstanceState.communicated RightScale::InstanceState.communicated stop_em_test end end it 'should always record startup tags' do run_em_test do RightScale::InstanceState.init(@identity) RightScale::InstanceState.startup_tags = [ 'a_tag', 'another_tag' ] RightScale::InstanceState.init(@identity) RightScale::InstanceState.startup_tags.should == [ 'a_tag', 'another_tag' ] stop_em_test end end end
46.078522
132
0.686197
e778e606a10cc68ee20efacfc37b67bce9400d3d
10,210
php
PHP
app/Http/Controllers/Backend/User/UserController.php
renjunzhao/laravel-layuiAdmin
59915929bfce750382bcb8b8975285e56ef8017f
[ "MIT" ]
1
2019-12-11T01:42:55.000Z
2019-12-11T01:42:55.000Z
app/Http/Controllers/Backend/User/UserController.php
renjunzhao/laravel-layuiAdmin
59915929bfce750382bcb8b8975285e56ef8017f
[ "MIT" ]
1
2020-06-02T02:13:39.000Z
2020-06-02T02:13:39.000Z
app/Http/Controllers/Backend/User/UserController.php
renjunzhao/laravel-layuiAdmin
59915929bfce750382bcb8b8975285e56ef8017f
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\Backend\User; use App\Models\User\AdminUser; use App\Repositories\Interfaces\User\AdminUserRepository; use App\Repositories\Interfaces\User\UserRepository; use App\Models\User\User; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Spatie\Permission\Models\Role; class UserController extends Controller { /** * @var */ protected $userRepository; /** * @var AdminUserRepository */ protected $adminUserRepository; /** * UserController constructor. * @param UserRepository $userRepository * @param AdminUserRepository $adminUserRepository */ public function __construct(UserRepository $userRepository,AdminUserRepository $adminUserRepository) { $this->userRepository = $userRepository; $this->adminUserRepository = $adminUserRepository; } /** * 用户信息 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function info() { $token = getToken(); $user = getAdminUser(); $role = Role::query()->get(); //获取用户的角色 $role_id = db('user_has_roles')->where('model_id',$user->id)->first()->role_id; return view('backend.user.user.info',compact('token','user','role','role_id')); } /** * 用户信息修改 * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function infoEdit(Request $request) { $data = [ 'nickname' => $request->nickname, 'remark' => $request->remark ]; AdminUser::query()->where('id',$request->id)->update($data); return json(0,'编辑成功',[ 'code' => 1001 ]); } /** * 用户修改密码 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function password() { $token = getToken(); $user = getAdminUser(); return view('backend.user.user.password',compact('token','user')); } /** * 密码修改 * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function passwordEdit(Request $request) { $user = AdminUser::query()->find(request('id')); if (!Hash::check($request->oldPassword,$user->password)){ return json(0,'原密码输入错误',[ 'code' => 5001 ]); } AdminUser::query()->where('id',$request->id)->update(['password' => Hash::make($request->password)]); return json(0,'修改成功',[ 'code' => 1001 ]); } /** * 用户列表 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function userList() { $token = getToken(); $user = getAdminUser(); return view('backend.user.user.list',compact('token','user')); } /** * 列表 1 用户列表 2 管理员列表 3 角色列表 * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function listApi(Request $request) { $type = request('type'); if ($type == 1){ $where = []; $where1 = []; $where2 = []; if (isset($request->username) && $request->username != null){ $where = [ ['username' ,'like', '%'.$request->username.'%'], ]; } if (isset($request->email) && $request->email != null){ $where1 = [ 'email' => $request->email ]; } if (isset($request->is_lock) && $request->is_lock != 0){ $where2 = [ 'is_lock' => $request->is_lock ]; } $user = User::query()->where($where)->where($where1)->where($where2)->paginate(request('limit',30)); $count = User::query()->count(); return listJson(0,'用户列表',$count,$user->items()); }elseif ($type == 2){ $where = []; if (isset($request->name) && $request->name != []){ $where = [ ['name','like','%'.$request->name.'%'] ]; } $user = AdminUser::query()->where($where)->paginate(request('limit',30))->items(); foreach($user as $k => $v){ $role = db('user_has_roles')->where('model_id',$v->id)->first(); if ($role){ $role_id = $role->role_id; $user[$k]['role_name'] = Role::query()->find($role_id)->name; }else{ $user[$k]['role_name'] = '无角色'; } } $count = AdminUser::query()->count(); return listJson(0,'后台管理员列表',$count,$user); } } /** * 删除 1 用户列表 2 管理员列表 3 角色列表 * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function delApi(Request $request) { $type = request('type'); if ($type == 1){ User::query()->where('id',$request->id)->delete(); return json(0,'删除成功',[ 'code' => 1001 ]); }elseif ($type == 2){ AdminUser::query()->where('id',$request->id)->delete(); return json(0,'删除成功',[ 'code' => 1001 ]); } } /** * 删除 1 用户列表 2 管理员列表 3 角色列表 * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function batchDelApi(Request $request) { $type = request('type'); $arr = $request->arr; $id = []; foreach($arr as $v){ $id[] = $v['id']; } if ($type == 1){ User::query()->whereIn('id',$id)->delete(); return json(0,'删除成功',[ 'code' => 1001 ]); }elseif ($type == 2){ AdminUser::query()->whereIn('id',$id)->delete(); return json(0,'删除成功',[ 'code' => 1001 ]); } } /** * 添加 1 用户列表 2 管理员列表 3 角色列表 * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function createApi(Request $request) { $type = request('type'); if ($type == 1){ }elseif ($type == 2){ $admin_user = AdminUser::query()->where('name',$request->name)->first(); if ($admin_user){ return json(0,'昵称重复',[ 'code' => 5001 ]); } $data = $request->except('_token','token','role','role_id'); $data['password'] = Hash::make($data['password']); $adminUser = AdminUser::query()->create($data); $user = AdminUser::query()->where('id',$adminUser->id)->first(); $role = Role::query()->find($request->role_id); if ($role){ $user->assignRole($role->name); } return json(0,'添加成功',[ 'code' => 1001 ]); } } /** * 编辑 1 用户列表 2 管理员列表 3 角色列表 * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function editApi(Request $request) { $type = request('type'); if ($type == 1){ $user = User::query()->where('id',$request->id)->first(); if (!$user){ return json(0,'用户不存在',[ 'code' => 5001 ]); } $data = $request->except('_token','token','file','type'); $user->update($data); return json(0,'更新成功',[ 'code' => 1001 ]); }elseif ($type == 2){ $admin_user = AdminUser::query() ->where('id','<>',$request->id) ->where('name',$request->name)->first(); if ($admin_user){ return json(0,'昵称重复',[ 'code' => 5001 ]); } $data = $request->except('_token','token','role','role_id','password','type'); $user = AdminUser::query()->where('id',$request->id)->first(); $oldRole = db('user_has_roles')->where('model_id',$user->id)->first(); if ($oldRole){ $roleOld = Role::query()->find($oldRole->role_id); if ($roleOld){ $user->removeRole($roleOld->name); } } $role = Role::query()->find($request->role_id); if ($role){ $user->assignRole($role->name); } AdminUser::query()->where('id',$request->id)->update($data); return json(0,'更新成功',[ 'code' => 1001 ]); } } /** * 用户编辑 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function userEditForm() { $token = getToken(); $user = getAdminUser(); $userObj = ''; if (request('id')){ $userObj = User::query()->find(request('id')); } return view('backend.user.user.userform',compact('token','user','userObj')); } /** * 管理员列表 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function adminUserList() { $token = getToken(); $user = getAdminUser(); return view('backend.user.administrators.list',compact('token','user')); } /** * 管理员编辑 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function adminUserEditForm() { $token = getToken(); $user = getAdminUser(); $userObj = ''; if (request('id')){ $userObj = AdminUser::query()->find(request('id')); } $role = db('user_has_roles')->where('model_id',request('id'))->first(); $role_id = ''; if ($role){ $role_id = $role->role_id; } $role = Role::query()->get(); return view('backend.user.administrators.adminform',compact('token','user','userObj','role_id','role')); } }
30.207101
112
0.480118
bf5b1c98d5be4e05910fc16a72130bf10b1fbf99
1,198
gemspec
Ruby
json_web_token.gemspec
garyf/json_web_token
1ad8a182722790876aa5f85bfdd218d65e23e3fe
[ "MIT" ]
71
2015-07-09T01:51:48.000Z
2021-07-20T03:21:08.000Z
json_web_token.gemspec
garyf/json_web_token
1ad8a182722790876aa5f85bfdd218d65e23e3fe
[ "MIT" ]
7
2016-10-07T07:01:02.000Z
2019-05-29T20:53:18.000Z
json_web_token.gemspec
garyf/json_web_token
1ad8a182722790876aa5f85bfdd218d65e23e3fe
[ "MIT" ]
8
2015-10-19T12:48:50.000Z
2020-07-14T11:16:31.000Z
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'json_web_token/version' Gem::Specification.new do |s| s.name = 'json_web_token' s.version = JsonWebToken::VERSION s.authors = ['Gary Fleshman'] s.email = ['gfleshman@newforge-tech.com'] s.summary = 'JSON Web Token (JWT) for Ruby' s.description = 'Ruby implementation of the JSON Web Token (JWT) standard, RFC 7519' s.homepage = 'https://github.com/garyf/json_web_token' s.license = 'MIT' s.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end s.require_paths = ['lib'] s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 2.2.0' s.add_runtime_dependency 'json', '~> 2.1' s.add_development_dependency 'bundler', '~> 1.15' s.add_development_dependency 'rake', '~> 12.0' s.add_development_dependency 'rspec', '~> 3.6' s.add_development_dependency 'pry-byebug', '~> 3.4' s.add_development_dependency 'simplecov', '~> 0.14' s.add_development_dependency 'yard', '~> 0.9' s.add_development_dependency 'wwtd', '~> 1.3' end
33.277778
88
0.652755
63b820544388b30dd0ed89c8b6f7330ec8fb8524
4,574
rs
Rust
core/src/avm1/globals/movie_clip_loader.rs
cyrozap/ruffle
88f368ad0a4fe207ecbe92ebf54cda889bcd7651
[ "Apache-2.0", "Unlicense" ]
10,028
2019-07-01T00:17:18.000Z
2022-03-31T23:54:07.000Z
core/src/avm1/globals/movie_clip_loader.rs
cyrozap/ruffle
88f368ad0a4fe207ecbe92ebf54cda889bcd7651
[ "Apache-2.0", "Unlicense" ]
4,776
2019-06-28T17:14:16.000Z
2022-03-31T21:04:05.000Z
core/src/avm1/globals/movie_clip_loader.rs
wcbx/ruffle
1fec012053bb4849be3ff8cef54edca23ec1abf5
[ "Apache-2.0", "Unlicense" ]
518
2019-08-09T02:18:04.000Z
2022-03-31T01:50:48.000Z
//! `MovieClipLoader` impl use crate::avm1::activation::Activation; use crate::avm1::error::Error; use crate::avm1::globals::as_broadcaster::BroadcasterFunctions; use crate::avm1::object::script_object::ScriptObject; use crate::avm1::object::TObject; use crate::avm1::property::Attribute; use crate::avm1::property_decl::{define_properties_on, Declaration}; use crate::avm1::{ArrayObject, Object, Value}; use crate::backend::navigator::RequestOptions; use crate::display_object::{DisplayObject, TDisplayObject}; use gc_arena::MutationContext; const PROTO_DECLS: &[Declaration] = declare_properties! { "loadClip" => method(load_clip); "unloadClip" => method(unload_clip); "getProgress" => method(get_progress); }; pub fn constructor<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let listeners = ArrayObject::new( activation.context.gc_context, activation.context.avm1.prototypes().array, [this.into()], ); this.define_value( activation.context.gc_context, "_listeners", Value::Object(listeners.into()), Attribute::DONT_ENUM, ); Ok(this.into()) } pub fn load_clip<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Object<'gc>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let url_val = args.get(0).cloned().unwrap_or(Value::Undefined); let url = url_val.coerce_to_string(activation)?; let target = args.get(1).cloned().unwrap_or(Value::Undefined); if let Value::Object(target) = target { if let Some(mc) = target .as_display_object() .and_then(|dobj| dobj.as_movie_clip()) { let fetch = activation .context .navigator .fetch(&url, RequestOptions::get()); let process = activation.context.load_manager.load_movie_into_clip( activation.context.player.clone().unwrap(), DisplayObject::MovieClip(mc), fetch, url.to_string(), None, Some(this), ); activation.context.navigator.spawn_future(process); } Ok(true.into()) } else { Ok(false.into()) } } pub fn unload_clip<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let target = args.get(0).cloned().unwrap_or(Value::Undefined); if let Value::Object(target) = target { if let Some(mut mc) = target .as_display_object() .and_then(|dobj| dobj.as_movie_clip()) { mc.unload(&mut activation.context); mc.replace_with_movie(activation.context.gc_context, None); return Ok(true.into()); } } Ok(false.into()) } pub fn get_progress<'gc>( activation: &mut Activation<'_, 'gc, '_>, _this: Object<'gc>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let target = args.get(0).cloned().unwrap_or(Value::Undefined); if let Value::Object(target) = target { if let Some(mc) = target .as_display_object() .and_then(|dobj| dobj.as_movie_clip()) { let ret_obj = ScriptObject::object(activation.context.gc_context, None); ret_obj.define_value( activation.context.gc_context, "bytesLoaded", mc.movie() .map(|mv| (mv.uncompressed_len()).into()) .unwrap_or(Value::Undefined), Attribute::empty(), ); ret_obj.define_value( activation.context.gc_context, "bytesTotal", mc.movie() .map(|mv| (mv.uncompressed_len()).into()) .unwrap_or(Value::Undefined), Attribute::empty(), ); return Ok(ret_obj.into()); } } Ok(Value::Undefined) } pub fn create_proto<'gc>( gc_context: MutationContext<'gc, '_>, proto: Object<'gc>, fn_proto: Object<'gc>, array_proto: Object<'gc>, broadcaster_functions: BroadcasterFunctions<'gc>, ) -> Object<'gc> { let mcl_proto = ScriptObject::object(gc_context, Some(proto)); broadcaster_functions.initialize(gc_context, mcl_proto.into(), array_proto); define_properties_on(PROTO_DECLS, gc_context, mcl_proto, fn_proto); mcl_proto.into() }
31.115646
84
0.583078
25591840480f6b324fe123504a8062062c94fe8f
165
cs
C#
VweCore/Abstractions/IRelativelyPositionable.cs
Synnotech-AG/VweXmlSetCollectionsError
0588ff557477f66515ac158b696fd10040a2a83d
[ "MIT" ]
146
2019-11-28T13:09:43.000Z
2022-03-29T04:46:50.000Z
VweCore/Abstractions/IRelativelyPositionable.cs
Synnotech-AG/VweXmlSetCollectionsError
0588ff557477f66515ac158b696fd10040a2a83d
[ "MIT" ]
229
2019-11-27T16:35:20.000Z
2022-02-23T09:18:04.000Z
VweCore/Abstractions/IRelativelyPositionable.cs
Synnotech-AG/VweXmlSetCollectionsError
0588ff557477f66515ac158b696fd10040a2a83d
[ "MIT" ]
21
2019-12-05T07:26:34.000Z
2021-12-03T16:06:07.000Z
using VweCore.Geometry; namespace VweCore.Abstractions { public interface IRelativelyPositionable : IMovable { Point2D Offset { get; set; } } }
18.333333
55
0.684848
b1206d64e38afbed9c3345648bd759bc83348958
516
py
Python
etl/tests/embedded/test_distance.py
Rockynrcan/nrcan_api
13d8fb306d8185f6bcd082c559ad3fe8b4340cc7
[ "MIT" ]
7
2017-12-15T03:58:29.000Z
2018-04-23T22:48:53.000Z
etl/tests/embedded/test_distance.py
Rockynrcan/nrcan_api
13d8fb306d8185f6bcd082c559ad3fe8b4340cc7
[ "MIT" ]
137
2018-01-24T16:44:57.000Z
2018-06-25T14:02:10.000Z
etl/tests/embedded/test_distance.py
Rockynrcan/nrcan_api
13d8fb306d8185f6bcd082c559ad3fe8b4340cc7
[ "MIT" ]
4
2018-02-15T12:40:52.000Z
2018-07-03T14:22:51.000Z
import pytest from energuide.embedded import distance def test_distance() -> None: output = distance.Distance(1) assert output.metres == 1.0 assert output.feet == pytest.approx(3.28084) def test_from_square_feet() -> None: output = distance.Distance.from_feet(1) assert output.metres == pytest.approx(0.304800) assert output.feet == pytest.approx(1.0) def test_equality() -> None: version1 = distance.Distance(1) version2 = distance.Distance(1) assert version1 == version2
23.454545
51
0.703488
e7bb2631cf41b3aec2d9d4bef888710171bf9305
4,500
dart
Dart
lib/screens/animated_container.dart
NitramTasu/FlutterWidgetGuide
cf85e46596a68ea2cc3ad941891a5852b1d2b62f
[ "Apache-2.0" ]
321
2019-08-20T11:42:20.000Z
2022-02-19T15:10:51.000Z
lib/screens/animated_container.dart
kiranjisac/FlutterWidgetGuide
d9c3bde38269d239b0e79e8638eaa2ed345ebb1e
[ "Apache-2.0" ]
11
2019-08-25T14:34:46.000Z
2020-10-26T16:34:21.000Z
lib/screens/animated_container.dart
kiranjisac/FlutterWidgetGuide
d9c3bde38269d239b0e79e8638eaa2ed345ebb1e
[ "Apache-2.0" ]
81
2019-08-22T02:38:44.000Z
2022-03-21T06:18:45.000Z
import 'package:flutter/material.dart'; import 'package:flutter_widget_guide/Code.dart'; import 'package:flutter_widget_guide/CodeScreen.dart'; import 'package:flutter_widget_guide/utils.dart'; import '../Ads.dart'; class AnimatedContainerWidget extends StatefulWidget { @override _AnimatedContainerWidgetState createState() => _AnimatedContainerWidgetState(); } class _AnimatedContainerWidgetState extends State<AnimatedContainerWidget> { Alignment _alignment = Alignment.center; double _animatedHeight = 200.0; double _animatedWidth = 400.0; double _iconHeight = 180.0; double _iconWidth = 180.0; Color _animatedColor = Colors.red; bool _isAnimated = false; @override void initState() { //Hide banner ad if it isn't already hidden Ads.hideBannerAd(); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: Text( 'Animated Container Widget', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, fontFamily: Utils.ubuntuRegularFont), ), actions: <Widget>[ IconButton( icon: Icon(Icons.code), onPressed: () => Navigator.push( context, MaterialPageRoute( builder: (context) => CodeScreen(code: Code.animatedContainerCode), ), ), ) ], ), body: SingleChildScrollView( child: Container( margin: EdgeInsets.only(top: 24), child: Center( ///Animated Container to change the background color with ///an animation child: AnimatedContainer( duration: Duration(seconds: 2), width: _animatedWidth, height: _animatedHeight, color: _animatedColor, curve: Curves.fastOutSlowIn, ///Animated container that changes the alignment of ///FlutterLogo with an animation child: AnimatedContainer( duration: Duration(seconds: 2), curve: Curves.fastOutSlowIn, alignment: _alignment, ///Animated Container to change the dimentions of the ///FlutterLogo with an animation child: AnimatedContainer( duration: Duration(seconds: 2), curve: Curves.fastOutSlowIn, height: _iconHeight, width: _iconWidth, child: FlutterLogo( colors: Colors.amber, textColor: Colors.white, ), ), ), ), ), ), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: FloatingActionButton.extended( backgroundColor: Colors.green, onPressed: () => setState(() { /// Condition to toggle the _isAnimated bool variable _animatedWidth == 400.0 ? _isAnimated = true : _isAnimated = false; /// Condition to change the alignment of Flutter logo _isAnimated ? _alignment = Alignment.topCenter : _alignment = Alignment.center; /// Condition to change the width of the background container _isAnimated ? _animatedWidth = 200.0 : _animatedWidth = 400.0; /// Condition to change the height of background container /// MediaQuery.of(context).size.height - 200 is done to keep /// height always above the FAB _isAnimated ? _animatedHeight = MediaQuery.of(context).size.height - 200 : _animatedHeight = 200.0; /// Condition to change the background color _isAnimated ? _animatedColor = Colors.lightBlue : _animatedColor = Colors.red; /// Condition to change the width of FlutterLogo _isAnimated ? _iconWidth = 100.0 : _iconWidth = 180.0; /// Condition to change the height of FlutterLogo _isAnimated ? _iconHeight = 100.0 : _iconHeight = 180.0; }), icon: Icon( Icons.movie_filter, color: Colors.white, ), label: Text( "Animate", style: TextStyle(color: Colors.white), ), ), ); } }
32.846715
77
0.574222
b2b0975db9ac20e3d4084a6a60a139c737f3983a
1,788
dart
Dart
example/example.dart
tvolkert/AnimatedLoginButton
90423c80cead771de8ca55cb53616486dbe42ee9
[ "Apache-2.0" ]
4
2019-07-30T12:34:14.000Z
2020-02-04T07:15:04.000Z
example/example.dart
tvolkert/AnimatedLoginButton
90423c80cead771de8ca55cb53616486dbe42ee9
[ "Apache-2.0" ]
1
2019-07-07T17:01:29.000Z
2019-07-07T17:01:29.000Z
example/example.dart
tvolkert/AnimatedLoginButton
90423c80cead771de8ca55cb53616486dbe42ee9
[ "Apache-2.0" ]
2
2019-07-04T04:50:03.000Z
2019-11-20T18:08:34.000Z
import 'dart:io'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:animatedloginbutton/animatedloginbutton.dart'; class LoginAnimationDemo extends StatefulWidget{ @override State<StatefulWidget> createState() { return new LoginAnimationDemoState(); } } class LoginAnimationDemoState extends State<LoginAnimationDemo>{ //使用系统的请求 var httpClient = new HttpClient(); var url = "https://github.com/"; var _result=""; final LoginErrorMessageController loginErrorMessageController=LoginErrorMessageController(); @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("登陆按钮动画"), ), body: new Center( child:new Container( child:new AnimatedLoginButton( loginErrorMessageController:loginErrorMessageController, onTap: () async { try { var request = await httpClient.getUrl(Uri.parse(url)); var response = await request.close(); if (response.statusCode == HttpStatus.ok) { _result = await response.transform(utf8.decoder).join(); //拿到数据后,对数据进行梳理 loginErrorMessageController.showErrorMessage("网络异常"); } else { _result = 'ERROR CODE: ${response.statusCode}'; loginErrorMessageController.showErrorMessage("网络异常 $_result"); } } catch (exception) { _result = '网络异常'; loginErrorMessageController.showErrorMessage("网络异常"); } print(_result); }, ), ), ), ); } }
27.090909
94
0.595638
a470924dadf2bb37a20bfe8a89376995dca64134
1,046
php
PHP
src/Common/Network/Response.php
keika299/Chap
0666326bcc663b5e3f2e642dc415106f489c8d93
[ "MIT" ]
null
null
null
src/Common/Network/Response.php
keika299/Chap
0666326bcc663b5e3f2e642dc415106f489c8d93
[ "MIT" ]
null
null
null
src/Common/Network/Response.php
keika299/Chap
0666326bcc663b5e3f2e642dc415106f489c8d93
[ "MIT" ]
null
null
null
<?php namespace keika299\ConohaAPI\Common\Network; use Psr\Http\Message\ResponseInterface; /** * Class Response * * This class is wrapper for \GuzzleHttp\Psr7\Response. * * @package keika299\ConohaAPI\Common\Network */ class Response { /** * @var ResponseInterface */ private $response; /** * Response constructor * * @param ResponseInterface $response */ public function __construct(ResponseInterface $response) { $this->response = $response; } /** * Get status code * * @return int */ public function getStatusCode() { return $this->response->getStatusCode(); } /** * Get response body * * @return string */ public function getBody() { return $this->response->getBody(); } /** * Get json object * * That object consists array. * * @return mixed */ public function getJson() { return json_decode($this->response->getBody()); } }
16.870968
60
0.566922
38c6800989b82798e903b01a7f73afba91370b55
398
php
PHP
app/Situacion.php
osmel/bh
b250307ac24ed4613dad6cdbeb53dc7a03a2fcd6
[ "MIT" ]
null
null
null
app/Situacion.php
osmel/bh
b250307ac24ed4613dad6cdbeb53dc7a03a2fcd6
[ "MIT" ]
null
null
null
app/Situacion.php
osmel/bh
b250307ac24ed4613dad6cdbeb53dc7a03a2fcd6
[ "MIT" ]
null
null
null
<?php namespace App; use App\CandidatoVacante; use Illuminate\Database\Eloquent\Model; class Situacion extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'id','nombre', ]; public function seleccionesCliente() { return $this->hasMany(CandidatoVacante::class); //,'user_id' } }
14.214286
68
0.605528
117784e6e795d4cbf1beeed39911cc33ed0fcd29
1,424
lua
Lua
game/scripts/vscripts/abilities/heroes/anko/modifiers/modifier_anko_senei_ta_jashu_ms_slow.lua
jaden-young/NWR
27c3c7103214d0e4f5c89e224dff8f539537337b
[ "MIT" ]
null
null
null
game/scripts/vscripts/abilities/heroes/anko/modifiers/modifier_anko_senei_ta_jashu_ms_slow.lua
jaden-young/NWR
27c3c7103214d0e4f5c89e224dff8f539537337b
[ "MIT" ]
4
2022-01-30T22:00:04.000Z
2022-02-09T16:51:39.000Z
game/scripts/vscripts/abilities/heroes/anko/modifiers/modifier_anko_senei_ta_jashu_ms_slow.lua
jaden-young/NWR
27c3c7103214d0e4f5c89e224dff8f539537337b
[ "MIT" ]
2
2021-11-11T03:42:14.000Z
2021-12-16T09:28:10.000Z
modifier_anko_senei_ta_jashu_ms_slow = class({}) function modifier_anko_senei_ta_jashu_ms_slow:IsDebuff() return 1 end function modifier_anko_senei_ta_jashu_ms_slow:IsHidden() return 0 end function modifier_anko_senei_ta_jashu_ms_slow:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_MOVESPEED_BASE_OVERRIDE } return funcs end --[[ ============================================================================================================ Author: Zenicus Date: November 11, 2015 -- adds a modifier which slows the target on x percent ================================================================================================================= ]] function modifier_anko_senei_ta_jashu_ms_slow:GetModifierMoveSpeedOverride(keys) print ("Current ms", self:GetIdealSpeed()) local ability_index = self:GetCaster():FindAbilityByName("anko_senei_ta_jashu"):GetAbilityIndex() if ability_index ~= nil then local ability = self:GetCaster():GetAbilityByIndex(ability_index) print ("Ability", ability) local ms_slow = ability:GetLevelSpecialValueFor("move_slow", (ability:GetLevel() - 1)) local current_ms = self:GetIdealSpeed() print ("MS_slow =", ms_slow) local new_ms = current_ms + current_ms*(ms_slow/100) print ("Final ms=", new_ms) return new_ms end end
33.116279
116
0.591994
f16e56911c5a4d9aa5474654bf55f9945cbdc56b
1,616
rake
Ruby
lib/tasks/assemble.rake
taf2/assemblage
4799faa9e67ecbf1483264aac11f305fd383edbe
[ "MIT" ]
1
2015-11-05T03:46:36.000Z
2015-11-05T03:46:36.000Z
lib/tasks/assemble.rake
taf2/assemblage
4799faa9e67ecbf1483264aac11f305fd383edbe
[ "MIT" ]
null
null
null
lib/tasks/assemble.rake
taf2/assemblage
4799faa9e67ecbf1483264aac11f305fd383edbe
[ "MIT" ]
null
null
null
$:.unshift File.expand_path(File.join(File.dirname(__FILE__),'..')) require 'assemblage' namespace :assemble do desc "Assemble all bundles for javascripts and stylesheeets" task :all => [ :js, :css ] task :js do targets = Assemblage::Packager.new.package_js.each do |target| puts "=> Assembled JavaScript at: #{target}" end File.open(File.join(Rails.root,'config/assembled.js.yml'), 'wb') {|f| f << YAML.dump(targets) } end task :css do targets = Assemblage::Packager.new.package_css.each do |target| puts "=> Assembled CSS at: #{target}" end File.open(File.join(Rails.root,'config/assembled.css.yml'), 'wb') {|f| f << YAML.dump(targets) } end desc "Given an assemblage configuration file, setup the correct directory strucutre and copy all css and js files into the each bundle folder" task :setup do if !File.exist?(Rails.root + "config/assemblage.rb") STDERR.puts "Unforuntately this command will only work if you have an config/assemblage.rb file." exit(1) end begin config = Assemblage::Config.new(Rails.root + "config/assemblage.rb") rescue Assemblage::Config::MissingFile => e original_filepath = e.filepath.gsub(e.bundle.to_s + '/','') if File.exist?(original_filepath) FileUtils.mkdir_p(File.dirname(e.filepath)) FileUtils.cp(original_filepath,e.filepath) puts "copy #{File.basename(original_filepath)} to #{e.bundle}" retry else raise "Unable to determine orgiinal file path of expected: #{e.filepath} in bundle: #{e.bundle}" end end end end
37.581395
144
0.672649
7611196dab6e77ab638fa6bf763c7c3875f86dcb
423
ps1
PowerShell
electron-cash.install/tools/chocolateyinstall.ps1
dampee/chocolatey-packages
4caf93732085ce71b5fb6be659af94436fb81db8
[ "MIT" ]
null
null
null
electron-cash.install/tools/chocolateyinstall.ps1
dampee/chocolatey-packages
4caf93732085ce71b5fb6be659af94436fb81db8
[ "MIT" ]
null
null
null
electron-cash.install/tools/chocolateyinstall.ps1
dampee/chocolatey-packages
4caf93732085ce71b5fb6be659af94436fb81db8
[ "MIT" ]
null
null
null
$ErrorActionPreference = 'Stop'; $packageArgs = @{ packageName = 'electron-cash' fileType = 'EXE' url = 'https://electroncash.org/downloads/4.2.4/win-linux/Electron-Cash-4.2.4-setup.exe' checksum = 'b4821e67a61e81943022546c9fb5ac107a80049b87cd0cee7a833a0af953793f' checksumType = 'sha256' silentArgs = '/S' validExitCodes= @(0) } Install-ChocolateyPackage @packageArgs
32.538462
101
0.678487
1b3de02fe6d9b332b40638face57b324d2aede55
1,226
lua
Lua
joypad/gui/input.lua
reueljonathan/love2d-virtual-joypad
bb4a448a5a1a632124b87f8e90df0f8681dcd43e
[ "MIT" ]
null
null
null
joypad/gui/input.lua
reueljonathan/love2d-virtual-joypad
bb4a448a5a1a632124b87f8e90df0f8681dcd43e
[ "MIT" ]
null
null
null
joypad/gui/input.lua
reueljonathan/love2d-virtual-joypad
bb4a448a5a1a632124b87f8e90df0f8681dcd43e
[ "MIT" ]
null
null
null
local Input = {} local lg = love.graphics function Input:new(x, y, width, height) local i = {} setmetatable(i, self) self.__index = self i.x = x i.y = y i.width = width i.height = height return i end function Input:resize(w, h) end function Input:keypressed(key) if self.focus and key == 'backspace' and self.text and self.text ~= '' then self.text = self.text:sub(1, self.text:len()-1) end end function Input:textinput(text) print(text) if self.focus then self.text = (self.text or '') .. text end end function Input:mousepressed(x, y, btn, isTouch) if self.focus then end end function Input:mousereleased(x, y) if not self.focus and x > self.x and x < self.x + self.width and y > self.y and y < self.y + self.height then self.focus = true love.keyboard.setTextInput(true) else self.focus = false end end function Input:draw() if self.focus then lg.setColor(255, 255, 255) else lg.setColor(100,100,100) end lg.rectangle('fill', self.x, self.y, self.width, self.height) lg.setColor(0,0,0) if self.text then lg.print(self.text, self.x + 5, self.y + 5) end end function Input:getText() return self.text end return Input
18.298507
77
0.658238
adbfe82cb82a6b853236ba62821aba1cfaf9732a
785
kt
Kotlin
compiler/testData/codegen/bytecodeText/conditions/noBoxingForPrimitiveEqBoxed.kt
Sathawale27/kotlin
9dd201aaf243cf9198cf129b22d3aa38fcff182c
[ "ECL-2.0", "Apache-2.0" ]
1
2020-04-16T10:47:38.000Z
2020-04-16T10:47:38.000Z
compiler/testData/codegen/bytecodeText/conditions/noBoxingForPrimitiveEqBoxed.kt
Sathawale27/kotlin
9dd201aaf243cf9198cf129b22d3aa38fcff182c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
compiler/testData/codegen/bytecodeText/conditions/noBoxingForPrimitiveEqBoxed.kt
Sathawale27/kotlin
9dd201aaf243cf9198cf129b22d3aa38fcff182c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// IGNORE_BACKEND: JVM_IR // TODO KT-36646 Don't box primitive values in equality comparison with nullable primitive values in JVM_IR fun testBoolean1(a: Boolean, b: Boolean?) = a == b fun testBoolean2(a: Boolean, b: Boolean?) = a != b fun testChar1(a: Char, b: Char?) = a == b fun testChar2(a: Char, b: Char?) = a != b fun testByte1(a: Byte, b: Byte?) = a == b fun testByte2(a: Byte, b: Byte?) = a != b fun testShort1(a: Short, b: Short?) = a == b fun testShort2(a: Short, b: Short?) = a != b fun testInt1(a: Int, b: Int?) = a == b fun testInt2(a: Int, b: Int?) = a != b fun testLong1(a: Long, b: Long?) = a == b fun testLong2(a: Long, b: Long?) = a != b // 2 charValue // 2 byteValue // 2 shortValue // 2 intValue // 2 longValue // 2 valueOf // 2 Boolean.valueOf // 2 areEqual
27.068966
107
0.631847
6be78730d1527a5a375e24af53c1e51c650cdd95
1,483
cpp
C++
cpp/source/example/AsioUdpClient.cpp
skydiveuas/skylync
73db7fe4593e262a1fc1a7b61c18190275abe723
[ "MIT" ]
1
2018-06-06T20:33:28.000Z
2018-06-06T20:33:28.000Z
cpp/source/example/AsioUdpClient.cpp
skydiveuas/skylync
73db7fe4593e262a1fc1a7b61c18190275abe723
[ "MIT" ]
null
null
null
cpp/source/example/AsioUdpClient.cpp
skydiveuas/skylync
73db7fe4593e262a1fc1a7b61c18190275abe723
[ "MIT" ]
1
2020-07-31T03:39:15.000Z
2020-07-31T03:39:15.000Z
#include "example/AsioUdpClient.hpp" #include <iostream> using namespace sl::example; AsioUdpClient::AsioUdpClient(sl::ICommInterface::Listener* _listener, asio::io_context& _ioContext): sl::ICommInterface(_listener), ioContext(_ioContext), socket(ioContext) { } void AsioUdpClient::connect(const std::string& host, const int port) { std::cout << "AsioUdpClient::connect" << std::endl; asio::ip::udp::resolver resolver(ioContext); asio::ip::udp::resolver::results_type endpoints = resolver.resolve(asio::ip::udp::v4(), host, std::to_string(port)); endpoint = *endpoints.begin(); socket.async_connect(endpoint, [this] (std::error_code ec) { if (!ec) { doRead(); listener.load()->onConnected(); } else { std::cout << "ERROR!!!!!!!!" << std::endl; } }); } void AsioUdpClient::disconnect() { std::cout << "AsioUdpClient::disconnect" << std::endl; listener.load()->onDisconnected(); } void AsioUdpClient::send(const DataPacket dataPacket) { std::cout << "AsioUdpClient::send" << std::endl; socket.async_send(asio::buffer(dataPacket.first, dataPacket.second), [this] (std::error_code ec, std::size_t /*length*/) { if (ec) { socket.close(); } }); } void AsioUdpClient::doRead() { std::cout << "AsioUdpClient::doRead - MISSING IMPLEMENTATION" << std::endl; }
25.568966
100
0.600135
cde9d8d3c09f05ec3abd5eed4f257b49a096b199
119,181
cs
C#
unity-sample-app/Assets/MoPub/Sample/Delight/Content/Views/UI/Editor/XmlEditor.cs
JunGroupProductions/mopub-unity-sdk
f479677f74964127f55016e83fbfc4916147c895
[ "Apache-2.0" ]
69
2017-07-22T14:38:21.000Z
2022-03-14T23:13:12.000Z
unity-sample-app/Assets/MoPub/Sample/Delight/Content/Views/UI/Editor/XmlEditor.cs
JunGroupProductions/mopub-unity-sdk
f479677f74964127f55016e83fbfc4916147c895
[ "Apache-2.0" ]
219
2017-07-10T23:20:13.000Z
2022-01-03T09:01:17.000Z
unity-sample-app/Assets/MoPub/Sample/Delight/Content/Views/UI/Editor/XmlEditor.cs
JunGroupProductions/mopub-unity-sdk
f479677f74964127f55016e83fbfc4916147c895
[ "Apache-2.0" ]
68
2017-09-13T09:19:02.000Z
2022-03-06T16:10:07.000Z
#if DELIGHT_MODULE_TEXTMESHPRO #region Using Statements using System; using System.Linq; using System.Collections.Generic; using System.Runtime.CompilerServices; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using TMPro; using System.Text; using System.Diagnostics; using System.Runtime.Remoting.Messaging; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using Delight.Editor.Parser; using UnityEditor; using JetBrains.Annotations; #endregion namespace Delight { /// <summary> /// Editor for changing view XML during runtime, part of the designer. /// </summary> public partial class XmlEditor { #region Fields public static float CharWidth = 9; // 10; // calculate by doing e.g. Label.TextMeshProUGUI.preferredWidth public static float LineHeight = 18.89f; //20.98f; // calculate by doing e.g. Label.TextMeshProUGUI.preferredHeight public static int SpacesPerTab = 2; public static float XmlTextMarginLeft = 20; public static float XmlTextMarginRight = 20; public static Color32 PropertyNameColor = new Color32(255, 72, 121, 255); // #ff4879 public static Color32 PropertyValueColor = new Color32(59, 155, 255, 255); // #3b9bff public static Color32 ViewNameColor = new Color32(74, 80, 78, 255); // #4a504e public static Color32 CommentColor = new Color32(0, 212, 0, 255); // #00d400 public static Color32 UndefinedColor = new Color32(255, 0, 0, 255); // #ff0000 public static Color32 TextSelectionColor = new Color32(224, 224, 224, 255); // #f4f4f4 public static Color32 ViewSelectionColor = new Color32(255, 250, 191, 255); // #fffabf public static Color32 CodeColor = new Color32(148, 0, 136, 255);// #940088 public static Color32 BindingColor = new Color32(226, 22, 255, 255); // #e217ff public static float KeyRepeatDelay = 0.30f; public static float KeyRepeatRate = 0.05f; public static float DoubleClickDelay = 0.5f; public static float CaretRepeatDelay = 0.5f; public static float CaretRepeatRate = 1.15f; public static float TooltipOffset = 0; public static float TooltipDelay = 0.30f; public static float MaxAutoCompleteBoxHeight = 150; public static Regex ViewNameStartRegex = new Regex(@"(?<=<)[A-Za-z0-9_]+(?=[\s>/])"); public static Regex QuoteContentRegex = new Regex(@"""(\\""|[^""])*"""); // "(\\"|[^"])*" public static int UndoHistoryLimit = 30; public List<int> SelectedLines = new List<int>(); private List<string> _lines = new List<string>(); private int _caretX; private int _caretY; private int _desiredCaretX; private int _previousClickCaretX; private int _previousClickCaretY; private XmlSyntaxElement _caretElement = XmlSyntaxElement.Undefined; private KeyCode _trackKeyDown = KeyCode.None; private float _caretDelayTimeElapsed; private float _caretRepeatTimeElapsed; private float _keyDownDelayTimeElapsed; private float _keyDownRepeatTimeElapsed; private float _mouseClickStart; private float _tooltipHoverTimeElapsed; private bool _tooltipDeactivatedUntilMouseMove; private Vector3 _previousMousePosition; private string _lastViewHover; private string _lastWordHover; private Mesh _selectionMesh = new Mesh(); private int _selectionOriginX; private int _selectionOriginY; private int _selectionTargetX; private int _selectionTargetY; private int _autoCompleteWordOriginX; private int _autoCompleteWordTargetX; private List<AutoCompleteOption> _autoCompleteOptions = new List<AutoCompleteOption>(); private XmlSyntaxElement _autoCompleteType = XmlSyntaxElement.Undefined; private string _lastWordAtCaret; private bool _autoCompleteActive; private bool _hasSelection; private CanvasRenderer _caretCanvasRenderer; private Vector3 _mouseDownPosition; private bool _clickedInsideEditor; private List<UIView> _selectedViews = new List<UIView>(); private List<XmlEditorUndoInfo> _undoInfo = new List<XmlEditorUndoInfo>(); private int _undoCount = 0; private List<int> _addedLines = new List<int>(); private List<int> _deletedLines = new List<int>(); #endregion #region Methods /// <summary> /// Called when a property has been changed. /// </summary> public override void OnChanged(string property) { base.OnChanged(property); switch (property) { case nameof(XmlText): ClearEditor(); if (XmlText != null) { _lines = new List<string>(XmlText.GetLines()); } AddUndoInfo(true); OnEditorChanged(); break; } } /// <summary> /// Called after the view has been initialized. /// </summary> public override void AfterInitialize() { base.AfterInitialize(); AutoCompleteOptions = new AutoCompleteOptionData(); } /// <summary> /// Called every frame and handles keyboard and mouse input. /// </summary> public override void Update() { if (IsFocused) { // make caret blink _caretDelayTimeElapsed += Time.deltaTime; if (_caretDelayTimeElapsed > CaretRepeatDelay) { _caretRepeatTimeElapsed += Time.deltaTime; Caret.IsActive = _caretRepeatTimeElapsed % CaretRepeatRate > CaretRepeatRate / 2; } } else { // hide autocomplete box DeactivateAutoComplete(); } // update XML editor left margin based on scroll position so the line numbers follow along with scrolling var scrollableContentOffset = ScrollableRegion.GetContentOffset(); XmlEditLeftMargin.Offset.Left = -scrollableContentOffset.x; bool ctrlDown = (Input.GetKey(KeyCode.LeftApple) || Input.GetKey(KeyCode.RightApple) || Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)) && !Input.GetKey(KeyCode.AltGr); bool scrollEngaged = ctrlDown || Input.GetMouseButton(2); bool mouseButtonDown = false; bool shiftDown = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); ScrollableRegion.ScrollEnabled = scrollEngaged; bool containsMouse = ContainsMouse(Input.mousePosition); // handle mouse clicks if (Input.GetMouseButtonDown(0)) { if (!containsMouse) { // user has clicked outside the editor - deselect and deactivate caret IsFocused = false; _hasSelection = false; Caret.IsActive = false; _clickedInsideEditor = false; DeactivateAutoComplete(); GenerateTextHighlightMeshes(); } else { IsFocused = true; _clickedInsideEditor = true; mouseButtonDown = true; _mouseDownPosition = Input.mousePosition; if (AutoCompleteBox.IsVisible) { if (!AutoCompleteBox.ContainsMouse(Input.mousePosition) || scrollEngaged || shiftDown) { // if clicked outside the autocomplete box, hide it DeactivateAutoComplete(); } else { // clicked inside box return; } } if (!scrollEngaged && !shiftDown) { // regular mouse click _hasSelection = false; GetMouseCaretPosition(out _caretX, out _caretY); _desiredCaretX = _caretX; _selectionOriginX = _caretX; _selectionOriginY = _caretY; // handle double-clicks float timeStamp = Time.unscaledTime; if (_mouseClickStart + DoubleClickDelay > timeStamp) { if (_previousClickCaretX == _caretX && _previousClickCaretY == _caretY) { // if double-click at the same spot, select the word at caret SelectWordAtCaret(); } } else { _mouseClickStart = timeStamp; } _previousClickCaretX = _caretX; _previousClickCaretY = _caretY; ActivateCaret(); UpdateTextAndCaret(false); } else if (ctrlDown && !shiftDown) { // handle selection logic GetMouseCaretPosition(out var _, out var clickY); // select view at line SelectViewAtLine?.Invoke(this, GetLineInLastParsedXml(clickY)); } } } // handle mouse drags if (((mouseButtonDown && shiftDown) || (Input.GetMouseButton(0) && _clickedInsideEditor && !scrollEngaged && !mouseButtonDown)) && !AutoCompleteBox.IsVisible) { // if we've dragged beyond a certain threshold update selection (or if we shift+mouse click) Vector3 delta = _mouseDownPosition - Input.mousePosition; if (Mathf.Abs(delta.x) > 3 || Mathf.Abs(delta.y) > 3 || (mouseButtonDown && shiftDown)) { // handle dragging selection GetMouseCaretPosition(out _selectionTargetX, out _selectionTargetY); _hasSelection = _selectionTargetX != _selectionOriginX || _selectionTargetY != _selectionOriginY; if (_hasSelection) { _caretX = _selectionTargetX; _caretY = _selectionTargetY; ActivateCaret(); UpdateTextAndCaret(false); } } } if (_tooltipDeactivatedUntilMouseMove) { // see if mouse has moved beyond threshold Vector3 delta = _previousMousePosition - Input.mousePosition; if (Mathf.Abs(delta.x) > 3 || Mathf.Abs(delta.y) > 3) { _tooltipDeactivatedUntilMouseMove = false; } } // handle tooltip hovers if (containsMouse) { GetMouseCaretPosition(out var caretX, out var caretY); var viewAtCaret = GetViewAtCaret(caretY); var wordAtCaret = GetWordAtCaret(caretX, caretY, out var originX, out var targetX); if (viewAtCaret == _lastViewHover && wordAtCaret == _lastWordHover) { _tooltipHoverTimeElapsed += Time.deltaTime; } else { DeactivateTooltip(); } _lastViewHover = viewAtCaret; _lastWordHover = wordAtCaret; if (_tooltipHoverTimeElapsed >= TooltipDelay) { if (String.IsNullOrEmpty(viewAtCaret) || String.IsNullOrEmpty(wordAtCaret)) { DeactivateTooltip(); } else if (wordAtCaret == viewAtCaret) { // hovering over view var comment = GetElementDoc(viewAtCaret); if (!String.IsNullOrWhiteSpace(comment)) { ActivateTooltip(comment); } else { DeactivateTooltip(); } } else { // hovering over a word inside view tag // see if word has "=" to the right then it's a property name var comment = GetElementDoc(viewAtCaret, wordAtCaret); if (!String.IsNullOrWhiteSpace(comment)) { ActivateTooltip(comment); } else { DeactivateTooltip(); } } if (TooltipBox.IsVisible) { // position tooltip box if (TooltipBox.OffsetFromParent == null) TooltipBox.OffsetFromParent = new ElementMargin(); TooltipBox.OffsetFromParent.Left = CharWidth * originX; TooltipBox.OffsetFromParent.Bottom = LineHeight * (_lines.Count - (caretY - 2)) + TooltipOffset; } } } else { DeactivateTooltip(); } // handle keyboard input if (Input.anyKey && IsFocused) { if (ctrlDown) { // handle control commands HandleControlInput(); } else { // handle regular input HandleKeyInput(); } } // F1 opens help section if (Input.GetKeyDown(KeyCode.F1)) { var viewName = GetViewAtCaret(); if (!string.IsNullOrWhiteSpace(viewName)) { Application.OpenURL(String.Format("https://delight-dev.github.io/Api/Views/{0}.html", viewName)); } } _previousMousePosition = Input.mousePosition; } /// <summary> /// Gets line in last parsed XML that corresponds to the line in the edited XML. /// </summary> public int GetLineInEditedXml(int lineInLastParsedXml) { int lineInEditedXml = lineInLastParsedXml; var sortedAddedLines = _addedLines.OrderBy(x => x).ToList(); var sortedDeletedLines = _deletedLines.OrderBy(x => x).ToList(); int maxCount = Math.Max(sortedAddedLines.Count, sortedDeletedLines.Count); for (int i = 0; i < maxCount; ++i) { if (i < sortedAddedLines.Count) { // if added line is on edited line or before, we add one to it if (sortedAddedLines[i] <= lineInEditedXml) { ++lineInEditedXml; } } if (i < sortedDeletedLines.Count) { // if deleted line is on edited line or before, we decrement it if (sortedDeletedLines[i] <= lineInEditedXml) { --lineInEditedXml; } } } //UnityEngine.Debug.Log(String.Format("GetLineInEditedXml({0}) -> {1}", lineInLastParsedXml+1, lineInEditedXml+1)); return lineInEditedXml; } /// <summary> /// Gets line in last parsed XML that corresponds to the line in the edited XML. /// </summary> public int GetLineInLastParsedXml(int lineInEditedXml) { int lineInLastParsedXml = lineInEditedXml - _addedLines.Count(x => x < lineInEditedXml) + _deletedLines.Count(x => x <= lineInEditedXml); //UnityEngine.Debug.Log(String.Format("GetLineInLastParsedXml({0}) = {1}", lineInEditedXml+1, lineInLastParsedXml+1)); return lineInLastParsedXml; } /// <summary> /// Called when (re-)parse of the XML is successful. Clears selection. /// </summary> public void OnParseSuccessful() { _addedLines.Clear(); _deletedLines.Clear(); } /// <summary> /// Called when a new line is added. /// </summary> public void OnLineAdded(int line) { int addedLine = line; for (int i = 0; i < _addedLines.Count; ++i) { if (_addedLines[i] >= addedLine) { _addedLines[i] = _addedLines[i] + 1; } } for (int i = 0; i < _deletedLines.Count; ++i) { if (_deletedLines[i] > addedLine) { _deletedLines[i] = _deletedLines[i] + 1; } } // if addded line is an deleted line - clear both int deletedLineIndex = _deletedLines.IndexOf(addedLine); if (deletedLineIndex >= 0) { _deletedLines.RemoveAt(deletedLineIndex); } else { _addedLines.Add(addedLine); } } /// <summary> /// Called when a new line is deleted. /// </summary> public void OnLineDeleted(int line) { int deletedLine = line; for (int i = 0; i < _deletedLines.Count; ++i) { if (_deletedLines[i] >= deletedLine) { _deletedLines[i] = _deletedLines[i] - 1; } } for (int i = 0; i < _addedLines.Count; ++i) { if (_addedLines[i] > deletedLine) { _addedLines[i] = _addedLines[i] - 1; } } // if deleted line is an added line - clear both int addedLineIndex = _addedLines.IndexOf(deletedLine); if (addedLineIndex >= 0) { _addedLines.RemoveAt(addedLineIndex); } else { _deletedLines.Add(deletedLine); } } /// <summary> /// Highlight selected views in the editor. /// </summary> public void SetSelectedViews(List<UIView> selectedViews, bool scrollToLastSelectedView = true) { _selectedViews = selectedViews; GenerateTextHighlightMeshes(scrollToLastSelectedView); } /// <summary> /// Activates tooltip. /// </summary> private void ActivateTooltip(string tooltipText) { if (_tooltipDeactivatedUntilMouseMove) return; TooltipLabel.Text = tooltipText; TooltipBox.IsVisible = true; } /// <summary> /// Deactivates the tooltip box. /// </summary> private void DeactivateTooltip(bool deactivateUntilMouseMove = false) { TooltipBox.IsVisible = false; _tooltipHoverTimeElapsed = 0; _lastViewHover = null; _lastWordHover = null; if (deactivateUntilMouseMove) { _tooltipDeactivatedUntilMouseMove = true; } _previousMousePosition = Input.mousePosition; } /// <summary> /// Gets XML text from editor. /// </summary> public string GetXmlText() { return XmlTextLabel.TextMeshProUGUI.text; } /// <summary> /// Selects the word at the current caret position. /// </summary> private void SelectWordAtCaret() { if (_lines[_caretY].Length <= 0) return; _selectionOriginX = _caretX - 1; _selectionTargetX = _caretX; _selectionOriginY = _caretY; _selectionTargetY = _caretY; if (_selectionOriginX < 0) _selectionOriginX = 0; // choose selection method Func<char, bool> selectChar = c => Char.IsLetterOrDigit(c); // select letters and digits by default char leftChar = _lines[_caretY][_selectionOriginX]; char rightChar = _selectionTargetX < _lines[_caretY].Length ? _lines[_caretY][_selectionTargetX] : leftChar; if ((Char.IsWhiteSpace(leftChar) && Char.IsWhiteSpace(rightChar)) || (Char.IsWhiteSpace(leftChar) && !Char.IsLetterOrDigit(rightChar)) || (!Char.IsLetterOrDigit(leftChar) && Char.IsWhiteSpace(rightChar))) { // if surrounded by whitespace, select whitespace selectChar = c => Char.IsWhiteSpace(c); } else if (!Char.IsLetterOrDigit(leftChar) && !Char.IsLetterOrDigit(rightChar)) { // if surrounded by special characters, select special characters selectChar = c => !Char.IsLetterOrDigit(c); } while (_selectionTargetX < _lines[_caretY].Length) { if (!selectChar(_lines[_caretY][_selectionTargetX])) { break; } ++_selectionTargetX; } while (_selectionOriginX >= 0) { if (!selectChar(_lines[_caretY][_selectionOriginX])) { _selectionOriginX = _selectionOriginX == _lines[_caretY].Length - 1 ? _selectionOriginX : _selectionOriginX + 1; break; } --_selectionOriginX; } if (_selectionOriginX < 0) _selectionOriginX = 0; _hasSelection = _selectionTargetX != _selectionOriginX || _selectionTargetY != _selectionOriginY; if (_hasSelection) { _desiredCaretX = _selectionTargetX; _caretX = _selectionTargetX; } } /// <summary> /// Gets mouse caret position. /// </summary> private void GetMouseCaretPosition(out int caretX, out int caretY) { // set text indicator UnityEngine.Canvas canvas = LayoutRoot.Canvas; Camera worldCamera = canvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : canvas.worldCamera; RectTransformUtility.ScreenPointToLocalPointInRectangle(XmlTextRegion.RectTransform, Input.mousePosition, worldCamera, out var localMousePosition); localMousePosition.x = localMousePosition.x + XmlTextRegion.ActualWidth / 2; localMousePosition.y = localMousePosition.y - XmlTextRegion.ActualHeight / 2; int lineIndex = Mathf.FloorToInt(Mathf.Abs(localMousePosition.y) / LineHeight); int charIndex = Mathf.RoundToInt(localMousePosition.x / CharWidth); if (charIndex < 0) { charIndex = 0; } if (lineIndex < 0) { lineIndex = 0; } caretY = lineIndex < _lines.Count ? lineIndex : _lines.Count - 1; caretX = charIndex < _lines[caretY].Length ? charIndex : _lines[caretY].Length; } /// <summary> /// Handles keyboard input. /// </summary> private void HandleKeyInput(string inputString = null, bool ignoreCheckKeyDown = false) { if (inputString == null) { inputString = Input.inputString; } if (Application.platform == RuntimePlatform.OSXEditor) { if (inputString.Length > 0) { inputString = inputString.Substring(0, 1); if (inputString == "\r") { inputString = (char)KeyCode.Return + ""; } } } bool textChanged = false; bool needReparse = false; // key has been pressed in previous frame if (_trackKeyDown != KeyCode.None) { if (Input.GetKey(_trackKeyDown)) { inputString = ""; _keyDownDelayTimeElapsed += Time.deltaTime; if (_keyDownDelayTimeElapsed > KeyRepeatDelay) { _keyDownRepeatTimeElapsed += Time.deltaTime; } if (_keyDownRepeatTimeElapsed > KeyRepeatRate) { _keyDownRepeatTimeElapsed = 0; inputString = (char)_trackKeyDown + ""; } } else { _trackKeyDown = KeyCode.None; _keyDownDelayTimeElapsed = 0; _keyDownRepeatTimeElapsed = 0; } } if (!ignoreCheckKeyDown) { // check if a key has been pressed down, these are the keys that don't show up in Input.inputString if (Input.GetKeyDown(KeyCode.LeftArrow)) { inputString = (char)KeyCode.LeftArrow + ""; _trackKeyDown = KeyCode.LeftArrow; _keyDownDelayTimeElapsed = 0; } else if (Input.GetKeyDown(KeyCode.RightArrow)) { inputString = (char)KeyCode.RightArrow + ""; _trackKeyDown = KeyCode.RightArrow; _keyDownDelayTimeElapsed = 0; } else if (Input.GetKeyDown(KeyCode.UpArrow)) { inputString = (char)KeyCode.UpArrow + ""; _trackKeyDown = KeyCode.UpArrow; _keyDownDelayTimeElapsed = 0; } else if (Input.GetKeyDown(KeyCode.DownArrow)) { inputString = (char)KeyCode.DownArrow + ""; _trackKeyDown = KeyCode.DownArrow; _keyDownDelayTimeElapsed = 0; } else if (Input.GetKeyDown(KeyCode.Tab)) { inputString = (char)KeyCode.Tab + ""; _trackKeyDown = KeyCode.Tab; _keyDownDelayTimeElapsed = 0; } else if (Input.GetKeyDown(KeyCode.Delete)) { inputString = (char)KeyCode.Delete + ""; _trackKeyDown = KeyCode.Delete; _keyDownDelayTimeElapsed = 0; } else if (Input.GetKeyDown(KeyCode.Home)) { inputString = (char)KeyCode.Home + ""; _trackKeyDown = KeyCode.Home; _keyDownDelayTimeElapsed = 0; } else if (Input.GetKeyDown(KeyCode.End)) { inputString = (char)KeyCode.End + ""; _trackKeyDown = KeyCode.End; _keyDownDelayTimeElapsed = 0; } else if (Input.GetKeyDown(KeyCode.PageDown)) { inputString = (char)KeyCode.PageDown + ""; _trackKeyDown = KeyCode.PageDown; _keyDownDelayTimeElapsed = 0; } else if (Input.GetKeyDown(KeyCode.PageUp)) { inputString = (char)KeyCode.PageUp + ""; _trackKeyDown = KeyCode.PageUp; _keyDownDelayTimeElapsed = 0; } else if (Input.GetKeyDown(KeyCode.Escape)) { inputString = (char)KeyCode.Escape + ""; } } if (inputString.Length <= 0) return; var shiftDown = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); bool updateDesiredCaretX = true; bool activateAutoComplete = _autoCompleteActive; KeyCode lastKeyCode; for (int i = 0; i < inputString.Length; ++i) { char c = inputString[i]; if (c == 10) // bugfix where return on some devices has keycode 10 not recognized by unity { c = (char)13; } KeyCode keyCode = (KeyCode)c; lastKeyCode = keyCode; //Debug.Log((int)c); switch (keyCode) { case KeyCode.Space: case KeyCode.Less: if (IsReadOnly) break; textChanged = true; if (_hasSelection) { DeleteSelection(); needReparse = true; } _lines[_caretY] = _lines[_caretY].InsertOrAdd(_caretX, c.ToString()); ++_caretX; DeactivateAutoComplete(); activateAutoComplete = true; if (IsEditingPropertyValue()) { needReparse = true; } break; case KeyCode.KeypadEnter: case KeyCode.Return: if (IsReadOnly) break; textChanged = true; // if autocomplete active, complete selected suggestion and break if (AutoCompleteBox.IsVisible) { activateAutoComplete = FinishAutoComplete(); needReparse = true; break; } if (_hasSelection) { DeleteSelection(); needReparse = true; } string viewName = string.Empty; int indentLevel = 0; bool hasGottenIndentLevel = false; if (_caretElement == XmlSyntaxElement.PropertyName || _caretElement == XmlSyntaxElement.ViewName) { if (_caretX >= _lines[_caretY].Length && _lines[_caretY].Length > 0) { var trimmedLine = _lines[_caretY].TrimEnd(); if (trimmedLine.EndsWith(".")) { // if we end view declaration with dot and press enter add "/>" to close it _lines[_caretY] = trimmedLine.Substring(0, trimmedLine.Length - 1).TrimEnd() + " />"; _caretX = _lines[_caretY].Length; _caretElement = XmlSyntaxElement.Undefined; needReparse = true; break; } else if (trimmedLine.EndsWith(",")) { // if we end view declaration with comma and press enter add ">" to close it _lines[_caretY] = trimmedLine.Substring(0, trimmedLine.Length - 1).TrimEnd() + ">"; _caretX = _lines[_caretY].Length; _caretElement = XmlSyntaxElement.Undefined; indentLevel = GetIndentLevelOfNextLine(out viewName); hasGottenIndentLevel = true; int currentIdentLevel = indentLevel - SpacesPerTab; if (currentIdentLevel < 0) currentIdentLevel = 0; var spacesStr = new string(' ', currentIdentLevel); _lines.InsertOrAdd(_caretY + 1, string.Format("{0}</{1}>", spacesStr, viewName)); OnLineAdded(_caretY + 1); needReparse = true; } } } // split the current line at caret position and add a new line with the new content if (!hasGottenIndentLevel) { indentLevel = GetIndentLevelOfNextLine(out viewName); } if (_caretX <= 0) { _lines.Insert(_caretY, string.Empty); OnLineAdded(_caretY); } else if (_caretX >= _lines[_caretY].Length) { _lines.InsertOrAdd(_caretY + 1, string.Empty); OnLineAdded(_caretY + 1); _lines[_caretY + 1] += new string(' ', indentLevel); _caretX = indentLevel; } else { var rightStr = _lines[_caretY].Substring(_caretX); var leftStr = _lines[_caretY].Substring(0, _caretX); _lines[_caretY] = leftStr; _lines.InsertOrAdd(_caretY + 1, rightStr.TrimStart()); OnLineAdded(String.IsNullOrWhiteSpace(leftStr) ? _caretY : _caretY + 1); // if left hand side is just white-space we've added a line on caretY _lines[_caretY + 1] = new string(' ', indentLevel) + _lines[_caretY + 1]; _caretX = indentLevel; } ++_caretY; break; case KeyCode.Backspace: // backspace if (IsReadOnly) break; textChanged = true; if (_hasSelection) { DeleteSelection(); needReparse = true; break; // do nothing else } --_caretX; if (_caretX < 0) { // we're at the beggining of the line hitting backspace --_caretY; if (_caretY < 0) { // we're at the top-left in the input field, so do nothing _caretY = 0; _caretX = 0; } else { // append line to the line we've backspaced to var newCaretX = _lines[_caretY].Length; _lines[_caretY] += _lines[_caretY + 1]; _caretX = newCaretX; _lines.RemoveAt(_caretY + 1); OnLineDeleted(_caretY + 1); } } else { _lines[_caretY] = _lines[_caretY].Remove(_caretX, 1); } if (IsEditingPropertyValue() || IsEditingViewNameThatExist()) { needReparse = true; } break; case KeyCode.Tab: if (IsReadOnly) break; textChanged = true; if (AutoCompleteBox.IsVisible) { activateAutoComplete = FinishAutoComplete(); needReparse = true; break; } if (_hasSelection) { DeleteSelection(); needReparse = true; } _lines[_caretY] = _lines[_caretY].InsertOrAdd(_caretX, new string(' ', SpacesPerTab)); _caretX += SpacesPerTab; if (IsEditingPropertyValue()) { needReparse = true; } break; case KeyCode.Delete: if (IsReadOnly) break; textChanged = true; if (_hasSelection) { DeleteSelection(); needReparse = true; break; // do nothing else } if (_caretX < _lines[_caretY].Length) { _lines[_caretY] = _lines[_caretY].Remove(_caretX, 1); } else { // we're at the end of the line hitting delete, are there more lines below? if (_caretY < _lines.Count - 1) { // yes. append below line to the current line OnLineDeleted(String.IsNullOrWhiteSpace(_lines[_caretY]) ? _caretY : _caretY + 1); _lines[_caretY] += _lines[_caretY + 1].TrimStart(); _lines.RemoveAt(_caretY + 1); } } if (IsEditingPropertyValue() || IsEditingViewNameThatExist()) { needReparse = true; } break; case KeyCode.LeftArrow: // if we move over non-alphanumeric character deactivate auto-complete int walkedOverCaret = _caretX - 1; if (walkedOverCaret < _lines[_caretY].Length && walkedOverCaret >= 0) { char walkedOverChar = _lines[_caretY][walkedOverCaret]; if (!Char.IsLetterOrDigit(walkedOverChar)) { activateAutoComplete = false; } } else { activateAutoComplete = false; } // handle selection if (shiftDown) { if (!_hasSelection) { // set origin of selection _selectionOriginX = _caretX; _selectionOriginY = _caretY; _selectionTargetX = _selectionOriginX; _selectionTargetY = _selectionOriginY; } } --_caretX; if (_caretX < 0) { --_caretY; if (_caretY < 0) { // we're at the top-left in the input field, so do nothing _caretY = 0; _caretX = 0; } else { // move to end of previous line _caretX = _lines[_caretY].Length; } } // handle selection if (shiftDown) { _selectionTargetX = _caretX; _selectionTargetY = _caretY; _hasSelection = _selectionTargetX != _selectionOriginX || _selectionTargetY != _selectionOriginY; } else { _hasSelection = false; } break; case KeyCode.RightArrow: // if we move over non-alphanumeric character deactivate auto-complete int rightWalkedOverCaret = _caretX; if (rightWalkedOverCaret < _lines[_caretY].Length && rightWalkedOverCaret >= 0) { char walkedOverChar = _lines[_caretY][rightWalkedOverCaret]; if (!Char.IsLetterOrDigit(walkedOverChar)) { activateAutoComplete = false; } } else { activateAutoComplete = false; } // handle selection if (shiftDown) { if (!_hasSelection) { // set origin of selection _selectionOriginX = _caretX; _selectionOriginY = _caretY; _selectionTargetX = _selectionOriginX; _selectionTargetY = _selectionOriginY; } } if (_caretX < _lines[_caretY].Length) { ++_caretX; } else if (_caretY < _lines.Count - 1) { // move to beginning of next line _caretX = 0; ++_caretY; } // handle selection if (shiftDown) { _selectionTargetX = _caretX; _selectionTargetY = _caretY; _hasSelection = _selectionTargetX != _selectionOriginX || _selectionTargetY != _selectionOriginY; } else { _hasSelection = false; } break; case KeyCode.UpArrow: // handle selection if (shiftDown) { activateAutoComplete = false; if (!_hasSelection) { // set origin of selection _selectionOriginX = _caretX; _selectionOriginY = _caretY; _selectionTargetX = _selectionOriginX; _selectionTargetY = _selectionOriginY; } } else if (AutoCompleteBox.IsVisible) { // if auto complete open, scroll in list and break AutoCompleteOptionsList.SelectPrevious(); break; } updateDesiredCaretX = false; if (_caretY > 0) { --_caretY; _caretX = _desiredCaretX >= _lines[_caretY].Length ? _lines[_caretY].Length : _desiredCaretX; } // handle selection if (shiftDown) { _selectionTargetX = _caretX; _selectionTargetY = _caretY; _hasSelection = _selectionTargetX != _selectionOriginX || _selectionTargetY != _selectionOriginY; } else { _hasSelection = false; } break; case KeyCode.DownArrow: // handle selection if (shiftDown) { activateAutoComplete = false; if (!_hasSelection) { // set origin of selection _selectionOriginX = _caretX; _selectionOriginY = _caretY; _selectionTargetX = _selectionOriginX; _selectionTargetY = _selectionOriginY; } } else if (AutoCompleteBox.IsVisible) { // if auto complete open, scroll in list and break AutoCompleteOptionsList.SelectNext(); break; } updateDesiredCaretX = false; if (_caretY < _lines.Count - 1) { ++_caretY; _caretX = _desiredCaretX >= _lines[_caretY].Length ? _lines[_caretY].Length : _desiredCaretX; } // handle selection if (shiftDown) { _selectionTargetX = _caretX; _selectionTargetY = _caretY; _hasSelection = _selectionTargetX != _selectionOriginX || _selectionTargetY != _selectionOriginY; } else { _hasSelection = false; } break; case KeyCode.Home: // handle selection if (shiftDown) { if (!_hasSelection) { // set origin of selection _selectionOriginX = _caretX; _selectionOriginY = _caretY; _selectionTargetX = _selectionOriginX; _selectionTargetY = _selectionOriginY; } } var nonSpaceIndex = _lines[_caretY].IndexOf(x => x != ' '); if (nonSpaceIndex < 0) nonSpaceIndex = 0; _caretX = _caretX == nonSpaceIndex ? 0 : nonSpaceIndex; // handle selection if (shiftDown) { _selectionTargetX = _caretX; _selectionTargetY = _caretY; _hasSelection = _selectionTargetX != _selectionOriginX || _selectionTargetY != _selectionOriginY; } else { _hasSelection = false; } break; case KeyCode.End: // handle selection if (shiftDown) { if (!_hasSelection) { // set origin of selection _selectionOriginX = _caretX; _selectionOriginY = _caretY; _selectionTargetX = _selectionOriginX; _selectionTargetY = _selectionOriginY; } } _caretX = _lines[_caretY].Length; // handle selection if (shiftDown) { _selectionTargetX = _caretX; _selectionTargetY = _caretY; _hasSelection = _selectionTargetX != _selectionOriginX || _selectionTargetY != _selectionOriginY; } else { _hasSelection = false; } break; case KeyCode.KeypadEquals: case KeyCode.Equals: if (IsReadOnly) break; textChanged = true; if (_hasSelection) { DeleteSelection(); } // add ="" if caret isn't in a property value or comment if (_caretElement != XmlSyntaxElement.PropertyValue && _caretElement != XmlSyntaxElement.EndPropertyValue && _caretElement != XmlSyntaxElement.BeginPropertyValue && _caretElement != XmlSyntaxElement.Comment && _caretElement != XmlSyntaxElement.EndComment) { _lines[_caretY] = _lines[_caretY].InsertOrAdd(_caretX, c + "\"\""); _caretX = _caretX + 2; DeactivateAutoComplete(); // re-trigger auto-complete activateAutoComplete = true; } else { _lines[_caretY] = _lines[_caretY].InsertOrAdd(_caretX, c.ToString()); ++_caretX; } activateAutoComplete = true; break; case KeyCode.PageDown: // handle selection if (shiftDown) { activateAutoComplete = false; if (!_hasSelection) { // set origin of selection _selectionOriginX = _caretX; _selectionOriginY = _caretY; _selectionTargetX = _selectionOriginX; _selectionTargetY = _selectionOriginY; } } else if (AutoCompleteBox.IsVisible) { // if auto complete open, scroll in list and break AutoCompleteOptionsList.ScrollPageDown(true); break; } updateDesiredCaretX = false; int jumpLines = Mathf.FloorToInt(ScrollableRegion.ViewportHeight / LineHeight); _caretY += jumpLines; if (_caretY > _lines.Count - 1) { _caretY = _lines.Count - 1; _caretX = _desiredCaretX >= _lines[_caretY].Length ? _lines[_caretY].Length : _desiredCaretX; } // handle selection if (shiftDown) { _selectionTargetX = _caretX; _selectionTargetY = _caretY; _hasSelection = _selectionTargetX != _selectionOriginX || _selectionTargetY != _selectionOriginY; } else { _hasSelection = false; } break; case KeyCode.Escape: activateAutoComplete = false; break; case KeyCode.PageUp: // handle selection if (shiftDown) { activateAutoComplete = false; if (!_hasSelection) { // set origin of selection _selectionOriginX = _caretX; _selectionOriginY = _caretY; _selectionTargetX = _selectionOriginX; _selectionTargetY = _selectionOriginY; } } else if (AutoCompleteBox.IsVisible) { // if auto complete open, scroll in list and break AutoCompleteOptionsList.ScrollPageUp(true); break; } updateDesiredCaretX = false; int jumpLinesUp = Mathf.FloorToInt(ScrollableRegion.ViewportHeight / LineHeight); _caretY -= jumpLinesUp; if (_caretY < 0) { _caretY = 0; _caretX = _desiredCaretX >= _lines[_caretY].Length ? _lines[_caretY].Length : _desiredCaretX; } // handle selection if (shiftDown) { _selectionTargetX = _caretX; _selectionTargetY = _caretY; _hasSelection = _selectionTargetX != _selectionOriginX || _selectionTargetY != _selectionOriginY; } else { _hasSelection = false; } break; default: if (IsReadOnly) break; textChanged = true; if (_hasSelection) { DeleteSelection(); needReparse = true; } string str = c.ToString(); if (_caretElement == XmlSyntaxElement.Undefined) { // if previous character isn't a "<" add it int previousChar = _caretX - 1; if (previousChar < 0 || previousChar >= _lines[_caretY].Length || _lines[_caretY][previousChar] != '<') { str = "<" + str; } activateAutoComplete = true; } if (activateAutoComplete && (c == ',' || c == '.')) { // terminate autocomplete when typing certain special characters to end the tag activateAutoComplete = false; } _lines[_caretY] = _lines[_caretY].InsertOrAdd(_caretX, str); _caretX += str.Length; if (IsEditingPropertyValue() || IsEditingViewNameThatExist()) { needReparse = true; } break; } if (updateDesiredCaretX) { // update desired caret unless up/down arrows have been pressed _desiredCaretX = _caretX; } } OnTextOrCaretChanged(textChanged, activateAutoComplete, needReparse, false); } /// <summary> /// Returns boolean indicating if caret position implies user is editing a property value. /// </summary> private bool IsEditingPropertyValue() { return _caretElement == XmlSyntaxElement.PropertyValue || _caretElement == XmlSyntaxElement.EndPropertyValue; } /// <summary> /// Returns boolean indicating if caret position implies user is editing a view name. /// </summary> private bool IsEditingViewName() { return _caretElement == XmlSyntaxElement.ViewName; } /// <summary> /// Returns boolean indicating if caret position implies user is editing a view name. /// </summary> private bool IsEditingViewNameThatExist() { if (!IsEditingViewName()) return false; string wordAtCaret = GetWordAtCaret(); return DesignerViews.Any(x => x.Name == wordAtCaret); } /// <summary> /// Called when text or caret has changed. /// </summary> private void OnTextOrCaretChanged(bool textChanged, bool activateAutoComplete, bool needReparse, bool skipAddUndoInfo) { if (textChanged && !skipAddUndoInfo) { AddUndoInfo(needReparse); } DeactivateTooltip(true); ActivateCaret(); OnEditorChanged(); // handle autocomplete if (activateAutoComplete) { ActivateAutoComplete(); } else { DeactivateAutoComplete(); } // check if caret is outside viewport and update scroll position float viewportWidth = ScrollableRegion.ViewportWidth; float viewportHeight = ScrollableRegion.ViewportHeight; var contentOffset = ScrollableRegion.GetContentOffset(); contentOffset.x = Math.Abs(contentOffset.x); contentOffset.y = Math.Abs(contentOffset.y); float caretOffsetX = _caretX * CharWidth + XmlEditLeftMargin.Width; float caretOffsetY = _caretY * LineHeight; float scrollOffsetX = -1; float scrollOffsetY = -1; if ((caretOffsetX + CharWidth + ScrollableRegion.VerticalScrollbar.ActualWidth) > (contentOffset.x + viewportWidth)) { scrollOffsetX = (caretOffsetX + CharWidth + ScrollableRegion.VerticalScrollbar.ActualWidth) - viewportWidth; } else if (caretOffsetX - XmlEditLeftMargin.Width < contentOffset.x) { scrollOffsetX = caretOffsetX - XmlEditLeftMargin.Width; } if ((caretOffsetY + LineHeight + ScrollableRegion.HorizontalScrollbar.ActualHeight) > (contentOffset.y + viewportHeight)) { scrollOffsetY = (caretOffsetY + LineHeight + ScrollableRegion.HorizontalScrollbar.ActualHeight) - viewportHeight; } else if (caretOffsetY < contentOffset.y) { scrollOffsetY = caretOffsetY; } if (scrollOffsetX >= 0 || scrollOffsetY >= 0) { if (scrollOffsetX >= 0 && scrollOffsetY >= 0) ScrollableRegion.SetAbsoluteScrollPosition(scrollOffsetX, scrollOffsetY); else if (scrollOffsetX >= 0) ScrollableRegion.SetHorizontalAbsoluteScrollPosition(scrollOffsetX); else ScrollableRegion.SetVerticalAbsoluteScrollPosition(scrollOffsetY); } if (textChanged && !IsReadOnly) { // trigger edit invent unless only arrow keys has been pressed Edit.Invoke(this, needReparse); } } /// <summary> /// Gets the selected text. /// </summary> private string GetSelection() { string selection = string.Empty; if (!_hasSelection) return selection; int startLine = Math.Min(_selectionOriginY, _selectionTargetY); int endLine = Math.Max(_selectionOriginY, _selectionTargetY); int startChar = startLine == endLine ? Math.Min(_selectionOriginX, _selectionTargetX) : _selectionOriginY > _selectionTargetY ? _selectionTargetX : _selectionOriginX; int endChar = startLine == endLine ? Math.Max(_selectionOriginX, _selectionTargetX) : _selectionOriginY > _selectionTargetY ? _selectionOriginX : _selectionTargetX; if (endLine == startLine) { return _lines[startLine].Substring(startChar, endChar - startChar); } else { var lines = new List<string>(); lines.Add(_lines[startLine].Substring(startChar)); int startRange = startLine + 1; if (endLine != startRange) { int endRange = (endLine - startLine) - 1; lines.AddRange(_lines.GetRange(startRange, endRange)); } lines.Add(_lines[endLine].Substring(0, endChar)); return String.Join(Environment.NewLine, lines); } } /// <summary> /// Removes the selected text. /// </summary> private void DeleteSelection() { _hasSelection = false; int startLine = Math.Min(_selectionOriginY, _selectionTargetY); int endLine = Math.Max(_selectionOriginY, _selectionTargetY); int startChar = startLine == endLine ? Math.Min(_selectionOriginX, _selectionTargetX) : _selectionOriginY > _selectionTargetY ? _selectionTargetX : _selectionOriginX; int endChar = startLine == endLine ? Math.Max(_selectionOriginX, _selectionTargetX) : _selectionOriginY > _selectionTargetY ? _selectionOriginX : _selectionTargetX; if (endLine == startLine) { _lines[startLine] = _lines[startLine].Substring(0, startChar) + _lines[startLine].Substring(endChar); } else { _lines[startLine] = _lines[startLine].Substring(0, startChar) + _lines[endLine].Substring(endChar); _lines.RemoveRange(startLine + 1, endLine - startLine); for (int i = 0; i < endLine - startLine; ++i) { OnLineDeleted(startLine + 1 + i); } } _caretX = startChar; _caretY = startLine; } /// <summary> /// Gets indendation level and viewname of the next line. /// </summary> private int GetIndentLevelOfNextLine(out string viewName) { viewName = string.Empty; bool getPropertyIdentation = false; if (_caretElement == XmlSyntaxElement.PropertyName) { getPropertyIdentation = true; } int caretY = _caretY; while (caretY >= 0) { var line = _lines[caretY]; if (caretY == _caretY) { line = line.Substring(0, _caretX); } var trimmedLine = line.Trim(); if (trimmedLine.StartsWith("<") && !trimmedLine.StartsWith("<!")) { int leadingSpaces = _lines[caretY].TakeWhile(Char.IsWhiteSpace).Count(); if (leadingSpaces + 1 < _lines[caretY].Length) { viewName = new string(_lines[caretY].Substring(leadingSpaces + 1).TakeWhile(Char.IsLetterOrDigit).ToArray()); } if (getPropertyIdentation) { return leadingSpaces + viewName.Length + 2; } else { // if trimmed line ends an open view we want the next indentation level return trimmedLine.EndsWith(">") && !trimmedLine.StartsWith("</") && !trimmedLine.EndsWith("/>") ? leadingSpaces + 2 : leadingSpaces; } } --caretY; } return 0; } /// <summary> /// Handles input when CTRL key is pressed. /// </summary> private void HandleControlInput() { bool updateText = false; bool needReparse = false; bool skipAddUndoInfo = false; var repeatKeyDown = KeyCode.None; // key has been pressed in previous frame if (_trackKeyDown != KeyCode.None) { if (Input.GetKey(_trackKeyDown)) { _keyDownDelayTimeElapsed += Time.deltaTime; if (_keyDownDelayTimeElapsed > KeyRepeatDelay) { _keyDownRepeatTimeElapsed += Time.deltaTime; } if (_keyDownRepeatTimeElapsed > KeyRepeatRate) { _keyDownRepeatTimeElapsed = 0; repeatKeyDown = _trackKeyDown; } } else { _trackKeyDown = KeyCode.None; _keyDownDelayTimeElapsed = 0; _keyDownRepeatTimeElapsed = 0; } } // CTRL+C - copy if (Input.GetKeyDown(KeyCode.C)) { if (_hasSelection) { GUIUtility.systemCopyBuffer = GetSelection(); } } // CTRL+X - cut if (Input.GetKeyDown(KeyCode.X)) { if (_hasSelection) { GUIUtility.systemCopyBuffer = GetSelection(); if (!IsReadOnly) { DeleteSelection(); updateText = true; needReparse = true; } } } // CTRL+V - paste if (Input.GetKeyDown(KeyCode.V) && !IsReadOnly) { var pasteText = GUIUtility.systemCopyBuffer; if (String.IsNullOrEmpty(pasteText)) return; if (_hasSelection) { DeleteSelection(); } var pasteLines = pasteText.GetLines().ToList(); if (pasteLines.Count == 1) { if (pasteLines[0].Length > 0) { _lines[_caretY] = _lines[_caretY].InsertOrAdd(_caretX, pasteLines[0]); _caretX += pasteLines[0].Length; } } else { var rightStr = string.Empty; var leftStr = string.Empty; if (_caretX <= 0) { rightStr = _lines[_caretY]; } else if (_caretX >= _lines[_caretY].Length) { leftStr = _lines[_caretY]; } else { rightStr = _lines[_caretY].Substring(_caretX); leftStr = _lines[_caretY].Substring(0, _caretX); } if (pasteLines[0].Length == 1) { _lines[_caretY] = leftStr + pasteLines[0] + rightStr; _caretX += pasteLines[0].Length; } else { _lines[_caretY] = leftStr + pasteLines[0]; int lastIndex = pasteLines.Count - 1; for (int j = 1; j < lastIndex; ++j) { _lines.InsertOrAdd(_caretY + j, pasteLines[j]); OnLineAdded(_caretY + j); } _lines.InsertOrAdd(_caretY + lastIndex, pasteLines[lastIndex] + rightStr); OnLineAdded(_caretY + lastIndex); _caretX = pasteLines[lastIndex].Length; _caretY += lastIndex; } } updateText = true; needReparse = true; } // CTRL+A - select all else if (Input.GetKeyDown(KeyCode.A)) { _selectionOriginX = 0; _selectionOriginY = 0; _selectionTargetY = _lines.Count() - 1; _selectionTargetX = _lines[_selectionTargetY].Length; _hasSelection = _selectionTargetX != _selectionOriginX || _selectionTargetY != _selectionOriginY; if (_hasSelection) { _caretX = _selectionTargetX; _caretY = _selectionTargetY; UpdateTextAndCaret(false); } } // CTRL+Space - trigger intellisense/autocomplete else if (Input.GetKeyDown(KeyCode.Space) && !IsReadOnly) { ActivateAutoComplete(); } // CTRL+Z - undo else if ((Input.GetKeyDown(KeyCode.Z) || repeatKeyDown == KeyCode.Z) && !IsReadOnly) { Undo(); skipAddUndoInfo = true; _trackKeyDown = KeyCode.Z; } // CTRL+Y - redo else if ((Input.GetKeyDown(KeyCode.Y) || repeatKeyDown == KeyCode.Y) && !IsReadOnly) { Redo(); skipAddUndoInfo = true; _trackKeyDown = KeyCode.Y; } // Command+Left - home on MAC else if(Input.GetKeyDown(KeyCode.LeftArrow) || repeatKeyDown == KeyCode.LeftArrow) { HandleKeyInput((char)KeyCode.Home + "", true); _trackKeyDown = KeyCode.LeftArrow; return; } // Command+Right - end on MAC else if (Input.GetKeyDown(KeyCode.RightArrow) || repeatKeyDown == KeyCode.RightArrow) { HandleKeyInput((char)KeyCode.End + "", true); _trackKeyDown = KeyCode.RightArrow; return; } // Command+Up - page up on MAC else if (Input.GetKeyDown(KeyCode.UpArrow) || repeatKeyDown == KeyCode.UpArrow) { HandleKeyInput((char)KeyCode.PageUp + "", true); _trackKeyDown = KeyCode.UpArrow; return; } // Command+Down - page down on MAC else if (Input.GetKeyDown(KeyCode.DownArrow) || repeatKeyDown == KeyCode.DownArrow) { HandleKeyInput((char)KeyCode.PageDown + "", true); _trackKeyDown = KeyCode.DownArrow; return; } if (updateText) { if (!skipAddUndoInfo) { AddUndoInfo(needReparse); } OnEditorChanged(); Edit.Invoke(this, needReparse); } } /// <summary> /// Undos last text edit. /// </summary> private void Undo() { if (_undoCount > 1) { --_undoCount; var undo = _undoInfo[_undoCount - 1]; _lines = undo.Lines.ToList(); _caretX = undo.CaretX; _caretY = undo.CaretY; OnTextOrCaretChanged(true, false, undo.NeedReparse, true); } } /// <summary> /// Redos last text edit. /// </summary> private void Redo() { if (_undoCount < _undoInfo.Count) { ++_undoCount; var redo = _undoInfo[_undoCount - 1]; _lines = redo.Lines.ToList(); _caretX = redo.CaretX; _caretY = redo.CaretY; OnTextOrCaretChanged(true, false, redo.NeedReparse, true); } } /// <summary> /// Adds undo info. /// </summary> private void AddUndoInfo(bool needReparse) { if (_undoCount != _undoInfo.Count) { _undoInfo = _undoInfo.Take(_undoCount).ToList(); } _undoInfo.Add(new XmlEditorUndoInfo { Lines = _lines.ToList(), NeedReparse = needReparse, CaretX = _caretX, CaretY = _caretY }); if (_undoCount >= UndoHistoryLimit) { _undoInfo.RemoveAt(0); } else { ++_undoCount; } } /// <summary> /// Called after the view has been loaded. /// </summary> protected override void AfterLoad() { base.AfterLoad(); //XmlTextLabel.GameObject.AddComponent<TMPro.Examples.TMP_TextInfoDebugTool>(); // comment after debugging LineNumbersRightBorder.Width = CharWidth; LineNumbersRightBorder.Offset.Left = CharWidth; Caret.Offset.Left = -(CharWidth / 2.0f); _caretCanvasRenderer = Caret.GameObject.GetComponent<CanvasRenderer>(); ClearEditor(); } /// <summary> /// Clears all input and resets editor to default state. /// </summary> public void ClearEditor() { _caretX = 0; _caretY = 0; _desiredCaretX = 0; _lines.Clear(); _lines.Add(string.Empty); _addedLines.Clear(); _deletedLines.Clear(); _hasSelection = false; _undoInfo.Clear(); _undoCount = 0; ScrollableRegion.SetScrollPosition(0, 0); OnEditorChanged(); } /// <summary> /// Called when the XML text, selection or caret has changed. /// </summary> private void OnEditorChanged() { string xmlText = String.Join(Environment.NewLine, _lines); XmlTextLabel.TextMeshProUGUI.text = xmlText; XmlTextLabel.TextMeshProUGUI.ForceMeshUpdate(); TMP_TextInfo textInfo = XmlTextLabel.TextMeshProUGUI.textInfo; var textBounds = XmlTextLabel.TextMeshProUGUI.textBounds; // set size and text of line numbers var maxLineNumberCharCount = _lines.Count().ToString().Length; var lineNumbersWidth = CharWidth * maxLineNumberCharCount; var lineNumbersHeight = _lines.Count() * LineHeight; LineNumbersLabel.Width = lineNumbersWidth; LineNumbersLabel.Height = lineNumbersHeight; LineNumbersLabel.Text = String.Join(Environment.NewLine, Enumerable.Range(1, _lines.Count()).Select(x => x.ToString())); float leftMarginSpacing = CharWidth; XmlEditLeftMargin.Width = lineNumbersWidth + leftMarginSpacing; XmlEditLeftMargin.Height = lineNumbersHeight; XmlEditLeftMargin.Margin.Right = leftMarginSpacing; // set size and margins of XML edit and text region var maxLineLength = _lines.Max(x => x.Length); float textWidth = maxLineLength * CharWidth; float textHeight = _lines.Count() * LineHeight; XmlEditRegion.Width = textWidth + XmlEditLeftMargin.Width + XmlTextMarginLeft + XmlTextMarginRight + ScrollableRegion.VerticalScrollbar.ActualWidth; XmlEditRegion.Height = textHeight + ScrollableRegion.HorizontalScrollbar.ActualHeight + LineHeight; XmlTextRegion.Margin.Left = XmlEditLeftMargin.Width; // update text, syntax highlighting, selection and caret position UpdateTextAndCaret(); } /// <summary> /// Updates text, syntax highlighting, selection and caret. /// </summary> public void UpdateTextAndCaret(bool syntaxHighlight = true) { if (Caret.OffsetFromParent == null) Caret.OffsetFromParent = new ElementMargin(); Caret.OffsetFromParent.Left = CharWidth * _caretX; Caret.OffsetFromParent.Top = LineHeight * _caretY; // position intellisense box if (AutoCompleteBox.OffsetFromParent == null) AutoCompleteBox.OffsetFromParent = new ElementMargin(); AutoCompleteBox.OffsetFromParent.Left = CharWidth * _caretX; AutoCompleteBox.OffsetFromParent.Top = LineHeight * (_caretY + 1); _caretElement = XmlSyntaxElement.Undefined; string xmlText = XmlTextLabel.TextMeshProUGUI.text; if (String.IsNullOrEmpty(xmlText)) { GenerateTextHighlightMeshes(); return; } TMP_TextInfo textInfo = XmlTextLabel.TextMeshProUGUI.textInfo; Color32[] newVertexColors; Color32 characterColor = XmlTextLabel.TextMeshProUGUI.color; var xmlSyntaxElement = XmlSyntaxElement.Undefined; int line = 0; int lineChar = 0; int characterCount = textInfo.characterCount; int caretX = _caretX; bool caretLastInLine = false; bool addLine = false; bool inEmbeddedCode = false; bool inBinding = false; bool lastCharacterInBinding = false; // if caret is at the end of the line use the previous character as indicator for the element we're at if (_lines[_caretY].Length == _caretX) { --caretX; caretLastInLine = true; } // go through characters, syntax highlight and track current caret element for (int characterIndex = 0; characterIndex < characterCount; ++characterIndex) { int materialIndex = textInfo.characterInfo[characterIndex].materialReferenceIndex; newVertexColors = textInfo.meshInfo[materialIndex].colors32; int vertexIndex = textInfo.characterInfo[characterIndex].vertexIndex; switch (xmlText[characterIndex]) { case '"': inEmbeddedCode = false; inBinding = false; if (xmlSyntaxElement == XmlSyntaxElement.Comment) break; if (characterIndex > 0 && xmlText[characterIndex - 1] == '\\') break; xmlSyntaxElement = xmlSyntaxElement == XmlSyntaxElement.BeginPropertyValue || xmlSyntaxElement == XmlSyntaxElement.PropertyValue ? XmlSyntaxElement.EndPropertyValue : XmlSyntaxElement.BeginPropertyValue; break; case '<': if (xmlSyntaxElement == XmlSyntaxElement.Comment) break; if (characterIndex + 3 < characterCount) { if (xmlText[characterIndex + 1] == '!' && xmlText[characterIndex + 2] == '-' && xmlText[characterIndex + 3] == '-') { xmlSyntaxElement = XmlSyntaxElement.Comment; break; } } if (xmlSyntaxElement == XmlSyntaxElement.PropertyValue) break; xmlSyntaxElement = XmlSyntaxElement.BeginViewName; break; case '/': if (xmlSyntaxElement == XmlSyntaxElement.Comment) break; if (xmlSyntaxElement == XmlSyntaxElement.PropertyValue) break; if (characterIndex - 1 >= 0) { if (xmlText[characterIndex - 1] == '<') { xmlSyntaxElement = XmlSyntaxElement.BeginViewName; break; } } xmlSyntaxElement = XmlSyntaxElement.EndViewName; break; case '>': if (xmlSyntaxElement == XmlSyntaxElement.Comment) { if (characterIndex - 4 >= 0) { if (xmlText[characterIndex - 1] == '-' && xmlText[characterIndex - 2] == '-' && !(xmlText[characterIndex - 3] == '!' && xmlText[characterIndex - 4] != '<')) { xmlSyntaxElement = XmlSyntaxElement.EndComment; break; } } break; } if (xmlSyntaxElement == XmlSyntaxElement.PropertyValue) break; xmlSyntaxElement = XmlSyntaxElement.EndView; break; case ' ': if (xmlSyntaxElement == XmlSyntaxElement.PropertyValue || xmlSyntaxElement == XmlSyntaxElement.Comment || xmlSyntaxElement == XmlSyntaxElement.Undefined) break; // if previous is part of a view name we don't want this to be a property name if (xmlSyntaxElement == XmlSyntaxElement.ViewName && !caretLastInLine && characterIndex - 1 >= 0) { char previousChar = xmlText[characterIndex - 1]; if (previousChar == '<' || Char.IsLetterOrDigit(previousChar)) { break; } } xmlSyntaxElement = XmlSyntaxElement.PropertyName; break; case '\n': addLine = true; inBinding = false; inEmbeddedCode = false; break; case '\r': lineChar = 0; inBinding = false; inEmbeddedCode = false; break; case '$': if (xmlSyntaxElement == XmlSyntaxElement.PropertyValue) { // embedded code inEmbeddedCode = true; } break; case '{': if (xmlSyntaxElement == XmlSyntaxElement.PropertyValue) { // '{{' is not in binding, so we need to check if neither previous or next char is '{' bool bracketsBefore = characterIndex - 1 >= 0 && xmlText[characterIndex - 1] == '{'; bool bracketsAfter = characterIndex + 1 < characterCount && xmlText[characterIndex + 1] == '{'; inBinding = !(bracketsBefore || bracketsAfter); } break; case '}': lastCharacterInBinding = true; break; default: if (xmlSyntaxElement == XmlSyntaxElement.ViewName) { if (characterIndex - 1 >= 0) { char previousChar = xmlText[characterIndex - 1]; if (previousChar == ' ') { xmlSyntaxElement = XmlSyntaxElement.PropertyName; break; } } } break; } if (!caretLastInLine && line == _caretY && lineChar == caretX) { _caretElement = xmlSyntaxElement; } switch (xmlSyntaxElement) { case XmlSyntaxElement.Undefined: characterColor = UndefinedColor; break; case XmlSyntaxElement.BeginViewName: characterColor = PropertyValueColor; xmlSyntaxElement = XmlSyntaxElement.ViewName; break; case XmlSyntaxElement.ViewName: characterColor = ViewNameColor; break; case XmlSyntaxElement.EndViewName: characterColor = PropertyValueColor; xmlSyntaxElement = XmlSyntaxElement.PropertyName; break; case XmlSyntaxElement.EndView: characterColor = PropertyValueColor; xmlSyntaxElement = XmlSyntaxElement.Undefined; break; case XmlSyntaxElement.BeginPropertyValue: characterColor = PropertyValueColor; xmlSyntaxElement = XmlSyntaxElement.PropertyValue; break; case XmlSyntaxElement.PropertyValue: characterColor = PropertyValueColor; break; case XmlSyntaxElement.EndPropertyValue: characterColor = PropertyValueColor; xmlSyntaxElement = XmlSyntaxElement.PropertyName; break; case XmlSyntaxElement.PropertyName: characterColor = PropertyNameColor; break; case XmlSyntaxElement.Comment: characterColor = CommentColor; break; case XmlSyntaxElement.EndComment: characterColor = CommentColor; xmlSyntaxElement = XmlSyntaxElement.Undefined; break; } if (caretLastInLine && line == _caretY && lineChar == caretX) { _caretElement = xmlSyntaxElement; } ++lineChar; if (addLine) { ++line; lineChar = 0; addLine = false; } if (inEmbeddedCode) { characterColor = CodeColor; } if (inBinding) { characterColor = BindingColor; } if (lastCharacterInBinding) { inBinding = false; lastCharacterInBinding = false; } if (textInfo.characterInfo[characterIndex].isVisible && syntaxHighlight) { newVertexColors[vertexIndex + 0] = characterColor; newVertexColors[vertexIndex + 1] = characterColor; newVertexColors[vertexIndex + 2] = characterColor; newVertexColors[vertexIndex + 3] = characterColor; } } // update text meshes if (syntaxHighlight) { XmlTextLabel.TextMeshProUGUI.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32); } // generate caret and selection meshes GenerateTextHighlightMeshes(); // for debugging purposes show which element we are in DebugTextLabel.Text = _caretElement.ToString(); } /// <summary> /// Generates caret and selection meshes. /// </summary> private void GenerateTextHighlightMeshes(bool scrollToLastSelectedView = false) { _selectionMesh = new Mesh(); SelectedLines.Clear(); using (var vertexHelper = new VertexHelper()) { if (_selectedViews.Any()) { foreach (var selectedView in _selectedViews) { int startLine = Math.Max(GetLineInEditedXml(selectedView.Template.LineNumber - 1), 0); int startChar = Math.Max(_lines[startLine].IndexOf("<"), 0);// Math.Max(selectedView.Template.LinePosition - 2, 0); if (startLine >= _lines.Count) continue; int endLine = startLine; int endChar = selectedView.Template.LinePosition + 20; SelectedLines.Add(startLine); for (int lineIndex = startLine; lineIndex < _lines.Count; ++lineIndex) { string line = _lines[lineIndex]; // replace everything in the line within quotes "" so we don't match end tags within strings line = QuoteContentRegex.Replace(line, x => { return new string('x', x.Value.Length); }); endChar = line.LastIndexOf(">") + 1; if (endChar > startChar) { endLine = lineIndex; break; } } // scroll to last highlighted view if (scrollToLastSelectedView && selectedView == _selectedViews.Last()) { // check if highlighted view is outside viewport and update scroll position float lineOffsetY = startLine * LineHeight; float viewportHeight = ScrollableRegion.ViewportHeight; var contentOffset = ScrollableRegion.GetContentOffset(); contentOffset.y = Math.Abs(contentOffset.y); float scrollOffsetY = -1; if ((lineOffsetY + LineHeight + ScrollableRegion.HorizontalScrollbar.ActualHeight) > (contentOffset.y + viewportHeight)) { scrollOffsetY = (lineOffsetY + (LineHeight * 3) + ScrollableRegion.HorizontalScrollbar.ActualHeight) - viewportHeight; } else if (lineOffsetY < contentOffset.y) { scrollOffsetY = lineOffsetY - (LineHeight * 2); } if (scrollOffsetY >= 0) { ScrollableRegion.SetVerticalAbsoluteScrollPosition(scrollOffsetY); } } GenerateTextHighlightMeshes(vertexHelper, startLine, endLine, startChar, endChar, ViewSelectionColor); } } if (_hasSelection) { int startLine = Math.Min(_selectionOriginY, _selectionTargetY); int endLine = Math.Max(_selectionOriginY, _selectionTargetY); int startChar = startLine == endLine ? Math.Min(_selectionOriginX, _selectionTargetX) : _selectionOriginY > _selectionTargetY ? _selectionTargetX : _selectionOriginX; int endChar = startLine == endLine ? Math.Max(_selectionOriginX, _selectionTargetX) : _selectionOriginY > _selectionTargetY ? _selectionOriginX : _selectionTargetX; GenerateTextHighlightMeshes(vertexHelper, startLine, endLine, startChar, endChar, TextSelectionColor); } vertexHelper.FillMesh(_selectionMesh); } TextSelection.CanvasRendererComponent.SetMesh(_selectionMesh); } /// <summary> /// Generates text highlight meshes. /// </summary> private void GenerateTextHighlightMeshes(VertexHelper vertexHelper, int startLine, int endLine, int startChar, int endChar, Color32 color) { UIVertex vertex = UIVertex.simpleVert; vertex.uv0 = Vector2.zero; vertex.color = color; var startX = -TextSelection.ActualWidth / 2; var startY = TextSelection.ActualHeight / 2; // draw selection quads for each line that the selection covers for (int line = startLine; line <= endLine; ++line) { int startCharCount = line == startLine ? startChar : 0; int endCharCount = (line == endLine ? endChar : _lines[line].Length + 1) - startCharCount; // generate vertices for selection Vector2 startPosition = new Vector2(startX + startCharCount * CharWidth, startY - line * LineHeight); Vector2 endPosition = new Vector2(startPosition.x + endCharCount * CharWidth, startPosition.y - LineHeight); // check if vertices are outside viewport and clamp position to viewport var contentOffset = ScrollableRegion.GetContentOffset(); contentOffset.x = Math.Abs(contentOffset.x); contentOffset.y = Math.Abs(contentOffset.y); var startIndex = vertexHelper.currentVertCount; vertex.position = new Vector3(startPosition.x, endPosition.y, 0.0f); vertexHelper.AddVert(vertex); vertex.position = new Vector3(endPosition.x, endPosition.y, 0.0f); vertexHelper.AddVert(vertex); vertex.position = new Vector3(endPosition.x, startPosition.y, 0.0f); vertexHelper.AddVert(vertex); vertex.position = new Vector3(startPosition.x, startPosition.y, 0.0f); vertexHelper.AddVert(vertex); vertexHelper.AddTriangle(startIndex, startIndex + 1, startIndex + 2); vertexHelper.AddTriangle(startIndex + 2, startIndex + 3, startIndex + 0); } } /// <summary> /// Makes caret visible and resets caret repeat delay. Used when caret is moved to make sure it's visible. /// </summary> public void ActivateCaret() { _caretDelayTimeElapsed = 0; _caretRepeatTimeElapsed = 0; Caret.IsActive = true; } /// <summary> /// Activates autocomplete box and content based on caret position. /// </summary> private void ActivateAutoComplete() { string wordAtCaret = GetWordAtCaret(out _autoCompleteWordOriginX, out _autoCompleteWordTargetX); DebugTextLabel.Text = String.Format("{0}: {1}", _caretElement.ToString(), wordAtCaret); bool updateOptions = _lastWordAtCaret != wordAtCaret; _lastWordAtCaret = wordAtCaret; if (!_autoCompleteActive) { // auto-complete activated, populate list _autoCompleteOptions.Clear(); switch (_caretElement) { case XmlSyntaxElement.ViewName: case XmlSyntaxElement.BeginViewName: foreach (var view in DesignerViews) { _autoCompleteOptions.Add(new AutoCompleteOption { Text = view.Name }); } break; case XmlSyntaxElement.EndView: case XmlSyntaxElement.EndViewName: case XmlSyntaxElement.PropertyName: { // get property names from current view var viewNameAtCaret = GetViewAtCaret(); var viewAtCaret = DesignerViews.FirstOrDefault(x => x.Name == viewNameAtCaret); if (viewAtCaret == null) break; var properties = CodeGenerator.GetPropertyDeclarations(viewAtCaret.ViewObject, true, true, true).OrderBy(x => x.Declaration.PropertyName); foreach (var property in properties) { if (property.Declaration.DeclarationType == PropertyDeclarationType.Template || property.Declaration.DeclarationType == PropertyDeclarationType.UnityComponent || (property.Declaration.DeclarationType == PropertyDeclarationType.View && !property.IsMapped)) continue; // ignore properties not set from XML _autoCompleteOptions.Add(new AutoCompleteOption { Text = property.Declaration.PropertyName }); } // add attribute properties _autoCompleteOptions.Add(new AutoCompleteOption { Text = "Id" }); _autoCompleteOptions.Add(new AutoCompleteOption { Text = "Style" }); _autoCompleteOptions.Add(new AutoCompleteOption { Text = "StateAnimations" }); } break; case XmlSyntaxElement.PropertyValue: case XmlSyntaxElement.EndPropertyValue: { var viewNameAtCaret = GetViewAtCaret(); var viewAtCaret = DesignerViews.FirstOrDefault(x => x.Name == viewNameAtCaret); if (viewAtCaret == null) break; var propertyNameAtCaret = GetPropertyAtCaret(); if (propertyNameAtCaret == "Style") { // populate with styles that can be applied to current view var contentObjectModel = ContentObjectModel.GetInstance(); var styleNames = contentObjectModel.GetStyleNames(viewNameAtCaret); foreach (var style in styleNames) { _autoCompleteOptions.Add(new AutoCompleteOption { Text = style }); } break; } if (propertyNameAtCaret == "StateAnimations") { // populate with state animations var contentObjectModel = ContentObjectModel.GetInstance(); var stateAnimationsNames = contentObjectModel.GetStateAnimationsNames(viewNameAtCaret); foreach (var stateAnimationsName in stateAnimationsNames) { _autoCompleteOptions.Add(new AutoCompleteOption { Text = stateAnimationsName }); } break; } var property = CodeGenerator.GetPropertyDeclarations(viewAtCaret.ViewObject, true, true, true).FirstOrDefault(x => x.Declaration.PropertyName == propertyNameAtCaret); if (property == null) break; if (property.IsAssetReference) { // populate depending on asset type var contentObjectModel = ContentObjectModel.GetInstance(); var assetObjects = contentObjectModel.AssetBundleObjects.SelectMany(x => x.AssetObjects).Where(x => x.Type == property.AssetType).OrderBy(x => x.Name).ToList(); foreach (var assetObject in assetObjects) { _autoCompleteOptions.Add(new AutoCompleteOption { Text = assetObject.Name, IsAsset = true, AssetObject = assetObject }); } } else if (property.Declaration.DeclarationType == PropertyDeclarationType.Default) { // see if type is an enum var type = MasterConfig.GetType(property.Declaration.PropertyTypeName); if (type != null && type.IsEnum) { var names = Enum.GetNames(type); foreach (var name in names.OrderBy(x => x)) { _autoCompleteOptions.Add(new AutoCompleteOption { Text = name }); } } } } break; default: break; } AutoCompleteOptions.Replace(_autoCompleteOptions); if (AutoCompleteOptions.Any()) { AutoCompleteOptions.SelectAndScrollTo(0, ElementAlignment.Center); updateOptions = true; } else { DeactivateAutoComplete(); return; } } else { // in some cases if caret element type changes we want to deactivate autocomplete bool deactivateAutoComplete = false; switch (_caretElement) { case XmlSyntaxElement.ViewName: case XmlSyntaxElement.BeginViewName: deactivateAutoComplete = _autoCompleteType != XmlSyntaxElement.ViewName && _autoCompleteType != XmlSyntaxElement.BeginViewName; break; case XmlSyntaxElement.EndViewName: case XmlSyntaxElement.PropertyName: deactivateAutoComplete = _autoCompleteType != XmlSyntaxElement.EndViewName && _autoCompleteType != XmlSyntaxElement.PropertyName; break; case XmlSyntaxElement.PropertyValue: case XmlSyntaxElement.EndPropertyValue: deactivateAutoComplete = _autoCompleteType != XmlSyntaxElement.PropertyValue && _autoCompleteType != XmlSyntaxElement.EndPropertyValue; break; default: deactivateAutoComplete = _caretElement != _autoCompleteType; break; } if (deactivateAutoComplete) { DeactivateAutoComplete(); return; } } _autoCompleteActive = true; _autoCompleteType = _caretElement; if (!updateOptions) return; int longestOption = 0; var matchedStartOptions = new List<AutoCompleteOption>(); var matchedAnyOptions = new List<AutoCompleteOption>(); var matchedOptions = new List<AutoCompleteOption>(); foreach (var option in _autoCompleteOptions) { if (option.MatchWithWord(wordAtCaret)) { if (option.IsMatchStart) { matchedStartOptions.Add(option); } else { matchedAnyOptions.Add(option); } int optionLength = option.Text.Length; longestOption = optionLength > longestOption ? optionLength : longestOption; } } matchedOptions.AddRange(matchedStartOptions); matchedOptions.AddRange(matchedAnyOptions); bool hasAnyMatch = matchedOptions.Any(); // arrange size of auto-complete box based on number of matches and the longest match in list AutoCompleteBox.IsVisible = hasAnyMatch; if (hasAnyMatch) { int matchCount = matchedOptions.Count(); AutoCompleteBox.Width = longestOption * CharWidth + 40; float height = matchCount * LineHeight; if (height > MaxAutoCompleteBoxHeight) { height = MaxAutoCompleteBoxHeight; } AutoCompleteBox.Height = height; AutoCompleteOptionsList.Height = height; AutoCompleteOptions.Replace(matchedOptions); AutoCompleteOptions.SelectAndScrollTo(matchedOptions.First()); } } /// <summary> /// Gets the view at the current caret position. /// </summary> public string GetViewAtCaret() { return GetViewAtCaret(_caretY); } /// <summary> /// Gets the view at the specified caret position. /// </summary> private string GetViewAtCaret(int caretY) { for (int lineIndex = caretY; lineIndex >= 0; --lineIndex) { string line = _lines[lineIndex]; // remove everything in the line within quotes "" so we don't match elements within strings line = QuoteContentRegex.Replace(line, String.Empty); var match = ViewNameStartRegex.Match(line); if (match.Success) { return match.Value; } } return string.Empty; } /// <summary> /// Gets the property name at the current caret position. /// </summary> private string GetPropertyAtCaret() { return GetPropertyAtCaret(_caretX, _caretY); } /// <summary> /// Gets the property name at the specified caret position. /// </summary> private string GetPropertyAtCaret(int caretX, int caretY) { string line = _lines[caretY].Substring(0, caretX); int equalIndex = line.LastIndexOf('='); if (equalIndex < 0) { return string.Empty; } line = line.Substring(0, equalIndex); string lastWord = line.Split(' ', '-').LastOrDefault(); if (String.IsNullOrEmpty(lastWord)) { return string.Empty; } return lastWord; } /// <summary> /// Gets the word at the current caret position. /// </summary> private string GetWordAtCaret() { return GetWordAtCaret(_caretX, _caretY, out _, out _); } /// <summary> /// Gets the word at the current caret position. /// </summary> private string GetWordAtCaret(out int originX, out int targetX) { return GetWordAtCaret(_caretX, _caretY, out originX, out targetX); } /// <summary> /// Gets the word at the specified caret position. /// </summary> private string GetWordAtCaret(int caretX, int caretY, out int originX, out int targetX) { if (_lines[caretY].Length <= 0) { originX = caretX; targetX = caretX; return string.Empty; } originX = caretX - 1; targetX = caretX; if (originX < 0) originX = 0; // get characters to the left and right of caret that are digits or letters Func<char, bool> selectChar = c => Char.IsLetterOrDigit(c); // select letters and digits by default while (targetX < _lines[caretY].Length) { if (!selectChar(_lines[caretY][targetX])) { break; } ++targetX; } while (originX >= 0) { if (!selectChar(_lines[caretY][originX])) { originX = originX == _lines[caretY].Length - 1 ? originX : originX + 1; break; } --originX; } if (originX < 0) originX = 0; int length = targetX - originX; bool wordAtCaret = length == 1 ? selectChar(_lines[caretY][originX]) : length > 0; if (wordAtCaret) { return _lines[caretY].Substring(originX, length); } else { originX = targetX; return string.Empty; } } /// <summary> /// Hides autocomplete box. /// </summary> private void DeactivateAutoComplete() { _autoCompleteActive = false; _autoCompleteType = XmlSyntaxElement.Undefined; AutoCompleteBox.IsVisible = false; } /// <summary> /// Called when option is selected in the autocomplete box. /// </summary> public void AutoCompleteOptionSelected(AutoCompleteOption option) { FinishAutoComplete(); OnTextOrCaretChanged(true, false, true, false); } /// <summary> /// Auto-completes the current text. /// </summary> private bool FinishAutoComplete() { if (IsReadOnly) return false; var option = SelectedAutoCompleteOption; var autoCompleteType = _autoCompleteType; DeactivateAutoComplete(); if (autoCompleteType == XmlSyntaxElement.PropertyName || autoCompleteType == XmlSyntaxElement.EndViewName || autoCompleteType == XmlSyntaxElement.EndView) { // when completing property name add ="" to the end and activate auto-complete for property values var rightOfAutoComplete = _lines[_caretY].Substring(_autoCompleteWordTargetX); string autoCompleteText = option.Text; if (!rightOfAutoComplete.StartsWith("=\"")) { autoCompleteText += "=\"\""; } _lines[_caretY] = _lines[_caretY].Substring(0, _autoCompleteWordOriginX) + autoCompleteText + rightOfAutoComplete; _caretX = _autoCompleteWordOriginX + option.Text.Length + 2; _autoCompleteType = XmlSyntaxElement.PropertyValue; _caretElement = XmlSyntaxElement.PropertyValue; ActivateAutoComplete(); return true; } else { _lines[_caretY] = _lines[_caretY].Substring(0, _autoCompleteWordOriginX) + option.Text + _lines[_caretY].Substring(_autoCompleteWordTargetX); _caretX = _autoCompleteWordOriginX + option.Text.Length; return false; } } /// <summary> /// Selects auto-complete item template based on option type. /// </summary> public string AutoCompleteOptionSelector(AutoCompleteOption option) { return option.IsAsset ? "AssetOptionItem" : "DefaultOptionItem"; } /// <summary> /// Gets property documentation for specified element. /// </summary> private string GetElementDoc(string viewName, string propertyName = null) { var config = MasterConfig.GetInstance(); var docObject = config.DocObjects.FirstOrDefault(x => x.Name == viewName); if (docObject == null) { if (propertyName == null) { return string.Empty; } else { var basedOnView = DesignerViews.FirstOrDefault(x => x.Name == viewName)?.ViewObject?.BasedOn; return basedOnView != null ? GetElementDoc(basedOnView.Name, propertyName) : null; } } if (propertyName == null) return docObject.Comment; var docProperty = docObject.Properties.FirstOrDefault(x => x.Name == propertyName); if (docProperty == null) { // check if property resides in parent view var basedOnView = DesignerViews.FirstOrDefault(x => x.Name == viewName)?.ViewObject?.BasedOn; if (basedOnView == null) return string.Empty; return GetElementDoc(basedOnView.Name, propertyName); } return docProperty.Comment; } #endregion } } #endif
41.906118
228
0.447873
06fb0903e24638bb9706ba18e2285e98c3d48045
39
py
Python
Ourlogger/__init__.py
peleg525/Ourlogger
d5f90e8d1a098e2261696024deee7b871c691fd7
[ "MIT" ]
null
null
null
Ourlogger/__init__.py
peleg525/Ourlogger
d5f90e8d1a098e2261696024deee7b871c691fd7
[ "MIT" ]
null
null
null
Ourlogger/__init__.py
peleg525/Ourlogger
d5f90e8d1a098e2261696024deee7b871c691fd7
[ "MIT" ]
null
null
null
from Ourlogger.Ourlogger import logger
19.5
38
0.871795
b30c699ccbf2debab269537a7f3f266744d4a804
909
py
Python
Python/UncommonWordsFromTwoSentences.py
ani03sha/potd
05ca25039c5462b68dae9d83e856dd4c66e7ab63
[ "MIT" ]
null
null
null
Python/UncommonWordsFromTwoSentences.py
ani03sha/potd
05ca25039c5462b68dae9d83e856dd4c66e7ab63
[ "MIT" ]
null
null
null
Python/UncommonWordsFromTwoSentences.py
ani03sha/potd
05ca25039c5462b68dae9d83e856dd4c66e7ab63
[ "MIT" ]
null
null
null
""" Given two strings representing sentences, return the words that are not common to both strings (i.e. the words that only appear in one of the sentences). You may assume that each sentence is a sequence of words (without punctuation) correctly separated using space characters. """ from typing import List class UncommonWordsFromTwoSentences: def uncommonFromSentences(self, A: str, B: str) -> List[str]: AB = (A + " " + B).split() unique = {} for i in range(len(AB)): if AB[i] in unique: unique[AB[i]] = unique[AB[i]] + 1 else: unique[AB[i]] = 1 return [word for word in unique if unique[word] == 1] if __name__ == "__main__": u = UncommonWordsFromTwoSentences() print(u.uncommonFromSentences("this apple is sweet", "this apple is sour")) print(u.uncommonFromSentences("apple apple", "banana"))
36.36
96
0.643564
cc55949e648b23f70eebbf98d4a5f6646cc2a374
3,655
swift
Swift
C4CoreTests/C4VectorTests.swift
jbloit/C4iOS
5c06e322f121476a8ab5cee09117f297571916bb
[ "MIT" ]
null
null
null
C4CoreTests/C4VectorTests.swift
jbloit/C4iOS
5c06e322f121476a8ab5cee09117f297571916bb
[ "MIT" ]
null
null
null
C4CoreTests/C4VectorTests.swift
jbloit/C4iOS
5c06e322f121476a8ab5cee09117f297571916bb
[ "MIT" ]
null
null
null
// Copyright © 2014 C4 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: The above copyright // notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. import C4Core import XCTest class C4VectorTests: XCTestCase { func testUnitVector() { let vector = C4Vector(x: 8, y: 8, z: 8) let unitVector = vector.unitVector()! XCTAssertEqualWithAccuracy(unitVector.magnitude, 1, 1e-15, "Magnitude of unit vector should be 1") XCTAssertEqual(unitVector.heading, vector.heading, "Heading of unit vector should be the same as the original") } func testNilUnitVector() { let vector = C4Vector(x: 0, y: 0, z: 0) let unitVector = vector.unitVector() XCTAssert(unitVector == nil, "Callin unitVector on a zero vector should return nil") } func testDotProduct() { let vectorA = C4Vector(x: 1, y: 0) let vectorB = C4Vector(x: 0, y: 1) XCTAssertEqualWithAccuracy(vectorA ⋅ vectorB, 0, 1e-15, "Dot product of perpendicular vectors should be 0") } func testAngleTo() { let vectorA = C4Vector(x: 2, y: 0) let vectorB = C4Vector(x: 1, y: 1) let angle = vectorA.angleTo(vectorB) XCTAssertEqualWithAccuracy(angle, Double(M_PI)/4.0, 1e-15, "Product should be PI/4") } func testAngleToBaseOn() { let vectorA = C4Vector(x: 2, y: 0) let vectorB = C4Vector(x: 1, y: 1) let vectorC = C4Vector(x: 1, y: 0) let angle = vectorA.angleTo(vectorB, basedOn:vectorC) XCTAssertEqualWithAccuracy(angle, Double(M_PI)/2.0, 1e-15, "Product should be PI/2") } func testDivideScalar() { for i in 10...1000 { var v = Double(random(below:i))+1.0 var vector = C4Vector(x:v,y:v) vector /= v XCTAssertEqual(vector.x, 1.0, "Vector should equal 1") } } func testMultiplyScalar() { for i in 10...1000 { let val = Double(i) var vector = C4Vector(x:val, y:val) vector *= 10 XCTAssertEqual(vector.x, val*10, "Vector should equal 1") } } func testAddition() { for i in 10...1000 { var val = Double(i) var vector = C4Vector(x: val, y: val) vector += C4Vector(x: 1, y: 1) XCTAssertEqual(vector.x, val+1, "Vectore should be original value + 1") } } func testSubtraction() { for i in 10...1000 { var val = Double(i) var vector = C4Vector(x: val, y: val) vector -= C4Vector(x: 1, y: 1) XCTAssertEqual(vector.x, val-1, "Vectore should be original value - 1") } } }
38.882979
119
0.628454
87aa9a95907e21921e32d2a380b1e3c5ef64142c
1,724
rb
Ruby
spec/support/database_cleaner.rb
tibbs001/ctwiki-loader
78264b47e5d884bb6ee52fd4b0e4b6c2040a3e49
[ "MIT" ]
null
null
null
spec/support/database_cleaner.rb
tibbs001/ctwiki-loader
78264b47e5d884bb6ee52fd4b0e4b6c2040a3e49
[ "MIT" ]
46
2019-01-12T19:43:04.000Z
2022-03-30T12:36:45.000Z
spec/support/database_cleaner.rb
tibbs001/ctwiki-loader
78264b47e5d884bb6ee52fd4b0e4b6c2040a3e49
[ "MIT" ]
null
null
null
RSpec.configure do |config| config.before(:suite) do #DatabaseCleaner.clean_with(:deletion) dump_file=Rails.root.join("spec/support/postgres.dmp") cmd="pg_restore -c -j 5 -v -h localhost -p 5432 -U #{ENV['AACT_DB_SUPER_USERNAME']} -d open_trials_test #{dump_file}" puts "============= Seeding test studies to use in rspec......." puts cmd puts "===========================" require 'open3' stdout, stderr, status = Open3.capture3(cmd) @dbconfig = YAML.load(File.read('config/database.yml')) ActiveRecord::Base.establish_connection @dbconfig[:test] con=ActiveRecord::Base.establish_connection( adapter: 'postgresql', database: 'open_trials_test', encoding: 'utf8', username: 'wiki', ).connection con.execute('grant usage on schema ctgov to wiki;') con.execute('grant usage on schema lookup to wiki;') con.execute('grant usage on schema pubmed to wiki;') con.execute('grant select on all tables in schema ctgov to wiki;') con.execute('grant select on all tables in schema lookup to wiki;') con.execute('grant select on all tables in schema pubmed to wiki;') con.execute('GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA lookup TO wiki'); con.execute('GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA pubmed TO wiki'); con.execute('grant all on all tables in schema lookup to wiki;') con.execute('grant all on all tables in schema pubmed to wiki;') con.disconnect! con = nil ActiveRecord::Base.establish_connection @dbconfig[:test] end config.before(:each) do DatabaseCleaner.strategy = :transaction end config.before(:each, js: true) do DatabaseCleaner.strategy = :deletion end end
39.181818
121
0.680974
0d2b041af2d3f0b30c80f973583739b1f787fc1c
4,243
c
C
src/env.c
mmasciol/lib-vawt
062d13a9a9926cc74dbf208202c50285531f61f6
[ "Apache-1.1" ]
null
null
null
src/env.c
mmasciol/lib-vawt
062d13a9a9926cc74dbf208202c50285531f61f6
[ "Apache-1.1" ]
null
null
null
src/env.c
mmasciol/lib-vawt
062d13a9a9926cc74dbf208202c50285531f61f6
[ "Apache-1.1" ]
null
null
null
/**************************************************************** * Copyright (C) 2016 mdm * * * * 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. * ****************************************************************/ #include <stdlib.h> #include <math.h> #include "sys.h" #include "domain.h" #include "env.h" size_t env_size_meter(const void *el) { return sizeof(struct Environment); } ERROR_CODE env_initialize_list(struct Domain* domain, char* msg, ERROR_CODE* ierr) { list_init(&domain->env); list_attributes_copy(&domain->env, env_size_meter, 1); return SAFE; } ERROR_CODE env_new_environment(list_t* restrict env, char* msg, ERROR_CODE* ierr) { ERROR_CODE success = SAFE; struct Environment new_env; struct Environment* env_ = NULL; success = env_initialize(&new_env, msg, ierr); CHECKERRK(FATAL_5,"Failed to initialize <Environment>"); list_append(env, &new_env); env_ = (struct Environment*)list_get_at(env, list_size(env)-1); CHECK_MALLOC(env_, FATAL_8, "<Environment>"); return SAFE; CLEAN_UP: return FATAL; } ERROR_CODE env_initialize(struct Environment* env, char* msg, ERROR_CODE* ierr) { env->V = NULL; env->ref_h = -999.9; env->u_inf = -999.9; env->rho = -999.9; env->mu = -999.9; env->shear = -999.9; return SAFE; } ERROR_CODE env_free(struct Environment* env, char* msg, ERROR_CODE* ierr) { FREE_OBJ(env->V); return SAFE; } ERROR_CODE env_set_rho(struct Environment* env, const double rho, char* msg, ERROR_CODE* ierr) { printf("%f",env->rho); printf(" >%f \n",rho); env->rho = rho; return SAFE; } ERROR_CODE env_set_ref_height(struct Environment* env, const double ref_h, char* msg, ERROR_CODE* ierr) { env->ref_h = ref_h; return SAFE; } ERROR_CODE env_set_inflow_velocity(struct Environment* env, const double u, char* msg, ERROR_CODE* ierr) { env->u_inf = u; return SAFE; } ERROR_CODE env_set_mu(struct Environment* env, const double mu, char* msg, ERROR_CODE* ierr) { env->mu = mu; return SAFE; } ERROR_CODE env_set_shear(struct Environment* env, const double shear, char* msg, ERROR_CODE* ierr) { env->shear = shear; return SAFE; } double env_get_rho(struct Environment* env, char* msg, ERROR_CODE* ierr) { return env->rho; } double env_get_mu(struct Environment* env, char* msg, ERROR_CODE* ierr) { return env->mu; } double env_get_shear(struct Environment* env, char* msg, ERROR_CODE* ierr) { return env->shear; } ERROR_CODE env_set_wind_velocity(struct Environment* env, const double u, char* msg, ERROR_CODE* ierr) { env->u_inf = u; return SAFE; } ERROR_CODE env_wind_shear(struct Environment* env, const double* z, const int nz, char* msg, ERROR_CODE* ierr) { int i = 0; const double ref_h = env->ref_h; const double shear = env->shear; if (!(env->V)) { env->V = malloc((nz)*sizeof(double)); CHECK_MALLOC((env->V), FATAL_8, "V"); } for(i=0 ; i<nz ; i++) { env->V[i] = (env->u_inf)*pow((z[i]/ref_h), shear); } return SAFE; CLEAN_UP: return FATAL; }
24.812865
113
0.602168
b30ee4404167f71144c1fa86f2705a052789fc51
1,594
lua
Lua
lua/weapons/gmod_tool/stools/spawn_companion_doll.lua
gmodbr/Teb-gm13b-Developer-Gui
f6310b3110e4fbc18fa5d5f02242d78e3a8d8397
[ "MIT" ]
null
null
null
lua/weapons/gmod_tool/stools/spawn_companion_doll.lua
gmodbr/Teb-gm13b-Developer-Gui
f6310b3110e4fbc18fa5d5f02242d78e3a8d8397
[ "MIT" ]
1
2022-03-23T11:08:18.000Z
2022-03-23T11:08:18.000Z
lua/weapons/gmod_tool/stools/spawn_companion_doll.lua
gmodbr/Teb-gm13b-Developer-Gui
f6310b3110e4fbc18fa5d5f02242d78e3a8d8397
[ "MIT" ]
1
2022-03-25T04:12:45.000Z
2022-03-25T04:12:45.000Z
TOOL.Category = "C_GM13B_GUI_DEV" TOOL.Name = "#Tool.spawn_companion_doll.name" TOOL.Command = nil TOOL.ConfigName = "" TOOL.Information = { { name = "left" }, } if CLIENT then language.Add("Tool.spawn_companion_doll.name", "Spawn the companion doll") language.Add("Tool.spawn_companion_doll.desc", "Spawns the companion doll") language.Add("Tool.spawn_companion_doll.left", "Spawn obj") end local function spawn_companion_doll(pos) if SERVER then local pos2 = Vector(math.Round(pos.x, 2), math.Round(pos.y, 2), math.Round(pos.z, 2)) local convertedProp = ents.Create("prop_physics") convertedProp:SetName("converted_prop_gm13_" .. "models/maxofs2d/companion_doll.mdl") convertedProp:SetNWBool("ritualprop", true) convertedProp:SetModel("models/maxofs2d/companion_doll.mdl") convertedProp:SetPos(pos2 + Vector(0,0,10)) convertedProp:SetAngles(Angle(0,0,0)) convertedProp.gm13_final_pos = Vector(2284.38, 3557.02, -85.69) convertedProp:Spawn() convertedProp:PhysicsInit(SOLID_VPHYSICS) convertedProp:SetMoveType(MOVETYPE_VPHYSICS) convertedProp:SetSolid(SOLID_VPHYSICS) local physObj = convertedProp:GetPhysicsObject() if IsValid(physObj) then physObj:Wake() end GM13.Ent:SetInvulnerable(convertedProp, true) GM13.Ent:BlockToolgun(convertedProp, true) GM13.Ent:BlockContextMenu(convertedProp, true) end end function TOOL:LeftClick(trace) spawn_companion_doll(trace.HitPos) return true end function TOOL.BuildCPanel(pnl) pnl:AddControl("Header",{Text = "#Tool.spawn_companion_doll.name", Description = "#Tool.spawn_companion_doll.desc"}) end
34.652174
117
0.771644
0c67aeefe8d7b29a759642bc619ddea401a5176e
596
rb
Ruby
test/models/log_entry_test.rb
jjculber/TXXLog
d9df573bf9804dbb9557b254a7a152509c551180
[ "MIT" ]
2
2020-04-14T16:25:16.000Z
2021-02-15T08:19:25.000Z
test/models/log_entry_test.rb
jjculber/TXXLog
d9df573bf9804dbb9557b254a7a152509c551180
[ "MIT" ]
11
2020-02-10T00:41:46.000Z
2022-03-31T00:17:38.000Z
test/models/log_entry_test.rb
jjculber/TXXLog
d9df573bf9804dbb9557b254a7a152509c551180
[ "MIT" ]
null
null
null
# == Schema Information # # Table name: log_entries # # id :integer not null, primary key # event_id :integer not null # contact_at :datetime # callsign :string # category :string # section :string # station_id :integer not null # user_id :integer not null # frequency :integer # mode :string # deleted :boolean # created_at :datetime not null # updated_at :datetime not null # require 'test_helper' class LogEntryTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
22.074074
53
0.612416