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
sequencelengths
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
sequencelengths
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
sequencelengths
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
25a7d3a01c57af5a7b71ad97053f46c8a20dec59
4,999
lua
Lua
lua/oleo/helpers.lua
egresh/oleo
1be4c936c5d52e91363e4fd47192090f6b824718
[ "MIT" ]
3
2022-02-10T04:56:20.000Z
2022-02-16T08:10:02.000Z
lua/oleo/helpers.lua
egresh/oleo
1be4c936c5d52e91363e4fd47192090f6b824718
[ "MIT" ]
null
null
null
lua/oleo/helpers.lua
egresh/oleo
1be4c936c5d52e91363e4fd47192090f6b824718
[ "MIT" ]
null
null
null
local M = {} -- get the project root for a git project function M.project_root() local root = vim.fn.system("git rev-parse --show-toplevel") if string.find(root, "fatal:") then root = vim.fn.getcwd() else root = string.gsub(root, "\n", "") end return root end -- print over a parameter list function M.pp(...) local count = select("#", ...) for idx, param in ipairs({ ... }) do if count > 1 then print("Param " .. idx .. ":") end for k, v in pairs(param) do print(k, v) end end end -- unload modules function M.unload(modules) print("Unloading " .. #modules .. " modules") for _, v in pairs(modules) do if package.loaded[v] then package.loaded[v] = nil print("Module " .. v .. " has been unloaded") else print("Module " .. v .. " wasn't already loaded") end end end function M.put(...) local objects = {} for i = 1, select("#", ...) do local v = select(i, ...) table.insert(objects, vim.inspect(v)) end print(table.concat(objects, "\n")) return ... end function M.dump(...) local objects = vim.tbl_map(vim.inspect, { ... }) print(unpack(objects)) return ... end function M.get_rtp() local rtp = vim.o.runtimepath local t = {} for dir in rtp:gmatch("([%w%-%/%.]+),?") do table.insert(t, dir) end table.sort(t) return t end function M.rtp() local rtp = M.get_rtp() M.pp(rtp) end function M.show_path() return vim.fn.join(vim.opt.path:get(), "\n") end function M.show_tagfiles() return vim.fn.join(vim.opt.tags:get(), "\n") end function M.buf_count() local buffers = vim.api.nvim_list_bufs() M.dump(buffers) end function M.reload_config() local loaded = {} for k in pairs(package.loaded) do table.insert(loaded, k) package.loaded[k] = nil end table.sort(loaded) for k, v in ipairs(loaded) do print(k, v) require(v) end end function M.dumptotmpfile(tbl, filename) local tmpname = "/Users/egresh/tmp/" if filename == nil then tmpname = tmpname .. "neovim_dump_file.txt" else tmpname = tmpname .. filename end vim.api.nvim_command("silent! redir! > " .. tmpname) vim.o.more = false M.dump(tbl) vim.api.nvim_command("redir END") vim.o.more = true vim.api.nvim_command('call nvim_input("<cr>")') end function M.get_package_path() local path = {} for _, v in ipairs(vim.fn.split(package.path, ";")) do table.insert(path, v) end return path end function M.neovim_config_files() local scan = require("plenary.scandir") local lua_files = scan.scan_dir(vim.fn.stdpath("config") .. "/lua") local after_files = scan.scan_dir(vim.fn.stdpath("config") .. "/after") local files = {} local dirs = { lua_files, after_files } for _, tbl in ipairs(dirs) do for _, file in ipairs(tbl) do table.insert(files, file) end end table.insert(files, 1, vim.env.MYVIMRC) return files end function M.package_grep(name) local matched = {} for k, _ in pairs(package.loaded) do if k:match(name) then table.insert(matched, k) end end return matched end function M.winenter() local filetype = vim.api.nvim_buf_get_option(0, "filetype") if filetype == "toggleterm" then vim.cmd("IndentBlanklineDisable") return elseif filetype ~= "NvimTree" then vim.wo.number = true vim.wo.relativenumber = true end vim.wo.signcolumn = "auto:9" end function M.load_plugin(plugin) print("The plugin is: " .. plugin) local status_ok, error = pcall(require(tostring(plugin))) if not status_ok then print("ERROR: unable to load plugin " .. error) else print("Plugin Loaded: " .. plugin) end end function M.format_lualine() local bufname = vim.api.nvim_buf_get_name(0) if not string.find(bufname, "toggleterm") then return { tostring(math.random(10)) } -- return { -- { "filetype", icon_only = true }, -- { "filename", file_status = true, path = 0 }, -- } end local program_name local term_number -- expected output... -- "term://~/.local/share/neovimwip/nvim//45438:htop;#toggleterm#2" _, _, program_name, term_number = string.find(bufname, "%d+:([%w]+);#toggleterm#(%d+)") print("the program name is " .. program_name) if program_name == nil then return "" end return { string.format("Term: %s # %d", program_name, term_number) } end function ConfigureTerminal() vim.wo.relativenumber = false vim.wo.number = false vim.cmd("highlight! link TermCursor Cursor") vim.cmd("highlight! TermCursorNC guibg=red guifg=white ctermbg=1 ctermfg=15") vim.cmd('exec "normal i"') end return M
22.722727
91
0.594919
2c7fe10dfd7aec3712aa1a82382025dfac5d27ae
10,808
py
Python
src/ui/sharp_editor.py
vincent-lg/cocomud
a2c174f15b024d834266e0bef3d0404732d34a47
[ "BSD-3-Clause" ]
3
2016-10-13T01:39:20.000Z
2017-08-01T15:58:12.000Z
src/ui/sharp_editor.py
vincent-lg/cocomud
a2c174f15b024d834266e0bef3d0404732d34a47
[ "BSD-3-Clause" ]
11
2018-11-27T16:13:11.000Z
2019-12-29T11:34:54.000Z
src/ui/sharp_editor.py
vlegoff/cocomud
a2c174f15b024d834266e0bef3d0404732d34a47
[ "BSD-3-Clause" ]
2
2017-08-02T19:36:57.000Z
2017-10-21T04:13:34.000Z
# Copyright (c) 2016-2020, LE GOFF Vincent # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of ytranslate nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """This file contains the SharpEditor class.""" import wx from ytranslate.tools import t class SharpEditor(wx.Panel): """SharpScript editor panel. This panel can be added into dialogs that have to support SharpScript editing. On the top, at the left of the panel, is an optional text field to edit SharpScript directly. To the right is a list of functions already associated with this entry. After buttons to edit and remove is a second list with new functions to be added. """ def __init__(self, dialog, engine, sharp, object, attribute, text=False, escape=False): """Creates the frame. Arguments: dialog: the parent dialog. engine: the game engine. sharp: the SharpScript engine. object: the object containing the field to be edited. attribute: the attribute's name of the object to edit. text (default to False): should a text field be added? escape (default to false): the #send calls are removed. If the SharpEditor is to modify a trigger, for instance, particularly its "action" attribute, the trigger is the object and "action" is the attribute's name. """ wx.Panel.__init__(self, dialog) self.engine = engine self.sharp_engine = sharp self.object = object self.attribute = attribute self.text = None self.escape = escape script = getattr(self.object, self.attribute) self.functions = sorted(sharp.functions.values(), key=lambda function: function.name) self.functions = [f for f in self.functions if f.description] # Shape sizer = wx.BoxSizer(wx.VERTICAL) top = wx.BoxSizer(wx.HORIZONTAL) bottom = wx.BoxSizer(wx.HORIZONTAL) self.SetSizer(sizer) # Insert a text field if text: s_text = wx.BoxSizer(wx.VERTICAL) l_text = wx.StaticText(self, label=t("common.action")) t_text = wx.TextCtrl(self, value=script, style=wx.TE_MULTILINE) self.text = t_text s_text.Add(l_text) s_text.Add(t_text) top.Add(s_text) # List of current functions self.existing = wx.ListCtrl(self, style=wx.LC_REPORT | wx.LC_SINGLE_SEL) self.existing.InsertColumn(0, t("common.action")) # Buttons self.edit = wx.Button(self, label=t("ui.button.edit")) self.remove = wx.Button(self, label=t("ui.button.remove")) top.Add(self.existing) top.Add(self.edit) top.Add(self.remove) self.populate_existing() # List of functions self.choices = wx.ListCtrl(self, style=wx.LC_REPORT | wx.LC_SINGLE_SEL) self.choices.InsertColumn(0, t("common.description")) self.populate_list() bottom.Add(self.choices) # Add button self.add = wx.Button(self, label=t("ui.button.add_action")) bottom.Add(self.add) # Event binding self.add.Bind(wx.EVT_BUTTON, self.OnAdd) self.edit.Bind(wx.EVT_BUTTON, self.OnEdit) self.remove.Bind(wx.EVT_BUTTON, self.OnRemove) def populate_list(self): """Populate the list with function names.""" self.choices.DeleteAllItems() for function in self.functions: try: description = t("sharp.{name}.description".format( name=function.name)) except ValueError: description = function.description self.choices.Append((description, )) self.choices.Select(0) self.choices.Focus(0) def populate_existing(self): """Populate the list with existing functions.""" self.existing.DeleteAllItems() script = getattr(self.object, self.attribute) if self.text: self.text.SetValue(script) lines = self.sharp_engine.format(script, return_str=False) for line in lines: self.existing.Append((line, )) self.existing.Select(0) self.existing.Focus(0) if lines: self.existing.Enable() self.edit.Enable() self.remove.Enable() else: self.existing.Disable() self.edit.Disable() self.remove.Disable() def OnAdd(self, e): """The 'add' button is pressed.""" index = self.choices.GetFirstSelected() try: function = self.functions[index] except IndexError: wx.MessageBox(t("ui.message.sharp.missing"), t("ui.message.error"), wx.OK | wx.ICON_ERROR) else: dialog = AddEditFunctionDialog(self.engine, self.sharp_engine, function, self.object, self.attribute, escape=self.escape) dialog.ShowModal() self.populate_existing() self.existing.SetFocus() def OnEdit(self, e): """The 'edit' button is pressed.""" index = self.existing.GetFirstSelected() script = getattr(self.object, self.attribute) lines = self.sharp_engine.format(script, return_str=False) try: line = lines[index] except IndexError: wx.MessageBox(t("ui.message.sharp.missing"), t("ui.message.error"), wx.OK | wx.ICON_ERROR) else: name, arguments, flags = self.sharp_engine.extract_arguments(line) function = self.sharp_engine.functions[name[1:]] dialog = AddEditFunctionDialog(self.engine, self.sharp_engine, function, self.object, self.attribute, index, escape=self.escape) dialog.ShowModal() self.populate_existing() self.existing.SetFocus() def OnRemove(self, e): """The 'remove' button is pressed.""" index = self.existing.GetFirstSelected() script = getattr(self.object, self.attribute) lines = self.sharp_engine.format(script, return_str=False) try: line = lines[index] except IndexError: wx.MessageBox(t("ui.message.sharp.missing"), t("ui.message.error"), wx.OK | wx.ICON_ERROR) else: value = wx.MessageBox(t("ui.message.sharp.remove", line=line), t("ui.alert.confirm"), wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if value == wx.YES: del lines[index] content = "\n".join(lines) setattr(self.object, self.attribute, content) self.populate_existing() self.existing.SetFocus() class AddEditFunctionDialog(wx.Dialog): """Add or edit a function.""" def __init__(self, engine, sharp_engine, function, object, attribute, index=-1, escape=False): super(AddEditFunctionDialog, self).__init__(None, title=t("common.action")) self.engine = engine self.sharp_engine = sharp_engine self.world = sharp_engine.world self.function = function self.object = object self.attribute = attribute self.index = index self.escape = escape arguments = [] flags = {} if index >= 0: script = getattr(self.object, self.attribute) lines = self.sharp_engine.format(script, return_str=False) line = lines[index] function, arguments, flags = self.sharp_engine.extract_arguments(line) # Dialog sizer = wx.BoxSizer(wx.VERTICAL) self.top = wx.BoxSizer(wx.VERTICAL) buttons = self.CreateButtonSizer(wx.OK | wx.CANCEL) self.SetSizer(sizer) # Add the function-specific configuration sizer.Add(self.top) self.function.display(self, *arguments, **flags) sizer.Add(buttons) # Event binding self.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.ID_OK) self.Bind(wx.EVT_BUTTON, self.OnCancel, id=wx.ID_CANCEL) def OnOk(self, e): """The 'OK' button is pressed.""" arguments = self.function.complete(self) if arguments is not None: function = "#" + self.function.name lines = (((function, ) + arguments), ) line = self.sharp_engine.format(lines) # Add to the entire content lines = self.sharp_engine.format(getattr(self.object, self.attribute), return_str=False) if self.index >= 0: lines[self.index] = line else: lines.append(line) if self.escape: print("escaping lines") for i, line in enumerate(lines): if line.startswith("#send "): line = line[6:] if line.startswith("{"): line = line[1:-1] lines[i] = line content = "\n".join(lines) setattr(self.object, self.attribute, content) self.Destroy() def OnCancel(self, e): """The 'cancel' button is pressed.""" self.Destroy()
37.397924
82
0.60668
ff9ce37db58fa2fd241426394039e7e8d2bbd785
229
py
Python
src/sentry/utils/validators.py
tobetterman/sentry
fe85d3aee19dcdbfdd27921c4fb04529fc995a79
[ "BSD-3-Clause" ]
1
2017-08-30T06:55:25.000Z
2017-08-30T06:55:25.000Z
src/sentry/utils/validators.py
tobetterman/sentry
fe85d3aee19dcdbfdd27921c4fb04529fc995a79
[ "BSD-3-Clause" ]
null
null
null
src/sentry/utils/validators.py
tobetterman/sentry
fe85d3aee19dcdbfdd27921c4fb04529fc995a79
[ "BSD-3-Clause" ]
null
null
null
from __future__ import absolute_import from ipaddr import IPAddress def validate_ip(value, required=True): if not required and not value: return # will raise a ValueError IPAddress(value) return value
17.615385
38
0.724891
faf0bd873a940267c6e1381804abd42cba023ef7
896
java
Java
src/com/innowhere/jnieasy/core/impl/common/classdesc/model/JavaClassAsNativeDirectFieldCallbackImpl.java
jmarranz/jnieasy
e295b23ee7418c8e412b025b957e64ceaba40fac
[ "Apache-2.0" ]
8
2016-10-26T13:20:20.000Z
2021-05-12T05:00:56.000Z
src/com/innowhere/jnieasy/core/impl/common/classdesc/model/JavaClassAsNativeDirectFieldCallbackImpl.java
jmarranz/jnieasy
e295b23ee7418c8e412b025b957e64ceaba40fac
[ "Apache-2.0" ]
null
null
null
src/com/innowhere/jnieasy/core/impl/common/classdesc/model/JavaClassAsNativeDirectFieldCallbackImpl.java
jmarranz/jnieasy
e295b23ee7418c8e412b025b957e64ceaba40fac
[ "Apache-2.0" ]
1
2022-01-14T03:18:08.000Z
2022-01-14T03:18:08.000Z
/* * JavaClassAsNativeDirectFieldCallbackImpl.java * * Created on 7 de julio de 2005, 18:10 * * To change this template, choose Tools | Options and locate the template under * the Source Creation and Management node. Right-click the template and choose * Open. You can then make changes to the template in the Source Editor. */ package com.innowhere.jnieasy.core.impl.common.classdesc.model; import com.innowhere.jnieasy.core.impl.common.classtype.model.natobj.method.ClassTypeNativeDirectFieldCallbackImpl; /** * * @author jmarranz */ public abstract class JavaClassAsNativeDirectFieldCallbackImpl extends JavaClassAsNativeDirectCallbackImpl { /** * Creates a new instance of JavaClassAsNativeDirectFieldCallbackImpl */ public JavaClassAsNativeDirectFieldCallbackImpl(ClassTypeNativeDirectFieldCallbackImpl classType) { super(classType); } }
29.866667
115
0.773438
ddab10d42d9dca54728bc9722d4a8d89c2c62a23
2,931
java
Java
lucene/core/src/test/org/apache/lucene/util/TestFrequencyTrackingRingBuffer.java
ywelsch/lucene
5207aae5279757bfd0d40f4995576d2af7d4ea31
[ "Apache-2.0" ]
1
2022-02-21T07:11:57.000Z
2022-02-21T07:11:57.000Z
lucene/core/src/test/org/apache/lucene/util/TestFrequencyTrackingRingBuffer.java
ywelsch/lucene
5207aae5279757bfd0d40f4995576d2af7d4ea31
[ "Apache-2.0" ]
14
2021-12-01T09:17:38.000Z
2021-12-22T12:20:41.000Z
lucene/core/src/test/org/apache/lucene/util/TestFrequencyTrackingRingBuffer.java
ywelsch/lucene
5207aae5279757bfd0d40f4995576d2af7d4ea31
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TestFrequencyTrackingRingBuffer extends LuceneTestCase { private static void assertBuffer( FrequencyTrackingRingBuffer buffer, int maxSize, int sentinel, List<Integer> items) { final List<Integer> recentItems; if (items.size() <= maxSize) { recentItems = new ArrayList<>(); for (int i = items.size(); i < maxSize; ++i) { recentItems.add(sentinel); } recentItems.addAll(items); } else { recentItems = items.subList(items.size() - maxSize, items.size()); } final Map<Integer, Integer> expectedFrequencies = new HashMap<Integer, Integer>(); for (Integer item : recentItems) { final Integer freq = expectedFrequencies.get(item); if (freq == null) { expectedFrequencies.put(item, 1); } else { expectedFrequencies.put(item, freq + 1); } } assertEquals(expectedFrequencies, buffer.asFrequencyMap()); } public void test() { final int iterations = atLeast(100); for (int i = 0; i < iterations; ++i) { final int maxSize = 2 + random().nextInt(100); final int numitems = random().nextInt(5000); final int maxitem = 1 + random().nextInt(100); List<Integer> items = new ArrayList<>(); final int sentinel = random().nextInt(200); FrequencyTrackingRingBuffer buffer = new FrequencyTrackingRingBuffer(maxSize, sentinel); for (int j = 0; j < numitems; ++j) { final Integer item = random().nextInt(maxitem); items.add(item); buffer.add(item); } assertBuffer(buffer, maxSize, sentinel, items); } } public void testRamBytesUsed() { final int maxSize = 2 + random().nextInt(10000); final int sentinel = random().nextInt(); FrequencyTrackingRingBuffer buffer = new FrequencyTrackingRingBuffer(maxSize, sentinel); for (int i = 0; i < 10000; ++i) { buffer.add(random().nextInt()); } assertEquals(RamUsageTester.ramUsed(buffer), buffer.ramBytesUsed()); } }
37.576923
94
0.679973
eb7881674c0efbab3ab2bf27efe26d8959cbbfa6
34
sql
SQL
backend/core/src/test/resources/schema.sql
manoj-savantly/sprout-platform
78d8aecdcb854ed2b278968014934a837149dbdb
[ "Apache-2.0" ]
13
2020-06-19T14:31:14.000Z
2022-02-21T17:37:12.000Z
backend/core/src/test/resources/schema.sql
manoj-savantly/sprout-platform
78d8aecdcb854ed2b278968014934a837149dbdb
[ "Apache-2.0" ]
114
2020-08-03T20:37:53.000Z
2022-03-30T19:05:36.000Z
backend/core/src/test/resources/schema.sql
manoj-savantly/sprout-platform
78d8aecdcb854ed2b278968014934a837149dbdb
[ "Apache-2.0" ]
4
2018-06-10T18:33:14.000Z
2021-07-25T14:18:52.000Z
CREATE SCHEMA IF NOT EXISTS SPROUT
34
34
0.852941
fb1efd27a1fab3a7d9597e39ab0e9e355a9a77c7
1,705
kt
Kotlin
golem-core/srcjvm/golem/platformsupport/repr.kt
venabled/golem
2f285908ff7adbb4e4b9df038255f33bb671bf18
[ "Apache-2.0" ]
1
2018-01-20T02:16:59.000Z
2018-01-20T02:16:59.000Z
golem-core/srcjvm/golem/platformsupport/repr.kt
venabled/golem
2f285908ff7adbb4e4b9df038255f33bb671bf18
[ "Apache-2.0" ]
null
null
null
golem-core/srcjvm/golem/platformsupport/repr.kt
venabled/golem
2f285908ff7adbb4e4b9df038255f33bb671bf18
[ "Apache-2.0" ]
1
2018-10-24T20:54:10.000Z
2018-10-24T20:54:10.000Z
package golem.platformsupport import golem.* import golem.matrix.* import java.io.ByteArrayOutputStream import java.io.PrintStream import java.text.DecimalFormat fun <T> repr(mat: Matrix<T>): String { val fmtString = when (matFormat) { SHORT_NUMBER -> "0.00##" LONG_NUMBER -> "0.00############" VERY_LONG_NUMBER -> "0.00#############################" SCIENTIFIC_NUMBER -> "0.00#####E0#" SCIENTIFIC_LONG_NUMBER -> "0.00############E0#" SCIENTIFIC_VERY_LONG_NUMBER -> "0.00############################E0#" else -> "0.00############" } var formatter = DecimalFormat(fmtString) val bstream = ByteArrayOutputStream() val pstream = PrintStream(bstream) mat.run { val lens = IntArray(numCols()) eachIndexed { row, col, element -> val formatted = formatter.format(element) if (lens[col] < formatted.length) lens[col] = formatted.length } var indent = "mat[" eachIndexed { row, col, element -> var formatted = formatter.format(element) if (col == 0) { if (row > 0) pstream.append("end\n") pstream.append(indent) indent = " " } if (formatted[0] != '-') formatted = " " + formatted pstream.append(formatted) if (col != lens.size - 1) pstream.append(",") (-1..(lens[col] - formatted.length)).forEach { pstream.append(" ") } } pstream.append("]") } return bstream.toString() }
32.788462
80
0.48563
4f29a44bad5c5701c273f5a2e7a7998c64c09dfd
2,632
rb
Ruby
test/graphql/ban_user_mutation_test.rb
cleancoindev/dao-server
3d44bb631affb96aad4e6ff855a76cff47f17638
[ "BSD-3-Clause" ]
2
2020-01-17T12:08:15.000Z
2020-04-27T13:40:08.000Z
test/graphql/ban_user_mutation_test.rb
cleancoindev/dao-server
3d44bb631affb96aad4e6ff855a76cff47f17638
[ "BSD-3-Clause" ]
8
2019-07-30T08:34:34.000Z
2021-09-27T22:15:09.000Z
test/graphql/ban_user_mutation_test.rb
DigixGlobal/dao-server
3d44bb631affb96aad4e6ff855a76cff47f17638
[ "BSD-3-Clause" ]
5
2019-08-17T15:50:38.000Z
2020-03-01T08:28:52.000Z
# frozen_string_literal: true require 'test_helper' class BanUserMutationTest < ActiveSupport::TestCase QUERY = <<~EOS mutation($id: String!) { banUser(input: { id: $id}) { user { id canComment isBanned } errors { field message } } } EOS test 'ban user mutation should work' do forum_admin = create(:forum_admin_user) user = create(:user, is_banned: false) result = DaoServerSchema.execute( QUERY, context: { current_user: forum_admin }, variables: { id: user.id.to_s } ) assert_nil result['errors'], 'should work and have no errors' assert_empty result['data']['banUser']['errors'], 'should have no errors' data = result['data']['banUser']['user'] assert data['isBanned'], 'should be banned' refute data['canComment'], 'should not be able to comment' repeat_result = DaoServerSchema.execute( QUERY, context: { current_user: forum_admin }, variables: { id: user.id.to_s } ) assert_not_empty repeat_result['data']['banUser']['errors'], 'should not allow banning of the same user' end test 'should fail safely' do forum_admin = create(:forum_admin_user) empty_result = DaoServerSchema.execute( QUERY, context: { current_user: forum_admin }, variables: {} ) assert_not_empty empty_result['errors'], 'should fail with empty data' not_found_result = DaoServerSchema.execute( QUERY, context: { current_user: forum_admin }, variables: { id: 'NON_EXISTENT_ID' } ) assert_not_empty not_found_result['data']['banUser']['errors'], 'should fail if user is not found' auth_result = DaoServerSchema.execute( QUERY, context: {}, variables: { id: forum_admin.id.to_s } ) assert_not_empty auth_result['errors'], 'should fail without a current user' unauthorized_result = DaoServerSchema.execute( QUERY, context: { current_user: create(:user) }, variables: { id: forum_admin.id.to_s } ) assert_not_empty unauthorized_result['errors'], 'should fail without a normal user' invalid_result = DaoServerSchema.execute( QUERY, context: { current_user: forum_admin }, variables: { id: forum_admin.id.to_s } ) assert_not_empty invalid_result['data']['banUser']['errors'], 'should fail to ban self ' end end
25.553398
67
0.594985
a7dc451a410b1cc73c2082b3f52d7d51ca728ad3
9,349
css
CSS
public/common/css/colors/blue.css
oluwadunsin/Investment-site-Codeigniter4
922190d7a46e69e2cd733c7a961fd29ba5210a2a
[ "MIT" ]
null
null
null
public/common/css/colors/blue.css
oluwadunsin/Investment-site-Codeigniter4
922190d7a46e69e2cd733c7a961fd29ba5210a2a
[ "MIT" ]
null
null
null
public/common/css/colors/blue.css
oluwadunsin/Investment-site-Codeigniter4
922190d7a46e69e2cd733c7a961fd29ba5210a2a
[ "MIT" ]
null
null
null
/* default color: #0888f0 */ /*Background*/ mark, .item-promotion-h5, .latest-blog-post-date, .owl-item.synced .process-item, .process-2-container .process-item span.order, .section-dark-ourStatistics .ourStatis-item-2 .circle-statis, .nav-tabs-arc-product > li.active > a, .nav-tabs-arc-product > li.active > a:hover, .nav-tabs-arc-product > li.active > a:focus, .arc-tabs-style-2 .nav-tabs, .arc-tabs-style-2 .nav-tabs > li.active > a, .arc-tabs-style-2 .nav-tabs > li.active > a:hover, .arc-tabs-style-3 .nav-tabs > li.active > a:focus, .arc-tabs-style-3 .nav-tabs > li.active > a, .arc-tabs-style-3 .nav-tabs > li.active > a:hover, .arc-tabs-style-3 .nav-tabs > li.active > a:focus, .arc-tabs-style-4 .nav-tabs > li.active:before, .accordion-process .panel-default > .panel-heading .panel-title > a, .accordion-process .panel-default > .panel-heading .panel-title > a.collapsed:hover, .accordion-style-light .panel-default > .panel-heading .panel-title > a, .accordion-style-light .panel-default > .panel-heading .panel-title > a.collapsed,.process-2-container .process-2-item span.order, .mobile-menu .open + a, .process-item:hover, .arc-sorting div.fancy-select ul.options li.selected, .arc-sorting div.fancy-select ul.options li:hover, ul.social-dark li a:hover, .accordion-style-light .panel-default > .panel-heading .panel-title > a.collapsed:hover, .footer-mobile-menu ul.social li a:hover, .mobile-menu > li:hover > a, .mobile-menu li li:hover a, ul.list-link-footer li:hover:before, ul.social li a:hover, ul.social li.active a, #to-the-top:hover, .btn-border-ghost:hover, .btn-main-color, .language div.fancy-select ul.options li.selected, .language div.fancy-select ul.options li:hover, .navi-level-1 > li .navi-level-2, span.mini-cart-counter, .navi-level-1.hover-style-2 li a span:before, .navi-level-1.hover-style-3 li a span:before, .navi-level-1.hover-style-5 li a span:before, .main-sidebar .tagcloud a:hover { background-color: #0888f0; } /*Fade background 95%*/ .project-terms a h4:before, .project-terms a.current h4:before, .project-terms-2 a h4:before, .layer-1, .blog-terms a h4:before, .blog-terms a:hover h4:before, .blog-terms a.current h4:before, .main-sidebar .promotion .promotionText, .element-item:hover .project-info, .project-terms a:hover h4:before, .project-terms-2 a.current h4:before, .project-terms-2 a:hover h4:before, .projectContainer .element-item:hover .project-info, .ourteamGrid-warp .team-grid-item:hover .grid-team-overlay, ul.social-dark li a:hover, #overlay, .modal-search { background-color: rgba(8, 136, 240, 0.95); } /*Color*/ .icon-promotion, .owl-partner-warp .prev-partners, .owl-partner-warp .next-partners, .owl-partner-warp .next-partners2, .owl-partner-warp .prev-partners2, .prev-team, .next-team, .sub-header a, .process-item, .slide-services .prev-detail-services, .slide-services .next-detail-services, ul.countdown li span, .header-mobile-menu .mm-toggle, .copyright a, .navi-level-1.dot-seperator > li > a:after, .navi-level-1.line-separator > li > a:after, .navi-level-1.circle-separator > li > a:after, .navi-level-1.square-separator > li > a:after, .navi-level-1.plus-separator > li > a:after, .navi-level-1.strip-separator > li > a:after, .navi-level-1.hover-style-4 li a:hover, .header-v6 .right-header a:hover, .sub-header .sub-header-content .breadcrumb-arc a, .navi-level-1 > li .navi-level-2 li a:hover, .btn-dark-color:hover, .btn-dark-color:focus { color: #0888f0; } /*Color On Hover*/ .chooseus-item:hover h4, .portfolio-grid-1-warp .portfolio-grid-1-container .element-item .project-info h4:hover, .portfolio-grid-1-warp .portfolio-grid-1-container .element-item .project-info a.cateProject:hover, .portfolio-grid-2-warp .portfolio-grid-2-container .element-item .project-info h4:hover, .portfolio-grid-2-warp .portfolio-grid-2-container .element-item .project-info a.cateProject:hover, .portfolio-grid-3-warp .portfolio-grid-3-container .element-item .project-info h4:hover, .portfolio-grid-3-warp .portfolio-grid-3-container .element-item .project-info a.cateProject:hover, .arr-pj-container a:hover, .latest-blog-post-description h3:hover, .latest-blog-post-data a:hover, .blog-inline .latest-blog-post-description h3:hover, ul.style-list-circle li a:hover, .footer-data .tags p a:hover, .footer-data .share p a:hover, .comment-respond .logged-in-as a:hover, .comment-respond .btn-submit:hover, .comments-area li.comment .comment-content .reply a:hover, .comments-area li.comment .comment-content cite a:hover, .comments-area li.comment .comment-content span a:hover, .widget .search-form .search-submit:hover, .main-sidebar li:hover::before, .main-sidebar li:hover a, .owl-partner-warp .prev-partners:hover, .owl-partner-warp .next-partners:hover, .owl-partner-warp .next-partners2:hover, .owl-partner-warp .prev-partners2:hover, .item-team .social-member a:hover, .prev-team:hover, .next-team:hover, .view-more:hover, .sidebar-left ul.sidebar-style-2 li:hover a, .sidebar-right ul.sidebar-style-2 li:hover a, .sidebar-right ul.sidebar-style-2 li.active a, .form-search-home-6 .btn-search-home-6:hover, .product-info h3:hover, .sub-header a:hover, table.shop_table .product-name a:hover, .item-team .member-info .social-member a:hover { color: #066cbf; } /*Stroke*/ .svg-triangle-icon, .hexagon { stroke: #0888f0; } /*Border*/ .avatar-testimonials img, .avatar-testimonials-1-columns-v2 img, .large-avatar img, .blog-1-column-warp .customNavigation .btn:hover, .form-subcribe input.form-control:focus, .owl-item.synced .process-item, .form-subcribe textarea.form-control:focus, .owl-item.synced .process-item, .accordion-style-light .panel-default > .panel-heading .panel-title > a,.item-team .member-info, .form-subcribe form input:focus, .tagcloud a:hover, .testimonial-1-column-v2-warp .customNavigation .btn:hover, .process-item:hover, .form-contact input.form-control:focus, .sidebar-left ul.sidebar-style-2 li:hover, .sidebar-right ul.sidebar-style-2 li:hover, .sidebar-left ul.sidebar-style-2 li.active, .sidebar-right ul.sidebar-style-2 li.active, .btn-coupon:hover, .form-contact-arc input.form-control:focus, .form-contact-arc textarea.form-control:focus, .newsletter-comingsoon .newsletter-email:focus, ul.countdown li, .tab-arc .nav-tabs > li.active > a, .tab-arc .nav-tabs > li.active > a:hover, .tab-arc .nav-tabs > li.active > a:focus, .arc-tabs-style-2 .nav-tabs, .arc-tabs-style-2 .nav-tabs > li.active > a, .arc-tabs-style-2 .nav-tabs > li.active > a:hover, .arc-tabs-style-2 .nav-tabs > li.active > a:focus, .form-subcrible-footer .btn-subcrible-footer:hover, ul.list-link-footer li:hover a, .form-subcrible-footer input.form-control:focus, .form-subcrible-footer input.form-control:hover { border-color: #0888f0; } .copyright a:hover { color: #066cbf; } .btn-border:hover, .btn-border:focus { border-color: #0888f0; color: #0888f0; } /*update*/ .portfolio-grid-1-warp .portfolio-grid-1-container .element-item .project-info h4,.portfolio-grid-2-warp .portfolio-grid-2-container .element-item .project-info h4, .portfolio-grid-2-warp .portfolio-grid-2-container .element-item .project-info h4 { color:#333; } ul.social li.active a,.sidebar-left ul.sidebar-style-2 li.active a,.sidebar-left ul.sidebar-style-2 li.active a,.sidebar-left ul.sidebar-style-2 li:hover a, ul.social li a:hover,.navi-level-1 > li .navi-level-2 li a,.projectContainer .element-item .project-info h4, .projectContainer .element-item .project-info a.cateProject:hover,.box-content-overlay-3 h2, .item-promotion-h5 .promotion-h5-text-box h3, .item-promotion-h5 a, .owl-item.synced .process-item, .ourteamGrid-warp .team-grid-item:hover .grid-team-overlay h5, .ourteamGrid-warp .team-grid-item:hover .grid-team-overlay p, .ourteamGrid-warp .team-grid-item:hover .grid-team-overlay p.description-member, .ourteamGrid-warp .team-grid-item .social-member a, .ourteamGrid-warp .team-grid-item:hover .grid-team-overlay p.member-job, .main-sidebar .promotion .promotionText, .main-sidebar .tagcloud a:hover, .section-dark-ourStatistics .ourStatis-item-2 .circle-statis,.section-dark-ourStatistics .ourStatis-item-2 .circle-statis h6, .projectContainer .element-item .project-info h4,.projectContainer .element-item .project-info a.cateProject,.process-2-container .process-2-item span.order, .navi-level-1.sub-navi > li a:hover, .main-sidebar ul li:hover a, .btn-main-color,.latest-blog-post-date,.latest-blog-post-date span.month,span.mini-cart-counter,mark,.box-content-overlay-3 .btn-dark-color,.project-terms a.current h4,.project-terms a:hover h4, .navi-level-1 > li .navi-level-2 li a:hover,.nav-tabs-arc-product > li.active > a,.nav-tabs-arc-product > li.active > a:focus,.nav-tabs-arc-product > li.active > a:hover, .btn-main-color,.navi-level-1 > li .navi-level-2 li a,.navi-level-1 > li .navi-level-2 li a:hover,.projectContainer .element-item .project-info h4,.projectContainer .element-item .project-info a.cateProject, .project-terms a h4:hover,.language div.fancy-select ul.options li.selected,.language div.fancy-select ul.options li:hover,span.mini-cart-counter, .btn-main-color:hover { color:#fff; }
40.297414
208
0.728634
4d48c67a76adff4b154fa661b70e7c1dfc491439
1,256
cs
C#
TRProject/Assets/Scripts/InteractionHandler.cs
mtaulty/Techorama2018
792c1774dcf9c73dd99d83f5132798e4f026328c
[ "MIT" ]
1
2018-06-03T09:46:05.000Z
2018-06-03T09:46:05.000Z
TRProject/Assets/Scripts/InteractionHandler.cs
mtaulty/Techorama2018
792c1774dcf9c73dd99d83f5132798e4f026328c
[ "MIT" ]
null
null
null
TRProject/Assets/Scripts/InteractionHandler.cs
mtaulty/Techorama2018
792c1774dcf9c73dd99d83f5132798e4f026328c
[ "MIT" ]
null
null
null
using HoloToolkit.Unity.InputModule; using HoloToolkit.Unity.InputModule.Utilities.Interactions; using UnityEngine; public class InteractionHandler : MonoBehaviour, IFocusable, IInputClickHandler { public void OnInputClicked(InputClickedEventData eventData) { if (!this.tapped) { this.tapped = true; // switch on gravity and let it fall. var rigidBody = this.gameObject.AddComponent<Rigidbody>(); rigidBody.freezeRotation = true; this.waitingToLand = true; } } void OnCollisionStay(Collision collision) { if (this.waitingToLand && (collision.relativeVelocity.magnitude < 0.01f)) { this.waitingToLand = false; Destroy(this.gameObject.GetComponent<Rigidbody>()); this.gameObject.GetComponent<TwoHandManipulatable>().enabled = true; } } public void OnFocusEnter() { if (!this.tapped) { this.gameObject.transform.localScale *= 1.2f; } } public void OnFocusExit() { if (!this.tapped) { this.gameObject.transform.localScale = Vector3.one; } } bool waitingToLand; bool tapped = false; }
27.304348
81
0.609873
38b9bad83a1f4d3d47bd4e5182b69d29d6df8007
4,675
php
PHP
resources/views/about.blade.php
adilJabbar/Cricket
3145c860863f0fdf5100ce303586673d9ca293e3
[ "MIT" ]
null
null
null
resources/views/about.blade.php
adilJabbar/Cricket
3145c860863f0fdf5100ce303586673d9ca293e3
[ "MIT" ]
null
null
null
resources/views/about.blade.php
adilJabbar/Cricket
3145c860863f0fdf5100ce303586673d9ca293e3
[ "MIT" ]
null
null
null
@extends('layouts.master') @section('content') <!-- Content ================================================== --> <div class="site-wrapper site-layout--default"> <main class="site-content" id="wrapper"> <div class="site-content__inner"> <div class="site-content__holder"> <figure class="page-thumbnail page-thumbnail--default"> @if ($about) <img class="page-bg-logo" src="{{ asset('storage/' . $about->side_logo_1) }}" alt=""> @else @endif <!-- Decoration --> <div class="ncr-page-decor"> <div class="ncr-page-decor__layer-1"> <div class="ncr-page-decor__layer-bg"></div> </div> <div class="ncr-page-decor__layer-2"></div> <div class="ncr-page-decor__layer-3"> <div class="ncr-page-decor__layer-bg"></div> </div> <div class="ncr-page-decor__layer-4"></div> <div class="ncr-page-decor__layer-5"></div> <div class="ncr-page-decor__layer-6"></div> </div> <!-- Decoration / End --> </figure> <h1 class="page-title h3">{{ $about->title ?? '' }}</h1> <div class="page-content"> <p> {!! $about->description ?? '' !!} </p> <div class="spacer"></div> @if ($about) <div style="background-image: url('{{ asset('storage/' . $about->image) }}'); height:50%"> @else @endif </div> <div class="spacer"></div> <h4>{{ $about->why_us_title ?? '' }}</h4> <div class="spacer"></div> <p> {!! $about->why_us_description ?? '' !!} </p> <div class="spacer"></div> <div class="row"> <div class="col-md-4 mb-4 mb-md-0"> <div class="counter"> <div class="counter__icon counter__icon--left"> @if ($about) <img src="{{ asset('storage/' . $about->logo_1) }}" width="35px"> @else @endif </div> <div class="counter__number">{{ $about->logo_number_1 ?? '' }}</div> <div class="counter__label">{{ $about->logo_name_1 ?? '' }}</div> </div> </div> <div class="col-md-4 mb-4 mb-md-0"> <div class="counter"> <div class="counter__icon counter__icon--left"> @if ($about) <img src="{{ asset('storage/' . $about->logo_2) }}" width="35px"> @else @endif </div> <div class="counter__number">{{ $about->logo_number_2 ?? '' }}</div> <div class="counter__label">{{ $about->logo_name_2 ?? '' }}</div> </div> </div> <div class="col-md-4"> <div class="counter"> <div class="counter__icon counter__icon--left"> @if ($about) <img src="{{ asset('storage/' . $about->logo_3) }}" width="35px"> @else @endif </div> <div class="counter__number">{{ $about->logo_number_3 ?? '' }}</div> <div class="counter__label">{{ $about->logo_name_3 ?? '' }}</div> </div> </div> </div> </div> </div> </div> </main> </div> @endsection
50.268817
118
0.327273
af2cbdbbe4882761d720cae084fa35170a30bb6b
2,959
py
Python
MsdnApiExtractor/spiders/ApiSpider.py
Varriount/MsdnApiExtractor
fdf0c271f0117507820cce5579f9c59f38f2c558
[ "MIT" ]
2
2015-06-21T01:44:39.000Z
2022-03-31T08:03:57.000Z
MsdnApiExtractor/spiders/ApiSpider.py
Varriount/MsdnApiExtractor
fdf0c271f0117507820cce5579f9c59f38f2c558
[ "MIT" ]
3
2015-07-13T08:02:43.000Z
2015-07-15T15:37:04.000Z
MsdnApiExtractor/spiders/ApiSpider.py
Varriount/MsdnApiExtractor
fdf0c271f0117507820cce5579f9c59f38f2c558
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import re from MsdnApiExtractor.items import ApiEntry from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors import LinkExtractor from string import maketrans from collections import OrderedDict # Misc constants strip_chars = u"\n\t\xa0" # Domain constants msdn_domain = "msdn.microsoft.com" msdn_url = 'https://' + msdn_domain + '/en-us/library/windows/desktop' msdn_filter = '[eE][nN]-[uU][sS]/library/windows' deny_filter = [ 'login\.live\.com', 'dev\.windows\.com', 'community/add' ] # XPath Constants common_entry_xpath = "//div[@id='mainSection']/table/tr[{0}]" table_xpath = "//div[@id='mainSection']//table" code_xpath = ("//div[@id='code-snippet-1']" "//div[contains(@id,'CodeSnippetContainerCode')]" "/div/pre//text()") def xpath_extract(resp, path): return ( unicode(u''.join(resp.xpath(path).extract())) .strip(strip_chars) .replace(u"\xa0", u' ') .replace(u"\t", u' ') .replace(u"\x00", u'') ) class ApiSpider(CrawlSpider): name = "ApiSpider" allowed_domains = [msdn_domain] start_urls = ( msdn_url + '/dn933214.aspx', msdn_url + '/ff818516.aspx', ) rules = [ Rule( LinkExtractor(allow=msdn_filter, deny=deny_filter), callback='parse_entry', process_links='process_links', follow=True ) ] processed_links = set() def process_links(self, links): i = 0 while i < len(links): link = links[i] processed_url = re.sub('\(v=.*?\)', '', link.url) if link.url in self.processed_links: del(links[i]) else: link.url = processed_url self.processed_links.add(processed_url) i += 1 return links def parse_entry(self, response): result = ApiEntry() # Set up result result['url'] = response.url result['code'] = xpath_extract(response, code_xpath) result['tables'] = [] result['metadata'] = OrderedDict() # Get table data tables = response.xpath(table_xpath) for table in tables[0:-1]: rows = table.xpath("tr") table_header = xpath_extract(rows[:1], './/th//text()') entries = [] for row in rows[1:]: entry = xpath_extract(row, 'td[1]//text()') entry = entry.replace("\n", " ") entries.append(entry) result['tables'].append((table_header, entries)) # Get metadata location_list = tables[-1:].xpath("tr") for row in location_list: name = xpath_extract(row, 'th//text()').lower().replace("\n", "") value = xpath_extract(row, 'td//text()').replace("\n", "") result['metadata'][name] = value return result
29.29703
77
0.562014
4bac771afa8d439dc79051fcccb0b4dfa4b5c3df
6,382
hpp
C++
libs/libnet/inc/net/post_mortem.hpp
mbits-os/JiraDesktop
eb9b66b9c11b2fba1079f03a6f90aea425ce6138
[ "MIT" ]
null
null
null
libs/libnet/inc/net/post_mortem.hpp
mbits-os/JiraDesktop
eb9b66b9c11b2fba1079f03a6f90aea425ce6138
[ "MIT" ]
null
null
null
libs/libnet/inc/net/post_mortem.hpp
mbits-os/JiraDesktop
eb9b66b9c11b2fba1079f03a6f90aea425ce6138
[ "MIT" ]
null
null
null
/* * Copyright (C) 2013 midnightBITS * * 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. */ #ifndef __POST_MORTEM_HPP__ #define __POST_MORTEM_HPP__ #include <thread> #include <net/filesystem.hpp> #ifdef WIN32 # include <windows.h> # pragma warning(push) // warning C4091: 'typedef ': ignored on left of 'tagSTRUCT' when no variable is declared # pragma warning(disable: 4091) # include <DbgHelp.h> # pragma warning(pop) # pragma comment(lib, "dbghelp.lib") #endif namespace pm { #ifdef WIN32 class Win32PostMortemSupport { static fs::path tempDir() { auto size = GetTempPath(0, nullptr); if (!size) return fs::current_path(); ++size; std::unique_ptr<WCHAR[]> path{ new WCHAR[size] }; if (!GetTempPath(size, path.get())) return fs::current_path(); return path.get(); } static std::wstring buildPath() { auto temp = tempDir(); temp /= "MiniDump.dmp"; temp.make_preferred(); return temp.wstring(); } static LPCWSTR dumpPath() { static std::wstring path = buildPath(); return path.c_str(); } static void Write(_EXCEPTION_POINTERS* ep) { auto mdt = static_cast<MINIDUMP_TYPE>( MiniDumpWithDataSegs | MiniDumpWithFullMemory | MiniDumpWithFullMemoryInfo | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithProcessThreadData | MiniDumpWithUnloadedModules ); auto file = CreateFileW(dumpPath(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (file && file != INVALID_HANDLE_VALUE) { wchar_t buffer[2048]; MINIDUMP_EXCEPTION_INFORMATION mei{ GetCurrentThreadId(), ep, TRUE }; if (!MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), file, mdt, ep ? &mei : nullptr, nullptr, nullptr)) { auto err = GetLastError(); CloseHandle(file); DeleteFileW(dumpPath()); if (!err) { swprintf_s(buffer, L"An error occured, but memory was not dumped due to unknown reason."); } else { swprintf_s(buffer, L"An error occured, but memory was not dumped due to error %08x.", err); } } else { CloseHandle(file); if (ep) { swprintf_s(buffer, L"An error %08x occured at %p (thread %u), memory dumped to:\n\n%s", ep->ExceptionRecord->ExceptionCode, ep->ExceptionRecord->ExceptionAddress, GetCurrentThreadId(), dumpPath()); } else { swprintf_s(buffer, L"An unkown error occured, memory dumped to:\n\n%s", dumpPath()); } } buffer[__countof(buffer) - 1] = 0; MessageBoxW(nullptr, buffer, L"This program perfomed illegal operation", MB_ICONINFORMATION); } TerminateProcess(GetCurrentProcess(), 1); } public: template <class Fn, class... Args> static void Run(Fn&& fn, Args&&... args) { (void)dumpPath(); // build file path now for any OOM later... _EXCEPTION_POINTERS* exception = nullptr; __try { fn(std::forward<Args>(args)...); } __except (exception = GetExceptionInformation(), EXCEPTION_EXECUTE_HANDLER) { Write(exception); } } }; template <class Fn, class... Args> inline void PostMortemSupport(Fn&& fn, Args&&... args) { Win32PostMortemSupport::Run(std::forward<Fn>(fn), std::forward<Args>(args)...); } #else // !WIN32 template <class Fn, class... Args> inline void PostMortemSupport(Fn&& fn, Args&&... args) { fn(std::forward<Args>(args)...); } #endif // WIN32 template <class Fn, class... Args> inline std::thread thread(Fn&& fn, Args&&... args) { return std::thread{ PostMortemSupport<Fn, Args...>, std::forward<Fn>(fn), std::forward<Args>(args)... }; } }; #define BEGIN_MSG_MAP_POSTMORTEM(theClass) \ public: \ BOOL ProcessWindowMessage(_In_ HWND hWnd, _In_ UINT uMsg, _In_ WPARAM wParam, \ _In_ LPARAM lParam, _Inout_ LRESULT& lResult, _In_ DWORD dwMsgMapID = 0) \ { \ BOOL retVal = FALSE; \ pm::PostMortemSupport([&, this] () mutable { \ auto innerLambda = [&, this] () mutable -> BOOL { \ BOOL bHandled = TRUE; \ (hWnd); \ (uMsg); \ (wParam); \ (lParam); \ (lResult); \ (bHandled); \ switch (dwMsgMapID) \ { \ case 0: #define END_MSG_MAP_POSTMORTEM() \ break; \ default: \ ATLTRACE(static_cast<int>(ATL::atlTraceWindowing), 0, _T("Invalid message map ID (%i)\n"), dwMsgMapID); \ ATLASSERT(FALSE); \ break; \ } \ return FALSE; \ }; \ retVal = innerLambda(); \ }); \ return retVal; \ } #endif // __POST_MORTEM_HPP__
35.455556
135
0.579912
43c07b03b435060b928e25fc3bb468e7cd6c1dee
185
lua
Lua
santosrp/gamemode/maps/rp_newexton2/properties/warehouse_northern_petrol.lua
xbread/Open-Source-Santos
300ca73c99c23acd6ba560392e6980dc776a87e8
[ "MIT" ]
11
2018-10-19T09:29:24.000Z
2022-02-25T04:18:44.000Z
santosrp/gamemode/maps/rp_newexton2/properties/warehouse_northern_petrol.lua
Heyter/Open-Source-Santos
e8ba51b1f548dab4c0590290e9a42f1565de24b3
[ "MIT" ]
11
2018-09-22T17:35:29.000Z
2022-03-07T20:59:02.000Z
santosrp/gamemode/maps/rp_newexton2/properties/warehouse_northern_petrol.lua
Heyter/Open-Source-Santos
e8ba51b1f548dab4c0590290e9a42f1565de24b3
[ "MIT" ]
7
2019-02-07T16:24:14.000Z
2021-06-02T13:59:51.000Z
local Prop = {} Prop.Name = "Northern Petrol" Prop.Cat = "Warehouse" Prop.Price = 850 Prop.Doors = { Vector( -6445.000000, 6211.000000, -13898.000000 ), } GM.Property:Register( Prop )
20.555556
52
0.686486
e2db49207a3d7e41fec922e1563363045e6b20db
2,257
py
Python
framework/class_builder.py
petrovp/networkx-related
ebe7053e032b527ebaa9565f96ba91145de3fd50
[ "BSD-3-Clause" ]
null
null
null
framework/class_builder.py
petrovp/networkx-related
ebe7053e032b527ebaa9565f96ba91145de3fd50
[ "BSD-3-Clause" ]
null
null
null
framework/class_builder.py
petrovp/networkx-related
ebe7053e032b527ebaa9565f96ba91145de3fd50
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright (C) 2018 by # Marta Grobelna <[email protected]> # Petre Petrov <[email protected]> # Rudi Floren <[email protected]> # Tobias Winkler <[email protected]> # All rights reserved. # BSD license. # # Authors: Marta Grobelna <[email protected]> # Petre Petrov <[email protected]> # Rudi Floren <[email protected]> # Tobias Winkler <[email protected]> from framework.generic_classes import * class CombinatorialClassBuilder: """ Interface for objects that build combinatorial classes. # TODO implement size checking mechanism. """ def zero_atom(self): raise NotImplementedError def l_atom(self): raise NotImplementedError def u_atom(self): raise NotImplementedError def product(self, lhs, rhs): """ Parameters ---------- lhs: CombinatorialClass rhs: CombinatorialClass """ raise NotImplementedError def set(self, elements): """ Parameters ---------- elements: list of CombinatorialClass """ raise NotImplementedError class DefaultBuilder(CombinatorialClassBuilder): """ Builds the generic objects. """ def zero_atom(self): return ZeroAtomClass() def l_atom(self): return LAtomClass() def u_atom(self): return UAtomClass() def product(self, lhs, rhs): return ProdClass(lhs, rhs) def set(self, elements): return SetClass(elements) class DummyBuilder(CombinatorialClassBuilder): """ Builds dummy objects. """ def zero_atom(self): return DummyClass() def l_atom(self): return DummyClass(l_size=1) def u_atom(self): return DummyClass(u_size=1) def product(self, lhs, rhs): l_size = lhs.l_size + rhs.l_size u_size = lhs.u_size + rhs.u_size return DummyClass(l_size, u_size) def set(self, elements): l_size = 0 u_size = 0 for dummy in elements: l_size += dummy.l_size u_size += dummy.u_size return DummyClass(l_size, u_size)
22.57
59
0.610102
4f3bcb85ac5ca12f9745f8936c2960dc09406673
1,868
kt
Kotlin
security/src/main/java/com/twilio/security/storage/EncryptedStorage.kt
ranand-twilio/twilio-verify-android
c5e04dd815132e0563eb71575c230742b1bb51bf
[ "Apache-2.0" ]
5
2020-10-22T21:40:46.000Z
2022-01-15T18:48:44.000Z
security/src/main/java/com/twilio/security/storage/EncryptedStorage.kt
ranand-twilio/twilio-verify-android
c5e04dd815132e0563eb71575c230742b1bb51bf
[ "Apache-2.0" ]
51
2020-10-15T17:41:45.000Z
2022-02-14T18:32:26.000Z
security/src/main/java/com/twilio/security/storage/EncryptedStorage.kt
ranand-twilio/twilio-verify-android
c5e04dd815132e0563eb71575c230742b1bb51bf
[ "Apache-2.0" ]
1
2021-06-10T18:33:45.000Z
2021-06-10T18:33:45.000Z
/* * Copyright (c) 2020 Twilio Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twilio.security.storage import android.content.SharedPreferences import com.twilio.security.crypto.key.template.AESGCMNoPaddingCipherTemplate import com.twilio.security.crypto.keyManager import com.twilio.security.storage.key.SecretKeyCipher import com.twilio.security.storage.key.SecretKeyProvider import kotlin.reflect.KClass interface EncryptedStorage { val secretKeyProvider: SecretKeyProvider val serializer: Serializer @Throws(StorageException::class) fun <T : Any> put( key: String, value: T ) @Throws(StorageException::class) fun <T : Any> get( key: String, kClass: KClass<T> ): T @Throws(StorageException::class) fun <T : Any> getAll( kClass: KClass<T> ): List<T> fun contains(key: String): Boolean fun remove(key: String) fun clear() } fun encryptedPreferences( storageAlias: String, sharedPreferences: SharedPreferences ): EncryptedStorage { val keyManager = keyManager() val secretKeyProvider = SecretKeyCipher( AESGCMNoPaddingCipherTemplate(storageAlias), keyManager ) if (!keyManager.contains(storageAlias) && sharedPreferences.all.isEmpty()) { secretKeyProvider.create() } return EncryptedPreferences(secretKeyProvider, sharedPreferences, DefaultSerializer()) }
28.738462
88
0.752141
c961bcf1399419ac6a981d8f1d110b46555d68f5
1,126
ts
TypeScript
node_modules/jsdoc-type-pratt-parser/dist/src/Parser.d.ts
jswny/corde-action
ea5919921086ef4d8acfa1f4681935ccb1ac1461
[ "MIT" ]
1
2021-11-08T20:46:20.000Z
2021-11-08T20:46:20.000Z
node_modules/jsdoc-type-pratt-parser/dist/src/Parser.d.ts
jswny/corde-action
ea5919921086ef4d8acfa1f4681935ccb1ac1461
[ "MIT" ]
null
null
null
node_modules/jsdoc-type-pratt-parser/dist/src/Parser.d.ts
jswny/corde-action
ea5919921086ef4d8acfa1f4681935ccb1ac1461
[ "MIT" ]
1
2021-11-08T17:38:44.000Z
2021-11-08T17:38:44.000Z
import { Token, TokenType } from './lexer/Token'; import { Lexer } from './lexer/Lexer'; import { InfixParslet, PrefixParslet } from './parslets/Parslet'; import { Grammar } from './grammars/Grammar'; import { Precedence } from './Precedence'; import { TerminalResult } from './result/TerminalResult'; import { IntermediateResult } from './result/IntermediateResult'; export declare class Parser { private readonly prefixParslets; private readonly infixParslets; private readonly lexer; constructor(grammar: Grammar, lexer?: Lexer); parseText(text: string): TerminalResult; getPrefixParslet(): PrefixParslet | undefined; getInfixParslet(precedence: Precedence): InfixParslet | undefined; canParseType(): boolean; parseType(precedence: Precedence): TerminalResult; parseIntermediateType(precedence: Precedence): IntermediateResult; parseInfixIntermediateType(result: IntermediateResult, precedence: Precedence): IntermediateResult; consume(type: TokenType): boolean; getToken(): Token; peekToken(): Token; previousToken(): Token | undefined; getLexer(): Lexer; }
43.307692
103
0.739787
af58e142e51307836e1cb2e7404429bfedc68ec9
3,792
py
Python
tests/test_api.py
obytes/fastql
3e77f92d0330e0ea4ffd5383691283529699ca79
[ "MIT" ]
32
2021-10-05T15:39:22.000Z
2022-02-03T17:06:18.000Z
tests/test_api.py
obytes/FastQL
3e77f92d0330e0ea4ffd5383691283529699ca79
[ "MIT" ]
11
2022-02-04T04:00:58.000Z
2022-03-28T15:22:46.000Z
tests/test_api.py
obytes/fastql
3e77f92d0330e0ea4ffd5383691283529699ca79
[ "MIT" ]
4
2021-11-16T15:57:31.000Z
2021-12-19T07:36:46.000Z
import asyncio import json from threading import Timer import httpx import pytest from ariadne.asgi import GQL_CONNECTION_INIT, GQL_START from websockets import connect my_storage = {} @pytest.fixture def storage(): return my_storage @pytest.mark.asyncio async def test_create_user(host, credentials, storage): query = """ mutation createUser($email: String!, $password: String!) { createUser(email: $email, password: $password) { id, errors } } """ async with httpx.AsyncClient() as client: response = await client.post( f"http://{host}/", timeout=60, json={"query": query, "variables": credentials}, ) json_response = json.loads(response.text) assert ("errors" in json_response) == False assert json_response["data"]["createUser"]["id"] is not None storage["user_id"] = json_response["data"]["createUser"]["id"] @pytest.mark.asyncio async def test_auth_user(host, credentials, storage): query = """ mutation authUser($email: String!, $password: String!) { createToken(email: $email, password: $password) { errors, token } } """ async with httpx.AsyncClient() as client: response = await client.post( f"http://{host}/", headers={}, timeout=60, json={"query": query, "variables": credentials}, ) json_response = json.loads(response.text) assert ("errors" in json_response) == False assert json_response["data"]["createToken"]["token"] is not None storage["token"] = json_response["data"]["createToken"]["token"] async def create_blog(host, storage): query = """ mutation createblog($title: String!, $description: String!) { createblog(title: $title, description: $description) { errors id } } """ token = storage["token"] async with httpx.AsyncClient() as client: response = await client.post( f"http://{host}/", headers={"Authorization": f"Bearer {token}"}, timeout=60, json={ "query": query, "variables": {"title": "title", "description": "description"}, }, ) json_response = json.loads(response.text) assert ("errors" in json_response) == True assert json_response["data"]["createblog"]["id"] is not None @pytest.mark.asyncio async def test_create_blog(server, host, storage): await create_blog(host, storage) @pytest.mark.asyncio async def test_subscription(server, host, storage): query = """ subscription reviewblog($token: String!) { reviewblog(token: $token) { errors id } } """ variables = {"token": f'Bearer {storage["token"]}'} ws = await connect(f"ws://{host}/", subprotocols=["graphql-ws"]) await ws.send(json.dumps({"type": GQL_CONNECTION_INIT})) await ws.send( json.dumps( {"type": GQL_START, "payload": {"query": query, "variables": variables},} ) ) received = await ws.recv() assert received == '{"type": "connection_ack"}' def delay_create_blog(server, host): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(create_blog(server, host)) timer = Timer(1.0, delay_create_blog, (server, host, storage)) timer.start() received = await ws.recv() await ws.close() json_response = json.loads(received) assert ("errors" in json_response) == False assert json_response["payload"]["data"]["reviewblog"]["id"] is not None
29.169231
85
0.587553
c6bea70eea7fead0d039bc6e72b3f5a81aef7939
1,157
py
Python
TinaBot/error_handler.py
skielred/TinaBot
eec9eaef0221f28f8f93ae152628c2a85321365d
[ "MIT" ]
null
null
null
TinaBot/error_handler.py
skielred/TinaBot
eec9eaef0221f28f8f93ae152628c2a85321365d
[ "MIT" ]
null
null
null
TinaBot/error_handler.py
skielred/TinaBot
eec9eaef0221f28f8f93ae152628c2a85321365d
[ "MIT" ]
null
null
null
import traceback from discord.ext import commands from .errors import * class CommandErrorHandler: def __init__(self, bot): self.bot = bot async def on_command_error(self, error, context): ignored = (commands.CommandNotFound) public = (commands.BadArgument, commands.MissingRequiredArgument, PriviledgeException) if hasattr(context.command, 'on_error') or isinstance(error, ignored): return # await self.bot.send_message(context.message.channel, '{0.mention}, {1}\n{2}'.format(context.message.author, error, traceback.format_tb(error.__traceback__))) if isinstance(error, public): await self.bot.send_message(context.message.channel, '{0.mention}, {1}'.format(context.message.author, error)) else: msg = '' for tb in traceback.format_tb(error.__traceback__): msg += tb await self.bot.send_message(self.bot.get_channel(self.bot.warnings), '{0} provoked an error on {1} :warning:\n{2}\n```\n{3}```'.format(context.message.author, context.message.server, error, msg)) await self.bot.doubt(context.message)
42.851852
207
0.6707
1a9b164144c0ca65f1b48ccaa731ed610ff29b65
2,691
py
Python
temporalis/time.py
builderjer/temporalis
2088080597b4aedd7ec83f3c5b8a726c29ab9b08
[ "Apache-2.0" ]
2
2020-04-10T12:35:49.000Z
2020-04-10T20:01:53.000Z
temporalis/time.py
JarbasAl/pyweather
9a623a4a1acbbdc8c1957028d6e428b94a2e89aa
[ "Apache-2.0" ]
1
2021-08-09T12:58:26.000Z
2021-08-09T12:58:26.000Z
temporalis/time.py
JarbasAl/pyweather
9a623a4a1acbbdc8c1957028d6e428b94a2e89aa
[ "Apache-2.0" ]
1
2021-04-27T16:47:23.000Z
2021-04-27T16:47:23.000Z
from pendulum import now def now_utc(): """ Retrieve the current datetime in UTC Returns: (datetime): The current datetime in Universal Time, aka GMT """ return now() def month_to_int(month): if isinstance(month, int) or isinstance(month, float): return int(month) if isinstance(month, str): month = month.lower() if month.startswith("jan"): return 1 if month.startswith("feb"): return 2 if month.startswith("mar"): return 3 if month.startswith("apr"): return 4 if month.startswith("may"): return 5 if month.startswith("jun"): return 6 if month.startswith("jul"): return 7 if month.startswith("aug"): return 8 if month.startswith("sep"): return 9 if month.startswith("oct"): return 10 if month.startswith("nov"): return 11 if month.startswith("dec"): return 12 return None def weekday_to_int(weekday): if isinstance(weekday, int) or isinstance(weekday, float): return int(weekday) if isinstance(weekday, str): weekday = weekday.lower() if weekday.startswith("mon"): return 0 if weekday.startswith("tue"): return 1 if weekday.startswith("wed"): return 2 if weekday.startswith("thu"): return 3 if weekday.startswith("fri"): return 4 if weekday.startswith("sat"): return 5 if weekday.startswith("sun"): return 6 return None def int_to_month(month): if month == 1: return "january" if month == 2: return "february" if month == 3: return "march" if month == 4: return "april" if month == 5: return "may" if month == 6: return "june" if month == 7: return "july" if month == 8: return "august" if month == 9: return "september" if month == 10: return "october" if month == 11: return "november" if month == 12: return "december" return str(month) def int_to_weekday(weekday): if weekday == 0: return "monday" if weekday == 1: return "tuesday" if weekday == 2: return "wednesday" if weekday == 3: return "thursday" if weekday == 4: return "friday" if weekday == 5: return "saturday" if weekday == 6: return "sunday" return str(weekday) def in_utc(date): return date.in_timezone("UTC")
23.4
67
0.531773
38cd37639d8d09e1f48c2172de30d9903c95868b
297
php
PHP
Facades/Bundles.php
wenlng/laravel5-bundles
c3155b6ffd92d561dcdbf46267f0d6fa3719088d
[ "MIT" ]
null
null
null
Facades/Bundles.php
wenlng/laravel5-bundles
c3155b6ffd92d561dcdbf46267f0d6fa3719088d
[ "MIT" ]
null
null
null
Facades/Bundles.php
wenlng/laravel5-bundles
c3155b6ffd92d561dcdbf46267f0d6fa3719088d
[ "MIT" ]
null
null
null
<?php /** * Author: liangwengao * Email: [email protected] * Date: 2017-01-25 * Time: 12:57 */ namespace Awen\Bundles\Facades; use Illuminate\Support\Facades\Facade; class Bundles extends Facade { protected static function getFacadeAccessor() { return 'bundles'; } }
14.85
49
0.673401
e6a01973ceccc7c39f7905024a47fc130f264736
688
swift
Swift
RoasterTests/Mocks/MockUserDefaults.swift
dasdom/phazel
a876be0ef96b0dfb8619876e389ab4eb2025044d
[ "MIT" ]
13
2017-01-25T19:51:51.000Z
2017-07-01T17:32:13.000Z
RoasterTests/Mocks/MockUserDefaults.swift
dasdom/phazel
a876be0ef96b0dfb8619876e389ab4eb2025044d
[ "MIT" ]
3
2017-03-05T23:38:56.000Z
2017-04-05T08:30:00.000Z
RoasterTests/Mocks/MockUserDefaults.swift
dasdom/phazel
a876be0ef96b0dfb8619876e389ab4eb2025044d
[ "MIT" ]
null
null
null
// Created by dasdom on 14/02/2017. // Copyright © 2017 dasdom. All rights reserved. // import UIKit class MockUserDefaults: UserDefaults { private var values: [String:Any] = [:] init(values: [String:Any] = [:]) { self.values = values super.init(suiteName: nil)! } override func string(forKey defaultName: String) -> String? { return values[defaultName] as? String } override func set(_ value: Any?, forKey defaultName: String) { if let value = value { values[defaultName] = value } } override func value(forKey key: String) -> Any? { return values[key] } }
22.193548
66
0.578488
5f5e1b3ee012a2b734263dd32a47e5ef0d362f1c
284
rake
Ruby
mrbgem.rake
matsumotory/mruby-pointer
8b46506dfdb12a79a16be1d1172ef3c9324bef96
[ "MIT" ]
2
2017-02-20T09:43:08.000Z
2018-10-17T02:29:52.000Z
mrbgem.rake
matsumotory/mruby-pointer
8b46506dfdb12a79a16be1d1172ef3c9324bef96
[ "MIT" ]
null
null
null
mrbgem.rake
matsumotory/mruby-pointer
8b46506dfdb12a79a16be1d1172ef3c9324bef96
[ "MIT" ]
null
null
null
MRuby::Gem::Specification.new('mruby-pointer') do |spec| spec.license = 'MIT' spec.authors = 'MATSUMOTO Ryosuke' spec.version = '0.0.1' spec.summary = 'Provide mruby C API which shared pointer between two mrb_states' spec.mruby.cc.include_paths << "#{spec.dir}/include" end
35.5
82
0.714789
059df1ccc63fccb4bf18b4ef223debb5f545b72c
951
py
Python
tests/perf.py
wemoloh/frepr
a0a33efdc6df53301966c9240e5f534ac6bf1426
[ "BSD-3-Clause" ]
1
2019-05-31T20:38:45.000Z
2019-05-31T20:38:45.000Z
tests/perf.py
wemoloh/frepr
a0a33efdc6df53301966c9240e5f534ac6bf1426
[ "BSD-3-Clause" ]
null
null
null
tests/perf.py
wemoloh/frepr
a0a33efdc6df53301966c9240e5f534ac6bf1426
[ "BSD-3-Clause" ]
null
null
null
from __future__ import print_function from random import getrandbits from struct import pack, unpack from timeit import timeit import frepr def random_double(): return unpack('d', pack('Q', getrandbits(64)))[0] values = [] def repr_all(): for value in values: repr(value) def main(nvalues, nruns): print('Creating {} random double values...'.format(nvalues)) global values values = [random_double() for _ in range(nvalues)] print('Applying native repr() to all values {} times...'.format(nruns)) t_repr = timeit(repr_all, number=nruns) print('{} seconds'.format(t_repr)) print('Applying new repr() to all values {} times...'.format(nruns)) frepr.install() t_frepr = timeit(repr_all, number=nruns) frepr.uninstall() print('{} seconds'.format(t_frepr)) print('New repr() is {} times faster.'.format(t_repr / t_frepr)) if __name__ == '__main__': main(1000000, 10)
25.702703
75
0.664564
f0121a4d41c75461c4e5b71b2a303685378cb247
40
sh
Shell
nodewebkit/linux32/run.sh
andrew-lis/Game5
4dfd7703b88232633f68114315bb6e666912a260
[ "MIT" ]
null
null
null
nodewebkit/linux32/run.sh
andrew-lis/Game5
4dfd7703b88232633f68114315bb6e666912a260
[ "MIT" ]
null
null
null
nodewebkit/linux32/run.sh
andrew-lis/Game5
4dfd7703b88232633f68114315bb6e666912a260
[ "MIT" ]
null
null
null
chmod +x game5 LD_LIBRARY_PATH=. ./game5
20
25
0.775
dd8626b81bb46df2415249a84ddcd9a02145f424
427
java
Java
chapter_004/src/main/java/ru/job4j/map/User.java
dvamedveda/b.savelev
68243893ca56846daad539c5b75dfc380736a824
[ "Apache-2.0" ]
1
2018-02-28T18:08:53.000Z
2018-02-28T18:08:53.000Z
chapter_004/src/main/java/ru/job4j/map/User.java
dvamedveda/b.savelev
68243893ca56846daad539c5b75dfc380736a824
[ "Apache-2.0" ]
4
2021-04-28T08:25:14.000Z
2022-02-16T01:14:14.000Z
chapter_004/src/main/java/ru/job4j/map/User.java
dvamedveda/b.savelev
68243893ca56846daad539c5b75dfc380736a824
[ "Apache-2.0" ]
null
null
null
package ru.job4j.map; import java.util.Calendar; /** * Класс описывающий модель User. * * @author - b.savelev (mailto: [email protected]) * @version - 1.0 * @since 0.1 */ public class User { String name; int children; Calendar birthday; public User(String name, int children, Calendar birthday) { this.name = name; this.children = children; this.birthday = birthday; } }
19.409091
63
0.63466
3b77dc0843d27df3c3c6ea3291246fe94a7e9634
1,592
sh
Shell
system_report.sh
bitrise-adam/android-ndk-lts
f85e2c3434a93b418600d8b6df6d4fdffabf549d
[ "MIT" ]
null
null
null
system_report.sh
bitrise-adam/android-ndk-lts
f85e2c3434a93b418600d8b6df6d4fdffabf549d
[ "MIT" ]
null
null
null
system_report.sh
bitrise-adam/android-ndk-lts
f85e2c3434a93b418600d8b6df6d4fdffabf549d
[ "MIT" ]
null
null
null
#!/bin/bash set -e if [[ "${IS_IGNORE_ERRORS}" == "true" ]] ; then echo " (i) Ignore Errors: enabled" set +e else echo " (i) Ignore Errors: disabled" fi echo echo '#' echo '# This System Report was generated by: https://github.com/bitrise-docker/android-ndk-lts/blob/master/system_report.sh' echo '# Pull Requests are welcome!' echo '#' echo echo echo "--- Bitrise CLI tool versions" ver_line="$(bitrise --version)" ; echo "* bitrise: $ver_line" ver_line="$(/root/.bitrise/tools/stepman --version)" ; echo "* stepman: $ver_line" ver_line="$(/root/.bitrise/tools/envman --version)" ; echo "* envman: $ver_line" if [[ "$CI" == "false" ]] ; then set +e fi ver_line="$(bitrise-bridge --version || echo 'No bitrise-bridge installed'))" ; echo "* bitrise-bridge: $ver_line" set -e echo "========================================" echo echo echo "=== Revision / ID ======================" if [ -z "$BITRISE_DOCKER_REV_NUMBER_ANDROID_NDK" ] ; then echo " [!] No BITRISE_DOCKER_REV_NUMBER_ANDROID_NDK defined!" exit 1 fi echo "* BITRISE_DOCKER_REV_NUMBER_ANDROID_NDK: $BITRISE_DOCKER_REV_NUMBER_ANDROID_NDK" if [ -z "$BITRISE_DOCKER_REV_NUMBER_ANDROID_NDK_LTS" ] ; then echo " [!] No BITRISE_DOCKER_REV_NUMBER_ANDROID_NDK_LTS defined!" exit 1 fi echo "* BITRISE_DOCKER_REV_NUMBER_ANDROID_NDK_LTS: $BITRISE_DOCKER_REV_NUMBER_ANDROID_NDK_LTS" echo "========================================" echo echo "$ cat ${ANDROID_NDK_HOME}/source.properties" cat "${ANDROID_NDK_HOME}/source.properties" echo echo "$ tree -L 2 /opt/android-ndk" tree -L 2 /opt/android-ndk echo
30.615385
124
0.663317
143d07c5c94cb07e41b5f98f7f311b022952daff
436
ts
TypeScript
chaincode/global/src/edp/EDP.ts
chrc/star
7fcfa22408c77a0e34883e608a797c230e09c2a3
[ "Apache-2.0" ]
9
2020-11-23T08:36:13.000Z
2021-03-21T20:58:56.000Z
chaincode/global/src/edp/EDP.ts
chrc/star
7fcfa22408c77a0e34883e608a797c230e09c2a3
[ "Apache-2.0" ]
null
null
null
chaincode/global/src/edp/EDP.ts
chrc/star
7fcfa22408c77a0e34883e608a797c230e09c2a3
[ "Apache-2.0" ]
12
2021-02-23T09:36:23.000Z
2021-04-27T12:53:49.000Z
/** * Copyright (C) 2020, RTE (http://www.rte-france.com) * SPDX-License-Identifier: Apache-2.0 */ import {AssetType} from '../../enums/AssetType'; export class EDP { public assetType: AssetType; public constructor( public edpRegisteredResourceId: string, public siteId: string, public edpRegisteredResourceName: string, public edpRegisteredResourceMrid: string ) { this.assetType = AssetType.EDP; } }
20.761905
54
0.699541
5795afbcb115460868f9d095b85c06cd0b690bfa
689
go
Go
ch4/ex4.5/main.go
Galser/goobook
020f0e2859549f0d1ce3d62b372426909b4bf2ef
[ "MIT" ]
null
null
null
ch4/ex4.5/main.go
Galser/goobook
020f0e2859549f0d1ce3d62b372426909b4bf2ef
[ "MIT" ]
null
null
null
ch4/ex4.5/main.go
Galser/goobook
020f0e2859549f0d1ce3d62b372426909b4bf2ef
[ "MIT" ]
null
null
null
// Function that eliminates adjacent elements // in-place from []string package main import "fmt" func RemoveDups(strings []string) []string { for i := 0; i < len(strings)-1; i++ { if strings[i] == strings[i+1] { copy(strings[i:], strings[i+1:]) strings = strings[:len(strings)-1] } } // strings iteration return strings } func main() { s := []string{"one", "two", "two", ".", ".", "three", "four", "four", "three"} fmt.Printf("String before cleaning : %v \n", s) s = RemoveDups(s) fmt.Printf("String after cleaning : %v \n", s) /* output : String before cleaning : [one two two . . three four four three] String after cleaning : [one two . three four three] */ }
24.607143
79
0.622642
be56af93b0ede0d00947809b859046b85132d145
139
rb
Ruby
db/migrate/20140511014501_add_views_to_media_content.rb
TorinAsakura/bride
d3472abfcefcbe845870a157d6ba3a5eb01ab873
[ "BSD-3-Clause" ]
null
null
null
db/migrate/20140511014501_add_views_to_media_content.rb
TorinAsakura/bride
d3472abfcefcbe845870a157d6ba3a5eb01ab873
[ "BSD-3-Clause" ]
null
null
null
db/migrate/20140511014501_add_views_to_media_content.rb
TorinAsakura/bride
d3472abfcefcbe845870a157d6ba3a5eb01ab873
[ "BSD-3-Clause" ]
null
null
null
class AddViewsToMediaContent < ActiveRecord::Migration def change add_column :media_contents, :views, :integer, default: 0 end end
23.166667
60
0.769784
1a3419d9a369b6178fead14fb5ba597f06af7429
991
py
Python
ExerciciosPythonMundo1/ex017.py
JamesonSantos/Curso-Python-Exercicios-Praticados
1fc1618ccf8692a552bac408e842dea8328e4e1a
[ "MIT" ]
null
null
null
ExerciciosPythonMundo1/ex017.py
JamesonSantos/Curso-Python-Exercicios-Praticados
1fc1618ccf8692a552bac408e842dea8328e4e1a
[ "MIT" ]
null
null
null
ExerciciosPythonMundo1/ex017.py
JamesonSantos/Curso-Python-Exercicios-Praticados
1fc1618ccf8692a552bac408e842dea8328e4e1a
[ "MIT" ]
null
null
null
''' n1 = float(input('Comprimento do cateto oposto: ')) n2 = float(input('Comprimento do cateto adjacente: ')) hi = (n1 ** 2 + n2 ** 2) ** (1/2) print('A hipotenusa vai medir {:.2f}'.format(hi)) ''' ''' from math import hypot n1 = float(input('Comprimento do cateto oposto: ')) n2 = float(input('Comprimento do cateto adjacente: ')) hi = hypot(n1, n2) print('A hipotenusa vai medir {:.2f}'.format(hi)) ''' ''' import math n1 = float(input('Comprimento do cateto oposto: ')) n2 = float(input('Comprimento do cateto adjacente: ')) hi = math.hypot(n1, n2) print('A hipotenusa vai medir {:.2f}'.format(hi)) ''' '''import math n1 = float(input('Comprimento do cateto oposto: ')) n2 = float(input('Comprimento do cateto adjacente: ')) print('A hipotenusa vai medir {:.2f}'.format(math.hypot(n1, n2)))''' from math import hypot n1 = float(input('Comprimento do cateto oposto: ')) n2 = float(input('Comprimento do cateto adjacente: ')) print('A hipotenusa vai medir {:.2f}'.format(hypot(n1,n2)))
30.96875
68
0.673058
3855dd3025ee8cce0057af0b512a9afe125a1954
387
cs
C#
OplachiSe/OplachiSe.Web/Models/VoteModels/NewVoteViewModel.cs
Popgeorgiev/OplachiSe
3e3de6df344ab0e5bbc4e2d72d0734f1079f1329
[ "MIT" ]
1
2015-03-25T10:22:53.000Z
2015-03-25T10:22:53.000Z
OplachiSe/OplachiSe.Web/Models/VoteModels/NewVoteViewModel.cs
Popgeorgiev/OplachiSe
3e3de6df344ab0e5bbc4e2d72d0734f1079f1329
[ "MIT" ]
null
null
null
OplachiSe/OplachiSe.Web/Models/VoteModels/NewVoteViewModel.cs
Popgeorgiev/OplachiSe
3e3de6df344ab0e5bbc4e2d72d0734f1079f1329
[ "MIT" ]
null
null
null
 namespace OplachiSe.Web.Models.VoteModels { using OplachiSe.Models; using OplachiSe.Web.Infrastructure.Mapping; using System.ComponentModel.DataAnnotations; public class NewVoteViewModel : IMapFrom<Vote> { [Display(Name = "Оценка")] [UIHint("VoteResult")] public int Value { get; set; } public int ComplainId { get; set; } } }
22.764706
50
0.651163
9316503274446133a846bec037a88c166edf785f
8,361
swift
Swift
Example/Example/ViewController.swift
pixlee/pixlee-ios
4516ec317c262122a4b17cd017280fe1274dfd1d
[ "MIT" ]
null
null
null
Example/Example/ViewController.swift
pixlee/pixlee-ios
4516ec317c262122a4b17cd017280fe1274dfd1d
[ "MIT" ]
21
2020-02-17T16:43:56.000Z
2022-01-18T22:39:58.000Z
Example/Example/ViewController.swift
pixlee/pixlee-ios
4516ec317c262122a4b17cd017280fe1274dfd1d
[ "MIT" ]
null
null
null
// // ViewController.swift // Example // // Created by Csaba Toth on 2020. 01. 08.. // Copyright © 2020. Pixlee. All rights reserved. // import PixleeSDK import UIKit class ViewController: UIViewController { var pixleeCredentials:PixleeCredentials = PixleeCredentials() var album: PXLAlbum? @IBOutlet var versionLabel: UILabel! var photos: [PXLPhoto] = [] @IBOutlet var widgetStackView: UIStackView! @IBOutlet var uiStackView: UIStackView! @IBOutlet var analyticsStackView: UIStackView! @IBOutlet var uiAutoAnalyticsStackView: UIStackView! override func viewDidLoad() { super.viewDidLoad() } func addEmptySpace(to: UIStackView){ to.layoutMargins = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) to.isLayoutMarginsRelativeArrangement = true to.layer.cornerRadius = CGFloat(20) to.layer.masksToBounds = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) addEmptySpace(to: uiStackView) addEmptySpace(to: analyticsStackView) addEmptySpace(to: uiAutoAnalyticsStackView) addEmptySpace(to: widgetStackView) do { try pixleeCredentials = PixleeCredentials.create() } catch{ self.showPopup(message: error.localizedDescription) } initClient() initAlbum() loadPhotos() //loadPhoto() testAnalyticsAPI() } func initClient(){ if let apiKey = pixleeCredentials.apiKey { // Where to get Pixlee API credentials? visit here: https://app.pixlee.com/app#settings/pixlee_api // add your Pixlee API key. PXLClient.sharedClient.apiKey = apiKey } if let secretKey = pixleeCredentials.secretKey { // add your Secret Key if you are making POST requests. PXLClient.sharedClient.secretKey = secretKey } PXLClient.sharedClient.autoAnalyticsEnabled = true // this is for multi-region products. if you don't have a set of region ids, please reach out your account manager to get it PXLClient.sharedClient.regionId = pixleeCredentials.regionId } func initAlbum() { // let dateString = "20190101" // let dateFormatter = DateFormatter() // dateFormatter.dateFormat = "yyyyMMdd" // let date = dateFormatter.date(from: dateString) // var filterOptions = PXLAlbumFilterOptions(minInstagramFollowers: 1, contentSource: [PXLContentSource.instagram_feed, PXLContentSource.instagram_story]) // album.filterOptions = filterOptions if let albumId = pixleeCredentials.albumId { album = PXLAlbum(identifier: albumId) } if let album = album { var filterOptions = PXLAlbumFilterOptions(contentType: ["video", "image"]) album.filterOptions = filterOptions album.sortOptions = PXLAlbumSortOptions(sortType: .approvedTime, ascending: false) } } func loadPhotos(){ if let album = album { _ = PXLClient.sharedClient.loadNextPageOfPhotosForAlbum(album: album) { photos, _ in if let photos = photos { self.photos = photos } } } } func testAnalyticsAPI(){ if let album = album { _ = PXLAnalyticsService.sharedAnalytics.logEvent(event: PXLAnalyticsEventOpenedWidget(album: album, widget: .other(customValue: "customWidgetName"))) { _ in print("Example opened analytics logged") } } } func getSamplePhotos() -> [PXLPhoto]? { if let album = album { guard album.photos.count < 1 else { return album.photos } guard photos.count < 1 else { return photos } _ = PXLClient.sharedClient.loadNextPageOfPhotosForAlbum(album: album) { photos, _ in if let photos = photos { self.photos = photos } } return [PXLPhoto]() } else { showPopup(message: "no album is loaded") return nil } } @IBAction func loadAlbum(_ sender: Any) { if let album = album { present(PXLAlbumViewController.viewControllerForAlbum(album: album), animated: true, completion: nil) } } // MARK: - APIs @IBAction func showWidget(_ sender: Any) { present(WidgetViewController.getInstance(), animated: true, completion: nil) } @IBAction func showProductUIExample(_ sender: Any) { present(ProductExampleViewController.getInstance(), animated: true, completion: nil) } @IBAction func showAPIGetPhotos(_ sender: Any) { present(GetPhotosViewController.getInstance(), animated: true, completion: nil) } @IBAction func showAPIGetPhoto(_ sender: Any) { present(GetPhotoViewController.getInstance(), animated: true, completion: nil) } @IBAction func showAnalytics(_ sender: Any) { present(AnalyticsViewController.getInstance(), animated: true, completion: nil) } // MARK: - UI Components + Auto Analytics @IBAction func showAutoAnalyticsUI(_ sender: Any) { present(AutoUIImageListViewController.getInstance(true), animated: true, completion: nil) } @IBAction func showAutoAnalyticsUITurnedOff(_ sender: Any) { present(AutoUIImageListViewController.getInstance(false), animated: true, completion: nil) } // MARK: - UI Components @IBAction func loadOneColumn(_ sender: Any) { if let photos = getSamplePhotos() { present(OneColumnViewController.getInstance(photos), animated: true, completion: nil) } } @IBAction func loadOneColumnAutoplay(_ sender: Any) { if let photos = getSamplePhotos() { present(AutoPlayViewController.getInstance(photos), animated: true, completion: nil) } } @IBAction func loadOneColumnInfiniteScroll(_ sender: Any) { if let photos = getSamplePhotos() { present(InfiniteScrollViewController.getInstance(photos), animated: true, completion: nil) } } @IBAction func loadTwoColumn(_ sender: Any) { if let photos = getSamplePhotos() { present(TwoColumnDemoListViewController.getInstance(photos), animated: true, completion: nil) } } @IBAction func loadGifFileHeader(_ sender: Any) { if let photos = getSamplePhotos() { present(ListWithGifFileViewController.getInstance(photos), animated: true, completion: nil) } } @IBAction func loadGifURLHeader(_ sender: Any) { if let photos = getSamplePhotos() { present(ListWithGifURLViewController.getInstance(photos), animated: true, completion: nil) } } @IBAction func loadTextHeader(_ sender: Any) { if let photos = getSamplePhotos() { present(ListWithTextViewController.getInstance(photos), animated: true, completion: nil) } } @IBAction func loadPhotoProductsView(_ sender: Any) { if let photos = getSamplePhotos() { present(PhotoProductListDemoViewController.getInstance(photos[0]), animated: true, completion: nil) } } } extension ViewController: PXLPhotoProductDelegate { public func onProductsLoaded(products: [PXLProduct]) -> [Int: Bool] { var bookmarks = [Int: Bool]() products.forEach { product in bookmarks[product.identifier] = true } return bookmarks } public func onBookmarkClicked(product: PXLProduct, isSelected: Bool) { print("Pruduct: \(product.identifier) is selected: \(isSelected)") } public func shouldOpenURL(url: URL) -> Bool { print("url: \(url)") return false } public func onProductClicked(product: PXLProduct) { print("Pruduct: \(product.identifier) clicked") } }
33.578313
169
0.612487
da598fd5a6c553713117b230e3081bbbfc825238
176
tsx
TypeScript
packages/native/src/components/Form/Slider/index.tsx
LedgerHQ/ui
1fe7c5d526c81ca83dfcb39727db21cafd3e2e61
[ "MIT" ]
15
2021-09-26T15:59:57.000Z
2022-03-06T05:47:25.000Z
packages/native/src/components/Form/Slider/index.tsx
LedgerHQ/ui
1fe7c5d526c81ca83dfcb39727db21cafd3e2e61
[ "MIT" ]
143
2021-09-30T12:21:43.000Z
2022-03-30T09:28:37.000Z
packages/native/src/components/Form/Slider/index.tsx
LedgerHQ/ui
1fe7c5d526c81ca83dfcb39727db21cafd3e2e61
[ "MIT" ]
6
2021-09-26T16:00:05.000Z
2022-03-06T05:47:29.000Z
import React from "react"; import type { SliderProps } from "./index.native"; const SliderScreen = (_props: SliderProps) => { return <></>; }; export default SliderScreen;
19.555556
50
0.6875
fa2b0fe8c1ef7aae8745830c2f78cadeadfc2e1b
4,165
cpp
C++
Silver/Silver/silver_shader.cpp
c272/silver
2721731c7803882e5b70118253237d565a3b6709
[ "Apache-2.0" ]
null
null
null
Silver/Silver/silver_shader.cpp
c272/silver
2721731c7803882e5b70118253237d565a3b6709
[ "Apache-2.0" ]
1
2018-09-16T14:09:18.000Z
2018-09-16T14:09:18.000Z
Silver/Silver/silver_shader.cpp
c272/silver
2721731c7803882e5b70118253237d565a3b6709
[ "Apache-2.0" ]
null
null
null
//Including basics. #include "silver_inc.h" #include "silver_shader.h" // SECTION 1 // FUNCTIONS ///Shader class constructor, takes the paths (relative or complete) of the vertex and fragment shader that will ///be used in the program. ///Parameters: (char* vertexPath, char* fragmentPath) slvr::Shader::Shader(char* vertexShaderPath, char* fragmentShaderPath) { std::ifstream vertexStream; std::ifstream fragmentStream; std::string vertexCode; std::string fragmentCode; //Enabling exceptions on streams. vertexStream.exceptions(std::ifstream::failbit | std::ifstream::badbit); fragmentStream.exceptions(std::ifstream::failbit | std::ifstream::badbit); //Attempting a stream. try { vertexStream.open(const_cast<const char*>(vertexShaderPath)); fragmentStream.open(const_cast<const char*>(fragmentShaderPath)); //Creating a stringstream to load buffer into. std::stringstream vertexSS, fragmentSS; vertexSS << vertexStream.rdbuf(); fragmentSS << fragmentStream.rdbuf(); //Closing streams, buffers have now been read out. vertexStream.close(); fragmentStream.close(); //Reading into strings. vertexCode = vertexSS.str(); fragmentCode = fragmentSS.str(); } catch (std::ifstream::failure e) { std::cout << "SHADER FAILURE: Could not load vertex/fragment Shader file.\n"; } //Converting vertex/frag to a const char*. const char* vertexShaderSource = vertexCode.c_str(); const char* fragmentShaderSource = fragmentCode.c_str(); //Attempting to compile shaders. GLuint vertex, fragment; int noerrors; char* log = new char[512]; //FIRST - Vertex Shader. vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vertexShaderSource, NULL); glCompileShader(vertex); //Checking for errors. glGetShaderiv(vertex, GL_COMPILE_STATUS, &noerrors); if (!noerrors) { //Failure, dump log. glGetShaderInfoLog(vertex, 512, NULL, log); std::cout << "SHADER FAILURE: Vertex shader failed to compile.\n" << log; } //SECOND - Fragment Shader. fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fragmentShaderSource, NULL); glCompileShader(fragment); //Checking for errors. glGetShaderiv(fragment, GL_COMPILE_STATUS, &noerrors); if (!noerrors) { //Failure, dump log. glGetShaderInfoLog(fragment, 512, NULL, log); std::cout << "SHADER FAILURE: Fragment shader failed to compile.\n" << log; } //Attempting to create and link shader program. ID = glCreateProgram(); glAttachShader(ID, vertex); glAttachShader(ID, fragment); glLinkProgram(ID); glGetProgramiv(ID, GL_LINK_STATUS, &noerrors); if (!noerrors) { glGetProgramInfoLog(ID, 512, NULL, log); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << log << std::endl; } //Deleting shaders after link, no longer required. glDeleteShader(vertex); glDeleteShader(fragment); } ///Destructor for the Shader class, deletes the program referenced by private UInt ID. ///Parameters: () slvr::Shader::~Shader() { glDeleteProgram(ID); } ///Sets the shader as the current active shader in the engine/OGL. ///Parameters: () void slvr::Shader::use() { glUseProgram(ID); } ///Sets a shader uniform property to the value given. ///One example could be "colour". ///Parameters: (std::string name_of_uniform, bool value_of_parameter) void slvr::Shader::setUniformBool(const std::string &name, bool value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value); } ///Sets a shader uniform property to the value given. ///One example could be "colour". ///Parameters: (std::string name_of_uniform, int value_of_parameter) void slvr::Shader::setUniformInt(const std::string &name, int value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), value); } ///Sets a shader uniform property to the value given. ///One example could be "colour". ///Parameters: (std::string name_of_uniform, float value_of_parameter) void slvr::Shader::setUniformFloat(const std::string &name, float value) const { glUniform1f(glGetUniformLocation(ID, name.c_str()), value); } ///A getter for the raw GL ID of the compiled shader program. ///Parameters: () GLuint slvr::Shader::getID() { return ID; }
30.851852
111
0.735654
0d6bfb51d355291ab879f6a86ec3b009ab6843c5
2,022
cs
C#
src/BikeSharing.Clients.Droid/Activities/MainActivity.cs
meijeran/BikeSharing
71fea652c947503a1197611c259787e52757ee71
[ "MIT" ]
null
null
null
src/BikeSharing.Clients.Droid/Activities/MainActivity.cs
meijeran/BikeSharing
71fea652c947503a1197611c259787e52757ee71
[ "MIT" ]
null
null
null
src/BikeSharing.Clients.Droid/Activities/MainActivity.cs
meijeran/BikeSharing
71fea652c947503a1197611c259787e52757ee71
[ "MIT" ]
null
null
null
using Acr.UserDialogs; using Android.App; using Android.Content; using Android.Content.PM; using Android.OS; using Android.Runtime; using BikeSharing.Clients.Core.Models; using BikeSharing.Clients.Core.Services.Interfaces; using BikeSharing.Clients.Core.ViewModels.Base; using Card.IO; using FFImageLoading.Forms.Droid; using Xamarin.Forms; using BikeSharing.Clients.Core; using BikeSharing.Clients.Droid.Services; namespace BikeSharing.Clients.Droid { [Activity( Label = "BikeSharing.Clients.Core", Icon = "@drawable/icon", Theme = "@style/MainTheme", ScreenOrientation = ScreenOrientation.Portrait)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); Xamarin.FormsMaps.Init(this, bundle); UserDialogs.Init(this); CachedImageRenderer.Init(); ViewModelLocator.Instance.Register<ICreditCardScannerService, CreditCardScannerService>(); LoadApplication(new App()); } protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (data != null) { var card = data.GetParcelableExtra(CardIOActivity.ExtraScanResult).JavaCast<CreditCard>(); var creditCardInfo = new CreditCardInformation { CardNumber = card.CardNumber, ExpirationMonth = card.ExpiryMonth.ToString(), ExpirationYear = card.ExpiryYear.ToString() }; MessagingCenter.Send(creditCardInfo, MessengerKeys.CreditCardScanned); } } } }
33.7
106
0.653314
60709cb11d296744f4db8b686e521029adbb02f5
1,611
h
C
abclient/abclient/GameMessagesWindow.h
pablokawan/ABx
064d6df265c48c667ce81b0a83f84e5e22a7ff53
[ "MIT" ]
null
null
null
abclient/abclient/GameMessagesWindow.h
pablokawan/ABx
064d6df265c48c667ce81b0a83f84e5e22a7ff53
[ "MIT" ]
null
null
null
abclient/abclient/GameMessagesWindow.h
pablokawan/ABx
064d6df265c48c667ce81b0a83f84e5e22a7ff53
[ "MIT" ]
null
null
null
/** * Copyright 2017-2020 Stefan Ascher * * 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. */ #pragma once #include <Urho3DAll.h> class GameMessagesWindow : public UIElement { URHO3D_OBJECT(GameMessagesWindow, UIElement) private: static constexpr float VISIBLE_TIME = 3.0f; float visibleTime_; SharedPtr<Text> text_; void HandleUpdate(StringHash eventType, VariantMap& eventData); public: static void RegisterObject(Context* context); GameMessagesWindow(Context* context); ~GameMessagesWindow() override; void ShowError(const String& message); };
38.357143
85
0.759777
38464be3edab166ec0a094b4888c1fd9bccc5e40
3,378
php
PHP
app/Http/Traits/DateTrait.php
KamalEssam/store-e-commer-backend
4f85cf8fc58e544d982efb548093391ba3459b69
[ "MIT" ]
null
null
null
app/Http/Traits/DateTrait.php
KamalEssam/store-e-commer-backend
4f85cf8fc58e544d982efb548093391ba3459b69
[ "MIT" ]
null
null
null
app/Http/Traits/DateTrait.php
KamalEssam/store-e-commer-backend
4f85cf8fc58e544d982efb548093391ba3459b69
[ "MIT" ]
null
null
null
<?php namespace App\Http\Traits; use Carbon\Carbon; use Config; trait DateTrait { /** * to know if this day = today or tomorrow * @param $day * @return string */ public static function getDayName($day) { switch ($day) { case self::getDateByFormat(self::getToday(), 'Y-m-d') : $day = trans('lang.today'); break; case self::getDateByFormat(self::getTomorrow(), 'Y-m-d') : $day = trans('lang.tomorrow'); break; default : return $day; } return $day; } /** * get day name by index * @param $day_index * @return mixed */ public static function getDayNameByIndex($day_index) { foreach (Config::get('lists.days') as $single_day) { if ($day_index == $single_day['day']) { $day_name = $single_day[app()->getLocale() . '_name']; break; } } return $day_name; } /** * get index of the day * @param $day * @return mixed */ public static function getDayIndex($day) { // get index day from days list in config $day_parsing = Carbon::parse($day, "Africa/Cairo"); //get name of day (sunday,monday,....) $day_name = self::getDateByFormat($day_parsing, 'l'); foreach (Config::get('lists.days') as $single_day) { if ($day_name == $single_day['en_name']) { $index = $single_day['day']; break; } } return $index; } /** * parse date * @param $date * @return Carbon */ public static function parseDate($date) { return Carbon::parse($date, "Africa/Cairo"); } /** * get today * @return Carbon */ public static function getToday() { return Carbon::today("Africa/Cairo"); } /** * get today * @return Carbon */ public static function getTomorrow() { return Carbon::tomorrow("Africa/Cairo"); } /** * @param $date * @param $format * @return string */ public static function getDateByFormat($date, $format) { return Carbon::parse($date, "Africa/Cairo")->format($format); } /** * get day formatted with am and pm * @param $time * @param string $format * @return string */ public static function getTimeByFormat($time, $format) { return Carbon::parse($time, "Africa/Cairo")->format($format); // return date($format, strtotime($time)); } /** * @param $date_from * @return string */ public static function readableDate($date_from) { $result = Carbon::createFromTimeStamp(strtotime($date_from), "Africa/Cairo")->diffForHumans(); return $result; } /** * add no of days to specific day * @param $add_from_day * @param $no_of_days * @return mixed */ public static function addDays($add_from_day, $no_of_days) { return $add_from_day->addDays($no_of_days); } /** * @param $format * @return string */ public static function getTodayFormat($format) { return Carbon::now("Africa/Cairo")->format($format); } }
22.671141
102
0.522795
36d41d6733e57616e57ef36b1d2c8a9ebe8d3b91
1,538
kt
Kotlin
app/src/main/java/com/srg/pruebamarvel/common/adapters/LocalDateTimeAdapter.kt
sebrodgar/prueba-tecnica-marvel
bfec1d716283ee8a7d638391be6272509f2064f0
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/srg/pruebamarvel/common/adapters/LocalDateTimeAdapter.kt
sebrodgar/prueba-tecnica-marvel
bfec1d716283ee8a7d638391be6272509f2064f0
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/srg/pruebamarvel/common/adapters/LocalDateTimeAdapter.kt
sebrodgar/prueba-tecnica-marvel
bfec1d716283ee8a7d638391be6272509f2064f0
[ "Apache-2.0" ]
null
null
null
package com.srg.pruebamarvel.common.adapters import com.google.gson.* import java.lang.reflect.Type import java.text.ParseException import java.time.LocalDate import java.time.LocalDateTime import java.time.format.DateTimeFormatter /** * Created by sebrodgar on 02/03/2021. */ class LocalDateTimeAdapter : JsonDeserializer<LocalDateTime?>, JsonSerializer<LocalDateTime?> { @Throws(JsonParseException::class) override fun deserialize( json: JsonElement, typeOfT: Type?, context: JsonDeserializationContext? ): LocalDateTime? { return try { val jsonStr = json.asJsonPrimitive.asString parseLocalDateTime(jsonStr) } catch (e: ParseException) { throw JsonParseException(e.message, e) } } @Throws(ParseException::class) private fun parseLocalDateTime(dateString: String?): LocalDateTime? { if (dateString == null || dateString.trim { it <= ' ' }.isEmpty()) { return null } return if (dateString.length == 10) { LocalDate.parse(dateString).atStartOfDay() } else LocalDateTime.parse( dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ") ) } override fun serialize( src: LocalDateTime?, typeOfSrc: Type?, context: JsonSerializationContext? ): JsonElement { val strDateTime: String = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(src) return JsonPrimitive(strDateTime) } }
30.156863
83
0.654096
46e3d030121d193981c94b651ec2bfd7ba678129
439
swift
Swift
day-068/Projects/PlaceCase/PlaceCase/Data/State/CurrentApplication.swift
CypherPoet/100-days-of-swiftui
d7bf8063f4eb97b59e7f2c665b42083a364f7b1c
[ "Unlicense" ]
24
2019-10-09T03:24:06.000Z
2020-01-13T10:34:04.000Z
day-068/Projects/PlaceCase/PlaceCase/Data/State/CurrentApplication.swift
michael-mimi/100-days-of-swiftui-and-combine
d7bf8063f4eb97b59e7f2c665b42083a364f7b1c
[ "Unlicense" ]
64
2019-10-09T00:07:46.000Z
2020-01-10T13:18:53.000Z
day-068/Projects/PlaceCase/PlaceCase/Data/State/CurrentApplication.swift
michael-mimi/100-days-of-swiftui-and-combine
d7bf8063f4eb97b59e7f2c665b42083a364f7b1c
[ "Unlicense" ]
6
2019-10-15T09:00:47.000Z
2019-12-16T12:28:10.000Z
// // CurrentApplication.swift // PlaceCase // // Created by CypherPoet on 12/14/19. // ✌️ // import Foundation struct CurrentApplication { var coreDataManager: CoreDataManager var wikipediaAPIService: WikipediaAPIService } var CurrentApp = CurrentApplication( coreDataManager: .shared, wikipediaAPIService: WikipediaAPIService( queue: DispatchQueue(label: "WikipediaAPI", qos: .userInitiated) ) )
17.56
72
0.715262
c66fe287b8cf299dffd45d05bddb4674275ee88a
210
py
Python
microservices-test-roadmap.py
emmanuelneri/microservices-roadmap
4bdb041e6ad2abcfb258942e105ef14b7b1d3896
[ "Apache-2.0" ]
6
2020-06-28T14:47:18.000Z
2022-01-16T03:47:56.000Z
microservices-test-roadmap.py
emmanuelneri/microservices-roadmap
4bdb041e6ad2abcfb258942e105ef14b7b1d3896
[ "Apache-2.0" ]
null
null
null
microservices-test-roadmap.py
emmanuelneri/microservices-roadmap
4bdb041e6ad2abcfb258942e105ef14b7b1d3896
[ "Apache-2.0" ]
null
null
null
from graphviz import Digraph from model.test import Test dot = Digraph(comment='Microservices Test Roadmap', format='png') test = Test() test.build(dot) dot.render('images/microservices-test-roadmap.gv')
19.090909
65
0.757143
e2540fd7d0a027b33e39c5705e1d7b6f23c563b3
2,112
py
Python
fashionnets/models/layer/Augmentation.py
NiklasHoltmeyer/FashionNets
918e57f122b8cfa36dba1d0b993c763ba35ac815
[ "MIT" ]
null
null
null
fashionnets/models/layer/Augmentation.py
NiklasHoltmeyer/FashionNets
918e57f122b8cfa36dba1d0b993c763ba35ac815
[ "MIT" ]
null
null
null
fashionnets/models/layer/Augmentation.py
NiklasHoltmeyer/FashionNets
918e57f122b8cfa36dba1d0b993c763ba35ac815
[ "MIT" ]
null
null
null
import tensorflow as tf from fashionnets.models.layer.RandomErasing import RandomErasing from fashionnets.models.layer.RandomHorizontalFlip import RandomHorizontalFlip from tensorflow.keras import layers def random_crop_layer(crop_shape): return layers.Lambda(lambda x: tf.image.random_crop(value=x, size=crop_shape)) def compose_augmentations(): def __call__(is_train): cfg = AugmentationConfig() if not is_train: return tf.keras.Sequential([ layers.experimental.preprocessing.Resizing(*cfg.SIZE_TRAIN), normalize_image(cfg.PIXEL_MEAN, cfg.PIXEL_STD), ]) pad = cfg.PADDING resize_padding_shape = cfg.SIZE_TRAIN[0] + pad, cfg.SIZE_TRAIN[1] + pad transform = tf.keras.Sequential([ layers.experimental.preprocessing.Resizing(*cfg.SIZE_TRAIN), RandomHorizontalFlip(p=cfg.PROB), resize_with_padding(resize_padding_shape), random_crop(cfg.SIZE_TRAIN), normalize_image(cfg.PIXEL_MEAN, cfg.PIXEL_STD), RandomErasing(probability=cfg.RE_PROB, mean=cfg.PIXEL_MEAN) ]) return transform return __call__ # padding, fill=0, padding_mode="constant" def resize_with_padding(shape): return layers.Lambda(lambda x: tf.image.resize_with_pad( x, shape[0], shape[1] )) def random_crop(input_shape): return layers.Lambda(lambda x: tf.image.random_crop(x, (input_shape[0], input_shape[1], 3)) ) import numpy as np from tensorflow.keras.layers.experimental import preprocessing def normalize_image(MEAN, STD): variance = [np.square(i) for i in STD] return preprocessing.Normalization(mean=MEAN, variance=variance) class AugmentationConfig: def __init__(self): self.PROB = 0.5 # Probability of Horizontal Flip self.RE_PROB = 0.5 # Probability of Random Erasing self.SIZE_TRAIN = [224, 224] self.PADDING = 10 self.PIXEL_MEAN = [0.485, 0.456, 0.406] self.PIXEL_STD = [0.229, 0.224, 0.225]
29.746479
85
0.668087
31ff697e8e7e07a51fd566777b394612abb910fc
1,464
rb
Ruby
app/models/concerns/gws/addon/circular/group_setting.rb
webtips/shirasagi
3f052f1a9ee2cedf6e7ac22b05062a106153ccad
[ "MIT" ]
101
2015-01-05T02:30:34.000Z
2022-03-04T09:36:44.000Z
app/models/concerns/gws/addon/circular/group_setting.rb
webtips/shirasagi
3f052f1a9ee2cedf6e7ac22b05062a106153ccad
[ "MIT" ]
2,722
2015-01-07T08:50:16.000Z
2022-03-30T01:56:16.000Z
app/models/concerns/gws/addon/circular/group_setting.rb
sunny4381/shirasagi
b679dd0c765c891d7d5bb5903abd11536b54c9ea
[ "MIT" ]
107
2015-01-17T16:12:59.000Z
2021-12-16T04:23:44.000Z
module Gws::Addon::Circular::GroupSetting extend ActiveSupport::Concern extend SS::Addon include Gws::Break set_addon_type :organization included do field :circular_default_due_date, type: Integer, default: 7 field :circular_max_member, type: Integer field :circular_filesize_limit, type: Integer field :circular_delete_threshold, type: Integer, default: 3 field :circular_files_break, type: String, default: 'vertically' field :circular_new_days, type: Integer permit_params :circular_default_due_date, :circular_max_member, :circular_filesize_limit, :circular_delete_threshold, :circular_files_break, :circular_new_days validates :circular_default_due_date, numericality: true validates :circular_delete_threshold, numericality: true validates :circular_files_break, inclusion: { in: %w(vertically horizontal), allow_blank: true } alias_method :circular_files_break_options, :break_options end def circular_delete_threshold_options I18n.t('gws/circular.options.circular_delete_threshold'). map. with_index. to_a end def circular_delete_threshold_name I18n.t('gws/circular.options.circular_delete_threshold')[circular_delete_threshold] end def circular_filesize_limit_in_bytes return if circular_filesize_limit.blank? circular_filesize_limit * 1_024 * 1_024 end def circular_new_days self[:circular_new_days].presence || 7 end end
30.5
100
0.772541
27b5622ef415bb04e0a723168e9b5b394e83a3eb
542
sql
SQL
ch08/readinglist_war/src/main/resources/db/migration/V1__initialize.sql
ishiningway/SpringBootInAction
500920a788afb35e5637921a6f4403f4358b08e8
[ "MIT" ]
67
2018-11-23T08:10:01.000Z
2022-03-26T11:52:45.000Z
ch08/readinglist_war/src/main/resources/db/migration/V1__initialize.sql
ishiningway/SpringBootInAction
500920a788afb35e5637921a6f4403f4358b08e8
[ "MIT" ]
371
2020-03-04T21:51:56.000Z
2022-03-31T20:59:11.000Z
ch08/readinglist_war/src/main/resources/db/migration/V1__initialize.sql
ishiningway/SpringBootInAction
500920a788afb35e5637921a6f4403f4358b08e8
[ "MIT" ]
60
2016-01-26T22:19:11.000Z
2018-11-02T04:12:22.000Z
create table Reader ( username varchar(25) unique not null, password varchar(25) not null, fullname varchar(50) not null ); create table Book ( id serial primary key, author varchar(50) not null, description varchar(1000) not null, isbn varchar(10) not null, title varchar(250) not null, reader_username varchar(25) not null, foreign key (reader_username) references Reader(username) ); create sequence hibernate_sequence; insert into Reader (username, password, fullname) values ('craig', 'password', 'Craig Walls');
25.809524
94
0.741697
dfe5ffc387f3a8d7aa4756fd5ed5816834cdd600
242
cs
C#
src/MAVN.Service.AdminAPI/Models/SmartVouchers/Campaigns/SmartVoucherCampaignCreateRequest.cs
HannaAndreevna/MAVN.Service.AdminAPI
fabee423633b8ead821df15287c2440b242c7bf0
[ "MIT" ]
null
null
null
src/MAVN.Service.AdminAPI/Models/SmartVouchers/Campaigns/SmartVoucherCampaignCreateRequest.cs
HannaAndreevna/MAVN.Service.AdminAPI
fabee423633b8ead821df15287c2440b242c7bf0
[ "MIT" ]
null
null
null
src/MAVN.Service.AdminAPI/Models/SmartVouchers/Campaigns/SmartVoucherCampaignCreateRequest.cs
HannaAndreevna/MAVN.Service.AdminAPI
fabee423633b8ead821df15287c2440b242c7bf0
[ "MIT" ]
null
null
null
using MAVN.Service.AdminAPI.Models.ActionRules; namespace MAVN.Service.AdminAPI.Models.SmartVouchers.Campaigns { public class SmartVoucherCampaignCreateRequest : SmartVoucherCampaignBaseRequest<MobileContentCreateRequest> { } }
26.888889
112
0.818182
2810b42226bdc7409349a7abefd1889849b50262
5,085
dart
Dart
firestore_rest/lib/src/patch_document_rest_impl.dart
luke14free/firebase_firestore.dart
831b82d8b82c10708bc9279bc646bd38b3634182
[ "BSD-2-Clause" ]
null
null
null
firestore_rest/lib/src/patch_document_rest_impl.dart
luke14free/firebase_firestore.dart
831b82d8b82c10708bc9279bc646bd38b3634182
[ "BSD-2-Clause" ]
null
null
null
firestore_rest/lib/src/patch_document_rest_impl.dart
luke14free/firebase_firestore.dart
831b82d8b82c10708bc9279bc646bd38b3634182
[ "BSD-2-Clause" ]
null
null
null
import 'package:path/path.dart'; import 'package:tekartik_firebase_firestore/firestore.dart'; import 'package:tekartik_firebase_firestore/src/common/value_key_mixin.dart'; // ignore: implementation_imports import 'package:tekartik_firebase_firestore_rest/src/document_rest_impl.dart'; import 'package:tekartik_firebase_firestore_rest/src/firestore_rest_impl.dart'; import 'package:tekartik_firebase_firestore_rest/src/import.dart'; import 'firestore/v1beta1.dart'; class SetDocument extends WriteDocument { SetDocument(FirestoreDocumentContext firestore, Map data) : super(firestore, data, merge: false); } class SetMergedDocument extends WriteDocument { SetMergedDocument(FirestoreDocumentContext firestore, Map data) : super(firestore, data, merge: false); @override void _fromMap(Map map) { if (map == null) { return null; } _currentParent = null; _fields = _firstMapToFields(map); } Map<String, Value> _firstMapToFields(Map map) { if (map == null) { return null; } var fields = <String, Value>{}; map.forEach((key, value) { final stringKey = key.toString(); fields[stringKey] = patchToRestValue(stringKey, value); fieldPaths ??= []; fieldPaths.add(escapeKey(stringKey)); }); return fields; } } class UpdateDocument extends WriteDocument { UpdateDocument(FirestoreDocumentContext firestore, Map data) : super(firestore, data, merge: true); @override void _fromMap(Map map) { if (map == null) { return null; } _currentParent = null; _fields = _firstMapToFields(map); } Map<String, Value> _firstMapToFields(Map map) { if (map == null) { return null; } var fields = <String, Value>{}; map.forEach((key, value) { final stringKey = key.toString(); fieldPaths ??= []; fieldPaths.add(stringKey); }); var expanded = expandUpdateData(map); expanded.forEach((key, value) { final stringKey = key.toString(); if (value == FieldValue.delete) { // Don't set it in the fields but add // it to fieldPaths. } else { // Build the tree // TODO test empty update fields[stringKey] = patchToRestValue(stringKey, value); } }); return fields; } @override Map<String, Value> _mapToFields(String me, Map map) { if (map == null) { return null; } var fields = <String, Value>{}; map.forEach((key, value) { final stringKey = key.toString(); if (value == FieldValue.delete) { // Don't set it in the fields but added in field paths } else { fields[stringKey] = patchToRestValue(stringKey, value); } }); return fields; } } class WriteDocument with DocumentContext { @override final FirestoreDocumentContext firestore; bool merge; final document = Document(); List<String> fieldPaths; Map<String, Value> _fields; WriteDocument(this.firestore, Map data, {@required this.merge}) { merge ??= false; _fromMap(data); document.fields = _fields; } Map<String, Value> get fields => document.fields; void _fromMap(Map map) { if (map == null) { return null; } _currentParent = null; _fields = _mapToFields(null, map); } String _currentParent; Value patchToRestValue(String key, dynamic value) { var me = _currentParent == null ? key : url.join(_currentParent, key); if (value is Map) { return _pathMapToRestValue(me, value); } return super.toRestValue(value); } Map<String, Value> _mapToFields(String me, Map map) { if (map == null) { return null; } var fields = <String, Value>{}; map.forEach((key, value) { final stringKey = key.toString(); if (value == FieldValue.delete) { // Don't set it in the fileds but add // it to fieldPaths. if (merge) { fieldPaths ??= []; fieldPaths.add(pathJoin(me, stringKey)); } } else { fields[stringKey] = patchToRestValue(stringKey, value); if (merge) { // add all field name fieldPaths ??= []; fieldPaths.add(pathJoin(me, stringKey)); } } }); return fields; } Value _pathMapToRestValue(String me, Map value) { var oldCurrent = _currentParent; try { _currentParent = me; return _mapToRestValue(me, value); } finally { _currentParent = oldCurrent; } } Value _mapToRestValue(String me, Map map) { var mapValue = MapValue()..fields = _mapToFields(me, map); return Value()..mapValue = mapValue; } @override String toString() { return 'doc: $fieldsToString $fieldPaths'; } String get fieldsToString { var sb = StringBuffer(); fields?.forEach((key, value) { if (sb.isNotEmpty) { sb.write(', '); } sb.write('$key: ${restValueToString(firestore, value)}'); }); if (sb.isEmpty && fields == null) { sb.write('(nullFields)'); } return sb.toString(); } }
24.684466
111
0.625959
72831ef0abb51e53c92dc8b14d121f10a587006e
989
cs
C#
Runtime/Utilities/Plotting/PlotFunctions.cs
pyrateml/droid
9accdc192f163f7590e47fe55049345ab38d6f3a
[ "Apache-2.0" ]
null
null
null
Runtime/Utilities/Plotting/PlotFunctions.cs
pyrateml/droid
9accdc192f163f7590e47fe55049345ab38d6f3a
[ "Apache-2.0" ]
null
null
null
Runtime/Utilities/Plotting/PlotFunctions.cs
pyrateml/droid
9accdc192f163f7590e47fe55049345ab38d6f3a
[ "Apache-2.0" ]
1
2018-09-27T14:30:30.000Z
2018-09-27T14:30:30.000Z
using System.Collections.Generic; using Neodroid.Runtime.Utilities.Structs; using UnityEngine; namespace Neodroid.Runtime.Utilities.Plotting { public static class PlotFunctions { static List<Points.ValuePoint> _points = new List<Points.ValuePoint>(); /// <summary> /// /// </summary> /// <param name="size"></param> /// <param name="min_val"></param> /// <param name="max_val"></param> /// <param name="particle_size"></param> /// <returns></returns> public static Points.ValuePoint[] SampleRandomSeries( int size, float min_val = 0, float max_val = 5, float particle_size = 1) { _points.Clear(); for (var j = 0; j < size; j++) { var point = new Vector3(j, Random.Range(min_val, max_val), 0); var vp = new Points.ValuePoint(point, Random.Range(min_val, max_val), particle_size); _points.Add(vp); } var points = _points.ToArray(); return points; } } }
29.969697
93
0.61274
8cd3088906b49c3e5511d5794659bb3003f5ef97
2,305
go
Go
handler/chat.go
JermineHu/ait
e0474aee2be77a27c3ddbefce42f12ccb154ab00
[ "MIT" ]
null
null
null
handler/chat.go
JermineHu/ait
e0474aee2be77a27c3ddbefce42f12ccb154ab00
[ "MIT" ]
null
null
null
handler/chat.go
JermineHu/ait
e0474aee2be77a27c3ddbefce42f12ccb154ab00
[ "MIT" ]
null
null
null
package handler import ( "github.com/labstack/echo" . "github.com/JermineHu/ait/consts" "strings" "fmt" "sync" "github.com/gorilla/websocket" "html/template" ) const MAX_CONNECTION int = 100 const JOIN_ROOM_FAILED int = -1 const Debug = true type ChatRoom struct { sync.Mutex clients map[int]*websocket.Conn currentId int } func (cr *ChatRoom)joinRoom(ws *websocket.Conn) int { cr.Lock() defer cr.Unlock() if len(cr.clients) >= MAX_CONNECTION { return JOIN_ROOM_FAILED } cr.currentId++ cr.clients[cr.currentId] = ws return cr.currentId } func (cr *ChatRoom)leftRoom(id int) { delete(cr.clients, id) } func (cr *ChatRoom)sendMessage(msg string) { for _, ws := range cr.clients { if err := ws.WriteMessage(websocket.TextMessage, []byte(msg)); err != nil { log4Demo("发送失败,Err:" + err.Error()) continue } } } var room ChatRoom func init() { roomMap := make(map[int]*websocket.Conn, MAX_CONNECTION) room = ChatRoom{clients:roomMap, currentId:0} } func log4Demo(msg string) { if Debug { fmt.Println(msg) } } func WrapChatRoutes(c *echo.Group) { ChatHandler(c) ChatIndexPageHandler(c) } var ( upgrader = websocket.Upgrader{} ) func ChatHandler(c *echo.Group){ h:= func(c echo.Context) (err error){ ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)//将当前http请求升级为websocket if err != nil { return } defer ws.Close()//跳出函数前关闭socket var id int if id = room.joinRoom(ws); id == JOIN_ROOM_FAILED { //将当前的socket对象加入room池子,用于后续的批量广播 err=ws.WriteMessage(websocket.TextMessage,[]byte( "加入聊天室失败")) if err != nil { c.Logger().Error(err) } return } defer room.leftRoom(id) //离开房间就要从池子里删除 ipAddress := strings.Split(ws.RemoteAddr().String(), ":")[0] + ":" for { _, msg, err := ws.ReadMessage()//读取消息 if err != nil { c.Logger().Error(err) return err } send_msg:= ipAddress + string(msg) room.sendMessage(send_msg)//将消息广播给进入该room的所有人,此处优化方案可以采用Kafka提高异步处理,提高并发效率 } return } c.GET(ChatRoomRoute, h) } func ChatIndexPageHandler(c *echo.Group) { h := func(c echo.Context) (err error) { t, _ := template.ParseFiles("assets/test.html") err=t.Execute(c.Response().Writer, nil) if err!=nil { log4Demo("Page Err:" + err.Error()) return } return } c.GET(ChatRoomIndexPageRoute, h) }
20.580357
86
0.67679
216a87fcf7e1d46cc86d5c32a292172b73c1a781
784
js
JavaScript
src/App.js
git99-src/employee-directory
a1894e616536185c4619e8c3517ee26e7e7a4d92
[ "MIT" ]
null
null
null
src/App.js
git99-src/employee-directory
a1894e616536185c4619e8c3517ee26e7e7a4d92
[ "MIT" ]
null
null
null
src/App.js
git99-src/employee-directory
a1894e616536185c4619e8c3517ee26e7e7a4d92
[ "MIT" ]
null
null
null
import React, { useEffect, useState } from "react"; import Table from "./components/Table"; import Search from "./components/Search"; import Header from "./components/Header"; import AllEmployees from "./data/randomUser.json"; function App() { const [search, setSearch] = useState(""); const filteredEmployees = AllEmployees.filter((item) => { return item.name.last.toUpperCase().includes(search.toUpperCase()); }); const handleSearchChange = (event) => { setSearch(event.target.value); }; useEffect(() => { console.log(search); }, [search]); return ( <div className="container"> <Header /> <Search value={search} onSearchChange={handleSearchChange} /> <Table employees={filteredEmployees} /> </div> ); } export default App;
27.034483
71
0.668367
076b33c8168bf99c7c6beefad6fdfa53e0ed6e13
5,722
cc
C++
game_example.cc
schroederdewitt/hanabi-learning-environment
cbeaae3d73af2fdadd1fdf6dae518657f2333a00
[ "Apache-2.0" ]
5
2021-06-15T05:06:10.000Z
2021-12-01T05:11:49.000Z
game_example.cc
schroederdewitt/hanabi-learning-environment
cbeaae3d73af2fdadd1fdf6dae518657f2333a00
[ "Apache-2.0" ]
1
2020-07-13T19:41:45.000Z
2020-07-13T19:41:45.000Z
game_example.cc
schroederdewitt/hanabi-learning-environment
cbeaae3d73af2fdadd1fdf6dae518657f2333a00
[ "Apache-2.0" ]
2
2020-12-24T01:33:25.000Z
2021-01-09T05:03:53.000Z
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cassert> #include <cstring> #include <iostream> #include <numeric> #include <random> #include <string> #include <unordered_map> #include "hanabi_game.h" #include "hanabi_state.h" #include "canonical_encoders.h" struct GameResult { int score; int fireworks_played; // Number of successful Play moves. int num_steps; // Number of moves by a player. }; constexpr const char* kGameParamArgPrefix = "--config.hanabi."; GameResult SimulateGame(const hanabi_learning_env::HanabiGame& game, bool verbose, std::mt19937* rng) { hanabi_learning_env::HanabiState state(&game); GameResult result = {0, 0, 0}; while (!state.IsTerminal()) { if (state.CurPlayer() == hanabi_learning_env::kChancePlayerId) { // All of this could be replaced with state.ApplyRandomChance(). // Only done this way to demonstrate picking specific chance moves. auto chance_outcomes = state.ChanceOutcomes(); std::discrete_distribution<std::mt19937::result_type> dist( chance_outcomes.second.begin(), chance_outcomes.second.end()); auto move = chance_outcomes.first[dist(*rng)]; if (verbose) { std::cout << "Legal chance:"; for (int i = 0; i < chance_outcomes.first.size(); ++i) { std::cout << " <" << chance_outcomes.first[i].ToString() << ", " << chance_outcomes.second[i] << ">"; } std::cout << "\n"; std::cout << "Sampled move: " << move.ToString() << "\n\n"; } state.ApplyMove(move); continue; } auto obs = hanabi_learning_env::HanabiObservation(state, state.CurPlayer()); hanabi_learning_env::CanonicalObservationEncoder encoder(&game); // std::vector<int> vecObs = encoder.Encode(obs); // std::cout << ">>>vec size: " << vecObs.size() << std::endl; auto legal_moves = state.LegalMoves(state.CurPlayer()); std::uniform_int_distribution<std::mt19937::result_type> dist( 0, legal_moves.size() - 1); auto move = legal_moves[dist(*rng)]; if (verbose) { std::cout << "Current player: " << state.CurPlayer() << "\n"; std::cout << state.ToString() << "\n\n"; std::cout << "Legal moves:"; for (int i = 0; i < legal_moves.size(); ++i) { std::cout << " " << legal_moves[i].ToString(); } std::cout << "\n"; std::cout << "Sampled move: " << move.ToString() << "\n\n"; } state.ApplyMove(move); ++result.num_steps; if (state.MoveHistory().back().scored) { ++result.fireworks_played; } } if (verbose) { std::cout << "Game done, terminal state:\n" << state.ToString() << "\n\n"; std::cout << "score = " << state.Score() << "\n\n"; } result.score = state.Score(); return result; } void SimulateGames( const std::unordered_map<std::string, std::string>& game_params, int num_trials = 1, bool verbose = true) { std::mt19937 rng; rng.seed(std::random_device()()); hanabi_learning_env::HanabiGame game(game_params); auto params = game.Parameters(); std::cout << "Hanabi game created, with parameters:\n"; for (const auto& item : params) { std::cout << " " << item.first << "=" << item.second << "\n"; } std::vector<GameResult> results; results.reserve(num_trials); for (int trial = 0; trial < num_trials; ++trial) { results.push_back(SimulateGame(game, verbose, &rng)); } if (num_trials > 1) { GameResult avg_score = std::accumulate( results.begin(), results.end(), GameResult(), [](const GameResult& lhs, const GameResult& rhs) { GameResult result = {lhs.score + rhs.score, lhs.fireworks_played + rhs.fireworks_played, lhs.num_steps + rhs.num_steps}; return result; }); std::cout << "Average score: " << static_cast<double>(avg_score.score) / results.size() << " average number of fireworks played: " << static_cast<double>(avg_score.fireworks_played) / results.size() << " average num_steps: " << static_cast<double>(avg_score.num_steps) / results.size() << "\n"; } } std::unordered_map<std::string, std::string> ParseArguments(int argc, char** argv) { std::unordered_map<std::string, std::string> game_params; const auto prefix_len = strlen(kGameParamArgPrefix); for (int i = 1; i < argc; ++i) { std::string param = argv[i]; if (param.compare(0, prefix_len, kGameParamArgPrefix) == 0 && param.size() > prefix_len) { std::string value; param = param.substr(prefix_len, std::string::npos); auto value_pos = param.find("="); if (value_pos != std::string::npos) { value = param.substr(value_pos + 1, std::string::npos); param = param.substr(0, value_pos); } game_params[param] = value; } } return game_params; } int main(int argc, char** argv) { auto game_params = ParseArguments(argc, argv); SimulateGames(game_params); return 0; }
35.7625
80
0.612199
7f44de42dd584d9d0e090a46d8aaf0a9af8a670b
14,791
php
PHP
resources/views/mstock/chongzhi.blade.php
xudong17/stock_laravel
9402065e0912bc5a87b034974693ae521b777588
[ "MIT" ]
null
null
null
resources/views/mstock/chongzhi.blade.php
xudong17/stock_laravel
9402065e0912bc5a87b034974693ae521b777588
[ "MIT" ]
null
null
null
resources/views/mstock/chongzhi.blade.php
xudong17/stock_laravel
9402065e0912bc5a87b034974693ae521b777588
[ "MIT" ]
null
null
null
<html style="font-size: 50px;"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>充值</title> <link rel="shortcut icon" href="{{ asset('favicon.ico') }}" type="image/x-icon"> <link href="{{ asset('mstock_assets/css/a.css') }}" rel="stylesheet"> <link href="{{ asset('mstock_assets/home/css/mui.css') }}" rel="stylesheet" /> <script src="{{ asset('mstock_assets/js/jquery-3.4.1.min.js') }}"></script> <script type="text/javascript">// 设置跟元素字体 document.documentElement.style.fontSize = document.documentElement.clientWidth / 7.5 + 'px' // var styleName = window.localStorage.getItem('styleName') // if(styleName == 'black'){ // document.getElementsByTagName('body')[0].className = 'black-bg' // }else{ // document.getElementsByTagName('body')[0].className = 'red-bg' // } //步骤一:创建异步对象 var ajax = new XMLHttpRequest() //步骤二:设置请求的url参数,参数一是请求的类型,参数二是请求的url,可以带参数,动态的传递参数starName到服务端 ajax.open('get', '/mstock/ajax?type=get_theme') //步骤三:发送请求 ajax.send() //步骤四:注册事件 onreadystatechange 状态改变就会调用 ajax.onreadystatechange = function () { if (ajax.readyState == 4 && ajax.status == 200) { //步骤五 如果能够进到这个判断 说明 数据 完美的回来了,并且请求的页面是存在的 //     console.log(JSON.parse(ajax.responseText).data);//输入相应的内容 var styleName = JSON.parse(ajax.responseText).data.siteColor // var styleName = window.localStorage.getItem('styleName') if (styleName == 'black') { window.localStorage.setItem('styleName', 'black') document.getElementsByTagName('body')[0].className = 'black-bg' } else if (styleName == 'yellow') { window.localStorage.setItem('styleName', 'red') document.getElementsByTagName('body')[0].className = 'yellow-bg' } else { window.localStorage.setItem('styleName', 'red') document.getElementsByTagName('body')[0].className = 'red-bg' } } }</script> <link href="{{ asset('mstock_assets/css/app.f43ba6eba25a8541867b353d66d64c2f.css') }}" rel="stylesheet"> </head> <body style="height: 100%; position: absolute; width: 100%;" class="black-bg" data-gr-c-s-loaded="true"> <div id="app"> <div data-v-7654e420="" class="wrapper"> <div data-v-7654e420="" class="header"> <header data-v-7654e420="" class="mint-header"> <div class="mint-header-button is-left"><a data-v-7654e420="" href="javascript:window.history.back();" class=""><button data-v-7654e420="" class="mint-button mint-button--default mint-button--normal"><span class="mint-button-icon"><i class="mintui mintui-back"></i></span> <label class="mint-button-text">我的</label></button></a></div> <h1 class="mint-header-title">充值</h1> <div class="mint-header-button is-right"></div> </header> </div> <div id="step"> <div data-v-7654e420="" class="box"> <div data-v-7654e420="" class="box-contain clearfix"> <div data-v-7654e420="" class="account text-center"> <p data-v-7654e420="" class="title">当前可用余额(元)</p> <p data-v-7654e420="" class="red number">{{$cancash}}</p> </div> </div> </div> <form id="czForm" action="/mstock/chongzhi?type=topay" method="POST"> <div data-v-7654e420="" class=" page-part transaction"> <div data-v-7654e420="" class="box-contain clearfix"> <div data-v-7654e420="" class="back-info"> <p data-v-7654e420="" class="title"> 选择面额(元) </p> <div data-v-7654e420="" class="box-tab"> <input data-v-7654e420="" type="number" class="btn-default" name="money" id="money" value="50000" min="{{$r6}}"> <div data-v-7654e420="" class="tab-con"> <ul data-v-7654e420="" class="radio-group clearfix" id="xzje"> <li data-v-7654e420=""> <div data-v-7654e420="" class="on" data-num="50000">50000</div> </li> <li data-v-7654e420=""> <div data-v-7654e420="" data-num="100000">100000</div> </li> <li data-v-7654e420=""> <div data-v-7654e420="" data-num="150000">150000</div> </li> <li data-v-7654e420=""> <div data-v-7654e420="" data-num="200000">200000</div> </li> </ul> </div> <p data-v-7654e420="" style="padding-bottom: 0.3rem;">最小充值金额为{{$r6}}元</p> </div> </div> <div data-v-7654e420="" class="back-info"> <p data-v-7654e420="" class="title"> 充值方式 </p> <div data-v-7654e420="" class="box-tab"> <div data-v-7654e420="" class="pay-radio"> <div data-v-7654e420="" class="pay-list on" style="display: flex;"><span data-v-7654e420="" class="col-md-4 pay-icon"><i data-v-7654e420="" class="iconfont icon-keyongzijin" style="color: rgb(18, 150, 219);"></i> 在线快捷支付 </span> <span data-v-7654e420="" class="col-md-4 pull-right" style="text-align: right;"><i data-v-7654e420="" class="icon-on iconfont icon-xuanzhong"></i></span></div> </div> </div> </div> </div> <div data-v-7654e420="" class="btnbox" id="btn_submit"> <span data-v-7654e420="" class="text-center btnok"> 立即充值 </span> </div> <div data-v-7654e420="" class="attention"> <p data-v-7654e420="">注意:充值默认充值在融资账户中。</p> </div> </div> <input type="hidden" name="agent" value="{{$agent}}" /> <input type="hidden" name="paytype" value="1" /> </form> </div> <div id="step1" style="display: none;"> <div data-v-7654e420="" class="box"> <div data-v-7654e420="" class="box-contain clearfix"> <div data-v-7654e420="" class="account text-center"> <p data-v-7654e420="" class="title">支付订单</p> <p data-v-7654e420="" class="red number" id="orderno">0</p> </div> </div> </div> <div data-v-77835d03="" class="form-block page-part"> <div data-v-77835d03="" class="mint-cell mint-field"> <div class="mint-cell-left"></div> <div class="mint-cell-wrapper"> <div class="mint-cell-title"> <span class="mint-cell-text">购币数量</span> </div> <div class="mint-cell-value"><input type="number" disabled="disabled" readonly class="mint-field-core" id="amount"> <span class="mint-field-state is-default"><i class="mintui mintui-field-default"></i></span> <div class="mint-field-other"></div> </div> </div> <div class="mint-cell-right"></div> </div> <div data-v-77835d03="" class="mint-cell mint-field"> <div class="mint-cell-left"></div> <div class="mint-cell-wrapper"> <div class="mint-cell-title"> <span class="mint-cell-text">支付金额(元)</span> </div> <div class="mint-cell-value"><input type="number" disabled="disabled" readonly class="mint-field-core" id="money1"> <span class="mint-field-state is-default"><i class="mintui mintui-field-default"></i></span> <div class="mint-field-other"></div> </div> </div> <div class="mint-cell-right"></div> </div> </div> <div data-v-0474a3b2="" class="back-info"> <p data-v-0474a3b2="" class="name"> 请向以下账户打款 <span id="money2" class="red">0</span> 元: </p> @foreach ($bank as $item) <ul data-v-0474a3b2="" style="padding-top:0.3rem;"> <li data-v-0474a3b2="" class="clearfix" style="display: flex;align-items: center;"> <div data-v-0474a3b2="" class="col-xs-1" style="padding-left: 0;"> <i data-v-7654e420="" class="iconfont icon-chongzhi" style="font-size:30px;color: rgb(0, 150, 136);"></i> </div> <div data-v-0474a3b2="" class="col-xs-7"> <p data-v-0474a3b2="">{{$item['bank']}}-{{$item['name']}}</p> <p data-v-0474a3b2="">{{$item['no']}}</p> </div> <div data-v-0474a3b2="" class="col-xs-4"> <button data-v-bfdcf7f4="" class="mint-button btn-red pull-right mint-button--danger mint-button--small copy_bankno" data-clipboard-text="{{$item['no']}}"> <label class="mint-button-text">复制卡号</label> </button> </div> </li> </ul> @endforeach <div data-v-7654e420="" class="btnbox" id="btn_submit_check"> <span data-v-7654e420="" class="text-center btnok"> 我已完成打款 </span> </div> <br> <p data-v-0474a3b2="" class="red" style="line-height:20px;">注意:打款完成后请一定记得点击上方 “我已完成打款” 按钮进行确认!</p> </div> </div> </div> </div> <script src="{{ asset('mstock_assets/home/js/moblie/mui.min.js') }}"></script> <script src="https://unpkg.com/clipboard@2/dist/clipboard.min.js"></script> <script> $(document).ready(function(){ $('#xzje li').on('click',function(){ var money = $(this).children('div').data('num'); $(this).children('div').addClass('on'); $(this).siblings().children('div').removeClass('on'); $('#money').val(money); }) var clipboard = new ClipboardJS('.copy_bankno'); clipboard.on('success', function (e) { mui.toast('复制成功'); e.clearSelection(); }); clipboard.on('error', function (e) { mui.toast('复制失败,请手动复制'); }); $('#btn_submit').on('click',function(e){ // $('#czForm').submit(); // return; e.preventDefault(); var data = $('#czForm').serialize(); $.ajax({ url: '/mstock/chongzhi?type=topay', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, type: 'POST', data: data, success: function(data){ var data = JSON.parse(data); if(data.code == 0){ var arr = data.msg.split('|'); var orderno = arr[1]; var amount = arr[2]; $('#orderno').text(orderno); $('#amount').val(amount); $('#money1').val($('#money').val()); $('#money2').text($('#money').val()); // $('#step').hide(); // $('#step1').show(); window.location.href="/mstock/chongzhi?orderno="+orderno; }else{ mui.toast(data.msg); } } }) // $.post('/mstock/chongzhi?type=topay',data,function(data){ // var data = JSON.parse(data); // if(data.code == 0){ // var arr = data.msg.split('|'); // var orderno = arr[1]; // var amount = arr[2]; // $('#orderno').text(orderno); // $('#amount').val(amount); // $('#money1').val($('#money').val()); // $('#money2').text($('#money').val()); // // $('#step').hide(); // // $('#step1').show(); // window.location.href="/mstock/chongzhi?orderno="+orderno; // }else{ // mui.toast(data.msg); // } // }) }) $('#btn_submit_check').on('click',function(){ //var data = mui.toast('状态调整成功,等待管理员确认'); }); }) </script> </body> </html>
53.205036
187
0.421608
a4218ac2d0ce1202c6ee4f8d5b421837d385e80b
2,584
php
PHP
system/core/Lang.php
nazar-007/article.kg
552e97ef4b32628b680b95d76b20c70e50f1be1d
[ "MIT" ]
null
null
null
system/core/Lang.php
nazar-007/article.kg
552e97ef4b32628b680b95d76b20c70e50f1be1d
[ "MIT" ]
null
null
null
system/core/Lang.php
nazar-007/article.kg
552e97ef4b32628b680b95d76b20c70e50f1be1d
[ "MIT" ]
null
null
null
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class CI_Lang { public $language = array(); public $is_loaded = array(); public function __construct() { log_message('info', 'Language Class Initialized'); } public function load($langfile, $idiom = '', $return = FALSE, $add_suffix = TRUE, $alt_path = '') { if (is_array($langfile)) { foreach ($langfile as $value) { $this->load($value, $idiom, $return, $add_suffix, $alt_path); } return; } $langfile = str_replace('.php', '', $langfile); if ($add_suffix === TRUE) { $langfile = preg_replace('/_lang$/', '', $langfile).'_lang'; } $langfile .= '.php'; if (empty($idiom) OR ! preg_match('/^[a-z_-]+$/i', $idiom)) { $config =& get_config(); $idiom = empty($config['language']) ? 'english' : $config['language']; } if ($return === FALSE && isset($this->is_loaded[$langfile]) && $this->is_loaded[$langfile] === $idiom) { return; } // Load the base file, so any others found can override it $basepath = BASEPATH.'language/'.$idiom.'/'.$langfile; if (($found = file_exists($basepath)) === TRUE) { include($basepath); } // Do we have an alternative path to look in? if ($alt_path !== '') { $alt_path .= 'language/'.$idiom.'/'.$langfile; if (file_exists($alt_path)) { include($alt_path); $found = TRUE; } } else { foreach (get_instance()->load->get_package_paths(TRUE) as $package_path) { $package_path .= 'language/'.$idiom.'/'.$langfile; if ($basepath !== $package_path && file_exists($package_path)) { include($package_path); $found = TRUE; break; } } } if ($found !== TRUE) { show_error('Unable to load the requested language file: language/'.$idiom.'/'.$langfile); } if ( ! isset($lang) OR ! is_array($lang)) { log_message('error', 'Language file contains no data: language/'.$idiom.'/'.$langfile); if ($return === TRUE) { return array(); } return; } if ($return === TRUE) { return $lang; } $this->is_loaded[$langfile] = $idiom; $this->language = array_merge($this->language, $lang); log_message('info', 'Language file loaded: language/'.$idiom.'/'.$langfile); return TRUE; } public function line($line, $log_errors = TRUE) { $value = isset($this->language[$line]) ? $this->language[$line] : FALSE; // Because killer robots like unicorns! if ($value === FALSE && $log_errors === TRUE) { log_message('error', 'Could not find the language line "'.$line.'"'); } return $value; } }
22.469565
104
0.595201
ccc6394b928f773bd54bd08e3f7e891405eb929f
1,277
rb
Ruby
spec/classes/agent_spec.rb
allan-reynolds/puppet-cloudstack
9cc8733322c3d7e6fb847872470cddc28921abb2
[ "Apache-2.0" ]
null
null
null
spec/classes/agent_spec.rb
allan-reynolds/puppet-cloudstack
9cc8733322c3d7e6fb847872470cddc28921abb2
[ "Apache-2.0" ]
null
null
null
spec/classes/agent_spec.rb
allan-reynolds/puppet-cloudstack
9cc8733322c3d7e6fb847872470cddc28921abb2
[ "Apache-2.0" ]
4
2015-05-19T17:58:16.000Z
2020-01-19T13:17:46.000Z
require 'spec_helper' describe 'cloudstack::agent' do Puppet::Util::Log.level = :warning Puppet::Util::Log.newdestination(:console) context "ubuntu" do let(:facts) { @ubuntu_facts } context "defaults" do it { should compile.with_all_deps } it { should contain_class('cloudstack::install::repo') } it { should contain_class('cloudstack::install::repo::apt') } it { should contain_class('apt') } it { should contain_apt__source('cloudstack').with({ 'location' => 'http://cloudstack.apt-get.eu/ubuntu', 'release' => 'trusty', 'repos' => '4.9', }) } it { should contain_package('cloudstack-agent') } end end context "centos" do let(:facts) { @centos_facts } context "defaults" do it { should compile.with_all_deps } it { should contain_class('cloudstack::install::repo') } it { should contain_class('cloudstack::install::repo::yum') } it { should contain_yumrepo('cloudstack').with({ 'baseurl' => 'http://cloudstack.apt-get.eu/centos/7/4.9', 'gpgcheck' => true, }) } it { should contain_package('cloudstack-agent') } end end end
28.377778
69
0.575568
3af5b6fa797c57b2dbed85bb2536afd35ee4f237
2,804
ps1
PowerShell
remove-BOM-from-files.ps1
jasongilbertson/powershellScripts
82b0293d3bf5c27aa8c7b31800b1a0fe7082615d
[ "MIT" ]
17
2016-04-14T16:41:29.000Z
2022-01-24T14:38:01.000Z
remove-BOM-from-files.ps1
jasongilbertson/powershellScripts
82b0293d3bf5c27aa8c7b31800b1a0fe7082615d
[ "MIT" ]
1
2017-07-19T16:51:26.000Z
2019-11-12T03:50:38.000Z
remove-BOM-from-files.ps1
jasongilbertson/powershellScripts
82b0293d3bf5c27aa8c7b31800b1a0fe7082615d
[ "MIT" ]
10
2018-05-05T18:27:34.000Z
2021-08-11T03:21:18.000Z
<# # cleans BOM from start of file in utf encoded files. # BOM affects use of iwr %script% | iex # this will convert files with BOM to utf-8 with no BOM # https://stackoverflow.com/questions/5596982/using-powershell-to-write-a-file-in-utf-8-without-the-bom example from iwr script download output PS C:\Users\cloudadmin> $t = iwr "http://aka.ms/directory-treesize.ps1" PS C:\Users\cloudadmin> $t | iex iex : At line:58 char:7 + do not display output PS C:\Users\cloudadmin> $t | fl * Content : {239, 187, 191, 60...} StatusCode : 200 StatusDescription : OK RawContentStream : Microsoft.PowerShell.Commands.WebResponseContentMemoryStream RawContentLength : 18585 RawContent : HTTP/1.1 200 OK ... X-Powered-By: ASP.NET issue------>>>> ???<# .SYNOPSIS powershell script to to enumerate directory summarizing in tree view directories over a given size #> param( $path = (get-location).path, $extensionFilter = "*.ps1", [switch]$listOnly, [switch]$saveAsAscii, [switch]$force ) $Utf8NoBom = New-Object Text.UTF8Encoding($False) function main() { foreach($file in get-childitem -Path $path -recurse -filter $extensionFilter) { $hasBom = has-bom -file $file if($hasBom -or $saveAsAscii -or $force) { if($hasBom) { write-host "file has bom: $($file.fullname)" -ForegroundColor Yellow } if(!$listOnly) { write-warning "re-writing file without bom: $($file.fullname)" $content = Get-Content $file.fullname -Raw if($saveAsAscii) { out-file -InputObject $content -Encoding ascii -FilePath ($file.fullname) } else { [System.IO.File]::WriteAllLines($file.fullname, $content, $Utf8NoBom) } } } else { write-host "file does *not* have bom: $($file.fullname)" -ForegroundColor Green } } } function has-bom($file) { [Byte[]]$bom = Get-Content -Encoding Byte -ReadCount 4 -TotalCount 4 -Path $file.fullname foreach ($encoding in [text.encoding]::GetEncodings().GetEncoding()) { $preamble = $encoding.GetPreamble() if ($preamble) { foreach ($i in 0..$preamble.Length) { if ($preamble[$i] -ne $bom[$i]) { continue } elseif ($i -eq $preable.Length) { return $true } } } } return $false } main
27.223301
117
0.530314
cc74038bbc83a870a29aca18910a61f8cbdbd01c
726
kt
Kotlin
compiler/testData/diagnostics/tests/TypeInference.kt
qussarah/declare
c83b764c7394efa3364915d973ae79c4ebed2437
[ "Apache-2.0" ]
7
2017-06-13T03:01:04.000Z
2021-04-22T03:01:06.000Z
compiler/testData/diagnostics/tests/TypeInference.kt
qussarah/declare
c83b764c7394efa3364915d973ae79c4ebed2437
[ "Apache-2.0" ]
null
null
null
compiler/testData/diagnostics/tests/TypeInference.kt
qussarah/declare
c83b764c7394efa3364915d973ae79c4ebed2437
[ "Apache-2.0" ]
4
2019-06-24T07:33:49.000Z
2020-04-21T21:52:37.000Z
class C<T>() { fun foo() : T {<!NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY!>}<!> } fun foo(<!UNUSED_PARAMETER!>c<!>: C<Int>) {} fun <T> bar() : C<T> {<!NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY!>}<!> fun main(args : Array<String>) { val <!UNUSED_VARIABLE!>a<!> : C<Int> = C(); val <!UNUSED_VARIABLE!>x<!> : C<in String> = C() val <!UNUSED_VARIABLE!>y<!> : C<out String> = C() val <!UNUSED_VARIABLE!>z<!> : C<*> = <!TYPE_INFERENCE_NO_INFORMATION_FOR_PARAMETER!>C<!>() val <!UNUSED_VARIABLE!>ba<!> : C<Int> = bar(); val <!UNUSED_VARIABLE!>bx<!> : C<in String> = bar() val <!UNUSED_VARIABLE!>by<!> : C<out String> = bar() val <!UNUSED_VARIABLE!>bz<!> : C<*> = <!TYPE_INFERENCE_NO_INFORMATION_FOR_PARAMETER!>bar<!>() }
40.333333
95
0.62259
5710a5f3b9e45f915c37bc03b24eb25460ec1d25
97
js
JavaScript
src/pages/Popup/selectors/index.js
Blockits/Wallet
e8404b6d4375ee55da1fcb9867594a9b0cb38892
[ "MIT" ]
null
null
null
src/pages/Popup/selectors/index.js
Blockits/Wallet
e8404b6d4375ee55da1fcb9867594a9b0cb38892
[ "MIT" ]
null
null
null
src/pages/Popup/selectors/index.js
Blockits/Wallet
e8404b6d4375ee55da1fcb9867594a9b0cb38892
[ "MIT" ]
null
null
null
export * from './selectors'; export * from './confirm-transaction'; export * from './custom-gas';
32.333333
38
0.680412
7293cc110105a92a883053769051a81e67fa6862
4,877
cs
C#
MechFallSequenceDamageAdder.cs
janxious/CharlesB
7184586b1322ee79732ef701865adaee63c92587
[ "MIT" ]
2
2019-05-16T23:23:48.000Z
2019-07-12T14:08:10.000Z
MechFallSequenceDamageAdder.cs
janxious/CharlesB
7184586b1322ee79732ef701865adaee63c92587
[ "MIT" ]
13
2018-06-07T06:32:40.000Z
2018-10-06T16:36:49.000Z
MechFallSequenceDamageAdder.cs
janxious/CharlesB
7184586b1322ee79732ef701865adaee63c92587
[ "MIT" ]
3
2018-07-31T01:52:47.000Z
2021-05-29T09:14:40.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Reflection.Emit; using BattleTech; using Harmony; using UnityEngine; namespace CharlesB { [HarmonyPatch(typeof(MechFallSequence), "setState")] public static class MechFallSequenceDamageAdder { static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { if (!Core.ModSettings.FallingDamage) return instructions; var instructionList = instructions.ToList(); var insertionIndex = instructionList.FindIndex( instruction => instruction.opcode == OpCodes.Ret // find early return ) + 2; var nopLabelReplaceIndex = insertionIndex - 1; instructionList[nopLabelReplaceIndex].opcode = OpCodes.Nop; // preserve jump label instructionList.Insert(insertionIndex, new CodeInstruction(OpCodes.Ldarg_0)); // replace code we just mangled var stateField = AccessTools.Field(typeof(MechFallSequence), "state"); var owningMechGetter = AccessTools.Property(typeof(MechFallSequence), "OwningMech").GetGetMethod(); var calculator = AccessTools.Method( typeof(MechFallSequenceDamageAdder), "ApplyFallingDamage", new Type[] {typeof(MechFallSequence), typeof(int), typeof(int)} ); var damageMethodCalloutInstructions = new List<CodeInstruction>(); damageMethodCalloutInstructions.Add(new CodeInstruction(OpCodes.Ldarg_0)); // this damageMethodCalloutInstructions.Add(new CodeInstruction(OpCodes.Ldarg_0)); // this damageMethodCalloutInstructions.Add(new CodeInstruction(OpCodes.Ldfld, stateField)); // this.state damageMethodCalloutInstructions.Add(new CodeInstruction(OpCodes.Ldarg_1)); // newState (Argument) damageMethodCalloutInstructions.Add(new CodeInstruction(OpCodes.Call, calculator)); // MechFallSequenceDamageAdder.DoDamage(this, this.state, newState) instructionList.InsertRange(insertionIndex, damageMethodCalloutInstructions); return instructionList; } private const int FinishedState = 3; private static readonly ArmorLocation[] possibleLocations = new[] { ArmorLocation.Head, ArmorLocation.CenterTorso, ArmorLocation.CenterTorsoRear, ArmorLocation.LeftTorso, ArmorLocation.LeftTorsoRear, ArmorLocation.RightTorso, ArmorLocation.RightTorsoRear, ArmorLocation.LeftArm, ArmorLocation.RightArm, ArmorLocation.RightLeg, ArmorLocation.LeftLeg }; static void ApplyFallingDamage(MechFallSequence sequence, int oldState, int newState) { if (newState != FinishedState) return; var mech = sequence.OwningMech; if (mech.IsFlaggedForDeath || mech.IsDead) return; // TODO: maybe even the dead should take damage? var locationTakingDamage = possibleLocations[UnityEngine.Random.Range(0, possibleLocations.Length)]; Logger.Debug($"falling happened!\nlocation taking damage: {locationTakingDamage}"); var rawFallingDamage = Core.ModSettings.FallingAmountDamagePerTon * mech.tonnage; var fallingDamageValue = rawFallingDamage; if (Core.ModSettings.PilotingSkillFallingDamageMitigation) { var mitigation = Calculator.PilotingMitigation(mech); var mitigationPercent = Mathf.RoundToInt(mitigation * 100); fallingDamageValue = rawFallingDamage - (mitigation * rawFallingDamage); Logger.Debug($"falling damage numbers\n" + $"pilotSkill: {mech.SkillPiloting}\n" + $"mitigation: {mitigation}\n" + $"rawFallingDamage: {rawFallingDamage}\n" + $"mitigationPercent: {mitigationPercent}\n" + $"fallingDamageValue: {fallingDamageValue}"); mech.Combat.MessageCenter.PublishMessage(new AddSequenceToStackMessage(new ShowActorInfoSequence(mech, $"Pilot Check: Avoided {mitigationPercent}% Falling Damage!", FloatieMessage.MessageNature.Neutral, true))); } mech.DEBUG_DamageLocation(locationTakingDamage, fallingDamageValue, mech, damageType: DamageType.Knockdown); if (AttackDirector.damageLogger.IsLogEnabled) { AttackDirector.damageLogger.Log($"@@@@@@@@ {mech.DisplayName} takes {fallingDamageValue} damage to its {Mech.GetLongArmorLocation(locationTakingDamage)} from falling!"); } } } }
55.420455
227
0.648349
ca2218ae2505774847192bc8e7fcc83e7a83f5b6
2,092
kt
Kotlin
arlocalizerview/src/main/java/com/netguru/arlocalizerview/location/LocationProvider.kt
masilv4/ar-localizer-view-android
1630602759b9c0132c82e01bceb3061d93dcad8f
[ "Apache-2.0" ]
30
2019-10-23T10:53:55.000Z
2022-02-17T08:14:05.000Z
arlocalizerview/src/main/java/com/netguru/arlocalizerview/location/LocationProvider.kt
tzasacky/ar-localizer-view-android
1630602759b9c0132c82e01bceb3061d93dcad8f
[ "Apache-2.0" ]
24
2019-10-08T05:57:37.000Z
2022-02-26T05:45:28.000Z
arlocalizerview/src/main/java/com/netguru/arlocalizerview/location/LocationProvider.kt
tzasacky/ar-localizer-view-android
1630602759b9c0132c82e01bceb3061d93dcad8f
[ "Apache-2.0" ]
11
2019-11-19T10:47:04.000Z
2021-12-23T06:35:11.000Z
package com.netguru.arlocalizerview.location import android.annotation.SuppressLint import android.location.Location import com.google.android.gms.location.LocationRequest import com.patloew.rxlocation.RxLocation import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.schedulers.Schedulers import kotlin.math.roundToInt internal class LocationProvider(private val rxLocation: RxLocation) { companion object { private const val LOCATION_REQUEST_INTERVAL = 5000L private const val FASTEST_REQUEST_INTERVAL = 20L private const val SMALLEST_DISPLACEMENT_NOTICED = 1f } private val locationRequest = LocationRequest().apply { interval = LOCATION_REQUEST_INTERVAL fastestInterval = FASTEST_REQUEST_INTERVAL smallestDisplacement = SMALLEST_DISPLACEMENT_NOTICED priority = LocationRequest.PRIORITY_HIGH_ACCURACY } @SuppressLint("MissingPermission") fun getLocationUpdates(): Flowable<LocationData> { return rxLocation.settings().checkAndHandleResolution(locationRequest) .toObservable() .flatMap { rxLocation.location().updates(locationRequest) } .subscribeOn(Schedulers.computation()) .observeOn(Schedulers.computation()) .toFlowable(BackpressureStrategy.LATEST) .flatMap { location -> Flowable.just( LocationData( location.latitude, location.longitude ) ) } } fun getDistanceBetweenPoints(currentLocation: LocationData?, destinationLocation: LocationData?): Int { val locationA = Location("A") locationA.latitude = currentLocation?.latitude ?: 0.0 locationA.longitude = currentLocation?.longitude ?: 0.0 val locationB = Location("B") locationB.latitude = destinationLocation?.latitude ?: 0.0 locationB.longitude = destinationLocation?.longitude ?: 0.0 return locationA.distanceTo(locationB).roundToInt() } }
36.068966
78
0.691683
641a04c2bc6d7d4924e239bbed4a887650349429
151
py
Python
my-detection-python/test-logs.py
Clark1216/Nvidia_Jetson-TensorRT_Inference_Basics
e45a6972ea9e231f1baa371ac4ec2e49e9b0067f
[ "MIT" ]
1
2022-02-08T02:07:26.000Z
2022-02-08T02:07:26.000Z
my-detection-python/test-logs.py
Clark1216/Nvidia_Jetson-inference
e45a6972ea9e231f1baa371ac4ec2e49e9b0067f
[ "MIT" ]
null
null
null
my-detection-python/test-logs.py
Clark1216/Nvidia_Jetson-inference
e45a6972ea9e231f1baa371ac4ec2e49e9b0067f
[ "MIT" ]
null
null
null
#!/usr/bin/python3 import logging logging.basicConfig(filename='log.log', level=logging.DEBUG) logging.info('This message should go to the log file')
25.166667
60
0.774834
6db45a4690a6c5fff203aefa77cc09ea415768f6
1,440
h
C
planning&perception/calibration_camera_laser/camera-laser-calibration/camLaserCalib/include/EllipseDetector.h
Hinson-A/guyueclass
e59129526729542dccefa6c7232378a00dc0175a
[ "Apache-2.0" ]
227
2021-01-20T05:34:32.000Z
2022-03-29T12:43:05.000Z
planning&perception/calibration_camera_laser/camera-laser-calibration/camLaserCalib/include/EllipseDetector.h
passYYYY/guyueclass
2054ccec2f5e6c002727a5561b494a1046484504
[ "Apache-2.0" ]
1
2021-04-22T05:56:00.000Z
2021-05-26T06:00:17.000Z
planning&perception/calibration_camera_laser/camera-laser-calibration/camLaserCalib/include/EllipseDetector.h
passYYYY/guyueclass
2054ccec2f5e6c002727a5561b494a1046484504
[ "Apache-2.0" ]
239
2021-01-28T02:59:53.000Z
2022-03-29T08:02:17.000Z
#pragma once //#include <opencv2/core/core.hpp> //#include <opencv2/imgproc/imgproc.hpp> //#include <opencv2/calib3d/calib3d.hpp> #include <opencv2/opencv.hpp> #include "Ellipse.h" // #include <opencv2/highgui/highgui.hpp> using namespace cv; using std::pair; class EllipseDetector { public: EllipseDetector(void); ~EllipseDetector(void); void processFrame(const Mat& _frame); private: bool findEllipses(const Mat& _frame, vector<EllipseN>& _detectedEllipses); void findEllipseContours(const Mat& _imgThreshold, vector<vector<Point>>& _contours, int _minContourPointsAllowed); void findEllipseCandidates(const vector<vector<Point>>& _contours, vector<EllipseN>& _detectedEllipses); void sortEllipses( vector<EllipseN>& _detectedEllipses); void rankX(vector<EllipseN>& _detectedE); void rankY(vector<EllipseN>& _detectedE); void estimatePosition(vector<EllipseN>& _detectedEllipses); void color_filter(Mat& _imgHsv); private: float m_minContourLengthAllowed; vector<Point2f> m_ellipseCorners2d; vector<Point3f> m_ellipseCorners3d; Mat m_camMat; Mat m_distCoeff; public: //Mat m_imgGray; //Mat m_imgThreshold; Mat m_imgHsv; Mat m_imgCanny; vector<vector<Point>> m_contours; vector< Point > hull; double t_fx,t_fy,t_cx,t_cy; size_t pairNum; //FILE *fp; public: vector<EllipseN> m_ellipses; vector<EllipseN> m_ellipsesRight; vector<EllipseN> m_ellipsesLeft; };
29.387755
117
0.752083
d36b39246e2c14e51258eaa7892b79bb3d5597d9
11,718
dart
Dart
lib/src/simulations/maurer_rose.dart
SGeetansh/simulate
0a67b7e4a9f0a49a808b4c12a76dca8accfc643b
[ "MIT" ]
null
null
null
lib/src/simulations/maurer_rose.dart
SGeetansh/simulate
0a67b7e4a9f0a49a808b4c12a76dca8accfc643b
[ "MIT" ]
null
null
null
lib/src/simulations/maurer_rose.dart
SGeetansh/simulate
0a67b7e4a9f0a49a808b4c12a76dca8accfc643b
[ "MIT" ]
null
null
null
import 'dart:io'; import 'dart:math'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; GlobalKey<MaurerRoseState> globalKey = GlobalKey<MaurerRoseState>(); class MaurerRoseCurve extends StatefulWidget { @override MaurerRoseCurveState createState() => MaurerRoseCurveState(); } class MaurerRoseCurveState extends State<MaurerRoseCurve> { double n = 0; double d = 0; // double dn = 0.001; // double dd = 0.001; bool animateN = false; bool animateD = false; bool animating = false; @override void initState() { SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]); super.initState(); } @override dispose() { SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight, ]); super.dispose(); } @override Widget build(BuildContext context) { ScreenUtil.init( context, width: 512.0, height: 1024.0, allowFontScaling: true, ); return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, leading: IconButton( icon: Icon(Icons.arrow_back_ios), onPressed: () { Navigator.pop(context); }, ), title: Text( 'MaurerRose Pattern', style: Theme.of(context).textTheme.headline6, ), centerTitle: true, ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, floatingActionButton: Padding( padding: const EdgeInsets.all(8.0), child: Visibility( visible: animateN || animateD, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ FloatingActionButton( heroTag: null, backgroundColor: Colors.white, child: (!animating) ? Icon( Icons.play_arrow, color: Colors.black, ) : Icon( Icons.pause, color: Colors.black, ), onPressed: () { setState(() { animating = !animating; d = globalKey.currentState.widget.d; n = globalKey.currentState.widget.n; }); }), FloatingActionButton( heroTag: null, child: Icon( Icons.highlight_off, color: Colors.black, ), backgroundColor: Colors.white, onPressed: () { setState(() { if (animateN) { n = 0; } if (animateD) { d = 0; } }); }, ) ], ), ), ), bottomNavigationBar: Container( height: ScreenUtil().setHeight(1024 / 5), child: Material( elevation: 30, color: Theme.of(context).primaryColor, child: ListView( padding: EdgeInsets.all(8.0), children: <Widget>[ SizedBox( height: 20, ), Slider( min: 0, max: 20, divisions: 200, activeColor: Theme.of(context).accentColor, inactiveColor: Colors.grey, onChanged: (animating) ? null : (value) { setState(() { n = double.parse(value.toStringAsFixed(1)); }); }, value: n, ), Center( child: Text( (animating && animateN) ? "N: Animating" : "N: ${n.toStringAsFixed(1)}", style: Theme.of(context).textTheme.subtitle2, ), ), Slider( min: 0, max: 100, divisions: 100, activeColor: Theme.of(context).accentColor, inactiveColor: Colors.grey, onChanged: (animating) ? null : (value) { setState(() { d = double.parse(value.toStringAsFixed(1)); }); }, value: d, ), Center( child: Text( (animating && animateD) ? "D: Animating" : "D: ${d.toStringAsFixed(1)}", style: Theme.of(context).textTheme.subtitle2, ), ), // Slider( // min: 0.001, // max: 0.01, // divisions: 9, // activeColor: Theme.of(context).accentColor, // inactiveColor: Colors.grey, // onChanged: (value) { // setState(() { // dn = double.parse(value.toStringAsFixed(3)); // }); // }, // value: dn, // ), // Center( // child: Text( // "dn: ${dn.toStringAsFixed(3)}", // style: Theme.of(context).textTheme.subtitle2, // ), // ), // Slider( // min: 0.001, // max: 0.01, // divisions: 9, // activeColor: Theme.of(context).accentColor, // inactiveColor: Colors.grey, // onChanged: (value) { // setState(() { // dd = double.parse(value.toStringAsFixed(3)); // }); // }, // value: dd, // ), // Center( // child: Text( // "dd: ${dd.toStringAsFixed(3)}", // style: Theme.of(context).textTheme.subtitle2, // ), // ), ], ), ), ), body: Container( width: MediaQuery.of(context).size.width, child: Stack( children: <Widget>[ MaurerRose( d: d, n: n, // dd: dd, // dn: dn, animateN: animateN, animateD: animateD, animating: animating, key: globalKey, ), Positioned( left: 12, child: Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Text( 'Animate with N:', ), Checkbox( onChanged: (animating) ? null : (_) { setState(() { animateN = !animateN; }); }, activeColor: Colors.red, value: animateN, ), ], ), ), Positioned( child: Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Text( 'Animate with D:', ), Checkbox( onChanged: (animating) ? null : (_) { setState(() { animateD = !animateD; }); }, activeColor: Colors.red, value: animateD, ), ], ), ), ], ), ), ); } } class MaurerRose extends StatefulWidget { MaurerRose({ Key key, @required this.d, @required this.n, // @required this.dd, // @required this.dn, @required this.animateN, @required this.animateD, @required this.animating, }) : super(key: key); double d; double n; // double dd; // double dn; final bool animateN; final bool animateD; final bool animating; @override MaurerRoseState createState() => MaurerRoseState(); } class MaurerRoseState extends State<MaurerRose> { nextStep() { setState(() { sleep(Duration(milliseconds: 10)); if (widget.animateN) { widget.n += 0.003; } if (widget.animateD) { widget.d += 0.005; } if (widget.n > 20) { widget.n = 0; } if (widget.d > 100) { widget.d = 0; } }); } @override Widget build(BuildContext context) { if (widget.animating) { WidgetsBinding.instance.addPostFrameCallback((_) { nextStep(); }); } return Stack( alignment: Alignment.center, children: <Widget>[ CustomPaint( painter: MaurerRosePainter( widget.d, widget.n, (MediaQuery.of(context).size.width / 2).roundToDouble(), (MediaQuery.of(context).size.height / 3).roundToDouble(), Theme.of(context).accentColor, ), child: Container(), ), Visibility( visible: widget.animateN, child: Positioned( bottom: 60, child: Text("N: ${widget.n.toStringAsFixed(1)}"), ), ), Visibility( visible: widget.animateD, child: Positioned( bottom: 40, child: Text("D: ${widget.d.toStringAsFixed(1)}"), ), ), ], ); } } class MaurerRosePainter extends CustomPainter { double d, n, c; double k, transformx, transformy; List<Offset> points = []; List<Offset> points2 = []; Color color; double q, x, y; int theta, r = 300; MaurerRosePainter( this.d, this.n, this.transformx, this.transformy, this.color, ) { k = n / d; } @override void paint(Canvas canvas, Size size) { var paint = Paint() ..color = color ..style = PaintingStyle.stroke ..strokeWidth = 1; for (theta = 0; theta <= 360; theta++) { k = theta * d * pi / 180; q = r * sin(n * k); x = q * cos(k); y = q * sin(k); this .points .add(Offset(x / 1.5, y / 1.5).translate(transformx, transformy)); } canvas.drawPoints(PointMode.polygon, points, paint); var paint2 = Paint() ..color = Colors.red ..style = PaintingStyle.stroke ..strokeWidth = 3; for (theta = 0; theta <= 360; theta++) { k = theta * pi / 180; q = r * sin(n * k); x = q * cos(k); y = q * sin(k); this .points2 .add(Offset(x / 1.5, y / 1.5).translate(transformx, transformy)); } canvas.drawPoints(PointMode.polygon, points2, paint2); } @override bool shouldRepaint(MaurerRosePainter oldDelegate) => true; @override bool shouldRebuildSemantics(MaurerRosePainter oldDelegate) => false; }
27.9
78
0.434801
db91b4543a367e98a6da0d50e53cf0ae482dc7b2
3,497
php
PHP
tests/Factory/LinkComposerTest.php
bednic/json-ap
bbff80c1f416926140a9990575bcf9f4bad0fcab
[ "MIT" ]
3
2020-05-12T20:40:15.000Z
2020-07-07T08:28:59.000Z
tests/Factory/LinkComposerTest.php
bednic/json-api
bbff80c1f416926140a9990575bcf9f4bad0fcab
[ "MIT" ]
null
null
null
tests/Factory/LinkComposerTest.php
bednic/json-api
bbff80c1f416926140a9990575bcf9f4bad0fcab
[ "MIT" ]
null
null
null
<?php declare(strict_types=1); namespace JSONAPI\Test\Factory; use Doctrine\Common\Cache\ArrayCache; use JSONAPI\Document\Document; use JSONAPI\Document\Id; use JSONAPI\Document\Link; use JSONAPI\Document\Relationship; use JSONAPI\Document\ResourceObject; use JSONAPI\Document\Type; use JSONAPI\Driver\AnnotationDriver; use JSONAPI\Factory\LinkComposer; use JSONAPI\Factory\MetadataFactory; use JSONAPI\URI\URIParser; use PHPUnit\Framework\TestCase; use Roave\DoctrineSimpleCache\SimpleCacheAdapter; use Slim\Psr7\Factory\ServerRequestFactory; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\Psr16Cache; class LinkComposerTest extends TestCase { /** * @var URIParser */ private static URIParser $up; private static string $baseURL; public static function setUpBeforeClass(): void { $metadata = MetadataFactory::create( [RESOURCES . '/valid'], new Psr16Cache(new ArrayAdapter()), new AnnotationDriver() ); $request = ServerRequestFactory::createFromGlobals(); self::$baseURL = 'http://unit.test.org/api'; self::$up = new URIParser($request, $metadata, self::$baseURL); } public function testSetDocumentLinks() { $document = new Document(); $factory = new LinkComposer(self::$baseURL); $factory->setDocumentLinks($document, self::$up); $links = $document->getLinks(); $this->assertIsArray($links); $this->assertArrayHasKey(Link::SELF, $links); $self = $links[Link::SELF]; $this->assertEquals( 'http://unit.test.org/api/getter/uuid?include=collection&' . 'fields%5Bresource%5D=publicProperty,privateProperty,relations', $self->getData() ); $this->assertTrue(filter_var($self->getData(), FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE) !== null); } public function testSetRelationshipLinks() { $resource = new ResourceObject(new Type('resource'), new Id('id')); $relationship = new Relationship('test'); $relationship->setData(null); $factory = new LinkComposer(self::$baseURL); $factory->setRelationshipLinks($relationship, $resource); $links = $relationship->getLinks(); $this->assertIsArray($links); $this->assertArrayHasKey(Link::SELF, $links); $self = $links[Link::SELF]; $this->assertEquals('http://unit.test.org/api/resource/id/relationships/test', $self->getData()); $this->assertTrue(filter_var($self->getData(), FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE) !== null); $related = $links[Link::RELATED]; $this->assertEquals('http://unit.test.org/api/resource/id/test', $related->getData()); $this->assertTrue(filter_var($related->getData(), FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE) !== null); } public function testSetResourceLink() { $resource = new ResourceObject(new Type('resource'), new Id('id')); $factory = new LinkComposer(self::$baseURL); $factory->setResourceLink($resource); $links = $resource->getLinks(); $this->assertIsArray($links); $this->assertArrayHasKey(Link::SELF, $links); $self = $links[Link::SELF]; $this->assertEquals('http://unit.test.org/api/resource/id', $self->getData()); $this->assertTrue(filter_var($self->getData(), FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE) !== null); } }
38.01087
113
0.661996
cf07d1ad96ba3c92b11f9ddd464e69fed5fb4c0e
1,918
php
PHP
app/Exports/DataTableExportStatusReport.php
hassanshuja/quotation
0311193fcaffec43ee329fbe28f219eeac9bb727
[ "MIT" ]
null
null
null
app/Exports/DataTableExportStatusReport.php
hassanshuja/quotation
0311193fcaffec43ee329fbe28f219eeac9bb727
[ "MIT" ]
4
2020-07-19T00:54:05.000Z
2022-02-10T20:28:22.000Z
app/Exports/DataTableExportStatusReport.php
hassanshuja/quotation
0311193fcaffec43ee329fbe28f219eeac9bb727
[ "MIT" ]
null
null
null
<?php namespace App\Exports; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder; use Maatwebsite\Excel\Concerns\WithHeadings; use Maatwebsite\Excel\Concerns\FromCollection; class DataTableExportStatusReport implements FromCollection, WithHeadings { protected $headings; protected $query; protected $columns; protected $invoice_rows; public function __construct(array $headings, Builder $query, array $columns, array $invoice_rows) { $this->headings = $headings; $this->query = $query; $this->columns = $columns; $this->invoice_rows = $invoice_rows; } public function headings(): array { array_push($this->headings, 'invoice_number'); return $this->headings; } public function collection() { array_push($this->columns, 'id'); $res = $this->query->with('quotes')->get($this->columns); foreach($res as $key => $val) { foreach($this->invoice_rows as $rowz){ if($val['quotes'] !== null && $val['status'] == 'Invoiced'){ if(json_decode($rowz->id) !== null){ if(in_array($val['quotes']['id'], json_decode($rowz->id))){ $res[$key]['invoice_number'] = $rowz->invoice_number; break; }else{ $res[$key]['invoice_number'] = ''; } } }else{ $res[$key]['invoice_number'] = ''; } } } array_push($this->columns, 'invoice_number'); return $res->each(function (Model $item) { unset($item->id); return $item->setAppends([]); }); } }
28.205882
101
0.499479
cd4f13837c08c2e8768bbf3d3bafdb61f8227d71
1,736
cs
C#
I18N/src/Cosmos.I18N/Languages/LanguageManager.cs
chinayou25/Cosmos
a0645267fb7fe3c3c83610f0a91b47a193879b64
[ "MIT" ]
3
2021-04-13T01:53:01.000Z
2021-04-15T21:47:00.000Z
I18N/src/Cosmos.I18N/Languages/LanguageManager.cs
chinayou25/Cosmos
a0645267fb7fe3c3c83610f0a91b47a193879b64
[ "MIT" ]
null
null
null
I18N/src/Cosmos.I18N/Languages/LanguageManager.cs
chinayou25/Cosmos
a0645267fb7fe3c3c83610f0a91b47a193879b64
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using EnumsNET; namespace Cosmos.I18N.Languages { public class LanguageManager { private readonly IList<Locale> _usedLanguages = new List<Locale>(); private readonly object _langObject = new object(); public LanguageManager() { } #region Contains public bool Contains(string langName) { return !string.IsNullOrWhiteSpace(langName) && Contains(langName.ToLocale()); } public bool Contains(Locale locale) { return _usedLanguages.Contains(locale); } #endregion #region Get language public Locale GetLanguage(string langName) { if (string.IsNullOrWhiteSpace(langName)) return GetCurrentCultureLanguage(); if (!Contains(langName)) return GetCurrentCultureLanguage(); return langName.ToLocale(); } public Locale GetCurrentCultureLanguage() { return CultureInfo.CurrentCulture.Name.ToLocale(); } #endregion #region Register used language public void RegisterUsedLangage(string lang) { if (string.IsNullOrWhiteSpace(lang)) throw new ArgumentNullException(nameof(lang)); RegisterUsedLangage(lang.ToLocale()); } public void RegisterUsedLangage(Locale locale) { lock (_langObject) { if (!Contains(locale)) { _usedLanguages.Add(locale); } } } #endregion public override string ToString() { return string.Join(",", _usedLanguages.Select(x => x.GetName())); } } }
28.459016
95
0.612327
cd4f74d8c9e166ba3b0e93a7e7c2233ad8cb7a0c
804
cs
C#
Assets/Rhythm/Script/BackgroundFlash.cs
Meanings11/Mountain-Cross
fe9ee3a4d8628b5b66ed7248f2f5a475a7069a0f
[ "MIT" ]
null
null
null
Assets/Rhythm/Script/BackgroundFlash.cs
Meanings11/Mountain-Cross
fe9ee3a4d8628b5b66ed7248f2f5a475a7069a0f
[ "MIT" ]
null
null
null
Assets/Rhythm/Script/BackgroundFlash.cs
Meanings11/Mountain-Cross
fe9ee3a4d8628b5b66ed7248f2f5a475a7069a0f
[ "MIT" ]
1
2021-12-02T21:04:47.000Z
2021-12-02T21:04:47.000Z
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BackgroundFlash : MonoBehaviour { public Color lerpedColor; public Color startColor; public Color currentColor; public int flashcountdown = 2; SpriteRenderer rend; // Use this for initialization void Start () { rend = GetComponent<SpriteRenderer> (); currentColor = rend.material.color; } // Update is called once per frame void Update () { currentColor = rend.material.color; rend.material.color = Color.Lerp (currentColor, startColor, Time.deltaTime * 18); } public void TempoTrigger(){ flashcountdown -= 1; if (flashcountdown == 0) { Debug.Log ("BackgroundFlash"); rend.material.color = lerpedColor; flashcountdown = 2; } } }
21.157895
84
0.689055
fedb4a94731a90e87be5e86d5b9783aae73f0909
5,325
go
Go
rmid3tag.go
inazak/rmid3tag
e3038bb2622e86b7f96cc20b5c364e96bacecb83
[ "MIT" ]
null
null
null
rmid3tag.go
inazak/rmid3tag
e3038bb2622e86b7f96cc20b5c364e96bacecb83
[ "MIT" ]
null
null
null
rmid3tag.go
inazak/rmid3tag
e3038bb2622e86b7f96cc20b5c364e96bacecb83
[ "MIT" ]
1
2021-02-26T11:57:36.000Z
2021-02-26T11:57:36.000Z
package rmid3tag import ( "fmt" "os" "io" "bytes" "golang.org/x/text/transform" "golang.org/x/text/encoding/unicode" ) type Stat struct { Size int64 V1TagExist bool V2TagExist bool OffsetMPEGFrame int64 } func (s *Stat) SizeOfMPEGFrame() int64 { if s.V1TagExist { return s.Size - s.OffsetMPEGFrame - 128 } return s.Size - s.OffsetMPEGFrame } // GetStat() provide mp3 file imformation. // Stat structure has MPEG frame offset and size. // +---------------+ // | ID3v2tag | // | (optional) | // +---------------+ <-- offset // | | | // | MPEG Frames | | size of mpeg frame // | | | // +---------------+ <-+ // | ID3v1tag | // | (optional) | // +---------------+ // func GetStat(filename string) (stat *Stat, err error) { stat = &Stat{} // open original file f, err := os.OpenFile(filename, os.O_RDONLY, 0644) if err != nil { return stat, err } defer f.Close() // filesize info, err := f.Stat() if err != nil { return stat, err } stat.Size = info.Size() // v2tag stat.V2TagExist, stat.OffsetMPEGFrame, err = getID3v2TagSize(f) if err != nil { return stat, err } // v1tag stat.V1TagExist, err = isExistID3v1Tag(f, stat.Size -128) if err != nil { return stat, err } return stat, nil } func getID3v2TagSize(r io.ReaderAt) (isExist bool, size int64, err error) { marker := make([]byte, 4) n, err := r.ReadAt(marker, 0) if n != 4 || err != nil { return false, 0, err } var offset int64 = 0 //header start position if string(marker[:3]) != "ID3" { // some mp3 file has irregular byte at the beginning, // so ignore them. if string(marker[1:]) == "ID3" { offset += 1 } else { // then marker not found return false, 0, nil } } isExist = true data := make([]byte, 4) n, err = r.ReadAt(data, 6 + offset) if n != 4 || err != nil { return isExist, 0, err } size = int64(decodeSynchsafe(data, 4)) size += 10 + offset //add v2 header size // Some files have padding greater than the specified size, // so search until the mpeg frame is found. for ;; size++ { ok, err := isExistMP3Frame(r, size) if err != nil { return isExist, size, fmt.Errorf("mpeg frame not found") } if ok { // found return isExist, size, nil } } return isExist, size, nil // do not reach here } func isExistID3v1Tag(r io.ReaderAt, offset int64) (bool, error) { marker := make([]byte, 3) n, err := r.ReadAt(marker, offset) if n != 3 || err != nil { return false, err } if string(marker) != "TAG" { return false, nil } return true, nil } func isExistMP3Frame(r io.ReaderAt, offset int64) (bool, error) { data := make([]byte, 2) n, err := r.ReadAt(data, offset) if n != 2 || err != nil { return false, err } // beginning byte pattern of mpeg frame pattern := [][]byte{ {0xff,0xfb}, {0xff,0xfa}, } for _, p := range pattern { if bytes.HasPrefix(data, p) { return true, nil } } return false, nil } //// utilites func decodeSynchsafe(data []byte, size int) int { result := 0 for i:=0; i<size; i++ { result += (int(data[i]) & 0x7f) << uint(7 * (size-1-i)) } return result } func encodeSynchsafe(data int, size int) []byte { result := make([]byte, size) for i:=0; i<size; i++ { result[i] = byte((data & 0x7f) >> uint(7 * (size-1-i))) } return result } //// for create func CreateMinimumTag(title, artist string) ([]byte, error) { tf, err := CreateTitleFrame(title) if err != nil { return []byte{}, err } af, err := CreateArtistFrame(artist) if err != nil { return []byte{}, err } return CreateID3V2Tag(tf, af), nil } func CreateID3V2Tag(frames ...[]byte) []byte { size := 0 for _, frame := range frames { size += len(frame) } buf := &bytes.Buffer{} buf.WriteString("ID3") buf.Write([]byte{0x3,0x0,0x0}) //version 2.3 buf.Write(encodeSynchsafe(size, 4)) for _, frame := range frames { buf.Write(frame) } return buf.Bytes() } func CreateTitleFrame(text string) ([]byte, error) { return CreateTextFrame("TIT2", text) } func CreateArtistFrame(text string) ([]byte, error) { return CreateTextFrame("TPE1", text) } func CreateTextFrame(id, text string) ([]byte, error) { data, err := encodeTextFrameData(text) if err != nil { return []byte{}, err } size := len(data) buf := &bytes.Buffer{} buf.WriteString(id) buf.WriteByte(byte(0xff&(size>>24))) buf.WriteByte(byte(0xff&(size>>16))) buf.WriteByte(byte(0xff&(size>>8))) buf.WriteByte(byte(0xff&size)) buf.Write([]byte{0x0,0x0}) buf.Write(data) return buf.Bytes(), nil } func encodeTextFrameData(s string) ([]byte, error) { u16bytes,err := toUTF16BEWithBOM(s) if err != nil { return []byte{}, err } buf := &bytes.Buffer{} buf.Write([]byte{0x1}) //encoding UTF16/useBOM buf.Write(u16bytes) buf.Write([]byte{0x0,0x0}) //null terminater return buf.Bytes(), nil } func toUTF16BEWithBOM(s string) ([]byte, error) { u16str, _, err := transform.String( unicode.UTF16(unicode.BigEndian, unicode.UseBOM).NewEncoder(), s) if err != nil { return []byte{}, err } return []byte(u16str), nil }
19.434307
75
0.587606
bec8e9029ded8c5a9cb7b062f81015e34dfe0ebb
511
tsx
TypeScript
src/components/footer/footer.tsx
jackschu/personal_site
995b207ccbbea9cd6bf96d23fae797f37dde73f0
[ "MIT" ]
null
null
null
src/components/footer/footer.tsx
jackschu/personal_site
995b207ccbbea9cd6bf96d23fae797f37dde73f0
[ "MIT" ]
null
null
null
src/components/footer/footer.tsx
jackschu/personal_site
995b207ccbbea9cd6bf96d23fae797f37dde73f0
[ "MIT" ]
null
null
null
import { Link } from 'gatsby' import React from 'react' import './style.scss' interface Props { author: string title: string } const Footer: React.FC<Props> = ({ author, title }: Props) => ( <div className="footer"> <div className="container"> <hr className="border-primary" /> <p> {title} <Link to="/profile/"> <br /> Built by <strong>{author}</strong> with React and Gatsby.js </Link> </p> </div> </div> ) export default Footer
19.653846
69
0.567515
05ba3a011d75ac8d190937c8a318b1cb85575559
1,324
py
Python
tensorflow/python/ipu/ops/experimental/popfloat_ops_grad.py
chenzhengda/tensorflow
8debb698097670458b5f21d728bc6f734a7b5a53
[ "Apache-2.0" ]
74
2020-07-06T17:11:39.000Z
2022-01-28T06:31:28.000Z
tensorflow/python/ipu/ops/experimental/popfloat_ops_grad.py
chenzhengda/tensorflow
8debb698097670458b5f21d728bc6f734a7b5a53
[ "Apache-2.0" ]
9
2020-10-13T23:25:29.000Z
2022-02-10T06:54:48.000Z
tensorflow/python/ipu/ops/experimental/popfloat_ops_grad.py
chenzhengda/tensorflow
8debb698097670458b5f21d728bc6f734a7b5a53
[ "Apache-2.0" ]
12
2020-07-08T07:27:17.000Z
2021-12-27T08:54:27.000Z
# Copyright 2019 The TensorFlow Authors. 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. # ============================================================================== """Gradients for Popfloat operators.""" from tensorflow.python.framework import ops """ These gradient function should *never* be called directly. """ @ops.RegisterGradient("CalcGfloatParams") def _calc_gfloat_params_backward(op, *grads): """Gradients for the CalcGfloatParams op.""" return None @ops.RegisterGradient("CastNativeToGfloat") def _cast_native_to_gfloat_backward(op, *grads): """Gradients for the CastToGfloat op.""" return [grads[0], None] @ops.RegisterGradient("CastGfloatToNative") def _cast_gfloat_to_native_backward(op, *grads): """Gradients for the CastFromGfloat op.""" return [grads[0], None]
35.783784
80
0.713746
3f74a0106e0941a22e4a04506a5331b4311c34d7
21,030
php
PHP
tools/asf_classes.php
yulonghu/asf
5542977fa5bd973b79c8750cd8e862bc02ec0ea9
[ "PHP-3.01" ]
291
2018-05-04T03:26:02.000Z
2021-03-23T15:44:24.000Z
tools/asf_classes.php
18615716991/asf
3d686441003b823bfe0bc26ecb71d538088af3c4
[ "PHP-3.01" ]
null
null
null
tools/asf_classes.php
18615716991/asf
3d686441003b823bfe0bc26ecb71d538088af3c4
[ "PHP-3.01" ]
13
2018-05-04T04:33:50.000Z
2020-04-10T23:11:38.000Z
<?php final class Asf_Application {/*{{{*/ protected $config = NULL; protected $dispatcher = NULL; protected $_env = NULL; protected static $_ins = NULL; public function __construct(mixed $config, string $section) public function init(mixed $config, string $section) public function bootstrap(void) public function constants(void) public function run(void) public function task(void) public function getInstance(void) public function getConfig(void) public function getModules(void) public function getRootPath(void) public function getEnv(void) public function getMode(void) public function setLogErrFileName(string $filename) public function setErrorHandler(callable $error_handler) public function setTimeoutHandler(callable $timeout_handler) } /*}}}*/ final class Asf_Dispatcher {/*{{{*/ protected static $_ins = NULL; protected $_request = NULL; public function getInstance(void) public function getRouter(void) public function getRequest(void) public function setDefaultModule(string $name) public function setDefaultService(string $name) public function setDefaultAction(string $name) public function throwException(bool $start) } /*}}}*/ final class Asf_Loader {/*{{{*/ protected static $_ins = NULL; public static function get(string $class_name, string $module_name = '', $unique_instance = 1) public static function logic(string $class_name, string $module_name = '', $unique_instance = 1) public static function dao(string $class_name, string $module_name = '', $unique_instance = 1) public static function import(string $file_name) public static function getInstance(string $library_path) public static function clean(string $class_name) } /*}}}*/ final class Asf_Sg {/*{{{*/ public static $inputs = ['get' => array(), 'post' => array(), 'cookie' => array()]; public static has(string $name [, bool $strtok = 1]) public static get(string $name [, mixed $default_value = null [, bool $strtok = 1]]) public static set(string $name, mixed $value) public static del(string $name) } /*}}}*/ /* {{{ config */ abstract class Asf_Config_AbstractConfig { protected $_conf = NULL; public function get(mixed $name = '', mixed $default = '') public function toArray(void) } final class Asf_Config_Ini extends Asf_Config_AbstractConfig { public function __construct(string $file_path, string $section = '') } final class Asf_Config_Php extends Asf_Config_AbstractConfig { public function __construct(string $file_path) } final class Asf_Config_Simple extends Asf_Config_AbstractConfig { public function __construct(array $values) } final class Asf_Config implements Countable, Iterator, ArrayAccess { public static function get(string $name = '', mixed $default = '') public function getIns(string $adapter, array $options) } /* }}} config */ final class Asf_Ensure {/*{{{*/ public static function isNull(mixed $data, int $errno) public static function notNull(mixed $data, int $errno) public static function isEmpty(mixed $data, int $errno) public static function NotEmpty(mixed $data, int $errno) public static function isFalse(mixed $data, int $errno) public static function notFalse(mixed $data, int $errno) public static function isTrue(mixed $data, int $errno) public static function out(string $data, int $errno) }/*}}}*/ abstract class Asf_Router_AbstractRoute {/*{{{*/ public function addRoute(string $name, array $data) public function getRoutes(void) }/*}}}*/ /* {{{ logger */ interface Asf_Log_LoggerInterface { public function emergency(string $message, array $content = array()) public function alert(string $message, array $content = array()) public function critical(string $message, array $content = array()) public function error(string $message, array $content = array()) public function warning(string $message, array $content = array()) public function notice(string $message, array $content = array()) public function info(string $message, array $content = array()) public function debug(string $message, array $content = array()) public function log(string $level, string $message, array $content = array()) } final class Asf_Log_Level { const SPECIAL = 'special'; const CUSTOM = 'custom'; const DEBUG = 'debug'; const INFO = 'info'; const NOTICE = 'notice'; const WARNING = 'warning'; const ERROR = 'error'; const CRITICAL = 'critical'; const ALERT = 'alert'; const EMERGENCY = 'emergency'; } abstract class Asf_Log_AbstractLogger implements Asf_Log_LoggerInterface { public function emergency(string $message, array $content = array()) public function alert(string $message, array $content = array()) public function critical(string $message, array $content = array()) public function error(string $message, array $content = array()) public function warning(string $message, array $content = array()) public function notice(string $message, array $content = array()) public function info(string $message, array $content = array()) public function debug(string $message, array $content = array()) public function log(string $level = 'info', string $message, array $content = array()) public function getFormatter(void) public function doLog(string $message) } final class Asf_Log_Adapter_File extends Asf_Log_AbstractLogger { public function __construct(string $file_name, string $file_path = '') public function doLog(string $message) public function close(void) } final class Asf_Log_Adapter_Syslog extends Asf_Log_AbstractLogger { public function __construct(string $ident, int $options = LOG_PID, int $facility = LOG_LOCAL0) public function doLog(string $message) public function close(void) } interface Asf_Log_FormatterInterface { public function format(string $level, int $time, string $message) } final class Asf_Log_Formatter_File implements Asf_Log_FormatterInterface { protected $_format = '{date} [{type}] {message}'; protected $_date_format = 'd-M-Y H:i:s e'; public function format(string $level, int $time, string $message) } final class Asf_Log_Formatter_Syslog implements Asf_Log_FormatterInterface { public function format(string $level, int $time, string $message) } final class Asf_Logger extends Asf_Log_AbstractLogger { public static function adapter(int $adapter_id, string $file_name) public static function init(string $full_path) public static function getHandles(void) } /* }}} logger */ abstract class Asf_AbstractService {/*{{{*/ protected $_req = NULL; protected $_res = NULL; public function getRequest(void) public function getResponse(void) public function getFileLogger(string $file_name) }/*}}}*/ /* {{{ db */ interface Asf_Db_AdapterInterface { public function insert(array $data, bool $retrun_insert_id = false) public function insertIgnore(array $data, bool $retrun_insert_id = true) public function update(array $data, array $condition = array(), int $limit = 1) public function delete(array $condition, int $limit = 1) public function findOne(string $sql, array $bind_value = array(), int $mode = PDO::FETCH_ASSOC) public function findAll(string $sql, array $bind_value = array(), int $mode = PDO::FETCH_ASSOC) public function findOneBy(array $data, array $fields = array(), int $mode = PDO::FETCH_ASSOC) public function findAllBy(array $data, array $fields = array(), int $mode = PDO::FETCH_ASSOC) public function exeNoquery(string $sql, array $bind_value = array()) public function exequery(string $sql, array $bind_value = array()) public function getRowByCmd(string $sql, array $bind_value = array()) public function getRowsByCmd(string $sql, array $bind_value = array()) public function addByArray(array $data) public function addDupByArray(array $data, array $update_cols) public function getCount(string $sql_where = '', array $bind_value = array()) public function getLastSql(void) public function setTable(string $name) public function getTable(void) public function close(void) } abstract class Asf_Db_AbstractAdapter implements Asf_Db_AdapterInterface { protected $_type = NULL; protected $_dbh = NULL; protected $_table = NULL; public function __construct(array $configs, bool $reconnection = false); public function insert(array $data, bool $retrun_insert_id = true) public function insertIgnore(array $data, bool $retrun_insert_id = true) public function update(array $data, array $condition = array(), int $limit = 1) public function delete(array $condition, int $limit = 1) public function findOne(string $sql, array $bind_value = array(), int $mode = PDO::FETCH_ASSOC) public function findAll(string $sql, array $bind_value = array(), int $mode = PDO::FETCH_ASSOC) public function findOneBy(array $data, array $fields = array(), int $mode = PDO::FETCH_ASSOC) public function findAllBy(array $data, array $fields = array(), int $mode = PDO::FETCH_ASSOC) public function exeNoquery(string $sql, array $bind_value = array()) public function exequery(string $sql, array $bind_value = array()) public function getRowByCmd(string $sql, array $bind_value = array()) public function getRowsByCmd(string $sql, array $bind_value = array()) public function addByArray(array $data) public function addDupByArray(array $data, array $update_cols) public function getCount(string $sql_where = '', array $bind_value = array()) public function getLastSql(void) public function setTable(string $name) public function getTable(void) public function close(void) public function __call(string $function_name, array $args) } final class Asf_Db_Adapter_Mysql extends Asf_Db_AbstractAdapter { protected $_type = 'mysql'; } final class Asf_Db_Adapter_Sqlite extends Asf_Db_AbstractAdapter { protected $_type = 'sqlite'; } final class Asf_Db_Adapter_Pgsql extends Asf_Db_AbstractAdapter { protected $_type = 'pgsql'; } final class Asf_Db { public static $_links = NULL; public static $_clink = NULL; public static function init(array $configs, int $adapter_id = 0, bool $reset = false) public static function initMysql(array $configs, bool $reset = false) public static function __callStatic(string $function_name, array $args) public static function getLinks(void) public static function QBS(void) public static function QBI(bool $ignore = false) public static function QBU(void) public static function QBD(void) } /* }}} db */ /* {{{ SQLQueryBuilder */ abstract class Asf_Db_AbstractQueryBuilder { public function where(string $columns, mixed $value, string $operator = '=') public function wheres(array $cols(string $key => mixed $value)) public function orwhere(string $columns, mixed $value, string $operator = '=') public function whereIn(string $columns, array $value) public function orWhereIn(string $columns, array $value) public function table(string $name, string $alias_name = '') public function from(string $name, string $alias_name = '') public function set(string $name, string $value) public function sets(array $cols(string $key => mixed $value)) public function limit(int $start_page, int $end_page) public function cm(string $data) public function like(string $columns, mixed $value) public function notLike(string $columns, mixed $value) public function between(string $columns, mixed $a, mixed $b) public function notBetween(string $columns, mixed $a, mixed $b) public function show(void) public function exec(bool $flags = 0) public function clear(void) public function getSql(void) public function getValues(void) } final class Asf_Db_QueryBuilder_Select extends Asf_Db_AbstractQueryBuilder { public function join(string $columns, string $alias_columns = '') public function leftJoin(string $columns, string $alias_columns = '') public function rightJoin(string $columns, string $alias_columns = '') public function innerJoin(string $columns, string $alias_columns = '') public function cols(mixed $columns, ...) public function having(string $columns, mixed $value, string $operator = '=') public function max(string $cloumn, string $alias_columns = '') public function min(string $cloumn, string $alias_columns = '') public function count(string $columns, string $alias_columns = '') public function sum(string $columns, string $alias_columns = '') public function on(string $cloumn_a, string $cloumn_b) public function distinct(string $columns, string $alias_columns = '') public function groupBy(string $columns) public function orderBy(string $columns, string $operator = 'DESC') public function union(void) public function unionAll(void) public function __construct(void) /* alias __construct */ public function select(void) } final class Asf_Db_QueryBuilder_Insert extends Asf_Db_AbstractQueryBuilder { public function __construct(bool $ignore = false) /* alias __construct */ public function insert(bool $ignore = false) public function onDku(string $columns, mixed $value) } final class Asf_Db_QueryBuilder_UpdateQueryBuilder extends Asf_Db_AbstractQueryBuilder { public function __construct(void) /* alias __construct */ public function update(void) } final class Asf_Db_QueryBuilder_DeleteQueryBuilder extends Asf_Db_AbstractQueryBuilder { public function __construct(void) /* alias __construct */ public function delete(void) } /* }}} SQLQueryBuilder */ /* {{{ http */ interface Asf_Http_ResponseInterface { public function setContentType(string $ctype, string $charset) public function redirect(string $url, int $status_code) public function setContent(string $content) public function appendContent(string $content) public function appendContent(string $content) public function getContent(void) public function send(void) } final class Asf_Http_Response implements Asf_Http_ResponseInterface { protected $_header = NUll; protected $_value = NUll; public function __construct(void) public function setContentType(string $ctype, string $charset) public function redirect(string $url, int $status_code) public function setContent(mixed $content) public function appendContent(mixed $content) public function appendContent(mixed $content) public function getContent(void) public function send(void) } interface Asf_Http_RequestInterface { public function isGet(void) public function isPost(void) public function isPut(void) public function isDelete(void) public function isPatch(void) public function isHead(void) public function isOptions(void) public function isCli(void) public function isXmlHttpRequest(void) public function isTrace(void) public function isConnect(void) public function isFlashRequest(void) public function isPropFind(void) public function getParam(string $name, mixed $default) public function getParams(void) public function getModuleName(void) public function getServiceName(void) public function getActionName(void) public function getMethod(void) public function getBaseUri(void) public function getRequestUri(void) public function getQuery(string $name [, mixed $default = NULL]) public function getPost(string $name [, mixed $default = NULL]) public function getRequest(string $name [, mixed $default = NULL]) public function getFiles(string $name [, mixed $default = NULL]) public function getCookie(string $name [, mixed $default = NULL]) public function getServer(string $name [, mixed $default = NULL]) public function getEnv(string $name [, mixed $default = NULL]) public function hasPost(void) public function hasQuery(void) public function hasServer(void) public function hasFiles(void) } final class Asf_Http_Request implements Asf_Http_RequestInterface { protected $method = NULL; protected $uri = NULL; protected $params = NULL; protected $module = NULL; protected $service = NULL; protected $action = NULL; protected $_base_uri = NULL; public function __construct(string $base_uri = '', string $request_uri = '') public function isGet(void) public function isPost(void) public function isPut(void) public function isDelete(void) public function isPatch(void) public function isHead(void) public function isOptions(void) public function isCli(void) public function isXmlHttpRequest(void) public function isTrace(void) public function isConnect(void) public function isFlashRequest(void) public function isPropFind(void) public function getParam(string $name, mixed $default = null) public function getParams(void) public function getModuleName(void) public function getServiceName(void) public function getActionName(void) public function getMethod(void) public function getBaseUri(void) public function getRequestUri(void) public function getQuery(string $name [, mixed $default = NULL]) public function getPost(string $name [, mixed $default = NULL]) public function getRequest(string $name [, mixed $default = NULL]) public function getFiles(string $name [, mixed $default = NULL]) public function getCookie(string $name [, mixed $default = NULL]) public function getServer(string $name [, mixed $default = NULL]) public function getEnv(string $name [, mixed $default = NULL]) public function hasPost(void) public function hasQuery(void) public function hasServer(void) public function hasFiles(void) } interface Asf_Http_CookieInterface { public function __construct([array $configs]) public function prefix(string $name) public function set(string $name, string $value) public function forever(string $name, string $value) public function has(string $name) public function get(string $name = '') public function del(string $name [, string $...]) public function clear(void) } final class Asf_Http_Cookie implements Asf_Http_CookieInterface { public Asf_Http_Cookie function __construct([array $configs]) public boolean function prefix(string $name) public boolean function set(string $name, string $value) public boolean function forever(string $name, string $value) public boolean function has(string $name) public mixed function get(string $name = '') public boolean function del(string $name [, string $...]) public boolean function clear(void) } /* }}} http */ /* {{{ Asf_Util */ class Asf_Util { public static function ip(void) public static function bytes2string(int $size, bool $space = 1) public static function guid(void) public static function atrim(array $data) public static function filterXss(array $data) public static function cpass(string $data, string $cpass = '') public static function iniSets(array $ini) public static function isEmail(string $email) public static function fileExt(string $filename) public static function getUrl(string $url, array $opts = array()) public static function postUrl(string $url, array $data = array(), array $opts = array()) } /* }}} Asf_Util */ /* {{{ Asf_Debug_Dump */ class Asf_Debug_Dump { public static function vars(mixed $expression [, mixed $... ]) } /* }}} Asf_Debug_Dump */ /* {{{ Asf_Cache */ final class Asf_Cache { public static function getConfig(void) public static function setConfig(array $config) public static function getLinks(void) public static function store(string $name) public static function clean(string $name) public static function cleanAll(void) } /* }}} Asf_Cache */ /* {{{ Asf_Cache_AbstractAdapter */ abstract class Asf_Cache_AbstractAdapter { public function getConnectInfo(void) public function getHandler(void) public function __construct(array $options) public function has(mixed $key) public function get(mixed $key) public function set(mixed $key, mixed $value) public function incr(mixed $key [, uint $step = 1]) public function decr(mixed $key [, uint $step = 1]) public function clear(void) } final class asf_Cache_Adapter_Redis extends Asf_Cache_Abstractadapter { public function __call(string $function_name, array $args) } final class asf_Cache_Adapter_Memcached extends Asf_Cache_Abstractadapter { public function __call(string $function_name, array $args) } /* }}} Asf_Cache_AbstractAdapter */
36.765734
100
0.719496
937f3d0e7be8347b2e51922924ae61829aa46db5
1,780
cs
C#
Web/EncantosSalao.Web/Areas/Administracao/Controllers/CategoriasController.cs
jucdesarlima/EncantosSalao
33e31d2f75ddf4af0ca0b639ed89ddfc43469216
[ "MIT" ]
null
null
null
Web/EncantosSalao.Web/Areas/Administracao/Controllers/CategoriasController.cs
jucdesarlima/EncantosSalao
33e31d2f75ddf4af0ca0b639ed89ddfc43469216
[ "MIT" ]
null
null
null
Web/EncantosSalao.Web/Areas/Administracao/Controllers/CategoriasController.cs
jucdesarlima/EncantosSalao
33e31d2f75ddf4af0ca0b639ed89ddfc43469216
[ "MIT" ]
null
null
null
namespace EncantosSalao.Web.Areas.Administracao.Controllers { using System.Threading.Tasks; using EncantosSalao.Comum; using EncantosSalao.Servicos.Dado.Categorias; using EncantosSalao.Web.VisaoModelos.Categorias; using Microsoft.AspNetCore.Mvc; public class CategoriasController : AdministracaoController { private readonly ICategoriasServico servicoCategorias; public CategoriasController( ICategoriasServico servicoCategorias) { this.servicoCategorias = servicoCategorias; } public async Task<IActionResult> Index() { var viewModel = new CategoriasListaVisaoModelo { Categorias = await this.servicoCategorias.PegaTodosAsync<CategoriaVisaoModelo>(), }; return this.View(viewModel); } public IActionResult AddCategory() { return this.View(); } //[HttpPost] //public async Task<IActionResult> AddCategory(CategoryInputModel input) //{ // if (!this.ModelState.IsValid) // { // return this.View(input); // } // string imageUrl; // await this.categoriesService.AddAsync(input.Name, input.Description, imageUrl); // return this.RedirectToAction("Index"); //} [HttpPost] public async Task<IActionResult> ExcluiCategoria(int id) { if (id <= ConstantesGlobais.ContadoresDadosSemeados.Categorias) { return this.RedirectToAction("Index"); } await this.servicoCategorias.ExcluiAsync(id); return this.RedirectToAction("Index"); } } }
28.709677
97
0.596067
af514a5a113b77ede796d595b3ce8d5dca2cb4f6
2,042
sql
SQL
sql/create.sql
wangguoke/imcs
7113cb38294855d08bbba42fdaf0f0f9a71febbb
[ "Apache-2.0" ]
136
2015-01-03T06:01:15.000Z
2022-03-23T19:23:15.000Z
sql/create.sql
wangguoke/imcs
7113cb38294855d08bbba42fdaf0f0f9a71febbb
[ "Apache-2.0" ]
29
2015-02-03T08:57:46.000Z
2022-02-18T09:17:08.000Z
sql/create.sql
knizhnik/imcs
b1a2d93f3fd465b55aa56a43d169f1c3344df4d4
[ "Apache-2.0" ]
31
2015-01-18T04:45:22.000Z
2020-12-28T07:19:45.000Z
create table Quote (Symbol char(10), Day date, Open real, High real, Low real, Close real, Volume integer); insert into Quote (Symbol,Day,Open,High,Low,Close,Volume) values ('IBM', date('01-Nov-2013'), 10.2, 11.0, 10.0, 10.5, 100); insert into Quote (Symbol,Day,Open,High,Low,Close,Volume) values ('IBM', date('02-Nov-2013'), 20.2, 20.2, 20.2, 20.2, 200); insert into Quote (Symbol,Day,Open,High,Low,Close,Volume) values ('IBM', date('04-Nov-2013'), 30.5, 31.0, 30.0, 30.2, 300); insert into Quote (Symbol,Day,Open,High,Low,Close,Volume) values ('IBM', date('05-Nov-2013'), 40.5, 41.0, 40.0, 40.2, 400); insert into Quote (Symbol,Day,Open,High,Low,Close,Volume) values ('IBM', date('06-Nov-2013'), 50.2, 51.0, 50.0, 50.5, 500); insert into Quote (Symbol,Day,Open,High,Low,Close,Volume) values ('ABB', date('03-Nov-2013'), 60.5, 61.0, 70.0, 60.2, 600); insert into Quote (Symbol,Day,Open,High,Low,Close,Volume) values ('ABB', date('06-Nov-2013'), 70.2, 71.0, 70.0, 70.5, 700); create extension imcs; select cs_create('Quote', 'Day', 'Symbol'); select Quote_load(); -- Table with varying size strings which are mapped to integers using dictionary create table CrashLog( log_time timestamp, ---when this data is produce,selective uid bigint, ---user id country varchar,----USA,Chine,Japan etc...cardinal number is ~ 100,has hot spot city varchar, ---cardinal number~10000,has hot spot device varchar, ---iphone4,nokiaX etc, cardinal number is 1000,has hot spot net varchar, -----wifi,Vodafone 3G... cardinal number is 10,hash hot spot os varchar); ----iOS6.x,Android 2.3 cardinal number is 100,hash hot spot insert into CrashLog values ('2014-04-14 11:54', 10000001, 'USA', 'New York', 'iPhone4', 'wifi', 'iOS6.x'); insert into CrashLog values ('2014-04-14 11:55', 10000002, 'Japan', 'Tokio', 'Sony Xperia Z1', 'Vodafone 3G', 'Android 4.4'); insert into CrashLog values ('2014-04-14 11:56', 10000003, 'China', 'Beijing', 'iPhone5', 'wifi', 'iOS7.x'); select cs_create('CrashLog', 'log_time'); select CrashLog_load(); select cs_used_memory();
68.066667
125
0.701763
b2dee06c7ec766bf36b6f67c62d72f37b332fd41
8,132
css
CSS
assets/style.css
shanghongshen001/SnapShotActivity
446d0bfdc7a2492f7c8c448621136f004c8e401e
[ "MIT" ]
null
null
null
assets/style.css
shanghongshen001/SnapShotActivity
446d0bfdc7a2492f7c8c448621136f004c8e401e
[ "MIT" ]
null
null
null
assets/style.css
shanghongshen001/SnapShotActivity
446d0bfdc7a2492f7c8c448621136f004c8e401e
[ "MIT" ]
null
null
null
/** * Copyright 2013 I Doc View * @author Godwin <[email protected]> */ /* ---------------------------------------------------------------------- */ /* Content /* ---------------------------------------------------------------------- */ /* -------------------------------------------------- */ /* Loading style /* -------------------------------------------------- */ .loading-mask { position: absolute; background-color: whiteSmoke; width: 100%; height: 100%; top: 0; left: 0; right: 0; bottom: 0; z-index: 2000; } .loading-mask .brand { position: absolute; width: 100%; bottom: 20px; } .loading-mask .loading-zone { width: 100%; max-width: 300px; margin: 100px auto; } .loading-mask .loading-zone .progress { height: 13px; } .loading-mask .loading-zone .text { text-align: center; margin: 5px auto; } /* -------------------------------------------------- */ /* Bootstrap responsive style /* -------------------------------------------------- */ body { padding-top: 60px; padding-bottom: 40px; } .sidebar-nav { padding: 9px 0; } @media (max-width: 980px) { /* Enable use of floated navbar text */ .navbar-text.pull-right { float: none; padding-left: 5px; padding-right: 5px; } } /* -------------------------------------------------- */ /* File upload /* -------------------------------------------------- */ .fileinput-button { position: relative; overflow: hidden; float: left; margin-right: 4px; } .fileinput-button input { position: absolute; top: 0; right: 0; margin: 0; opacity: 0; filter: alpha(opacity=0); transform: translate(-300px, 0) scale(4); font-size: 23px; direction: ltr; cursor: pointer; } /* -------------------------------------------------- */ /* Header Style /* -------------------------------------------------- */ .navbar .brand { text-overflow: ellipsis; overflow: hidden; white-space: nowrap; max-width: 80%; } /* -------------------------------------------------- */ /* Search & Highlight /* -------------------------------------------------- */ .highlight { background-color: #FFFF88; } .highlight-selected { background-color: darkorange; } /* -------------------------------------------------- */ /* Word Style /* -------------------------------------------------- */ .word-body, .ppt-body { background-color:#EBEBEB; min-height: 100%; -webkit-font-smoothing:antialiased; font-smoothing:antialiased; text-rendering:optimizeLegibility; } .word-body table { width: auto !important; } .word-page{ line-height: normal; margin-right: auto; margin-left: auto; margin-bottom: 15px; max-width: 795px; background-color:#FFF; -moz-border-radius: 1px; border-radius: 1px; -moz-box-shadow: 0 0 10px 5px #888; -webkit-box-shadow: 0 0 10px 5px #888; box-shadow: 0 0 10px 5px #888; } .word-page .word-content { position: relative; background-color:#FFF; max-width: 75%; word-wrap: break-word; word-break: break-all; margin: 0px auto; padding-top: 10%; padding-bottom: 10%; } .doc-page .doc-content p{ word-wrap:break-word; word-break:normal; margin: 0px; } /* -------------------------------------------------- */ /* PPT Style /* -------------------------------------------------- */ .slide-img-container { margin: 0 auto; bottom: 20px; top: 0px; right: 5px; padding-bottom: 10px; position: relative; width: 100%; text-align: center; } .slide-img-container img { -moz-border-radius: 5px; border-radius: 2px; -moz-box-shadow: 0 0 10px 3px #888; -webkit-box-shadow: 0 0 10px 3px #888; box-shadow: 0 0 10px 3px #888; } .slide-img-container-sync { margin: 0 auto; bottom: 20px; top: 0px; right: 5px; padding-bottom: 10px; position: relative; width: 100%; text-align: center; } .slide-img-container-sync img { -moz-border-radius: 5px; border-radius: 2px; -moz-box-shadow: 0 0 10px 3px #888; -webkit-box-shadow: 0 0 10px 3px #888; box-shadow: 0 0 10px 3px #888; } .ppt-thumb-border { border: 3px solid darkorange; } .ppt-turn-left-mask, .ppt-turn-right-mask { position: absolute; width: 50%; height: 100%; top: 0; left: 0px; z-index: 500; cursor: url("../img/arr_left.cur"), auto; display: block; } .ppt-turn-right-mask { left: inherit; right: 0; cursor: url("../img/arr_right.cur"), auto; } /* -------------------------------------------------- */ /* PPT Draw Style /* -------------------------------------------------- */ #cursors{ position:relative; } #cursors .cursor{ position:absolute; width:15px; height:22px; background:url('/static/draw/img/pointer.png') no-repeat -4px 0; } /* -------------------------------------------------- */ /* PDF Style /* -------------------------------------------------- */ .pdf-body { background-color:#EBEBEB; min-height: 100%; -webkit-font-smoothing:antialiased; font-smoothing:antialiased; text-rendering:optimizeLegibility; } .pdf-page{ line-height: normal; margin-right: auto; margin-left: auto; margin-bottom: 15px; max-width: 795px; background-color:#FFF; -moz-border-radius: 1px; border-radius: 1px; -moz-box-shadow: 0 0 10px 5px #888; -webkit-box-shadow: 0 0 10px 5px #888; box-shadow: 0 0 10px 5px #888; text-align: center; } .pdf-page .pdf-content { position: relative; background-color:#FFF; word-wrap: break-word; word-break: break-all; margin: 0px auto; } /* -------------------------------------------------- */ /* Table Style /* -------------------------------------------------- */ table { border-collapse: collapse; word-wrap: break-word; margin: 0px auto; } table td { text-align: center !important; } /* table, tbody, tfoot, thead, tr, th, td { border: 1px solid #dddddd !important; } */ /* -------------------------------------------------- */ /* Back to Top /* -------------------------------------------------- */ #back-to-top, .touch-device #back-to-top:hover { background: url(../img/arrow-up-large.png) no-repeat center center; background-color: rgb(221, 221, 221); background-color: rgba(221, 221, 221, .7); bottom: 20px; color: transparent; display: none; font: 0/0 a; height: 46px; position: fixed; right: 20px; text-shadow: none; -webkit-transition: all .2s ease; -moz-transition: all .2s ease; -ms-transition: all .2s ease; -o-transition: all .2s ease; transition: all .2s ease; width: 45px; z-index: 3000; } #back-to-top:hover, .touch-device #back-to-top:active { background-color: #f15a23; } /* -------------------------------------------------- */ /* Footer /* -------------------------------------------------- */ footer { text-align: center; } /* -------------------------------------------------- */ /* Bottom paging progress /* -------------------------------------------------- */ .bottom-paging-progress { position: fixed; width: 100%; bottom: 0px; left: 0px; margin: 0px auto; height: 3px; } .paging-bottom-all { border-top: 1px solid #d8d8d8; height: 20px; position: fixed; bottom: 0px; left: 0px; right: 0px; width: 100%; cursor: pointer; } .paging-bottom-sub { float: left; display: inline-block; text-align: center; height: 20px; font-weight: bold; color: green; } /* -------------------------------------------------- */ /* Mobile css /* -------------------------------------------------- */ @media (max-width: 767px) { .word-body { padding-top: 40px; } .word-page .word-content { max-width: 85%; } /* 取消手机端Word预览左右边距 */ .word-body .container-fluid-content { padding-left: 0px; padding-right: 0px; } .word-body, .ppt-body, .pdf-body { background-color:#FFF; } .word-page{ -moz-box-shadow: 0 0 10px 5px #FFF; -webkit-box-shadow: 0 0 0px 0px #FFF; box-shadow: 0 0 0px 0px #FFF; } .pdf-body { padding-top: 50px; } .pdf-body .container-fluid-content { padding-left: 0px; padding-right: 0px; } }
21.177083
86
0.498893
c267bb1a68f6cf8ee7b0de337609fc207c875d12
442
h
C
include/core/move/moves/QuickGuard.h
Linyxus/YaPokemon
a8533dff4d59ba0c15f765167ebb733396876a18
[ "MIT" ]
null
null
null
include/core/move/moves/QuickGuard.h
Linyxus/YaPokemon
a8533dff4d59ba0c15f765167ebb733396876a18
[ "MIT" ]
null
null
null
include/core/move/moves/QuickGuard.h
Linyxus/YaPokemon
a8533dff4d59ba0c15f765167ebb733396876a18
[ "MIT" ]
null
null
null
// // Created by Yichen Xu on 2020/9/5. // #ifndef YAPOKEMON_QUICKGUARD_H #define YAPOKEMON_QUICKGUARD_H #include <move/BufMove.h> class QuickGuard : public BufMove { public: QuickGuard(); ~QuickGuard() = default; string name() const override; string desc() const override { return "摆出防御的姿态,提升防御"; } MoveCat move_cat() const override { return MCNormal; } }; #endif //YAPOKEMON_QUICKGUARD_H
15.785714
39
0.662896
e4cfec0589854114cedd65884e5d4cb25dcc4457
492
swift
Swift
Math/Sqrt(x)/sqrtx.playground/Contents.swift
gibsongibsonx/LeetCode
45be3448a44233bf333d6dd8997fbb173f8c487f
[ "MIT" ]
null
null
null
Math/Sqrt(x)/sqrtx.playground/Contents.swift
gibsongibsonx/LeetCode
45be3448a44233bf333d6dd8997fbb173f8c487f
[ "MIT" ]
null
null
null
Math/Sqrt(x)/sqrtx.playground/Contents.swift
gibsongibsonx/LeetCode
45be3448a44233bf333d6dd8997fbb173f8c487f
[ "MIT" ]
null
null
null
import Foundation // https://leetcode.com/problems/sqrtx/ // Discuss: https://vk.cc/c3OjBx class Solution { func mySqrt(_ x: Int) -> Int { return Int(sqrt(Double(x))) } } import XCTest // Executed 2 tests, with 0 failures (0 unexpected) in 0.005 (0.007) seconds class Tests: XCTestCase { let s = Solution() func test0() { XCTAssertEqual(s.mySqrt(4), 2) } func test1() { XCTAssertEqual(s.mySqrt(8), 2) } } Tests.defaultTestSuite.run()
18.222222
76
0.619919
b07d7b08d9895f83fef369e6d67073c04ac83c89
5,756
py
Python
veloso/stacked_area.py
victorgveloso/visualizacao_covid
6dfe923fb01ce047f65e82d603e38355b3a4e0dd
[ "MIT" ]
null
null
null
veloso/stacked_area.py
victorgveloso/visualizacao_covid
6dfe923fb01ce047f65e82d603e38355b3a4e0dd
[ "MIT" ]
null
null
null
veloso/stacked_area.py
victorgveloso/visualizacao_covid
6dfe923fb01ce047f65e82d603e38355b3a4e0dd
[ "MIT" ]
2
2021-06-26T17:11:26.000Z
2021-08-10T05:42:54.000Z
import dash import numpy as np import pandas as pd import plotly.graph_objects as go from dash.dependencies import Input, Output from pandas.core.groupby import DataFrameGroupBy import dash_html_components as html import dash_core_components as dcc class StackedArea: azul = "rgb(0, 102, 255)" azul_escuro = "rgb(0, 102, 153)" rosa = "rgb(255, 0, 255)" laranja = "rgb(255, 153, 0)" verde = "rgb(0, 153, 51)" vermelho = "rgb(204, 0, 0)" roxo = "rgb(153, 51, 153)" marrom = "rgb(153, 102, 51)" color = [azul, laranja, azul_escuro, roxo, rosa, marrom] fig: go.Figure total_df: pd.DataFrame categories: pd.DataFrame semanas: pd.DataFrame df: pd.DataFrame def show(self): self.fig.show() def __init__(self, df: pd.DataFrame, category: str, x_col: str, y_col: str): self.df = df self.categories = df[category].unique().tolist() self.total_df = self.generate_total_df(x_col) df['Total semana (%)'] = self.calculate_percentage(x_col) self.fig = self.generate_figure(category, x_col, y_col) def generate_total_df(self, x_col: str) -> pd.DataFrame: result = self.df.groupby(x_col).apply(self.calculate_total).reset_index() result.columns = [x_col, 'to be removed', 'Total dia (semana)'] return result[[x_col, 'Total dia (semana)']] @staticmethod def calculate_total(grouped_df: DataFrameGroupBy) -> pd.DataFrame: result = {'Total (semana)': [sum(grouped_df['Total (semana)'].tolist())]} return pd.DataFrame(result) def calculate_percentage(self, x_col: str) -> pd.Series: df = self.df.join(self.total_df.set_index(x_col), on=x_col) return (df['Total (semana)'] / df['Total dia (semana)']) * 100 def calculate_y(self, category, i, x_col, y_col): y = self.df[self.df[category] == self.categories[i]][y_col].tolist() return y + [1] * (len(self.df[x_col].unique().tolist()) - len(y)) def generate_figure(self, category: str, x_col: str, y_col: str): fig = go.Figure() for i in range(len(self.categories)): y = self.calculate_y(category, i, x_col, y_col) if i == 0: fig.add_trace(go.Scatter( x=(self.df[x_col].unique().tolist()), y=y, mode='lines', line=dict(width=0.5, color=self.color[i]), name=self.categories[i], stackgroup='one', groupnorm='percent' # sets the normalization for the sum of the stackgroup )) else: fig.add_trace(go.Scatter( x=(self.df[x_col].unique().tolist()), y=y, mode='lines', line=dict(width=0.5, color=self.color[i]), name=self.categories[i], stackgroup='one' # sets the normalization for the sum of the stackgroup )) fig.update_layout( showlegend=True, xaxis_type='category', yaxis=dict( type='linear', range=[1, 100], ticksuffix='%'), xaxis_title="Semana - início em 17/01/2021 até 20/06/2021", yaxis_title="Vacinas (%)", font=dict(size=25) ) return fig class StackedAreaDataset: @staticmethod def update(estado: str): df = StackedAreaDataset.load() if estado != "Todos": df = df[df['Estado'] == estado] semanas = df['Semana de aplicação'].tolist() convert = {1: 7, 2: 8, 3: 9, 4: 10, 5: 11, 6: 12, 7: 13, 8: 14, 9: 15, 10: 16, 11: 17, 12: 18, 13: 19, 14: 20, 15: 21, 16: 22, 17: 23, 18: 24, 19: 25, 20: 26, 21: 27, 22: 28, 23: 29, 24: 30, 33: 1, 38: 2, 40: 3, 51: 4, 52: 5, 53: 6} for i in range(len(semanas)): semanas[i] = convert[semanas[i]] - 1 df['Semana de aplicação'] = np.array(semanas) - 2 semana_aplicaca_por_vacina = df.groupby(by=['Semana de aplicação', 'Nome da vacina']).apply( lambda e: pd.DataFrame({'Total (semana)': [e['Total (semana)'].sum()]})).reset_index() semana_aplicaca_por_vacina = semana_aplicaca_por_vacina[ ['Semana de aplicação', 'Total (semana)', 'Nome da vacina']] return semana_aplicaca_por_vacina @staticmethod def load(): df = pd.read_csv("areas_empilhadas.csv") df = df[df['Semana de aplicação'] != 25] return df class StackedAreaDash(StackedArea): def __init__(self, app: dash.Dash): df = StackedAreaDataset.update("Todos") super().__init__(df, "Nome da vacina", 'Semana de aplicação', 'Total (semana)') opcoes = [{'label': i, 'value': i} for i in (['Todos'] + StackedAreaDataset.load()['Estado'].unique().tolist())] self.component_html = html.Div([ html.Hr(), html.H4('Porcentagem de aplicação por semana para cada tipo de vacina'), html.Label("Selecione o estado"), html.Div([ dcc.Dropdown( id='estado', options=opcoes, value='Todos', ) ], style={'width': '48%', 'display': 'inline-block'}), dcc.Graph(id='areas-empilhadas') ]) app.callback(Output('areas-empilhadas', 'figure'), Input('estado', 'value'))(self.callback) @staticmethod def callback(estado: str): print(estado) return StackedArea(StackedAreaDataset.update(estado), "Nome da vacina", 'Semana de aplicação', 'Total (semana)').fig
39.424658
113
0.558895
4824c0eb736c28dc6826098a28c3f0d692cb7081
721
swift
Swift
Shared/Set/BrowserTableViewCell.swift
vito-royeca/ManaGuide-ios
a8aaa1b40e4726a8de151da1d98f5b12a2dd21e9
[ "MIT" ]
null
null
null
Shared/Set/BrowserTableViewCell.swift
vito-royeca/ManaGuide-ios
a8aaa1b40e4726a8de151da1d98f5b12a2dd21e9
[ "MIT" ]
40
2018-06-14T02:53:27.000Z
2018-12-27T00:54:53.000Z
Shared/Set/BrowserTableViewCell.swift
vito-royeca/ManaGuide-ios
a8aaa1b40e4726a8de151da1d98f5b12a2dd21e9
[ "MIT" ]
null
null
null
// // BrowserTableViewCell.swift // ManaGuide // // Created by Jovito Royeca on 26/07/2017. // Copyright © 2017 Jovito Royeca. All rights reserved. // import UIKit class BrowserTableViewCell: UITableViewCell { static let reuseIdentifier = "BrowserCell" // MARK: Outlets @IBOutlet weak var webView: UIWebView! // MARK: Overrides override func awakeFromNib() { super.awakeFromNib() // Initialization code selectionStyle = .none accessoryType = .none } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
21.848485
65
0.644938
3b2879d41ab8ace6112334c8e401c81087862380
1,197
rs
Rust
src/prob_134.rs
caibirdme/leetcode_rust
08111c0c084a3a9588aa3e1e482eeae838156048
[ "MIT" ]
5
2019-12-28T01:24:50.000Z
2020-12-20T02:35:59.000Z
src/prob_134.rs
caibirdme/leetcode_rust
08111c0c084a3a9588aa3e1e482eeae838156048
[ "MIT" ]
10
2020-02-23T12:12:49.000Z
2020-03-27T02:45:06.000Z
src/prob_134.rs
caibirdme/leetcode_rust
08111c0c084a3a9588aa3e1e482eeae838156048
[ "MIT" ]
null
null
null
impl Solution { pub fn can_complete_circuit(gas: Vec<i32>, cost: Vec<i32>) -> i32 { if gas.iter().sum::<i32>() < cost.iter().sum() { return -1; } let mut ans = -1; let mut rest = 0; let mut i = 0; while i < gas.len() { if ans == -1 && gas[i]<cost[i] { i+=1; continue; } if ans == -1 { rest = gas[i] - cost[i]; ans = i as i32; i+=1; } else { rest += gas[i] - cost[i]; if rest < 0 { ans = -1; } else { i+=1; } } } ans } } struct Solution; #[cfg(test)] mod tests { use super::Solution; #[test] fn test_can_complete_circuit() { let test_cases = vec![ (vec![1,2,3,4,5], vec![3,4,5,1,2], 3), (vec![2,3,4], vec![3,4,3], -1), ]; for (gas, cost, expect) in test_cases { assert_eq!(Solution::can_complete_circuit(gas.clone(), cost.clone()), expect, "gas: {:?}, cost: {:?}", gas, cost); } } }
24.9375
126
0.375104
d693c758c32c2c542c8cbd6915fa1813fd90f18e
898
cs
C#
HandiBugTracker/HandiBugTrackerDataManager/Models/ComponentBugOptionsModel.cs
handitan/HandiBugTracker
771ccddcc615c16e07e625b8fc56afbdf752b2a9
[ "MIT" ]
null
null
null
HandiBugTracker/HandiBugTrackerDataManager/Models/ComponentBugOptionsModel.cs
handitan/HandiBugTracker
771ccddcc615c16e07e625b8fc56afbdf752b2a9
[ "MIT" ]
null
null
null
HandiBugTracker/HandiBugTrackerDataManager/Models/ComponentBugOptionsModel.cs
handitan/HandiBugTracker
771ccddcc615c16e07e625b8fc56afbdf752b2a9
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HandiBugTrackerDataManager.Models { public class ComponentBugOptionsModel { public List<BugPriorityModel> BugPriorityList { get; set; } public List<BugSeverityModel> BugSeverityList { get; set; } public List<BugStatusModel> BugStatusList { get; set; } public List<BugStatusSubStateModel> BugStatusSubStateList { get; set; } public List<BugTypeModel> BugTypeList { get; set; } public List<ProductModel> ProductList { get; set; } public List<ProductHardwareModel> ProductHardwareList { get; set; } public List<ProductOSModel> ProductOSList { get; set; } public List<ComponentModel> ComponentList { get; set; } public List<ProductVersionModel> ProductVersionList { get; set; } } }
39.043478
79
0.711581
f5b1b15a89035c6719d7d9ba61d145fee8503e1f
6,177
css
CSS
src/styles/characters.css
Qboussard/pray-the-dice
6a126433a25d40581241b37cca374cf4f025692b
[ "MIT" ]
null
null
null
src/styles/characters.css
Qboussard/pray-the-dice
6a126433a25d40581241b37cca374cf4f025692b
[ "MIT" ]
null
null
null
src/styles/characters.css
Qboussard/pray-the-dice
6a126433a25d40581241b37cca374cf4f025692b
[ "MIT" ]
1
2021-11-22T15:54:50.000Z
2021-11-22T15:54:50.000Z
.Overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(27, 29, 41, 0.4); } .ReactModal__Content::-webkit-scrollbar { display: none; } .containerCharacters { display: grid; grid-gap: 20px; grid-template-areas: "listCharacters" "newCharacterForm"; } .campaignInformation { display: flex; flex-direction: column; } .campaignInformation div { flex: 1; } .listCharacters { grid-area: listCharacters; } .newCharacterForm { grid-area: newCharacterForm; } .defaultInformation { grid-area: defaultInformation; } .skillsContainer { grid-area: skillsContainer; display: grid; grid-template-columns: 1fr; justify-content: flex-start; grid-template-areas: "createCharacterButton" "skills"; } .createCharacterButton { grid-area: createCharacterButton; } .characteristics { grid-area: characteristics; } .characteristics label { display: flex; flex-direction: row; justify-content: flex-start; align-items: center; } .characteristics label span { min-width: 200px; } .defaultInformation label.column { display: flex; flex-direction: column; justify-content: space-between; width: calc(100% - 15px); } .textAreaDescription { height: 100px; margin: 0.5rem 0; width: calc(100% - 15px); display: block; } input[type=text].nameNewCharacter { margin: 0.5rem 0px; width: calc(100% - 15px); display: block; } .list { display: flex; flex-direction: row; flex-wrap: wrap; justify-content: center; } .list li a{ display: flex; flex-direction: column; justify-content: center; align-items: center; } /* .list li a div{ display: inline-block; } */ .skillRow { display: flex; justify-content: space-between; margin: 0.5rem 0; min-height: 30px; align-items: center; } .skillRow input[type=number] { align-self: flex-end; justify-self: flex-end; margin: 0 0.25rem; } .skillRow label input { /* min-width: 25px; */ } .skillRow .skillName { min-width: 220px; } .newCharacterForm { display: grid; grid-gap: 20px; grid-template-areas: "listCharacters" "newCharacterForm"; } .formNewCharacter { display: grid; grid-gap: 20px; grid-template-areas: "defaultInformation" "characteristics" "skillsContainer" "createCharacterButton"; } .formNewCharacter .switch{ margin-bottom: 1rem; } .inputCharacteristics, .inputSkills { width: 50px; margin: 0.25rem; } .tutoCreation ul { list-style-type: circle; padding-inline-start: 20px; } .tutoCreation ul li { margin-bottom: 0.5rem; } .tutoCreation { background-color: #007991; padding: 0.5rem; margin-left: -20px; margin-right: -20px; } .tutoCreation p { margin-top: 0; margin-bottom: 0.5rem; } .tutoCreation span, .tutoCreation p, .tutoCreation ul li{ color: #fff } .skillsContainer .tabsContainer { display: flex; flex: 1; flex-direction: row; justify-content: space-between; overflow: hidden; border-bottom:3px solid #ffad23; position: relative; margin: 0 -20px; } .skillsContainer .tab { width: 50%; position: relative; text-align: center; padding:0.5rem 1rem; cursor:pointer; border-radius: 0.25rem 0 0 0; color:#ffad23; } .skillsContainer .tab:first-child { border-radius: 0 0.25rem 0 0; } .skillsContainer .tab.active { background-color: #ffad23; /* box-shadow:inset 0px -10em 0px 0px #ffad23; */ position:relative; color:#fff; } .skillsContainer .active:after, .skillsContainer .active:before{ content:''; position:absolute; bottom: 0; width:10px; height: 10px; background-color: #fff; border-radius: 50%; } .skillsContainer .active:after{ right: -10px; box-shadow: -5px 5px 0 #ffad23; } .skillsContainer .active:before{ left: -10px; box-shadow: 5px 5px 0 #ffad23; } .campaignInformation div p span:first-child { color: #6c757d; } .settingsCampaign .switch { margin-top: 1rem; margin-bottom: 1rem; } .ReactModalPortal h2 { margin-block-start: 0.25rem; margin-block-end: 0.25rem; } .ReactModalPortal::-webkit-scrollbar { display: none; } @media (min-width: 500px) { .containerCharacters { grid-template-areas: "listCharacters" "newCharacterForm"; } .campaignInformation { display: flex; flex-direction: row; } .defaultInformation label.column { width: 510px } .textAreaDescription { min-height: 100px; max-width: 490px; min-width: 490px; } input[type=text].nameNewCharacter { margin: 0.5rem 0px; width: auto; display: inline-block; } .skillsContainer { justify-content: flex-start; } .defaultInformation label.column { width: 80% } .textAreaDescription { min-height: 100px; max-width: 80%; min-width: 80%; } .tutoCreation { margin-left: 0px; margin-right: 0px; border-radius: 0.25rem; } .tabsContainer { margin: 0; } } @media (min-width: 800px) { .containerCharacters { grid-gap: 20px; grid-template-areas: "listCharacters" "newCharacterForm"; } .listCharacters .list .link { margin-left: 0.25rem; margin-right: 0.25rem; } .formNewCharacter { display: grid; grid-template-columns: 1fr 0fr; grid-gap: 20px; } input[type=text].nameNewCharacter { margin: 0.5rem 0px; width: auto; display: inline-block; } .defaultInformation label.column { width: 510px } .textAreaDescription { min-height: 100px; max-width: 490px; min-width: 490px; } .characteristics { grid-area: characteristics; max-width: auto; } .list { justify-content: flex-start; } .list li a div{ display: inline-block; } .list li a{ display: flex; flex-direction: column; flex-wrap: wrap; align-items: center; justify-content: center; } .skillRow { justify-content: flex-start; } } @media (min-width: 1300px) { .formNewCharacter { display: grid; grid-template-columns: 1fr; grid-gap: 20px; /* grid-template-areas: "defaultInformation" "characteristics" "characteristics" "skillsContainer"; */ } .createCharacterButton { display: flex; justify-content: flex-end; } }
19.18323
57
0.66521
c669f6c13a239784c5468c74f51c22662d7b1077
3,130
py
Python
jobs/zinc15/process_data.py
gfrogat/tpp_python
3fafda066d73d6aa1fd8b38b943fd92d45c4df18
[ "MIT" ]
null
null
null
jobs/zinc15/process_data.py
gfrogat/tpp_python
3fafda066d73d6aa1fd8b38b943fd92d45c4df18
[ "MIT" ]
null
null
null
jobs/zinc15/process_data.py
gfrogat/tpp_python
3fafda066d73d6aa1fd8b38b943fd92d45c4df18
[ "MIT" ]
null
null
null
import argparse import logging from pathlib import Path from pyspark.sql import SparkSession, Window from pyspark.sql import functions as F from tpp.utils.argcheck import check_input_path, check_output_path if __name__ == "__main__": parser = argparse.ArgumentParser( prog="ZINC15 Data Processing", description="Process ZINC15 data in `parquet` format", ) parser.add_argument( "--input", required=True, type=Path, metavar="PATH", dest="input_path", help=f"Path to PubChem folder (FTP schema)", ) parser.add_argument( "--output", required=True, type=Path, metavar="PATH", dest="output_path", help="Path where output should be written to in `parquet` format", ) parser.add_argument("--num-partitions", type=int, dest="num_partitions", default=50) args = parser.parse_args() check_input_path(args.input_path) check_output_path(args.output_path) try: spark = ( SparkSession.builder.appName(parser.prog) .config("spark.sql.execution.arrow.enabled", "true") .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer") .getOrCreate() ) data = spark.read.parquet(args.input_path.as_posix()) data = data.repartition(args.num_partitions) data = data.dropna() # Remove non-unique inchikey per mol_id collisions w = Window.partitionBy("mol_id") data = data.withColumn( "num_inchikey", F.size(F.collect_set("inchikey").over(w)) ).filter(F.col("num_inchikey") == 1) triples = data.groupby(["mol_id", "gene_name"]).agg( F.mean("affinity").alias("avg_affinity"), F.collect_set("mol_file").alias("mol_file"), F.collect_set("inchikey").alias("inchikey"), ) triples = triples.withColumn( "activity", F.when(F.col("avg_affinity") > 8, 1).otherwise(-1) ) w = Window.partitionBy("gene_name") triples = ( triples.withColumn( "actives", F.count(F.when(F.col("activity") == 1, 0)).over(w) ) .withColumn( "inactives", F.count(F.when(F.col("activity") == -1, 0)).over(w) ) .filter( (F.col("actives") > 10) & (F.col("inactives") > 10) & (F.col("actives") + F.col("inactives") > 25) ) .select( "mol_id", F.col("inchikey")[0].alias("inchikey"), # inchikey are unique F.col("mol_file")[0].alias( "mol_file" ), # use one of molfile (have same inchikey) "gene_name", "activity", ) ) triples.write.parquet(args.output_path.as_posix()) except Exception as e: logging.exception(e) raise SystemExit( "Spark Job encountered a problem. Check the logs for more information" ) finally: spark.stop()
31.938776
88
0.55655
eb74668d637e10aec2ae95022ff7ac80c162301b
1,698
swift
Swift
generated/authz/src/EPA_FdV_AUTHZ_SpecialistTechnologistCardiovascularProviderCodes.swift
gematik/ref-ePA-FdV-ModulKit
9bcb9422cd6d6318d043c27ac95745ea67ce641f
[ "Apache-2.0" ]
3
2020-05-05T07:51:51.000Z
2021-03-24T16:59:06.000Z
generated/authz/src/EPA_FdV_AUTHZ_SpecialistTechnologistCardiovascularProviderCodes.swift
gematik/ref-ePA-FdV-ModulKit
9bcb9422cd6d6318d043c27ac95745ea67ce641f
[ "Apache-2.0" ]
null
null
null
generated/authz/src/EPA_FdV_AUTHZ_SpecialistTechnologistCardiovascularProviderCodes.swift
gematik/ref-ePA-FdV-ModulKit
9bcb9422cd6d6318d043c27ac95745ea67ce641f
[ "Apache-2.0" ]
null
null
null
//---------------------------------------------------- // // Generated by www.easywsdl.com // Version: 5.7.0.0 // // Created by Quasar Development // //--------------------------------------------------- import Foundation /** * specDomain: S20623 (C-0-T19465-S20608-S20623-cpt) */ public enum EPA_FdV_AUTHZ_SpecialistTechnologistCardiovascularProviderCodes:Int,CustomStringConvertible { case _246X00000X case _246XC2901X case _246XS1301X case _246XC2903X static func createWithXml(node:DDXMLNode) -> EPA_FdV_AUTHZ_SpecialistTechnologistCardiovascularProviderCodes? { return createWithString(value: node.stringValue!) } static func createWithString(value:String) -> EPA_FdV_AUTHZ_SpecialistTechnologistCardiovascularProviderCodes? { var i = 0 while let item = EPA_FdV_AUTHZ_SpecialistTechnologistCardiovascularProviderCodes(rawValue: i) { if String(describing: item) == value { return item } i += 1 } return nil } public var stringValue : String { return description } public var description : String { switch self { case ._246X00000X: return "246X00000X" case ._246XC2901X: return "246XC2901X" case ._246XS1301X: return "246XS1301X" case ._246XC2903X: return "246XC2903X" } } public func getValue() -> Int { return rawValue } func serialize(__parent:DDXMLNode) { __parent.stringValue = stringValue } }
23.583333
115
0.56066
43b7bfb24c73450508ddb376daea8bc79f451041
2,818
lua
Lua
archived_files/default_test_run.lua
MuteSpirit/yunit
5a850fa720086cb40627328d0533110d4cc11790
[ "MIT" ]
null
null
null
archived_files/default_test_run.lua
MuteSpirit/yunit
5a850fa720086cb40627328d0533110d4cc11790
[ "MIT" ]
null
null
null
archived_files/default_test_run.lua
MuteSpirit/yunit
5a850fa720086cb40627328d0533110d4cc11790
[ "MIT" ]
null
null
null
local lfs = require "yunit.lfs" local fs = require "yunit.filesystem" local testRunner = require "yunit.test_runner" local testResultHandlers = require "yunit.test_result_handlers" local usedLtueArray = {} --[=[ use this function to control what LTUE need to load and use, i.e. for usage only 'yunit.luaunit' run: lua -l yunit.work_in_scite -l yunit.default_test_run -e "use{'yunit.luaunit'}" -e "run[[test.t.lua]]" in command line --]=] function use(ltueArray) usedLtueArray = ltueArray end --[=[ @param[in] inArg Maybe: 1) path to test container 2) path of directory with test containers (recursive search) 3) table with elements from item 1, 2, 3 --]=] function run(inArg) if nil == inArg then error('not nill expected as argument, but was one') return end local runner = testRunner.TestRunner:new() runner:addResultHandler(testResultHandlers.EstimatedTime:new()) if testResultHandler then runner:addResultHandler(testResultHandler) end runner:addLoadtHandler(testResultHandlers.TextLoadTestContainerHandler:new()) local listOfUsedLtueWasNotSpecifiedInCommandLine = not next(usedLtueArray) if listOfUsedLtueWasNotSpecifiedInCommandLine then runner:loadLtue('yunit.luaunit') runner:loadLtue('yunit.cppunit') else for _, ltueName in ipairs(usedLtueArray) do runner:loadLtue(ltueName) end end local fixFailed = testResultHandlers.FixFailed:new() runner:addResultHandler(fixFailed) runner:addLoadtHandler(fixFailed) local function handleArg(arg) if 'string' == type(arg) then local path = arg if not fs.isExist(path) then error('receive path to unexist file/directory: "' .. path .. '"') return elseif fs.isDir(path) then runner:runTestContainersFromDir(path) elseif fs.isFile(path) then runner:runTestContainer(path) else error('receive path to unknown file system object type (not file and not directory): "' .. path .. '"') return end elseif 'table' == type(arg) then for _, path in pairs(arg) do handleArg(path) end else error('table or string expected, but was %s', type(arg)) return end end runner:onTestsBegin() handleArg(inArg) runner:onTestsEnd() if not fixFailed:passed() then print(fixFailed:message()) io.stdout:flush() io.stderr:flush() os.exit(-1) end end
31.311111
120
0.598297
e80e747e91ae319701bcf3624c108ee1703b8750
1,677
dart
Dart
clients/dart-jaguar/generated/test/queue_blocked_item_test.dart
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
clients/dart-jaguar/generated/test/queue_blocked_item_test.dart
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
clients/dart-jaguar/generated/test/queue_blocked_item_test.dart
cliffano/jenkins-api-clients-generator
522d02b3a130a29471df5ec1d3d22c822b3d0813
[ "MIT" ]
null
null
null
import 'package:openapi/api.dart'; import 'package:test/test.dart'; // tests for QueueBlockedItem void main() { var instance = new QueueBlockedItem(); group('test QueueBlockedItem', () { // String class_ (default value: null) test('to test the property `class_`', () async { // TODO }); // List<CauseAction> actions (default value: const []) test('to test the property `actions`', () async { // TODO }); // bool blocked (default value: null) test('to test the property `blocked`', () async { // TODO }); // bool buildable (default value: null) test('to test the property `buildable`', () async { // TODO }); // int id (default value: null) test('to test the property `id`', () async { // TODO }); // int inQueueSince (default value: null) test('to test the property `inQueueSince`', () async { // TODO }); // String params (default value: null) test('to test the property `params`', () async { // TODO }); // bool stuck (default value: null) test('to test the property `stuck`', () async { // TODO }); // FreeStyleProject task (default value: null) test('to test the property `task`', () async { // TODO }); // String url (default value: null) test('to test the property `url`', () async { // TODO }); // String why (default value: null) test('to test the property `why`', () async { // TODO }); // int buildableStartMilliseconds (default value: null) test('to test the property `buildableStartMilliseconds`', () async { // TODO }); }); }
22.972603
72
0.565295
1476b4377761ef87109f98daad75f77e04af400c
2,583
tsx
TypeScript
example/src/Basic/index.tsx
TheRakeshPurohit/react-flow
663024b628b240029c7d39d5d41c4bee47a8038c
[ "MIT" ]
null
null
null
example/src/Basic/index.tsx
TheRakeshPurohit/react-flow
663024b628b240029c7d39d5d41c4bee47a8038c
[ "MIT" ]
null
null
null
example/src/Basic/index.tsx
TheRakeshPurohit/react-flow
663024b628b240029c7d39d5d41c4bee47a8038c
[ "MIT" ]
null
null
null
import { MouseEvent } from 'react'; import ReactFlow, { ReactFlowProvider, Background, BackgroundVariant, Node, Edge, useReactFlow, } from 'react-flow-renderer'; const onNodeDragStop = (_: MouseEvent, node: Node) => console.log('drag stop', node); const onNodeClick = (_: MouseEvent, node: Node) => console.log('click', node); const initialNodes: Node[] = [ { id: '1', type: 'input', data: { label: 'Node 1' }, position: { x: 250, y: 5 }, className: 'light' }, { id: '2', data: { label: 'Node 2' }, position: { x: 100, y: 100 }, className: 'light' }, { id: '3', data: { label: 'Node 3' }, position: { x: 400, y: 100 }, className: 'light' }, { id: '4', data: { label: 'Node 4' }, position: { x: 400, y: 200 }, className: 'light' }, ]; const initialEdges: Edge[] = [ { id: 'e1-2', source: '1', target: '2', animated: true }, { id: 'e1-3', source: '1', target: '3' }, ]; const defaultEdgeOptions = { zIndex: 0 }; const BasicFlow = () => { const instance = useReactFlow(); const updatePos = () => { instance.setNodes((nodes) => nodes.map((node) => { node.position = { x: Math.random() * 400, y: Math.random() * 400, }; return node; }) ); }; const logToObject = () => console.log(instance.toObject()); const resetTransform = () => instance.setViewport({ x: 0, y: 0, zoom: 1 }); const toggleClassnames = () => { instance.setNodes((nodes) => nodes.map((node) => { node.className = node.className === 'light' ? 'dark' : 'light'; return node; }) ); }; return ( <ReactFlow defaultNodes={initialNodes} defaultEdges={initialEdges} onNodeClick={onNodeClick} onNodeDragStop={onNodeDragStop} className="react-flow-basic-example" minZoom={0.2} maxZoom={4} fitView defaultEdgeOptions={defaultEdgeOptions} > <Background variant={BackgroundVariant.Lines} /> <div style={{ position: 'absolute', right: 10, top: 10, zIndex: 4 }}> <button onClick={resetTransform} style={{ marginRight: 5 }}> reset transform </button> <button onClick={updatePos} style={{ marginRight: 5 }}> change pos </button> <button onClick={toggleClassnames} style={{ marginRight: 5 }}> toggle classnames </button> <button onClick={logToObject}>toObject</button> </div> </ReactFlow> ); }; export default function App() { return ( <ReactFlowProvider> <BasicFlow /> </ReactFlowProvider> ); }
27.189474
104
0.57259
df9673bbc2ca2dd2a2b3b0f6e739baabe92fcfb6
32,924
cs
C#
ImageViewer/DisplaySetFactories.cs
SNBnani/Xian
e07cb943476705ac3721921cf0f0906485d9f59d
[ "Apache-2.0" ]
1
2019-02-18T11:41:46.000Z
2019-02-18T11:41:46.000Z
ImageViewer/DisplaySetFactories.cs
nhannd/Xian
e07cb943476705ac3721921cf0f0906485d9f59d
[ "Apache-2.0" ]
null
null
null
ImageViewer/DisplaySetFactories.cs
nhannd/Xian
e07cb943476705ac3721921cf0f0906485d9f59d
[ "Apache-2.0" ]
null
null
null
#region License // Copyright (c) 2011, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This software is licensed under the Open Software License v3.0. // For the complete license, see http://www.clearcanvas.ca/OSLv3.0 #endregion using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using ClearCanvas.Common; using ClearCanvas.Common.Utilities; using ClearCanvas.Dicom; using ClearCanvas.ImageViewer.Annotations; using ClearCanvas.ImageViewer.Graphics; using ClearCanvas.ImageViewer.StudyManagement; using ClearCanvas.Dicom.ServiceModel.Query; namespace ClearCanvas.ImageViewer { #region Default [Cloneable(false)] public class SeriesDisplaySetDescriptor : DicomDisplaySetDescriptor { public SeriesDisplaySetDescriptor(ISeriesIdentifier sourceSeries, IPresentationImageFactory presentationImageFactory) : base(sourceSeries, presentationImageFactory) { Platform.CheckForNullReference(sourceSeries, "sourceSeries"); Platform.CheckForNullReference(presentationImageFactory, "presentationImageFactory"); } protected SeriesDisplaySetDescriptor(SeriesDisplaySetDescriptor source, ICloningContext context) : base(source, context) { } protected override string GetName() { return String.Format("{0}: {1}", SourceSeries.SeriesNumber, SourceSeries.SeriesDescription); } protected override string GetDescription() { return SourceSeries.SeriesDescription; } protected override string GetUid() { return SourceSeries.SeriesInstanceUid; } } [Cloneable(false)] public class SingleFrameDisplaySetDescriptor : DicomDisplaySetDescriptor { private readonly string _suffix; private readonly string _seriesInstanceUid; private readonly string _sopInstanceUid; private readonly int _frameNumber; private readonly int _position; public SingleFrameDisplaySetDescriptor(ISeriesIdentifier sourceSeries, Frame frame, int position) : base(sourceSeries) { Platform.CheckForNullReference(sourceSeries, "sourceSeries"); Platform.CheckForNullReference(frame, "frame"); _seriesInstanceUid = frame.SeriesInstanceUid; _sopInstanceUid = frame.SopInstanceUid; _frameNumber = frame.FrameNumber; _position = position; if (sourceSeries.SeriesInstanceUid == frame.SeriesInstanceUid) { _suffix = String.Format(SR.SuffixFormatSingleFrameDisplaySet, frame.ParentImageSop.InstanceNumber, _frameNumber); } else { //this is a referenced frame (e.g. key iamge). _suffix = String.Format(SR.SuffixFormatSingleReferencedFrameDisplaySet, frame.ParentImageSop.SeriesNumber, frame.ParentImageSop.InstanceNumber, _frameNumber); } } protected SingleFrameDisplaySetDescriptor(SingleFrameDisplaySetDescriptor source, ICloningContext context) : base(source, context) { context.CloneFields(source, this); } protected override string GetName() { if (String.IsNullOrEmpty(SourceSeries.SeriesDescription)) return String.Format("{0}: {1}", SourceSeries.SeriesNumber, _suffix); else return String.Format("{0}: {1} - {2}", SourceSeries.SeriesNumber, SourceSeries.SeriesDescription, _suffix); } protected override string GetDescription() { if (String.IsNullOrEmpty(SourceSeries.SeriesDescription)) return _suffix; else return String.Format("{0} - {1}", SourceSeries.SeriesDescription, _suffix); } protected override string GetUid() { return String.Format("{0}:{1}:{2}:{3}:{4}", SourceSeries.SeriesInstanceUid, _seriesInstanceUid, _sopInstanceUid, _frameNumber, _position); } } [Cloneable(false)] public class SingleImageDisplaySetDescriptor : DicomDisplaySetDescriptor { private readonly string _suffix; private readonly string _seriesInstanceUid; private readonly string _sopInstanceUid; private readonly int _position; public SingleImageDisplaySetDescriptor(ISeriesIdentifier sourceSeries, ImageSop imageSop, int position) : base(sourceSeries) { Platform.CheckForNullReference(sourceSeries, "sourceSeries"); Platform.CheckForNullReference(imageSop, "imageSop"); _sopInstanceUid = imageSop.SopInstanceUid; _seriesInstanceUid = imageSop.SeriesInstanceUid; _position = position; string laterality = imageSop.ImageLaterality; string viewPosition = imageSop.ViewPosition; if (string.IsNullOrEmpty(viewPosition)) { DicomAttributeSQ codeSequence = imageSop[DicomTags.ViewCodeSequence] as DicomAttributeSQ; if (codeSequence != null && !codeSequence.IsNull && codeSequence.Count > 0) viewPosition = codeSequence[0][DicomTags.CodeMeaning].GetString(0, null); } string lateralityViewPosition = null; if (!String.IsNullOrEmpty(laterality) && !String.IsNullOrEmpty(viewPosition)) lateralityViewPosition = String.Format("{0}/{1}", laterality, viewPosition); else if (!String.IsNullOrEmpty(laterality)) lateralityViewPosition = laterality; else if (!String.IsNullOrEmpty(viewPosition)) lateralityViewPosition = viewPosition; if (sourceSeries.SeriesInstanceUid == imageSop.SeriesInstanceUid) { if (lateralityViewPosition != null) _suffix = String.Format(SR.SuffixFormatSingleImageDisplaySetWithLateralityViewPosition, lateralityViewPosition, imageSop.InstanceNumber); else _suffix = String.Format(SR.SuffixFormatSingleImageDisplaySet, imageSop.InstanceNumber); } else { //this is a referenced image (e.g. key image). if (lateralityViewPosition != null) _suffix = String.Format(SR.SuffixFormatSingleReferencedImageDisplaySetWithLateralityViewPosition, lateralityViewPosition, imageSop.SeriesNumber, imageSop.InstanceNumber); else _suffix = String.Format(SR.SuffixFormatSingleReferencedImageDisplaySet, imageSop.SeriesNumber, imageSop.InstanceNumber); } } protected SingleImageDisplaySetDescriptor(SingleImageDisplaySetDescriptor source, ICloningContext context) : base(source, context) { context.CloneFields(source, this); } protected override string GetName() { if (String.IsNullOrEmpty(SourceSeries.SeriesDescription)) return String.Format("{0}: {1}", SourceSeries.SeriesNumber, _suffix); else return String.Format("{0}: {1} - {2}", SourceSeries.SeriesNumber, SourceSeries.SeriesDescription, _suffix); } protected override string GetDescription() { if (String.IsNullOrEmpty(SourceSeries.SeriesDescription)) return _suffix; else return String.Format("{0} - {1}", SourceSeries.SeriesDescription, _suffix); } protected override string GetUid() { return String.Format("{0}:{1}:{2}:{3}", SourceSeries.SeriesInstanceUid, _seriesInstanceUid, _sopInstanceUid, _position); } } /// <summary> /// A <see cref="DisplaySetFactory"/> for the most typical cases; creating a <see cref="IDisplaySet"/> that /// contains <see cref="IPresentationImage"/>s for the entire series, and creating a single <see cref="IDisplaySet"/> for /// each image in the series. /// </summary> public class BasicDisplaySetFactory : DisplaySetFactory { /// <summary> /// Constructor. /// </summary> public BasicDisplaySetFactory() { } /// <summary> /// Constructor. /// </summary> /// <param name="presentationImageFactory">The <see cref="IPresentationImageFactory"/> /// used to create the <see cref="IPresentationImage"/>s that populate the constructed <see cref="IDisplaySet"/>s.</param> public BasicDisplaySetFactory(IPresentationImageFactory presentationImageFactory) : base(presentationImageFactory) { } /// <summary> /// Specifies whether single image display sets should be created. /// </summary> /// <remarks> /// When this is false, series display sets are created. However, in the degenerate case /// where a series has only one image, the factory will not return a display set when /// this property is true. Instead, you must set this property to false in order /// to get a series display set returned. /// </remarks> public bool CreateSingleImageDisplaySets { get; set; } /// <summary> /// Creates <see cref="IDisplaySet"/>s from the given <see cref="Series"/>. /// </summary> /// <param name="series">The series for which <see cref="IDisplaySet"/>s are to be created.</param> /// <returns>A list of created <see cref="IDisplaySet"/>s.</returns> public override List<IDisplaySet> CreateDisplaySets(Series series) { if (CreateSingleImageDisplaySets) return DoCreateSingleImageDisplaySets(series); var displaySets = new List<IDisplaySet>(); var displaySet = CreateSeriesDisplaySet(series); if (displaySet != null) { displaySet.PresentationImages.Sort(); displaySets.Add(displaySet); } return displaySets; } private IDisplaySet CreateSeriesDisplaySet(Series series) { IDisplaySet displaySet = null; List<IPresentationImage> images = new List<IPresentationImage>(); foreach (Sop sop in series.Sops) images.AddRange(PresentationImageFactory.CreateImages(sop)); if (images.Count > 0) { DisplaySetDescriptor descriptor = new SeriesDisplaySetDescriptor(series.GetIdentifier(), PresentationImageFactory); displaySet = new DisplaySet(descriptor); foreach (IPresentationImage image in images) displaySet.PresentationImages.Add(image); } return displaySet; } private List<IDisplaySet> DoCreateSingleImageDisplaySets(Series series) { List<IDisplaySet> displaySets = new List<IDisplaySet>(); int position = 0; foreach (Sop sop in series.Sops) { List<IPresentationImage> images = PresentationImageFactory.CreateImages(sop); if (images.Count == 0) continue; if (sop.IsImage) { ImageSop imageSop = (ImageSop)sop; DicomDisplaySetDescriptor descriptor; if (imageSop.NumberOfFrames == 1) descriptor = new SingleImageDisplaySetDescriptor(series.GetIdentifier(), imageSop, position++); else descriptor = new MultiframeDisplaySetDescriptor(series.GetIdentifier(), sop.SopInstanceUid, sop.InstanceNumber); DisplaySet displaySet = new DisplaySet(descriptor); foreach (IPresentationImage image in images) displaySet.PresentationImages.Add(image); displaySets.Add(displaySet); } else { //The sop is actually a container for other referenced sops, like key images. foreach (IPresentationImage image in images) { DisplaySetDescriptor descriptor = null; if (image is IImageSopProvider) { IImageSopProvider provider = (IImageSopProvider) image; if (provider.ImageSop.NumberOfFrames == 1) descriptor = new SingleImageDisplaySetDescriptor(series.GetIdentifier(), provider.ImageSop, position++); else descriptor = new SingleFrameDisplaySetDescriptor(series.GetIdentifier(), provider.Frame, position++); } else { //TODO (CR Jan 2010): this because the design here is funny... the factory here should actually know something about the key object series it is building for ISeriesIdentifier sourceSeries = series.GetIdentifier(); descriptor = new BasicDisplaySetDescriptor(); descriptor.Description = sourceSeries.SeriesDescription; descriptor.Name = string.Format("{0}: {1}", sourceSeries.SeriesNumber, sourceSeries.SeriesDescription); descriptor.Number = sourceSeries.SeriesNumber.GetValueOrDefault(0); descriptor.Uid = sourceSeries.SeriesInstanceUid; } DisplaySet displaySet = new DisplaySet(descriptor); displaySet.PresentationImages.Add(image); displaySets.Add(displaySet); } } } if (displaySets.Count == 1) { //Degenerate case; single image series, which we're not supposed to create. displaySets[0].Dispose(); displaySets.Clear(); } return displaySets; } internal static IEnumerable<IDisplaySet> CreateSeriesDisplaySets(Series series, StudyTree studyTree) { BasicDisplaySetFactory factory = new BasicDisplaySetFactory(); factory.SetStudyTree(studyTree); return factory.CreateDisplaySets(series); } } #endregion #region MR Echo [Cloneable(false)] public class MREchoDisplaySetDescriptor : DicomDisplaySetDescriptor { private readonly string _suffix; public MREchoDisplaySetDescriptor(ISeriesIdentifier sourceSeries, int echoNumber, IPresentationImageFactory presentationImageFactory) : base(sourceSeries, presentationImageFactory) { Platform.CheckForNullReference(sourceSeries, "sourceSeries"); EchoNumber = echoNumber; _suffix = String.Format(SR.SuffixFormatMREchoDisplaySet, echoNumber); } protected MREchoDisplaySetDescriptor(MREchoDisplaySetDescriptor source, ICloningContext context) : base(source, context) { context.CloneFields(source, this); } public int EchoNumber { get; private set; } protected override string GetName() { if (String.IsNullOrEmpty(base.SourceSeries.SeriesDescription)) return String.Format("{0}: {1}", SourceSeries.SeriesNumber, _suffix); else return String.Format("{0}: {1} - {2}", SourceSeries.SeriesNumber, SourceSeries.SeriesDescription, _suffix); } protected override string GetDescription() { if (String.IsNullOrEmpty(base.SourceSeries.SeriesDescription)) return _suffix; else return String.Format("{0} - {1}", SourceSeries.SeriesDescription, _suffix); } protected override string GetUid() { return String.Format("{0}:Echo{1}", SourceSeries.SeriesInstanceUid, EchoNumber); } } /// <summary> /// A <see cref="DisplaySetFactory"/> that splits MR series with multiple echoes into multiple <see cref="IDisplaySet"/>s; one per echo. /// </summary> public class MREchoDisplaySetFactory : DisplaySetFactory { /// <summary> /// Constructor. /// </summary> public MREchoDisplaySetFactory() {} /// <summary> /// Constructor. /// </summary> /// <param name="presentationImageFactory">The <see cref="IPresentationImageFactory"/> /// used to create the <see cref="IPresentationImage"/>s that populate the constructed <see cref="IDisplaySet"/>s.</param> public MREchoDisplaySetFactory(IPresentationImageFactory presentationImageFactory) : base(presentationImageFactory) { } /// <summary> /// Creates zero or more <see cref="IDisplaySet"/>s from the given <see cref="Series"/>. /// </summary> /// <remarks> /// When the input <see cref="Series"/> does not have multiple echoes, no <see cref="IDisplaySet"/>s will be returned. /// Otherwise, at least 2 <see cref="IDisplaySet"/>s will be returned. /// </remarks> public override List<IDisplaySet> CreateDisplaySets(Series series) { List<IDisplaySet> displaySets = new List<IDisplaySet>(); if (series.Modality == "MR") { SortedDictionary<int, List<Sop>> imagesByEchoNumber = SplitMREchos(series.Sops); if (imagesByEchoNumber.Count > 1) { foreach (KeyValuePair<int, List<Sop>> echoImages in imagesByEchoNumber) { List<IPresentationImage> images = new List<IPresentationImage>(); foreach (ImageSop sop in echoImages.Value) images.AddRange(PresentationImageFactory.CreateImages(sop)); if (images.Count > 0) { IDisplaySet displaySet = new DisplaySet(new MREchoDisplaySetDescriptor(series.GetIdentifier(), echoImages.Key, PresentationImageFactory)); foreach (IPresentationImage image in images) displaySet.PresentationImages.Add(image); displaySet.PresentationImages.Sort(); displaySets.Add(displaySet); } } } } return displaySets; } private static SortedDictionary<int, List<Sop>> SplitMREchos(IEnumerable<Sop> sops) { SortedDictionary<int, List<Sop>> imagesByEchoNumber = new SortedDictionary<int, List<Sop>>(); foreach (Sop sop in sops) { if (sop.IsImage) { DicomAttribute echoAttribute = sop.DataSource[DicomTags.EchoNumbers]; if (!echoAttribute.IsEmpty) { int echoNumber = echoAttribute.GetInt32(0, 0); if (!imagesByEchoNumber.ContainsKey(echoNumber)) imagesByEchoNumber[echoNumber] = new List<Sop>(); imagesByEchoNumber[echoNumber].Add(sop); } } } return imagesByEchoNumber; } } #endregion #region Mixed Multi-frame [Cloneable(false)] public class MultiframeDisplaySetDescriptor : DicomDisplaySetDescriptor { private readonly string _sopInstanceUid; private readonly string _suffix; public MultiframeDisplaySetDescriptor(ISeriesIdentifier sourceSeries, string sopInstanceUid, int instanceNumber) : base(sourceSeries) { SopInstanceUid = sopInstanceUid; InstanceNumber = instanceNumber; Platform.CheckForNullReference(sourceSeries, "sourceSeries"); Platform.CheckForEmptyString(sopInstanceUid, "sopInstanceUid"); _sopInstanceUid = sopInstanceUid; _suffix = String.Format(SR.SuffixFormatMultiframeDisplaySet, instanceNumber); } protected MultiframeDisplaySetDescriptor(MultiframeDisplaySetDescriptor source, ICloningContext context) : base(source, context) { context.CloneFields(source, this); } public string SopInstanceUid { get; private set; } public int InstanceNumber { get; private set; } protected override string GetName() { if (String.IsNullOrEmpty(base.SourceSeries.SeriesDescription)) return String.Format("{0}: {1}", SourceSeries.SeriesNumber, _suffix); else return String.Format("{0}: {1} - {2}", SourceSeries.SeriesNumber, SourceSeries.SeriesDescription, _suffix); } protected override string GetDescription() { if (String.IsNullOrEmpty(base.SourceSeries.SeriesDescription)) return _suffix; else return String.Format("{0} - {1}", SourceSeries.SeriesDescription, _suffix); } protected override string GetUid() { return _sopInstanceUid; } } [Cloneable(false)] public class SingleImagesDisplaySetDescriptor : DicomDisplaySetDescriptor { private readonly string _suffix; public SingleImagesDisplaySetDescriptor(ISeriesIdentifier sourceSeries, IPresentationImageFactory presentationImageFactory) : base(sourceSeries, presentationImageFactory) { Platform.CheckForNullReference(sourceSeries, "sourceSeries"); _suffix = SR.SuffixSingleImagesDisplaySet; } protected SingleImagesDisplaySetDescriptor(SingleImagesDisplaySetDescriptor source, ICloningContext context) : base(source, context) { context.CloneFields(source, this); } protected override string GetName() { if (String.IsNullOrEmpty(base.SourceSeries.SeriesDescription)) return String.Format("{0}: {1}", SourceSeries.SeriesNumber, _suffix); else return String.Format("{0}: {1} - {2}", SourceSeries.SeriesNumber, SourceSeries.SeriesDescription, _suffix); } protected override string GetDescription() { if (String.IsNullOrEmpty(base.SourceSeries.SeriesDescription)) return _suffix; else return String.Format("{0} - {1}", SourceSeries.SeriesDescription, _suffix); } protected override string GetUid() { return String.Format("{0}:SingleImages", SourceSeries.SeriesInstanceUid); } } /// <summary> /// A <see cref="DisplaySetFactory"/> that splits series with multiple single or multiframe images into /// separate <see cref="IDisplaySet"/>s. /// </summary> /// <remarks> /// This factory will only create <see cref="IDisplaySet"/>s when the following is true. /// <list type="bullet"> /// <item>The input series contains more than one multiframe image.</item> /// <item>The input series contains at least one multiframe image and at least one single frame image.</item> /// </list> /// For typical series, consisting only of single frame images, no <see cref="IDisplaySet"/>s will be created. /// The <see cref="IDisplaySet"/>s that are created are: /// <list type="bullet"> /// <item>One <see cref="IDisplaySet"/> per multiframe image.</item> /// <item>One <see cref="IDisplaySet"/> containing all the single frame images, if any.</item> /// </list> /// </remarks> public class MixedMultiFrameDisplaySetFactory : DisplaySetFactory { /// <summary> /// Constructor. /// </summary> public MixedMultiFrameDisplaySetFactory() {} /// <summary> /// Constructor. /// </summary> /// <param name="presentationImageFactory">The <see cref="IPresentationImageFactory"/> /// used to create the <see cref="IPresentationImage"/>s that populate the constructed <see cref="IDisplaySet"/>s.</param> public MixedMultiFrameDisplaySetFactory(IPresentationImageFactory presentationImageFactory) : base(presentationImageFactory) { } /// <summary> /// Creates zero or more <see cref="IDisplaySet"/>s from the given <see cref="Series"/>. /// </summary> /// <remarks>When the input series does not contain a mixture of single and multiframe /// images, no <see cref="IDisplaySet"/>s will be returned.</remarks> public override List<IDisplaySet> CreateDisplaySets(Series series) { List<IDisplaySet> displaySets = new List<IDisplaySet>(); List<ImageSop> singleFrames = new List<ImageSop>(); List<ImageSop> multiFrames = new List<ImageSop>(); foreach (Sop sop in series.Sops) { if (sop.IsImage) { ImageSop imageSop = (ImageSop)sop; if (imageSop.NumberOfFrames > 1) multiFrames.Add(imageSop); else singleFrames.Add(imageSop); } } if (multiFrames.Count > 1 || (singleFrames.Count > 0 && multiFrames.Count > 0)) { if (singleFrames.Count > 0) { List<IPresentationImage> singleFrameImages = new List<IPresentationImage>(); foreach (ImageSop singleFrame in singleFrames) singleFrameImages.AddRange(PresentationImageFactory.CreateImages(singleFrame)); if (singleFrameImages.Count > 0) { var descriptor = new SingleImagesDisplaySetDescriptor(series.GetIdentifier(), PresentationImageFactory); var singleImagesDisplaySet = new DisplaySet(descriptor); foreach (IPresentationImage singleFrameImage in singleFrameImages) singleImagesDisplaySet.PresentationImages.Add(singleFrameImage); singleImagesDisplaySet.PresentationImages.Sort(); displaySets.Add(singleImagesDisplaySet); } } foreach (ImageSop multiFrame in multiFrames) { List<IPresentationImage> multiFrameImages = PresentationImageFactory.CreateImages(multiFrame); if (multiFrameImages.Count > 0) { MultiframeDisplaySetDescriptor descriptor = new MultiframeDisplaySetDescriptor(multiFrame.ParentSeries.GetIdentifier(), multiFrame.SopInstanceUid, multiFrame.InstanceNumber); DisplaySet displaySet = new DisplaySet(descriptor); foreach (IPresentationImage multiFrameImage in multiFrameImages) displaySet.PresentationImages.Add(multiFrameImage); displaySet.PresentationImages.Sort(); displaySets.Add(displaySet); } } } return displaySets; } } #endregion #region EntireStudy [Cloneable(false)] public class ModalityDisplaySetDescriptor : DicomDisplaySetDescriptor { public ModalityDisplaySetDescriptor(IStudyIdentifier sourceStudy, string modality, IPresentationImageFactory presentationImageFactory) : base(null, presentationImageFactory) { Platform.CheckForNullReference(sourceStudy, "sourceStudy"); Platform.CheckForEmptyString(modality, "modality"); SourceStudy = sourceStudy; Modality = modality; } protected ModalityDisplaySetDescriptor(ModalityDisplaySetDescriptor source, ICloningContext context) :base(source, context) { //context.CloneFields(source, this); Modality = source.Modality; SourceStudy = source.SourceStudy; } public IStudyIdentifier SourceStudy { get; private set; } public string Modality { get; private set; } protected override string GetName() { return String.Format(SR.FormatNameModalityDisplaySet, Modality); } protected override string GetDescription() { return String.Format(SR.FormatDescriptionModalityDisplaySet, Modality); } protected override string GetUid() { return String.Format("AllImages_{0}_{1}", Modality, SourceStudy.StudyInstanceUid); } } public class ModalityDisplaySetFactory : DisplaySetFactory { public ModalityDisplaySetFactory() { } public ModalityDisplaySetFactory(IPresentationImageFactory presentationImageFactory) : base(presentationImageFactory) { } private IDisplaySet CreateDisplaySet(Study study, IEnumerable<Series> modalitySeries) { var first = modalitySeries.FirstOrDefault(); if (first == null) return null; var modality = first.Modality; if (String.IsNullOrEmpty(modality)) return null; var displaySet = new DisplaySet(new ModalityDisplaySetDescriptor(study.GetIdentifier(), modality, PresentationImageFactory)); int seriesCount = 0; foreach (var series in modalitySeries) { bool added = false; foreach (var imageSop in series.Sops) //We don't want key images, references etc. { foreach (var image in PresentationImageFactory.CreateImages(imageSop)) { displaySet.PresentationImages.Add(image); added = true; } } if (added) ++seriesCount; } // Degenerate case is one series, in which case we don't create this display set. if (seriesCount > 1) return displaySet; displaySet.Dispose(); return null; } public IDisplaySet CreateDisplaySet(Study study, string modality) { return CreateDisplaySet(study, study.Series.Where(s => s.Modality == modality)); } public override List<IDisplaySet> CreateDisplaySets(Study study) { var displaySets = new List<IDisplaySet>(); foreach (var seriesByModality in study.Series.GroupBy(s => s.Modality)) { var displaySet = CreateDisplaySet(study, seriesByModality); if (displaySet != null) { displaySet.PresentationImages.Sort(); displaySets.Add(displaySet); } } return displaySets; } public override List<IDisplaySet> CreateDisplaySets(Series series) { throw new NotSupportedException(); } } #endregion #region Placeholder public class PlaceholderDisplaySetFactory : DisplaySetFactory { public override List<IDisplaySet> CreateDisplaySets(Series series) { var images = new List<IPresentationImage>(); foreach (var sop in series.Sops) { // TODO CR (Oct 11): To be reworked before next Community release, since we do want this to show // only create placeholders for any non-image, non-presentation state SOPs if (sop.IsImage || sop.SopClassUid == SopClass.EncapsulatedPdfStorageUid || sop.SopClassUid == SopClass.GrayscaleSoftcopyPresentationStateStorageSopClassUid || sop.SopClassUid == SopClass.ColorSoftcopyPresentationStateStorageSopClassUid || sop.SopClassUid == SopClass.PseudoColorSoftcopyPresentationStateStorageSopClassUid || sop.SopClassUid == SopClass.BlendingSoftcopyPresentationStateStorageSopClassUid) continue; images.Add(new PlaceholderPresentationImage(sop)); } if (images.Count > 0) { var displaySet = new DisplaySet(new SeriesDisplaySetDescriptor(series.GetIdentifier(), PresentationImageFactory)); foreach (var image in images) displaySet.PresentationImages.Add(image); return new List<IDisplaySet>(new[] { displaySet }); } return new List<IDisplaySet>(); } #region PlaceholderPresentationImage Class [Cloneable] private sealed class PlaceholderPresentationImage : BasicPresentationImage, ISopProvider { [CloneIgnore] private ISopReference _sopReference; public PlaceholderPresentationImage(Sop sop) : base(new GrayscaleImageGraphic(1, 1)) { _sopReference = sop.CreateTransientReference(); var sopClass = SopClass.GetSopClass(sop.SopClassUid); var sopClassDescription = sopClass != null ? sopClass.Name : SR.LabelUnknown; CompositeImageGraphic.Graphics.Add(new ErrorMessageGraphic { Text = string.Format(SR.MessageUnsupportedImageType, sopClassDescription), Color = Color.WhiteSmoke }); Platform.Log(LogLevel.Warn, "Unsupported SOP Class \"{0} ({1})\" (SOP Instance {2})", sopClassDescription, sop.SopClassUid, sop.SopInstanceUid); } /// <summary> /// Cloning constructor. /// </summary> /// <param name="source">The source object from which to clone.</param> /// <param name="context">The cloning context object.</param> private PlaceholderPresentationImage(PlaceholderPresentationImage source, ICloningContext context) : base(source, context) { _sopReference = source._sopReference.Clone(); context.CloneFields(source, this); } protected override void Dispose(bool disposing) { if (_sopReference != null) { _sopReference.Dispose(); _sopReference = null; } base.Dispose(disposing); } public Sop Sop { get { return _sopReference.Sop; } } protected override IAnnotationLayout CreateAnnotationLayout() { return new AnnotationLayout(); } public override IPresentationImage CreateFreshCopy() { return new PlaceholderPresentationImage(_sopReference.Sop); } [Cloneable(true)] private class ErrorMessageGraphic : InvariantTextPrimitive { protected override SpatialTransform CreateSpatialTransform() { return new InvariantSpatialTransform(this); } public override void OnDrawing() { if (base.ParentPresentationImage != null) { CoordinateSystem = CoordinateSystem.Destination; try { var clientRectangle = ParentPresentationImage.ClientRectangle; Location = new PointF(clientRectangle.Width / 2f, clientRectangle.Height / 2f); } finally { ResetCoordinateSystem(); } } base.OnDrawing(); } } } #endregion } #endregion }
35.7481
181
0.658851
4a1a6fa438cf0e3c274d3b51fd3a3216cef026c7
497
h
C
HintsOnboarding/HintsOnboarding.h
carloshpdoc/tooltips
bd2d12fb17ba0133501623df0e27bd25d5aa0d9a
[ "MIT" ]
null
null
null
HintsOnboarding/HintsOnboarding.h
carloshpdoc/tooltips
bd2d12fb17ba0133501623df0e27bd25d5aa0d9a
[ "MIT" ]
null
null
null
HintsOnboarding/HintsOnboarding.h
carloshpdoc/tooltips
bd2d12fb17ba0133501623df0e27bd25d5aa0d9a
[ "MIT" ]
null
null
null
// // HintsOnboarding.h // HintsOnboarding // // Created by Carlos Henrique on 05/07/21. // #import <Foundation/Foundation.h> //! Project version number for HintsOnboarding. FOUNDATION_EXPORT double HintsOnboardingVersionNumber; //! Project version string for HintsOnboarding. FOUNDATION_EXPORT const unsigned char HintsOnboardingVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <HintsOnboarding/PublicHeader.h>
26.157895
140
0.788732
edb0421a0c05bf7b8b32d98223aebe02fdc4bcb9
12,519
ps1
PowerShell
src/LabServices/exports/New-AzLabServicesLabPlan.ps1
Aviv-Yaniv/azure-powershell
cd12623240e06f54c74ad820d5c85410e3651c23
[ "MIT" ]
1
2022-03-30T13:51:37.000Z
2022-03-30T13:51:37.000Z
src/LabServices/exports/New-AzLabServicesLabPlan.ps1
Aviv-Yaniv/azure-powershell
cd12623240e06f54c74ad820d5c85410e3651c23
[ "MIT" ]
1
2022-03-18T21:01:39.000Z
2022-03-18T21:01:39.000Z
src/LabServices/exports/New-AzLabServicesLabPlan.ps1
yanfa317/azure-powershell
8b0e3334fa5b3cac182612a0663a4216af7ded4f
[ "MIT" ]
null
null
null
# ---------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code # is regenerated. # ---------------------------------------------------------------------------------- <# .Synopsis Operation to create or update a Lab Plan resource. .Description Operation to create or update a Lab Plan resource. .Example PS C:\> New-AzLabServicesLabPlan ` -LabPlanName "testplan" ` -ResourceGroupName "Group Name" ` -Location "westus2" ` -AllowedRegion @('westus2', 'eastus2') ` -DefaultAutoShutdownProfileShutdownOnDisconnect Disabled ` -DefaultAutoShutdownProfileShutdownOnIdle None ` -DefaultAutoShutdownProfileShutdownWhenNotConnected Disabled ` -DefaultConnectionProfileClientRdpAccess Public ` -DefaultConnectionProfileClientSshAccess None ` -SupportInfoEmail '[email protected]' ` -SupportInfoInstruction 'test information' ` -SupportInfoPhone '123-456-7890' ` -SupportInfoUrl 'https:\\test.com' ` -DefaultConnectionProfileWebRdpAccess None ` -DefaultConnectionProfileWebSshAccess None Location Name -------- ---- westus2 testplan .Outputs Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.ILabPlan .Link https://docs.microsoft.com/powershell/module/az.labservices/new-azlabserviceslabplan #> function New-AzLabServicesLabPlan { [OutputType([Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20211001Preview.ILabPlan])] [CmdletBinding(DefaultParameterSetName='CreateExpanded', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] param( [Parameter(Mandatory)] [Alias('LabPlanName')] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Path')] [System.String] # The name of the lab plan that uniquely identifies it within containing resource group. # Used in resource URIs and in UI. ${Name}, [Parameter(Mandatory)] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Path')] [System.String] # The name of the resource group. # The name is case insensitive. ${ResourceGroupName}, [Parameter()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Path')] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] [System.String] # The ID of the target subscription. ${SubscriptionId}, [Parameter(Mandatory)] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [System.String] # The geo-location where the resource lives ${Location}, [Parameter()] [AllowEmptyCollection()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [System.String[]] # The allowed regions for the lab creator to use when creating labs using this lab plan. ${AllowedRegion}, [Parameter()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [System.TimeSpan] # The amount of time a VM will stay running after a user disconnects if this behavior is enabled. ${DefaultAutoShutdownProfileDisconnectDelay}, [Parameter()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [System.TimeSpan] # The amount of time a VM will idle before it is shutdown if this behavior is enabled. ${DefaultAutoShutdownProfileIdleDelay}, [Parameter()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [System.TimeSpan] # The amount of time a VM will stay running before it is shutdown if no connection is made and this behavior is enabled. ${DefaultAutoShutdownProfileNoConnectDelay}, [Parameter()] [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.EnableState])] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.EnableState] # Whether shutdown on disconnect is enabled ${DefaultAutoShutdownProfileShutdownOnDisconnect}, [Parameter()] [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.ShutdownOnIdleMode])] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.ShutdownOnIdleMode] # Whether a VM will get shutdown when it has idled for a period of time. ${DefaultAutoShutdownProfileShutdownOnIdle}, [Parameter()] [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.EnableState])] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.EnableState] # Whether a VM will get shutdown when it hasn't been connected to after a period of time. ${DefaultAutoShutdownProfileShutdownWhenNotConnected}, [Parameter()] [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.ConnectionType])] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.ConnectionType] # The enabled access level for Client Access over RDP. ${DefaultConnectionProfileClientRdpAccess}, [Parameter()] [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.ConnectionType])] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.ConnectionType] # The enabled access level for Client Access over SSH. ${DefaultConnectionProfileClientSshAccess}, [Parameter()] [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.ConnectionType])] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.ConnectionType] # The enabled access level for Web Access over RDP. ${DefaultConnectionProfileWebRdpAccess}, [Parameter()] [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.ConnectionType])] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Support.ConnectionType] # The enabled access level for Web Access over SSH. ${DefaultConnectionProfileWebSshAccess}, [Parameter()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [System.String] # The external subnet resource id ${DefaultNetworkProfileSubnetId}, [Parameter()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [System.String] # Base Url of the lms instance this lab plan can link lab rosters against. ${LinkedLmsInstance}, [Parameter()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [System.String] # Resource ID of the Shared Image Gallery attached to this lab plan. # When saving a lab template virtual machine image it will be persisted in this gallery. # Shared images from the gallery can be made available to use when creating new labs. ${SharedGalleryId}, [Parameter()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [System.String] # Support contact email address. ${SupportInfoEmail}, [Parameter()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [System.String] # Support instructions. ${SupportInfoInstruction}, [Parameter()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [System.String] # Support contact phone number. ${SupportInfoPhone}, [Parameter()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [System.String] # Support web address. ${SupportInfoUrl}, [Parameter()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Body')] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.Info(PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.LabServices.Models.Api20.ITrackedResourceTags]))] [System.Collections.Hashtable] # Resource tags. ${Tag}, [Parameter()] [Alias('AzureRMContext', 'AzureCredential')] [ValidateNotNull()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Azure')] [System.Management.Automation.PSObject] # The credentials, account, tenant, and subscription used for communication with Azure. ${DefaultProfile}, [Parameter()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Runtime')] [System.Management.Automation.SwitchParameter] # Run the command as a job ${AsJob}, [Parameter(DontShow)] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Runtime')] [System.Management.Automation.SwitchParameter] # Wait for .NET debugger to attach ${Break}, [Parameter(DontShow)] [ValidateNotNull()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Runtime')] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.SendAsyncStep[]] # SendAsync Pipeline Steps to be appended to the front of the pipeline ${HttpPipelineAppend}, [Parameter(DontShow)] [ValidateNotNull()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Runtime')] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.SendAsyncStep[]] # SendAsync Pipeline Steps to be prepended to the front of the pipeline ${HttpPipelinePrepend}, [Parameter()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Runtime')] [System.Management.Automation.SwitchParameter] # Run the command asynchronously ${NoWait}, [Parameter(DontShow)] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Runtime')] [System.Uri] # The URI for the proxy server to use ${Proxy}, [Parameter(DontShow)] [ValidateNotNull()] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Runtime')] [System.Management.Automation.PSCredential] # Credentials for a proxy server to use for the remote call ${ProxyCredential}, [Parameter(DontShow)] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Category('Runtime')] [System.Management.Automation.SwitchParameter] # Use the default credentials for the proxy ${ProxyUseDefaultCredentials} ) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $parameterSet = $PSCmdlet.ParameterSetName $mapping = @{ CreateExpanded = 'Az.LabServices.private\New-AzLabServicesLabPlan_CreateExpanded'; } if (('CreateExpanded') -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('SubscriptionId')) { $PSBoundParameters['SubscriptionId'] = (Get-AzContext).Subscription.Id } $cmdInfo = Get-Command -Name $mapping[$parameterSet] [Microsoft.Azure.PowerShell.Cmdlets.LabServices.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters} $steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } }
40.911765
173
0.709402
cbd7f265eb39b0683a99842e28767af22a8ef1e5
61,565
c
C
main/g.c
arbruijn/d1dos
00b969f31fd475530e7e24d7e9759c70705634e0
[ "Unlicense" ]
2
2022-01-15T17:56:45.000Z
2022-02-16T17:58:02.000Z
main/g.c
arbruijn/d1dos
00b969f31fd475530e7e24d7e9759c70705634e0
[ "Unlicense" ]
1
2022-02-16T18:08:42.000Z
2022-02-21T07:42:27.000Z
main/g.c
arbruijn/d1dos
00b969f31fd475530e7e24d7e9759c70705634e0
[ "Unlicense" ]
null
null
null
/* THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE. COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. */ /* * $Source: f:/miner/source/main/rcs/gauges.c $ * $Revision: 2.1 $ * $Author: john $ * $Date: 1995/02/27 13:13:45 $ * * Inferno gauge drivers * * $Log: gauges.c $ * Revision 2.1 1995/02/27 13:13:45 john * Removed floating point. * * Revision 2.0 1995/02/27 11:29:06 john * New version 2.0, which has no anonymous unions, builds with * Watcom 10.0, and doesn't require parsing BITMAPS.TBL. * * Revision 1.203 1995/02/11 01:56:45 mike * move up weapons text on fullscreen hud, missiles was offscreen. * * Revision 1.202 1995/02/09 13:23:34 rob * Added reticle names in demo playback. * * Revision 1.201 1995/02/08 19:20:46 rob * Show cloaked teammates on H * UD. Get rid of show ID's in anarchy option. * * Revision 1.200 1995/02/07 21:09:00 mike * add flashing to invulnerability and cloak on fullscreen. * * Revision 1.199 1995/02/02 21:55:57 matt * Added new colored key icons for fullscreen * * Revision 1.198 1995/01/30 17:17:07 rob * Fixed teammate names on hud. * * Revision 1.197 1995/01/28 17:40:49 mike * fix gauge fontcolor. * * Revision 1.196 1995/01/27 17:03:14 mike * fix placement of weapon info in multiplayer fullscreen, as per AP request. * * Revision 1.195 1995/01/27 11:51:23 rob * Put deaths tally into cooperative mode * * Revision 1.194 1995/01/27 11:43:24 adam * fiddled with key display * * Revision 1.193 1995/01/25 23:38:35 mike * fix keys on fullscreen. * * Revision 1.192 1995/01/24 22:03:28 mike * Lotsa hud stuff, put a lot of messages up. * * Revision 1.191 1995/01/23 16:47:21 rob * Fixed problem with playing extra life noise in coop. * * Revision 1.190 1995/01/22 16:00:46 mike * remove unneeded string. * * Revision 1.189 1995/01/22 15:58:22 mike * localization * * Revision 1.188 1995/01/20 17:19:45 rob * Fixing colors of hud kill list players. * * Revision 1.187 1995/01/20 09:19:18 allender * record player flags when in CM_FULL_SCREEN * * Revision 1.186 1995/01/19 16:29:09 allender * made demo recording of weapon change be in this file for shareware only * * Revision 1.185 1995/01/19 15:00:33 allender * code to record shield, energy, and ammo in fullscreen * * Revision 1.184 1995/01/19 13:43:13 matt * Fixed "cheater" message on HUD * * Revision 1.183 1995/01/18 16:11:58 mike * Don't show added scores of 0. * * Revision 1.182 1995/01/17 17:42:39 allender * do ammo counts in demo recording * * Revision 1.181 1995/01/16 17:26:25 rob * Fixed problem with coloration of team kill list. * * Revision 1.180 1995/01/16 17:22:39 john * Made so that KB and framerate don't collide. * * Revision 1.179 1995/01/16 14:58:31 matt * Changed score_added display to print "Cheater!" when cheats enabled * * Revision 1.178 1995/01/15 19:42:07 matt * Ripped out hostage faces for registered version * * Revision 1.177 1995/01/15 19:25:07 mike * show vulcan ammo and secondary ammo in fullscreen view. * * Revision 1.176 1995/01/15 13:16:12 john * Made so that paging always happens, lowmem just loads less. * Also, make KB load print to hud. * * Revision 1.175 1995/01/14 19:17:32 john * First version of piggy paging. * * Revision 1.174 1995/01/05 21:25:23 rob * Re-did some changes lost due to RCS weirdness. * * Revision 1.173 1995/01/05 12:22:34 rob * Don't show player names for cloaked players. * * Revision 1.172 1995/01/04 17:14:50 allender * make init_gauges work properly on demo playback * * Revision 1.171 1995/01/04 15:04:42 allender * new demo calls for registered version * * Revision 1.167 1995/01/03 13:03:57 allender * pass score points instead of total points. Added ifdef for * multi_send_score * * Revision 1.166 1995/01/03 11:45:02 allender * add hook to record player score * * Revision 1.165 1995/01/03 11:25:19 allender * remove newdemo stuff around score display * * Revision 1.163 1995/01/02 21:03:53 rob * Fixing up the hud-score-list for coop games. * * Revision 1.162 1994/12/31 20:54:40 rob * Added coop mode HUD score list. * Added more generic system for player names on HUD. * * Revision 1.161 1994/12/30 20:13:01 rob * Ifdef reticle names on shareware. * Added robot reticle naming. * * Revision 1.160 1994/12/29 17:53:51 mike * move up energy/shield in fullscreen to get out of way of kill list. * * Revision 1.159 1994/12/29 16:44:05 mike * add energy and shield showing. * * Revision 1.158 1994/12/28 16:34:29 mike * make warning beep go away on Player_is_dead. * * Revision 1.157 1994/12/28 10:00:43 allender * change in init_gauges to for multiplayer demo playbacks * * Revision 1.156 1994/12/27 11:06:46 allender * removed some previous code to for demo playback stuff * * Revision 1.155 1994/12/23 14:23:06 john * Added floating reticle for VR helments. * * Revision 1.154 1994/12/21 12:56:41 allender * on multiplayer demo playback, show kills and deaths * * Revision 1.153 1994/12/19 20:28:42 rob * Get rid of kill list in coop games. * * Revision 1.152 1994/12/14 18:06:44 matt * Removed compile warnings * * Revision 1.151 1994/12/14 15:21:28 rob * Made gauges align in status_bar net game. * * Revision 1.150 1994/12/12 17:20:33 matt * Don't get bonus points when cheating * * Revision 1.149 1994/12/12 16:47:00 matt * When cheating, get no score. Change level cheat to prompt for and * jump to new level. * * Revision 1.148 1994/12/12 12:05:45 rob * Grey out players who are disconnected. * * Revision 1.147 1994/12/09 16:19:48 yuan * kill matrix stuff. * * Revision 1.146 1994/12/09 16:12:34 rob * Fixed up the status bar kills gauges for net play. * * Revision 1.145 1994/12/09 01:55:34 rob * Added kills list to HUD/status bar. * Added something for Mark. * * Revision 1.144 1994/12/08 21:03:30 allender * pass old player flags to record_player_flags * * Revision 1.143 1994/12/07 22:49:33 mike * no homing missile warning during endlevel sequence. * * Revision 1.142 1994/12/06 13:55:31 matt * Use new rounding func, f2ir() * * Revision 1.141 1994/12/03 19:03:37 matt * Fixed vulcan ammo HUD message * * Revision 1.140 1994/12/03 18:43:18 matt * Fixed (hopefully) claok gauge * * Revision 1.139 1994/12/03 14:26:21 yuan * Fixed dumb bug * * Revision 1.138 1994/12/03 14:17:30 yuan * Localization 320 * */ #pragma off (unreferenced) static char rcsid[] = "$Id: gauges.c 2.1 1995/02/27 13:13:45 john Exp $"; #pragma on (unreferenced) #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include "inferno.h" #include "game.h" #include "screens.h" #include "gauges.h" #include "physics.h" #include "error.h" #include "menu.h" // For the font. #include "mono.h" #include "collide.h" #include "newdemo.h" #include "player.h" #include "gamefont.h" #include "hostage.h" #include "bm.h" #include "text.h" #include "powerup.h" #include "sounds.h" #include "multi.h" #include "network.h" #include "endlevel.h" #include "wall.h" #include "text.h" #include "render.h" #include "piggy.h" bitmap_index Gauges[MAX_GAUGE_BMS]; // Array of all gauge bitmaps. grs_canvas *Canv_LeftEnergyGauge; grs_canvas *Canv_SBEnergyGauge; grs_canvas *Canv_RightEnergyGauge; grs_canvas *Canv_NumericalGauge; //bitmap numbers for gauges #define GAUGE_SHIELDS 0 //0..9, in decreasing order (100%,90%...0%) #define GAUGE_INVULNERABLE 10 //10..19 #define N_INVULNERABLE_FRAMES 10 #define GAUGE_SPEED 20 //unused #define GAUGE_ENERGY_LEFT 21 #define GAUGE_ENERGY_RIGHT 22 #define GAUGE_NUMERICAL 23 #define GAUGE_BLUE_KEY 24 #define GAUGE_GOLD_KEY 25 #define GAUGE_RED_KEY 26 #define GAUGE_BLUE_KEY_OFF 27 #define GAUGE_GOLD_KEY_OFF 28 #define GAUGE_RED_KEY_OFF 29 #define SB_GAUGE_BLUE_KEY 30 #define SB_GAUGE_GOLD_KEY 31 #define SB_GAUGE_RED_KEY 32 #define SB_GAUGE_BLUE_KEY_OFF 33 #define SB_GAUGE_GOLD_KEY_OFF 34 #define SB_GAUGE_RED_KEY_OFF 35 #define SB_GAUGE_ENERGY 36 #define GAUGE_LIVES 37 #define GAUGE_SHIPS 38 #define GAUGE_SHIPS_LAST 45 #define RETICLE_CROSS 46 #define RETICLE_PRIMARY 48 #define RETICLE_SECONDARY 51 #define RETICLE_LAST 55 #define GAUGE_HOMING_WARNING_ON 56 #define GAUGE_HOMING_WARNING_OFF 57 #define SML_RETICLE_CROSS 58 #define SML_RETICLE_PRIMARY 60 #define SML_RETICLE_SECONDARY 63 #define SML_RETICLE_LAST 67 #define KEY_ICON_BLUE 68 #define KEY_ICON_YELLOW 69 #define KEY_ICON_RED 70 //change MAX_GAUGE_BMS when adding gauges //Coordinats for gauges #define GAUGE_BLUE_KEY_X 45 #define GAUGE_BLUE_KEY_Y 152 #define GAUGE_GOLD_KEY_X 44 #define GAUGE_GOLD_KEY_Y 162 #define GAUGE_RED_KEY_X 43 #define GAUGE_RED_KEY_Y 172 #define SB_GAUGE_KEYS_X 11 #define SB_GAUGE_BLUE_KEY_Y 153 #define SB_GAUGE_GOLD_KEY_Y 169 #define SB_GAUGE_RED_KEY_Y 185 #define LEFT_ENERGY_GAUGE_X 70 #define LEFT_ENERGY_GAUGE_Y 131 #define LEFT_ENERGY_GAUGE_W 64 #define LEFT_ENERGY_GAUGE_H 8 #define RIGHT_ENERGY_GAUGE_X 190 #define RIGHT_ENERGY_GAUGE_Y 131 #define RIGHT_ENERGY_GAUGE_W 64 #define RIGHT_ENERGY_GAUGE_H 8 #define SB_ENERGY_GAUGE_X 98 #define SB_ENERGY_GAUGE_Y 155 #define SB_ENERGY_GAUGE_W 16 #define SB_ENERGY_GAUGE_H 41 #define SB_ENERGY_NUM_X (SB_ENERGY_GAUGE_X+2) #define SB_ENERGY_NUM_Y 190 #define SHIELD_GAUGE_X 146 #define SHIELD_GAUGE_Y 155 #define SHIELD_GAUGE_W 35 #define SHIELD_GAUGE_H 32 #define SHIP_GAUGE_X (SHIELD_GAUGE_X+5) #define SHIP_GAUGE_Y (SHIELD_GAUGE_Y+5) #define SB_SHIELD_GAUGE_X 123 //139 #define SB_SHIELD_GAUGE_Y 163 #define SB_SHIP_GAUGE_X (SB_SHIELD_GAUGE_X+5) #define SB_SHIP_GAUGE_Y (SB_SHIELD_GAUGE_Y+5) #define SB_SHIELD_NUM_X (SB_SHIELD_GAUGE_X+12) //151 #define SB_SHIELD_NUM_Y 156 #define NUMERICAL_GAUGE_X 154 #define NUMERICAL_GAUGE_Y 130 #define NUMERICAL_GAUGE_W 19 #define NUMERICAL_GAUGE_H 22 #define PRIMARY_W_PIC_X 64 #define PRIMARY_W_PIC_Y 154 #define PRIMARY_W_TEXT_X 87 #define PRIMARY_W_TEXT_Y 157 #define PRIMARY_AMMO_X (96-3) #define PRIMARY_AMMO_Y 171 #define SECONDARY_W_PIC_X 234 #define SECONDARY_W_PIC_Y 154 #define SECONDARY_W_TEXT_X 207 #define SECONDARY_W_TEXT_Y 157 #define SECONDARY_AMMO_X 213 #define SECONDARY_AMMO_Y 171 #define SB_LIVES_X 266 #define SB_LIVES_Y 185 #define SB_LIVES_LABEL_X 237 #define SB_LIVES_LABEL_Y (SB_LIVES_Y+1) #define SB_SCORE_RIGHT 301 #define SB_SCORE_Y 158 #define SB_SCORE_LABEL_X 237 #define SB_SCORE_ADDED_RIGHT 301 #define SB_SCORE_ADDED_Y 165 static int score_display; static fix score_time; static int old_score = -1; static int old_energy = -1; static int old_shields = -1; static int old_laser = -1; static int old_flags = -1; static int invulnerable_frame = 0; static int old_weapon[2] = {-1,-1}; static int old_ammo_count[2] = {-1,-1}; static int old_cloak = 0; static int old_lives = -1; static int cloak_fade_state; //0=steady, -1 fading out, 1 fading in #define WS_SET 0 //in correct state #define WS_FADING_OUT 1 #define WS_FADING_IN 2 int weapon_box_states[2]; fix weapon_box_fade_values[2]; #define FADE_SCALE (2*i2f(GR_FADE_LEVELS)/REARM_TIME) // fade out and back in REARM_TIME, in fade levels per seconds (int) typedef struct span { byte l,r; } span; //store delta x values from left of box span weapon_window_left[] = { //first span 67,154 {4,53}, {4,53}, {4,53}, {4,53}, {4,53}, {3,53}, {3,53}, {3,53}, {3,53}, {3,53}, {3,53}, {3,53}, {3,53}, {2,53}, {2,53}, {2,53}, {2,53}, {2,53}, {2,53}, {2,53}, {2,53}, {1,53}, {1,53}, {1,53}, {1,53}, {1,53}, {1,53}, {1,53}, {1,53}, {0,53}, {0,53}, {0,53}, {0,53}, {0,52}, {1,52}, {2,51}, {3,51}, {4,50}, {5,50}, }; //store delta x values from left of box span weapon_window_right[] = { //first span 207,154 {208-202,255-202}, {206-202,257-202}, {205-202,258-202}, {204-202,259-202}, {203-202,260-202}, {203-202,260-202}, {203-202,260-202}, {203-202,260-202}, {203-202,260-202}, {203-202,261-202}, {203-202,261-202}, {203-202,261-202}, {203-202,261-202}, {203-202,261-202}, {203-202,261-202}, {203-202,261-202}, {203-202,261-202}, {203-202,261-202}, {203-202,262-202}, {203-202,262-202}, {203-202,262-202}, {203-202,262-202}, {203-202,262-202}, {203-202,262-202}, {203-202,262-202}, {203-202,262-202}, {204-202,263-202}, {204-202,263-202}, {204-202,263-202}, {204-202,263-202}, {204-202,263-202}, {204-202,263-202}, {204-202,263-202}, {204-202,263-202}, {204-202,263-202}, {204-202,263-202}, {204-202,263-202}, {204-202,263-202}, {205-202,263-202}, {206-202,262-202}, {207-202,261-202}, {208-202,260-202}, {211-202,255-202}, }; #define N_LEFT_WINDOW_SPANS (sizeof(weapon_window_left)/sizeof(*weapon_window_left)) #define N_RIGHT_WINDOW_SPANS (sizeof(weapon_window_right)/sizeof(*weapon_window_right)) #define PRIMARY_W_BOX_LEFT 63 #define PRIMARY_W_BOX_TOP 154 #define PRIMARY_W_BOX_RIGHT (PRIMARY_W_BOX_LEFT+58) #define PRIMARY_W_BOX_BOT (PRIMARY_W_BOX_TOP+N_LEFT_WINDOW_SPANS-1) #define SECONDARY_W_BOX_LEFT 202 //207 #define SECONDARY_W_BOX_TOP 151 #define SECONDARY_W_BOX_RIGHT 263 //(SECONDARY_W_BOX_LEFT+54) #define SECONDARY_W_BOX_BOT (SECONDARY_W_BOX_TOP+N_RIGHT_WINDOW_SPANS-1) #define SB_PRIMARY_W_BOX_LEFT 34 //50 #define SB_PRIMARY_W_BOX_TOP 153 #define SB_PRIMARY_W_BOX_RIGHT (SB_PRIMARY_W_BOX_LEFT+53) #define SB_PRIMARY_W_BOX_BOT (195) #define SB_SECONDARY_W_BOX_LEFT 169 //210 #define SB_SECONDARY_W_BOX_TOP 153 #define SB_SECONDARY_W_BOX_RIGHT (SB_SECONDARY_W_BOX_LEFT+54) #define SB_SECONDARY_W_BOX_BOT (153+43) #define SB_PRIMARY_W_PIC_X (SB_PRIMARY_W_BOX_LEFT+1) //51 #define SB_PRIMARY_W_PIC_Y 154 #define SB_PRIMARY_W_TEXT_X (SB_PRIMARY_W_BOX_LEFT+24) //(51+23) #define SB_PRIMARY_W_TEXT_Y 157 #define SB_PRIMARY_AMMO_X ((SB_PRIMARY_W_BOX_LEFT+33)-3) //(51+32) #define SB_PRIMARY_AMMO_Y 171 #define SB_SECONDARY_W_PIC_X (SB_SECONDARY_W_BOX_LEFT+29) //(212+27) #define SB_SECONDARY_W_PIC_Y 154 #define SB_SECONDARY_W_TEXT_X (SB_SECONDARY_W_BOX_LEFT+2) //212 #define SB_SECONDARY_W_TEXT_Y 157 #define SB_SECONDARY_AMMO_X (SB_SECONDARY_W_BOX_LEFT+11) //(212+9) #define SB_SECONDARY_AMMO_Y 171 typedef struct gauge_box { int left,top; int right,bot; //maximal box span *spanlist; //list of left,right spans for copy } gauge_box; //first two are primary & secondary //seconds two are the same for the status bar gauge_box gauge_boxes[] = { {PRIMARY_W_BOX_LEFT,PRIMARY_W_BOX_TOP,PRIMARY_W_BOX_RIGHT,PRIMARY_W_BOX_BOT,weapon_window_left}, {SECONDARY_W_BOX_LEFT,SECONDARY_W_BOX_TOP,SECONDARY_W_BOX_RIGHT,SECONDARY_W_BOX_BOT,weapon_window_right}, {SB_PRIMARY_W_BOX_LEFT,SB_PRIMARY_W_BOX_TOP,SB_PRIMARY_W_BOX_RIGHT,SB_PRIMARY_W_BOX_BOT,NULL}, {SB_SECONDARY_W_BOX_LEFT,SB_SECONDARY_W_BOX_TOP,SB_SECONDARY_W_BOX_RIGHT,SB_SECONDARY_W_BOX_BOT,NULL} }; int Color_0_31_0 = -1; //copy a box from the off-screen buffer to the visible page copy_gauge_box(gauge_box *box,grs_bitmap *bm) { if (box->spanlist) { int n_spans = box->bot-box->top+1; int cnt,y; //gr_setcolor(BM_XRGB(31,0,0)); for (cnt=0,y=box->top;cnt<n_spans;cnt++,y++) gr_bm_ubitblt(box->spanlist[cnt].r-box->spanlist[cnt].l+1,1, box->left+box->spanlist[cnt].l,y,box->left+box->spanlist[cnt].l,y,bm,&grd_curcanv->cv_bitmap); //gr_scanline(box->left+box->spanlist[cnt].l,box->left+box->spanlist[cnt].r,y); } else gr_bm_ubitblt(box->right-box->left+1,box->bot-box->top+1, box->left,box->top,box->left,box->top, bm,&grd_curcanv->cv_bitmap); } //fills in the coords of the hostage video window get_hostage_window_coords(int *x,int *y,int *w,int *h) { if (Cockpit_mode == CM_STATUS_BAR) { *x = SB_SECONDARY_W_BOX_LEFT; *y = SB_SECONDARY_W_BOX_TOP; *w = SB_SECONDARY_W_BOX_RIGHT - SB_SECONDARY_W_BOX_LEFT + 1; *h = SB_SECONDARY_W_BOX_BOT - SB_SECONDARY_W_BOX_TOP + 1; } else { *x = SECONDARY_W_BOX_LEFT; *y = SECONDARY_W_BOX_TOP; *w = SECONDARY_W_BOX_RIGHT - SECONDARY_W_BOX_LEFT + 1; *h = SECONDARY_W_BOX_BOT - SECONDARY_W_BOX_TOP + 1; } } //these should be in gr.h #define cv_w cv_bitmap.bm_w #define cv_h cv_bitmap.bm_h #define HUD_MESSAGE_LENGTH 150 #define HUD_MAX_NUM 4 extern int HUD_nmessages, hud_first; // From hud.c extern char HUD_messages[HUD_MAX_NUM][HUD_MESSAGE_LENGTH+5]; void hud_show_score() { char score_str[20]; int w, h, aw; if ((HUD_nmessages > 0) && (strlen(HUD_messages[hud_first]) > 38)) return; gr_set_curfont( GAME_FONT ); if ( ((Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP)) ) { sprintf(score_str, "%s: %5d", TXT_KILLS, Players[Player_num].net_kills_total); } else { sprintf(score_str, "%s: %5d", TXT_SCORE, Players[Player_num].score); } gr_get_string_size(score_str, &w, &h, &aw ); if (Color_0_31_0 == -1) Color_0_31_0 = gr_getcolor(0,31,0); gr_set_fontcolor(Color_0_31_0, -1); gr_printf(grd_curcanv->cv_w-w-2, 3, score_str); } void hud_show_score_added() { int color; int w, h, aw; char score_str[20]; if ( (Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP) ) return; if (score_display == 0) return; gr_set_curfont( GAME_FONT ); score_time -= FrameTime; if (score_time > 0) { color = f2i(score_time * 20) + 10; if (color < 10) color = 10; if (color > 31) color = 31; if (Cheats_enabled) sprintf(score_str, "%s", TXT_CHEATER); else sprintf(score_str, "%5d", score_display); gr_get_string_size(score_str, &w, &h, &aw ); gr_set_fontcolor(gr_getcolor(0, color, 0),-1 ); gr_printf(grd_curcanv->cv_w-w-2-10, GAME_FONT->ft_h+5, score_str); } else { score_time = 0; score_display = 0; } } void sb_show_score() { char score_str[20]; int x,y; int w, h, aw; static int last_x=SB_SCORE_RIGHT; int redraw_score; if ( (Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP) ) redraw_score = -99; else redraw_score = -1; if (old_score==redraw_score) { gr_set_curfont( GAME_FONT ); gr_set_fontcolor(gr_getcolor(0,20,0),-1 ); if ( (Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP) ) gr_printf(SB_SCORE_LABEL_X,SB_SCORE_Y,"%s:", TXT_KILLS); else gr_printf(SB_SCORE_LABEL_X,SB_SCORE_Y,"%s:", TXT_SCORE); } gr_set_curfont( GAME_FONT ); if ( (Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP) ) sprintf(score_str, "%5d", Players[Player_num].net_kills_total); else sprintf(score_str, "%5d", Players[Player_num].score); gr_get_string_size(score_str, &w, &h, &aw ); x = SB_SCORE_RIGHT-w-2; y = SB_SCORE_Y; //erase old score gr_setcolor(BM_XRGB(0,0,0)); gr_rect(last_x,y,SB_SCORE_RIGHT,y+GAME_FONT->ft_h); if ( (Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP) ) gr_set_fontcolor(gr_getcolor(0,20,0),-1 ); else gr_set_fontcolor(gr_getcolor(0,31,0),-1 ); gr_printf(x,y,score_str); last_x = x; } void sb_show_score_added() { int color; int w, h, aw; char score_str[32]; int x; static int last_x=SB_SCORE_ADDED_RIGHT; static int last_score_display = -1; if ( (Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP) ) return; if (score_display == 0) return; gr_set_curfont( GAME_FONT ); score_time -= FrameTime; if (score_time > 0) { if (score_display != last_score_display) { gr_setcolor(BM_XRGB(0,0,0)); gr_rect(last_x,SB_SCORE_ADDED_Y,SB_SCORE_ADDED_RIGHT,SB_SCORE_ADDED_Y+GAME_FONT->ft_h); last_score_display = score_display; } color = f2i(score_time * 20) + 10; if (color < 10) color = 10; if (color > 31) color = 31; if (Cheats_enabled) sprintf(score_str, "%s", TXT_CHEATER); else sprintf(score_str, "%5d", score_display); gr_get_string_size(score_str, &w, &h, &aw ); x = SB_SCORE_ADDED_RIGHT-w-2; gr_set_fontcolor(gr_getcolor(0, color, 0),-1 ); gr_printf(x, SB_SCORE_ADDED_Y, score_str); last_x = x; } else { //erase old score gr_setcolor(BM_XRGB(0,0,0)); gr_rect(last_x,SB_SCORE_ADDED_Y,SB_SCORE_ADDED_RIGHT,SB_SCORE_ADDED_Y+GAME_FONT->ft_h); score_time = 0; score_display = 0; } } fix Last_warning_beep_time = 0; // Time we last played homing missile warning beep. // ----------------------------------------------------------------------------- void play_homing_warning(void) { fix beep_delay; if (Endlevel_sequence || Player_is_dead) return; if (Players[Player_num].homing_object_dist >= 0) { beep_delay = Players[Player_num].homing_object_dist/128; if (beep_delay > F1_0) beep_delay = F1_0; else if (beep_delay < F1_0/8) beep_delay = F1_0/8; if (GameTime - Last_warning_beep_time > beep_delay/2) { digi_play_sample( SOUND_HOMING_WARNING, F1_0 ); Last_warning_beep_time = GameTime; } } } int Last_homing_warning_shown=-1; // ----------------------------------------------------------------------------- void show_homing_warning(void) { if ((Cockpit_mode == CM_STATUS_BAR) || (Endlevel_sequence)) { if (Last_homing_warning_shown == 1) { PIGGY_PAGE_IN( Gauges[GAUGE_HOMING_WARNING_OFF] ); gr_ubitmapm( 7, 171, &GameBitmaps[Gauges[GAUGE_HOMING_WARNING_OFF].index] ); Last_homing_warning_shown = 0; } return; } gr_set_current_canvas( get_current_game_screen() ); if (Players[Player_num].homing_object_dist >= 0) { if (GameTime & 0x4000) { if (Last_homing_warning_shown != 1) { PIGGY_PAGE_IN(Gauges[GAUGE_HOMING_WARNING_ON]); gr_ubitmapm( 7, 171, &GameBitmaps[Gauges[GAUGE_HOMING_WARNING_ON].index]); Last_homing_warning_shown = 1; } } else { if (Last_homing_warning_shown != 0) { PIGGY_PAGE_IN(Gauges[GAUGE_HOMING_WARNING_OFF]); gr_ubitmapm( 7, 171, &GameBitmaps[Gauges[GAUGE_HOMING_WARNING_OFF].index] ); Last_homing_warning_shown = 0; } } } else if (Last_homing_warning_shown != 0) { PIGGY_PAGE_IN(Gauges[GAUGE_HOMING_WARNING_OFF]); gr_ubitmapm( 7, 171, &GameBitmaps[Gauges[GAUGE_HOMING_WARNING_OFF].index] ); Last_homing_warning_shown = 0; } } #define MAX_SHOWN_LIVES 4 void hud_show_homing_warning(void) { if (Players[Player_num].homing_object_dist >= 0) { if (GameTime & 0x4000) { gr_set_current_canvas(&VR_render_sub_buffer[0]); //render off-screen gr_set_curfont( GAME_FONT ); gr_set_fontcolor(gr_getcolor(0,31,0),-1 ); gr_printf(0x8000, grd_curcanv->cv_h-8,TXT_LOCK); } } } void hud_show_keys(void) { if (Players[Player_num].flags & PLAYER_FLAGS_BLUE_KEY) { PIGGY_PAGE_IN(Gauges[KEY_ICON_BLUE]); gr_ubitmapm(2,24,&GameBitmaps[Gauges[KEY_ICON_BLUE].index]); } if (Players[Player_num].flags & PLAYER_FLAGS_GOLD_KEY) { PIGGY_PAGE_IN(Gauges[KEY_ICON_YELLOW]); gr_ubitmapm(10,24,&GameBitmaps[Gauges[KEY_ICON_YELLOW].index]); } if (Players[Player_num].flags & PLAYER_FLAGS_RED_KEY) { PIGGY_PAGE_IN(Gauges[KEY_ICON_RED]); gr_ubitmapm(18,24,&GameBitmaps[Gauges[KEY_ICON_RED].index]); } } void hud_show_energy(void) { gr_set_current_canvas(&VR_render_sub_buffer[0]); //render off-screen gr_set_curfont( GAME_FONT ); gr_set_fontcolor(gr_getcolor(0,31,0),-1 ); if (Game_mode & GM_MULTI) gr_printf(2, grd_curcanv->cv_h-40,"%s: %i", TXT_ENERGY, f2ir(Players[Player_num].energy)); else gr_printf(2, grd_curcanv->cv_h-8,"%s: %i", TXT_ENERGY, f2ir(Players[Player_num].energy)); if (Newdemo_state==ND_STATE_RECORDING ) { int energy = f2ir(Players[Player_num].energy); if (energy != old_energy) { #ifdef SHAREWARE newdemo_record_player_energy(energy); #else newdemo_record_player_energy(old_energy, energy); #endif old_energy = energy; } } } void hud_show_weapons(void) { int w, h, aw; int y; char weapon_str[32], temp_str[10]; gr_set_current_canvas(&VR_render_sub_buffer[0]); //render off-screen gr_set_curfont( GAME_FONT ); gr_set_fontcolor(gr_getcolor(0,31,0),-1 ); if (Game_mode & GM_MULTI) y = grd_curcanv->cv_h-32; else y = grd_curcanv->cv_h; // #ifndef RELEASE y -= 8; // #endif switch (Primary_weapon) { case 0: if (Players[Player_num].flags & PLAYER_FLAGS_QUAD_LASERS) sprintf(weapon_str, "%s %s %i", TXT_QUAD, TXT_LASER, Players[Player_num].laser_level+1); else sprintf(weapon_str, "%s %i", TXT_LASER, Players[Player_num].laser_level+1); break; case 1: sprintf(weapon_str, "%s: %i", TXT_W_VULCAN_S, f2i(Players[Player_num].primary_ammo[Primary_weapon] * VULCAN_AMMO_SCALE)); break; case 2: strcpy(weapon_str, TXT_W_SPREADFIRE_S); break; #ifndef SHAREWARE case 3: strcpy(weapon_str, TXT_W_PLASMA_S); break; case 4: strcpy(weapon_str, TXT_W_FUSION_S); break; #endif } gr_get_string_size(weapon_str, &w, &h, &aw ); gr_printf(315-w, y-8, weapon_str); if (Primary_weapon == VULCAN_INDEX) { #ifndef SHAREWARE if (Players[Player_num].primary_ammo[Primary_weapon] != old_ammo_count[0]) { if (Newdemo_state == ND_STATE_RECORDING) newdemo_record_primary_ammo(old_ammo_count[0], Players[Player_num].primary_ammo[Primary_weapon]); old_ammo_count[0] = Players[Player_num].primary_ammo[Primary_weapon]; } #endif } switch (Secondary_weapon) { case 0: strcpy(weapon_str, TXT_CONCUSSION); break; case 1: strcpy(weapon_str, TXT_HOMING); break; case 2: strcpy(weapon_str, TXT_PROXBOMB ); break; #ifndef SHAREWARE case 3: strcpy(weapon_str, TXT_SMART); break; case 4: strcpy(weapon_str, TXT_MEGA); break; #endif default: Int3(); weapon_str[0] = 0; break; } #ifndef SHAREWARE if (Players[Player_num].secondary_ammo[Secondary_weapon] != old_ammo_count[1]) { if (Newdemo_state == ND_STATE_RECORDING) newdemo_record_secondary_ammo(old_ammo_count[1], Players[Player_num].secondary_ammo[Secondary_weapon]); old_ammo_count[1] = Players[Player_num].secondary_ammo[Secondary_weapon]; } #endif strcat(weapon_str, " "); strcat(weapon_str, itoa(Players[Player_num].secondary_ammo[Secondary_weapon], temp_str, 10)); gr_get_string_size(weapon_str, &w, &h, &aw ); gr_printf(315-w, y, weapon_str); } void hud_show_cloak_invuln(void) { if (Players[Player_num].flags & PLAYER_FLAGS_CLOAKED) { int y = grd_curcanv->cv_h; if (Game_mode & GM_MULTI) y -= 72; else y -= 32; if ((Players[Player_num].cloak_time+CLOAK_TIME_MAX - GameTime > F1_0*3 ) || (GameTime & 0x8000)) gr_printf(2, y, "%s", TXT_CLOAKED); } if (Players[Player_num].flags & PLAYER_FLAGS_INVULNERABLE) { int y = grd_curcanv->cv_h; if (Game_mode & GM_MULTI) y -= 80; else y -= 40; if (((Players[Player_num].invulnerable_time + INVULNERABLE_TIME_MAX - GameTime) > F1_0*4) || (GameTime & 0x8000)) gr_printf(2, y, "%s", TXT_INVULNERABLE); } } void hud_show_shield(void) { gr_set_current_canvas(&VR_render_sub_buffer[0]); //render off-screen gr_set_curfont( GAME_FONT ); gr_set_fontcolor(gr_getcolor(0,31,0),-1 ); if (Game_mode & GM_MULTI) gr_printf(2, grd_curcanv->cv_h-48,"%s: %i", TXT_SHIELD, f2ir(Players[Player_num].shields)); else gr_printf(2, grd_curcanv->cv_h-16,"%s: %i", TXT_SHIELD, f2ir(Players[Player_num].shields)); if (Newdemo_state==ND_STATE_RECORDING ) { int shields = f2ir(Players[Player_num].shields); if (shields != old_shields) { // Draw the shield gauge #ifdef SHAREWARE newdemo_record_player_shields(shields); #else newdemo_record_player_shields(old_shields, shields); #endif old_shields = shields; } } } //draw the icons for number of lives hud_show_lives() { if ((HUD_nmessages > 0) && (strlen(HUD_messages[hud_first]) > 38)) return; if (Game_mode & GM_MULTI) { gr_set_curfont( GAME_FONT ); gr_set_fontcolor(gr_getcolor(0,31,0),-1 ); gr_printf(10, 3, "%s: %d", TXT_DEATHS, Players[Player_num].net_killed_total); } else if (Players[Player_num].lives > 1) { gr_set_curfont( GAME_FONT ); gr_set_fontcolor(gr_getcolor(0,20,0),-1 ); PIGGY_PAGE_IN(Gauges[GAUGE_LIVES]); gr_ubitmapm(10,3,&GameBitmaps[Gauges[GAUGE_LIVES].index]); gr_printf(22, 3, "x %d", Players[Player_num].lives-1); } } sb_show_lives() { int x,y; grs_bitmap * bm = &GameBitmaps[Gauges[GAUGE_LIVES].index]; x = SB_LIVES_X; y = SB_LIVES_Y; if (old_lives==-1) { gr_set_curfont( GAME_FONT ); gr_set_fontcolor(gr_getcolor(0,20,0),-1 ); if (Game_mode & GM_MULTI) gr_printf(SB_LIVES_LABEL_X,SB_LIVES_LABEL_Y,"%s:", TXT_DEATHS); else gr_printf(SB_LIVES_LABEL_X,SB_LIVES_LABEL_Y,"%s:", TXT_LIVES); } if (Game_mode & GM_MULTI) { char killed_str[20]; int w, h, aw; static int last_x = SB_SCORE_RIGHT; int x; sprintf(killed_str, "%5d", Players[Player_num].net_killed_total); gr_get_string_size(killed_str, &w, &h, &aw); gr_setcolor(BM_XRGB(0,0,0)); gr_rect(last_x, y+1, SB_SCORE_RIGHT, y+GAME_FONT->ft_h); gr_set_fontcolor(gr_getcolor(0,20,0),-1); x = SB_SCORE_RIGHT-w-2; gr_printf(x, y+1, killed_str); last_x = x; return; } if (old_lives==-1 || Players[Player_num].lives != old_lives) { //erase old icons gr_setcolor(BM_XRGB(0,0,0)); gr_rect(x, y, x+32, y+bm->bm_h); if (Players[Player_num].lives-1 > 0) { gr_set_curfont( GAME_FONT ); gr_set_fontcolor(gr_getcolor(0,20,0),-1 ); PIGGY_PAGE_IN(Gauges[GAUGE_LIVES]); gr_ubitmapm(x, y,bm); gr_printf(x+12, y, "x %d", Players[Player_num].lives-1); } } // for (i=0;i<draw_count;i++,x+=bm->bm_w+2) // gr_ubitmapm(x,y,bm); } #ifndef RELEASE #ifdef PIGGY_USE_PAGING extern int Piggy_bitmap_cache_next; #endif void show_time() { int secs = f2i(Players[Player_num].time_level) % 60; int mins = f2i(Players[Player_num].time_level) / 60; gr_set_curfont( GAME_FONT ); if (Color_0_31_0 == -1) Color_0_31_0 = gr_getcolor(0,31,0); gr_set_fontcolor(Color_0_31_0, -1 ); gr_printf(grd_curcanv->cv_w-25,grd_curcanv->cv_h-28,"%d:%02d", mins, secs); #ifdef PIGGY_USE_PAGING { char text[25]; int w,h,aw; sprintf( text, "%d KB", Piggy_bitmap_cache_next/1024 ); gr_get_string_size( text, &w, &h, &aw ); gr_printf(grd_curcanv->cv_w-10-w,grd_curcanv->cv_h/2, text ); } #endif } #endif #define EXTRA_SHIP_SCORE 50000 //get new ship every this many points void add_points_to_score(int points) { int prev_score; score_time += f1_0*2; score_display += points; if (score_time > f1_0*4) score_time = f1_0*4; if (points == 0 || Cheats_enabled) return; if ((Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP)) return; prev_score=Players[Player_num].score; Players[Player_num].score += points; #ifndef SHAREWARE if (Newdemo_state == ND_STATE_RECORDING) newdemo_record_player_score(points); #endif #ifndef SHAREWARE if (Game_mode & GM_MULTI_COOP) multi_send_score(); #endif if (Game_mode & GM_MULTI) return; if (Players[Player_num].score/EXTRA_SHIP_SCORE != prev_score/EXTRA_SHIP_SCORE) { int snd; Players[Player_num].lives += Players[Player_num].score/EXTRA_SHIP_SCORE - prev_score/EXTRA_SHIP_SCORE; powerup_basic(20, 20, 20, 0, TXT_EXTRA_LIFE); if ((snd=Powerup_info[POW_EXTRA_LIFE].hit_sound) > -1 ) digi_play_sample( snd, F1_0 ); } } void add_bonus_points_to_score(int points) { int prev_score; if (points == 0 || Cheats_enabled) return; prev_score=Players[Player_num].score; Players[Player_num].score += points; #ifndef SHAREWARE if (Newdemo_state == ND_STATE_RECORDING) newdemo_record_player_score(points); #endif if (Game_mode & GM_MULTI) return; if (Players[Player_num].score/EXTRA_SHIP_SCORE != prev_score/EXTRA_SHIP_SCORE) { int snd; Players[Player_num].lives += Players[Player_num].score/EXTRA_SHIP_SCORE - prev_score/EXTRA_SHIP_SCORE; if ((snd=Powerup_info[POW_EXTRA_LIFE].hit_sound) > -1 ) digi_play_sample( snd, F1_0 ); } } void init_gauge_canvases() { Canv_LeftEnergyGauge = gr_create_canvas( LEFT_ENERGY_GAUGE_W, LEFT_ENERGY_GAUGE_H ); Canv_SBEnergyGauge = gr_create_canvas( SB_ENERGY_GAUGE_W, SB_ENERGY_GAUGE_H ); Canv_RightEnergyGauge = gr_create_canvas( RIGHT_ENERGY_GAUGE_W, RIGHT_ENERGY_GAUGE_H ); Canv_NumericalGauge = gr_create_canvas( NUMERICAL_GAUGE_W, NUMERICAL_GAUGE_H ); } void close_gauge_canvases() { gr_free_canvas( Canv_LeftEnergyGauge ); gr_free_canvas( Canv_SBEnergyGauge ); gr_free_canvas( Canv_RightEnergyGauge ); gr_free_canvas( Canv_NumericalGauge ); } void init_gauges() { //draw_gauges_on = 1; if ( ((Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP)) || ((Newdemo_state == ND_STATE_PLAYBACK) && (Newdemo_game_mode & GM_MULTI) && !(Newdemo_game_mode & GM_MULTI_COOP)) ) old_score = -99; else old_score = -1; old_energy = -1; old_shields = -1; old_laser = -1; old_flags = -1; old_cloak = -1; old_lives = -1; old_weapon[0] = old_weapon[1]= -1; old_ammo_count[0] = old_ammo_count[1] = -1; cloak_fade_state = 0; } void draw_energy_bar(int energy) { int not_energy; int x1, x2, y; // Draw left energy bar gr_set_current_canvas( Canv_LeftEnergyGauge ); PIGGY_PAGE_IN(Gauges[GAUGE_ENERGY_LEFT]); gr_ubitmapm( 0, 0, &GameBitmaps[Gauges[GAUGE_ENERGY_LEFT].index] ); gr_setcolor( 0 ); not_energy = 61 - (energy*61)/100; if (energy < 100) for (y=0; y<8; y++) { x1 = 7 - y; x2 = 7 - y + not_energy; if ( y>=0 && y<2 ) if (x2 > LEFT_ENERGY_GAUGE_W - 1) x2 = LEFT_ENERGY_GAUGE_W - 1; if ( y>=2 && y<6 ) if (x2 > LEFT_ENERGY_GAUGE_W - 2) x2 = LEFT_ENERGY_GAUGE_W - 2; if ( y>=6 ) if (x2 > LEFT_ENERGY_GAUGE_W - 3) x2 = LEFT_ENERGY_GAUGE_W - 3; if (x2 > x1) gr_uscanline( x1, x2, y ); } gr_set_current_canvas( get_current_game_screen() ); gr_ubitmapm( LEFT_ENERGY_GAUGE_X, LEFT_ENERGY_GAUGE_Y, &Canv_LeftEnergyGauge->cv_bitmap ); // Draw right energy bar gr_set_current_canvas( Canv_RightEnergyGauge ); PIGGY_PAGE_IN(Gauges[GAUGE_ENERGY_RIGHT]); gr_ubitmapm( 0, 0, &GameBitmaps[Gauges[GAUGE_ENERGY_RIGHT].index] ); if (energy < 100) for (y=0; y<8; y++) { x1 = RIGHT_ENERGY_GAUGE_W - 8 + y - not_energy; x2 = RIGHT_ENERGY_GAUGE_W - 8 + y; if ( y>=0 && y<2 ) if (x1 < 0) x1 = 0; if ( y>=2 && y<6 ) if (x1 < 1) x1 = 1; if ( y>=6 ) if (x1 < 2) x1 = 2; if (x2 > x1) gr_uscanline( x1, x2, y ); } gr_set_current_canvas( get_current_game_screen() ); gr_ubitmapm( RIGHT_ENERGY_GAUGE_X, RIGHT_ENERGY_GAUGE_Y, &Canv_RightEnergyGauge->cv_bitmap ); } void draw_shield_bar(int shield) { int bm_num = shield>=100?9:(shield / 10); PIGGY_PAGE_IN(Gauges[GAUGE_SHIELDS+9-bm_num] ); gr_ubitmapm( SHIELD_GAUGE_X, SHIELD_GAUGE_Y, &GameBitmaps[Gauges[GAUGE_SHIELDS+9-bm_num].index] ); } #define CLOAK_FADE_WAIT_TIME 0x400 void draw_player_ship(int cloak_state,int old_cloak_state,int x, int y) { static fix cloak_fade_timer=0; static int cloak_fade_value=GR_FADE_LEVELS-1; grs_bitmap *bm; if (Game_mode & GM_TEAM) { PIGGY_PAGE_IN(Gauges[GAUGE_SHIPS+get_team(Player_num)]); bm = &GameBitmaps[Gauges[GAUGE_SHIPS+get_team(Player_num)].index]; } else { PIGGY_PAGE_IN(Gauges[GAUGE_SHIPS+Player_num]); bm = &GameBitmaps[Gauges[GAUGE_SHIPS+Player_num].index]; } if (old_cloak_state==-1 && cloak_state) cloak_fade_value=0; if (!cloak_state) { cloak_fade_value=GR_FADE_LEVELS-1; cloak_fade_state = 0; } if (cloak_state==1 && old_cloak_state==0) cloak_fade_state = -1; //else if (cloak_state==0 && old_cloak_state==1) // cloak_fade_state = 1; if (cloak_state==old_cloak_state) //doing "about-to-uncloak" effect if (cloak_fade_state==0) cloak_fade_state = 2; if (cloak_fade_state) cloak_fade_timer -= FrameTime; while (cloak_fade_state && cloak_fade_timer < 0) { cloak_fade_timer += CLOAK_FADE_WAIT_TIME; cloak_fade_value += cloak_fade_state; if (cloak_fade_value >= GR_FADE_LEVELS-1) { cloak_fade_value = GR_FADE_LEVELS-1; if (cloak_fade_state == 2 && cloak_state) cloak_fade_state = -2; else cloak_fade_state = 0; } else if (cloak_fade_value <= 0) { cloak_fade_value = 0; if (cloak_fade_state == -2) cloak_fade_state = 2; else cloak_fade_state = 0; } } gr_set_current_canvas(&VR_render_buffer[0]); gr_ubitmap( x, y, bm); Gr_scanline_darkening_level = cloak_fade_value; gr_rect(x, y, x+bm->bm_w-1, y+bm->bm_h-1); Gr_scanline_darkening_level = GR_FADE_LEVELS; gr_set_current_canvas(get_current_game_screen()); gr_bm_ubitbltm( bm->bm_w, bm->bm_h, x, y, x, y, &VR_render_sub_buffer[0].cv_bitmap, &grd_curcanv->cv_bitmap); } #define INV_FRAME_TIME (f1_0/10) //how long for each frame void draw_numerical_display(int shield, int energy) { gr_set_current_canvas( Canv_NumericalGauge ); gr_set_curfont( GAME_FONT ); PIGGY_PAGE_IN(Gauges[GAUGE_NUMERICAL]); gr_ubitmap( 0, 0, &GameBitmaps[Gauges[GAUGE_NUMERICAL].index] ); gr_set_fontcolor(gr_getcolor(14,14,23),-1 ); gr_printf((shield>99)?3:((shield>9)?5:7),15,"%d",shield); gr_set_fontcolor(gr_getcolor(25,18,6),-1 ); gr_printf((energy>99)?3:((energy>9)?5:7),2,"%d",energy); gr_set_current_canvas( get_current_game_screen() ); gr_ubitmapm( NUMERICAL_GAUGE_X, NUMERICAL_GAUGE_Y, &Canv_NumericalGauge->cv_bitmap ); } void draw_keys() { gr_set_current_canvas( get_current_game_screen() ); if (Players[Player_num].flags & PLAYER_FLAGS_BLUE_KEY ) { PIGGY_PAGE_IN(Gauges[GAUGE_BLUE_KEY]); gr_ubitmapm( GAUGE_BLUE_KEY_X, GAUGE_BLUE_KEY_Y, &GameBitmaps[Gauges[GAUGE_BLUE_KEY].index] ); } else { PIGGY_PAGE_IN(Gauges[GAUGE_BLUE_KEY_OFF]); gr_ubitmapm( GAUGE_BLUE_KEY_X, GAUGE_BLUE_KEY_Y, &GameBitmaps[Gauges[GAUGE_BLUE_KEY_OFF].index] ); } if (Players[Player_num].flags & PLAYER_FLAGS_GOLD_KEY) { PIGGY_PAGE_IN(Gauges[GAUGE_GOLD_KEY]); gr_ubitmapm( GAUGE_GOLD_KEY_X, GAUGE_GOLD_KEY_Y, &GameBitmaps[Gauges[GAUGE_GOLD_KEY].index] ); } else { PIGGY_PAGE_IN(Gauges[GAUGE_GOLD_KEY_OFF]); gr_ubitmapm( GAUGE_GOLD_KEY_X, GAUGE_GOLD_KEY_Y, &GameBitmaps[Gauges[GAUGE_GOLD_KEY_OFF].index] ); } if (Players[Player_num].flags & PLAYER_FLAGS_RED_KEY) { PIGGY_PAGE_IN( Gauges[GAUGE_RED_KEY] ); gr_ubitmapm( GAUGE_RED_KEY_X, GAUGE_RED_KEY_Y, &GameBitmaps[Gauges[GAUGE_RED_KEY].index] ); } else { PIGGY_PAGE_IN(Gauges[GAUGE_RED_KEY_OFF]); gr_ubitmapm( GAUGE_RED_KEY_X, GAUGE_RED_KEY_Y, &GameBitmaps[Gauges[GAUGE_RED_KEY_OFF].index] ); } } draw_weapon_info_sub(int info_index,gauge_box *box,int pic_x,int pic_y,char *name,int text_x,int text_y) { grs_bitmap *bm; char *p; //clear the window gr_setcolor(BM_XRGB(0,0,0)); gr_rect(box->left,box->top,box->right,box->bot); bm=&GameBitmaps[Weapon_info[info_index].picture.index]; Assert(bm != NULL); PIGGY_PAGE_IN( Weapon_info[info_index].picture ); gr_ubitmapm(pic_x,pic_y,bm); gr_set_fontcolor(gr_getcolor(0,20,0),-1 ); if ((p=strchr(name,'\n'))!=NULL) { *p=0; gr_printf(text_x,text_y,name); gr_printf(text_x,text_y+grd_curcanv->cv_font->ft_h+1,p+1); *p='\n'; } else gr_printf(text_x,text_y,name); // For laser, show level and quadness if (info_index == 0) { char temp_str[7]; sprintf(temp_str, "%s: 0", TXT_LVL); temp_str[5] = Players[Player_num].laser_level+1 + '0'; gr_printf(text_x,text_y+8, temp_str); if (Players[Player_num].flags & PLAYER_FLAGS_QUAD_LASERS) { strcpy(temp_str, TXT_QUAD); gr_printf(text_x,text_y+16, temp_str); } } } draw_weapon_info(int weapon_type,int weapon_num) { #ifdef SHAREWARE if (Newdemo_state==ND_STATE_RECORDING ) newdemo_record_player_weapon(weapon_type, weapon_num); #endif if (weapon_type == 0) if (Cockpit_mode == CM_STATUS_BAR) draw_weapon_info_sub(Primary_weapon_to_weapon_info[weapon_num], &gauge_boxes[2], SB_PRIMARY_W_PIC_X,SB_PRIMARY_W_PIC_Y, PRIMARY_WEAPON_NAMES_SHORT(weapon_num), SB_PRIMARY_W_TEXT_X,SB_PRIMARY_W_TEXT_Y); else draw_weapon_info_sub(Primary_weapon_to_weapon_info[weapon_num], &gauge_boxes[0], PRIMARY_W_PIC_X,PRIMARY_W_PIC_Y, PRIMARY_WEAPON_NAMES_SHORT(weapon_num), PRIMARY_W_TEXT_X,PRIMARY_W_TEXT_Y); else if (Cockpit_mode == CM_STATUS_BAR) draw_weapon_info_sub(Secondary_weapon_to_weapon_info[weapon_num], &gauge_boxes[3], SB_SECONDARY_W_PIC_X,SB_SECONDARY_W_PIC_Y, SECONDARY_WEAPON_NAMES_SHORT(weapon_num), SB_SECONDARY_W_TEXT_X,SB_SECONDARY_W_TEXT_Y); else draw_weapon_info_sub(Secondary_weapon_to_weapon_info[weapon_num], &gauge_boxes[1], SECONDARY_W_PIC_X,SECONDARY_W_PIC_Y, SECONDARY_WEAPON_NAMES_SHORT(weapon_num), SECONDARY_W_TEXT_X,SECONDARY_W_TEXT_Y); } draw_ammo_info(int x,int y,int ammo_count,int primary) { int w; if (primary) w = (grd_curcanv->cv_font->ft_w*6)/2; else w = (grd_curcanv->cv_font->ft_w*5)/2; gr_setcolor(BM_XRGB(0,0,0)); gr_rect(x,y,x+w,y+grd_curcanv->cv_font->ft_h); gr_set_fontcolor(gr_getcolor(20,0,0),-1 ); gr_printf(x,y,"%03d",ammo_count); } draw_primary_ammo_info(int ammo_count) { if (Cockpit_mode == CM_STATUS_BAR) draw_ammo_info(SB_PRIMARY_AMMO_X,SB_PRIMARY_AMMO_Y,ammo_count,1); else draw_ammo_info(PRIMARY_AMMO_X,PRIMARY_AMMO_Y,ammo_count,1); } draw_secondary_ammo_info(int ammo_count) { if (Cockpit_mode == CM_STATUS_BAR) draw_ammo_info(SB_SECONDARY_AMMO_X,SB_SECONDARY_AMMO_Y,ammo_count,0); else draw_ammo_info(SECONDARY_AMMO_X,SECONDARY_AMMO_Y,ammo_count,0); } //returns true if drew picture int draw_weapon_box(int weapon_type,int weapon_num) { int drew_flag=0; gr_set_current_canvas(&VR_render_buffer[0]); gr_set_curfont( GAME_FONT ); if (weapon_num != old_weapon[weapon_type] && weapon_box_states[weapon_type] == WS_SET) { weapon_box_states[weapon_type] = WS_FADING_OUT; weapon_box_fade_values[weapon_type]=i2f(GR_FADE_LEVELS-1); } if (old_weapon[weapon_type] == -1) { draw_weapon_info(weapon_type,weapon_num); old_weapon[weapon_type] = weapon_num; old_ammo_count[weapon_type]=-1; drew_flag=1; weapon_box_states[weapon_type] = WS_SET; } if (weapon_box_states[weapon_type] == WS_FADING_OUT) { draw_weapon_info(weapon_type,old_weapon[weapon_type]); old_ammo_count[weapon_type]=-1; drew_flag=1; weapon_box_fade_values[weapon_type] -= FrameTime * FADE_SCALE; if (weapon_box_fade_values[weapon_type] <= 0) { weapon_box_states[weapon_type] = WS_FADING_IN; old_weapon[weapon_type] = weapon_num; weapon_box_fade_values[weapon_type] = 0; } } else if (weapon_box_states[weapon_type] == WS_FADING_IN) { if (weapon_num != old_weapon[weapon_type]) { weapon_box_states[weapon_type] = WS_FADING_OUT; } else { draw_weapon_info(weapon_type,weapon_num); old_ammo_count[weapon_type]=-1; drew_flag=1; weapon_box_fade_values[weapon_type] += FrameTime * FADE_SCALE; if (weapon_box_fade_values[weapon_type] >= i2f(GR_FADE_LEVELS-1)) weapon_box_states[weapon_type] = WS_SET; } } if (weapon_box_states[weapon_type] != WS_SET) { //fade gauge int fade_value = f2i(weapon_box_fade_values[weapon_type]); int boxofs = (Cockpit_mode==CM_STATUS_BAR)?2:0; Gr_scanline_darkening_level = fade_value; gr_rect(gauge_boxes[boxofs+weapon_type].left,gauge_boxes[boxofs+weapon_type].top,gauge_boxes[boxofs+weapon_type].right,gauge_boxes[boxofs+weapon_type].bot); Gr_scanline_darkening_level = GR_FADE_LEVELS; } gr_set_current_canvas(get_current_game_screen()); return drew_flag; } draw_weapon_boxes() { int boxofs = (Cockpit_mode==CM_STATUS_BAR)?2:0; int drew; drew = draw_weapon_box(0,Primary_weapon); if (drew) copy_gauge_box(&gauge_boxes[boxofs+0],&VR_render_buffer[0].cv_bitmap); if (weapon_box_states[0] == WS_SET) if (Players[Player_num].primary_ammo[Primary_weapon] != old_ammo_count[0]) { if (Primary_weapon == VULCAN_INDEX) { #ifndef SHAREWARE if (Newdemo_state == ND_STATE_RECORDING) newdemo_record_primary_ammo(old_ammo_count[0], Players[Player_num].primary_ammo[Primary_weapon]); #endif draw_primary_ammo_info(f2i(VULCAN_AMMO_SCALE * Players[Player_num].primary_ammo[Primary_weapon])); old_ammo_count[0] = Players[Player_num].primary_ammo[Primary_weapon]; } } if (!hostage_is_vclip_playing()) { drew = draw_weapon_box(1,Secondary_weapon); if (drew) copy_gauge_box(&gauge_boxes[boxofs+1],&VR_render_buffer[0].cv_bitmap); if (weapon_box_states[1] == WS_SET) if (Players[Player_num].secondary_ammo[Secondary_weapon] != old_ammo_count[1]) { #ifndef SHAREWARE if (Newdemo_state == ND_STATE_RECORDING) newdemo_record_secondary_ammo(old_ammo_count[1], Players[Player_num].secondary_ammo[Secondary_weapon]); #endif draw_secondary_ammo_info(Players[Player_num].secondary_ammo[Secondary_weapon]); old_ammo_count[1] = Players[Player_num].secondary_ammo[Secondary_weapon]; } } } sb_draw_energy_bar(energy) { int erase_height; gr_set_current_canvas( Canv_SBEnergyGauge ); PIGGY_PAGE_IN(Gauges[SB_GAUGE_ENERGY]); gr_ubitmapm( 0, 0, &GameBitmaps[Gauges[SB_GAUGE_ENERGY].index] ); erase_height = (100 - energy) * SB_ENERGY_GAUGE_H / 100; if (erase_height > 0) { gr_setcolor( 0 ); gr_rect(0,0,SB_ENERGY_GAUGE_W-1,erase_height-1); } gr_set_current_canvas( get_current_game_screen() ); gr_ubitmapm( SB_ENERGY_GAUGE_X, SB_ENERGY_GAUGE_Y, &Canv_SBEnergyGauge->cv_bitmap ); //draw numbers gr_set_fontcolor(gr_getcolor(25,18,6),-1 ); gr_printf((energy>99)?SB_ENERGY_NUM_X:((energy>9)?SB_ENERGY_NUM_X+2:SB_ENERGY_NUM_X+4),SB_ENERGY_NUM_Y,"%d",energy); } sb_draw_shield_num(int shield) { grs_bitmap *bm = &GameBitmaps[cockpit_bitmap[Cockpit_mode].index]; //draw numbers gr_set_curfont( GAME_FONT ); gr_set_fontcolor(gr_getcolor(14,14,23),-1 ); //erase old one PIGGY_PAGE_IN( cockpit_bitmap[Cockpit_mode] ); gr_setcolor(gr_gpixel(bm,SB_SHIELD_NUM_X,SB_SHIELD_NUM_Y-(VR_render_width-bm->bm_h))); gr_rect(SB_SHIELD_NUM_X,SB_SHIELD_NUM_Y,SB_SHIELD_NUM_X+13,SB_SHIELD_NUM_Y+GAME_FONT->ft_h); gr_printf((shield>99)?SB_SHIELD_NUM_X:((shield>9)?SB_SHIELD_NUM_X+2:SB_SHIELD_NUM_X+4),SB_SHIELD_NUM_Y,"%d",shield); } sb_draw_shield_bar(int shield) { int bm_num = shield>=100?9:(shield / 10); gr_set_current_canvas( get_current_game_screen() ); PIGGY_PAGE_IN( Gauges[GAUGE_SHIELDS+9-bm_num] ); gr_ubitmapm( SB_SHIELD_GAUGE_X, SB_SHIELD_GAUGE_Y, &GameBitmaps[Gauges[GAUGE_SHIELDS+9-bm_num].index] ); } sb_draw_keys() { grs_bitmap * bm; int flags = Players[Player_num].flags; gr_set_current_canvas( get_current_game_screen() ); bm = &GameBitmaps[Gauges[(flags&PLAYER_FLAGS_BLUE_KEY)?SB_GAUGE_BLUE_KEY:SB_GAUGE_BLUE_KEY_OFF].index]; PIGGY_PAGE_IN(Gauges[(flags&PLAYER_FLAGS_BLUE_KEY)?SB_GAUGE_BLUE_KEY:SB_GAUGE_BLUE_KEY_OFF]); gr_ubitmapm( SB_GAUGE_KEYS_X, SB_GAUGE_BLUE_KEY_Y, bm ); bm = &GameBitmaps[Gauges[(flags&PLAYER_FLAGS_GOLD_KEY)?SB_GAUGE_GOLD_KEY:SB_GAUGE_GOLD_KEY_OFF].index]; PIGGY_PAGE_IN(Gauges[(flags&PLAYER_FLAGS_GOLD_KEY)?SB_GAUGE_GOLD_KEY:SB_GAUGE_GOLD_KEY_OFF]); gr_ubitmapm( SB_GAUGE_KEYS_X, SB_GAUGE_GOLD_KEY_Y, bm ); bm = &GameBitmaps[Gauges[(flags&PLAYER_FLAGS_RED_KEY)?SB_GAUGE_RED_KEY:SB_GAUGE_RED_KEY_OFF].index]; PIGGY_PAGE_IN(Gauges[(flags&PLAYER_FLAGS_RED_KEY)?SB_GAUGE_RED_KEY:SB_GAUGE_RED_KEY_OFF]); gr_ubitmapm( SB_GAUGE_KEYS_X, SB_GAUGE_RED_KEY_Y, bm ); } // Draws invulnerable ship, or maybe the flashing ship, depending on invulnerability time left. void draw_invulnerable_ship() { static fix time=0; gr_set_current_canvas( get_current_game_screen() ); if (((Players[Player_num].invulnerable_time + INVULNERABLE_TIME_MAX - GameTime) > F1_0*4) || (GameTime & 0x8000)) { if (Cockpit_mode == CM_STATUS_BAR) { PIGGY_PAGE_IN(Gauges[GAUGE_INVULNERABLE+invulnerable_frame]); gr_ubitmapm( SB_SHIELD_GAUGE_X, SB_SHIELD_GAUGE_Y, &GameBitmaps[Gauges[GAUGE_INVULNERABLE+invulnerable_frame].index] ); } else { PIGGY_PAGE_IN(Gauges[GAUGE_INVULNERABLE+invulnerable_frame]); gr_ubitmapm( SHIELD_GAUGE_X, SHIELD_GAUGE_Y, &GameBitmaps[Gauges[GAUGE_INVULNERABLE+invulnerable_frame].index] ); } time += FrameTime; while (time > INV_FRAME_TIME) { time -= INV_FRAME_TIME; if (++invulnerable_frame == N_INVULNERABLE_FRAMES) invulnerable_frame=0; } } else if (Cockpit_mode == CM_STATUS_BAR) sb_draw_shield_bar(f2ir(Players[Player_num].shields)); else draw_shield_bar(f2ir(Players[Player_num].shields)); } #ifdef HOSTAGE_FACES draw_hostage_gauge() { int drew; gr_set_current_canvas(Canv_game_offscrn); drew = do_hostage_effects(); if (drew) { int boxofs = (Cockpit_mode==CM_STATUS_BAR)?2:0; gr_set_current_canvas(Canv_game); copy_gauge_box(&gauge_boxes[boxofs+1],&Canv_game_offscrn->cv_bitmap); old_weapon[1] = old_ammo_count[1] = -1; } } #endif extern int Missile_gun; extern int allowed_to_fire_laser(void); extern int allowed_to_fire_missile(void); rgb player_rgb[] = { {15,15,23}, {27,0,0}, {0,23,0}, {30,11,31}, {31,16,0}, {24,17,6}, {14,21,12}, {29,29,0}, }; //draw the reticle show_reticle(int force_big_one) { int x,y; int laser_ready,missile_ready,laser_ammo,missile_ammo; int cross_bm_num,primary_bm_num,secondary_bm_num; x = grd_curcanv->cv_w/2; y = grd_curcanv->cv_h/2; laser_ready = allowed_to_fire_laser(); missile_ready = allowed_to_fire_missile(); laser_ammo = player_has_weapon(Primary_weapon,0); missile_ammo = player_has_weapon(Secondary_weapon,1); primary_bm_num = (laser_ready && laser_ammo==HAS_ALL); secondary_bm_num = (missile_ready && missile_ammo==HAS_ALL); if (primary_bm_num && Primary_weapon==LASER_INDEX && (Players[Player_num].flags & PLAYER_FLAGS_QUAD_LASERS)) primary_bm_num++; if (Secondary_weapon!=CONCUSSION_INDEX && Secondary_weapon!=HOMING_INDEX) secondary_bm_num += 3; //now value is 0,1 or 3,4 else if (secondary_bm_num && !(Missile_gun&1)) secondary_bm_num++; cross_bm_num = ((primary_bm_num > 0) || (secondary_bm_num > 0)); Assert(primary_bm_num <= 2); Assert(secondary_bm_num <= 4); Assert(cross_bm_num <= 1); if (grd_curcanv->cv_bitmap.bm_w > 200 || force_big_one) { PIGGY_PAGE_IN(Gauges[RETICLE_CROSS + cross_bm_num]); gr_ubitmapm(x-4 ,y-2,&GameBitmaps[Gauges[RETICLE_CROSS + cross_bm_num].index]); PIGGY_PAGE_IN(Gauges[RETICLE_PRIMARY + primary_bm_num]); gr_ubitmapm(x-15,y+6,&GameBitmaps[Gauges[RETICLE_PRIMARY + primary_bm_num].index]); PIGGY_PAGE_IN(Gauges[RETICLE_SECONDARY + secondary_bm_num]); gr_ubitmapm(x-12,y+1,&GameBitmaps[Gauges[RETICLE_SECONDARY + secondary_bm_num].index]); } else { PIGGY_PAGE_IN(Gauges[SML_RETICLE_CROSS + cross_bm_num]); gr_ubitmapm(x-2,y-1,&GameBitmaps[Gauges[SML_RETICLE_CROSS + cross_bm_num].index]); PIGGY_PAGE_IN(Gauges[SML_RETICLE_PRIMARY + primary_bm_num]); gr_ubitmapm(x-8,y+2,&GameBitmaps[Gauges[SML_RETICLE_PRIMARY + primary_bm_num].index]); PIGGY_PAGE_IN(Gauges[SML_RETICLE_SECONDARY + secondary_bm_num]); gr_ubitmapm(x-6,y-2,&GameBitmaps[Gauges[SML_RETICLE_SECONDARY + secondary_bm_num].index]); } #ifndef SHAREWARE if ((Newdemo_state == ND_STATE_PLAYBACK) || (((Game_mode & GM_MULTI_COOP) || (Game_mode & GM_TEAM)) && Show_reticle_name)) { // Draw player callsign for player in sights fvi_query fq; vms_vector orient; int Hit_type; fvi_info Hit_data; fq.p0 = &ConsoleObject->pos; orient = ConsoleObject->orient.fvec; vm_vec_scale(&orient, F1_0*1024); vm_vec_add2(&orient, fq.p0); fq.p1 = &orient; fq.rad = 0; fq.thisobjnum = ConsoleObject - Objects; fq.flags = FQ_TRANSWALL | FQ_CHECK_OBJS; fq.startseg = ConsoleObject->segnum; fq.ignore_obj_list = NULL; Hit_type = find_vector_intersection(&fq, &Hit_data); if ((Hit_type == HIT_OBJECT) && (Objects[Hit_data.hit_object].type == OBJ_PLAYER)) { // Draw callsign on HUD char s[CALLSIGN_LEN+1]; int w, h, aw; int x1, y1; int pnum; int color_num; pnum = Objects[Hit_data.hit_object].id; if ((Game_mode & GM_TEAM) && (get_team(pnum) != get_team(Player_num)) && (Newdemo_state != ND_STATE_PLAYBACK)) return; if (Game_mode & GM_TEAM) color_num = get_team(pnum); else color_num = pnum; sprintf(s, "%s", Players[pnum].callsign); gr_get_string_size(s, &w, &h, &aw); gr_set_fontcolor(gr_getcolor(player_rgb[color_num].r,player_rgb[color_num].g,player_rgb[color_num].b),-1 ); x1 = x-(w/2); y1 = y+12; gr_string (x1, y1, s); // } } #ifndef NDEBUG else if ((Hit_type == HIT_OBJECT) && (Objects[Hit_data.hit_object].type == OBJ_ROBOT)) { char s[CALLSIGN_LEN+1]; int w, h, aw; int x1, y1; int color_num = 0; sprintf(s, "%d", Hit_data.hit_object); gr_get_string_size(s, &w, &h, &aw); gr_set_fontcolor(gr_getcolor(player_rgb[color_num].r,player_rgb[color_num].g,player_rgb[color_num].b),-1 ); x1 = x-(w/2); y1 = y+12; gr_string (x1, y1, s); } #endif } #endif } hud_show_kill_list() { int n_players,player_list[MAX_NUM_NET_PLAYERS]; int n_left,i,x0,x1,y,save_y,fth; if (Show_kill_list_timer > 0) { Show_kill_list_timer -= FrameTime; if (Show_kill_list_timer < 0) Show_kill_list = 0; } #ifdef SHAREWARE if (Game_mode & GM_MULTI_COOP) { Show_kill_list = 0; return; } #endif gr_set_curfont( GAME_FONT ); n_players = multi_get_kill_list(player_list); if (Show_kill_list == 2) n_players = 2; if (n_players <= 4) n_left = n_players; else n_left = (n_players+1)/2; //If font size changes, this code might not work right anymore Assert(GAME_FONT->ft_h==5 && GAME_FONT->ft_w==7); fth = GAME_FONT->ft_h; x0 = 1; x1 = 43; #ifndef SHAREWARE if (Game_mode & GM_MULTI_COOP) x1 = 31; #endif save_y = y = grd_curcanv->cv_h - n_left*(fth+1); if (Cockpit_mode == CM_FULL_COCKPIT) { save_y = y -= 6; #ifndef SHAREWARE if (Game_mode & GM_MULTI_COOP) x1 = 33; else #endif x1 = 43; } for (i=0;i<n_players;i++) { int player_num; char name[9]; int sw,sh,aw; if (i==n_left) { if (Cockpit_mode == CM_FULL_COCKPIT) x0 = grd_curcanv->cv_w - 53; else x0 = grd_curcanv->cv_w - 60; #ifndef SHAREWARE if (Game_mode & GM_MULTI_COOP) x1 = grd_curcanv->cv_w - 27; else #endif x1 = grd_curcanv->cv_w - 15; y = save_y; } if (Show_kill_list == 2) player_num = i; else player_num = player_list[i]; if (Show_kill_list == 1) { int color; if (Players[player_num].connected != 1) gr_set_fontcolor(gr_getcolor(12, 12, 12), -1); else if (Game_mode & GM_TEAM) { color = get_team(player_num); gr_set_fontcolor(gr_getcolor(player_rgb[color].r,player_rgb[color].g,player_rgb[color].b),-1 ); } else { color = player_num; gr_set_fontcolor(gr_getcolor(player_rgb[color].r,player_rgb[color].g,player_rgb[color].b),-1 ); } } else { gr_set_fontcolor(gr_getcolor(player_rgb[player_num].r,player_rgb[player_num].g,player_rgb[player_num].b),-1 ); } if (Show_kill_list == 2) strcpy(name, Netgame.team_name[i]); else strcpy(name,Players[player_num].callsign); gr_get_string_size(name,&sw,&sh,&aw); while (sw > (x1-x0-3)) { name[strlen(name)-1]=0; gr_get_string_size(name,&sw,&sh,&aw); } gr_printf(x0,y,"%s",name); if (Show_kill_list == 2) gr_printf(x1,y,"%3d",team_kills[i]); #ifndef SHAREWARE else if (Game_mode & GM_MULTI_COOP) gr_printf(x1,y,"%-6d",Players[player_num].score); #endif else gr_printf(x1,y,"%3d",Players[player_num].net_kills_total); y += fth+1; } } //draw all the things on the HUD void draw_hud() { // Show score so long as not in rearview if ( !Rear_view && Cockpit_mode!=CM_REAR_VIEW && Cockpit_mode!=CM_STATUS_BAR) { hud_show_score(); if (score_time) hud_show_score_added(); } // Show other stuff if not in rearview or letterbox. if (!Rear_view && Cockpit_mode!=CM_REAR_VIEW) { // && Cockpit_mode!=CM_LETTERBOX) { if (Cockpit_mode==CM_STATUS_BAR || Cockpit_mode==CM_FULL_SCREEN) hud_show_homing_warning(); if (Cockpit_mode==CM_FULL_SCREEN) { hud_show_energy(); hud_show_shield(); hud_show_weapons(); hud_show_keys(); hud_show_cloak_invuln(); if ( ( Newdemo_state==ND_STATE_RECORDING ) && ( Players[Player_num].flags != old_flags )) { newdemo_record_player_flags(old_flags, Players[Player_num].flags); old_flags = Players[Player_num].flags; } } #ifndef RELEASE if (!(Game_mode&GM_MULTI && Show_kill_list)) show_time(); #endif if (Cockpit_mode != CM_LETTERBOX && (!Use_player_head_angles)) show_reticle(0); HUD_render_message_frame(); if (Cockpit_mode!=CM_STATUS_BAR) hud_show_lives(); if (Game_mode&GM_MULTI && Show_kill_list) hud_show_kill_list(); } if (Rear_view && Cockpit_mode!=CM_REAR_VIEW) { HUD_render_message_frame(); gr_set_curfont( GAME_FONT ); gr_set_fontcolor(gr_getcolor(0,31,0),-1 ); gr_printf(0x8000,grd_curcanv->cv_h-10,TXT_REAR_VIEW); } } //print out some player statistics void render_gauges() { int energy = f2ir(Players[Player_num].energy); int shields = f2ir(Players[Player_num].shields); int cloak = ((Players[Player_num].flags&PLAYER_FLAGS_CLOAKED) != 0); Assert(Cockpit_mode==CM_FULL_COCKPIT || Cockpit_mode==CM_STATUS_BAR); #ifdef HOSTAGE_FACES draw_hostage_gauge(); #endif if (shields < 0 ) shields = 0; gr_set_current_canvas(get_current_game_screen()); gr_set_curfont( GAME_FONT ); if (Newdemo_state == ND_STATE_RECORDING) if (Players[Player_num].homing_object_dist >= 0) newdemo_record_homing_distance(Players[Player_num].homing_object_dist); if (Cockpit_mode == CM_FULL_COCKPIT) { if (energy != old_energy) { if (Newdemo_state==ND_STATE_RECORDING ) { #ifdef SHAREWARE newdemo_record_player_energy(energy); #else newdemo_record_player_energy(old_energy, energy); #endif } draw_energy_bar(energy); draw_numerical_display(shields, energy); old_energy = energy; } if (Players[Player_num].flags & PLAYER_FLAGS_INVULNERABLE) { draw_numerical_display(shields, energy); draw_invulnerable_ship(); old_shields = shields ^ 1; } else if (shields != old_shields) { // Draw the shield gauge if (Newdemo_state==ND_STATE_RECORDING ) { #ifdef SHAREWARE newdemo_record_player_shields(shields); #else newdemo_record_player_shields(old_shields, shields); #endif } draw_shield_bar(shields); draw_numerical_display(shields, energy); old_shields = shields; } if (Players[Player_num].flags != old_flags) { if (Newdemo_state==ND_STATE_RECORDING ) newdemo_record_player_flags(old_flags, Players[Player_num].flags); draw_keys(); old_flags = Players[Player_num].flags; } show_homing_warning(); } else if (Cockpit_mode == CM_STATUS_BAR) { if (energy != old_energy) { if (Newdemo_state==ND_STATE_RECORDING ) { #ifdef SHAREWARE newdemo_record_player_energy(energy); #else newdemo_record_player_energy(old_energy, energy); #endif } sb_draw_energy_bar(energy); old_energy = energy; } if (Players[Player_num].flags & PLAYER_FLAGS_INVULNERABLE) { draw_invulnerable_ship(); old_shields = shields ^ 1; sb_draw_shield_num(shields); } else if (shields != old_shields) { // Draw the shield gauge if (Newdemo_state==ND_STATE_RECORDING ) { #ifdef SHAREWARE newdemo_record_player_shields(shields); #else newdemo_record_player_shields(old_shields, shields); #endif } sb_draw_shield_bar(shields); old_shields = shields; sb_draw_shield_num(shields); } if (Players[Player_num].flags != old_flags) { if (Newdemo_state==ND_STATE_RECORDING ) newdemo_record_player_flags(old_flags, Players[Player_num].flags); sb_draw_keys(); old_flags = Players[Player_num].flags; } if ((Game_mode & GM_MULTI) && !(Game_mode & GM_MULTI_COOP)) { if (Players[Player_num].net_killed_total != old_lives) { sb_show_lives(); old_lives = Players[Player_num].net_killed_total; } } else { if (Players[Player_num].lives != old_lives) { sb_show_lives(); old_lives = Players[Player_num].lives; } } if ((Game_mode&GM_MULTI) && !(Game_mode & GM_MULTI_COOP)) { if (Players[Player_num].net_kills_total != old_score) { sb_show_score(); old_score = Players[Player_num].net_kills_total; } } else { if (Players[Player_num].score != old_score) { sb_show_score(); old_score = Players[Player_num].score; } if (score_time) sb_show_score_added(); } } if (cloak != old_cloak || cloak_fade_state || (cloak && GameTime>Players[Player_num].cloak_time+CLOAK_TIME_MAX-i2f(3))) { if (Cockpit_mode == CM_FULL_COCKPIT) draw_player_ship(cloak,old_cloak,SHIP_GAUGE_X,SHIP_GAUGE_Y); else draw_player_ship(cloak,old_cloak,SB_SHIP_GAUGE_X,SB_SHIP_GAUGE_Y); old_cloak=cloak; } draw_weapon_boxes(); } // --------------------------------------------------------------------------------------------------------- // Call when picked up a laser powerup. // If laser is active, set old_weapon[0] to -1 to force redraw. void update_laser_weapon_info(void) { if (old_weapon[0] == 0) old_weapon[0] = -1; }
27.472111
255
0.713685
0afa48e2e4699971d6e4af57eaaf2b90dfee3019
2,961
cs
C#
ExchangeRatePredictor/Program.cs
duytech/ExchangeRatePredictor
68e4397acd2a511cfd1cf5a727891b116616aef8
[ "MIT" ]
null
null
null
ExchangeRatePredictor/Program.cs
duytech/ExchangeRatePredictor
68e4397acd2a511cfd1cf5a727891b116616aef8
[ "MIT" ]
null
null
null
ExchangeRatePredictor/Program.cs
duytech/ExchangeRatePredictor
68e4397acd2a511cfd1cf5a727891b116616aef8
[ "MIT" ]
null
null
null
using ExchangeRatePredictor.Foundation; using ExchangeRatePredictor.Foundation.Application; using ExchangeRatePredictor.Foundation.Common; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Serilog; using System; using System.IO; namespace ExchangeRatePredictor { public class Program { public static int Main(string[] args) { ILogger<Program> logger = null; try { IConfiguration configuration = BuildConfiguration(); IServiceProvider container = ConfigureServices(configuration); ConfigureLogger(configuration); logger = container.GetService<ILoggerFactory>().CreateLogger<Program>(); IApplication app = container.GetService<IApplication>(); string result = app.Process(args); logger.LogInformation(result); return 1; } catch (Exception ex) { try { var messages = ex.GetAllMessages(); logger.LogError(messages); logger.LogInformation("Please refer to the log file for more information"); logger.LogDebug(ex, "Something went wrong."); } catch (Exception e) { Console.WriteLine(e.ToString()); Console.ReadLine(); } return 0; } } private static IConfiguration BuildConfiguration() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true); return builder.Build(); } private static IServiceProvider ConfigureServices(IConfiguration configuration) { var serviceCollection = new ServiceCollection(); serviceCollection.AddLogging(config => config.AddSerilog()); serviceCollection.AddTransient<IOpenExchangeRateClient, OpenExchangeRateClient>(); serviceCollection.AddSingleton<IConfiguration>(configuration); serviceCollection.AddTransient<IExchangeRateDataReader, ExchangeRateDataReader>(); serviceCollection.AddTransient<IPredictor, Predictor>(); serviceCollection.AddTransient<IApplication, CmdApplication>(); return serviceCollection.BuildServiceProvider(); } private static void ConfigureLogger(IConfiguration configuration) { var serilogger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .CreateLogger(); Log.Logger = serilogger; } } }
34.034483
95
0.594056
8d809cad87cbf06a604cd358ae192ad92f079719
1,977
js
JavaScript
gulpfile.js
juliangrosshauser/juliangrosshauser.com
bddfc3c0987f3333ff7bf22de07f7691d51cde54
[ "MIT" ]
null
null
null
gulpfile.js
juliangrosshauser/juliangrosshauser.com
bddfc3c0987f3333ff7bf22de07f7691d51cde54
[ "MIT" ]
null
null
null
gulpfile.js
juliangrosshauser/juliangrosshauser.com
bddfc3c0987f3333ff7bf22de07f7691d51cde54
[ "MIT" ]
null
null
null
var browserSync = require('browser-sync'), del = require('del'), gulp = require('gulp'), autoprefixer = require('gulp-autoprefixer'), concat = require('gulp-concat'), htmlmin = require('gulp-htmlmin'), imagemin = require('gulp-imagemin'), minify = require('gulp-minify-css'), sass = require('gulp-sass'), uglify = require('gulp-uglify'); gulp.task('html', function() { return gulp.src('index.html') .pipe(htmlmin({ collapseWhitespace: true })) .pipe(gulp.dest('dist')); }); gulp.task('sass', function() { return gulp.src('sass/style.scss') .pipe(sass({ style: "expanded" })) .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 9', 'opera 12.1', 'ios 6', 'android 4')) .pipe(concat('style.css')) .pipe(gulp.dest('build/css')) .pipe(browserSync.reload({ stream: true })); }); gulp.task('css', ['sass'], function() { return gulp.src([ 'css/normalize.css', 'css/skeleton.css', 'build/css/style.css' ]) .pipe(concat('style.min.css')) .pipe(minify()) .pipe(gulp.dest('dist/css')); }); gulp.task('js', function() { return gulp.src([ 'js/typekit.js', 'js/analytics.js' ]) .pipe(concat('script.min.js')) .pipe(uglify({ preserveComments: 'none', outSourceMap: false })) .pipe(gulp.dest('dist/js')); }); gulp.task('img', function() { return gulp.src('images/*') .pipe(imagemin({ optimizationLevel: 7, progressive: true, interlaced: true })) .pipe(gulp.dest('dist/images')); }); gulp.task('clean', function(cb) { del(['dist', 'build'], cb); }); gulp.task('default', ['clean'], function() { gulp.start('html', 'css', 'js', 'img'); }); gulp.task('dev', ['default'], function() { browserSync({ server: { baseDir: './' }, notify: false }); gulp.watch('index.html', [browserSync.reload]); gulp.watch('sass/**/*.scss', ['sass']); gulp.watch('js/**/*.js', ['js']); });
26.716216
97
0.572585
1ed67b4fca4431563980d6569d776a2ab9fd82bb
9,509
dart
Dart
lib/components/intro_screen/gf_intro_screen.dart
ionicfirebaseapp/getflutter
de9e93bc6de80adaeefe0587df15ed721afd8bc9
[ "MIT" ]
1,452
2019-12-20T07:29:37.000Z
2020-05-05T12:39:23.000Z
lib/components/intro_screen/gf_intro_screen.dart
ionicfirebaseapp/getflutter
de9e93bc6de80adaeefe0587df15ed721afd8bc9
[ "MIT" ]
32
2020-01-20T06:35:48.000Z
2020-05-04T22:58:17.000Z
lib/components/intro_screen/gf_intro_screen.dart
ionicfirebaseapp/getflutter
de9e93bc6de80adaeefe0587df15ed721afd8bc9
[ "MIT" ]
190
2019-12-20T11:09:33.000Z
2020-05-05T02:24:51.000Z
import 'package:flutter/material.dart'; import 'package:getwidget/getwidget.dart'; class GFIntroScreen extends StatefulWidget { /// GF Intro Screen is virtual unique interactive Slider that helps users get started with an app. /// It has many features that helps to build custom-made introduction screen sliders. /// Presents informative screens to users with various possibilities in customization. const GFIntroScreen({ Key? key, required this.pageController, required this.currentIndex, required this.pageCount, required this.slides, this.color, this.width, this.height, this.borderRadius, this.border, this.introScreenBottomNavigationBar, this.showIntroScreenBottomNavigationBar = true, this.child, this.navigationBarColor = GFColors.SUCCESS, this.navigationBarHeight = 50, this.navigationBarShape, this.navigationBarWidth, this.navigationBarPadding = const EdgeInsets.all(8), this.navigationBarMargin = const EdgeInsets.all(8), this.showDivider = true, this.dividerColor = Colors.white, this.dividerHeight = 1, this.dividerThickness = 2, this.dotShape, this.inactiveColor = GFColors.LIGHT, this.activeColor = GFColors.PRIMARY, this.dotHeight = 12, this.dotWidth = 12, this.dotMargin = const EdgeInsets.symmetric(horizontal: 2), this.backButton, this.forwardButton, this.doneButton, this.skipButton, this.onDoneTap, this.onForwardButtonTap, this.onBackButtonTap, this.onSkipTap, this.forwardButtonText = 'NEXT', this.backButtonText = 'BACK', this.doneButtonText = 'GO', this.skipButtonText = 'SKIP', this.skipButtonTextStyle = const TextStyle( color: Colors.black, fontSize: 16, ), this.doneButtonTextStyle = const TextStyle( color: Colors.black, fontSize: 16, ), this.backButtonTextStyle = const TextStyle( color: Colors.black, fontSize: 16, ), this.forwardButtonTextStyle = const TextStyle( color: Colors.black, fontSize: 16, ), this.showButton = true, this.showPagination = true, }) : super(key: key); /// defines the list of slides final List<Widget> slides; /// allows one to control [GFIntroScreen] slides final PageController pageController; /// defines background color of the [GFIntroScreen] slides final Color? color; /// defines [GFIntroScreen] slides height final double? height; /// defines [GFIntroScreen] slides width final double? width; /// defines [GFIntroScreen] border radius to defines slides shape final BorderRadius? borderRadius; /// defines [GFIntroScreen] slides border final Border? border; /// defines [GFIntroScreen]'s bottom navigation bar final GFIntroScreenBottomNavigationBar? introScreenBottomNavigationBar; /// on true state, displays [GFIntroScreenBottomNavigationBar], defaults to false final bool showIntroScreenBottomNavigationBar; /// defines the currentIndex of [GFIntroScreen] slides, default value is 0 final int currentIndex; /// defines the length of [GFIntroScreen] slides, default value is 0 final int pageCount; /// defines [GFIntroScreenBottomNavigationBar]'s child, it takes any widget final Widget? child; /// defines [GFIntroScreenBottomNavigationBar] height final double navigationBarHeight; /// defines [GFIntroScreenBottomNavigationBar] width final double? navigationBarWidth; /// defines [GFIntroScreenBottomNavigationBar] padding final EdgeInsets navigationBarPadding; /// defines [GFIntroScreenBottomNavigationBar] margin final EdgeInsets navigationBarMargin; /// defines [GFIntroScreenBottomNavigationBar] color final Color navigationBarColor; /// defines the shape of [GFIntroScreenBottomNavigationBar] final ShapeBorder? navigationBarShape; /// Called when the forward button is tapped final VoidCallback? onForwardButtonTap; /// Called when the back button is tapped final VoidCallback? onBackButtonTap; /// Called when the done button is tapped final VoidCallback? onDoneTap; /// Called when the skip button is tapped final VoidCallback? onSkipTap; /// takes any Widget to define the backButton widget, final Widget? backButton; /// takes any Widget to define the forwardButton widget final Widget? forwardButton; /// takes any Widget to define the doneButton widget final Widget? doneButton; /// takes any Widget to define the skipButton widget final Widget? skipButton; /// takes String to define backButton text final String backButtonText; /// takes String to define forwardButton text final String forwardButtonText; /// takes String to define doneButton text final String doneButtonText; /// takes String to define skipButton text final String skipButtonText; /// defines the skipButton textStyle final TextStyle skipButtonTextStyle; /// defines the doneButton textStyle final TextStyle doneButtonTextStyle; /// defines the backButton textStyle final TextStyle backButtonTextStyle; /// defines the forwardButton textStyle final TextStyle forwardButtonTextStyle; /// on true state, displays [Divider], defaults to true final bool showDivider; /// on true state, displays buttons, defaults to true final bool showButton; /// on true state, displays pagination, defaults to true final bool showPagination; /// defines divider height final double dividerHeight; /// defines divider thickness final double dividerThickness; /// defines divider color final Color dividerColor; /// defines pagination shape final ShapeBorder? dotShape; /// defines pagination inactive color final Color inactiveColor; /// defines pagination active color final Color activeColor; /// defines pagination height final double dotHeight; /// defines pagination width final double dotWidth; /// defines pagination in between space final EdgeInsets dotMargin; @override _GFIntroScreenState createState() => _GFIntroScreenState(); } class _GFIntroScreenState extends State<GFIntroScreen> { @override Widget build(BuildContext context) => Center( child: Container( width: widget.width, height: widget.height, decoration: BoxDecoration( borderRadius: widget.borderRadius ?? BorderRadius.circular(0), border: widget.border ?? Border.all(width: 0), color: widget.color, ), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Expanded( child: PageView( controller: widget.pageController, children: widget.slides, ), ), widget.showIntroScreenBottomNavigationBar ? widget.introScreenBottomNavigationBar ?? GFIntroScreenBottomNavigationBar( pageController: widget.pageController, pageCount: widget.slides.length, currentIndex: widget.currentIndex, child: widget.child, navigationBarColor: widget.navigationBarColor, navigationBarHeight: widget.navigationBarHeight, navigationBarShape: widget.navigationBarShape, navigationBarWidth: widget.navigationBarWidth, navigationBarPadding: widget.navigationBarPadding, navigationBarMargin: widget.navigationBarMargin, showDivider: widget.showDivider, dividerColor: widget.dividerColor, dividerHeight: widget.dividerHeight, dividerThickness: widget.dividerThickness, dotShape: widget.dotShape, inactiveColor: widget.inactiveColor, activeColor: widget.activeColor, dotHeight: widget.dotHeight, dotWidth: widget.dotWidth, dotMargin: widget.dotMargin, backButton: widget.backButton, forwardButton: widget.forwardButton, doneButton: widget.doneButton, skipButton: widget.skipButton, onDoneTap: widget.onDoneTap, onForwardButtonTap: widget.onForwardButtonTap, onBackButtonTap: widget.onBackButtonTap, onSkipTap: widget.onSkipTap, forwardButtonText: widget.forwardButtonText, backButtonText: widget.backButtonText, doneButtonText: widget.doneButtonText, skipButtonText: widget.skipButtonText, skipButtonTextStyle: widget.skipButtonTextStyle, doneButtonTextStyle: widget.doneButtonTextStyle, backButtonTextStyle: widget.backButtonTextStyle, forwardButtonTextStyle: widget.forwardButtonTextStyle, showButton: widget.showButton, showPagination: widget.showPagination, ) : Container(), ], ), ), ); }
33.839858
100
0.663266
2c9a3bf6b9e629d54a1ec7e85b97bc1415ee0361
6,278
py
Python
musx/paint.py
ricktaube/musx
5fb116b1a1ade9ef42a9a3c8311c604795e0af6a
[ "BSD-3-Clause" ]
9
2021-06-03T21:36:53.000Z
2021-06-13T01:53:17.000Z
musx/paint.py
musx-admin/musx
5fb116b1a1ade9ef42a9a3c8311c604795e0af6a
[ "BSD-3-Clause" ]
2
2021-06-03T18:38:57.000Z
2021-06-13T10:46:28.000Z
musx/paint.py
musx-admin/musx
5fb116b1a1ade9ef42a9a3c8311c604795e0af6a
[ "BSD-3-Clause" ]
1
2022-02-12T23:04:27.000Z
2022-02-12T23:04:27.000Z
############################################################################### """ The paint.py module provides two high-level composers that can produce a wide variety of interesting textures and music. The `brush()` composer outputs Notes in sequential order, similar to how a paint brush makes lines on a canvas. In contrast, the `spray()` composer generates Notes by applying random selection to its input parameters. For examples of using paint.py see gamelan.py, blues.py and messiaen.py in the demos directory. """ from musx import Note, cycle, choose def brush(score, *, length=None, end=None, rhythm=.5, duration=None, pitch=60, amplitude=.5, instrument=0, microdivs=1): """ Outputs Notes in sequential order, automatically looping parameter list values until the algorithm stops. Parameters ---------- score : Score The Notes that are generated will be added to this score. length : number The number of MIDI events to generate. Either length or end must be specified. end : number An end time after which no more events will be generated. Either end or length must be specified. rhythm : number | list A rhythm or list of rhythms that specify the amount of time to wait between notes. Negative rhythm values are interpreted as musical rests, i.e. events are not output but time advances. The default value is 0.5. duration : number | list A duration or list of durations that specify the amount of time each MIDI event lasts. The default value is the current rhythm. pitch : number | list A MIDI key number or list of key numbers to play. The list can contain sublists of key numbers; in this case each sublist is treated as a chord (the key numbers in the sublist are performed simultaneously.) amplitude : number | list A value or list of values between 0.0 and 1.0 for determining the loudness of the MIDI events. instrument : number | list A MIDI channel number 0 to 15, or a list of channel numbers. Channel value 9 will send events to the synthesizer's drum map for triggering various percussion sounds. tuning : int A value 1 to 16 setting the divisions per semitone used for microtonal quantization of floating point keynums. See Note, Seq and the micro.py demo file for more information. """ # user must specify either length or end parameter counter = 0 if length: if end: raise TypeError("specify either length or end, not both.") stopitr = length thisitr = (lambda: counter) else: if not end: raise TypeError("specify either length or end.") stopitr = end thisitr = (lambda: score.elapsed) # convert all values into cycles cyc = (lambda x: cycle(x if type(x) is list else [x])) rhy = cyc(rhythm) dur = cyc(duration) key = cyc(pitch) amp = cyc(amplitude) chan = cyc(instrument) while (thisitr() < stopitr): t = score.now #print("counter=", counter, "now=", t) r = next(rhy) d = next(dur) k = next(key) a = next(amp) c = next(chan) if r > 0: if not d: d = r if type(k) is list: for j in k: m = Note(time=t, duration=d, pitch=j, amplitude=a, instrument=c) score.add(m) else: m = Note(time=t, duration=d, pitch=k, amplitude=a, instrument=c) score.add(m) counter += 1 yield abs(r) def spray(score, *, length=None, end=None, rhythm=.5, duration=None, pitch= 60, band=0, amplitude=.5, instrument=0): """ Generates Notes using discrete random selection. Most parameters allow lists of values to be specified, in which case elements are randomly selected from the lists every time an event is output. Parameters ---------- Parameters are the same as brush() except for these changes or additions: pitch : number | list A MIDI key number or list of key numbers to play. If a list is specified a key number is randomly selected from the list for each midi event. band : number | list A number is treated as a half-step range on either side of the current key choice from which the next key number will be chosen. If a list of intervals is specified then randomly selected intervals are added added to the current key number to determine the key number played. The list can also contain sublists of intervals, in which case each sublist is treated as a chord, i.e. the intervals in the sublist are added to the current key and performed simultaneously. """ # user must specify either length or end parameter counter = 0 if length: if end: raise TypeError("specify either leng or end, not both.") stopitr = length thisitr = (lambda: counter) else: if not end: raise TypeError("specify either length or end.") stopitr = end thisitr = (lambda: score.elapsed) # convert each param into a chooser pattern. ran = (lambda x: choose(x if type(x) is list else [x])) rhy = ran(rhythm) dur = ran(duration) key = ran(pitch) amp = ran(amplitude) chan = ran(instrument) band = choose( [i for i in range(-band, band+1)] if type(band) is int else band ) while (thisitr() < stopitr): t = score.now #print("counter=", counter, "now=", t) r = next(rhy) d = next(dur) k = next(key) a = next(amp) c = next(chan) b = next(band) if type(b) is list: k = [k+i for i in b] else: k = k + b #print("pitch=", k, end=" ") if r > 0: if not d: d = r if type(k) is list: for j in k: m = Note(time=t, duration=d, pitch=j, amplitude=a, instrument=c) score.add(m) else: m = Note(time=t, duration=d, pitch=k, amplitude=a, instrument=c) score.add(m) counter += 1 yield abs(r)
39.2375
120
0.609111
0ad937441526c8be291e1bef8e5e304f2c2b9437
4,321
cs
C#
Hemlock/UtilityCollections.cs
Jorch72/Hemlock
2a4eb295ee390d90b04ad58d97d0819ba46e167f
[ "MIT" ]
null
null
null
Hemlock/UtilityCollections.cs
Jorch72/Hemlock
2a4eb295ee390d90b04ad58d97d0819ba46e167f
[ "MIT" ]
null
null
null
Hemlock/UtilityCollections.cs
Jorch72/Hemlock
2a4eb295ee390d90b04ad58d97d0819ba46e167f
[ "MIT" ]
null
null
null
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace UtilityCollections { public class DefaultHashSet<T> : HashSet<T> { public bool this[T t] { get { return Contains(t); } set { if(value) Add(t); else Remove(t); } } public DefaultHashSet() { } public DefaultHashSet(IEqualityComparer<T> comparer) : base(comparer) { } public DefaultHashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer = null) : base(collection, comparer) { } } public class DefaultValueDictionary<TKey, TValue> : Dictionary<TKey, TValue> { new public TValue this[TKey key] { get { TValue v; TryGetValue(key, out v); //TryGetValue sets its out parameter to default if not found. return v; } set { base[key] = value; } } public DefaultValueDictionary() { } public DefaultValueDictionary(IEqualityComparer<TKey> comparer) : base(comparer) { } public DefaultValueDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer = null) : base(dictionary, comparer) { } } public class MultiValueDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, IEnumerable<TValue>>> { private Dictionary<TKey, ICollection<TValue>> d; private readonly Func<ICollection<TValue>> createCollection; public MultiValueDictionary() { d = new Dictionary<TKey, ICollection<TValue>>(); createCollection = () => new List<TValue>(); } public MultiValueDictionary(IEqualityComparer<TKey> comparer) { d = new Dictionary<TKey, ICollection<TValue>>(comparer); createCollection = () => new List<TValue>(); } private MultiValueDictionary(Func<ICollection<TValue>> createCollection, IEqualityComparer<TKey> comparer = null) { d = new Dictionary<TKey, ICollection<TValue>>(comparer); this.createCollection = createCollection; } public static MultiValueDictionary<TKey, TValue> Create<TCollection>() where TCollection : ICollection<TValue>, new() { return new MultiValueDictionary<TKey, TValue>(() => new TCollection()); } public static MultiValueDictionary<TKey, TValue> Create<TCollection>(IEqualityComparer<TKey> comparer) where TCollection : ICollection<TValue>, new() { return new MultiValueDictionary<TKey, TValue>(() => new TCollection(), comparer); } IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); //todo: xml note that empty collections can be returned? public IEnumerator<KeyValuePair<TKey, IEnumerable<TValue>>> GetEnumerator() { foreach(var pair in d) yield return new KeyValuePair<TKey, IEnumerable<TValue>>(pair.Key, pair.Value); } public IEnumerable<KeyValuePair<TKey, TValue>> GetAllKeyValuePairs() { foreach(var pair in d) { foreach(var v in pair.Value) { yield return new KeyValuePair<TKey, TValue>(pair.Key, v); } } } public IEnumerable<TKey> GetAllKeys() => d.Keys; public IEnumerable<TValue> GetAllValues() { foreach(var collection in d.Values) { foreach(var v in collection) { yield return v; } } } public IEnumerable<TValue> this[TKey key] { get { if(d.ContainsKey(key)) return d[key]; else return Enumerable.Empty<TValue>(); } //todo: xml: This one replaces the entire contents of this key. set { if(value == null) { d.Remove(key); } else { ICollection<TValue> coll = createCollection(); foreach(TValue v in value) { coll.Add(v); } d[key] = coll; } } } public void Add(TKey key, TValue value) { if(!d.ContainsKey(key)) d.Add(key, createCollection()); d[key].Add(value); } public bool Remove(TKey key, TValue value) { if(d.ContainsKey(key)) return d[key].Remove(value); else return false; } public void Clear() { d.Clear(); } public void Clear(TKey key) { d.Remove(key); } public bool Contains(TKey key, TValue value) => d.ContainsKey(key) && d[key].Contains(value); public bool Contains(TValue value) { foreach(var list in d.Values) { if(list.Contains(value)) return true; } return false; } public bool AddUnique(TKey key, TValue value) { if(Contains(key, value)) return false; if(!d.ContainsKey(key)) d.Add(key, createCollection()); d[key].Add(value); return true; } public bool AnyValues(TKey key) => d.ContainsKey(key) && d[key].Any(); } }
34.846774
121
0.691738
da8fc0be0ac106b7cc8dcedf2c8c7594730da123
1,239
php
PHP
src/messages/Document.php
Code-Bureau/irstagenda-php-client
47ba76cbd39bd6c444ff64550c4ffa3ddbab9bc9
[ "MIT" ]
null
null
null
src/messages/Document.php
Code-Bureau/irstagenda-php-client
47ba76cbd39bd6c444ff64550c4ffa3ddbab9bc9
[ "MIT" ]
null
null
null
src/messages/Document.php
Code-Bureau/irstagenda-php-client
47ba76cbd39bd6c444ff64550c4ffa3ddbab9bc9
[ "MIT" ]
null
null
null
<?php namespace CodeBureau\FirstAgendaApi\Messages; /** * Class Document * @package CodeBureau\FirstAgendaApi\Messages */ class Document { private $uuid; private $title; private $order; /** * Document constructor. */ public function __construct() { $this->uuid = null; $this->title = null; $this->order = 0; } /** * @return null */ public function getUuid() { return $this->uuid; } /** * @param null $uuid * @return Document */ public function setUuid($uuid): Document { $this->uuid = $uuid; return $this; } /** * @return null */ public function getTitle() { return $this->title; } /** * @param null $title * @return Document */ public function setTitle($title): Document { $this->title = $title; return $this; } /** * @return null */ public function getOrder() { return $this->order; } /** * @param int $order * @return Document */ public function setOrder(int $order): Document { $this->order = $order; return $this; } }
15.884615
50
0.500404
df9268bedee9e49bc43a4100423d018fd9530326
397
cs
C#
Plugins/_CYM/UI/Utils/Misc/UIStatsAdd.cs
chengyimingvb/CYMUni
b1ba58bdfdd3a6d9bfe7ebbd971f8e3cc80312f2
[ "MIT" ]
1
2021-04-26T10:26:24.000Z
2021-04-26T10:26:24.000Z
Plugins/_CYM/UI/Utils/Misc/UIStatsAdd.cs
chengyimingvb/CYMUni
b1ba58bdfdd3a6d9bfe7ebbd971f8e3cc80312f2
[ "MIT" ]
null
null
null
Plugins/_CYM/UI/Utils/Misc/UIStatsAdd.cs
chengyimingvb/CYMUni
b1ba58bdfdd3a6d9bfe7ebbd971f8e3cc80312f2
[ "MIT" ]
1
2021-05-24T13:40:42.000Z
2021-05-24T13:40:42.000Z
using UnityEngine; using UnityEngine.UI; namespace CYM.UI { public class UIStatsAdd : MonoBehaviour { [SerializeField] private UnityEngine.UI.Text m_ValueText; public void OnButtonPress() { if (this.m_ValueText == null) return; this.m_ValueText.text = (int.Parse(this.m_ValueText.text) + 1).ToString(); } } }
19.85
86
0.594458
a3c8f3a4820679be4c380ab4d27f7a207ab564c8
4,319
htm
HTML
themes/casa/partials/site/scripts.htm
pukcab/project
011e5e1e1e7d02081593ed5e29d8832b839bc25b
[ "MIT" ]
null
null
null
themes/casa/partials/site/scripts.htm
pukcab/project
011e5e1e1e7d02081593ed5e29d8832b839bc25b
[ "MIT" ]
null
null
null
themes/casa/partials/site/scripts.htm
pukcab/project
011e5e1e1e7d02081593ed5e29d8832b839bc25b
[ "MIT" ]
null
null
null
<div id="custom_notifications" class="custom-notifications dsp_none"> <ul class="list-unstyled notifications clearfix" data-tabbed_notifications="notif-group"> </ul> <div class="clearfix"></div> <div id="notif-group" class="tabbed_notifications"></div> </div> <!-- jQuery --> <script src="{{'assets/vendors/jquery/dist/jquery.min.js' | theme }}"</script> <!-- Bootstrap --> <script src="{{'assets/vendors/bootstrap/dist/js/bootstrap.min.js' | theme }}"</script> <!-- FastClick --> <script src="{{'assets/vendors/fastclick/lib/fastclick.js' | theme }}"</script> <!-- NProgress --> <script src="{{'assets/vendors/nprogress/nprogress.js' | theme }}"</script> <!-- bootstrap-progressbar --> <script src="{{'assets/vendors/bootstrap-progressbar/bootstrap-progressbar.min.js' | theme }}"</script> <!-- iCheck --> <script src="{{'assets/vendors/iCheck/icheck.min.js' | theme }}"</script> <!-- PNotify --> <script src="{{'assets/vendors/pnotify/dist/pnotify.js' | theme }}"</script> <script src="{{'assets/vendors/pnotify/dist/pnotify.buttons.js' | theme }}"</script> <script src="{{'assets/vendors/pnotify/dist/pnotify.nonblock.js' | theme }}"</script> <!-- Custom Theme Scripts --> <script src="{{'assets/build/js/custom.min.js' | theme }}"></script> <!-- PNotify --> <script> $(document).ready(function() { new PNotify({ title: "PNotify", type: "info", text: "Welcome. Try hovering over me. You can click things behind me, because I'm non-blocking.", nonblock: { nonblock: true }, addclass: 'dark', styling: 'bootstrap3', hide: false, before_close: function(PNotify) { PNotify.update({ title: PNotify.options.title + " - Enjoy your Stay", before_close: null }); PNotify.queueRemove(); return false; } }); }); </script> <!-- /PNotify --> <!-- Custom Notification --> <script> $(document).ready(function() { var cnt = 10; TabbedNotification = function(options) { var message = "<div id='ntf" + cnt + "' class='text alert-" + options.type + "' style='display:none'><h2><i class='fa fa-bell'></i> " + options.title + "</h2><div class='close'><a href='javascript:;' class='notification_close'><i class='fa fa-close'></i></a></div><p>" + options.text + "</p></div>"; if (!document.getElementById('custom_notifications')) { alert('doesnt exists'); } else { $('#custom_notifications ul.notifications').append("<li><a id='ntlink" + cnt + "' class='alert-" + options.type + "' href='#ntf" + cnt + "'><i class='fa fa-bell animated shake'></i></a></li>"); $('#custom_notifications #notif-group').append(message); cnt++; CustomTabs(options); } }; CustomTabs = function(options) { $('.tabbed_notifications > div').hide(); $('.tabbed_notifications > div:first-of-type').show(); $('#custom_notifications').removeClass('dsp_none'); $('.notifications a').click(function(e) { e.preventDefault(); var $this = $(this), tabbed_notifications = '#' + $this.parents('.notifications').data('tabbed_notifications'), others = $this.closest('li').siblings().children('a'), target = $this.attr('href'); others.removeClass('active'); $this.addClass('active'); $(tabbed_notifications).children('div').hide(); $(target).show(); }); }; CustomTabs(); var tabid = idname = ''; $(document).on('click', '.notification_close', function(e) { idname = $(this).parent().parent().attr("id"); tabid = idname.substr(-2); $('#ntf' + tabid).remove(); $('#ntlink' + tabid).parent().remove(); $('.notifications a').first().addClass('active'); $('#notif-group div').first().css('display', 'block'); }); });="45"></div> </script> <!-- /Custom Notification --> </body> </html>
38.90991
205
0.541097
663c98f0c662091df6ee412efbd0ae138fc376af
153
py
Python
devind_notifications/tasks/__init__.py
devind-team/devind-django-notifications
cf74bb0fdc9308f87a563b46c25d9a239da20841
[ "MIT" ]
null
null
null
devind_notifications/tasks/__init__.py
devind-team/devind-django-notifications
cf74bb0fdc9308f87a563b46c25d9a239da20841
[ "MIT" ]
4
2022-03-01T08:11:57.000Z
2022-03-31T14:10:58.000Z
devind_notifications/tasks/__init__.py
devind-team/devind-django-notifications
cf74bb0fdc9308f87a563b46c25d9a239da20841
[ "MIT" ]
null
null
null
from .congratulation_tasks import happy_birthday from .mail_tasks import send_mail from .notification_tasks import send_notification, send_notifications
38.25
69
0.888889
b4c8689491e4ef9eced2c99990c99161170d0d08
8,447
swift
Swift
Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Registration.swift
bupstan/XcodeBenchmark
5c7ba37abee5058670c05fdb6f43ebd7ff860999
[ "MIT" ]
1,562
2020-08-19T00:30:37.000Z
2022-03-31T15:15:22.000Z
Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Registration.swift
bupstan/XcodeBenchmark
5c7ba37abee5058670c05fdb6f43ebd7ff860999
[ "MIT" ]
198
2020-08-19T01:01:10.000Z
2022-03-23T16:40:29.000Z
Pods/DTTableViewManager/Sources/DTTableViewManager/DTTableViewManager+Registration.swift
bupstan/XcodeBenchmark
5c7ba37abee5058670c05fdb6f43ebd7ff860999
[ "MIT" ]
247
2020-09-06T18:34:40.000Z
2022-03-30T09:03:50.000Z
// // DTTableViewManager+Registration.swift // DTTableViewManager // // Created by Denys Telezhkin on 26.08.17. // Copyright © 2017 Denys Telezhkin. All rights reserved. // // 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 UIKit import DTModelStorage extension DTTableViewManager { /// Registers mapping for `cellClass`. Mapping will automatically check for nib with the same name as `cellClass` and register it, if it is found. `UITableViewCell` can also be designed in storyboard. /// - Parameters: /// - cellClass: UITableViewCell subclass type, conforming to `ModelTransfer` protocol. /// - mapping: mapping configuration closure, executed before any registration or dequeue is performed. /// - handler: configuration closure, that is run when cell is dequeued. Please note, that `handler` is called before `update(with:)` method. open func register<Cell:ModelTransfer>(_ cellClass:Cell.Type, mapping: ((ViewModelMapping<Cell, Cell.ModelType>) -> Void)? = nil, handler: @escaping (Cell, Cell.ModelType, IndexPath) -> Void = { _, _, _ in }) where Cell: UITableViewCell { self.viewFactory.registerCellClass(cellClass, handler: handler, mapping: mapping) } /// Registers mapping from `modelType` to `cellClass`. Mapping will automatically check for nib with the same name as `cellClass` and register it, if it is found. `UITableViewCell` can also be designed in storyboard. /// - Parameters: /// - cellClass: UITableViewCell to register /// - modelType: Model type, which is mapped to `cellClass`. /// - mapping: mapping configuration closure, executed before any registration or dequeue is performed. /// - handler: configuration closure, that is run when cell is dequeued. open func register<Cell: UITableViewCell, Model>(_ cellClass: Cell.Type, for modelType: Model.Type, mapping: ((ViewModelMapping<Cell, Model>) -> Void)? = nil, handler: @escaping (Cell, Model, IndexPath) -> Void) { viewFactory.registerCellClass(cellClass, modelType, handler: handler, mapping: mapping) } /// Registers mapping from model class to header view of `headerClass` type. /// /// Method will automatically check for nib with the same name as `headerClass`. If it exists - nib will be registered instead of class. /// This method also sets TableViewConfiguration.sectionHeaderStyle property to .view. /// - Note: Views does not need to be `UITableViewHeaderFooterView`, if it's a `UIView` subclass, it also will be created from XIB. In the latter case, events defined inside mapping closure are not supported. /// - Note: `handler` closure is called before `update(with:)` method. open func registerHeader<View:ModelTransfer>(_ headerClass : View.Type, mapping: ((ViewModelMapping<View, View.ModelType>) -> Void)? = nil, handler: @escaping (View, View.ModelType, Int) -> Void = { _, _, _ in }) where View: UIView { configuration.sectionHeaderStyle = .view viewFactory.registerSupplementaryClass(View.self, ofKind: DTTableViewElementSectionHeader, handler: handler, mapping: mapping) } /// Registers mapping from model class to header view of `headerClass` type. /// /// Method will automatically check for nib with the same name as `headerClass`. If it exists - nib will be registered instead of class. /// This method also sets TableViewConfiguration.sectionHeaderStyle property to .view. /// - Note: Views does not need to be `UITableViewHeaderFooterView`, if it's a `UIView` subclass, it also will be created from XIB. In the latter case, events defined inside mapping closure are not supported. open func registerHeader<View: UIView, Model>(_ headerClass : View.Type, for: Model.Type, mapping: ((ViewModelMapping<View, Model>) -> Void)? = nil, handler: @escaping (View, Model, Int) -> Void) { configuration.sectionHeaderStyle = .view viewFactory.registerSupplementaryClass(View.self, ofKind: DTTableViewElementSectionHeader, handler: handler, mapping: mapping) } /// Registers mapping from model class to footerView view of `footerClass` type. /// /// Method will automatically check for nib with the same name as `footerClass`. If it exists - nib will be registered instead of class. /// This method also sets TableViewConfiguration.sectionFooterStyle property to .view. /// - Note: Views does not need to be `UITableViewHeaderFooterView`, if it's a `UIView` subclass, it also will be created from XIB. In the latter case, events defined inside mapping closure are not supported. /// - Note: `handler` closure is called before `update(with:)` method. open func registerFooter<View:ModelTransfer>(_ footerClass: View.Type, mapping: ((ViewModelMapping<View, View.ModelType>) -> Void)? = nil, handler: @escaping (View, View.ModelType, Int) -> Void = { _, _, _ in }) where View:UIView { configuration.sectionFooterStyle = .view viewFactory.registerSupplementaryClass(View.self, ofKind: DTTableViewElementSectionFooter, handler: handler, mapping: mapping) } /// Registers mapping from model class to footer view of `footerClass` type. /// /// Method will automatically check for nib with the same name as `footerClass`. If it exists - nib will be registered instead of class. /// This method also sets TableViewConfiguration.sectionFooterStyle property to .view. /// - Note: Views does not need to be `UITableViewHeaderFooterView`, if it's a `UIView` subclass, it will be created from XIB. In the latter case, events defined inside mapping closure are not supported. open func registerFooter<View: UIView, Model>(_ footerClass : View.Type, for: Model.Type, mapping: ((ViewModelMapping<View, Model>) -> Void)? = nil, handler: @escaping (View, Model, Int) -> Void) { configuration.sectionFooterStyle = .view viewFactory.registerSupplementaryClass(View.self, ofKind: DTTableViewElementSectionFooter, handler: handler, mapping: mapping) } /// Unregisters `cellClass` from `DTTableViewManager` and `UITableView`. open func unregister<Cell:ModelTransfer>(_ cellClass: Cell.Type) where Cell:UITableViewCell { viewFactory.unregisterCellClass(Cell.self) } /// Unregisters `headerClass` from `DTTableViewManager` and `UITableView`. open func unregisterHeader<View:ModelTransfer>(_ headerClass: View.Type) where View: UIView { viewFactory.unregisterHeaderClass(View.self) } /// Unregisters `footerClass` from `DTTableViewManager` and `UITableView`. open func unregisterFooter<View:ModelTransfer>(_ footerClass: View.Type) where View: UIView { viewFactory.unregisterFooterClass(View.self) } }
66.511811
220
0.67302
7c0ea8f40c1861d3c27bd4412c84dd010848ed6f
322
h
C
Futures/Futures/Community/C/CommunityPopularVC.h
Ssiswent/Futures
f27e9b7be82c2367f73fe4b5baca3db38fd46d34
[ "MIT" ]
null
null
null
Futures/Futures/Community/C/CommunityPopularVC.h
Ssiswent/Futures
f27e9b7be82c2367f73fe4b5baca3db38fd46d34
[ "MIT" ]
null
null
null
Futures/Futures/Community/C/CommunityPopularVC.h
Ssiswent/Futures
f27e9b7be82c2367f73fe4b5baca3db38fd46d34
[ "MIT" ]
null
null
null
// // CommunityPopularVC.h // Futures // // Created by Ssiswent on 2020/6/4. // Copyright © 2020 Ssiswent. All rights reserved. // #import "ContentBaseViewController.h" NS_ASSUME_NONNULL_BEGIN @interface CommunityPopularVC : ContentBaseViewController<JXCategoryListContentViewDelegate> @end NS_ASSUME_NONNULL_END
17.888889
92
0.785714
f597ae4cda0b7c8ea6415d4842c6ad4dcef6617b
375
lua
Lua
SeaBlock/settings-updates/bobplates.lua
markbrockettrobson/SeaBlock
1649fb8c27c4babf4b2af6a87072088e2340b32a
[ "MIT" ]
null
null
null
SeaBlock/settings-updates/bobplates.lua
markbrockettrobson/SeaBlock
1649fb8c27c4babf4b2af6a87072088e2340b32a
[ "MIT" ]
null
null
null
SeaBlock/settings-updates/bobplates.lua
markbrockettrobson/SeaBlock
1649fb8c27c4babf4b2af6a87072088e2340b32a
[ "MIT" ]
null
null
null
-- Bob's Metals, Chemicals and Intermediates seablock.overwrite_setting('bool-setting', 'bobmods-plates-cheapersteel', false) seablock.overwrite_setting('bool-setting', 'bobmods-plates-newsteel', false) seablock.overwrite_setting('bool-setting', 'bobmods-plates-nuclearupdate', true) seablock.overwrite_setting('bool-setting', 'bobmods-plates-expensive-electrolysis', false)
62.5
90
0.810667