repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
MaiReo/crass
src/cui/ktg/ktg.cpp
<reponame>MaiReo/crass #include <windows.h> #include <tchar.h> #include <crass_types.h> #include <acui.h> #include <cui.h> #include <resource.h> #include <package.h> #include <cui_error.h> #include <utility.h> #include <stdio.h> struct acui_information ktg_cui_information = { _T("工畫堂スタジオ"), /* copyright */ _T(""), /* system */ _T(".arc"), /* package */ _T("0.0.2"), /* revision */ _T("痴汉公贼"), /* author */ _T("2007.05.12 20:41"), /* date */ NULL, /* notion */ ACUI_ATTRIBUTE_LEVEL_DEVELOP }; #pragma pack (1) typedef struct { u32 magic; // 0xa8bcadbe u32 version; // must be 0 u32 size; u32 offset; // 实际的数据的文件偏移 } arc_header_t; typedef struct { u32 comprlen; u32 flags; u32 uncomprlen; } arc_entry_t; typedef struct { //u32 parts; // 100030466 script, string: 1 u32 ident; // script, string: 0/* 资源目录标识符(顶级通常为0) */ u32 reserved; // script, string: 0 u32 entries; u32 length; // 该parts的长度 } arc_info_header_t; typedef struct { u32 offset; u32 comprlen; u32 flags; u32 uncomprlen; } arc_info_entry_t; #if 0 typedef struct { u32 parts; // 100030466 u32 ident; // script: 0/* 资源目录标识符(顶级通常为0) */ u32 reserved; // script: 0 u32 entries; u32 info_length; ......info // script: name_segment u32 ident; /* 资源目录标识符(次级,比如DDS) */ u32 reserved; u32 entries2; u32 info_length; ......info //script u32 name_offset; size_entries: flag width height [entries2个] // 因为通常entries所在的段表示的不是图像 offset u32 comprlen; u32 flags; u32 uncomprlen; size_index; } arc_info_t; #endif #pragma pack () typedef struct { WCHAR name[64]; u32 offset; u32 comprlen; u32 uncomprlen; u32 flags; } my_arc_entry_t; static void lzss_uncompress(BYTE *uncompr, DWORD uncomprlen, BYTE *compr, DWORD comprlen) { unsigned int act_uncomprlen = 0; /* compr中的当前字节中的下一个扫描位的位置 */ unsigned int curbit = 0; /* compr中的当前扫描字节 */ unsigned int curbyte = 0; unsigned int nCurWindowByte = 0xfee; unsigned int win_size = 4096; BYTE win[4096]; WORD flag = 0; memset(win, 0, sizeof(win)); while (act_uncomprlen < uncomprlen) { flag >>= 1; if (!(flag & 0x0100)) flag = compr[curbyte++] | 0xff00; if (flag & 1) { unsigned char data; data = compr[curbyte++]; uncompr[act_uncomprlen++] = data; if (act_uncomprlen == uncomprlen) break; /* 输出的1字节放入滑动窗口 */ win[nCurWindowByte++] = data; nCurWindowByte &= win_size - 1; } else { unsigned int copy_bytes, win_offset; unsigned int i; win_offset = compr[curbyte++]; copy_bytes = compr[curbyte++]; win_offset |= (copy_bytes & 0xf0) << 4; copy_bytes &= 0x0f; copy_bytes += 3; for (i = 0; i < copy_bytes; i++) { unsigned char data; data = win[(win_offset + i) & (win_size - 1)]; uncompr[act_uncomprlen++] = data; if (act_uncomprlen == uncomprlen) return; /* 输出的1字节放入滑动窗口 */ win[nCurWindowByte++] = data; nCurWindowByte &= win_size - 1; } } } } /********************* arc *********************/ static int ktg_arc_match(struct package *pkg) { arc_header_t arc_header; if (pkg->pio->open(pkg, IO_READONLY)) return -CUI_EOPEN; if (pkg->pio->read(pkg, &arc_header, sizeof(arc_header))) { pkg->pio->close(pkg); return -CUI_EREAD; } u32 size; if (pkg->pio->length_of(pkg, &size)) { pkg->pio->close(pkg); return -CUI_ELEN; } if (arc_header.magic != 0xA8BCADBE || arc_header.version || arc_header.size != size) { pkg->pio->close(pkg); return -CUI_EMATCH; } package_set_private(pkg, arc_header.offset); return 0; } static int ktg_arc_extract_directory(struct package *pkg, struct package_directory *pkg_dir) { arc_info_header_t *entry_info_buffer; BYTE *entry_name_buffer = NULL; BYTE *orig_entry_info_buffer = NULL; DWORD entry_name_buffer_length, entry_info_buffer_length; DWORD parts; int err = 0; /* 提取名称段和info段 */ for (DWORD i = 0; i < 2; ++i) { arc_entry_t arc_entry; if (pkg->pio->read(pkg, &arc_entry, sizeof(arc_entry))) { err = -CUI_EREAD; break; } if (arc_entry.flags > 3) { err = -CUI_EMATCH; break; } DWORD comprlen = arc_entry.comprlen - sizeof(arc_entry); BYTE *compr = new BYTE[comprlen]; if (!compr) { err = -CUI_EMEM; break; } DWORD uncomprlen = arc_entry.uncomprlen; BYTE *uncompr = new BYTE[uncomprlen]; if (!uncompr) { err = -CUI_EMEM; delete [] compr; break; } if (pkg->pio->read(pkg, compr, comprlen)) { err = -CUI_EREAD; delete [] uncompr; delete [] compr; break; } if (arc_entry.flags & 1) { for (DWORD k = 0; k < comprlen; ++k) compr[k] = ~compr[k]; } if (arc_entry.flags & 2) lzss_uncompress(uncompr, uncomprlen, compr, comprlen); else memcpy(uncompr, compr, uncomprlen); delete [] compr; if (!i) { entry_name_buffer_length = uncomprlen; entry_name_buffer = uncompr; } else { entry_info_buffer_length = uncomprlen - 4; orig_entry_info_buffer = uncompr; entry_info_buffer = (arc_info_header_t *)(uncompr + 4); parts = *(u32 *)uncompr; } } if (err) { delete [] orig_entry_info_buffer; delete [] entry_name_buffer; return err; } u32 *name_offset = NULL; my_arc_entry_t *index_buffer; arc_info_entry_t *entry; unsigned int index_length; u32 data_offset; #if 2 TCHAR save_name[MAX_PATH]; _stprintf(save_name, _T("%s_name"), pkg->name); MySaveFile(save_name, entry_name_buffer, entry_name_buffer_length); _stprintf(save_name, _T("%s_info"), pkg->name); MySaveFile(save_name, entry_info_buffer, entry_info_buffer_length); exit(0); #endif index_length = entry_info_buffer->entries * sizeof(my_arc_entry_t); index_buffer = (my_arc_entry_t *)malloc(index_length); if (!index_buffer) { free(entry_name_buffer); free(entry_info_buffer); return -CUI_EMEM; } data_offset = (u32)package_get_private(pkg); unsigned int start_index = 0; for (i = 0; i < parts; i++) { name_offset = (u32 *)(entry_info_buffer + 1); entry = (arc_info_entry_t *)(name_offset + entry_info_buffer->entries); for (unsigned int k = start_index; k < start_index + entry_info_buffer->entries; k++) { wcscpy(index_buffer[k].name, (WCHAR *)&entry_name_buffer[name_offset[k]]); index_buffer[k].offset = entry[k].offset + data_offset; index_buffer[k].comprlen = entry[k].comprlen - 12; index_buffer[k].uncomprlen = entry[k].uncomprlen; index_buffer[k].flags = entry[k].flags; } if (i + 1 < parts) { entry += entry_info_buffer->entries; start_index += entry_info_buffer->entries; entry_info_buffer = (arc_info_header_t *)entry; index_buffer = (my_arc_entry_t *)realloc(index_buffer, index_length + entry_info_buffer->entries * sizeof(my_arc_entry_t)); if (!index_buffer) break; index_length += entry_info_buffer->entries * sizeof(my_arc_entry_t); } } if (i != parts) { free(index_buffer); free(entry_name_buffer); free(orig_entry_info_buffer); return -CUI_EMEM; } free(entry_name_buffer); free(orig_entry_info_buffer); pkg_dir->index_entries = index_length / sizeof(my_arc_entry_t); pkg_dir->index_entry_length = sizeof(my_arc_entry_t); pkg_dir->directory = index_buffer; pkg_dir->directory_length = index_length; return 0; } static int ktg_arc_parse_resource_info(struct package *pkg, struct package_resource *pkg_res) { my_arc_entry_t *arc_entry; if (!pkg || !pkg_res) return -CUI_EPARA; arc_entry = (my_arc_entry_t *)pkg_res->actual_index_entry; wcscpy((WCHAR *)pkg_res->name, arc_entry->name); pkg_res->name_length = -1; pkg_res->raw_data_length = arc_entry->comprlen; pkg_res->actual_data_length = arc_entry->uncomprlen; pkg_res->offset = arc_entry->offset; pkg_res->flags |= PKG_RES_FLAG_UNICODE; return 0; } static int ktg_arc_extract_resource(struct package *pkg, struct package_resource *pkg_res) { BYTE *compr, *uncompr; DWORD comprlen, uncomprlen; my_arc_entry_t *arc_entry; if (!pkg || !pkg_res) return -CUI_EPARA; arc_entry = (my_arc_entry_t *)pkg_res->actual_index_entry; comprlen = pkg_res->raw_data_length; compr = (BYTE *)malloc(comprlen); if (!compr) return -CUI_EMEM; if (pkg->pio->readvec(pkg, compr, comprlen, pkg_res->offset, IO_SEEK_SET)) { free(compr); return -CUI_EREADVEC; } if (arc_entry->flags > 3) { free(compr); return -CUI_EMATCH; } if (arc_entry->flags & 1) { for (unsigned int k = 0; k < comprlen; k++) compr[k] = ~compr[k]; } // core:100028c7c if (arc_entry->flags & 2) { uncomprlen = pkg_res->actual_data_length; uncompr = (BYTE *)malloc(uncomprlen); if (!uncompr) { free(compr); return -CUI_EMEM; } lzss_uncompress(uncompr, uncomprlen, compr, comprlen); free(compr); compr = NULL; } else { /* 1001bf70 */ //printf("[unsupported %x]\n", arc_entry->flags); //exit(0); uncomprlen = 0; uncompr = NULL; } pkg_res->raw_data = compr; pkg_res->actual_data = uncompr; pkg_res->actual_data_length = uncomprlen; return 0; } static int ktg_arc_save_resource(struct resource *res, struct package_resource *pkg_res) { if (!res || !pkg_res) return -CUI_EPARA; if (res->rio->create(res)) return -CUI_ECREATE; if (pkg_res->actual_data && pkg_res->actual_data_length) { if (res->rio->write(res, pkg_res->actual_data, pkg_res->actual_data_length)) { res->rio->close(res); return -CUI_EWRITE; } } else if (pkg_res->raw_data && pkg_res->raw_data_length) { if (res->rio->write(res, pkg_res->raw_data, pkg_res->raw_data_length)) { res->rio->close(res); return -CUI_EWRITE; } } res->rio->close(res); return 0; } static void ktg_arc_release_resource(struct package *pkg, struct package_resource *pkg_res) { if (!pkg || !pkg_res) return; if (pkg_res->actual_data) { free(pkg_res->actual_data); pkg_res->actual_data = NULL; } if (pkg_res->raw_data) { free(pkg_res->raw_data); pkg_res->raw_data = NULL; } } static void ktg_arc_release(struct package *pkg, struct package_directory *pkg_dir) { if (!pkg || !pkg_dir) return; if (pkg_dir->directory) { free(pkg_dir->directory); pkg_dir->directory = NULL; } package_set_private(pkg, NULL); pkg->pio->close(pkg); } static cui_ext_operation ktg_arc_operation = { ktg_arc_match, /* match */ ktg_arc_extract_directory, /* extract_directory */ ktg_arc_parse_resource_info, /* parse_resource_info */ ktg_arc_extract_resource, /* extract_resource */ ktg_arc_save_resource, /* save_resource */ ktg_arc_release_resource, /* release_resource */ ktg_arc_release /* release */ }; int CALLBACK ktg_register_cui(struct cui_register_callback *callback) { if (callback->add_extension(callback->cui, _T(".arc"), NULL, NULL, &ktg_arc_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR)) return -1; return 0; } }
AljazBozic/CommonUtils
tests/unit_tests/timing/TimingTest.cpp
#include "common_utils/timing/Timing.h" #include <gtest/gtest.h> using namespace common_utils; namespace timing_tests { //###################################################################################################### // Timing test. TEST(TimingTest, PrintReport) { timing::start("TimingTest::totalTime"); for (int i = 0; i < 100; ++i) { timing::start("SimpleOperations::multiplication"); int a = i * i; timing::stop("SimpleOperations::multiplication"); timing::start("SimpleOperations::assignment"); int b = i; timing::stop("SimpleOperations::assignment"); timing::start("SimpleOperations::sum"); int c = a + b; timing::stop("SimpleOperations::sum"); } timing::stop("TimingTest::totalTime"); timing::print("TimingTest"); timing::print("SimpleOperations"); timing::print("TimingTest;SimpleOperations"); timing::print(); } TEST(TimingTest, PreprocessorSyntax) { TIME("TimingTest::totalTime") { for (int i = 0; i < 100; ++i) { int a, b, c; TIME("SimpleOperations::multiplication") { a = i * i; } TIME("SimpleOperations::assignment") { b = i; } TIME("SimpleOperations::sum") { c = a + b; } } } timing::print("TimingTest"); timing::print("SimpleOperations"); timing::print("TimingTest;SimpleOperations"); timing::print(); } TEST(TimingTest, AverageTime) { TIME("TimingTest::totalTime") { for (int i = 0; i < 100; ++i) { int a, b, c; TIME("SimpleOperations::multiplication") { a = i * i; } TIME("SimpleOperations::assignment") { b = i; } TIME("SimpleOperations::sum") { c = a + b; } } } cout << "Average multiplication time: " << timing::averageTime("SimpleOperations::multiplication") << endl; cout << "Average assignment time: " << timing::averageTime("SimpleOperations::assignment") << endl; cout << "Average sum time: " << timing::averageTime("SimpleOperations::sum") << endl; } } // namespace timing_tests
porscheinformatik/pnet-data-api
pnet-data-api-java/src/main/java/pnet/data/api/util/RestrictContractType.java
<filename>pnet-data-api-java/src/main/java/pnet/data/api/util/RestrictContractType.java package pnet.data.api.util; import java.util.Collection; /** * Restricts contract types. * * @author ham * @param <SELF> the type of the filter for chaining */ public interface RestrictContractType<SELF extends Restrict<SELF>> extends Restrict<SELF> { default SELF contractType(String... contractTypeMatchcodes) { return restrict("contractType", (Object[]) contractTypeMatchcodes); } default SELF contractTypes(Collection<String> contractTypeMatchcodes) { return contractType(contractTypeMatchcodes.toArray(new String[contractTypeMatchcodes.size()])); } }
EtherTyper/dummydroid-patched
de/onyxbits/raccoon/standalone/gui/bridge/DirectoryManager.java
package de.onyxbits.raccoon.standalone.gui.bridge; import de.onyxbits.raccoon.platformtools.Binaries; import de.onyxbits.raccoon.platformtools.bridge.BridgeDirectory; import de.onyxbits.raccoon.standalone.SystemProperties; import de.onyxbits.raccoon.standalone.base.AbstractModule; import de.onyxbits.raccoon.standalone.base.AppAdapter; import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import javax.swing.event.EventListenerList; public class DirectoryManager extends AbstractModule implements SystemProperties { private Thread thread; private EventListenerList listeners; private Directory directory; private void ensureRunning() { if (this.directory == null || !this.directory.ping()) { InetAddress addr = InetAddress.getLoopbackAddress(); int port = 0; try { port = Integer.parseInt(System.getProperty("adb.port", "5037")); } catch (NumberFormatException var5) { } try { if (System.getProperty("adb.host") != null) { addr = InetAddress.getByName(System.getProperty("adb.host")); } } catch (UnknownHostException var4) { } Binaries bin = new Binaries(this.pathOf()); this.listeners = new EventListenerList(); this.directory = new Directory(bin.pathOfAdb(), addr, port, this.listeners); this.thread = new Thread(this.directory); this.thread.start(); } } public File pathOf() { return new File(((AppAdapter)this.fetch(AppAdapter.class)).pathOf(), "platform-tools"); } public BridgeDirectory getDirectory() { this.ensureRunning(); return this.directory; } public void addDirectoryListener(DirectoryListener listener) { this.ensureRunning(); this.listeners.add(DirectoryListener.class, listener); } public void removeDirectoryListener(DirectoryListener listener) { this.ensureRunning(); this.listeners.remove(DirectoryListener.class, listener); } public boolean isAvailable() { this.ensureRunning(); if (this.directory.ping()) { return true; } else { File f = (new Binaries(this.pathOf())).pathOfAdb(); return f != null && f.exists() && f.canExecute(); } } public void shutdown() { if (this.directory != null) { this.directory.kill(); } } }
EricVanEldik/openui5
src/sap.ui.core/test/sap/ui/core/qunit/component/testdata/async/lib2/library-preload.js
sap.ui.predefine("sap/test/lib2/library", ['jquery.sap.global', 'sap/test/lib4/library'], function(jQuery, library1) { "use strict"; sap.ui.getCore().initLibrary({ name:"sap.test.lib2", noLibraryCSS:true }); }); sap.ui.require.preload({ "version":"2.0", "name":"sap.test.lib2", "modules":{ "sap/test/lib2/manifest.json":"{\n\t\"sap.ui5\": {\n\t\t\"dependencies\": {\n\t\t\t\"libs\": {\n\t\t\t\"sap.test.lib4\": {}\n\t\t}\n\t\t}\n\t}\n}" } });
tilnewman/castle-crawl
src/save-game.cpp
<gh_stars>0 // This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // // save-game.cpp // #include "save-game.hpp" #include "board.hpp" #include "context.hpp" #include <filesystem> #include <fstream> namespace castlecrawl { void SaveGame::saveToFile(Context & context) { // gather data context.maps.save(context); player = context.player; player_pos = context.board.player().position(); // serialize json j = *this; // save to file std::ofstream fileStream("saved-game.txt", std::ios_base::trunc); fileStream << std::setw(4) << j; } std::string SaveGame::loadFromFile(Context & context) { try { // check that file exists const std::filesystem::path path{ "saved-game.txt" }; if (!std::filesystem::exists(path)) { throw std::runtime_error("Error: No saved game to load!"); } // open file std::ifstream fileStream(path.string(), std::ios_base::in); if (!fileStream.good()) { throw std::runtime_error("Error: Unable to open saved game file!"); } try { // load from file json j; fileStream >> j; // deserialize *this = j.get<SaveGame>(); } catch (...) { throw std::runtime_error("Error: Saved game file contains errors!"); } // distribute data context.board.player().position(context, player_pos); context.player = player; context.maps.load(context); return ""; } catch (const std::exception & ex) { return ex.what(); } } } // namespace castlecrawl
black-shadows/LeetCode-Solutions
C++/read-n-characters-given-read4.cpp
<filename>C++/read-n-characters-given-read4.cpp // Time: O(n) // Space: O(1) int read4(char *buf); class Solution { public: /** * @param buf Destination buffer * @param n Maximum number of characters to read * @return The number of characters read */ int read(char *buf, int n) { int read_bytes = 0; char buffer[4]; for (int i = 0; i <= n / 4; ++i) { if (int size = read4(buffer)) { size = min(size, n - read_bytes); for (int j = 0; j < size; ++j) { buf[read_bytes++] = buffer[j]; } } else { break; } } return read_bytes; } };
ideacrew/ledger_redux
components/qbo/app/entities/qbo/vendors/vendor.rb
module Qbo::Vendors class Vendor < Dry::Struct attribute :"GivenName", Types::Strict::String.meta(omittable: true) attribute :"DisplayName", Types::Strict::String.meta(omittable: false) attribute :"FamilyName", Types::Strict::String.meta(omittable: true) attribute :"Id", Types::Strict::String.meta(omittable: true) attribute :"SyncToken", Types::Strict::String.meta(omittable: true) attribute :"domain", Types::Strict::String.meta(omittable: true) attribute :"Vendor1099", Types::Bool.meta(omittable: true) attribute :"AcctNum", Types::Strict::String.meta(omittable: true) attribute :"CompanyName", Types::Strict::String.meta(omittable: true) attribute :"BillAddr", Qbo::Locations::Address.optional.meta(omittable: true) attribute :"WebAddr", Dry::Struct.meta(omittable: true) do attribute :"URI", Types::Strict::String.meta(omittable: true) end attribute :"PrimaryEmailAddr", Dry::Struct.meta(omittable: true) do attribute :"Address", Types::Strict::String.meta(omittable: true) end attribute :"PrimaryPhone", Dry::Struct.meta(omittable: true) do attribute :"FreeFormNumber", Types::Strict::String.meta(omittable: true) end attribute :"sparse", Types::Bool.meta(omittable: true) attribute :"Active", Types::Bool.meta(omittable: true) attribute :"MetaData", Types::Hash.meta(omittable: true) attribute :"Balance", Types::Float.meta(omittable: true) attribute :"PrintOnCheckName", Types::Strict::String.meta(omittable: true) end end
meteoorkip/GROOVE
groove/src/groove/gui/display/StateDisplay.java
<gh_stars>1-10 /* * GROOVE: GRaphs for Object Oriented VErification Copyright 2003--2007 * University of Twente * * 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. * * $Id: StateDisplay.java 5883 2017-04-07 17:16:03Z rensink $ */ package groove.gui.display; import static groove.gui.SimulatorModel.Change.GRAMMAR; import static groove.gui.SimulatorModel.Change.GTS; import static groove.gui.SimulatorModel.Change.MATCH; import static groove.gui.SimulatorModel.Change.STATE; import java.awt.BorderLayout; import java.awt.Color; import java.awt.geom.Point2D; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Observer; import java.util.Set; import java.util.Stack; import java.util.WeakHashMap; import javax.swing.JComponent; import javax.swing.JSplitPane; import javax.swing.JToolBar; import javax.swing.JTree; import org.jgraph.event.GraphSelectionEvent; import org.jgraph.event.GraphSelectionListener; import groove.grammar.aspect.AspectEdge; import groove.grammar.aspect.AspectGraph; import groove.grammar.aspect.AspectNode; import groove.grammar.aspect.GraphConverter; import groove.grammar.aspect.GraphConverter.HostToAspectMap; import groove.grammar.host.HostEdge; import groove.grammar.host.HostGraphMorphism; import groove.grammar.host.HostNode; import groove.grammar.host.HostNodeSet; import groove.grammar.model.GrammarModel; import groove.grammar.model.HostModel; import groove.grammar.rule.RuleNode; import groove.graph.GraphInfo; import groove.gui.Options; import groove.gui.Simulator; import groove.gui.SimulatorListener; import groove.gui.SimulatorModel; import groove.gui.SimulatorModel.Change; import groove.gui.jgraph.AspectJCell; import groove.gui.jgraph.AspectJEdge; import groove.gui.jgraph.AspectJGraph; import groove.gui.jgraph.AspectJModel; import groove.gui.jgraph.AspectJVertex; import groove.gui.jgraph.JAttr; import groove.gui.list.ErrorListPanel; import groove.gui.look.VisualKey; import groove.gui.look.VisualMap; import groove.gui.tree.StateTree; import groove.gui.tree.TypeTree; import groove.io.HTMLConverter; import groove.lts.GTS; import groove.lts.GraphNextState; import groove.lts.GraphState; import groove.lts.GraphTransition; import groove.lts.MatchResult; import groove.lts.RecipeTransition; import groove.lts.RuleTransition; import groove.lts.StartGraphState; import groove.transform.Proof; import groove.transform.RuleApplication; import groove.util.line.LineStyle; import groove.util.parse.FormatError; /** * Window that displays and controls the current lts graph. Auxiliary class for * Simulator. * * @author <NAME> * @version $Revision: 5883 $ $Date: 2008-02-05 13:28:06 $ */ public class StateDisplay extends Display implements SimulatorListener { /** Creates a LTS panel for a given simulator. */ public StateDisplay(Simulator simulator) { super(simulator, DisplayKind.STATE); } @Override protected void buildDisplay() { JToolBar toolBar = Options.createToolBar(); fillToolBar(toolBar); add(toolBar, BorderLayout.NORTH); add(getDisplayPanel()); } @Override protected JTree createList() { return new StateTree(getSimulator()); } @Override protected JToolBar createListToolBar() { JToolBar result = Options.createToolBar(); result.add(getActions().getEditStateAction()); result.add(getActions().getSaveStateAction()); result.addSeparator(); result.add(getActions().getBackAction()); result.add(getActions().getForwardAction()); return result; } @Override protected JComponent createInfoPanel() { TypeTree labelTree = getLabelTree(); TitledPanel result = new TitledPanel(Options.LABEL_PANE_TITLE, labelTree, labelTree.createToolBar(), true); result.setEnabledBackground(JAttr.STATE_BACKGROUND); return result; } @Override protected void installListeners() { this.graphSelectionListener = new GraphSelectionListener() { @Override public void valueChanged(GraphSelectionEvent e) { if (StateDisplay.this.matchSelected) { // change only if cells were removed from the selection boolean removed = false; Object[] cells = e.getCells(); for (int i = 0; !removed && i < cells.length; i++) { removed = !e.isAddedCell(i); } if (removed) { clearSelectedMatch(false); } } } }; getSimulatorModel().addListener(this, GRAMMAR, GTS, STATE, MATCH); activateListening(); } /** * Activates all listeners. */ private void activateListening() { if (this.listening) { throw new IllegalStateException(); } // make sure that removals from the selection model // also deselect the match getJGraph().addGraphSelectionListener(this.graphSelectionListener); this.listening = true; } /** * Suspend all listening activity to avoid dependent updates. */ private boolean suspendListening() { boolean result = this.listening; if (result) { getJGraph().removeGraphSelectionListener(this.graphSelectionListener); this.listening = false; } return result; } private void fillToolBar(JToolBar result) { result.removeAll(); result.add(getActions().getExplorationDialogAction()); result.addSeparator(); result.add(getActions().getStartSimulationAction()); result.add(getActions().getApplyMatchAction()); result.add(getActions().getAnimateAction()); result.add(getActions().getExploreAction()); result.addSeparator(); result.add(getActions().getBackAction()); result.add(getActions().getForwardAction()); } /** Lazily creates and returns the top-level display panel. */ private JSplitPane getDisplayPanel() { JSplitPane result = this.displayPanel; if (result == null) { this.displayPanel = result = new JSplitPane(JSplitPane.VERTICAL_SPLIT); result.setTopComponent(getGraphPanel()); result.setBottomComponent(getErrorPanel()); result.setDividerSize(0); result.setContinuousLayout(true); result.setResizeWeight(0.9); result.resetToPreferredSizes(); result.setBorder(null); } return result; } /** Split pane containing the {@link #stateGraphPanel} and the {@link #errorPanel}. */ private JSplitPane displayPanel; /** Returns the currently displayed state graph. */ public AspectGraph getStateGraph() { return getJGraph().getModel() .getGraph(); } /** Returns component on which the state graph is displayed. */ public JGraphPanel<AspectGraph> getGraphPanel() { JGraphPanel<AspectGraph> result = this.stateGraphPanel; if (result == null) { result = this.stateGraphPanel = new JGraphPanel<AspectGraph>(getJGraph()) { @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); getInfoPanel().setEnabled(enabled); } }; result.initialise(); result.setBorder(null); result.setEnabledBackground(JAttr.STATE_BACKGROUND); result.getJGraph() .setToolTipEnabled(true); } return result; } /** JGraph panel on this display. */ private JGraphPanel<AspectGraph> stateGraphPanel; /** Gets the error panel, creating it (lazily) if necessary. */ private ErrorListPanel getErrorPanel() { if (this.errorPanel == null) { this.errorPanel = new ErrorListPanel("Errors in state graph"); this.errorPanel.addSelectionListener(createErrorListener()); } return this.errorPanel; } /** List of state errors, only shown if there are any errors in the current state. */ private ErrorListPanel errorPanel; /** Returns the JGraph component of the state display. */ final public AspectJGraph getJGraph() { AspectJGraph result = this.jGraph; if (result == null) { result = this.jGraph = new AspectJGraph(getSimulator(), getKind(), false); result.setLabelTree(getLabelTree()); } return result; } /** JGraph showing the current state. */ private AspectJGraph jGraph; /** Lazily creates and returns the label tree for the display. */ private TypeTree getLabelTree() { TypeTree result = this.labelTree; if (result == null) { result = this.labelTree = new TypeTree(getJGraph(), true); } return result; } /** The tree component showing (and allowing filtering of) the transitions in the LTS. */ private TypeTree labelTree; /** Creates the listener of the error panel. */ private Observer createErrorListener() { return new Observer() { @Override public void update(Observable o, Object arg) { if (arg != null) { AspectJCell errorCell = getJGraph().getModel() .getErrorMap() .get(arg); if (errorCell != null) { getJGraph().setSelectionCell(errorCell); } } } }; } @Override public void update(SimulatorModel source, SimulatorModel oldModel, Set<Change> changes) { if (!suspendListening()) { return; } // check if layout should be transferred GraphTransition oldTtrans = oldModel.getTransition(); boolean transferLayout = oldTtrans != null && oldTtrans != source.getTransition() && oldTtrans.target() == source.getState(); if (changes.contains(GTS) && source.getGTS() != oldModel.getGTS()) { startSimulation(source.getGTS()); } else if (changes.contains(STATE)) { GraphState newState = source.getState(); if (newState != null) { // clear the match on the current state clearSelectedMatch(true); } else { if (transferLayout) { transferLayout(oldTtrans); transferLayout = false; } } // set the graph model to the new state displayState(newState); } if (changes.contains(MATCH)) { if (transferLayout) { transferLayout(oldTtrans); } if (source.getMatch() == null) { clearSelectedMatch(true); } else { selectMatch(source.getMatch() .getEvent() .getMatch(source.getState() .getGraph())); } // all cells repainted, even though everything but the // edge colour seems to be OK even without doing this getJGraph().refreshAllCells(); } updateStatus(); activateListening(); } private void startSimulation(GTS gts) { // clear the states from the aspect and model maps this.stateToJModel.clear(); this.stateToAspectMap.clear(); // only change the displayed model if we are currently displaying a // state displayState(getSimulatorModel().getState()); } /** * Emphasise the given match. * @param match the match to be emphasised (non-null) */ private void selectMatch(Proof match) { assert match != null : "Match update should not be called with empty match"; displayState(getSimulatorModel().getState()); AspectJModel jModel = getJGraph().getModel(); HostToAspectMap aspectMap = getAspectMap(getSimulatorModel().getState()); Set<AspectJCell> emphElems = new HashSet<>(); match.getNodeValues() .stream() .map(n -> jModel.getJCellForNode(aspectMap.getNode(n))) .filter(c -> c != null) .forEach(c -> emphElems.add(c)); match.getEdgeValues() .stream() .map(e -> jModel.getJCellForEdge(aspectMap.getEdge(e))) .filter(c -> c != null) .forEach(c -> emphElems.add(c)); getJGraph().setSelectionCells(emphElems.toArray()); this.matchSelected = true; } /** Updates the display status bar. */ private void updateStatus() { StringBuilder result = new StringBuilder(); result.append("Current state"); GraphState state = getSimulatorModel().getState(); if (state != null) { result.append(": "); String stateID = state.toString(); result.append(HTMLConverter.UNDERLINE_TAG.on(stateID)); if (stateID.equals("s0")) { HostModel startGraph = getSimulatorModel().getGrammar() .getStartGraphModel(); if (startGraph != null) { result.append("="); result.append(startGraph.getLastName()); } } MatchResult match = getSimulatorModel().getMatch(); boolean brackets = false; if (state.isInternalState()) { result.append(brackets ? ", " : " ("); brackets = true; result.append("transient state"); } if (state.isInternalState()) { result.append(brackets ? ", " : " ("); brackets = true; result.append("removed from state space"); } if (state.isError()) { result.append(brackets ? ", " : " ("); brackets = true; result.append("has errors"); } if (match != null) { result.append(brackets ? "; " : " ("); brackets = true; if (getJGraph().isShowAnchors()) { result.append(String.format("with match '%s'", match.getEvent())); } else { result.append(String.format("with match of <i>%s</i>", match.getEvent() .getRule() .getQualName())); } } if (brackets) { result.append(')'); } } getGraphPanel().getStatusLabel() .setText(HTMLConverter.HTML_TAG.on(result) .toString()); } /** Changes the display to a given state. */ public void displayState(GraphState state) { clearSelectedMatch(true); if (state == null) { getJGraph().setModel(null); } else { AspectJModel model = getAspectJModel(state); getJGraph().setModel(model); getJGraph().doLayout(false); } Color background; if (state != null && state.isError()) { Collection<FormatError> errors = GraphInfo.getErrors(state.getGraph()); getErrorPanel().setEntries(errors); getDisplayPanel().setBottomComponent(getErrorPanel()); getDisplayPanel().resetToPreferredSizes(); background = JAttr.ERROR_BACKGROUND; } else { getErrorPanel().clearEntries(); getDisplayPanel().remove(getErrorPanel()); background = state != null && state.isInternalState() ? JAttr.TRANSIENT_BACKGROUND : JAttr.STATE_BACKGROUND; } getGraphPanel().setEnabledBackground(background); getLabelTree().setBackground(background); } /** * Clears the emphasis due to the currently selected match, if any. * Also changes the match selection in the rule tree to the corresponding * rule. * @param clear if {@code true}, the current selection should be cleared; * otherwise it should be preserved */ private boolean clearSelectedMatch(boolean clear) { boolean result = this.listening && this.matchSelected; if (result) { this.matchSelected = false; if (clear) { getJGraph().clearSelection(); } getSimulatorModel().setMatch(getSimulatorModel().getState(), null); updateStatus(); } return result; } /** * Returns a graph model for a given state graph. The graph model is * retrieved from {@link #stateToJModel}; if there is no image for the requested * state then one is created. */ private AspectJModel getAspectJModel(GraphState state) { HostToAspectMap aspectMap = getAspectMap(state); AspectGraph aspectGraph = aspectMap.getAspectGraph(); AspectJModel result = this.stateToJModel.get(state); if (result == null) { result = createAspectJModel(aspectGraph); assert result != null; this.stateToJModel.put(state, result); // try to find layout information for the model if (state instanceof GraphNextState) { setNextStateLayout((GraphNextState) state, result); } else { assert state instanceof StartGraphState; // this is the start state setStartGraphLayout(result); } } return result; } private void setNextStateLayout(GraphNextState state, AspectJModel result) { Stack<GraphTransition> stack = new Stack<>(); GraphState source = state; do { GraphTransition trans = ((GraphNextState) source).getInTransition(); stack.push(trans); source = trans.source(); } while (source instanceof GraphNextState && !this.stateToJModel.containsKey(source)); AspectJModel model = getAspectJModel(source); AttributesMap map = extractAttributes(model, getAspectMap(source)); while (!stack.isEmpty()) { GraphTransition trans = stack.pop(); map = transferAttributes(map, trans); } applyAttributes(map, result, getAspectMap(state)); } /** * Returns a map from host graph elements to layout attributes, * extracted from a given aspect model under a host-to-aspect map. */ private AttributesMap extractAttributes(AspectJModel model, HostToAspectMap aspectMap) { AttributesMap result = new AttributesMap(); for (Map.Entry<HostNode,? extends AspectNode> entry : aspectMap.nodeMap() .entrySet()) { AspectNode aspectNode = entry.getValue(); AspectJVertex jCell = model.getJCellForNode(aspectNode); assert jCell != null : "Source element " + aspectNode + " unknown"; result.nodeMap.put(entry.getKey(), new Attributes(jCell)); } // compute target edge attributes for (Map.Entry<HostEdge,? extends AspectEdge> entry : aspectMap.edgeMap() .entrySet()) { AspectEdge aspectEdge = entry.getValue(); AspectJCell jCell = model.getJCellForEdge(aspectEdge); if (jCell instanceof AspectJEdge) { result.edgeMap.put(entry.getKey(), new Attributes((AspectJEdge) jCell)); } } return result; } /** Creates a mapping from host elements to layout attributes for * the target graph of a transition, given the attributes mapping for * the source graph. */ private AttributesMap transferAttributes(AttributesMap map, GraphTransition trans) { AttributesMap result = new AttributesMap(); HostGraphMorphism morphism = trans.getMorphism(); Map<HostNode,Attributes> sourceNodeMap = map.nodeMap; Map<HostNode,Attributes> resultNodeMap = result.nodeMap; Map<HostNode,Color> newColorMap = extractNewColors(trans); HostNodeSet newNodes = new HostNodeSet(trans.target() .getGraph() .nodeSet()); // transfer node attributes for (Map.Entry<HostNode,HostNode> entry : morphism.nodeMap() .entrySet()) { HostNode sourceNode = entry.getKey(); Attributes attr = sourceNodeMap.get(sourceNode); HostNode targetNode = entry.getValue(); assert trans.target() .getGraph() .containsNode(targetNode); Color newColor = newColorMap.get(targetNode); if (newColor != null) { if (attr == null) { attr = new Attributes(newColor); } else { attr.color = newColor; } } if (attr != null) { resultNodeMap.put(targetNode, attr); } newNodes.remove(targetNode); } // add node colours for the new nodes for (HostNode newNode : newNodes) { Color newColor = newColorMap.get(newNode); if (newColor != null) { Attributes attr = new Attributes(newColor); resultNodeMap.put(newNode, attr); } } // transfer edge attributes Map<HostEdge,Attributes> sourceEdgeMap = map.edgeMap; Map<HostEdge,Attributes> resultEdgeMap = result.edgeMap; for (Map.Entry<HostEdge,HostEdge> entry : morphism.edgeMap() .entrySet()) { HostEdge sourceEdge = entry.getKey(); Attributes attr = sourceEdgeMap.get(sourceEdge); if (attr != null) { HostEdge targetEdge = entry.getValue(); resultEdgeMap.put(targetEdge, attr); } } return result; } /** Stores the computed attributes into an aspect model. */ private void applyAttributes(AttributesMap map, AspectJModel result, HostToAspectMap aspectMap) { // initially set all cells to layoutable, // (which is partially undone later) // so the new nodes and edges get a change of being layed out result.setLayoutable(true); for (Map.Entry<HostNode,Attributes> e : map.nodeMap.entrySet()) { AspectNode aspectNode = aspectMap.getNode(e.getKey()); assert aspectNode != null : "Target element " + e.getKey() + " unknown"; AspectJVertex jCell = result.getJCellForNode(aspectNode); assert jCell != null : "Target element " + aspectNode + " unknown"; Attributes attrs = e.getValue(); jCell.putVisuals(attrs.toVisuals()); jCell.setGrayedOut(attrs.grayedOut); jCell.setLayoutable(attrs.pos == null); result.synchroniseLayout(jCell); if (attrs.color != null) { // also colour all outgoing edges Iterator<? extends AspectJEdge> iter = jCell.getContext(); while (iter.hasNext()) { AspectJEdge jEdge = iter.next(); if (jEdge.getSourceVertex() == jCell) { jEdge.putVisual(VisualKey.COLOR, attrs.color); } } } } // store target edge attributes for (Map.Entry<HostEdge,Attributes> e : map.edgeMap.entrySet()) { AspectEdge aspectEdge = aspectMap.getEdge(e.getKey()); assert aspectEdge != null : "Target element " + e.getKey() + " unknown"; AspectJCell jCell = result.getJCellForEdge(aspectEdge); if (jCell instanceof AspectJVertex) { continue; } assert jCell != null : "Target element " + aspectEdge + " unknown"; Attributes attr = e.getValue(); jCell.putVisuals(attr.toVisuals()); jCell.setGrayedOut(attr.grayedOut); result.synchroniseLayout(jCell); } } /** Transfers colours and layout from the source to the target of a given transition. */ private void transferLayout(GraphTransition trans) { AttributesMap map = extractAttributes(this.stateToJModel.get(trans.source()), getAspectMap(trans.source())); map = transferAttributes(map, trans); applyAttributes(map, this.stateToJModel.get(trans.target()), getAspectMap(trans.target())); } /** * Creates a mapping from host nodes to colours * as newly generated by a given transition. */ private Map<HostNode,Color> extractNewColors(GraphTransition trans) { Map<HostNode,Color> result = new HashMap<>(); // transfer colours along transition if (trans instanceof RuleTransition) { result = transferColors(result, (RuleTransition) trans); } else { for (RuleTransition ruleTrans : ((RecipeTransition) trans).getPath()) { result = transferColors(result, ruleTrans); } } return result; } /** * Transforms a colour map of a transition source graph * into a colour map for the transition target graph. * @param colorMap original colour map for the source graph * @param trans transition from source to target * @return colour map for the target graph */ private Map<HostNode,Color> transferColors(Map<HostNode,Color> colorMap, RuleTransition trans) { Map<HostNode,Color> result = new HashMap<>(); // extract new colours from target RuleApplication application = trans.createRuleApplication(); Map<RuleNode,HostNodeSet> comatch = application.getComatch(); for (Map.Entry<RuleNode,Color> colorEntry : application.getRule() .getColorMap() .entrySet()) { HostNodeSet matches = comatch.get(colorEntry.getKey()); // possibly this node has no matches, for instance if it is universally // quantified if (matches != null) { for (HostNode hostNode : matches) { result.put(hostNode, colorEntry.getValue()); } } } // now copy colours from source to target HostGraphMorphism morphism = trans.getMorphism(); for (Map.Entry<HostNode,Color> colorEntry : colorMap.entrySet()) { HostNode newNode = morphism.getNode(colorEntry.getKey()); if (!result.containsKey(newNode)) { result.put(newNode, colorEntry.getValue()); } } return result; } /** Copies layout from the host model of the start graph. */ private void setStartGraphLayout(AspectJModel result) { AspectGraph startGraph = getGrammar().getStartGraphModel() .getSource(); AspectJModel startModel = createAspectJModel(startGraph); for (AspectNode node : startGraph.nodeSet()) { AspectJVertex stateVertex = result.getJCellForNode(node); // meta nodes are not in the state; // data nodes may have been merged if (stateVertex == null) { continue; } AspectJVertex graphVertex = startModel.getJCellForNode(node); stateVertex.putVisuals(graphVertex.getVisuals()); stateVertex.setGrayedOut(graphVertex.isGrayedOut()); result.synchroniseLayout(stateVertex); stateVertex.setLayoutable(false); } for (AspectEdge edge : startGraph.edgeSet()) { AspectJCell stateEdge = result.getJCellForEdge(edge); // meta edges and merged data edges are not in the state if (stateEdge == null) { continue; } AspectJCell graphEdge = startModel.getJCellForEdge(edge); stateEdge.putVisuals(graphEdge.getVisuals()); stateEdge.setGrayedOut(graphEdge.isGrayedOut()); result.synchroniseLayout(stateEdge); } } /** Creates a j-model for a given aspect graph. */ private AspectJModel createAspectJModel(AspectGraph graph) { AspectJModel result = getJGraph().newModel(); result.loadGraph(graph); return result; } /** Convenience method to retrieve the current grammar view. */ private GrammarModel getGrammar() { return getSimulatorModel().getGrammar(); } /** * Returns the aspect map for a given state. * Retrieves the result from {@link #stateToAspectMap}, * creating and inserting it if necessary. */ private HostToAspectMap getAspectMap(GraphState state) { HostToAspectMap result = this.stateToAspectMap.get(state); if (result == null) { this.stateToAspectMap.put(state, result = GraphConverter.toAspectMap(state.getGraph())); } return result; } /** * Mapping from graphs to the corresponding graph models. */ private final Map<GraphState,AspectJModel> stateToJModel = new WeakHashMap<>(); /** * Mapping from graphs to the corresponding graph models. */ private final Map<GraphState,HostToAspectMap> stateToAspectMap = new WeakHashMap<>(); /** Flag indicating that the listeners are activated. */ private boolean listening; private GraphSelectionListener graphSelectionListener; /** Flag indicating if there is any match selected. */ private boolean matchSelected; /** Temporary record of graph element attributes. */ private static class Attributes { Attributes(AspectJVertex jVertex) { VisualMap visuals = jVertex.getVisuals(); this.pos = visuals.getNodePos(); this.grayedOut = jVertex.isGrayedOut(); this.color = visuals.getColor(); this.points = null; this.labelPosition = null; this.lineStyle = null; } Attributes(Color color) { this.pos = null; this.grayedOut = false; this.color = color; this.points = null; this.labelPosition = null; this.lineStyle = LineStyle.DEFAULT_VALUE; } Attributes(AspectJEdge jEdge) { VisualMap visuals = jEdge.getVisuals(); this.pos = null; this.grayedOut = jEdge.isGrayedOut(); this.color = null; this.points = visuals.getPoints(); this.labelPosition = visuals.getLabelPos(); this.lineStyle = visuals.getLineStyle(); } VisualMap toVisuals() { VisualMap result = new VisualMap(); if (this.pos != null) { result.setNodePos(this.pos); } if (this.color != null) { result.setColor(this.color); } if (this.points != null) { result.setPoints(this.points); } if (this.labelPosition != null) { result.setLabelPos(this.labelPosition); } if (this.lineStyle != null) { result.setLineStyle(this.lineStyle); } return result; } final Point2D pos; Color color; final boolean grayedOut; final List<Point2D> points; final Point2D labelPosition; final LineStyle lineStyle; } /** Mapping from host elements to attributes. */ private static class AttributesMap { final Map<HostNode,Attributes> nodeMap = new HashMap<>(); final Map<HostEdge,Attributes> edgeMap = new HashMap<>(); } }
Dabble-of-DevOps-Bio/ella
src/webui/src/js/store/modules/views/workflows/actions/getReferences.js
import processReferences from '../../../../common/helpers/processReferences' import { getReferencesIdsForAllele } from '../../../../common/helpers/reference' function getReferences({ http, path, state }) { let alleles = state.get('views.workflows.interpretation.data.alleles') // Get all reference ids from alleles let ids = [] let pubmedIds = [] for (let allele of Object.values(alleles)) { if (allele.annotation.references) { for (let ref of allele.annotation.references) { if (ref.id) { ids.push(ref.id) } else if (ref.pubmed_id) { pubmedIds.push(ref.pubmed_id) } } } } ids = [...new Set(ids)] pubmedIds = [...new Set(pubmedIds)] let refById = http.get(`references/`, { q: JSON.stringify({ id: ids }) }) let refByPmid = http.get(`references/`, { q: JSON.stringify({ pubmed_id: pubmedIds }) }) let references = [] return Promise.all([refById, refByPmid]) .then((args) => { let [refId, refByPmid] = args references = new Set(refId.result.concat(refByPmid.result)) }) .then((response) => { processReferences(references) let result = {} for (let r of references) { result[r.id] = r } return path.success({ result: result }) }) .catch((response) => { return path.error({ result: response.result }) }) } export default getReferences
UCLA-SEAL/RefFinder
Ref-Finder/code/metapackage/MetaInfo.java
/* * Ref-Finder * Copyright (C) <2015> <PLSE_UCLA> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package metapackage; import java.io.File; import lsclipse.LSclipse; import org.eclipse.core.runtime.IPath; public class MetaInfo { public static final int k = 1; public static final int minConcFact = 3; public static final int beamSize = 100; public static final double accuracy = 0.75D; public static final int maxException = 10; public static final String baseDir = LSclipse.getDefault().getStateLocation().toOSString(); public static final File srcDir = new File(baseDir, "input"); public static final File resDir = new File(baseDir, "output"); public static final File fdbDir = new File(baseDir, "fdb"); public static final File lsclipseDir = new File(srcDir, "lsclipse"); public static final File included2kb = new File(srcDir, "2KB_lsdPred.rub"); public static final File includedDelta = new File(srcDir, "deltaKB_lsdPred.rub"); public static final String winnowings = new File(srcDir, "winnowingRules.rub").getAbsolutePath(); public static final String modifiedWinnowings = new File(srcDir, "convertedwinnowingRules.rub").getAbsolutePath(); public static final String lsclipse2KB = new File(lsclipseDir, "2KB_lsclipsePred.rub").getAbsolutePath(); public static final String lsclipseDelta = new File(lsclipseDir, "deltaKB_lsclipsePred.rub").getAbsolutePath(); public static final String lsclipseRefactorPred = new File(lsclipseDir, "preds1.rub").getAbsolutePath(); public static final String lsclipseRefactorDeltaPrimed = new File(lsclipseDir, "deltaKB_primed_lsdPred.rub").getAbsolutePath(); public static final String resultsFile = new File(resDir, "Hierarchical_lsclipse_Temp.rub").getAbsolutePath(); public static final String ongoingResultsFile = new File(resDir, "exmp.rub").getAbsolutePath(); public static final String refsOnlyFile = new File(resDir, "output.rub").getAbsolutePath(); }
toywar94/Swime
src/main/java/com/swime/util/NoticeHandler.java
//package com.swime.util; // //import lombok.extern.log4j.Log4j; //import org.springframework.context.annotation.Bean; //import org.springframework.security.core.Authentication; //import org.springframework.security.core.context.SecurityContextHolder; //import org.springframework.web.bind.annotation.RequestMapping; //import org.springframework.web.socket.TextMessage; //import org.springframework.web.socket.WebSocketSession; //import org.springframework.web.socket.handler.TextWebSocketHandler; // //import java.util.Map; //import java.util.concurrent.ConcurrentHashMap; // //@Log4j //public class NoticeHandler extends TextWebSocketHandler { // // // 로그인중인 유저 // Map<String, WebSocketSession> users = new ConcurrentHashMap<>(); // // // 클라이언트가 서버로 연결시 // @Override // public void afterConnectionEstablished(WebSocketSession session) throws Exception { // // log.info("연결됨"); // log.info(session.getPrincipal().getName() + "님이 연결되었습니다."); // //// // 접속한 유저의 정보를 받아오기 //// Authentication auth = SecurityContextHolder.getContext().getAuthentication(); //// //// String userId = auth.getName(); //// //// log.info("접속했네요."); //// log.info("userId = " + userId); // // // 로그인중인 유저의 웹소켓 세션정보를 저장 // } // // 클라이언트가 Data 전송시 // @Override // protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { // super.handleTextMessage(session, message); // } //}
1162242970/Bill
app/src/main/java/com/felix/simplebook/activity/sign/ISignListener.java
package com.felix.simplebook.activity.sign; /** * Created by android on 18-5-24. */ public interface ISignListener { void onSignInSuccess(); void onSignInFailed(); void onSignUpSuccess(); void onSignUpFailed(); }
markusbuchholz/Cpp-High-Performance-Second-Edition
Chapter08/constexpr_if_mod.cpp
#if _MSC_VER #pragma warning(disable : 4244) #endif #include <gtest/gtest.h> #include <cmath> #include <type_traits> template <typename T> auto generic_mod(const T& v, const T& n) -> T { assert(n != 0); if (std::is_floating_point_v<T>) { return std::fmod(v, n); } else { return v % n; // if T is a floating point, this line wont compile } } template <typename T> auto constexpr_if_generic_mod(const T& v, const T& n) -> T { assert(n != 0); if constexpr (std::is_floating_point_v<T>) { return std::fmod(v, n); } else { // If T is a floating point, return v % n; // this code is eradicated } } TEST(ConstexprIfMod, ModOfInts) { auto const value = 7; auto const modulus = 5; auto const result = generic_mod(value, modulus); auto const constexpr_if_result = constexpr_if_generic_mod(value, modulus); ASSERT_EQ(constexpr_if_result, result); } TEST(ConstexprIfMod, ModOfFloats) { auto const value = 1.5f; auto const modulus = 1.0f; // Compilation error % operation for float value // auto const result = generic_mod(value, modulus); auto const constexpr_if_result = constexpr_if_generic_mod(value, modulus); ASSERT_FLOAT_EQ(0.5f, constexpr_if_result); }
comqdhb/JSFML
src/java/org/jsfml/graphics/Glyph.java
package org.jsfml.graphics; /** * Describes a glyph in a {@link Font}. * * @see Font */ public final class Glyph { /** * The offset to move horizontally to the next character. */ public final int advance; /** * The bounding rectangle of the glyph, in coordinates relative to the baseline. */ public final IntRect bounds; /** * The texture coordinates of the glyph on the font's texture. */ public final IntRect textureRect; /** * Constructs a glyph with the specified parameters. * <p/> * Note that this constructor is reserved for internal use and should * never be required to be used directly. Glyphs should be obtained * using the {@link Font#getGlyph(int, int, boolean)} method. * * @param advance the offset to move horizontally to the next character. * @param bounds the boundaries of the glyph. * @param textureRect the texture rectangle used by the glyph. * @see Font#getGlyph(int, int, boolean) */ public Glyph(int advance, IntRect bounds, IntRect textureRect) { this.advance = advance; this.bounds = bounds; this.textureRect = textureRect; } }
8osm/AtomMC
src/main/java/net/minecraft/client/gui/recipebook/IRecipeShownListener.java
<reponame>8osm/AtomMC<filename>src/main/java/net/minecraft/client/gui/recipebook/IRecipeShownListener.java package net.minecraft.client.gui.recipebook; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public interface IRecipeShownListener { void recipesUpdated(); GuiRecipeBook func_194310_f(); }
backtory/neveshtanak
src/ir/pegahtech/saas/client/shared/enums/UserDirection.java
<reponame>backtory/neveshtanak<filename>src/ir/pegahtech/saas/client/shared/enums/UserDirection.java package ir.pegahtech.saas.client.shared.enums; public enum UserDirection { From(1),To(2),Both(3); private final int val; private UserDirection(int val){ this.val = val; } public int getVal(){ return val; } }
mateusmarinho/python3-cursoemvideo
PythonExercicios/08-listas/ex083.py
'''Crie um programa onde o usuário digite uma expressão qualquer que use parênteses. Seu aplicativo deverá analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta.''' expressao = input('Digite a expressão: ') pilha = [] for simb in expressao: if simb == '(': pilha.append('(') elif simb == ')': if len(pilha) > 0: pilha.pop() else: pilha.append(')') break if len(pilha) == 0: print('Sua expressão está válida!') else: print('Sua expressão não está válida!')
RodSalg/PROJECTS-IN-C--AEDI-AND-AEDII-
aed2 codebench/lista10/questao1.c
<reponame>RodSalg/PROJECTS-IN-C--AEDI-AND-AEDII-<gh_stars>1-10 #include <stdio.h> #include <stdlib.h> // a tabela funciona agora vou aperfeiçoar para utilizar na q1 // // constante que representa o tamanho da tabela //#define M 99 typedef struct { int matricula; } Pessoa; // inicializa a tabela com esse valor porque saberei que posição está preenchida ou nao void inicializarTabela(Pessoa tabelaHash[], int M) { int i; for (i = 0; i < M; i++) { tabelaHash[i].matricula = -1; // marcamos através da matrícula } } // funcao de espalhamento // vai receber a matrícula e gerar um código para salvar o elemento pessoa int gerarCodigoHash(int chave, int M) { return chave % M; // recebe a chave e retorna o resto da divisao da chave por M; } // inserir uma pessoa na tabela; void inserir(Pessoa tabelaHash[], int mat, int M) { Pessoa pes; pes.matricula = mat; int indice = gerarCodigoHash(pes.matricula, M); while (tabelaHash[indice].matricula != -1) { indice = gerarCodigoHash(indice + 1, M); } tabelaHash[indice] = pes; } Pessoa *buscar(Pessoa tabelaHash[], int chave, int M) { int indice = gerarCodigoHash(chave, M); while (tabelaHash[indice].matricula != -1) { if (tabelaHash[indice].matricula == chave) { return &tabelaHash[indice]; } else { indice = gerarCodigoHash(indice + 1, M); } } return NULL; } void imprimir( Pessoa tabelaHash[], int M) { int i; for (i = 0; i < M; i++) { if (tabelaHash[i].matricula != -1) { printf("%d %d\n", i, tabelaHash[i].matricula); } else { printf("%d null \n", i); } } } int main() { int tam; scanf("%d", &tam); int num; Pessoa tabelaHash[tam]; inicializarTabela(tabelaHash, tam); scanf("%d", &num); while (num != 0) { inserir(tabelaHash, num, tam); scanf("%d", &num); } imprimir(tabelaHash, tam); }
jainvikas8/trusted-firmware-m
platform/ext/target/cypress/psoc64/libs/mtb-pdl-cat1/docs/pdl_api_reference_manual/html/group__group__crypto__lld__vu.js
<filename>platform/ext/target/cypress/psoc64/libs/mtb-pdl-cat1/docs/pdl_api_reference_manual/html/group__group__crypto__lld__vu.js<gh_stars>1-10 var group__group__crypto__lld__vu = [ [ "Functions", "group__group__crypto__lld__vu__functions.html", "group__group__crypto__lld__vu__functions" ] ];
vanncho/SurviveSoftUni
src/game/models/DumbZombie.java
<reponame>vanncho/SurviveSoftUni package game.models; import game.staticData.Constants; import game.models.interfaces.RandomDirectionMovable; import game.sprites.ImageLoader; import game.sprites.SpriteAnimation; import javafx.geometry.Rectangle2D; import javafx.scene.image.ImageView; import javafx.util.Duration; public class DumbZombie extends EnemyImpl implements RandomDirectionMovable { private final int SPRITE_COUNT = 4; private final int SPRITE_COLUMNS = 4; private final int SPRITE_OFFSET_X = 0; private final int SPRITE_OFFSET_Y = 0; private final int SPRITE_WIDTH = 64; private final int SPRITE_HEIGHT = 64; private char moveDirection; // For use of randomised movement public DumbZombie(int setTranslateX, int setTranslateY) { super(setTranslateX, setTranslateY); //Image info this.setSpriteCount(SPRITE_COUNT); this.setSpriteColumns(SPRITE_COLUMNS); this.setSpriteOffsetX(SPRITE_OFFSET_X); this.setSpriteOffsetY(SPRITE_OFFSET_Y); this.setSpriteWidth(SPRITE_WIDTH); this.setSpriteHeight(SPRITE_HEIGHT); this.setObjectSize(Constants.ZOMBIE_SIZE); this.setEnemyImageView(new ImageView(ImageLoader.DUMB_ZOMBIE_IMAGE)); this.getEnemyImageView().setFitHeight(Constants.ZOMBIE_SIZE); this.getEnemyImageView().setFitWidth(Constants.ZOMBIE_SIZE); this.getEnemyImageView().setViewport(new Rectangle2D(this.getSpriteOffsetX(), this.getSpriteOffsetY(), this.getSpriteWidth(), this.getSpriteHeight())); this.setAnimation(new SpriteAnimation(this.getEnemyImageView(), Duration.millis(1000), this.getSpriteCount(), this.getSpriteColumns(), this.getSpriteOffsetX(), this.getSpriteOffsetY(), this.getSpriteWidth(), this.getSpriteHeight())); getChildren().addAll(this.getEnemyImageView()); this.setBoundingBox(calcBoundingBox(Constants.ZOMBIE_SIZE)); this.setHealth(Constants.ZOMBIE_HEALTH); //Regular cell to cell movement this.setIsCentered(false); this.setAllowNextCellMove(false); //Random movement this.setMoveDirection('U'); } @Override public char getMoveDirection() { return this.moveDirection; } private void setMoveDirection(char moveDirection) { this.moveDirection = moveDirection; } @Override public void changeMoveDirection(char moveDirection) { this.setMoveDirection(moveDirection); } }
matty-matt/movie-keeper-core
trailer-service/src/main/java/com/kociszewski/moviekeeper/infrastructure/TrailerController.java
package com.kociszewski.moviekeeper.infrastructure; import com.kociszewski.moviekeeper.domain.queries.GetTrailersQuery; import lombok.RequiredArgsConstructor; import org.axonframework.messaging.responsetypes.ResponseTypes; import org.axonframework.queryhandling.QueryGateway; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequiredArgsConstructor @RequestMapping("/movies/{movieId}/videos") public class TrailerController { private final QueryGateway queryGateway; @GetMapping public List<TrailerDTO> trailers(@PathVariable("movieId") String movieId) { return queryGateway.query( new GetTrailersQuery(movieId), ResponseTypes.multipleInstancesOf(TrailerDTO.class)).join(); } }
wdlkmpx/fsp
bsd_src/function.c
/*- * Copyright (c) 1990 The Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * <NAME> of the University of California, Berkeley. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. */ #include "tweak.h" #ifdef HAVE_UNISTD_H #ifndef __hpux #include <unistd.h> #endif #endif #include <stdio.h> #include <stdlib.h> #include "my-string.h" #include <sys/types.h> #include <sys/stat.h> #include <sys/param.h> #ifdef _POSIX_SOURCE #include "limits.h" #if !defined(MAXPATHLEN) && defined(PATH_MAX) #define MAXPATHLEN PATH_MAX #endif #endif #ifdef HAVE_TZFILE_H #include <tzfile.h> #endif #include "common_def.h" #include "client_def.h" #include "c_extern.h" #ifdef TIME_WITH_SYS_TIME # include <sys/time.h> # include <time.h> #else # ifdef HAVE_SYS_TIME_H # include <sys/time.h> # else # include <time.h> # endif #endif #ifdef HAVE_SYS_WAIT_H #include <sys/wait.h> #endif #ifndef WEXITSTATUS #define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8) #endif #ifndef WIFEXITED #define WIFEXITED(stat_val) (((stat_val) & 255) == 0) #endif #include "find.h" #define FIND_EQUAL 0 #define FIND_LESSTHAN 1 #define FIND_GREATER 2 #define COMPARE(a, b) { \ switch(plan->flags) { \ case FIND_EQUAL: \ return(a == b); \ case FIND_LESSTHAN: \ return(a < b); \ case FIND_GREATER: \ return(a > b); \ } \ return(0); \ } static PLAN *palloc (enum ntype t, int (*f)()) { PLAN *new; new = (PLAN *) malloc(sizeof(PLAN)); if ( new ) { new->type = t; new->eval = f; new->flags = 0; new->next = NULL; return(new); } perror("palloc"); exit(EX_OSERR); } extern int isoutput; extern int process; /* * find_parsenum -- * Parse a string of the form [+-]# and return the value. */ static long find_parsenum (PLAN * plan, const char * option, char * str, char * endch) { long value; char *endchar; /* pointer to character ending conversion */ /* determine comparison from leading + or - */ switch(*str) { case '+': ++str; plan->flags = FIND_GREATER; break; case '-': ++str; plan->flags = FIND_LESSTHAN; break; default: plan->flags = FIND_EQUAL; break; } /* * convert the string with strtol(). Note, if strtol() returns zero * and endchar points to the beginning of the string we know we have * a syntax error. */ value = strtol(str, &endchar, 10); if ( (!value && endchar == str) || (endchar[0] && (!endch || endchar[0] != *endch))) { fprintf(stderr,"%s: %s", option, "illegal numeric value"); exit(EX_USAGE); } if (endch) *endch = endchar[0]; return(value); } /* * -time n functions -- * * True if the difference between the file time and the * current time is n 24 hour periods. * */ extern time_t now; static int find_time (PLAN * plan, struct stat * sbuf, char * path) { /* with FSP sbuf.st_atime=sbuf.st_ctime=sbuf.st_mtime */ COMPARE((now - sbuf->st_atime + SECSPERDAY - 1) / SECSPERDAY, plan->t_data); } PLAN * c_time (char * arg) { PLAN *new; new = palloc(N_TIME, find_time); new->t_data = find_parsenum(new, "-time", arg, NULL); return(new); } /* * brace_subst -- * Replace occurrences of {} in s1 with s2 and return the result string. */ static void brace_subst (char * orig, char ** store, char * path, int len) { register int plen; register char ch, *p; plen = strlen(path); for (p = *store; (ch = *orig) ; ++orig) if (ch == '{' && orig[1] == '}') { while ((p - *store) + plen > len) if (!(*store = (char *)realloc(*store, len *= 2))) { perror("realloc"); client_done(); exit(EX_OSERR); } memmove(p,path,plen); p += plen; ++orig; } else *p++ = ch; *p = '\0'; } /* * queryuser -- * print a message to standard error and then read input from standard * input. If the input is 'y' then 1 is returned. */ static int queryuser (char ** argv) { int ch, first, nl; fprintf(stderr, "\"%s", *argv); while (*++argv) fprintf(stderr, " %s", *argv); fprintf(stderr, "\"? "); fflush(stderr); first = ch = getchar(); for (nl = 0;;) { if (ch == '\n') { nl = 1; break; } if (ch == EOF) break; ch = getchar(); } if (!nl) { fprintf(stderr, "\n"); fflush(stderr); } return(first == 'y'); } /* * [-exec | -ok] utility [arg ... ] ; functions -- * * True if the executed utility returns a zero value as exit status. * The end of the primary expression is delimited by a semicolon. If * "{}" occurs anywhere, it gets replaced by the current pathname. * The current directory for the execution of utility is the same as * the current directory when the find utility was started. * * The primary -ok is different in that it requests affirmation of the * user before executing the utility. */ static int find_exec (PLAN * plan, struct stat * sbuf, char * path) { register int cnt; pid_t pid; #ifndef HAVE_UNION_WAIT int status; #else union wait status; #endif for (cnt = 0; plan->e_argv[cnt]; ++cnt) if (plan->e_len[cnt]) brace_subst(plan->e_orig[cnt], &plan->e_argv[cnt], path, plan->e_len[cnt]); if (plan->flags && !queryuser(plan->e_argv)) return(0); switch(pid = fork()) { case -1: perror ("fork"); exit(EX_OSERR); case 0: execvp(plan->e_argv[0], plan->e_argv); perror ("execvp"); exit(EX_OSERR); } pid = wait(&status); return(pid != -1 && WIFEXITED(status) && !WEXITSTATUS(status)); } static char *emalloc_ffind (unsigned int len) { char *p; if ( (p = (char *)malloc(len))) return((char *)p); perror("malloc"); exit(EX_OSERR); } /* * c_exec -- * build three parallel arrays, one with pointers to the strings passed * on the command line, one with (possibly duplicated) pointers to the * argv array, and one with integer values that are lengths of the * strings, but also flags meaning that the string has to be massaged. */ PLAN *c_exec (char *** argvp, int isok) { PLAN *new; /* node returned */ register int cnt; register char **argv, **ap, *p; isoutput = 1; new = palloc(N_EXEC, find_exec); new->flags = isok; for (ap = argv = *argvp;; ++ap) { if (!*ap) { fprintf(stderr,"%s: no terminating", isok ? "-ok" : "-exec"); exit(EX_USAGE); } if (**ap == ';') break; } cnt = ap - *argvp + 1; new->e_argv = (char **)emalloc_ffind((unsigned int)cnt * sizeof(char *)); new->e_orig = (char **)emalloc_ffind((unsigned int)cnt * sizeof(char *)); new->e_len = (int *)emalloc_ffind((unsigned int)cnt * sizeof(int)); for (argv = *argvp, cnt = 0; argv < ap; ++argv, ++cnt) { new->e_orig[cnt] = *argv; for (p = *argv; *p; ++p) if (p[0] == '{' && p[1] == '}') { new->e_argv[cnt] = (char *)emalloc_ffind((unsigned int)MAXPATHLEN); new->e_len[cnt] = MAXPATHLEN; break; } if (!*p) { new->e_argv[cnt] = *argv; new->e_len[cnt] = 0; } } new->e_argv[cnt] = new->e_orig[cnt] = NULL; *argvp = argv + 1; return(new); } static void printtime_ffind (time_t ftime) { int i; char *longstring; longstring = (char *)ctime(&ftime); for (i = 4; i < 11; ++i) putchar(longstring[i]); #define SIXMONTHS ((DAYSPERNYEAR / 2) * SECSPERDAY) if (ftime + SIXMONTHS > time((time_t *)NULL)) for (i = 11; i < 16; ++i) putchar(longstring[i]); else { (void)putchar(' '); for (i = 20; i < 24; ++i) putchar(longstring[i]); } putchar(' '); } #define BLK(A) (((A)+1023)/1024) static void printlong_ffind (char * name, struct stat * sb) { const char *modep; printf("%4ld ", (long)BLK(sb->st_size)); modep = ((S_IFDIR & sb->st_mode)) ? "drwxrwxrwx" : "-rw-rw-rw-" ; printf("%s %3u %-*s %-*s ", modep, (unsigned int)sb->st_nlink, 8, "nobody", 8, "nobody"); printf("%8ld ", (long)sb->st_size); printtime_ffind(sb->st_mtime); printf("%s", name); putchar('\n'); } /* * -ls functions -- * * Always true - prints the current sbuf to stdout in "ls" format. */ static int find_ls (PLAN * plan, struct stat * sbuf, char * path) { printlong_ffind(path, sbuf); return(1); } PLAN *c_ls (void) { isoutput = 1; return(palloc(N_LS, find_ls)); } /* * -name functions -- * * True if the basename of the filename being examined * matches pattern using Pattern Matching Notation S3.14 */ static int find_name (PLAN * plan, struct stat * sbuf, char * path) { register char *name; /* extract filename */ for (name = path + strlen(path); name > path && *name != '/'; name--); if (*name == '/') name++; return (fnmatch(plan->c_data, name, 0)); } PLAN *c_name (char * pattern) { PLAN *new; new = palloc(N_NAME, find_name); new->c_data = pattern; return(new); } /* * -newer file functions -- * * True if the current file has been modified more recently * then the modification time of the file named by the pathname * file. */ static int find_newer (PLAN * plan, struct stat * sbuf, char * path) { return(sbuf->st_mtime > plan->t_data); } PLAN *c_newer (char * filename) { PLAN *new; struct stat sb; if (stat(filename, &sb)) { perror("stat"); exit(EX_NOINPUT); } new = palloc(N_NEWER, find_newer); new->t_data = sb.st_mtime; return(new); } /* * -print functions -- * * Always true, causes the current pathame to be written to * standard output. */ static int find_print (PLAN * plan, struct stat * sbuf, char * path) { (void)printf("%s\n", path); return(1); } PLAN *c_print (void) { isoutput = 1; return(palloc(N_PRINT, find_print)); } /* * -prune functions -- * * Prune a portion of the hierarchy. */ static int find_prune (PLAN * plan, struct stat * sbuf, char * path) { process = -1; return(1); } PLAN *c_prune (void) { return(palloc(N_PRUNE, find_prune)); } /* * -size n[c] functions -- * * True if the file size in bytes, divided by an implementation defined * value and rounded up to the next integer, is n. If n is followed by * a c, the size is in bytes. */ #define FIND_SIZE 512 static int divsize = 1; static int find_size (PLAN * plan, struct stat * sbuf, char * path) { off_t size; size = divsize ? ((sbuf->st_size + FIND_SIZE - 1)/FIND_SIZE) : sbuf->st_size; COMPARE(size, plan->o_data); } PLAN *c_size (char * arg) { PLAN *new; char endch='c'; new = palloc(N_SIZE, find_size); new->o_data = find_parsenum(new, "-size", arg, &endch); if (endch == 'c') divsize = 0; return(new); } /* * -type c functions -- * * True if the type of the file is c, where c is d or f for * directory or regular file, respectively. */ static int find_type (PLAN * plan, struct stat * sbuf, char * path) { return((sbuf->st_mode & S_IFMT) == plan->m_data); } PLAN *c_type (char * typestring) { PLAN *new; mode_t mask; switch (typestring[0]) { case 'd': mask = S_IFDIR; break; case 'f': mask = S_IFREG; break; default: fprintf(stderr,"-type: unknown type"); exit(EX_USAGE); } new = palloc(N_TYPE, find_type); new->m_data = mask; return(new); } /* * ( expression ) functions -- * * True if expression is true. */ int find_expr (PLAN * plan, struct stat * sbuf, char * path) { register PLAN *p; register int state; for(p=plan->p_data[0]; p && (state=(p->eval)(p, sbuf, path)); p=p->next); return(state); } /* * N_OPENPAREN and N_CLOSEPAREN nodes are temporary place markers. They are * eliminated during phase 2 of find_formplan() --- the '(' node is converted * to a N_EXPR node containing the expression and the ')' node is discarded. */ PLAN *c_openparen (void) { return(palloc(N_OPENPAREN, (int (*)())-1)); } PLAN *c_closeparen (void) { return(palloc(N_CLOSEPAREN, (int (*)())-1)); } /* * ! expression functions -- * * Negation of a primary; the unary NOT operator. */ static int find_not (PLAN * plan, struct stat * sbuf, char * path) { register PLAN *p; register int state; for(p=plan->p_data[0]; p && (state=(p->eval)(p, sbuf, path)); p=p->next); return(!state); } PLAN *c_not (void) { return(palloc(N_NOT, find_not)); } /* * expression -o expression functions -- * * Alternation of primaries; the OR operator. The second expression is * not evaluated if the first expression is true. */ static int find_or (PLAN * plan, struct stat * sbuf, char * path) { register PLAN *p; register int state; for(p=plan->p_data[0]; p && (state=(p->eval)(p, sbuf, path)); p=p->next); if (state) return(1); for(p=plan->p_data[1]; p && (state=(p->eval)(p, sbuf, path)); p=p->next); return(state); } PLAN *c_or (void) { return(palloc(N_OR, find_or)); }
kyzyx/scanalyze
ProxyScan.h
// ProxyScan.h placeholder for unloaded scans // created 3/12/99 <NAME> (<EMAIL>) #ifndef _PROXYSCAN_H_ #define _PROXYSCAN_H_ #include "RigidScan.h" class ProxyScan: public RigidScan { public: // ProxyScan manipulation ProxyScan (const crope& proxyForFileName, const Pnt3& min, const Pnt3& max); ~ProxyScan(); public: // RigidScan methods: // Display virtual MeshTransport* mesh(bool perVertex = true, bool stripped = true, ColorSource color = colorNone, int colorSize = 3); virtual crope getInfo(void); virtual unsigned long byteSize() { return sizeof(ProxyScan); } }; #endif // _PROXYSCAN_H_
abhay-lal/18CSC207J-APP
Exercise-3/06.py
class Banks_SRMIST: def getBalance(): return 0 class CUB(Banks_SRMIST): def getBalance(balance): return balance class HDFC(Banks_SRMIST): def getBalance(balance): return balance class Indian_Bank(Banks_SRMIST): def getBalance(balance): return balance Banks_SRMIST() print(CUB.getBalance(15000)) print(HDFC.getBalance(30000)) print(Indian_Bank.getBalance(40000))
msimar/gravity
Core/src/main/java/org/zalando/core/utils/SnackBarBuilder.java
package org.zalando.core.utils; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Color; import android.support.annotation.ColorRes; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import java.util.Arrays; import org.zalando.core.R; /** * Untils to create and display a {@link Snackbar} */ public class SnackBarBuilder { private final View parentView; private String text; private String buttonText; private int textColor; private int maxLines; private int backgroundColorRes; private int actionColorRes; private Runnable action; private int duration = Snackbar.LENGTH_SHORT; /** * Constructor for the builder * * @param parentView {@link View} parentView of the snackBar */ public SnackBarBuilder(@NonNull View parentView) { this.parentView = parentView; } /** * Set text for the SnackBar * * @param charSequence {@link CharSequence} text to set * @return {@link SnackBarBuilder} to continue building SnackBar */ public SnackBarBuilder setText(@NonNull CharSequence charSequence) { text = charSequence.toString(); return this; } /** * Set text for the SnackBar * * @param stringRes {@link StringRes} text from String to set * @return {@link SnackBarBuilder} to continue building SnackBar */ public SnackBarBuilder setText(@StringRes int stringRes) { text = parentView.getContext().getString(stringRes); return this; } /** * Set background color for the SnackBar * * @param colorRes {@link StringRes} color to set * @return {@link SnackBarBuilder} to continue building SnackBar */ public SnackBarBuilder setBackgroundColor(@ColorRes int colorRes) { this.backgroundColorRes = colorRes; return this; } /** * Set action color for the SnackBar * * @param colorRes {@link StringRes} color to set * @return {@link SnackBarBuilder} to continue building SnackBar */ public SnackBarBuilder setActionColor(@ColorRes int colorRes) { this.actionColorRes = colorRes; return this; } /** * Set action color for the SnackBar * * @param onClickAction {@link StringRes} action to perform when click * @return {@link SnackBarBuilder} to continue building SnackBar */ public SnackBarBuilder setOnClickAction(@NonNull Runnable onClickAction) { this.action = onClickAction; return this; } /** * Set duration of the SnackBar * * @param duration to set * @return {@link SnackBarBuilder} to continue building SnackBar */ public SnackBarBuilder setDuration(@Snackbar.Duration int duration) { this.duration = duration; return this; } /** * Set text for SnackBar button * * @param buttonText {@link CharSequence} to set * @return {@link SnackBarBuilder} to continue building SnackBar */ public SnackBarBuilder setButtonText(@NonNull CharSequence buttonText) { this.buttonText = buttonText.toString(); return this; } /** * Set text for the SnackBar button * * @param stringRes {@link StringRes} text from String to set * @return {@link SnackBarBuilder} to continue building SnackBar */ public SnackBarBuilder setButtonText(@StringRes int stringRes) { this.buttonText = parentView.getContext().getString(stringRes); return this; } /** * Set text color for the SnackBar button * * @param colorRes {@link ColorRes} color to set * @return {@link SnackBarBuilder} to continue building SnackBar */ public SnackBarBuilder setTextColor(@ColorRes int colorRes) { this.textColor = colorRes; return this; } /** * Set max line of text for snackbar * * @param maxLines to set * @return {@link SnackBarBuilder} to continue building SnackBar */ public SnackBarBuilder setMaxLines(int maxLines) { this.maxLines = maxLines; return this; } /** * Build and display the snackbar. */ public Snackbar build() { Preconditions.checkNotNull(text, "SnackBar text has not been set"); final Snackbar snackbar = Snackbar.make(parentView, text, duration); styleSnackbar(parentView.getContext(), snackbar); if (action != null) { snackbar.setAction(buttonText, new OnClickListener() { @Override public void onClick(View v) { action.run(); } }); if (actionColorRes != 0) { snackbar.setActionTextColor(ContextCompat.getColor(parentView.getContext(), actionColorRes)); } } if (backgroundColorRes != 0) { snackbar.getView().setBackgroundColor( ContextCompat.getColor(parentView.getContext(), backgroundColorRes)); } if (textColor != 0) { ((TextView) snackbar.getView().findViewById(R.id.snackbar_text)) .setTextColor(ContextCompat.getColor(parentView.getContext(), textColor)); } if (maxLines != 0) { ((TextView) snackbar.getView().findViewById(R.id.snackbar_text)).setMaxLines(maxLines); } return snackbar; } /** * Styles the given Snackbar based on the styles defined in application styles with a name * "SnackbarStyle". * * @param context {@link Context} * @param snackbar {@link Snackbar} */ @SuppressWarnings("ResourceType") //Solves lint bug private static void styleSnackbar(Context context, Snackbar snackbar) { View snackView = snackbar.getView(); //Get the styles defined in the XML: int[] attrs = {android.R.attr.textColor, android.R.attr.background, android.R.attr.textColorHighlight}; // Sort attrs array to order, to do binary seach. Arrays.sort(attrs); int textColor = Color.BLACK; int actionTextColor = Color.BLACK; int backgroundColor = Color.WHITE; int resID = context.getResources().getIdentifier("SnackbarStyle", "style", context.getPackageName()); //Try to fetch the style attributes try { TypedArray ta = context.getTheme().obtainStyledAttributes(resID, attrs); try { // Fetch the style attributes. Array has to be sorted to fetch the correct value. textColor = ta.getColor(Arrays.binarySearch(attrs, android.R.attr.textColor), Color.BLACK); backgroundColor = ta.getColor(Arrays.binarySearch(attrs, android.R.attr.background), Color.WHITE); actionTextColor = ta.getColor(Arrays.binarySearch( attrs, android.R.attr.textColorHighlight), Color.BLACK); } finally { ta.recycle(); } } catch (Resources.NotFoundException e) { //Attributes could not be found //ignore } //Apply the styles: snackView.setBackgroundColor(backgroundColor); ((TextView) snackView.findViewById(R.id.snackbar_text)) .setTextColor(textColor); snackbar.setActionTextColor(actionTextColor); } }
Nohysiwe/FastAPIBlogBackend
PythonBlog/databases/relationDatabase/orms/uniqueViewORM.py
from .. import DB_BASE as Base from sqlalchemy.dialects.postgresql import TIMESTAMP from sqlalchemy import Column, Integer, Sequence class UniqueViewORM(Base): __tablename__ = 'tb_unique_view' __table_args__ = {'comment': '访问量表'} id = Column(Integer, Sequence("tb_unique_view_id_seq"), primary_key=True, comment='主键id') create_time = Column(TIMESTAMP(precision=0), nullable=False, comment='时间') views_count = Column(Integer, nullable=False, comment='访问量') __all__ = ["UniqueViewORM"]
unity-idm/furms
furms-rest-api/src/main/java/io/imunity/furms/rest/admin/CommunityRestService.java
/* * Copyright (c) 2021 <NAME>.c. All rights reserved. * See LICENSE file for licensing information. */ package io.imunity.furms.rest.admin; import io.imunity.furms.api.communites.CommunityService; import io.imunity.furms.api.community_allocation.CommunityAllocationService; import io.imunity.furms.api.generic_groups.GenericGroupService; import io.imunity.furms.api.projects.ProjectService; import io.imunity.furms.domain.generic_groups.GenericGroup; import io.imunity.furms.domain.generic_groups.GenericGroupId; import io.imunity.furms.rest.error.exceptions.CommunityAllocationRestNotFoundException; import org.springframework.stereotype.Service; import java.util.List; import java.util.UUID; import static java.lang.String.format; import static java.util.stream.Collectors.toList; @Service class CommunityRestService { private final CommunityService communityService; private final ProjectService projectService; private final CommunityAllocationService communityAllocationService; private final ResourceChecker resourceChecker; private final ProjectsRestConverter projectsRestConverter; private final GenericGroupService genericGroupService; CommunityRestService(CommunityService communityService, ProjectService projectService, CommunityAllocationService communityAllocationService, ProjectsRestConverter projectsRestConverter, GenericGroupService genericGroupService) { this.communityService = communityService; this.projectService = projectService; this.communityAllocationService = communityAllocationService; this.resourceChecker = new ResourceChecker(communityService::existsById); this.projectsRestConverter = projectsRestConverter; this.genericGroupService = genericGroupService; } List<Community> findAll() { return communityService.findAllOfCurrentUser().stream() .map(community -> new Community( community, communityAllocationService.findAllByCommunityId(community.getId()))) .collect(toList()); } Community findOneById(String communityId) { return resourceChecker.performIfExists(communityId, () -> communityService.findById(communityId)) .map(community -> new Community( community, communityAllocationService.findAllByCommunityId(communityId))) .get(); } List<Project> findAllProjectsByCommunityId(String communityId) { return resourceChecker.performIfExists(communityId, () -> projectService.findAllByCommunityId(communityId)) .stream() .map(projectsRestConverter::convert) .collect(toList()); } List<CommunityAllocation> findAllocationByCommunityId(String communityId) { resourceChecker.performIfExists(communityId, () -> communityService.findById(communityId)); return communityAllocationService.findAllWithRelatedObjects(communityId).stream() .map(CommunityAllocation::new) .collect(toList()); } CommunityAllocation findAllocationByIdAndCommunityId(String communityAllocationId, String communityId) { return resourceChecker.performIfExists(communityId, () -> communityAllocationService.findByCommunityIdAndIdWithRelatedObjects(communityId, communityAllocationId)) .filter(allocation -> allocation.communityId.equals(communityId)) .map(CommunityAllocation::new) .orElseThrow(() -> new CommunityAllocationRestNotFoundException(format( "Could not locate Community Allocation for provided id=%s and communityId=%s", communityAllocationId, communityId))); } List<CommunityAllocation> addAllocation(String communityId, CommunityAllocationAddRequest request) { resourceChecker.performIfExists(communityId, () -> communityService.findById(communityId)); communityAllocationService.create(io.imunity.furms.domain.community_allocation.CommunityAllocation.builder() .communityId(communityId) .resourceCreditId(request.creditId) .name(request.name) .amount(request.amount) .build()); return findAllocationByCommunityId(communityId); } List<Group> getGroups(String communityId){ return resourceChecker.performIfExists(communityId, () -> genericGroupService.findAll(communityId)).stream() .map(group -> new Group(group.id.id.toString(), group.name, group.description)) .collect(toList()); } GroupWithMembers getGroupWithMember(String communityId, String groupId){ return resourceChecker.performIfExists(communityId, () -> genericGroupService.findGroupWithAssignments(communityId, new GenericGroupId(groupId))) .map(group -> new GroupWithMembers( group.group.id.id.toString(), group.group.name, group.group.description, group.memberships.stream() .map(x -> x.fenixUserId.id) .collect(toList()))) .get(); } void deleteGroup(String communityId, String groupId){ resourceChecker.performIfExists(communityId, () -> genericGroupService.findBy(communityId, new GenericGroupId(groupId))); genericGroupService.delete(communityId, new GenericGroupId(UUID.fromString(groupId))); } Group updateGroup(String communityId, String groupId, GroupDefinitionRequest request){ resourceChecker.performIfExists(communityId, () -> genericGroupService.findBy(communityId, new GenericGroupId(groupId))); genericGroupService.update(GenericGroup.builder() .id(UUID.fromString(groupId)) .communityId(communityId) .name(request.name) .description(request.description) .build()); return new Group(groupId, request.name, request.description); } Group addGroup(String communityId, GroupDefinitionRequest request){ GenericGroupId genericGroupId = genericGroupService.create(GenericGroup.builder() .communityId(communityId) .name(request.name) .description(request.description) .build()); return new Group(genericGroupId.id.toString(), request.name, request.description); } }
kkcookies99/UAST
Dataset/Leetcode/valid/28/130.cpp
class Solution { public: int XXX(string haystack, string needle) { if(needle.size()==0) return 0; if(haystack.size()==0) return -1; int i=0,j=0; while(i<haystack.size()&&j<needle.size()){ if(haystack[i]==needle[j]){ j++; i++; }else{ i-=(j-1); j=0; } //cout<<i<<" "<<j<<endl; } if(j==needle.size()){ return i-needle.size(); } return -1; } };
sanaehirotaka/ark-savegame-toolkit
src/main/java/qowyn/ark/properties/PropertyUnknown.java
<filename>src/main/java/qowyn/ark/properties/PropertyUnknown.java package qowyn.ark.properties; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonNode; import qowyn.ark.ArkArchive; import qowyn.ark.NameSizeCalculator; import qowyn.ark.types.ArkName; public class PropertyUnknown extends PropertyBase<byte[]> { private final ArkName type; public PropertyUnknown(ArkArchive archive, ArkName name, ArkName type) { super(archive, name); this.type = type; value = archive.getBytes(dataSize); } public PropertyUnknown(JsonNode node) { super(node); this.type = ArkName.from(node.path("type").asText()); try { value = node.path("value").binaryValue(); } catch (IOException ex) { throw new UnreadablePropertyException(ex); } } @Override public Class<byte[]> getValueClass() { return byte[].class; } @Override public ArkName getType() { return type; } @Override public int calculateDataSize(NameSizeCalculator nameSizer) { return value.length; } @Override protected void writeBinaryValue(ArkArchive archive) { archive.putBytes(value); } @Override protected void writeJsonValue(JsonGenerator generator) throws IOException { generator.writeBinaryField("value", value); } @Override public final void setValue(byte[] value) { throw new UnsupportedOperationException(); } }
sassoftware/conary
conary_test/webfieldstest.py
# # Copyright (c) SAS Institute Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from conary_test import rephelp from conary.web.fields import intFields, boolFields, strFields from conary.web.fields import listFields, dictFields from conary.web.fields import MissingParameterError, BadParameterError class WebFieldsTest(rephelp.RepositoryHelper): @intFields(thing1 = 1, thing2 = 2, thing3 = None) def decoratedFuncInt(self, thing1, thing2, thing3): return thing1 + thing2 + thing3 @intFields(alpha = 10) @boolFields(beta = None, gamma = False) def decoratedFuncBool(self, alpha, beta, gamma): if (beta and gamma): return alpha * 10 else: return alpha @strFields(back = None, forth = None) def decoratedFuncStr(self, back, forth): return back + forth @listFields(str, shoppingList = [ 'milk', 'cheese', 'chunky bacon' ]) @listFields(str, thingsToTake = None) def decoratedFuncListStr(self, shoppingList, thingsToTake): return 'chunky bacon' in shoppingList @listFields(tuple(((int), (str))), things = [ (1, 'hen'), (2, 'squawking geese'), (3, 'corpulent porpoises') ] ) def decoratedFuncListTuple(self, things): count = 0 for x in things: count += x[0] return count @dictFields(needs = None) def decoratedFuncDict(self, needs): return len(needs) def testIntFields(self): # test default values self.assertEqual(self.decoratedFuncInt(thing3 = 0), 3) # test one default value self.assertEqual(self.decoratedFuncInt(thing2 = 0, thing3 = 2), 3) # test normal usage self.assertEqual(self.decoratedFuncInt(thing1 = 100, thing2 = 50, thing3 = 25), 175) # test for exception if a non-integer is passed in self.assertRaises(BadParameterError, self.decoratedFuncInt, thing1 = 'fofdjk', thing2 = 2, thing3 = 3) # test for exception if an expected parameter is missing self.assertRaises(MissingParameterError, self.decoratedFuncInt, thing1 = 3, thing2 = 1) def testBoolFields(self): # test default values self.assertEqual(self.decoratedFuncBool(beta = 0), 10) # test normal usage self.assertEqual(self.decoratedFuncBool(beta = 1, gamma = 1), 100) # test mixed usage self.assertEqual(self.decoratedFuncBool(alpha = 20, beta = 1, gamma = 1), 200) # test for exception if a non-integer is passed in self.assertRaises(BadParameterError, self.decoratedFuncBool, beta = 'f', gamma = 1) # test for exception if an expected parameter is missing self.assertRaises(MissingParameterError, self.decoratedFuncBool) def testStrFields(self): # test normal operation self.assertEqual(self.decoratedFuncStr(back = 'lati', forth = 'da'), "latida") # test normal operation with an empty string self.assertEqual(self.decoratedFuncStr(back = '', forth = 'da'), "da") # test missing parameter self.assertRaises(MissingParameterError, self.decoratedFuncStr, forth = 'da') def testListStrFields(self): # test defaults self.assertEqual(self.decoratedFuncListStr(thingsToTake = ['hat', 'coat', 'gloves', 'breath mints']), True) # test normal operation self.assertEqual(self.decoratedFuncListStr(shoppingList = [ 'milk' ], thingsToTake = []), False) # test missing parameter self.assertRaises(MissingParameterError, self.decoratedFuncListStr, shoppingList = [ 'beer' ]) def testListTupleFields(self): # test defaults self.assertEqual(self.decoratedFuncListTuple(), 6) # test normal operation self.assertEqual(self.decoratedFuncListTuple(things = []), 0) def testDictFields(self): # test normal operation self.assertEqual(self.decoratedFuncDict(needs = { 'warrior': 'food' }), 1) self.assertEqual(self.decoratedFuncDict(needs = { 'elf': 'food', 'tori': 'neil'}), 2)
tapis-project/notifications
api/src/main/java/edu/utexas/tacc/tapis/notifications/api/responses/RespSubscriptions.java
<reponame>tapis-project/notifications<filename>api/src/main/java/edu/utexas/tacc/tapis/notifications/api/responses/RespSubscriptions.java package edu.utexas.tacc.tapis.notifications.api.responses; import com.google.gson.JsonArray; import edu.utexas.tacc.tapis.notifications.api.responses.results.TapisSubscriptionDTO; import edu.utexas.tacc.tapis.notifications.model.Subscription; import edu.utexas.tacc.tapis.sharedapi.responses.RespAbstract; import edu.utexas.tacc.tapis.sharedapi.responses.results.ResultListMetadata; import java.util.List; /* Results from a retrieval of Subscription resources. */ public final class RespSubscriptions extends RespAbstract { public JsonArray result; public RespSubscriptions(List<Subscription> subscriptionList, int limit, String orderBy, int skip, String startAfter, int totalCount, List<String> selectList) { result = new JsonArray(); for (Subscription subscription : subscriptionList) { result.add(new TapisSubscriptionDTO(subscription).getDisplayObject(selectList)); } ResultListMetadata meta = new ResultListMetadata(); meta.recordCount = result.size(); meta.recordLimit = limit; meta.recordsSkipped = skip; meta.orderBy = orderBy; meta.startAfter = startAfter; meta.totalCount = totalCount; metadata = meta; } }
hao-wang/Montage
js-test-suite/testsuite/77d71a1b426d3d2e825198cbbb11b3e8.js
load("fcfbc86708bc3a4062c2091a062e13b6.js"); load("faa81dc98fc13338aca921d45eebae79.js"); // Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * The production IterationStatement: "for (var VariableDeclarationNoIn in Expression) Statement" * * @path ch12/12.6/12.6.4/S12.6.4_A4.1.js * @description Using Object as an Expression is appropriate. Eval is used */ __str=""; __evaluated = eval("for(var ind in (hash={2:'b',1:'a',4:'d',3:'c'}))__str+=hash[ind]"); ////////////////////////////////////////////////////////////////////////////// //CHECK#1 if ( !( (__evaluated.indexOf("a")!==-1)& (__evaluated.indexOf("b")!==-1)& (__evaluated.indexOf("c")!==-1)&(__evaluated.indexOf("d")!==-1) ) ) { $ERROR('#1: (__evaluated.indexOf("a")!==-1)& (__evaluated.indexOf("b")!==-1)& (__evaluated.indexOf("c")!==-1)&(__evaluated.indexOf("d")!==-1)'); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#2 if (__str !== __evaluated) { $ERROR('#2: __str === __evaluated. Actual: __str ==='+ __str ); } // //////////////////////////////////////////////////////////////////////////////
duke-libraries/dul-hydra
app/controllers/application_controller.rb
require 'dul_hydra' class ApplicationController < ActionController::Base include Blacklight::Controller include Blacklight::Base include Hydra::Controller::ControllerBehavior include Hydra::AccessControlsEnforcement include Ddr::Auth::RoleBasedAccessControlsEnforcement # This applies appropriate access controls to all Blacklight solr queries self.solr_search_params_logic += [:add_access_controls_to_solr_params] protect_from_forgery before_action :authenticate_user! before_action :configure_permitted_parameters, if: :devise_controller? helper_method :group_service helper_method :all_permissions helper_method :find_models_with_gated_discovery helper_method :acting_as_superuser? rescue_from CanCan::AccessDenied do |exception| render file: "#{Rails.root}/public/403", formats: [:html], status: 403, layout: false end protected def acting_as_superuser? signed_in?(:superuser) end def gated_discovery_filters return [] if acting_as_superuser? super end def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email, :password, :remember_me) } end def find_models_with_gated_discovery(model, opts={}) solr_opts = { q: "#{Ddr::IndexFields::ACTIVE_FEDORA_MODEL}:\"#{model.name}\"", fq: gated_discovery_filters.join(" OR "), sort: "#{Ddr::IndexFields::TITLE} ASC", rows: 9999 } solr_opts.merge! opts solr_response = query_solr(solr_opts) solr_results = solr_response.docs ActiveFedora::SolrService.lazy_reify_solr_results(solr_results, load_from_solr: true) end def all_permissions warn "[DEPRECATION] `all_permissions` is deprecated and should not be used with role-based access control." # IMPORTANT - rights controller behavior depends on the permissions being # ordered from lowest to highest so that assignment of multiple permissions # to a user or group results in the highest permission being granted. # No doubt this is really terrible, but there it is. ["discover", "read", "edit"] end end
sho25/activemq
activemq-broker/src/main/java/org/apache/activemq/memory/CacheEntry.java
<gh_stars>0 begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|activemq operator|. name|memory package|; end_package begin_class specifier|public class|class name|CacheEntry block|{ specifier|public specifier|final name|Object name|key decl_stmt|; specifier|public specifier|final name|Object name|value decl_stmt|; specifier|public name|CacheEntry name|next decl_stmt|; specifier|public name|CacheEntry name|previous decl_stmt|; specifier|public name|CacheEntryList name|owner decl_stmt|; specifier|public name|CacheEntry parameter_list|( name|Object name|key parameter_list|, name|Object name|value parameter_list|) block|{ name|this operator|. name|key operator|= name|key expr_stmt|; name|this operator|. name|value operator|= name|value expr_stmt|; block|} comment|/** * @return false if you are trying to remove the tail pointer. */ specifier|public name|boolean name|remove parameter_list|() block|{ comment|// Cannot remove if this is a tail pointer. comment|// Or not linked. if|if condition|( name|owner operator|== literal|null operator||| name|this operator|. name|key operator|== literal|null operator||| name|this operator|. name|next operator|== literal|null condition|) block|{ return|return literal|false return|; block|} synchronized|synchronized init|( name|owner operator|. name|tail init|) block|{ name|this operator|. name|next operator|. name|previous operator|= name|this operator|. name|previous expr_stmt|; name|this operator|. name|previous operator|. name|next operator|= name|this operator|. name|next expr_stmt|; name|this operator|. name|owner operator|= literal|null expr_stmt|; name|this operator|. name|next operator|= literal|null expr_stmt|; name|this operator|. name|previous operator|= literal|null expr_stmt|; block|} return|return literal|true return|; block|} block|} end_class end_unit
aiplan4eu/unified-planning
unified_planning/test/test_partial_order_plan.py
# Copyright 2021 AIPlan4EU project # # 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. import unified_planning as up from unified_planning.shortcuts import * from unified_planning.model.problem_kind import full_classical_kind, full_numeric_kind from unified_planning.test import TestCase, main, skipIfEngineNotAvailable from unified_planning.test.examples import get_example_problems class TestPartialOrderPlan(TestCase): def setUp(self): TestCase.setUp(self) self.problems = get_example_problems() @skipIfEngineNotAvailable('sequential_plan_validator') def test_all(self): with PlanValidator(name='sequential_plan_validator') as validator: assert validator is not None for problem, plan in self.problems.values(): if validator.supports(problem.kind): self.assertTrue(isinstance(plan, up.plans.SequentialPlan)) pop_plan = plan.to_partial_order_plan(problem) for sorted_plan in pop_plan.all_sequential_plans(): validation_result = validator.validate(problem, sorted_plan) self.assertEqual(up.engines.ValidationResultStatus.VALID, validation_result.status)
navikt/fpinfo-historikk
src/main/java/no/nav/foreldrepenger/historikk/tjenester/tilbakekreving/TilbakekrevingMapper.java
<filename>src/main/java/no/nav/foreldrepenger/historikk/tjenester/tilbakekreving/TilbakekrevingMapper.java package no.nav.foreldrepenger.historikk.tjenester.tilbakekreving; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class TilbakekrevingMapper { private static final Logger LOG = LoggerFactory.getLogger(TilbakekrevingMapper.class); private TilbakekrevingMapper() { } static JPATilbakekrevingInnslag fraHendelse(TilbakekrevingHendelse m) { LOG.info("Mapper fra {}", m); var dialog = new JPATilbakekrevingInnslag(); dialog.setYtelseType(m.getYtelseType()); dialog.setInnsendt(m.getOpprettet()); dialog.setAktørId(m.getAktørId()); dialog.setFnr(m.getFnr()); dialog.setSaksnr(m.getSaksnummer()); dialog.setGyldigTil(m.getGyldigTil()); dialog.setAktiv(m.isAktiv()); dialog.setTekst("TODO"); dialog.setHendelse(m.getHendelse()); dialog.setDialogId(m.getDialogId()); dialog.setJournalpostId(m.getJournalpostId()); LOG.info("Mappet til {}", dialog); return dialog; } static TilbakekrevingInnslag tilInnslag(JPATilbakekrevingInnslag i) { LOG.info("Mapper fra innslag {}", i); var innslag = new TilbakekrevingInnslag(i.getHendelse(), i.getGyldigTil(), i.getTekst(), i.getYtelseType()); innslag.setAktørId(i.getAktørId()); innslag.setFnr(i.getFnr()); innslag.setOpprettet(i.getOpprettet()); innslag.setSaksnr(i.getSaksnr()); innslag.setAktiv(i.isAktiv()); innslag.setDialogId(i.getDialogId()); innslag.setInnsendt(i.getInnsendt()); innslag.setJournalpostId(i.getJournalpostId()); LOG.info("Mappet til innslag {}", innslag); return innslag; } }
TharakaCz/ains-food-order-and-tranceport-system
food-order-system/src/main/java/com/foodordersystem/controller/TranceportController.java
/** * Jun 6, 2019 * food-order-system * com.foodordersystem.controller */ package com.foodordersystem.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.foodordersystem.helper.TranceportDto; import com.foodordersystem.service.TranceportService; /** * @author <NAME> */ @RestController @CrossOrigin @RequestMapping(value="/api/v1/tranceport") public class TranceportController { @Autowired private TranceportService tranceportService; @PostMapping(value="/saveTranceport") public ResponseEntity<Object>saveTranceport(@RequestBody TranceportDto tranceportDto){ try { return new ResponseEntity<Object>(tranceportService.saveTranceport(tranceportDto),HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } @PostMapping(value="/updateTranceport") public ResponseEntity<Object>updateTranceport(@RequestBody TranceportDto tranceportDto){ try { return new ResponseEntity<Object>(tranceportService.updateTranceport(tranceportDto),HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } @DeleteMapping(value="/deleteTranceport/{tranceportID}") public ResponseEntity<Object>deleteTranceport(@PathVariable("tranceportID")String tranceportID){ try { return new ResponseEntity<Object>(tranceportService.deleteTranceport(tranceportID),HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } @GetMapping(value="/searchTranceport/{tranceportID}") public ResponseEntity<Object>searchTranceport(@PathVariable("tranceportID")String tranceportID){ try { return new ResponseEntity<Object>(tranceportService.searchTranceport(tranceportID),HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } @GetMapping(value="/getAllTranceports") public ResponseEntity<Object>getAllTranceport(){ try { return new ResponseEntity<Object>(tranceportService.getAllTranceport(),HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } } }
liuxingA/LearnReactNative
5678/HelloWorld/index.ios.js
<filename>5678/HelloWorld/index.ios.js /** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import KeyboardDemo from './Demo/KeyboardDemo'; import NetDemo from './Demo/NetDemo'; import GeolocationDemo from './Demo/GeolocationDemo'; import AsyncStorageDemo from './Demo/AsyncStorageDemo'; import ClipboardDemo from './Demo/ClipboardDemo'; import NetInfoDemo from './Demo/NetInfoDemo'; import {AnimatedValueDemo,AnimatedValueXYDemo,SpringAnimatedValueXYDemo,InterpolationAnimatedValueDemo,CalculateAnimatedValueDemo,AnimatedGroupDemo,LayoutAnimationDemo,CustomAnimatedDemo} from './Demo/AnimatedDemo'; import PanResponderDemo from './Demo/PanResponderDemo'; import DimensionsDemo from './Demo/DimensionsDemo'; import PlatformDemo from './Demo/PlatformDemo'; import TimerDemo from './Demo/TimerDemo'; import NativeDemo from './Demo/NativeDemo'; import NativeViewDemo from './Demo/NativeViewDemo'; import TextDemo from './Demo/TextDemo'; import ButtonDemo from './Demo/ButtonDemo'; import ImageDemo from './Demo/ImageDemo'; import SwitchDemo from './Demo/SwitchDemo'; import SliderDemo from './Demo/SliderDemo'; import ActivityIndicatorDemo from './Demo/ActivityIndicatorDemo'; import TextInputDemo from './Demo/TextInputDemo'; import StatusBarDemo from './Demo/StatusBarDemo'; import PickerDemo from './Demo/PickerDemo'; import ModalDemo from './Demo/ModalDemo'; import KeyboardAvoidingViewDemo from './Demo/KeyboardAvoidingViewDemo'; import ViewDemo from './Demo/ViewDemo'; import ScrollViewDemo from './Demo/ScrollViewDemo'; import ListViewDemo from './Demo/ListViewDemo'; import FlatListDemo from './Demo/FlatListDmeo'; import DatePickerIOSDemo from './Demo/DataPickerIOSDemo'; // import NavigatiorDemo from './Demo/NavigatiorDemo'; import {LayoutDemoOne,LayoutDemoTwo,LayoutDemoThree} from './Demo/LayoutDemo'; import AlertDemo from './Demo/AlertDemo'; import AlertIOSDemo from './Demo/AlertIOSDemo'; import ActionSheetIOSDemo from './Demo/ActionSheetIOSDemo'; import PropsDemo from './Demo/PropsDemo'; export default class HelloWorld extends Component { render() { return (<PropsDemo bgColor="red" title="我是标题"/>); } } AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism
Variant Programs/4-3/12/EtdDeveloper.java
import java.util.ArrayDeque; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; public class EtdDeveloper extends Compiler { private ArrayDeque<Sue> fitBacklog = null; private ArrayDeque<Malfunction> anomalyCue = null; private int clipOther = 0; public EtdDeveloper() { this.fitBacklog = new ArrayDeque<>(); this.anomalyCue = new ArrayDeque<>(); clipOther = HourPurity; } public synchronized void nbsClick() { List<Malfunction> problems = new LinkedList<>(); for (Malfunction f : anomalyCue) { if (f.makeFitDay() == this.conveyFormerGene()) problems.add(f); } for (Malfunction flaw : problems) { anomalyCue.remove(flaw); reinstatementProgramme.totSheet( new Website( flaw.beatProceedings().fixOrders().peek(), flaw.beatProceedings().makeDimidiate(), 0), flaw.beatProceedings()); if (!fitBacklog.contains(flaw.beatProceedings())) { this.electedMethods(flaw.beatProceedings()); } } if (afootSummons != null) { clipOther--; if (afootSummons.isEnded()) { afootSummons.arrangedGoSentence(this.conveyFormerGene()); this.accomplishedProcedure.addLast(afootSummons); afootSummons = null; } if (clipOther == 0 && afootSummons != null) { if (fitBacklog.isEmpty()) { clipOther = HourPurity; } else { this.electedMethods(afootSummons); afootSummons = null; } } } if (afootSummons == null && !fitBacklog.isEmpty()) { afootSummons = this.preppedNegotiations(); clipOther = HourPurity; } this.passAdjacentAsked(); } public synchronized void electedMethods(Sue appendage) { fitBacklog.addLast(appendage); } public synchronized Sue preppedNegotiations() { return fitBacklog.removeFirst(); } private synchronized void passAdjacentAsked() { if (this.afootSummons == null) { return; } while (!reinstatementProgramme.seePetition(this.afootSummons)) { this.submitLayoutsDefective(); clipOther = HourPurity; if (!fitBacklog.isEmpty()) { afootSummons = preppedNegotiations(); } else { afootSummons = null; return; } } afootSummons.procedureFutureAsking(); } private synchronized void submitLayoutsDefective() { Malfunction f = new Malfunction(this.conveyFormerGene(), afootSummons); anomalyCue.add(f); afootSummons.obtainDemerit().add(f); } }
noelevans/playground
rpi/reset_piglow.py
from piglow import PiGlow def main(): piglow = PiGlow() piglow.all(0) if __name__ == '__main__': main()
udongo/udongo
spec/factories/redirects.rb
<filename>spec/factories/redirects.rb FactoryGirl.define do factory :redirect do source_uri '/nl/foo' destination_uri '/nl/bar' status_code 303 end end
mhnvelu/DataStructures-And-Algorithms
src/main/java/com/dsa/tree/ListOfDepthsSolution1.java
<filename>src/main/java/com/dsa/tree/ListOfDepthsSolution1.java package com.dsa.tree; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /* Problem: Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth If the tree has depth D, then the algorithm should produce D linked lists */ /* Solutions : using BFS With each level i, we will have already fully visited all nodes on level i-1. This means that to get which nodes are on level i, we can simply look at all children of the nodes of level i-1 It takes O(n) time, O(n) space */ public class ListOfDepthsSolution1 { public static void main(String a[]) { int nodes[] = {5, 1, 4, 7, 9, 2, 8}; TreeNode root = Tree.getTree(nodes); ListOfDepthsSolution1 obj = new ListOfDepthsSolution1(); System.out.println(obj.createLinkedListLPerLevel(root)); } private List<LinkedList<TreeNode>> createLinkedListLPerLevel(TreeNode treeNode) { List<LinkedList<TreeNode>> result = new ArrayList<>(); LinkedList<TreeNode> current = new LinkedList<>(); current.add(treeNode); while (current.size() > 0) { result.add(current); // // level i-1 LinkedList<TreeNode> parents = current; // level i current = new LinkedList<>(); for (TreeNode parent : parents) { if (parent.left != null) { current.add(parent.left); } if (parent.right != null) { current.add(parent.right); } } } return result; } }
deepcloudlabs/dcl202-2021-mar-01
study-arrays/src/com/example/StudyArrays.java
<reponame>deepcloudlabs/dcl202-2021-mar-01<filename>study-arrays/src/com/example/StudyArrays.java<gh_stars>0 package com.example; import java.util.Arrays; import java.util.Comparator; @SuppressWarnings("unused") public class StudyArrays { public static void main(String[] args) { int number = 42; // scalar variable Integer numbers1 []; // array int [] numbers2 = {4,8,15,16,23,42}; // array numbers1 = new Integer[10]; // 10 elements: 0,0,0,0,0,0,0,0,0,0 System.out.println(numbers1.length); numbers1 = new Integer[] {4,8,15,16,23,42}; // 6 elements System.out.println(numbers1.length); // static: numbers1.length is constant System.out.println(numbers1[5]); // 42 System.out.println(numbers1[numbers1.length-1]); // 42 // System.out.println(numbers1[-1]); // ArrayIndexOutOfBoundsException // Outer Loop over arrays #1 for (var i=0;i<numbers1.length;i += 3) { System.out.println(numbers1[i]); } for (var i=numbers1.length-1;i>=0;i-=2) { System.out.println(numbers1[i]); } // Outer Loop over arrays #2 (Java SE 5) : for-each -> read-only for (int num : numbers1) { // SAFE: ArrayIndexOutOfBoundsException System.out.println(num); num = num * 2; // does not change the original array } for (var num : numbers1) { // SAFE: ArrayIndexOutOfBoundsException System.out.println(num); } // Inner Loop over arrays #3: Stream API (Java SE 8) Arrays.stream(numbers1).forEach(System.out::println); // Arrays: utility class Arrays.sort(numbers1,new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2-o1; } }); // Functional Programming Arrays.sort(numbers1, (o1,o2) -> o2-o1 ); // Lambda Expression // Functional Interface : Comparator Comparator<Integer> orderByAsc = Integer::compare; // Method Reference Arrays.sort(numbers1, orderByAsc.reversed()); // Lambda Expression System.out.println(Arrays.toString(numbers1)); } }
TCKACHIKSIS/lms
problem/migrations/0007_problemstats.py
# Generated by Django 3.1.8 on 2021-05-24 12:00 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('problem', '0006_merge_20210517_1923'), ] operations = [ migrations.CreateModel( name='ProblemStats', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('green', models.IntegerField()), ('yellow', models.IntegerField()), ('red', models.IntegerField()), ('problem', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='problem.problem')), ], ), ]
guxuede/gm
src/main/java/com/guxuede/ShaderLesson2.java
package com.guxuede; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL30; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShaderProgram; /** * * 预设的几个attibute(属性,SpriteBatch 传入的,只能在vertex使用), public static final String POSITION_ATTRIBUTE = "a_position"; public static final String NORMAL_ATTRIBUTE = "a_normal"; public static final String COLOR_ATTRIBUTE = "a_color"; //batch.setColor(Color.BLUE); 时的值 public static final String TEXCOORD_ATTRIBUTE = "a_texCoord"; public static final String TANGENT_ATTRIBUTE = "a_tangent"; public static final String BINORMAL_ATTRIBUTE = "a_binormal"; gl_FragCoord 像素所在的位置 * A port of ShaderLesson2 from lwjgl-basics to LibGDX: * https://github.com/mattdesl/lwjgl-basics/wiki/ShaderLesson2 * * @author davedes */ public class ShaderLesson2 implements ApplicationListener { //Minor differences: //LibGDX Position attribute is a vec4 //u_projView is called u_projTrans //we need to set ShaderProgram.pedantic to false //LibGDX uses lower-left as origin (0, 0) //TexCoord attribute requires "0" appended at end to denote GL_TEXTURE0 //ShaderProgram.TEXCOORD_ATTRIBUTE+"0" //It's wise to use LOWP for color attribute in GL ES public static void main(String[] args) { LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); cfg.title = "Shader Lesson 2"; cfg.width = 640; cfg.height = 480; cfg.resizable = false; new LwjglApplication(new ShaderLesson2(), cfg); } final String VERT = "attribute vec4 "+ ShaderProgram.POSITION_ATTRIBUTE+";\n" + "attribute vec4 "+ShaderProgram.COLOR_ATTRIBUTE+";\n" + "attribute vec2 "+ShaderProgram.TEXCOORD_ATTRIBUTE+"0;\n" + "uniform mat4 u_projTrans;\n" + " \n" + "varying vec4 vColor;\n" + "varying vec2 vTexCoord;\n" + "void main() {\n" + " vColor = "+ShaderProgram.COLOR_ATTRIBUTE+";\n" + " vTexCoord = "+ShaderProgram.TEXCOORD_ATTRIBUTE+"0;\n" + " gl_Position = u_projTrans * " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" + "}"; final String FRAG = //GL ES specific stuff "#ifdef GL_ES\n" // + "#define LOWP lowp\n" // + "precision mediump float;\n" // + "#else\n" // + "#define LOWP \n" // + "#endif\n" + // "varying LOWP vec4 vColor;\n" + "varying vec2 vTexCoord;\n" + "uniform sampler2D u_texture;\n" + "void main() {\n" + " vec4 texColor = texture2D(u_texture, vTexCoord);\n" + " \n" + " texColor.rgb = 1.0 - texColor.rgb;\n" + " \n" + " gl_FragColor = texColor * vColor;\n" + "}"; Texture tex; SpriteBatch batch; OrthographicCamera cam; ShaderProgram shader; @Override public void create() { tex = new Texture(Gdx.files.internal("data/items.png")); //important since we aren't using some uniforms and attributes that SpriteBatch expects ShaderProgram.pedantic = false; shader = new ShaderProgram(VERT, FRAG); if (!shader.isCompiled()) { System.err.println(shader.getLog()); System.exit(0); } if (shader.getLog().length()!=0) System.out.println(shader.getLog()); batch = new SpriteBatch(1000, shader); batch.setShader(shader); cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); cam.setToOrtho(false); } @Override public void resize(int width, int height) { cam.setToOrtho(false, width, height); batch.setProjectionMatrix(cam.combined); } @Override public void render() { Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT); batch.begin(); //notice that LibGDX coordinate system origin is lower-left batch.draw(tex, 10, 10); // batch.draw(tex, 10, 320, 32, 32); batch.end(); } @Override public void pause() { } @Override public void resume() { } @Override public void dispose() { batch.dispose(); shader.dispose(); tex.dispose(); } }
itspriyansh/filemanager-packages
packages/server-nodejs/node_modules/ignore-styles/ignore-styles.js
<reponame>itspriyansh/filemanager-packages<gh_stars>1-10 export const DEFAULT_EXTENSIONS = [ '.css', '.scss', '.sass', '.pcss', '.stylus', '.styl', '.less', '.sss', '.gif', '.jpeg', '.jpg', '.png', '.svg', '.mp4', '.webm', '.ogv' ] export let oldHandlers = {} export function noOp () {} export function restore () { for (const ext in oldHandlers) { if (oldHandlers[ext] === undefined) { delete require.extensions[ext] } else { require.extensions[ext] = oldHandlers[ext] } } oldHandlers = {} } export default function register (extensions = DEFAULT_EXTENSIONS, handler = noOp) { restore() for (const ext of extensions) { oldHandlers[ext] = require.extensions[ext] require.extensions[ext] = handler } } // Run at import register()
yaowng/searchuser_app
app/components/UserItemCounter/index.js
import React from 'react'; import Wrapper from './Wrapper'; function UserItemCounter({ profile }) { return ( <Wrapper> <p> <strong>Repositories:</strong> {profile.public_repos} || <strong>Followers:</strong> {profile.followers} || <strong>Following:</strong> {profile.following} </p> </Wrapper> ); } UserItemCounter.propTypes = { profile: React.PropTypes.any, }; export default UserItemCounter;
slaby93/bidwrangler_demo
src/routes/Auction/routes/View/View.js
<filename>src/routes/Auction/routes/View/View.js import React from 'react'; import styled from 'styled-components'; import Button, { LinkButton, ButtonsWrapper } from 'components/elements/Button'; export const View = ({ className, currentPrice, name, authorId, userUid, onBid, auctionId, isOwner, isMyBidWinning, }) => { const newPrice = currentPrice + 100; return ( <div className={className}> <h1>{isOwner ? 'Auctioner' : 'Bidder'}</h1> <h1>Name: {name}</h1> <span>Current price: ${currentPrice}</span> <ButtonsWrapper> {!isOwner && !isMyBidWinning && <Button bgColor="#d2e686" onClick={() => onBid(auctionId, newPrice)}>Bid ${newPrice}</Button>} {!isOwner && isMyBidWinning && <Button disabled>My winning bid ${newPrice}</Button>} {isOwner && <Button disabled>Current price ${currentPrice}</Button> } <LinkButton grow to="/auctions/list"> Back </LinkButton> </ButtonsWrapper> </div> ); }; const Styled = styled(View)` width: 50%; display: flex; flex-direction: column; justify-self: center; align-self: center; ${ButtonsWrapper} { align-self: center; margin-top: 20px; width: 240px; } `; export default Styled;
johnaparker/MiePy
examples/tests/incident_expansion.py
"""Decompose an x-polarized plane wave into the VSHs""" import numpy as np import matplotlib.pyplot as plt import miepy ### source definition source = miepy.sources.plane_wave.from_string(polarization='x') k = 2*np.pi/1 Nmax = 5 ### grid plane x = np.linspace(-.3,.3,30) y = np.linspace(-.3,.3,30) z = 0 X,Y,Z = np.meshgrid(x,y,z, indexing='ij') coords = np.array([X,Y,Z]) ### exact fields def exact(): E = source.E(coords, k).squeeze() fig,ax = plt.subplots() I = np.sum(np.abs(E)**2, axis=0) im = ax.pcolormesh(X.squeeze(),Y.squeeze(),I, vmin=0.9, vmax=1.1) plt.colorbar(im) ax.quiver(X.squeeze(),Y.squeeze(),E[0].real, E[1].real) ### analytic expansion def analytic(): p,q = source.structure([0,0,0], k, Nmax) f = miepy.vsh.expand(p, q, k, miepy.vsh.vsh_mode.incident) expanded_E = f(X,Y,Z).squeeze() fig,ax = plt.subplots() I = np.sum(np.abs(expanded_E)**2, axis=0) im = ax.pcolormesh(X.squeeze(),Y.squeeze(),I) plt.colorbar(im) ax.quiver(X.squeeze(),Y.squeeze(),expanded_E[0].real, expanded_E[1].real) return p,q ### numerical decomposition and expansion def numeric(): p,q = miepy.vsh.decompose_source(source, k, Nmax, sampling=31) f = miepy.vsh.expand(p, q, k, miepy.vsh.vsh_mode.incident) expanded_E = f(X,Y,Z).squeeze() fig,ax = plt.subplots() I = np.sum(np.abs(expanded_E)**2, axis=0) im = ax.pcolormesh(X.squeeze(),Y.squeeze(),I) plt.colorbar(im) ax.quiver(X.squeeze(),Y.squeeze(),expanded_E[0].real, expanded_E[1].real) return p,q exact() p1, q1 = analytic() p2, q2 = numeric() err = np.sum(np.abs(p2-p1)**2 + np.abs(q2-q1)**2) print(err) plt.show()
uk-gov-mirror/DFE-Digital.get-help-with-tech
db/migrate/20200907114036_create_computacenter_user_changes.rb
class CreateComputacenterUserChanges < ActiveRecord::Migration[6.0] def change create_table :computacenter_user_changes do |t| t.integer :user_id t.text :first_name t.text :last_name t.text :email_address t.text :telephone t.text :responsible_body t.text :responsible_body_urn t.text :cc_sold_to_number t.text :school t.text :school_urn t.text :cc_ship_to_number t.datetime :updated_at_timestamp t.integer :type_of_update t.text :original_email_address t.timestamps end add_index :computacenter_user_changes, :user_id add_index :computacenter_user_changes, :updated_at_timestamp end end
Diffblue-benchmarks/heroic
heroic-dist/src/test/java/com/spotify/heroic/AbstractLocalClusterIT.java
<filename>heroic-dist/src/test/java/com/spotify/heroic/AbstractLocalClusterIT.java<gh_stars>100-1000 package com.spotify.heroic; import static org.junit.Assert.assertEquals; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.spotify.heroic.cluster.ClusterManagerModule; import com.spotify.heroic.cluster.NodeMetadataFactory; import com.spotify.heroic.cluster.RpcProtocolModule; import com.spotify.heroic.cluster.discovery.simple.StaticListDiscoveryModule; import com.spotify.heroic.dagger.CoreComponent; import com.spotify.heroic.profile.MemoryProfile; import com.spotify.heroic.querylogging.QueryLogger; import com.spotify.heroic.querylogging.QueryLoggerFactory; import com.spotify.heroic.querylogging.QueryLoggingComponent; import com.spotify.heroic.querylogging.QueryLoggingModule; import com.spotify.heroic.rpc.grpc.GrpcRpcProtocolModule; import com.spotify.heroic.rpc.jvm.JvmRpcContext; import com.spotify.heroic.rpc.jvm.JvmRpcProtocolModule; import eu.toolchain.async.AsyncFuture; import eu.toolchain.async.TinyAsync; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.junit.After; import org.junit.Before; import org.mockito.Mockito; public abstract class AbstractLocalClusterIT { protected final ExecutorService executor = Executors.newSingleThreadExecutor(); protected final TinyAsync async = TinyAsync.builder().executor(executor).build(); protected List<HeroicCoreInstance> instances; private final Map<String, QueryLogger> loggers = new HashMap<>(); private final QueryLoggingModule mockQueryLoggingModule = early -> new QueryLoggingComponent() { @Override public QueryLoggerFactory queryLoggerFactory() { return new QueryLoggerFactory() { @Override public QueryLogger create(final String component) { synchronized (loggers) { QueryLogger logger = loggers.get(component); if (logger == null) { logger = Mockito.mock(QueryLogger.class); loggers.put(component, logger); } return logger; } } }; } }; protected String protocol() { return "jvm"; } /** * Override to configure more than one instance. * <p> * These will be available in the {@link #instances} field. * * @return a list of URIs. */ protected List<URI> instanceUris() { return ImmutableList.of(URI.create(protocol() + "://a"), URI.create(protocol() + "://b")); } /** * Overload the default metadata behavior. * * If empty, default factories will be used. * * @return a list of metadata factories, that will be round-robined over. */ protected List<NodeMetadataFactory> metadataFactories() { return ImmutableList.of(); } /** * Prepare the environment before the test. * <p> * {@link #instances} have been configured before this is called and can be safely used. * * @return a future that indicates that the environment is ready. */ protected AsyncFuture<Void> prepareEnvironment() { return async.resolved(null); } /** * Access to locally pre-configured query loggers which have been provided to all instances. * * @param component Component to get logger for * @return a QueryLogger or empty */ protected Optional<QueryLogger> getQueryLogger(final String component) { synchronized (loggers) { return Optional.ofNullable(loggers.get(component)); } } @Before public final void abstractSetup() throws Exception { final JvmRpcContext context = new JvmRpcContext(); final List<URI> uris = instanceUris(); final List<Integer> expectedNumberOfNodes = uris.stream().map(u -> uris.size()).collect(Collectors.toList()); int instanceIndex = 0; final List<HeroicCoreInstance> instances = new ArrayList<>(); for (final URI uri : uris) { instances.add(setupCore(uri, uris, context, instanceIndex++)); } this.instances = instances; final AsyncFuture<Void> startup = async.collectAndDiscard( instances.stream().map(HeroicCoreInstance::start).collect(Collectors.toList())); // Refresh all cores, allowing them to discover each other. final AsyncFuture<Void> refresh = startup.lazyTransform(v -> { return setupStaticNodes().lazyTransform(ignore -> async.collectAndDiscard(instances .stream() .map(c -> c.inject(inj -> inj.clusterManager().refresh())) .collect(Collectors.toList()))); }); refresh.lazyTransform(v -> { // verify that the correct number of nodes are visible from all instances. final List<Integer> actualNumberOfNodes = instances .stream() .map(c -> c.inject(inj -> inj.clusterManager().getNodes().size())) .collect(Collectors.toList()); assertEquals(expectedNumberOfNodes, actualNumberOfNodes); return prepareEnvironment(); }).get(10, TimeUnit.SECONDS); } private AsyncFuture<Void> setupStaticNodes() { // JVM protocol does not require static nodes since addresses are known beforehand. if ("jvm".equals(protocol())) { return async.resolved(null); } // Collect remote URIs from instances to get ahold of generated port. final List<AsyncFuture<String>> remotes = instances .stream() .map(c -> c.inject(CoreComponent::clusterManager)) .map(c -> c.protocols().iterator().next().getListenURI()) .collect(Collectors.toList()); return async.collect(remotes).lazyTransform(uris -> { final List<AsyncFuture<Void>> addNodes = new ArrayList<>(); for (final String stringUri : uris) { final URI remoteUri = URI.create(stringUri); instances.forEach(instance -> { final URI uri = URI.create(remoteUri.getScheme() + "://127.0.0.1:" + remoteUri.getPort()); addNodes.add(instance.inject(CoreComponent::clusterManager).addStaticNode(uri)); }); } return async.collectAndDiscard(addNodes); }); } @After public final void abstractTeardown() throws Exception { async .collectAndDiscard( instances.stream().map(HeroicCoreInstance::shutdown).collect(Collectors.toList())) .get(10, TimeUnit.SECONDS); } private HeroicCoreInstance setupCore( final URI uri, final List<URI> uris, final JvmRpcContext context, final int index ) { try { return setupCoreThrowing(uri, uris, context, index); } catch (Exception e) { throw Throwables.propagate(e); } } private HeroicCoreInstance setupCoreThrowing( final URI uri, final List<URI> uris, final JvmRpcContext context, final int index ) throws Exception { final RpcProtocolModule protocol; final StaticListDiscoveryModule discovery; switch (uri.getScheme()) { case "jvm": protocol = JvmRpcProtocolModule.builder().context(context).bindName(uri.getHost()).build(); discovery = new StaticListDiscoveryModule(uris); break; case "grpc": protocol = GrpcRpcProtocolModule.builder().port(0).build(); discovery = new StaticListDiscoveryModule(ImmutableList.of()); break; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } return HeroicCore .builder() .setupShellServer(false) .setupService(false) .oneshot(true) .executor(executor) .configFragment(HeroicConfig .builder() .cluster(buildClusterConfig(uri, protocol, discovery, index))) .configFragment(HeroicConfig.builder().queryLogging(mockQueryLoggingModule)) .profile(new MemoryProfile()) .modules(HeroicModules.ALL_MODULES) .build() .newInstance(); } private ClusterManagerModule.Builder buildClusterConfig( final URI uri, final RpcProtocolModule protocol, final StaticListDiscoveryModule discovery, int index ) { final ClusterManagerModule.Builder cluster = ClusterManagerModule .builder() .tags(ImmutableMap.of("shard", uri.getHost())) .protocols(ImmutableList.of(protocol)) .discovery(discovery); final List<NodeMetadataFactory> factories = metadataFactories(); if (!factories.isEmpty()) { cluster.metadataFactory(factories.get(index % factories.size())); } return cluster; } }
drganam/stainless
core/src/main/scala/stainless/extraction/imperative/AntiAliasing.scala
/* Copyright 2009-2021 EPFL, Lausanne */ package stainless package extraction package imperative import inox.FatalError import scala.util.Try trait AntiAliasing extends oo.CachingPhase with SimpleSorts with oo.IdentityTypeDefs with oo.SimpleClasses with EffectsAnalyzer with EffectsChecker with GhostChecker { self => import s._ // Function rewriting depends on the effects analysis which relies on all dependencies // of the function, so we use a dependency cache here. override protected final val funCache = new ExtractionCache[s.FunDef, FunctionResult]((fd, context) => getDependencyKey(fd.id)(context.symbols) ) // Function types are rewritten by the transformer depending on the result of the // effects analysis, so we again use a dependency cache here. override protected final val sortCache = new ExtractionCache[s.ADTSort, SortResult]((sort, context) => getDependencyKey(sort.id)(context.symbols) ) // Function types are rewritten by the transformer depending on the result of the // effects analysis, so we again use a dependency cache here. override protected final val classCache = new ExtractionCache[s.ClassDef, ClassResult]((cd, context) => getDependencyKey(cd.id)(context.symbols) ) override protected type FunctionResult = Option[FunDef] override protected def registerFunctions(symbols: t.Symbols, functions: Seq[Option[t.FunDef]]): t.Symbols = symbols.withFunctions(functions.flatten) protected case class SymbolsAnalysis(symbols: Symbols) extends EffectsAnalysis { import symbols._ // Convert a function type with mutable parameters, into a function type // that returns the mutable parameters. This makes explicit all possible // effects of the function. This should be used for higher order functions // declared as parameters. def makeFunctionTypeExplicit(tpe: Type): Type = tpe match { case ft @ FunctionType(from, to) => ft.copy(to = tupleTypeWrap(to +: from.filter(isMutableType(_))).copiedFrom(to)).copiedFrom(tpe) case pt @ PiType(params, to) => pt.copy(to = tupleTypeWrap(to +: params.map(_.tpe).filter(isMutableType(_))).copiedFrom(to)).copiedFrom(tpe) } object transformer extends SelfTreeTransformer { // XXX: since ApplyLetRec stores the type of the corresponding function, // we have to make sure to NOT make that first-class function type explicit!! override def transform(e: Expr): Expr = e match { case ApplyLetRec(id, tparams, tpe, tps, args) => ApplyLetRec( id, tparams map (tp => transform(tp).asInstanceOf[TypeParameter]), FunctionType(tpe.from map transform, transform(tpe.to)).copiedFrom(tpe), tps map transform, args map transform ).copiedFrom(e) case _ => super.transform(e) } override def transform(tpe: Type): Type = tpe match { case ft @ (_: FunctionType | _: PiType) => makeFunctionTypeExplicit(ft) case _ => super.transform(tpe) } } } override protected type TransformerContext = SymbolsAnalysis override protected def getContext(symbols: Symbols) = SymbolsAnalysis(symbols) override protected def extractFunction(analysis: SymbolsAnalysis, fd: FunDef): Option[FunDef] = { import analysis._ import symbols._ checkGhost(fd)(analysis) checkEffects(fd)(analysis) match { case CheckResult.Ok => () case CheckResult.Skip => return None case CheckResult.Error(err) => throw err } type Environment = (Set[ValDef], Map[ValDef, Expr], Map[Identifier, LocalFunDef]) implicit class EnvWrapper(env: Environment) { val (bindings, rewritings, locals) = env def withBinding(vd: ValDef): Environment = (bindings + vd, rewritings, locals) def withBindings(vds: Iterable[ValDef]): Environment = (bindings ++ vds, rewritings, locals) def withRewritings(map: Map[ValDef, Expr]): Environment = (bindings, rewritings ++ map, locals) def withLocals(fds: Seq[LocalFunDef]): Environment = (bindings, rewritings, locals ++ fds.map(fd => fd.id -> fd)) } object Environment { def empty: Environment = (Set.empty, Map.empty, Map.empty) } /* Create a new FunDef for a given FunDef in the program. * Adapt the signature to express its effects. In case the * function has no effect, this will still return the original * fundef. * * Also update FunctionType parameters that need to become explicit * about the effect they could perform (returning any mutable type that * they receive). */ def updateFunction(fd: FunAbstraction, env: Environment): FunAbstraction = { val aliasedParams = analysis.getAliasedParams(fd) val newFd = fd.copy(returnType = analysis.getReturnType(fd)) if (aliasedParams.isEmpty) { newFd.copy(fullBody = makeSideEffectsExplicit(fd.fullBody, fd, env, Seq.empty)) } else { val (specs, body) = exprOps.deconstructSpecs(fd.fullBody) val freshLocals: Seq[ValDef] = aliasedParams.map(v => v.freshen) val freshSubst = aliasedParams.zip(freshLocals).map(p => p._1.toVariable -> p._2.toVariable).toMap val newBody = body.map { body => val freshBody = exprOps.replaceFromSymbols(freshSubst, body) val explicitBody = makeSideEffectsExplicit(freshBody, fd, env withBindings freshLocals, freshLocals.map(_.toVariable)) //WARNING: only works if side effects in Tuples are extracted from left to right, // in the ImperativeTransformation phase. val finalBody: Expr = Tuple(explicitBody +: freshLocals.map(_.toVariable)).copiedFrom(body) freshLocals.zip(aliasedParams).foldLeft(finalBody) { (bd, vp) => LetVar(vp._1, vp._2.toVariable, bd).copiedFrom(body) } } val newSpecs = specs.map { case exprOps.Postcondition(post @ Lambda(Seq(res), postBody)) => val newRes = ValDef(res.id.freshen, newFd.returnType).copiedFrom(res) val newBody = exprOps.replaceSingle( aliasedParams.map(vd => (Old(vd.toVariable), vd.toVariable): (Expr, Expr)).toMap ++ aliasedParams.zipWithIndex.map { case (vd, i) => (vd.toVariable, TupleSelect(newRes.toVariable, i+2).copiedFrom(vd)): (Expr, Expr) }.toMap + (res.toVariable -> TupleSelect(newRes.toVariable, 1).copiedFrom(res)), makeSideEffectsExplicit(postBody, fd, env, Seq.empty) ) exprOps.Postcondition(Lambda(Seq(newRes), newBody).copiedFrom(post)) case spec => spec } newFd.copy(fullBody = exprOps.reconstructSpecs(newSpecs, newBody, newFd.returnType)) } } //We turn all local val of mutable objects into vars and explicit side effects //using assignments. We also make sure that no aliasing is being done. def makeSideEffectsExplicit( body: Expr, originalFd: FunAbstraction, env: Environment, freshLocals: Seq[Variable] ): Expr = { object transformer extends inox.transformers.Transformer { override val s: self.s.type = self.s override val t: self.t.type = self.t override type Env = Environment def select(pos: inox.utils.Position, tpe: Type, expr: Expr, path: Seq[Accessor]): (Expr, Expr) = (tpe, path) match { case (adt: ADTType, ADTFieldAccessor(id) +: xs) => val constructors = adt.getSort.constructors val constructor = constructors.find(_.fields.exists(_.id == id)).get val field = constructor.fields.find(_.id == id).get val condition = if (constructors.size > 1) { IsConstructor(expr, constructor.id).setPos(pos) } else { BooleanLiteral(true).setPos(pos) } val (recCond, recSelect) = select(pos, field.tpe, ADTSelector(expr, id).setPos(pos), xs) (and(condition, recCond), recSelect) case (ct: ClassType, ClassFieldAccessor(id) +: xs) => val field = getClassField(ct, id).get val fieldClassType = classForField(ct, id).get.toType val condition = IsInstanceOf(expr, fieldClassType).setPos(pos) val (recCond, recSelect) = select(pos, field.tpe, ClassSelector(AsInstanceOf(expr, fieldClassType).setPos(expr), id).setPos(pos), xs) (and(condition, recCond), recSelect) case (tt: TupleType, TupleFieldAccessor(idx) +: xs) => select(pos, tt.bases(idx - 1), TupleSelect(expr, idx).setPos(pos), xs) case (ArrayType(base), ArrayAccessor(idx) +: xs) => select(pos, base, ArraySelect(expr, idx).setPos(pos), xs) case (MutableMapType(from, to), MutableMapAccessor(idx) +: xs) => select(pos, to, MutableMapApply(expr, idx).setPos(pos), xs) case (_, Nil) => (BooleanLiteral(true).setPos(pos), expr) } def makeAssignment(pos: inox.utils.Position, resSelect: Expr, outerEffect: Effect, effect: Effect): Expr = { val (cond, result) = select(pos, resSelect.getType, resSelect, outerEffect.path.toSeq) // We only overwrite the receiver when it is an actual mutable type. // This is necessary to handle immutable types being upcasted to `Any`, which is mutable. val assignment = if (isMutableType(effect.receiver.getType)) { val newValue = updatedTarget(effect.toTarget, Annotated(result, Seq(DropVCs)).setPos(pos)) val castedValue = Annotated(AsInstanceOf(newValue, effect.receiver.getType), Seq(DropVCs)) Assignment(effect.receiver, castedValue).setPos(pos) } else UnitLiteral().setPos(pos) if (cond == BooleanLiteral(true)) assignment else IfExpr(cond, assignment, UnitLiteral().setPos(pos)).setPos(pos) } def mapApplication(formalArgs: Seq[ValDef], args: Seq[Expr], nfi: Expr, nfiType: Type, fiEffects: Set[Effect], env: Env): Expr = { if (fiEffects.exists(e => formalArgs contains e.receiver.toVal)) { val localEffects = (formalArgs zip args) .map { case (vd, arg) => (fiEffects.filter(_.receiver == vd.toVariable), arg) } .filter { case (effects, _) => effects.nonEmpty } .map { case (effects, arg) => val rArg = exprOps.replaceFromSymbols(env.rewritings, arg) effects map (e => (e, e on rArg)) } //TODO: The case f(A(x1,x1,x1)) could probably be handled by forbidding creation at any program point of // case class with multiple refs as it is probably not useful val freshRes = ValDef(FreshIdentifier("res"), nfiType).copiedFrom(nfi) val extractResults = Block( for { (effects, index) <- localEffects.zipWithIndex (outerEffect0, innerEffects) <- effects effect0 <- innerEffects } yield { val outerEffect = outerEffect0.removeUnknownAccessor val effect = effect0.removeUnknownAccessor val pos = args(index).getPos val resSelect = TupleSelect(freshRes.toVariable, index + 2) makeAssignment(pos, resSelect, outerEffect, effect) }, TupleSelect(freshRes.toVariable, 1)) if (isMutableType(nfiType)) { LetVar(freshRes, nfi, transform(extractResults, env withBinding freshRes)) } else { Let(freshRes, nfi, transform(extractResults, env)) } } else { nfi } } // throws an exception if two arguments in the sequence share a target prefix private def checkAliasing(expr: Expr, args: Seq[Expr]): Unit = { val argTargets: Seq[((Expr, Set[Target]), Int)] = args.filter(arg => isMutableType(arg.getType)) .map(arg => arg -> Try(getAllTargets(arg)).toOption .getOrElse( exprOps.variablesOf(arg) .filter(v => isMutableType(v.tpe)) .map(v => Target(v, None, Path.empty)) ) ).zipWithIndex for (((arg1, targets1), i) <- argTargets) { val otherTargets: Seq[(Expr, Set[Target])] = argTargets.filter(_._2 != i).map(_._1) for (target1 <- targets1) for ((arg2, targets2) <- otherTargets) for (target2 <- targets2) if (target1.maybePrefixOf(target2) || target2.maybePrefixOf(target1)) throw MalformedStainlessCode(expr, s"Illegal passing of aliased parameters ${arg1.asString} (with target: ${target1.asString}) " + s"and ${arg2.asString} (with target: ${target2.asString})" ) } } override def transform(e: Expr, env: Env): Expr = (e match { case v: Variable if env.rewritings.contains(v.toVal) => env.rewritings(v.toVal) case ret @ Return(_) if freshLocals.isEmpty => super.transform(e, env) case ret @ Return(retExpr) => Return(Tuple(transform(retExpr, env) +: freshLocals.map(_.setPos(ret))).setPos(ret)).setPos(ret) case swap @ Swap(array1, index1, array2, index2) => val base = array1.getType.asInstanceOf[ArrayType].base val temp = ValDef.fresh("temp", base).setPos(swap) val ra1 = exprOps.replaceFromSymbols(env.rewritings, array1) val targets1 = getDirectTargets(ra1, ArrayAccessor(index1)) val ra2 = exprOps.replaceFromSymbols(env.rewritings, array2) val targets2 = getDirectTargets(ra2, ArrayAccessor(index2)) if (targets1.exists(target => !env.bindings.contains(target.receiver.toVal))) throw MalformedStainlessCode(swap, "Unsupported swap (first array)") if (targets2.exists(target => !env.bindings.contains(target.receiver.toVal))) throw MalformedStainlessCode(swap, "Unsupported swap (second array)") val updates1 = targets1.toSeq map { target => val applied = updatedTarget(target, ArraySelect(array2, index2).setPos(swap)) transform(Assignment(target.receiver, applied).setPos(swap), env) } val updates2 = targets2.toSeq map { target => val applied = updatedTarget(target, temp.toVariable) transform(Assignment(target.receiver, applied).setPos(swap), env) } val updates = updates1 ++ updates2 if (updates.isEmpty) UnitLiteral().setPos(swap) else Let(temp, transform(ArraySelect(array1, index1).setPos(swap), env), Block(updates.init, updates.last).setPos(swap) ).setPos(swap) case l @ Let(vd, e, b) if isMutableType(vd.tpe) => // see https://github.com/epfl-lara/stainless/pull/920 for discussion val newExpr = transform(e, env) val targets = Try(getAllTargets(newExpr)) if (targets.isSuccess) { // This branch handles all cases when targets can be precisely computed, namely when // 1. newExpr is a fresh expression // 2. newExpr is a precise alias to an existing variable val rewriting = targets.get.foldRight(vd.toVariable : Expr) { case (Target(r, Some(cond), path), rewriting) => val wrapped = path.wrap(r).getOrElse( throw MalformedStainlessCode(l, "Unsupported `val` in AntiAliasing (conditional target)") ) IfExpr(cond, wrapped, rewriting) case (Target(r, None, path), rewriting) => path.wrap(r).getOrElse( throw MalformedStainlessCode(l, "Unsupported `val` in AntiAliasing (unconditional target)") ) } val newBody = transform(b, env withRewritings Map(vd -> rewriting) withBinding vd) LetVar(vd, newExpr, newBody).copiedFrom(l) } else if ((exprOps.variablesOf(e) & exprOps.variablesOf(b)).forall(v => !isMutableType(v.tpe))) { val newBody = transform(b, env withBinding vd) // for all effects of `b` whose receiver is `vd` val copyEffects = effects(b).filter(_.receiver == vd.toVariable).flatMap { eff => // we apply the effect on the bound expression (after transformation) eff.on(newExpr).map { eff2 => makeAssignment(l.getPos, eff.receiver, eff, eff2) } } val resVd = ValDef.fresh("res", b.getType).copiedFrom(b) LetVar( vd, newExpr, Let(resVd, newBody, Block(copyEffects.toSeq, resVd.toVariable).copiedFrom(l)).copiedFrom(l) ).copiedFrom(l) } else { throw MalformedStainlessCode(l, "Unexpected `val` in AntiAliasing (couldn't compute targets and there are mutable variables shared between the binding and the body)") } case l @ LetVar(vd, e, b) if isMutableType(vd.tpe) => val newExpr = transform(e, env) val newBody = transform(b, env withBinding vd) LetVar(vd, newExpr, newBody).copiedFrom(l) case m @ MatchExpr(scrut, cses) if isMutableType(scrut.getType) => if (effects(scrut).nonEmpty) { def liftEffects(e: Expr): (Seq[(ValDef, Expr)], Expr) = e match { case ArraySelect(e, i) if effects(i).nonEmpty => val (eBindings, eLift) = liftEffects(e) val vd = ValDef(FreshIdentifier("index", true), Int32Type().copiedFrom(i)).copiedFrom(i) (eBindings :+ (vd -> i), ArraySelect(eLift, vd.toVariable).copiedFrom(e)) case _ if effects(e).nonEmpty => throw MalformedStainlessCode(m, "Unexpected effects in match scrutinee") case _ => (Seq.empty, e) } val (bindings, newScrut) = liftEffects(scrut) val newMatch = bindings.foldRight(MatchExpr(newScrut, cses).copiedFrom(m): Expr) { case ((vd, e), b) => Let(vd, e, b).copiedFrom(m) } transform(newMatch, env) } else { val newScrut = transform(scrut, env) val newCases = cses.map { case mc @ MatchCase(pattern, guard, rhs) => val newRewritings = mapForPattern(newScrut, pattern).filterKeys(v => isMutableType(v.getType)) val newGuard = guard.map(transform(_, env withRewritings newRewritings)) val newRhs = transform(rhs, env withRewritings newRewritings) MatchCase(pattern, newGuard, newRhs).copiedFrom(mc) } MatchExpr(newScrut, newCases).copiedFrom(m) } case up @ ArrayUpdate(a, i, v) => val ra = exprOps.replaceFromSymbols(env.rewritings, a) val targets = getDirectTargets(ra, ArrayAccessor(i)) if (targets.exists(target => !env.bindings.contains(target.receiver.toVal))) throw MalformedStainlessCode(up, "Unsupported form of array update") Block(targets.toSeq map { target => val applied = updatedTarget(target, v) transform(Assignment(target.receiver, applied).copiedFrom(up), env) }, UnitLiteral().copiedFrom(up)).copiedFrom(up) case up @ MutableMapUpdate(map, k, v) => val rmap = exprOps.replaceFromSymbols(env.rewritings, map) val targets = getDirectTargets(rmap, MutableMapAccessor(k)) if (targets.exists(target => !env.bindings.contains(target.receiver.toVal))) throw MalformedStainlessCode(up, "Unsupported form of map update") Block(targets.toSeq map { target => val applied = updatedTarget(target, v) transform(Assignment(target.receiver, applied).copiedFrom(up), env) }, UnitLiteral().copiedFrom(up)).copiedFrom(up) case as @ FieldAssignment(o, id, v) => val so = exprOps.replaceFromSymbols(env.rewritings, o) val accessor = typeToAccessor(o.getType, id) val targets = getDirectTargets(so, accessor) if (targets.exists(target => !env.bindings.contains(target.receiver.toVal))) throw MalformedStainlessCode(as, "Unsupported form of field assignment") Block(targets.toSeq map { target => val applied = updatedTarget(target, v) transform(Assignment(target.receiver, applied).copiedFrom(as), env) }, UnitLiteral().copiedFrom(as)).copiedFrom(as) // we need to replace local fundef by the new updated fun defs. case l @ LetRec(fds, body) => val nfds = fds.map(fd => updateFunction(Inner(fd), env withLocals fds).toLocal) LetRec(nfds, transform(body, env withLocals fds)).copiedFrom(l) case e @ Ensuring(body, l @ Lambda(params, post)) => Ensuring(transform(body, env), Lambda(params, transform(post, env)).copiedFrom(l)).copiedFrom(e) case l @ Lambda(params, body) => val ft @ FunctionType(_, _) = l.getType val ownEffects = functionTypeEffects(ft) val aliasedParams: Seq[ValDef] = params.zipWithIndex.flatMap { case (vd, i) if ownEffects.contains(i) => Some(vd) case _ => None } if (aliasedParams.isEmpty) { Lambda(params, transform(body, env)).copiedFrom(l) } else { val freshLocals = aliasedParams.map(v => v.freshen) val rewritingMap = aliasedParams.zip(freshLocals).map(p => p._1.toVariable -> p._2.toVariable).toMap val freshBody = exprOps.replaceFromSymbols(rewritingMap, body) //WARNING: only works if side effects in Tuples are extracted from left to right, // in the ImperativeTransformation phase. val finalBody: Expr = Tuple(freshBody +: freshLocals.map(_.toVariable)) val wrappedBody: Expr = freshLocals.zip(aliasedParams).foldLeft(finalBody) { (bd, vp) => LetVar(vp._1, vp._2.toVariable, bd).copiedFrom(bd) } Lambda(params, transform(wrappedBody, env)).copiedFrom(l) } case fi @ FunctionInvocation(id, tps, args) => val fd = Outer(fi.tfd.fd) val rewrittenArgs = args.map(exprOps.replaceFromSymbols(env.rewritings, _)) if (!fi.tfd.flags.exists(_.name == "accessor") && !fi.tfd.flags.contains(IsPure)) checkAliasing(fi, rewrittenArgs) val nfi = FunctionInvocation( id, tps, rewrittenArgs.map(transform(_, env)) ).copiedFrom(fi) mapApplication(fd.params, args, nfi, fi.tfd.instantiate(analysis.getReturnType(fd)), effects(fd), env) case alr @ ApplyLetRec(id, tparams, tpe, tps, args) => val fd = Inner(env.locals(id)) val rewrittenArgs = args.map(exprOps.replaceFromSymbols(env.rewritings, _)) checkAliasing(alr, rewrittenArgs) val vis: Set[Variable] = varsInScope(fd) rewrittenArgs.flatMap(exprOps.variablesOf(_)).find(vis contains _) .foreach(v => context.reporter.fatalError(alr.getPos, "Illegal passing of aliased local variable: " + v)) val nfi = ApplyLetRec( id, tparams, FunctionType(fd.params.map(_.getType), analysis.getReturnType(fd)).copiedFrom(tpe), tps, rewrittenArgs.map(transform(_, env)) ).copiedFrom(alr) val resultType = typeOps.instantiateType(analysis.getReturnType(fd), (tparams zip tps).toMap) mapApplication(fd.params, args, nfi, resultType, effects(fd), env) case app @ Application(callee, args) => val ft @ FunctionType(from, to) = callee.getType val ftEffects = functionTypeEffects(ft) if (ftEffects.nonEmpty) { val rewrittenArgs = args.map(exprOps.replaceFromSymbols(env.rewritings, _)) checkAliasing(app, rewrittenArgs) val nfi = Application( transform(callee, env), rewrittenArgs.map(transform(_, env)) ).copiedFrom(app) val params = from.map(tpe => ValDef.fresh("x", tpe)) val appEffects = params.zipWithIndex.collect { case (vd, i) if ftEffects(i) => ModifyingEffect(vd.toVariable, Path.empty) } val to = makeFunctionTypeExplicit(ft).asInstanceOf[FunctionType].to mapApplication(params, args, nfi, to, appEffects.toSet, env) } else { Application(transform(callee, env), args.map(transform(_, env))).copiedFrom(app) } case Operator(es, recons) => recons(es.map(transform(_, env))) }).copiedFrom(e) } transformer.transform(body, env) } //for each fun def, all the vars the the body captures. //Only mutable types. def varsInScope(fd: FunAbstraction): Set[Variable] = { val allFreeVars = exprOps.variablesOf(fd.fullBody) val freeVars = allFreeVars -- fd.params.map(_.toVariable) freeVars.filter(v => isMutableType(v.tpe)) } // Given a receiver object (mutable class, array or map, usually as a reference id), // and a path of field/index access, build a copy of the original object, with // properly updated values def updatedTarget(target: Target, newValue: Expr): Expr = { def rec(receiver: Expr, path: Seq[Accessor]): Expr = path match { case ADTFieldAccessor(id) :: fs => val adt @ ADTType(_, tps) = receiver.getType val tcons = adt.getSort.constructors.find(_.fields.exists(_.id == id)).get val r = rec(Annotated(ADTSelector(receiver, id).copiedFrom(newValue), Seq(DropVCs)).copiedFrom(newValue), fs) ADT(tcons.id, tps, tcons.definition.fields.map { vd => if (vd.id == id) r else Annotated(ADTSelector(receiver, vd.id).copiedFrom(receiver), Seq(DropVCs)).copiedFrom(receiver) }).copiedFrom(newValue) case ClassFieldAccessor(id) :: fs => val optCd = receiver.getType match { case ct: ClassType => classForField(ct, id) case tp => throw FatalError(s"Cannot apply ClassFieldAccessor to type $tp") } val (cd, ct) = optCd.map(cd => (cd, cd.toType)).getOrElse { throw FatalError(s"Could find class for type ${receiver.getType}") } val casted = AsInstanceOf(receiver, cd.toType).copiedFrom(receiver) val r = rec(Annotated(ClassSelector(casted, id).copiedFrom(newValue), Seq(DropVCs)).copiedFrom(newValue), fs) ClassConstructor(ct, ct.tcd.fields.map { vd => if (vd.id == id) r else Annotated(ClassSelector(casted, vd.id).copiedFrom(receiver), Seq(DropVCs)).copiedFrom(receiver) }).copiedFrom(newValue) case TupleFieldAccessor(index) :: fs => val tt @ TupleType(_) = receiver.getType val r = rec(Annotated(TupleSelect(receiver, index).copiedFrom(newValue), Seq(DropVCs)).copiedFrom(newValue), fs) Tuple((1 to tt.dimension).map { i => if (i == index) r else Annotated(TupleSelect(receiver, i).copiedFrom(receiver), Seq(DropVCs)).copiedFrom(receiver) }).copiedFrom(newValue) case ArrayAccessor(index) :: fs => val r = rec(Annotated(ArraySelect(receiver, index).copiedFrom(newValue), Seq(DropVCs)).copiedFrom(newValue), fs) ArrayUpdated(receiver, index, r).copiedFrom(newValue) case MutableMapAccessor(index) :: fs => val r = rec(Annotated(MutableMapApply(receiver, index).copiedFrom(newValue), Seq(DropVCs)).copiedFrom(newValue), fs) MutableMapUpdated(receiver, index, r).copiedFrom(newValue) case Nil => newValue } target match { case Target(receiver, None, path) => rec(receiver, path.toSeq) case Target(receiver, Some(condition), path) if effects(condition).nonEmpty => throw MalformedStainlessCode(condition, s"Effects are not allowed in condition of effects: ${condition.asString}") case Target(receiver, Some(condition), path) => Annotated( AsInstanceOf( IfExpr( condition.setPos(newValue), rec(receiver, path.toSeq), receiver ).copiedFrom(newValue), receiver.getType ).copiedFrom(newValue), Seq(DropVCs) ).copiedFrom(newValue) } } Some(transformer.transform(updateFunction(Outer(fd), Environment.empty).toFun)) } override protected def extractSort(analysis: SymbolsAnalysis, sort: ADTSort): ADTSort = analysis.transformer.transform(sort) override protected def extractClass(analysis: SymbolsAnalysis, cd: ClassDef): ClassDef = analysis.transformer.transform(cd) } object AntiAliasing { def apply(trees: Trees)(implicit ctx: inox.Context): ExtractionPipeline { val s: trees.type val t: trees.type } = new AntiAliasing { override val s: trees.type = trees override val t: trees.type = trees override val context = ctx } }
RuralDeer/RrokDemo
rrokclient/src/main/java/com/cn/request/enums/DataSource.java
package com.cn.request.enums; /** * Date: 2019/7/22 * <p> * Time: 2:02 PM * <p> * author: 鹿文龙 */ public enum DataSource { /** * 网络 */ NET, /** * 缓存 */ CACHE }
terifan/HuffmanCodec
src/org/terifan/compression/util/Log.java
package org.terifan.compression.util; import java.io.PrintStream; public class Log { public final static PrintStream out = System.out; public static int LEVEL = 0; private final static String INDENT = "... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... "; private static int mIndent; public static void inc() { mIndent++; } public static void dec() { mIndent--; } public static void s(String aMessage, Object... aParams) { logImpl(0, aMessage, aParams); } public static void e(String aMessage, Object... aParams) { logImpl(1, aMessage, aParams); } public static void w(String aMessage, Object... aParams) { logImpl(2, aMessage, aParams); } public static void i(String aMessage, Object... aParams) { logImpl(3, aMessage, aParams); } public static void v(String aMessage, Object... aParams) { logImpl(4, aMessage, aParams); } public static void d(String aMessage, Object... aParams) { logImpl(5, aMessage, aParams); } private static void logImpl(int aLevel, String aMessage, Object... aParams) { if (aLevel <= LEVEL && aMessage != null) { String message = INDENT.substring(0, 4 * Math.min(mIndent, 20)) + String.format(aMessage, aParams); StackTraceElement[] trace = Thread.currentThread().getStackTrace(); String className = trace[3].getClassName(); className = className.substring(className.lastIndexOf(".") + 1); String methodName = trace[3].getMethodName(); String loggerName = trace[3].getFileName() + ":" + trace[3].getLineNumber(); String type; switch (aLevel) { case 0: type = "SEVERE"; break; case 1: type = "ERROR"; break; case 2: type = "WARN"; break; case 3: type = "INFO"; break; case 4: type = "VERBOSE"; break; case 5: type = "DEBUG"; break; default: type = ""; break; } System.out.printf("%-30s%-30s%-30s%-7s %s\n", loggerName, className, methodName, type, message); } } public static void hexDump(byte[] aBuffer) { if (aBuffer == null) { Log.out.println("hexdump: null"); return; } if (aBuffer.length == 0) { Log.out.println("hexdump: empty"); return; } int LW = 32; int MR = 1000; StringBuilder binText = new StringBuilder(""); StringBuilder hexText = new StringBuilder(""); for (int row = 0, offset = 0; offset < aBuffer.length && row < MR; row++) { hexText.append(String.format("%04d: ", row * LW)); int padding = 3 * LW + LW / 8; for (int i = 0; offset < aBuffer.length && i < LW; i++) { int c = 0xff & aBuffer[offset++]; hexText.append(String.format("%02x ", c)); binText.append(Character.isISOControl(c) ? '.' : (char)c); padding -= 3; if ((i & 7) == 7) { hexText.append(" "); padding--; } } for (int i = 0; i < padding; i++) { hexText.append(" "); } Log.out.println(hexText.append(binText).toString()); binText.setLength(0); hexText.setLength(0); } } public static String toString(byte[] aValue) { return aValue == null ? null : new String(aValue); } }
best08618/asylo
gcc-gcc-7_3_0-release/libgomp/testsuite/libgomp.c/pr45784.c
/* PR c/45784 */ /* { dg-do run } */ void foo (int n) { char *p, vla[2 * n]; int i; #pragma omp parallel for for (p = vla; p < vla + (sizeof (vla) / sizeof (vla[0])); p++) *p = ' '; #pragma omp parallel for for (i = 0; i < 2 * n; i++) if (vla[i] != ' ') __builtin_abort (); } void bar (int n) { char *p, vla1[n], vla2[n * 2], vla3[n * 3], vla4[n * 4]; int i; __builtin_memset (vla4, ' ', n * 4); #pragma omp parallel for for (p = vla4 + sizeof (vla1); p < vla4 + sizeof (vla3) - sizeof (vla2) + sizeof (vla1); p += sizeof (vla4) / sizeof (vla4)) p[0] = '!'; #pragma omp parallel for for (i = 0; i < n * 4; i++) if (vla4[i] != ((i >= n && i < 2 * n) ? '!' : ' ')) __builtin_abort (); } int main () { volatile int n; n = 128; foo (n); bar (n); return 0; }
fnando/signal
test/test_helper.rb
# frozen_string_literal: true require "simplecov" SimpleCov.start require "bundler/setup" require "active_record" I18n.enforce_available_locales = false require "minitest/utils" require "minitest/autorun" require "voltage" require "voltage/mock" require "support/observable" require "support/observable_with_call" require "support/user" require "support/callable" require "support/emitter" ActiveRecord::Base.establish_connection( adapter: "sqlite3", database: ":memory:" ) ActiveRecord::Schema.define(version: 0) do create_table :users do |t| t.string :username end end
Salman-Shaik/truth-or-dare
src/webapp/public/js/common/networkCalls.js
<filename>src/webapp/public/js/common/networkCalls.js import { showErrorAlert } from "./methods"; export const fetchGames = async () => await fetch("/games") .then((r) => r.text()) .then((data) => JSON.parse(data)) .catch((e) => showErrorAlert("Didn't Fetch, Please Try Again!")); export const fetchParticipants = async () => await fetch("/participants") .then((r) => r.text()) .then((data) => JSON.parse(data)) .catch((e) => showErrorAlert("Didn't Fetch, Please Try Again!")); export const fetchTruth = async () => await fetch("/truth") .then((r) => r.text()) .catch((e) => showErrorAlert("Didn't Fetch, Please Try Again!")); export const fetchDare = async () => await fetch("/dare") .then((r) => r.text()) .catch((e) => showErrorAlert("Didn't Fetch, Please Try Again!")); export const saveParticipants = async (body) => await fetch("/participants", { headers: { "Content-Type": "application/json" }, method: "post", body: body, }) .then((r) => +r.status) .catch((e) => showErrorAlert("Didn't Save, Please Try Again!")); export const enableGroupEdition = async () => await fetch("/groupEdition", { method: "get", }) .then((r) => +r.status) .catch((e) => showErrorAlert("Didn't Save, Please Try Again!")); export const saveMode = async (body) => await fetch("mode", { headers: { "Content-Type": "application/json" }, method: "post", body: JSON.stringify(body), }) .then((r) => +r.status) .catch((e) => showErrorAlert("Didn't Save, Please Try Again!")); export const deleteGame = async () => await fetch("/game", { headers: { "Content-Type": "application/json" }, method: "delete", }).catch((e) => showErrorAlert("Didn't Delete, Please Try Again!")); export const updateGameStatus = async (status) => await fetch("/status", { headers: { "Content-Type": "application/json" }, method: "put", body: JSON.stringify({ status }), }).catch((e) => showErrorAlert("Didn't Update, Please Try Again!"));
zayyaroo06/connect-java-sdk
src/main/java/com/squareup/connect/models/V1VariationInventoryAlertType.java
<gh_stars>0 /* * Square Connect API * Client library for accessing the Square Connect APIs * * OpenAPI spec version: 2.0 * Contact: <EMAIL> * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.squareup.connect.models; import java.util.Objects; import io.swagger.annotations.ApiModel; import com.fasterxml.jackson.annotation.JsonCreator; /** * */ public enum V1VariationInventoryAlertType { LOW_QUANTITY("LOW_QUANTITY"), NONE("NONE"), INVESTMENT("INVESTMENT"), LOAN("LOAN"), SAVINGS("SAVINGS"), OTHER("OTHER"); private String value; V1VariationInventoryAlertType(String value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static V1VariationInventoryAlertType fromValue(String text) { for (V1VariationInventoryAlertType b : V1VariationInventoryAlertType.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } }
dosier/G-Earth
G-Earth/src/main/java/wasm/disassembly/values/WFloat.java
package wasm.disassembly.values; import java.io.BufferedInputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; public class WFloat { public static float read(BufferedInputStream in) throws IOException { byte[] bytes = new byte[4]; in.read(bytes); return ByteBuffer.wrap(bytes).getFloat(); } public static void write(float value, OutputStream out) throws IOException { byte[] bytes = new byte[4]; ByteBuffer.wrap(bytes).putFloat(value); out.write(bytes); } }
kierangillen/force
src/desktop/components/fair_week_marketing/Meta.js
import PropTypes from "prop-types" import React from "react" export const FairWeekMeta = props => { const { meta: { description, title } } = props return ( <div> <title>{title}</title> <meta property="og:title" content={title} /> <meta property="description" content={description} /> <meta property="og:description" content={description} /> <meta property="twitter:description" content={description} /> </div> ) } FairWeekMeta.propTypes = { meta: PropTypes.object, }
HJBDev/vue-atlas
src/Loading/index.js
export { default as VaLoading } from './install'
sarang-apps/darshan_browser
ios/chrome/browser/autofill/form_input_suggestions_provider.h
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef IOS_CHROME_BROWSER_AUTOFILL_FORM_INPUT_SUGGESTIONS_PROVIDER_H_ #define IOS_CHROME_BROWSER_AUTOFILL_FORM_INPUT_SUGGESTIONS_PROVIDER_H_ #import <Foundation/Foundation.h> #include "ios/chrome/browser/autofill/form_suggestion_client.h" namespace autofill { struct FormActivityParams; } namespace web { struct FormActivityParams; class WebState; } // namespace web @class FormSuggestion; @protocol FormInputNavigator; @protocol FormInputSuggestionsProvider; // Block type to provide form suggestions asynchronously. typedef void (^FormSuggestionsReadyCompletion)( NSArray<FormSuggestion*>* suggestions, id<FormInputSuggestionsProvider> provider); // Represents an object that can provide form input suggestions. @protocol FormInputSuggestionsProvider<FormSuggestionClient> // A delegate for form navigation. @property(nonatomic, weak) id<FormInputNavigator> formInputNavigator; // Asynchronously retrieves form suggestions from this provider for the // specified form/field and returns it via |accessoryViewUpdateBlock|. View // will be nil if no accessories are available from this provider. - (void)retrieveSuggestionsForForm:(const autofill::FormActivityParams&)params webState:(web::WebState*)webState accessoryViewUpdateBlock: (FormSuggestionsReadyCompletion)accessoryViewUpdateBlock; // Notifies this provider that the accessory view is going away. - (void)inputAccessoryViewControllerDidReset; @end #endif // IOS_CHROME_BROWSER_AUTOFILL_FORM_INPUT_SUGGESTIONS_PROVIDER_H_
go-tk/jroh
go/apicommon/incomingrpc.go
package apicommon import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" ) type IncomingRPC struct { Namespace string ServiceName string MethodName string FullMethodName string MethodIndex int Params Model Results Model RemoteIP string InboundHeader http.Header OutboundHeader http.Header TraceID string RawParams []byte StatusCode int ErrorCode ErrorCode RawResults []byte handler IncomingRPCHandler filters []IncomingRPCHandler nextFilterIndex int reader io.Reader readRawParamsCache struct { err error has bool } loadParamsCache struct { err error has bool } encodeResultsCache struct { err error has bool } } func (ir *IncomingRPC) SetHandler(handler IncomingRPCHandler) { ir.handler = handler } func (ir *IncomingRPC) SetFilters(filters []IncomingRPCHandler) { ir.filters = filters } func (ir *IncomingRPC) SetReader(reader io.Reader) { ir.reader = reader } func (ir *IncomingRPC) Do(ctx context.Context) (returnedErr error) { i := ir.nextFilterIndex ir.nextFilterIndex++ n := len(ir.filters) if i > n { panic("too many calls") } if i == 0 { ctx = MakeContextWithIncomingRPC(ctx, ir) } if i < n { return ir.filters[i](ctx, ir) } if err := ir.LoadParams(ctx); err != nil { return fmt.Errorf("load params: %w", err) } if err := ir.handler(ctx, ir); err != nil { if error, ok := err.(*Error); ok { ir.StatusCode = error.StatusCode ir.ErrorCode = error.Code } else { if errIsTemporary(err) { ir.StatusCode = http.StatusServiceUnavailable } else { ir.StatusCode = http.StatusInternalServerError } ir.ErrorCode = -1 } return err } return nil } func (ir *IncomingRPC) LoadParams(ctx context.Context) error { cache := &ir.loadParamsCache if !cache.has { cache.err = ir.doLoadParams(ctx) cache.has = true } return cache.err } func (ir *IncomingRPC) doLoadParams(ctx context.Context) error { if err := ir.ReadRawParams(); err != nil { ir.StatusCode = http.StatusBadRequest ir.ErrorCode = -1 return err } if err := ir.decodeRawParams(ctx); err != nil { ir.StatusCode = http.StatusBadRequest ir.ErrorCode = -1 return err } validationContext := NewValidationContext(ctx) if !ir.Params.Validate(validationContext) { error := NewInvalidParamsError() error.Details = validationContext.ErrorDetails() ir.StatusCode = error.StatusCode ir.ErrorCode = error.Code return error } return nil } func (ir *IncomingRPC) decodeRawParams(ctx context.Context) error { if err := json.Unmarshal(ir.RawParams, ir.Params); err != nil { return fmt.Errorf("unmarshal json; objectType=\"%T\": %w", ir.Params, err) } return nil } func (ir *IncomingRPC) ReadRawParams() error { cache := &ir.readRawParamsCache if !cache.has { cache.err = ir.doReadRawParams() cache.has = true } return cache.err } func (ir *IncomingRPC) doReadRawParams() error { var buffer bytes.Buffer n, err := buffer.ReadFrom(ir.reader) if err != nil { return fmt.Errorf("read data: %w", err) } if n == 0 { return nil } ir.RawParams = buffer.Bytes() return nil } func (ir *IncomingRPC) EncodeResults() error { cache := &ir.encodeResultsCache if !cache.has { cache.err = ir.doEncodeResults() cache.has = true } return cache.err } func (ir *IncomingRPC) doEncodeResults() error { var buffer bytes.Buffer encoder := json.NewEncoder(&buffer) encoder.SetEscapeHTML(false) if DebugMode { encoder.SetIndent("", " ") } if err := encoder.Encode(ir.Results); err != nil { return fmt.Errorf("marshal json; objectType=\"%T\": %w", ir.Results, err) } rawResults := buffer.Bytes() if !DebugMode { // Remove trailing '\n' rawResults = rawResults[:len(rawResults)-1] } ir.RawResults = rawResults return nil } type IncomingRPCHandler func(ctx context.Context, incomingRPC *IncomingRPC) (err error) type contextValueIncomingRPC struct{} func MakeContextWithIncomingRPC(ctx context.Context, incomingRPC *IncomingRPC) context.Context { return context.WithValue(ctx, contextValueIncomingRPC{}, incomingRPC) } func GetIncomingRPCFromContext(ctx context.Context) (*IncomingRPC, bool) { incomingRPC, ok := ctx.Value(contextValueIncomingRPC{}).(*IncomingRPC) return incomingRPC, ok }
pago/AufgabenViewer
src/com/pagosoft/myview/view/PDFViewerPanel.java
/* * Copyright (c) 2010 <NAME>. All rights reserved. */ package com.pagosoft.myview.view; import com.google.inject.Inject; import com.pagosoft.eventbus.ApplicationListener; import com.pagosoft.eventbus.EventBus; import com.pagosoft.myview.domain.Document; import com.pagosoft.myview.events.DocumentChangedEvent; import com.pagosoft.myview.events.ExerciseChangedEvent; import com.pagosoft.myview.util.Utils; import com.sun.pdfview.PDFFile; import com.sun.pdfview.PDFPage; import com.sun.pdfview.PagePanel; import javax.swing.*; import java.awt.*; import java.io.*; import java.nio.ByteBuffer; /** * Created by IntelliJ IDEA. * User: pago * Date: 02.01.2010 * Time: 23:16:48 * To change this template use File | Settings | File Templates. */ public class PDFViewerPanel extends JPanel { @Inject public PDFViewerPanel(final EventBus eventBus) { super(new BorderLayout()); setBackground(Color.WHITE); setBorder(BorderFactory.createLineBorder(new Color(0x676767), 20)); setPreferredSize(new Dimension(700, 900)); // fix potential repaint issues final PagePanel viewer = new PagePanel(); viewer.setBackground(Color.WHITE); add(viewer, BorderLayout.CENTER); eventBus.add(ExerciseChangedEvent.class, new ApplicationListener<ExerciseChangedEvent>() { public void handleEvent(ExerciseChangedEvent event) { //load a pdf from a byte buffer Document doc = event.getSource().getNextDocument(); eventBus.fireSwingEvent(new DocumentChangedEvent(doc)); try { PDFFile pdffile = Utils.toPDFFile(doc); // show the first page PDFPage page = pdffile.getPage(0); viewer.showPage(page); } catch (Exception e) { e.printStackTrace(); } } }); } }
giubueno/services-core
services/catarse/db/migrate/20200715210652_creation_and_push_to_online_rdevents_on_solidarity_projects.rb
<reponame>giubueno/services-core class CreationAndPushToOnlineRdeventsOnSolidarityProjects < ActiveRecord::Migration[4.2] def up execute <<-SQL CREATE OR REPLACE FUNCTION public.is_solidarity_project(project_id integer) RETURNS boolean LANGUAGE sql AS $$ select exists( select integration.project_id from public.project_integrations integration where integration.project_id = $1 and integration.name = 'SOLIDARITY_SERVICE_FEE' ); $$ ; CREATE OR REPLACE FUNCTION public.flexible_project_rdevents_dispatcher() RETURNS trigger LANGUAGE plpgsql AS $function$ DECLARE v_user_id integer; v_project_id integer; v_enabled_events text[]; v_mode_concat text; BEGIN v_enabled_events = ARRAY['online', 'waiting_funds', 'successful', 'failed']; SELECT project_id FROM flexible_projects WHERE id = NEW.flexible_project_id INTO v_project_id; SELECT user_id FROM projects WHERE id = v_project_id INTO v_user_id; v_mode_concat = (CASE WHEN is_solidarity_project(NEW.flexible_project_id) THEN 'solidaria_project_' ELSE 'flex_project_' END); IF NEW.to_state = ANY(v_enabled_events) THEN INSERT INTO public.rdevents (user_id, project_id, event_name, created_at) VALUES (v_user_id, v_project_id, v_mode_concat||NEW.to_state, now()); END IF; RETURN NULL; END; $function$ ; CREATE OR REPLACE FUNCTION public.project_rdevents_dispatcher() RETURNS trigger LANGUAGE plpgsql AS $function$ DECLARE v_enabled_events text[]; v_project public.projects; v_mode_concat text; BEGIN v_enabled_events = ARRAY['in_analysis', 'approved', 'online', 'waiting_funds', 'successful', 'failed']; SELECT * FROM projects WHERE id = NEW.project_id INTO v_project; v_mode_concat = (CASE WHEN is_solidarity_project(NEW.project_id) THEN 'solidaria_project_' WHEN v_project.mode = 'flex' THEN 'flex_project_' WHEN v_project.mode = 'sub' THEN 'sub_project_' ELSE 'project_' END); IF NEW.to_state = ANY(v_enabled_events) THEN INSERT INTO public.rdevents (user_id, project_id, event_name, created_at) VALUES (v_project.user_id, NEW.project_id, v_mode_concat||NEW.to_state, now()); END IF; RETURN NULL; END; $function$ ; drop trigger project_received_conversion on projects; drop function project_received_conversion; SQL end def down execute <<-SQL DROP FUNCTION public.is_solidarity_project(project_id integer); CREATE OR REPLACE FUNCTION public.project_rdevents_dispatcher() RETURNS trigger LANGUAGE plpgsql AS $function$ DECLARE v_enabled_events text[]; v_project public.projects; v_mode_concat text; BEGIN v_enabled_events = ARRAY['in_analysis', 'approved', 'online', 'waiting_funds', 'successful', 'failed']; SELECT * FROM projects WHERE id = NEW.project_id INTO v_project; v_mode_concat = (CASE WHEN v_project.mode = 'flex' THEN 'flex_project_' WHEN v_project.mode = 'sub' THEN 'sub_project_' ELSE 'project_' END); IF NEW.to_state = ANY(v_enabled_events) THEN INSERT INTO public.rdevents (user_id, project_id, event_name, created_at) VALUES (v_project.user_id, NEW.project_id, v_mode_concat||NEW.to_state, now()); END IF; RETURN NULL; END; $function$ ; CREATE OR REPLACE FUNCTION public.flexible_project_rdevents_dispatcher() RETURNS trigger LANGUAGE plpgsql AS $function$ DECLARE v_user_id integer; v_project_id integer; v_enabled_events text[]; BEGIN v_enabled_events = ARRAY['online', 'waiting_funds', 'successful', 'failed']; SELECT project_id FROM flexible_projects WHERE id = NEW.flexible_project_id INTO v_project_id; SELECT user_id FROM projects WHERE id = v_project_id INTO v_user_id; IF NEW.to_state = ANY(v_enabled_events) THEN INSERT INTO public.rdevents (user_id, project_id, event_name, created_at) VALUES (v_user_id, v_project_id, 'flex_project_'||NEW.to_state, now()); END IF; RETURN NULL; END; $function$ ; --- CREATE OR REPLACE FUNCTION public.project_received_conversion() RETURNS trigger LANGUAGE plpgsql AS $function$ DECLARE _rd_event_name text; BEGIN _rd_event_name := (CASE NEW.mode WHEN 'sub' THEN 'sub_project_draft' ELSE 'project_draft' END); INSERT INTO public.rdevents (user_id, project_id, event_name) VALUES (NEW.user_id, NEW.id, _rd_event_name); RETURN NULL; END; $function$ ; --- SQL end end
longtuge/app
src/main/java/app/coolweather/com/myapplication/model/shopping/common/util/TokenUtils.java
<reponame>longtuge/app<filename>src/main/java/app/coolweather/com/myapplication/model/shopping/common/util/TokenUtils.java package app.coolweather.com.myapplication.model.shopping.common.util; import android.content.Context; import java.util.HashMap; import java.util.Map; public class TokenUtils { // Volley请求类提供了一个 getHeaers()的方法,重载这个方法可以自定义HTTP 的头信息。 public static Map<String, String> getHeaders(Context context) { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/json"); headers.put("Content-Type", "application/json; charset=UTF-8"); // headers.put("accessToken", SharePreferenceUtilNew.getInstance() // .getAccessToken()); // headers.put("accessToken","94b9261a-b0d5-4456-beff-e17def1b12bb"); return headers; } }
jperedadnr/FXGL
fxgl-base/src/main/java/com/almasb/fxgl/physics/box2d/collision/WorldManifold.java
<reponame>jperedadnr/FXGL<gh_stars>1-10 /* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB (<EMAIL>). * See LICENSE for details. */ package com.almasb.fxgl.physics.box2d.collision; import com.almasb.fxgl.core.math.Vec2; import com.almasb.fxgl.physics.box2d.common.JBoxSettings; import com.almasb.fxgl.physics.box2d.common.JBoxUtils; import com.almasb.fxgl.physics.box2d.common.Rotation; import com.almasb.fxgl.physics.box2d.common.Transform; /** * This is used to compute the current state of a contact manifold. * * @author daniel */ public final class WorldManifold { /** * World vector pointing from A to B */ public final Vec2 normal = new Vec2(); /** * World contact point (point of intersection) */ public final Vec2[] points = new Vec2[JBoxSettings.maxManifoldPoints]; /** * A negative value indicates overlap, in meters. */ private final float[] separations = new float[JBoxSettings.maxManifoldPoints]; public WorldManifold() { for (int i = 0; i < JBoxSettings.maxManifoldPoints; i++) { points[i] = new Vec2(); } } private final Vec2 pool3 = new Vec2(); private final Vec2 pool4 = new Vec2(); public void initialize(final Manifold manifold, final Transform xfA, float radiusA, final Transform xfB, float radiusB) { if (manifold.pointCount == 0) { return; } switch (manifold.type) { case CIRCLES: { final Vec2 pointA = pool3; final Vec2 pointB = pool4; normal.x = 1; normal.y = 0; Vec2 v = manifold.localPoint; // Transform.mulToOutUnsafe(xfA, manifold.localPoint, pointA); // Transform.mulToOutUnsafe(xfB, manifold.points[0].localPoint, pointB); pointA.x = (xfA.q.c * v.x - xfA.q.s * v.y) + xfA.p.x; pointA.y = (xfA.q.s * v.x + xfA.q.c * v.y) + xfA.p.y; Vec2 mp0p = manifold.points[0].localPoint; pointB.x = (xfB.q.c * mp0p.x - xfB.q.s * mp0p.y) + xfB.p.x; pointB.y = (xfB.q.s * mp0p.x + xfB.q.c * mp0p.y) + xfB.p.y; if (JBoxUtils.distanceSquared(pointA, pointB) > JBoxSettings.EPSILON * JBoxSettings.EPSILON) { normal.x = pointB.x - pointA.x; normal.y = pointB.y - pointA.y; normal.getLengthAndNormalize(); } final float cAx = normal.x * radiusA + pointA.x; final float cAy = normal.y * radiusA + pointA.y; final float cBx = -normal.x * radiusB + pointB.x; final float cBy = -normal.y * radiusB + pointB.y; points[0].x = (cAx + cBx) * .5f; points[0].y = (cAy + cBy) * .5f; separations[0] = (cBx - cAx) * normal.x + (cBy - cAy) * normal.y; } break; case FACE_A: { final Vec2 planePoint = pool3; Rotation.mulToOutUnsafe(xfA.q, manifold.localNormal, normal); Transform.mulToOut(xfA, manifold.localPoint, planePoint); final Vec2 clipPoint = pool4; for (int i = 0; i < manifold.pointCount; i++) { // b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint); // b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint, // normal)) * normal; // b2Vec2 cB = clipPoint - radiusB * normal; // points[i] = 0.5f * (cA + cB); Transform.mulToOut(xfB, manifold.points[i].localPoint, clipPoint); // use cA as temporary for now // cA.set(clipPoint).subLocal(planePoint); // float scalar = radiusA - Vec2.dot(cA, normal); // cA.set(normal).mulLocal(scalar).addLocal(clipPoint); // cB.set(normal).mulLocal(radiusB).subLocal(clipPoint).negateLocal(); // points[i].set(cA).addLocal(cB).mulLocal(0.5f); final float scalar = radiusA - ((clipPoint.x - planePoint.x) * normal.x + (clipPoint.y - planePoint.y) * normal.y); final float cAx = normal.x * scalar + clipPoint.x; final float cAy = normal.y * scalar + clipPoint.y; final float cBx = -normal.x * radiusB + clipPoint.x; final float cBy = -normal.y * radiusB + clipPoint.y; points[i].x = (cAx + cBx) * .5f; points[i].y = (cAy + cBy) * .5f; separations[i] = (cBx - cAx) * normal.x + (cBy - cAy) * normal.y; } } break; case FACE_B: final Vec2 planePoint = pool3; Rotation.mulToOutUnsafe(xfB.q, manifold.localNormal, normal); Transform.mulToOut(xfB, manifold.localPoint, planePoint); // final Mat22 R = xfB.q; // normal.x = R.ex.x * manifold.localNormal.x + R.ey.x * manifold.localNormal.y; // normal.y = R.ex.y * manifold.localNormal.x + R.ey.y * manifold.localNormal.y; // final Vec2 v = manifold.localPoint; // planePoint.x = xfB.p.x + xfB.q.ex.x * v.x + xfB.q.ey.x * v.y; // planePoint.y = xfB.p.y + xfB.q.ex.y * v.x + xfB.q.ey.y * v.y; final Vec2 clipPoint = pool4; for (int i = 0; i < manifold.pointCount; i++) { // b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint); // b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint, // normal)) * normal; // b2Vec2 cA = clipPoint - radiusA * normal; // points[i] = 0.5f * (cA + cB); Transform.mulToOut(xfA, manifold.points[i].localPoint, clipPoint); // cB.set(clipPoint).subLocal(planePoint); // float scalar = radiusB - Vec2.dot(cB, normal); // cB.set(normal).mulLocal(scalar).addLocal(clipPoint); // cA.set(normal).mulLocal(radiusA).subLocal(clipPoint).negateLocal(); // points[i].set(cA).addLocal(cB).mulLocal(0.5f); // points[i] = 0.5f * (cA + cB); // // clipPoint.x = xfA.p.x + xfA.q.ex.x * manifold.points[i].localPoint.x + xfA.q.ey.x * // manifold.points[i].localPoint.y; // clipPoint.y = xfA.p.y + xfA.q.ex.y * manifold.points[i].localPoint.x + xfA.q.ey.y * // manifold.points[i].localPoint.y; final float scalar = radiusB - ((clipPoint.x - planePoint.x) * normal.x + (clipPoint.y - planePoint.y) * normal.y); final float cBx = normal.x * scalar + clipPoint.x; final float cBy = normal.y * scalar + clipPoint.y; final float cAx = -normal.x * radiusA + clipPoint.x; final float cAy = -normal.y * radiusA + clipPoint.y; points[i].x = (cAx + cBx) * .5f; points[i].y = (cAy + cBy) * .5f; separations[i] = (cAx - cBx) * normal.x + (cAy - cBy) * normal.y; } // Ensure normal points from A to B. normal.x = -normal.x; normal.y = -normal.y; break; } } }
puyanLiu/LPYFramework
node-demo/lesson1/app6.js
/** * async(https://github.com/caolan/async ) * demo https://github.com/alsotang/async_demo */ var async = require('async'); // 并发连接数的计数器 var concurrencyCount = 0; var fetchUrl = function (url, callback) { // delay 的值在 2000 以内,是个随机的整数 var delay = parseInt((Math.random() * 10000000) % 2000, 10); concurrencyCount++; console.log('现在的并发数是', concurrencyCount, ',正在抓取的是', url, ',耗时' + delay + '毫秒'); setTimeout(function () { concurrencyCount--; callback(null, url + ' html content'); }, delay); }; // fetchUrl('http://www.baidu.com', function (err, content) { // // do something with `content` // }); var urls = []; for(var i = 0; i < 30; i++) { urls.push('http://datasource_' + i); } async.mapLimit(urls, 5, function (url, callback) { fetchUrl(url, callback); }, function (err, result) { console.log('final:'); console.log(result); });
PesiTheWizard/townsquare
server/game/cards/01-DTR/Ambush.js
<reponame>PesiTheWizard/townsquare const ActionCard = require('../../actioncard.js'); const GameActions = require('../../GameActions/index.js'); class Ambush extends ActionCard { setupCardAbilities(ability) { this.job({ title: 'Ambush', playType: 'noon', cost: ability.costs.bootLeader(), target: { activePromptTitle: 'Choose a dude to ambush', waitingPromptTitle: 'Waiting for opponent to choose a dude', cardCondition: { location: 'play area' }, cardType: ['dude'] }, handler: (context) => { if(!context.target.isWanted()) { this.game.once('onLeaderPosseFormed', event => event.shootout.actOnLeaderPosse(dude => this.game.resolveGameAction(GameActions.addBounty({ card: dude }), context))); this.game.addMessage('{0}\'s posse all receive 1 bounty since {1} is not wanted', context.player, context.target); } }, message: context => this.game.addMessage('{0} uses {1} to lead an ambush against {2}', context.player, this, context.target), onSuccess: (job, context) => { if(job.mark.location === 'play area') { this.game.resolveGameAction(GameActions.aceCard({ card: job.mark }), context).thenExecute(() => { this.game.addMessage('{0} successfuly ambushed and aced {1}', context.player, job.mark); }); } } }); } } Ambush.code = '01114'; module.exports = Ambush;
jasonnam/buck
src/com/facebook/buck/util/ContextualProcessExecutor.java
<reponame>jasonnam/buck<filename>src/com/facebook/buck/util/ContextualProcessExecutor.java /* * Copyright (c) Facebook, Inc. and its affiliates. * * 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.facebook.buck.util; import com.facebook.buck.core.build.execution.context.actionid.ActionId; import com.facebook.buck.event.IsolatedEventBus; import com.facebook.buck.util.timing.Clock; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import java.io.IOException; import java.io.PrintStream; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; /** ProcessExecutor with an additional context */ public class ContextualProcessExecutor extends DelegateProcessExecutor { public static final String ANSI_ESCAPE_SEQUENCES_ENABLED = "ansi_escape_sequences_enabled"; public static final String VERBOSITY = "verbosity"; private final ImmutableMap<String, String> context; public ContextualProcessExecutor(ProcessExecutor delegate, ImmutableMap<String, String> context) { super(delegate); this.context = context; } @Override public LaunchedProcess launchProcess(ProcessExecutorParams params) throws IOException { return getDelegate().launchProcess(params, context); } @Override public LaunchedProcess launchProcess( ProcessExecutorParams params, ImmutableMap<String, String> context) throws IOException { return getDelegate().launchProcess(params, MoreMaps.merge(this.context, context)); } @Override public Result launchAndExecute(ProcessExecutorParams params) throws InterruptedException, IOException { return getDelegate().launchAndExecute(params, context); } @Override public Result launchAndExecute(ProcessExecutorParams params, ImmutableMap<String, String> context) throws InterruptedException, IOException { return getDelegate().launchAndExecute(params, MoreMaps.merge(this.context, context)); } @Override public Result launchAndExecute( ProcessExecutorParams params, Set<Option> options, Optional<Stdin> stdin, Optional<Long> timeOutMs, Optional<Consumer<Process>> timeOutHandler) throws InterruptedException, IOException { return getDelegate() .launchAndExecute(params, context, options, stdin, timeOutMs, timeOutHandler); } @Override public Result launchAndExecute( ProcessExecutorParams params, ImmutableMap<String, String> context, Set<Option> options, Optional<Stdin> stdin, Optional<Long> timeOutMs, Optional<Consumer<Process>> timeOutHandler) throws InterruptedException, IOException { return getDelegate() .launchAndExecute( params, MoreMaps.merge(this.context, context), options, stdin, timeOutMs, timeOutHandler); } @Override public ProcessExecutor cloneWithOutputStreams( PrintStream newStdOutStream, PrintStream newStdErrStream) { return new ContextualProcessExecutor( getDelegate().cloneWithOutputStreams(newStdOutStream, newStdErrStream), context); } @Override public ProcessExecutor withDownwardAPI( DownwardApiProcessExecutorFactory factory, NamedPipeEventHandlerFactory namedPipeEventHandlerFactory, IsolatedEventBus buckEventBus, ActionId actionId, Clock clock) { String ansiEnabled = context.get(ANSI_ESCAPE_SEQUENCES_ENABLED); Preconditions.checkNotNull(ansiEnabled, ANSI_ESCAPE_SEQUENCES_ENABLED + " key is not provided"); boolean ansiEscapeSequencesEnabled = Boolean.parseBoolean(ansiEnabled); String verbosityString = context.get(VERBOSITY); Preconditions.checkNotNull(verbosityString, VERBOSITY + " key is not provided"); Verbosity verbosity = Verbosity.valueOf(verbosityString); return factory.create( this, namedPipeEventHandlerFactory, ConsoleParams.of(ansiEscapeSequencesEnabled, verbosity), buckEventBus, actionId, clock); } }
falost/avatar-box
uni_modules/uni-sec-check/uniCloud/cloudfunctions/common/uni-sec-check/utils/type.js
const _toString = Object.prototype.toString function isPlainObject(obj) { return _toString.call(obj) === '[object Object]' } function isFn(fn) { return typeof fn === 'function' } module.exports = { isPlainObject, isFn }
teambition/urbs-console
src/bll/user_test.go
<gh_stars>1-10 package bll import ( "context" "testing" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/teambition/urbs-console/src/service" "github.com/teambition/urbs-console/src/service/mock_service" "github.com/teambition/urbs-console/src/tpl" "github.com/teambition/urbs-setting/src/schema" ) func TestUser(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() usMock := mock_service.NewMockUrbsSettingInterface(ctrl) user := &User{services: service.NewServices(testDB)} user.services.UrbsSetting = usMock t.Run(`BatchAdd`, func(t *testing.T) { require := require.New(t) mockReturn := new(tpl.BoolRes) mockReturn.Result = true usMock.EXPECT().UserBatchAdd(nil, []string{"123"}).Return(mockReturn, nil) _, err := user.BatchAdd(nil, []string{"123"}) require.Nil(err) }) t.Run(`UserListSettingsUnionAll should work`, func(t *testing.T) { assert := assert.New(t) uid := tpl.RandUID() product := tpl.RandName() label := tpl.RandLabel() module := tpl.RandName() setting := tpl.RandName() HID := tpl.RandUID() value := tpl.RandName() args := &tpl.MySettingsQueryURL{ UID: uid, Product: product, Client: "ios", WithLabel: true, } mockReturn := &tpl.MySettingsRes{ Result: []*tpl.MySetting{{ HID: HID, Product: product, Module: module, Name: setting, Value: value, }}, } usMock.EXPECT().UserListSettingsUnionAll(nil, args).Return(mockReturn, nil) mockCacheLabelsInfoRes := &tpl.CacheLabelsInfoRes{ Result: []schema.UserCacheLabel{ { Label: label, Clients: []string{"ios"}, }, }, } usMock.EXPECT().LabelsCache(nil, product, uid).Return(mockCacheLabelsInfoRes, nil) res, err := user.ListSettingsUnionAll(nil, args) assert.Nil(err) assert.Equal(product, res.Result[0].Product) assert.Equal("urbs", res.Result[0].Module) assert.Equal("", res.Result[0].HID) assert.Equal(label, res.Result[0].Name) assert.Equal("true", res.Result[0].Value) assert.Equal(product, res.Result[1].Product) assert.Equal(module, res.Result[1].Module) assert.Equal(HID, res.Result[1].HID) assert.Equal(setting, res.Result[1].Name) assert.Equal(value, res.Result[1].Value) }) } func testUserBatchCreate(tt *TestTools, uid string) { _, err := testBlls.User.BatchAdd(context.Background(), []string{uid}) tt.Require.Nil(err) } func testUserListLables(tt *TestTools, uid string, count int) { args := &tpl.UIDPaginationURL{ UID: uid, } res, err := testBlls.User.ListLables(getUidContext(), args) tt.Require.Nil(err) tt.Require.Equal(count, len(res.Result)) }
spynad/ITMO_Study
Programming/Lab7/server/src/main/java/connection/ConnectionListenerImpl2.java
package connection; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.channels.spi.SelectorProvider; public class ConnectionListenerImpl2 { private Selector selector; private ServerSocketChannel serverChannel; private InetSocketAddress socketAddress; public Selector openConnection() throws IOException { selector = SelectorProvider.provider().openSelector(); serverChannel = ServerSocketChannel.open(); serverChannel.configureBlocking(false); serverChannel.socket().bind(socketAddress); serverChannel.register(selector, SelectionKey.OP_ACCEPT); return selector; } public void accept(SelectionKey key) throws IOException { ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_READ); } public void stop() throws IOException { } public Selector getSelector() { return selector; } public void setSocketAddress(InetSocketAddress socketAddress) { this.socketAddress = socketAddress; } }
b2wdigital/asgard-events-indexer
indexer/__main__.py
import asyncio from indexer.app import main asyncio.get_event_loop().run_until_complete(main())
DurasExperience/proto
client/app/desktop/components/WebGLExperiment/chapters/Indochine/02/index.js
<reponame>DurasExperience/proto<filename>client/app/desktop/components/WebGLExperiment/chapters/Indochine/02/index.js<gh_stars>0 import { Group, Mesh, SphereBufferGeometry, MeshBasicMaterial } from 'three' import HandWoman from './HandWoman' import HandMan from './HandMan' // import HandSplines from './HandSplines' import BackgroundHands from './BackgroundHands' import Background from './Background' import Observer from './Observer' import Actions from './../../../../../../../flux/actions' import Store from './../../../../../../../flux/store/desktop' import EventsConstants from './../../../../../../../flux/constants/EventsConstants' import AudioManager from './../../../../../../../helpers/AudioManager' import GUI from './../../../../../../../helpers/GUI' import { indochine_02 as Config, handManSplines as handManSplinesConfig } from './Config/' import GlobalConfig from '././../../../../../../../config' import ClearObject3D from './../../../utils/ClearObject3D' import BoxBlurPass from 'avdp-wagner/src/passes/box-blur/BoxBlurPass' import VignettePass from 'avdp-wagner/src/passes/vignette/VignettePass' import ZoomBlurPass from 'avdp-wagner/src/passes/zoom-blur/ZoomBlurPass' import MultiPassBloomPass from 'avdp-wagner/src/passes/bloom/MultiPassBloomPass' import BlendPass from 'avdp-wagner/src/passes/blend/BlendPass' import GodrayPass from 'avdp-wagner/src/passes/godray/godraypass' class Indochine02 extends Group { constructor( scene, controlsContainer ) { super() this.name = 'indochine-02' this.scene = scene this.config = Config this.handManSplinesConfig = handManSplinesConfig this.bind() this.observer = new Observer( scene, controlsContainer, this.fadeOut ) this.observer.enableSpline() this.background = new Background() this.handWoman = new HandWoman( this.observer.duration ) this.handMan = new HandMan( this.observer.duration ) // this.handManSplines = new HandSplines( 'man', this.handManSplinesConfig, this.scene.camera ) this.add( this.background ) this.add( this.handWoman ) this.add( this.handMan ) // this.add( this.handManSplines ) this.objects = [ this.handWoman, this.handMan, this.background ] this.initPostProcessing() this.count = 0 } bind() { [ 'resize', 'update', 'reverse', 'fadeIn', 'fadeOut', 'play', 'clearGroup' ] .forEach( ( fn ) => this[ fn ] = this[ fn ].bind( this ) ) } addListeners() { if ( GlobalConfig.mobileConnect ) Store.socketRoom.on( EventsConstants.PINCH_START, this.reverse ) else Store.on( EventsConstants.SPACE_DOWN, this.reverse ) } removeListeners() { if ( GlobalConfig.mobileConnect ) Store.socketRoom.off( EventsConstants.PINCH_START, this.reverse ) else Store.off( EventsConstants.SPACE_DOWN, this.reverse ) } start() { this.scene.setupPostProcessing( this.passes ) this.play() this.addGUI() } play() { this.objects.push( this.observer ) this.fadeIn() this.observer.init() /** * show spline */ // this.observer.createGeometry() this.observer.start() this.observer.play() this.handWoman.init() this.handMan.init() this.addListeners() } down(){ } initPostProcessing() { this.boxBlurPass = new BoxBlurPass( this.config.postProcessing.boxBlurPass.x, this.config.postProcessing.boxBlurPass.y ) this.vignettePass = new VignettePass( { boost: this.config.postProcessing.vignettePass.boost, reduction: this.config.postProcessing.vignettePass.reduction } ) this.zoomBlurPass = new ZoomBlurPass( this.config.postProcessing.zoomBlurPass ) this.multiPassBloomPass = new MultiPassBloomPass( this.config.postProcessing.multiPassBloomPass ) this.passes = [ this.boxBlurPass, this.multiPassBloomPass, this.zoomBlurPass, this.vignettePass ] } addGUI() { this.observer.addGUI() this.handWoman.addGUI() this.handMan.addGUI() this.background.addGUI() this.vignettePass.params.range = [ 0, 10 ] this.zoomBlurPass.params.range = [ 0, 2 ] this.multiPassBloomPass.params.range = [ 0, 5 ] GUI.panel .addGroup({ label: 'Post Processing', enable: false }) .addSubGroup({ label: 'Vignette Pass' }) .addSlider( this.vignettePass.params, 'boost', 'range', { step: 0.05 } ) .addSlider( this.vignettePass.params, 'reduction', 'range', { step: 0.05 } ) .addSubGroup({ label: 'Zoom Blur Pass' }) .addSlider( this.zoomBlurPass.params, 'strength', 'range', { step: 0.05 } ) .addSubGroup({ label: 'Multi Pass Bloom Pass' }) .addSlider( this.multiPassBloomPass.params, 'blurAmount', 'range', { step: 0.05 } ) .addSlider( this.multiPassBloomPass.params, 'zoomBlurStrength', 'range', { step: 0.05 } ) } reverse() { this.background.reverse() this.handWoman.reverse( 4 ) this.handMan.reverse( 4 ) } fadeIn() { this.fadeInTl = new TimelineMax() this.fadeInTl.fromTo( this.vignettePass.params, 2, { boost: 0 }, { boost: 1, ease: Sine.easeOut } ) } fadeOut() { this.vignettePass.params.boost = this.config.postProcessing.vignettePass.boost this.vignettePass.params.reduction = this.config.postProcessing.vignettePass.reduction // this.scene.passes.push( this.vignettePass ) this.fadeOutTl = new TimelineMax({ onComplete: this.clearGroup }) this.fadeOutTl.to( this.vignettePass.params, 2, { boost: 0, ease: Sine.easeOut } ) } clearGroup() { this.removeListeners() this.remove( this.observer ) this.remove( this.handWoman ) this.remove( this.handMan ) for ( let i = this.children.length - 1; i >= 0; i--) { const child = this.children[ i ] this.remove( child ) ClearObject3D( child ) } this.passes = [] this.scene.setupPostProcessing( this.passes ) this.objects = [] this.fadeInTl.clear() this.fadeOutTl.clear() this.handWoman.clear() this.handMan.clear() if ( GlobalConfig.mobileConnect ) Store.socketRoom.emit( EventsConstants.CHANGE_CHAPTER ) Actions.endAmbient() Actions.changeSubpage( '/troubles/01' ) } update( time ) { for ( let obj of this.objects ) { obj.update( time ) } } resize( newWidth, newHeight ) { } } export default Indochine02
AlexRogalskiy/DevArtifacts
master/autotools-book-files/autotools/book/flaim-ch8-10/sql/src/sqlstatement.h
//------------------------------------------------------------------------------ // Desc: This file contains SQL statement class. // Tabs: 3 // // Copyright (c) 2006-2007 Novell, Inc. All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; version 2.1 // of the License. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, contact Novell, Inc. // // To contact Novell about this file by physical or electronic mail, // you may find current contact information at www.novell.com. // // $Id$ //------------------------------------------------------------------------------ #ifndef SQLSTATEMENT_H #define SQLSTATEMENT_H // Maximum name length for table names, column names, and index names #define MAX_SQL_NAME_LEN 128 class SQLQuery; typedef struct SELECT_EXPR { SQLQuery * pSqlQuery; SELECT_EXPR * pNext; } SELECT_EXPR; typedef struct COLUMN_SET { FLMUINT uiColumnNum; SQLQuery * pSqlQuery; COLUMN_SET * pNext; } COLUMN_SET; typedef struct TABLE_ITEM { FLMUINT uiTableNum; const char * pszTableAlias; FLMUINT uiIndexNum; FLMBOOL bScan; } TABLE_ITEM; typedef enum { SQL_PARSE_STATS } eSQLStatus; typedef RCODE (* SQL_STATUS_HOOK)( eSQLStatus eStatusType, void * pvArg1, void * pvArg2, void * pvArg3, void * pvUserData); //------------------------------------------------------------------------------ // Desc: Base object that defines methods which must be present for all ODBC // handle objects. //------------------------------------------------------------------------------ class ODBCObject : public F_Object { public: ODBCObject() { m_hMutex = F_MUTEX_NULL; m_pszStateInfo = NULL; m_uiErrMsgLen = 0; m_bHaveError = FALSE; m_uiNumDiagRecs = 0; } virtual ~ODBCObject() { if (m_hMutex != F_MUTEX_NULL) { f_mutexDestroy( &m_hMutex); } } FINLINE FLMINT SQFAPI AddRef( void) { return( f_atomicInc( &m_refCnt)); } FINLINE FLMINT SQFAPI Release( void) { FLMINT iRefCnt; if ((iRefCnt = f_atomicDec( &m_refCnt)) == 0) { delete this; } return( iRefCnt); } FINLINE RCODE setupObject( void) { return( f_mutexCreate( &m_hMutex)); } FINLINE void lockObject( void) { f_mutexLock( m_hMutex); } FINLINE void unlockObject( void) { f_mutexUnlock( m_hMutex); } FINLINE const char * getStateInfo( void) { return( m_pszStateInfo); } FINLINE FLMUINT getErrMsgLen( void) { return( m_uiErrMsgLen); } FINLINE const char * getErrMsg( void) { if (m_uiErrMsgLen) { return( m_szErrMsg [0]); } else { return( NULL); } } FINLINE RCODE getRCODE( void) { return( m_rc); } FINLINE FLMBOOL haveError( void) { return( m_bHaveError); } FINLINE void clearState( void) { m_bHaveError = FALSE; m_uiNumDiagRecs = 0; } FINLINE void setStateInfo( const char * pszStateInfo) { m_pszStateInfo = pszStateInfo; m_uiErrMsgLen = 0; m_rc = NE_SFLM_OK; m_bHaveError = TRUE; } FINLINE void setGeneralErrMsg( const char * pszErrMsg, RCODE rc = NE_SFLM_OK) { m_pszStateInfo = "HY000"; m_uiErrMsgLen = f_strlen( pszErrMsg); // Copy null terminator character too. f_memcpy( m_szErrMsg, pszErrMsg, m_uiErrMsgLen + 1); m_rc = rc; m_bHaveError = TRUE; } // Must be implemented by inheriting class. virtual FLMBOOL canRelease( void) = 0; private: F_MUTEX m_hMutex; const char * m_pszStateInfo; char * m_szErrMsg [200]; FLMUINT m_uiErrMsgLen; RCODE m_rc; FLMUINT m_bHaveError; FLMUINT m_uiNumDiagRecs; }; /*============================================================================ Desc: SQL statement class. Parses and executes SQL statements. This object type is returned for ODBC for handles of type SQL_HANDLE_STMT or SQLHSTMT. ============================================================================*/ class SQLStatement : public ODBCObject { public: #define MAX_SQL_TOKEN_SIZE 80 SQLStatement(); virtual ~SQLStatement(); RCODE setupStatement( void); void resetStatement( void); RCODE executeSQL( IF_IStream * pStream, F_Db * pDb, SQL_STATS * pSQLStats); FINLINE FLMBOOL canRelease( void) { // VISIT: Need to determine whether or not this is possible. return( TRUE); } SQLConnection * getConnection( void) { return( m_pConnection); } private: // Methods RCODE getByte( FLMBYTE * pucByte); FINLINE void ungetByte( FLMBYTE ucByte) { // Can only unget a single byte. flmAssert( !m_ucUngetByte); m_ucUngetByte = ucByte; m_sqlStats.uiChars--; } RCODE getLine( void); FINLINE FLMBYTE getChar( void) { if (m_uiCurrLineOffset == m_uiCurrLineBytes) { return( (FLMBYTE)0); } else { FLMBYTE ucChar = m_pucCurrLineBuf [m_uiCurrLineOffset++]; return( ucChar); } } FINLINE FLMBYTE peekChar( void) { if (m_uiCurrLineOffset == m_uiCurrLineBytes) { return( (FLMBYTE)0); } else { return( m_pucCurrLineBuf [m_uiCurrLineOffset]); } } FINLINE void ungetChar( void) { // There should never be a reason to unget past the beginning of the current // line. flmAssert( m_uiCurrLineOffset); m_uiCurrLineOffset--; } RCODE skipWhitespace( FLMBOOL bRequired); RCODE haveToken( const char * pszToken, FLMBOOL bEofOK, SQLParseError eNotHaveErr = SQL_NO_ERROR); RCODE getToken( char * pszToken, FLMUINT uiTokenBufSize, FLMBOOL bEofOK, FLMUINT * puiTokenLineOffset, FLMUINT * puiTokenLen); FINLINE void setErrInfo( FLMUINT uiErrLineNum, FLMUINT uiErrLineOffset, SQLParseError eErrorType, FLMUINT uiErrLineFilePos, FLMUINT uiErrLineBytes) { m_sqlStats.uiErrLineNum = uiErrLineNum; m_sqlStats.uiErrLineOffset = uiErrLineOffset; m_sqlStats.eErrorType = eErrorType; m_sqlStats.uiErrLineFilePos = uiErrLineFilePos; m_sqlStats.uiErrLineBytes = uiErrLineBytes; } RCODE getBinaryValue( F_DynaBuf * pDynaBuf); RCODE getUTF8String( FLMBOOL bMustHaveEqual, FLMBOOL bStripWildcardEscapes, FLMBYTE * pszStr, FLMUINT uiStrBufSize, FLMUINT * puiStrLen, FLMUINT * puiNumChars, F_DynaBuf * pDynaBuf); RCODE getNumber( FLMBOOL bMustHaveEqual, FLMUINT64 * pui64Num, FLMBOOL * pbNeg, FLMBOOL bNegAllowed); RCODE getBool( FLMBOOL bMustHaveEqual, FLMBOOL * pbBool); RCODE getUINT( FLMBOOL bMustHaveEqual, FLMUINT * puiNum); RCODE getName( char * pszName, FLMUINT uiNameBufSize, FLMUINT * puiNameLen, FLMUINT * puiTokenLineOffset); RCODE getEncDefName( FLMBOOL bMustExist, char * pszEncDefName, FLMUINT uiEncDefNameBufSize, FLMUINT * puiEncDefNameLen, F_ENCDEF ** ppEncDef); RCODE getTableName( FLMBOOL bMustExist, char * pszTableName, FLMUINT uiTableNameBufSize, FLMUINT * puiTableNameLen, F_TABLE ** ppTable); RCODE getIndexName( FLMBOOL bMustExist, F_TABLE * pTable, char * pszIndexName, FLMUINT uiIndexNameBufSize, FLMUINT * puiIndexNameLen, F_INDEX ** ppIndex); RCODE getStringValue( F_COLUMN * pColumn, F_COLUMN_VALUE * pColumnValue); RCODE getNumberValue( F_COLUMN_VALUE * pColumnValue); RCODE getBinaryValue( F_COLUMN * pColumn, F_COLUMN_VALUE * pColumnValue); RCODE getValue( F_COLUMN * pColumn, F_COLUMN_VALUE * pColumnValue); RCODE insertRow( void); RCODE processCreateDatabase( void); RCODE processOpenDatabase( void); RCODE processDropDatabase( void); RCODE getDataType( eDataType * peDataType, FLMUINT * puiMax, FLMUINT * puiEncDefNum, FLMUINT * puiFlags); RCODE processCreateTable( void); RCODE processDropTable( void); RCODE processCreateIndex( FLMBOOL bUnique); RCODE processDropIndex( void); RCODE processInsertRow( void); RCODE parseSetColumns( TABLE_ITEM * pTableList, COLUMN_SET ** ppFirstColumnSet, COLUMN_SET ** ppLastColumnSet, FLMUINT * puiNumColumnsToSet, FLMBOOL * pbHadWhere); RCODE processUpdateRows( void); RCODE processDeleteRows( void); RCODE processAlphaToken( TABLE_ITEM * pTableList, const char ** ppszTerminatingTokens, const char ** ppszTerminator, SQLQuery * pSqlQuery, FLMBOOL * pbDone); RCODE parseCriteria( TABLE_ITEM * pTableList, const char ** ppszTerminatingTokens, FLMBOOL bEofOK, const char ** ppszTerminator, SQLQuery * pSqlQuery); RCODE parseSelectExpressions( SELECT_EXPR ** ppFirstSelectExpr, SELECT_EXPR ** ppLastSelectExpr); RCODE processSelect( void); // Data F_Db * m_pDb; IF_XML * m_pXml; FLMBYTE m_ucUngetByte; FLMBYTE * m_pucCurrLineBuf; FLMUINT m_uiCurrLineBufMaxBytes; FLMUINT m_uiCurrLineOffset; FLMUINT m_uiCurrLineNum; FLMUINT m_uiCurrLineFilePos; FLMUINT m_uiCurrLineBytes; IF_IStream * m_pStream; FLMUINT m_uiFlags; SQL_STATUS_HOOK m_fnStatus; void * m_pvCallbackData; SQL_STATS m_sqlStats; F_Pool m_tmpPool; SQLConnection * m_pConnection; SQLStatement * m_pNextInConnection; SQLStatement * m_pPrevInConnection; friend class F_Db; friend class F_Database; friend class SQLConnection; friend class SQLEnv; friend class SQLDesc; }; RCODE resolveColumnName( F_Db * pDb, TABLE_ITEM * pTableList, const char * pszTableAlias, const char * pszColumnName, FLMUINT * puiTableNum, FLMUINT * puiColumnNum, SQLParseError * peParseError); #endif // SQLSTATEMENT_H
bjornreppen/natur-kart
src/Kodetre/Kodeliste/KodeVindu.js
<gh_stars>0 import Detaljeringsgrad from "./Detaljeringsgrad"; import Overordnet from "./Overordnet"; import React, { useState, useEffect } from "react"; import språk from "../../språk"; import Graf from "./Graf"; import Flagg from "./Flagg"; import Kodekort from "./Kodekort"; import Kodeliste from "./Kodeliste"; import Statistikk from "./Statistikk"; import Gradienter from "./Gradienter"; import Ekspander from "./Ekspander"; import Ingress from "./Ingress"; import Kurver from "./Kurver"; import Kurve from "./Kurve"; import { CallSplit, MergeType, DescriptionOutlined, ShowChart, Gradient } from "@material-ui/icons/"; import KurveContainer from "./KurveContainer"; import Nedlasting from "./Nedlasting"; import { SettingsContext } from "../../SettingsContext"; const KodeVindu = ({ erAktivert, onNavigate, onFitBounds, meta, data, kurve, onMouseEnter, onMouseLeave, onToggleLayer, opplystKode, onUpdateLayerProp, onUpdateMetaProp }) => { const initialExpand = () => JSON.parse(localStorage.getItem("expand") || "{}"); const [expand, setExpand] = useState(initialExpand); useEffect(() => { localStorage.setItem("expand", JSON.stringify(expand)); }, [expand]); if (!meta) return null; const { kode, url, farge, prefiks, bbox, ingress, infoUrl, tittel, nivå, overordnet, antallNaturomrader, antallArter, stats } = meta; const mor = overordnet[0] || { tittel: {} }; const gradientLength = meta.gradient ? Object.entries(meta.gradient).length : 0; const flaggLength = meta.flagg ? Object.entries(meta.flagg).length : 0; return ( <SettingsContext.Consumer> {context => { return ( <div square="false" elevation={4} style={{ position: "relative", top: -72 }} > <Kodekort kode={kode} farge={farge} url={url} prefiks={prefiks} bbox={bbox} tittel={tittel} nivå={nivå} overordnet={overordnet} onNavigate={onNavigate} erAktivert={erAktivert} onFitBounds={onFitBounds} onToggleLayer={onToggleLayer} /> {kode === "NN-LA-TI" && ( <Detaljeringsgrad onUpdateLayerProp={onUpdateLayerProp} value={meta.depth} /> )} <Ekspander visible={!!ingress} expanded={expand.ingress} heading="Beskrivelse" icon={<DescriptionOutlined />} onExpand={() => setExpand({ ...expand, ingress: !expand.ingress }) } > <Ingress beskrivelse={ingress} infoUrl={infoUrl} /> </Ekspander> <Ekspander visible={prefiks !== "AO" && !!stats} expanded={expand.stats} heading="Statistikk" onExpand={() => setExpand({ ...expand, stats: !expand.stats })} > <Statistikk prefiks={prefiks} overordnet={overordnet} tittel={språk(meta.tittel)} infoUrl={infoUrl} stats={stats} arealPrefix={mor.areal} toppnavn={mor.tittel.nb} arealVindu={antallArter} arterVindu={antallArter} geometrierVindu={antallNaturomrader} /> </Ekspander> <Ekspander visible={overordnet.length > 0} expanded={expand.tagger} icon={<MergeType style={{ transform: "rotate(-45deg)" }} />} heading="Hierarki" heading2={overordnet.length} onExpand={() => setExpand({ ...expand, tagger: !expand.tagger })} > <Overordnet overordnet={overordnet} onNavigate={onNavigate} /> </Ekspander> <Ekspander expanded={expand.innhold || overordnet.length === 0} visible={meta.barn.length > 0} heading={meta.undernivå} heading2={meta.barn.length} icon={<CallSplit style={{ transform: "rotate(180deg)" }} />} onExpand={() => setExpand({ ...expand, innhold: !expand.innhold }) } > {false && ( <KurveContainer key={"a.url"} punkt={{ url: "Biota/Plantae/Magnoliophyta/Eudicots/Ericales/Primulaceae/Primula/Scandinavica" }} gradient={{ url: "Natur_i_Norge/Landskap/Landskapsgradient/Arealbruksintensitet/", barn: [] }} > <Kurve logY={true} /> </KurveContainer> )} <Kodeliste title="" parentkode={kode} størsteAreal={data.størsteAreal} apidata={data.barn} metadata={meta.barn} onNavigate={onNavigate} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} opplystKode={opplystKode} onUpdateMetaProp={onUpdateMetaProp} /> </Ekspander> {meta.gradient && Object.entries(meta.gradient).map(([kode, node]) => ( <Ekspander expanded={expand[node.tittel.nb]} visible={gradientLength > 0} heading={node.tittel.nb} heading2={Object.values(node.barn).length} icon={<Gradient />} onExpand={() => setExpand({ ...expand, [node.tittel.nb]: !expand[node.tittel.nb] }) } > <Gradienter gradient={node.barn} onNavigate={onNavigate} visKoder={context.visKoder} /> </Ekspander> ))} {true && meta.kart.format.raster_gradient && ( <Ekspander expanded={expand.stat1d} visible={true} heading={"Frekvens"} heading2="" icon={<ShowChart />} onExpand={() => setExpand({ ...expand, frek: !expand.frek })} > <KurveContainer gradient={meta}> <Kurve logY={true} /> </KurveContainer> </Ekspander> )} {kurve && ( <Ekspander expanded={expand.stat1d} visible={true} heading={"Relativ frekvens"} heading2="" icon={<ShowChart />} onExpand={() => setExpand({ ...expand, stat1d: !expand.stat1d }) } > <Kurver meta={meta} punkt={kurve.punkt} gradient={kurve.gradient} /> </Ekspander> )} <Ekspander expanded={expand.flagg} visible={flaggLength > 0} heading="Egenskaper" heading2={flaggLength} onExpand={() => setExpand({ ...expand, flagg: !expand.flagg })} > <Flagg flagg={meta.flagg} onNavigate={url => { console.warn(url); onNavigate(url); }} /> </Ekspander> <Graf url={url} graf={meta.graf} parentkode={kode} onNavigate={onNavigate} expand={expand} onSetExpand={setExpand} /> <Nedlasting url={url} heading="Datakilde" noder={meta.datakilde} parentkode={kode} onNavigate={onNavigate} expand={expand} onSetExpand={setExpand} /> </div> ); }} </SettingsContext.Consumer> ); }; export default KodeVindu;
ivomarvan/quick_faces
src/img/processor/faces/marker/marker.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "<NAME>" __email__ = "<EMAIL>" __description__ = ''' Img processor for writing tags to image. ''' import sys import os import cv2 # root of project repository THE_FILE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.abspath(os.path.join(THE_FILE_DIR, '../..', '..', '..', '..')) sys.path.append(PROJECT_ROOT) from src.img.container.image import Image from src.img.container.result import ImageProcessorResult from src.img.processor.processor import ImgProcessor from src.img.processor.faces.landmarks_detector.result import LandmarksDetectorResult from src.img.processor.faces.face_detector.result import FaceDetectorResult from src.img.processor.reformat.squere_crop.result import SquereCropResult class ImgMarkerProcessor(ImgProcessor): def __init__(self, resize_factor: (int, int) = (1,1)): super().__init__('marker') self._resize_factor = resize_factor self.add_not_none_option('resize_factor', self._resize_factor) def _process_image(self, img: Image = None) -> (Image, ImageProcessorResult): ''' Face coordinates an landmarks was found in orig_img_array. But work_img was created by resizing of work_img_array We want to mark found points in orig_img_array. ''' orig_img_array = img.get_orig_img_array() work_img_array = img.get_work_img_array() orig_shape = orig_img_array.shape h_orig = orig_shape[0] w_orig = orig_shape[1] work_shape = work_img_array.shape h_work = work_shape[0] w_work = work_shape[1] reformat_result = img.get_results().get_results_for_processor_super_class(SquereCropResult) if reformat_result: img_scale = reformat_result[0].get_img_scale() mx, my = img_scale, img_scale else: mx, my = w_orig / w_work, h_orig / h_work def r_x(x: int) -> int: return int(round(mx * x, 0)) def r_y(y: int) -> int: return int(round(my * y, 0)) faces_results = img.get_results().get_results_for_processor_super_class(FaceDetectorResult) for face_result in faces_results: face_color = face_result.get_processor().get_option('color') for face_rectangle in face_result.get_rectangles(): # draw face l_t = face_rectangle.left_top() x1 = l_t.x() y1 = l_t.y() r_b = face_rectangle.right_bottom() x2 = r_b.x() y2 = r_b.y() pt1 = (r_x(x1), r_y(y1)) pt2 = (r_x(x2), r_y(y2)) try: cv2.rectangle(img=orig_img_array, pt1=pt1, pt2=pt2, color=face_color, thickness=2) except Exception as e: print('!' * 5, e) landmark_results = img.get_results().get_results_for_processor_super_class(LandmarksDetectorResult) # [FaceLandmarsks] for landmark_result in landmark_results: # FaceLandmarsks for face_landmarks in landmark_result.get_face_landmark_couples(): landmarks = face_landmarks.get_landmarks() # [Point] face_result = face_landmarks.get_face_result() # FaceDetectorResult landmarks_color = landmark_result.get_processor().get_option('color') face_color = face_result.get_processor().get_option('color') # draw landmarks for landmark_point in landmarks: x, y = landmark_point.x(), landmark_point.y() try: cv2.circle(orig_img_array, (r_x(x), r_y(y)), 1, face_color, 2) cv2.circle(orig_img_array, (r_x(x), r_y(y)), 2, landmarks_color, -1) except Exception as e: print('$' * 5, e) return img, ImageProcessorResult(self)
MarginC/kame
netbsd/sys/arch/arc/jazz/asc.c
<filename>netbsd/sys/arch/arc/jazz/asc.c /* $NetBSD: asc.c,v 1.6 2001/11/14 18:15:15 thorpej Exp $ */ /* $OpenBSD: asc.c,v 1.9 1998/03/16 09:38:39 pefo Exp $ */ /* NetBSD: asc.c,v 1.10 1994/12/05 19:11:12 dean Exp */ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * <NAME> and <NAME>. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. * * @(#)asc.c 8.3 (Berkeley) 7/3/94 */ /* * Mach Operating System * Copyright (c) 1991,1990,1989 Carnegie Mellon University * All Rights Reserved. * * Permission to use, copy, modify and distribute this software and its * documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or <EMAIL> * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie the * rights to redistribute these changes. */ /* * HISTORY * Log: scsi_53C94_hdw.c,v * Revision 2.5 91/02/05 17:45:07 mrt * Added author notices * [91/02/04 11:18:43 mrt] * * Changed to use new Mach copyright * [91/02/02 12:17:20 mrt] * * Revision 2.4 91/01/08 15:48:24 rpd * Added continuation argument to thread_block. * [90/12/27 rpd] * * Revision 2.3 90/12/05 23:34:48 af * Recovered from pmax merge.. and from the destruction of a disk. * [90/12/03 23:40:40 af] * * Revision 2.1.1.1 90/11/01 03:39:09 af * Created, from the DEC specs: * "PMAZ-AA TURBOchannel SCSI Module Functional Specification" * Workstation Systems Engineering, Palo Alto, CA. Aug 27, 1990. * And from the NCR data sheets * "NCR 53C94, 53C95, 53C96 Advances SCSI Controller" * [90/09/03 af] */ /* * File: scsi_53C94_hdw.h * Author: <NAME>, Carnegie Mellon University * Date: 9/90 * * Bottom layer of the SCSI driver: chip-dependent functions * * This file contains the code that is specific to the NCR 53C94 * SCSI chip (Host Bus Adapter in SCSI parlance): probing, start * operation, and interrupt routine. */ /* * This layer works based on small simple 'scripts' that are installed * at the start of the command and drive the chip to completion. * The idea comes from the specs of the NCR 53C700 'script' processor. * * There are various reasons for this, mainly * - Performance: identify the common (successful) path, and follow it; * at interrupt time no code is needed to find the current status * - Code size: it should be easy to compact common operations * - Adaptability: the code skeleton should adapt to different chips without * terrible complications. * - Error handling: and it is easy to modify the actions performed * by the scripts to cope with strange but well identified sequences * */ #include <sys/param.h> #include <sys/systm.h> #include <sys/dkstat.h> #include <sys/buf.h> #include <sys/proc.h> #include <sys/conf.h> #include <sys/errno.h> #include <sys/device.h> #include <uvm/uvm_extern.h> #include <dev/scsipi/scsi_all.h> #include <dev/scsipi/scsipi_all.h> #include <dev/scsipi/scsiconf.h> #include <mips/cache.h> #include <machine/cpu.h> #include <machine/autoconf.h> #include <machine/bus.h> #include <arc/jazz/jazziovar.h> #include <arc/jazz/jazzdmatlbreg.h> #include <arc/jazz/dma.h> #include <arc/jazz/scsi.h> #include <arc/jazz/ascreg.h> #include <arc/jazz/ascvar.h> #include <arc/jazz/pica.h> #define readback(a) { register int foo; foo = (a); } /* * In 4ns ticks. */ int asc_to_scsi_period[] = { 32, 33, 34, 35, 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, }; /* * Internal forward declarations. */ struct asc_softc; static void asc_reset __P((struct asc_softc *, asc_regmap_t *)); static void asc_startcmd __P((struct asc_softc *, int)); #ifdef DEBUG int asc_debug = 1; int asc_debug_cmd; int asc_debug_bn; int asc_debug_sz; #define NLOG 16 struct asc_log { u_int status; u_char state; u_char msg; int target; int resid; } asc_log[NLOG], *asc_logp = asc_log; #define PACK(unit, status, ss, ir) \ ((unit << 24) | (status << 16) | (ss << 8) | ir) #endif /* * Scripts are entries in a state machine table. * A script has four parts: a pre-condition, an action, a command to the chip, * and an index into asc_scripts for the next state. The first triggers error * handling if not satisfied and in our case it is formed by the * values of the interrupt register and status register, this * basically captures the phase of the bus and the TC and BS * bits. The action part is just a function pointer, and the * command is what the 53C94 should be told to do at the end * of the action processing. This command is only issued and the * script proceeds if the action routine returns TRUE. * See asc_intr() for how and where this is all done. */ typedef struct script { int condition; /* expected state at interrupt time */ int (*action)(struct asc_softc *, int, int, int); /* extra operations */ int command; /* command to the chip */ struct script *next; /* index into asc_scripts for next state */ } script_t; /* Matching on the condition value */ #define SCRIPT_MATCH(ir, csr) ((ir) | (((csr) & 0x67) << 8)) /* forward decls of script actions */ /* when nothing needed */ static int script_nop __P((struct asc_softc *, int, int, int)); /* all come to an end */ static int asc_end __P((struct asc_softc *, int, int, int)); /* get status from target */ static int asc_get_status __P((struct asc_softc *, int, int, int)); /* start reading data from target */ static int asc_dma_in __P((struct asc_softc *, int, int, int)); /* cleanup after all data is read */ static int asc_last_dma_in __P((struct asc_softc *, int, int, int)); /* resume data in after a message */ static int asc_resume_in __P((struct asc_softc *, int, int, int)); /* resume DMA after a disconnect */ static int asc_resume_dma_in __P((struct asc_softc *, int, int, int)); /* send data to target via dma */ static int asc_dma_out __P((struct asc_softc *, int, int, int)); /* cleanup after all data is written */ static int asc_last_dma_out __P((struct asc_softc *, int, int, int)); /* resume data out after a message */ static int asc_resume_out __P((struct asc_softc *, int, int, int)); /* resume DMA after a disconnect */ static int asc_resume_dma_out __P((struct asc_softc *, int, int, int)); /* negotiate sync xfer */ static int asc_sendsync __P((struct asc_softc *, int, int, int)); /* negotiate sync xfer */ static int asc_replysync __P((struct asc_softc *, int, int, int)); /* process a message byte */ static int asc_msg_in __P((struct asc_softc *, int, int, int)); /* process an expected disconnect */ static int asc_disconnect __P((struct asc_softc *, int, int, int)); /* Define the index into asc_scripts for various state transitions */ #define SCRIPT_DATA_IN 0 #define SCRIPT_CONTINUE_IN 2 #define SCRIPT_DATA_OUT 3 #define SCRIPT_CONTINUE_OUT 5 #define SCRIPT_SIMPLE 6 #define SCRIPT_GET_STATUS 7 #define SCRIPT_DONE 8 #define SCRIPT_MSG_IN 9 #define SCRIPT_REPLY_SYNC 11 #define SCRIPT_TRY_SYNC 12 #define SCRIPT_DISCONNECT 15 #define SCRIPT_RESEL 16 #define SCRIPT_RESUME_IN 17 #define SCRIPT_RESUME_DMA_IN 18 #define SCRIPT_RESUME_OUT 19 #define SCRIPT_RESUME_DMA_OUT 20 #define SCRIPT_RESUME_NO_DATA 21 /* * Scripts */ script_t asc_scripts[] = { /* start data in */ {SCRIPT_MATCH(ASC_INT_FC | ASC_INT_BS, ASC_PHASE_DATAI), /* 0 */ asc_dma_in, ASC_CMD_XFER_INFO | ASC_CMD_DMA, &asc_scripts[SCRIPT_DATA_IN + 1]}, {SCRIPT_MATCH(ASC_INT_BS, ASC_PHASE_STATUS), /* 1 */ asc_last_dma_in, ASC_CMD_I_COMPLETE, &asc_scripts[SCRIPT_GET_STATUS]}, /* continue data in after a chunk is finished */ {SCRIPT_MATCH(ASC_INT_BS, ASC_PHASE_DATAI), /* 2 */ asc_dma_in, ASC_CMD_XFER_INFO | ASC_CMD_DMA, &asc_scripts[SCRIPT_DATA_IN + 1]}, /* start data out */ {SCRIPT_MATCH(ASC_INT_FC | ASC_INT_BS, ASC_PHASE_DATAO), /* 3 */ asc_dma_out, ASC_CMD_XFER_INFO | ASC_CMD_DMA, &asc_scripts[SCRIPT_DATA_OUT + 1]}, {SCRIPT_MATCH(ASC_INT_BS, ASC_PHASE_STATUS), /* 4 */ asc_last_dma_out, ASC_CMD_I_COMPLETE, &asc_scripts[SCRIPT_GET_STATUS]}, /* continue data out after a chunk is finished */ {SCRIPT_MATCH(ASC_INT_BS, ASC_PHASE_DATAO), /* 5 */ asc_dma_out, ASC_CMD_XFER_INFO | ASC_CMD_DMA, &asc_scripts[SCRIPT_DATA_OUT + 1]}, /* simple command with no data transfer */ {SCRIPT_MATCH(ASC_INT_FC | ASC_INT_BS, ASC_PHASE_STATUS), /* 6 */ script_nop, ASC_CMD_I_COMPLETE, &asc_scripts[SCRIPT_GET_STATUS]}, /* get status and finish command */ {SCRIPT_MATCH(ASC_INT_FC, ASC_PHASE_MSG_IN), /* 7 */ asc_get_status, ASC_CMD_MSG_ACPT, &asc_scripts[SCRIPT_DONE]}, {SCRIPT_MATCH(ASC_INT_DISC, 0), /* 8 */ asc_end, ASC_CMD_NOP, &asc_scripts[SCRIPT_DONE]}, /* message in */ {SCRIPT_MATCH(ASC_INT_FC, ASC_PHASE_MSG_IN), /* 9 */ asc_msg_in, ASC_CMD_MSG_ACPT, &asc_scripts[SCRIPT_MSG_IN + 1]}, {SCRIPT_MATCH(ASC_INT_BS, ASC_PHASE_MSG_IN), /* 10 */ script_nop, ASC_CMD_XFER_INFO, &asc_scripts[SCRIPT_MSG_IN]}, /* send synchonous negotiation reply */ {SCRIPT_MATCH(ASC_INT_BS, ASC_PHASE_MSG_OUT), /* 11 */ asc_replysync, ASC_CMD_XFER_INFO, &asc_scripts[SCRIPT_REPLY_SYNC]}, /* try to negotiate synchonous transfer parameters */ {SCRIPT_MATCH(ASC_INT_FC | ASC_INT_BS, ASC_PHASE_MSG_OUT), /* 12 */ asc_sendsync, ASC_CMD_XFER_INFO, &asc_scripts[SCRIPT_TRY_SYNC + 1]}, {SCRIPT_MATCH(ASC_INT_BS, ASC_PHASE_MSG_IN), /* 13 */ script_nop, ASC_CMD_XFER_INFO, &asc_scripts[SCRIPT_MSG_IN]}, {SCRIPT_MATCH(ASC_INT_BS, ASC_PHASE_COMMAND), /* 14 */ script_nop, ASC_CMD_XFER_INFO | ASC_CMD_DMA, &asc_scripts[SCRIPT_RESUME_NO_DATA]}, /* handle a disconnect */ {SCRIPT_MATCH(ASC_INT_DISC, ASC_PHASE_DATAO), /* 15 */ asc_disconnect, ASC_CMD_ENABLE_SEL, &asc_scripts[SCRIPT_RESEL]}, /* reselect sequence: this is just a placeholder so match fails */ {SCRIPT_MATCH(0, ASC_PHASE_MSG_IN), /* 16 */ script_nop, ASC_CMD_MSG_ACPT, &asc_scripts[SCRIPT_RESEL]}, /* resume data in after a message */ {SCRIPT_MATCH(ASC_INT_BS, ASC_PHASE_DATAI), /* 17 */ asc_resume_in, ASC_CMD_XFER_INFO | ASC_CMD_DMA, &asc_scripts[SCRIPT_DATA_IN + 1]}, /* resume partial DMA data in after a message */ {SCRIPT_MATCH(ASC_INT_BS, ASC_PHASE_DATAI), /* 18 */ asc_resume_dma_in, ASC_CMD_XFER_INFO | ASC_CMD_DMA, &asc_scripts[SCRIPT_DATA_IN + 1]}, /* resume data out after a message */ {SCRIPT_MATCH(ASC_INT_BS, ASC_PHASE_DATAO), /* 19 */ asc_resume_out, ASC_CMD_XFER_INFO | ASC_CMD_DMA, &asc_scripts[SCRIPT_DATA_OUT + 1]}, /* resume partial DMA data out after a message */ {SCRIPT_MATCH(ASC_INT_BS, ASC_PHASE_DATAO), /* 20 */ asc_resume_dma_out, ASC_CMD_XFER_INFO | ASC_CMD_DMA, &asc_scripts[SCRIPT_DATA_OUT + 1]}, /* resume after a message when there is no more data */ {SCRIPT_MATCH(ASC_INT_BS, ASC_PHASE_STATUS), /* 21 */ script_nop, ASC_CMD_I_COMPLETE, &asc_scripts[SCRIPT_GET_STATUS]}, }; /* * State kept for each active SCSI device. */ typedef struct scsi_state { script_t *script; /* saved script while processing error */ struct scsi_generic cmd;/* storage for scsi command */ int statusByte; /* status byte returned during STATUS_PHASE */ u_int dmaBufSize; /* DMA buffer size */ int dmalen; /* amount to transfer in this chunk */ int dmaresid; /* amount not transfered if chunk suspended */ int cmdlen; /* length of command in cmd */ int buflen; /* total remaining amount of data to transfer */ vaddr_t buf; /* current pointer within scsicmd->buf */ int flags; /* see below */ int msglen; /* number of message bytes to read */ int msgcnt; /* number of message bytes received */ u_char sync_period; /* DMA synchronous period */ u_char sync_offset; /* DMA synchronous xfer offset or 0 if async */ u_char msg_out; /* next MSG_OUT byte to send */ u_char msg_in[16]; /* buffer for multibyte messages */ } State; /* state flags */ #define DISCONN 0x001 /* true if currently disconnected from bus */ #define DMA_IN_PROGRESS 0x002 /* true if data DMA started */ #define DMA_IN 0x004 /* true if reading from SCSI device */ #define DMA_OUT 0x010 /* true if writing to SCSI device */ #define DID_SYNC 0x020 /* true if synchronous offset was negotiated */ #define TRY_SYNC 0x040 /* true if try neg. synchronous offset */ #define PARITY_ERR 0x080 /* true if parity error seen */ /* * State kept for each active SCSI host interface (53C94). */ struct asc_softc { struct device sc_dev; /* use as a device */ asc_regmap_t *regs; /* chip address */ dma_softc_t __dma; /* stupid macro..... */ dma_softc_t *dma; /* dma control structure */ int sc_id; /* SCSI ID of this interface */ int myidmask; /* ~(1 << myid) */ int state; /* current SCSI connection state */ int target; /* target SCSI ID if busy */ script_t *script; /* next expected interrupt & action */ struct scsipi_xfer *cmdq[ASC_NCMD];/* Pointer to queued commands */ struct scsipi_xfer *cmd[ASC_NCMD];/* Pointer to current active command */ State st[ASC_NCMD]; /* state info for each active command */ int min_period; /* Min transfer period clk/byte */ int max_period; /* Max transfer period clk/byte */ int ccf; /* CCF, whatever that really is? */ int timeout_250; /* 250ms timeout */ int tb_ticks; /* 4ns. ticks/tb channel ticks */ int is24bit; /* if 53CF94/96-2, 24bit address */ struct scsipi_channel sc_channel; struct scsipi_adapter sc_adapter; }; #define ASC_STATE_IDLE 0 /* idle state */ #define ASC_STATE_BUSY 1 /* selecting or currently connected */ #define ASC_STATE_TARGET 2 /* currently selected as target */ #define ASC_STATE_RESEL 3 /* currently waiting for reselect */ typedef struct asc_softc *asc_softc_t; struct asc_timing { int min_period; /* Min transfer period clk/byte */ int max_period; /* Max transfer period clk/byte */ int ccf; /* CCF, whatever that really is? */ int timeout_250; /* 250ms timeout */ int tb_ticks; /* 4ns. ticks/tb channel ticks */ } asc_timing_40mhz = { ASC_MIN_PERIOD40, ASC_MAX_PERIOD40, ASC_CCF(40), ASC_TIMEOUT_250(40, 8 /* exception for ASC_CCF(40) (== 0) */), 6, /* 6.25 */ }, asc_timing_25mhz = { ASC_MIN_PERIOD25, ASC_MAX_PERIOD25, ASC_CCF(25), ASC_TIMEOUT_250(25, ASC_CCF(25)), 10, }, asc_timing_12mhz = { ASC_MIN_PERIOD12, ASC_MAX_PERIOD12, ASC_CCF(13), ASC_TIMEOUT_250(13, ASC_CCF(13)), 20, }; struct asc_config *asc_conf = NULL; /* * Autoconfiguration data for config. */ int ascmatch __P((struct device *, struct cfdata *, void *)); void ascattach __P((struct device *, struct device *, void *)); int asc_doprobe __P((void *, int, int, struct device *)); struct cfattach asc_ca = { sizeof(struct asc_softc), ascmatch, ascattach }; /* * Glue to the machine dependent scsi */ void asc_scsipi_request __P((struct scsipi_channel *, scsipi_adapter_req_t, void *)); static int asc_intr __P((void *)); static void asc_poll __P((struct asc_softc *, int)); #ifdef DEBUG static void asc_DumpLog __P((char *)); #endif /* * Match driver based on name */ int ascmatch(parent, match, aux) struct device *parent; struct cfdata *match; void *aux; { struct jazzio_attach_args *ja = aux; if(strcmp(ja->ja_name, "asc") != 0) return (0); return (1); } void ascattach(parent, self, aux) struct device *parent; struct device *self; void *aux; { struct jazzio_attach_args *ja = aux; asc_softc_t asc = (void *)self; asc_regmap_t *regs; int id, s, i; int bufsiz; if (asc_conf == NULL) panic("asc_conf isn't initialized"); /* * Initialize hw descriptor, cache some pointers */ asc->regs = (asc_regmap_t *)ja->ja_addr; /* XXX */ /* * Set up machine dependencies. * 1) how to do dma * 2) timing based on chip clock frequency */ #if 1 /*XXX check if code handles 0 as 64k */ bufsiz = 63 * 1024; #else bufsiz = 64 * 1024; #endif asc->dma = &asc->__dma; asc_dma_init(asc->dma); /* * Now for timing. */ asc->min_period = asc_conf->ac_timing->min_period; asc->max_period = asc_conf->ac_timing->max_period; asc->ccf = asc_conf->ac_timing->ccf; asc->timeout_250 = asc_conf->ac_timing->timeout_250; asc->tb_ticks = asc_conf->ac_timing->tb_ticks; asc->state = ASC_STATE_IDLE; asc->target = -1; regs = asc->regs; /* * Reset chip, fully. Note that interrupts are already enabled. */ s = splbio(); /* preserve our ID for now */ asc->sc_id = regs->asc_cnfg1 & ASC_CNFG1_MY_BUS_ID; asc->myidmask = ~(1 << asc->sc_id); /* identify 53CF9x-2 or not */ regs->asc_cmd = ASC_CMD_RESET; wbflush(); DELAY(25); regs->asc_cmd = ASC_CMD_DMA | ASC_CMD_NOP; wbflush(); DELAY(25); regs->asc_cnfg2 = ASC_CNFG2_FE; wbflush(); DELAY(25); regs->asc_cmd = ASC_CMD_DMA | ASC_CMD_NOP; wbflush(); DELAY(25); asc->is24bit = regs->asc_id == ASC_ID_53CF94; asc_reset(asc, regs); /* * Our SCSI id on the bus. * The user can set this via the prom on 3maxen/picaen. * If this changes it is easy to fix: make a default that * can be changed as boot arg. */ #ifdef unneeded regs->asc_cnfg1 = (regs->asc_cnfg1 & ~ASC_CNFG1_MY_BUS_ID) | (scsi_initiator_id[unit] & 0x7); asc->sc_id = regs->asc_cnfg1 & ASC_CNFG1_MY_BUS_ID; #endif id = asc->sc_id; splx(s); /* * Give each target its DMA buffer region. * The buffer address is the same for all targets, * the allocated dma viritual scatter/gather space. */ for (i = 0; i < ASC_NCMD; i++) { asc->st[i].dmaBufSize = bufsiz; } /* * Set up interrupt handler. */ jazzio_intr_establish(ja->ja_intr, asc_intr, (void *)asc); printf(": %s, target %d\n", asc->is24bit ? "NCR53CF9X-2" : "NCR53C94", id); asc->sc_adapter.adapt_dev = &asc->sc_dev; asc->sc_adapter.adapt_nchannels = 1; asc->sc_adapter.adapt_openings = 7; asc->sc_adapter.adapt_max_periph = 1; asc->sc_adapter.adapt_ioctl = NULL; asc->sc_adapter.adapt_minphys = minphys; asc->sc_adapter.adapt_request = asc_scsipi_request; memset(&asc->sc_channel, 0, sizeof(asc->sc_channel)); asc->sc_channel.chan_adapter = &asc->sc_adapter; asc->sc_channel.chan_bustype = &scsi_bustype; asc->sc_channel.chan_channel = 0; asc->sc_channel.chan_ntargets = 8; asc->sc_channel.chan_nluns = 8; asc->sc_channel.chan_id = asc->sc_id; /* * Now try to attach all the sub devices. */ config_found(self, &asc->sc_channel, scsiprint); } /* * Start activity on a SCSI device. * We maintain information on each device separately since devices can * connect/disconnect during an operation. */ void asc_scsipi_request(chan, req, arg) struct scsipi_channel *chan; scsipi_adapter_req_t req; void *arg; { struct scsipi_xfer *xs; struct scsipi_periph *periph; struct asc_softc *asc = (void *)chan->chan_adapter->adapt_dev; int dontqueue, s; switch (req) { case ADAPTER_REQ_RUN_XFER: xs = arg; periph = xs->xs_periph; dontqueue = xs->xs_control & XS_CTL_POLL; /* * Flush caches for any data buffer */ if(xs->datalen != 0) { mips_dcache_wbinv_range((vaddr_t)xs->data, xs->datalen); } /* * The hack on the next few lines are to avoid buffers * mapped to UADDR. Realloc to the kva uarea address. */ if((u_int)(xs->data) >= UADDR) { xs->data = ((u_int)(xs->data) & ~UADDR) + (u_char *)(curproc->p_addr); } s = splbio(); asc->cmd[periph->periph_target] = xs; /* * Going to launch. * Make a local copy of the command and some pointers. */ asc_startcmd(asc, periph->periph_target); /* * If in startup, interrupts not usable yet. */ if(dontqueue) { asc_poll(asc,periph->periph_target); } splx(s); return; case ADAPTER_REQ_GROW_RESOURCES: /* XXX Not supported. */ return; case ADAPTER_REQ_SET_XFER_MODE: /* XXX Not supported. */ return; } } void asc_poll(asc, target) struct asc_softc *asc; int target; { struct scsipi_xfer *scsicmd = asc->cmd[target]; int count = scsicmd->timeout * 10; while(count) { if(asc->regs->asc_status &ASC_CSR_INT) { asc_intr(asc); } if(scsicmd->xs_status & XS_STS_DONE) break; DELAY(5); count--; } if(count == 0) { scsicmd->error = XS_TIMEOUT; asc_end(asc, 0, 0, 0); } } static void asc_reset(asc, regs) asc_softc_t asc; asc_regmap_t *regs; { /* * Reset chip and wait till done */ regs->asc_cmd = ASC_CMD_RESET; wbflush(); DELAY(25); /* spec says this is needed after reset */ regs->asc_cmd = ASC_CMD_NOP; wbflush(); DELAY(25); /* * Set up various chip parameters */ regs->asc_ccf = asc->ccf; wbflush(); DELAY(25); regs->asc_sel_timo = asc->timeout_250; /* restore our ID */ regs->asc_cnfg1 = asc->sc_id | ASC_CNFG1_P_CHECK; /* include ASC_CNFG2_SCSI2 if you want to allow SCSI II commands */ regs->asc_cnfg2 = /* ASC_CNFG2_RFB | ASC_CNFG2_SCSI2 | */ ASC_CNFG2_EPL; regs->asc_cnfg3 = asc_conf->ac_cnfg3; /* zero anything else */ ASC_TC_PUT(regs, 0, asc->is24bit); regs->asc_syn_p = asc->min_period; regs->asc_syn_o = 0; /* async for now */ wbflush(); } /* * Start a SCSI command on a target. */ static void asc_startcmd(asc, target) asc_softc_t asc; int target; { asc_regmap_t *regs; State *state; struct scsipi_xfer *scsicmd; int i, len; /* * See if another target is currently selected on this SCSI bus. */ if (asc->target >= 0) return; regs = asc->regs; /* * If a reselection is in progress, it is Ok to ignore it since * the ASC will automatically cancel the command and flush * the FIFO if the ASC is reselected before the command starts. * If we try to use ASC_CMD_DISABLE_SEL, we can hang the system if * a reselect occurs before starting the command. */ asc->state = ASC_STATE_BUSY; asc->target = target; /* cache some pointers */ scsicmd = asc->cmd[target]; state = &asc->st[target]; /* * Init the chip and target state. */ state->flags = state->flags & DID_SYNC; state->script = (script_t *)0; state->msg_out = SCSI_NO_OP; /* * Set up for DMA of command output. Also need to flush cache. */ bcopy(scsicmd->cmd, &state->cmd, scsicmd->cmdlen); state->cmdlen = scsicmd->cmdlen; state->buf = (vaddr_t)scsicmd->data; state->buflen = scsicmd->datalen; len = state->cmdlen; state->dmalen = len; #ifdef DEBUG if (asc_debug > 1) { printf("asc_startcmd: %s target %d cmd %x len %d\n", asc->sc_dev.dv_xname, target, state->cmd.opcode, state->buflen); } #endif /* check for simple SCSI command with no data transfer */ if (scsicmd->xs_control & XS_CTL_DATA_OUT) { asc->script = &asc_scripts[SCRIPT_DATA_OUT]; state->flags |= DMA_OUT; } else if (scsicmd->xs_control & XS_CTL_DATA_IN) { asc->script = &asc_scripts[SCRIPT_DATA_IN]; state->flags |= DMA_IN; } else if (state->buflen == 0) { /* check for sync negotiation */ if ((scsicmd->xs_status & /* SCSICMD_USE_SYNC */ 0) && !(state->flags & DID_SYNC)) { asc->script = &asc_scripts[SCRIPT_TRY_SYNC]; state->flags |= TRY_SYNC; } else asc->script = &asc_scripts[SCRIPT_SIMPLE]; state->buf = (vaddr_t)0; } #ifdef DEBUG asc_debug_cmd = state->cmd.opcode; if (state->cmd.opcode == SCSI_READ_EXT) { asc_debug_bn = (state->cmd.bytes[1] << 24) | (state->cmd.bytes[2] << 16) | (state->cmd.bytes[3] << 8) | state->cmd.bytes[4]; asc_debug_sz = (state->cmd.bytes[6] << 8) | state->cmd.bytes[7]; } asc_logp->status = PACK(asc->sc_dev.dv_unit, 0, 0, asc_debug_cmd); asc_logp->target = asc->target; asc_logp->state = asc->script - asc_scripts; asc_logp->msg = SCSI_DIS_REC_IDENTIFY; asc_logp->resid = scsicmd->datalen; if (++asc_logp >= &asc_log[NLOG]) asc_logp = asc_log; #endif /* preload the FIFO with the message and command to be sent */ regs->asc_fifo = SCSI_DIS_REC_IDENTIFY | (scsicmd->xs_periph->periph_lun & 0x07); for( i = 0; i < len; i++ ) { regs->asc_fifo = ((caddr_t)&state->cmd)[i]; } ASC_TC_PUT(regs, 0, asc->is24bit); readback(regs->asc_cmd); regs->asc_cmd = ASC_CMD_DMA; readback(regs->asc_cmd); regs->asc_dbus_id = target; readback(regs->asc_dbus_id); regs->asc_syn_p = state->sync_period; readback(regs->asc_syn_p); regs->asc_syn_o = state->sync_offset; readback(regs->asc_syn_o); /*XXX PEFO */ /* we are not using sync transfer now, need to check this if we will */ if (state->flags & TRY_SYNC) regs->asc_cmd = ASC_CMD_SEL_ATN_STOP; else regs->asc_cmd = ASC_CMD_SEL_ATN; readback(regs->asc_cmd); } /* * Interrupt routine * Take interrupts from the chip * * Implementation: * Move along the current command's script if * all is well, invoke error handler if not. */ int asc_intr(sc) void *sc; { asc_softc_t asc = sc; asc_regmap_t *regs = asc->regs; State *state; script_t *scpt; int ss, ir, status; /* collect ephemeral information */ status = regs->asc_status; ss = regs->asc_ss; if ((status & ASC_CSR_INT) == 0) /* Make shure it's a real interrupt */ return(0); ir = regs->asc_intr; /* this resets the previous two */ scpt = asc->script; #ifdef DEBUG asc_logp->status = PACK(asc->sc_dev.dv_unit, status, ss, ir); asc_logp->target = (asc->state == ASC_STATE_BUSY) ? asc->target : -1; asc_logp->state = scpt - asc_scripts; asc_logp->msg = -1; asc_logp->resid = 0; if (++asc_logp >= &asc_log[NLOG]) asc_logp = asc_log; if (asc_debug > 2) printf("asc_intr: status %x ss %x ir %x cond %d:%x\n", status, ss, ir, scpt - asc_scripts, scpt->condition); #endif /* check the expected state */ if (SCRIPT_MATCH(ir, status) == scpt->condition) { /* * Perform the appropriate operation, then proceed. */ if ((*scpt->action)(asc, status, ss, ir)) { regs->asc_cmd = scpt->command; readback(regs->asc_cmd); asc->script = scpt->next; } goto done; } /* * Check for parity error. * Hardware will automatically set ATN * to request the device for a MSG_OUT phase. */ if (status & ASC_CSR_PE) { printf("%s: SCSI device %d: incomming parity error seen\n", asc->sc_dev.dv_xname, asc->target); asc->st[asc->target].flags |= PARITY_ERR; } /* * Check for gross error. * Probably a bug in a device driver. */ if (status & ASC_CSR_GE) { printf("%s: SCSI device %d: gross error\n", asc->sc_dev.dv_xname, asc->target); goto abort; } /* check for message in or out */ if ((ir & ~ASC_INT_FC) == ASC_INT_BS) { register int len, fifo; state = &asc->st[asc->target]; switch (ASC_PHASE(status)) { case ASC_PHASE_DATAI: case ASC_PHASE_DATAO: ASC_TC_GET(regs, len); fifo = regs->asc_flags & ASC_FLAGS_FIFO_CNT; printf("asc_intr: data overrun: buflen %d dmalen %d tc %d fifo %d\n", state->buflen, state->dmalen, len, fifo); goto abort; case ASC_PHASE_MSG_IN: break; case ASC_PHASE_MSG_OUT: /* * Check for parity error. * Hardware will automatically set ATN * to request the device for a MSG_OUT phase. */ if (state->flags & PARITY_ERR) { state->flags &= ~PARITY_ERR; state->msg_out = SCSI_MESSAGE_PARITY_ERROR; /* reset message in counter */ state->msglen = 0; } else state->msg_out = SCSI_NO_OP; regs->asc_fifo = state->msg_out; regs->asc_cmd = ASC_CMD_XFER_INFO; readback(regs->asc_cmd); goto done; case ASC_PHASE_STATUS: /* probably an error in the SCSI command */ asc->script = &asc_scripts[SCRIPT_GET_STATUS]; regs->asc_cmd = ASC_CMD_I_COMPLETE; readback(regs->asc_cmd); goto done; default: goto abort; } if (state->script) goto abort; /* * OK, message coming in clean up whatever is going on. * Get number of bytes left to transfered from byte counter * counter decrements when data is trf on the SCSI bus */ ASC_TC_GET(regs, len); fifo = regs->asc_flags & ASC_FLAGS_FIFO_CNT; /* flush any data in the FIFO */ if (fifo && !(state->flags & DMA_IN_PROGRESS)) { printf("asc_intr: fifo flush %d len %d fifo %x\n", fifo, len, regs->asc_fifo); regs->asc_cmd = ASC_CMD_FLUSH; readback(regs->asc_cmd); DELAY(2); } else if (fifo && state->flags & DMA_IN_PROGRESS) { if (state->flags & DMA_OUT) { len += fifo; /* Bytes dma'ed but not sent */ } else if (state->flags & DMA_IN) { printf("asc_intr: IN: dmalen %d len %d fifo %d\n", state->dmalen, len, fifo); /* XXX */ } regs->asc_cmd = ASC_CMD_FLUSH; readback(regs->asc_cmd); DELAY(2); } if (len && (state->flags & DMA_IN_PROGRESS)) { /* save number of bytes still to be sent or received */ state->dmaresid = len; state->flags &= ~DMA_IN_PROGRESS; ASC_TC_PUT(regs, 0, asc->is24bit); #ifdef DEBUG if (asc_logp == asc_log) asc_log[NLOG - 1].resid = len; else asc_logp[-1].resid = len; #endif /* setup state to resume to */ if (state->flags & DMA_IN) { /* * Since the ASC_CNFG3_SRB bit of the * cnfg3 register bit is not set, * we just transferred an extra byte. * Since we can't resume on an odd byte * boundary, we copy the valid data out * and resume DMA at the start address. */ if (len & 1) { printf("asc_intr: msg in len %d (fifo %d)\n", len, fifo); /* XXX */ len = state->dmalen - len; goto do_in; } state->script = &asc_scripts[SCRIPT_RESUME_DMA_IN]; } else if (state->flags & DMA_OUT) state->script = &asc_scripts[SCRIPT_RESUME_DMA_OUT]; else state->script = asc->script; } else if (state->flags & DMA_IN) { if (len) { #ifdef DEBUG printf("asc_intr: 1: bn %d len %d (fifo %d)\n", asc_debug_bn, len, fifo); /* XXX */ #endif goto abort; } /* setup state to resume to */ if (state->flags & DMA_IN_PROGRESS) { len = state->dmalen; state->flags &= ~DMA_IN_PROGRESS; do_in: DMA_END(asc->dma); state->buf += len; state->buflen -= len; } if (state->buflen) state->script = &asc_scripts[SCRIPT_RESUME_IN]; else state->script = &asc_scripts[SCRIPT_RESUME_NO_DATA]; } else if (state->flags & DMA_OUT) { if (len) { printf("asc_intr: 2: len %d (fifo %d)\n", len, fifo); /* XXX */ /* XXX THEO */ #if 1 regs->asc_cmd = ASC_CMD_FLUSH; readback(regs->asc_cmd); DELAY(2); len = 0; #else goto abort; #endif } /* * If this is the last chunk, the next expected * state is to get status. */ if (state->flags & DMA_IN_PROGRESS) { state->flags &= ~DMA_IN_PROGRESS; DMA_END(asc->dma); len = state->dmalen; state->buf += len; state->buflen -= len; } if (state->buflen) state->script = &asc_scripts[SCRIPT_RESUME_OUT]; else state->script = &asc_scripts[SCRIPT_RESUME_NO_DATA]; } else if (asc->script == &asc_scripts[SCRIPT_SIMPLE]) state->script = &asc_scripts[SCRIPT_RESUME_NO_DATA]; else state->script = asc->script; /* setup to receive a message */ asc->script = &asc_scripts[SCRIPT_MSG_IN]; state->msglen = 0; regs->asc_cmd = ASC_CMD_XFER_INFO; readback(regs->asc_cmd); goto done; } /* check for SCSI bus reset */ if (ir & ASC_INT_RESET) { register int i; printf("%s: SCSI bus reset!!\n", asc->sc_dev.dv_xname); /* need to flush any pending commands */ for (i = 0; i < ASC_NCMD; i++) { if (!asc->cmd[i]) continue; asc->cmd[i]->error = XS_DRIVER_STUFFUP; asc_end(asc, 0, 0, 0); } /* rearbitrate synchronous offset */ for (i = 0; i < ASC_NCMD; i++) { asc->st[i].sync_offset = 0; asc->st[i].flags = 0; } asc->target = -1; return(1); } /* check for command errors */ if (ir & ASC_INT_ILL) goto abort; /* check for disconnect */ if (ir & ASC_INT_DISC) { state = &asc->st[asc->target]; switch (asc->script - asc_scripts) { case SCRIPT_DONE: case SCRIPT_DISCONNECT: /* * Disconnects can happen normally when the * command is complete with the phase being * either ASC_PHASE_DATAO or ASC_PHASE_MSG_IN. * The SCRIPT_MATCH() only checks for one phase * so we can wind up here. * Perform the appropriate operation, then proceed. */ if ((*scpt->action)(asc, status, ss, ir)) { regs->asc_cmd = scpt->command; readback(regs->asc_cmd); asc->script = scpt->next; } goto done; case SCRIPT_TRY_SYNC: case SCRIPT_SIMPLE: case SCRIPT_DATA_IN: case SCRIPT_DATA_OUT: /* one of the starting scripts */ if (ASC_SS(ss) == 0) { /* device did not respond */ if (regs->asc_flags & ASC_FLAGS_FIFO_CNT) { regs->asc_cmd = ASC_CMD_FLUSH; readback(regs->asc_cmd); } asc->cmd[asc->target]->error = XS_SELTIMEOUT; asc_end(asc, status, ss, ir); return(1); } /* FALLTHROUGH */ default: printf("%s: SCSI device %d: unexpected disconnect\n", asc->sc_dev.dv_xname, asc->target); #ifdef DEBUG asc_DumpLog("asc_disc"); #endif /* * On rare occasions my RZ24 does a disconnect during * data in phase and the following seems to keep it * happy. * XXX Should a scsi disk ever do this?? */ asc->script = &asc_scripts[SCRIPT_RESEL]; asc->state = ASC_STATE_RESEL; state->flags |= DISCONN; regs->asc_cmd = ASC_CMD_ENABLE_SEL; readback(regs->asc_cmd); return(1); } } /* check for reselect */ if (ir & ASC_INT_RESEL) { unsigned fifo, id, msg; fifo = regs->asc_flags & ASC_FLAGS_FIFO_CNT; if (fifo < 2) goto abort; /* read unencoded SCSI ID and convert to binary */ msg = regs->asc_fifo & asc->myidmask; for (id = 0; (msg & 1) == 0; id++) msg >>= 1; /* read identify message */ msg = regs->asc_fifo; #ifdef DEBUG if (asc_logp == asc_log) asc_log[NLOG - 1].msg = msg; else asc_logp[-1].msg = msg; #endif asc->state = ASC_STATE_BUSY; asc->target = id; state = &asc->st[id]; asc->script = state->script; state->script = (script_t *)0; if (!(state->flags & DISCONN)) goto abort; state->flags &= ~DISCONN; regs->asc_syn_p = state->sync_period; regs->asc_syn_o = state->sync_offset; regs->asc_cmd = ASC_CMD_MSG_ACPT; readback(regs->asc_cmd); goto done; } /* check if we are being selected as a target */ if (ir & (ASC_INT_SEL | ASC_INT_SEL_ATN)) goto abort; /* * 'ir' must be just ASC_INT_FC. * This is normal if canceling an ASC_ENABLE_SEL. */ done: wbflush(); /* * If the next interrupt comes in immediatly the interrupt * dispatcher (which we are returning to) will catch it * before returning to the interrupted code. */ return(1); abort: #ifdef DEBUG asc_DumpLog("asc_intr"); #endif panic("asc_intr"); return(1); } /* * All the many little things that the interrupt * routine might switch to. */ /* ARGSUSED */ static int script_nop(asc, status, ss, ir) asc_softc_t asc; int status, ss, ir; { return (1); } /* ARGSUSED */ static int asc_get_status(asc, status, ss, ir) register asc_softc_t asc; register int status, ss, ir; { register asc_regmap_t *regs = asc->regs; register int data; /* * Get the last two bytes in the FIFO. */ if ((data = regs->asc_flags & ASC_FLAGS_FIFO_CNT) != 2) { printf("asc_get_status: cmdreg %x, fifo cnt %d\n", regs->asc_cmd, data); /* XXX */ #ifdef DEBUG asc_DumpLog("get_status"); /* XXX */ #endif if (data < 2) { asc->regs->asc_cmd = ASC_CMD_MSG_ACPT; readback(asc->regs->asc_cmd); return (0); } do { data = regs->asc_fifo; } while ((regs->asc_flags & ASC_FLAGS_FIFO_CNT) > 2); } /* save the status byte */ asc->st[asc->target].statusByte = data = regs->asc_fifo; #ifdef DEBUG if (asc_logp == asc_log) asc_log[NLOG - 1].msg = data; else asc_logp[-1].msg = data; #endif /* get the (presumed) command_complete message */ if ((data = regs->asc_fifo) == SCSI_COMMAND_COMPLETE) return (1); #ifdef DEBUG printf("asc_get_status: status %x cmd %x\n", asc->st[asc->target].statusByte, data); asc_DumpLog("asc_get_status"); #endif return (0); } /* ARGSUSED */ static int asc_end(asc, status, ss, ir) asc_softc_t asc; int status, ss, ir; { struct scsipi_xfer *scsicmd; struct scsipi_periph *periph; State *state; int i, target; asc->state = ASC_STATE_IDLE; target = asc->target; asc->target = -1; scsicmd = asc->cmd[target]; periph = scsicmd->xs_periph; asc->cmd[target] = (struct scsipi_xfer *)0; state = &asc->st[target]; #ifdef DEBUG if (asc_debug > 1) { printf("asc_end: %s target %d cmd %x err %d resid %d\n", asc->sc_dev.dv_xname, target, state->cmd.opcode, scsicmd->error, state->buflen); } #endif #ifdef DIAGNOSTIC if (target < 0 || !scsicmd) panic("asc_end"); #endif /* look for disconnected devices */ for (i = 0; i < ASC_NCMD; i++) { if (!asc->cmd[i] || !(asc->st[i].flags & DISCONN)) continue; asc->regs->asc_cmd = ASC_CMD_ENABLE_SEL; readback(asc->regs->asc_cmd); asc->state = ASC_STATE_RESEL; asc->script = &asc_scripts[SCRIPT_RESEL]; break; } if(scsicmd->error == XS_NOERROR) { if((state->statusByte & ST_MASK) == SCSI_CHECK) { scsicmd->status = state->statusByte; scsicmd->error = XS_BUSY; } } scsicmd->resid = state->buflen; /* * Look for another device that is ready. * May want to keep last one started and increment for fairness * rather than always starting at zero. */ for (i = 0; i < ASC_NCMD; i++) { /* don't restart a disconnected command */ if (!asc->cmd[i] || (asc->st[i].flags & DISCONN)) continue; asc_startcmd(asc, i); break; } /* signal device driver that the command is done */ scsipi_done(scsicmd); return (0); } /* ARGSUSED */ static int asc_dma_in(asc, status, ss, ir) register asc_softc_t asc; register int status, ss, ir; { register asc_regmap_t *regs = asc->regs; register State *state = &asc->st[asc->target]; register int len; /* check for previous chunk in buffer */ if (state->flags & DMA_IN_PROGRESS) { /* * Only count bytes that have been copied to memory. * There may be some bytes in the FIFO if synchonous transfers * are in progress. */ DMA_END(asc->dma); ASC_TC_GET(regs, len); len = state->dmalen - len; state->buf += len; state->buflen -= len; } /* setup to start reading the next chunk */ len = state->buflen; #ifdef DEBUG if (asc_logp == asc_log) asc_log[NLOG - 1].resid = len; else asc_logp[-1].resid = len; #endif if (len > state->dmaBufSize) len = state->dmaBufSize; state->dmalen = len; DMA_START(asc->dma, (caddr_t)state->buf, len, DMA_FROM_DEV); ASC_TC_PUT(regs, len, asc->is24bit); #ifdef DEBUG if (asc_debug > 2) printf("asc_dma_in: buflen %d, len %d\n", state->buflen, len); #endif /* check for next chunk */ state->flags |= DMA_IN_PROGRESS; if (len != state->buflen) { regs->asc_cmd = ASC_CMD_XFER_INFO | ASC_CMD_DMA; readback(regs->asc_cmd); asc->script = &asc_scripts[SCRIPT_CONTINUE_IN]; return (0); } return (1); } /* ARGSUSED */ static int asc_last_dma_in(asc, status, ss, ir) register asc_softc_t asc; register int status, ss, ir; { register asc_regmap_t *regs = asc->regs; register State *state = &asc->st[asc->target]; register int len, fifo; DMA_END(asc->dma); ASC_TC_GET(regs, len); fifo = regs->asc_flags & ASC_FLAGS_FIFO_CNT; #ifdef DEBUG if (asc_debug > 2) printf("asc_last_dma_in: buflen %d dmalen %d tc %d fifo %d\n", state->buflen, state->dmalen, len, fifo); #endif if (fifo) { /* device must be trying to send more than we expect */ regs->asc_cmd = ASC_CMD_FLUSH; readback(regs->asc_cmd); } state->flags &= ~DMA_IN_PROGRESS; len = state->dmalen - len; state->buflen -= len; return (1); } /* ARGSUSED */ static int asc_resume_in(asc, status, ss, ir) register asc_softc_t asc; register int status, ss, ir; { register asc_regmap_t *regs = asc->regs; register State *state = &asc->st[asc->target]; register int len; /* setup to start reading the next chunk */ len = state->buflen; #ifdef DEBUG if (asc_logp == asc_log) asc_log[NLOG - 1].resid = len; else asc_logp[-1].resid = len; #endif if (len > state->dmaBufSize) len = state->dmaBufSize; state->dmalen = len; #ifdef DEBUG if (asc_logp == asc_log) asc_log[NLOG - 1].resid = len; else asc_logp[-1].resid = len; #endif DMA_START(asc->dma, (caddr_t)state->buf, len, DMA_FROM_DEV); ASC_TC_PUT(regs, len, asc->is24bit); #ifdef DEBUG if (asc_debug > 2) printf("asc_resume_in: buflen %d, len %d\n", state->buflen, len); #endif /* check for next chunk */ state->flags |= DMA_IN_PROGRESS; if (len != state->buflen) { regs->asc_cmd = ASC_CMD_XFER_INFO | ASC_CMD_DMA; readback(regs->asc_cmd); asc->script = &asc_scripts[SCRIPT_CONTINUE_IN]; return (0); } return (1); } /* ARGSUSED */ static int asc_resume_dma_in(asc, status, ss, ir) register asc_softc_t asc; register int status, ss, ir; { register asc_regmap_t *regs = asc->regs; register State *state = &asc->st[asc->target]; register int len, off; /* setup to finish reading the current chunk */ len = state->dmaresid; off = state->dmalen - len; if ((off & 1) && state->sync_offset) { printf("asc_resume_dma_in: odd xfer dmalen %d len %d off %d\n", state->dmalen, len, off); /* XXX */ regs->asc_res_fifo = ((u_char *)state->buf)[off]; /*XXX Need to flush cache ? */ } DMA_START(asc->dma, (caddr_t)state->buf + off, len, DMA_FROM_DEV); ASC_TC_PUT(regs, len, asc->is24bit); #ifdef DEBUG if (asc_debug > 2) printf("asc_resume_dma_in: buflen %d dmalen %d len %d off %d\n", state->dmalen, state->buflen, len, off); #endif /* check for next chunk */ state->flags |= DMA_IN_PROGRESS; if (state->dmalen != state->buflen) { regs->asc_cmd = ASC_CMD_XFER_INFO | ASC_CMD_DMA; readback(regs->asc_cmd); asc->script = &asc_scripts[SCRIPT_CONTINUE_IN]; return (0); } return (1); } /* ARGSUSED */ static int asc_dma_out(asc, status, ss, ir) register asc_softc_t asc; register int status, ss, ir; { register asc_regmap_t *regs = asc->regs; register State *state = &asc->st[asc->target]; register int len, fifo; if (state->flags & DMA_IN_PROGRESS) { /* check to be sure previous chunk was finished */ ASC_TC_GET(regs, len); fifo = regs->asc_flags & ASC_FLAGS_FIFO_CNT; if (len || fifo) printf("asc_dma_out: buflen %d dmalen %d tc %d fifo %d\n", state->buflen, state->dmalen, len, fifo); /* XXX */ len += fifo; len = state->dmalen - len; state->buf += len; state->buflen -= len; } /* setup for this chunk */ len = state->buflen; #ifdef DEBUG if (asc_logp == asc_log) asc_log[NLOG - 1].resid = len; else asc_logp[-1].resid = len; #endif if (len > state->dmaBufSize) len = state->dmaBufSize; state->dmalen = len; DMA_START(asc->dma, (caddr_t)state->buf, len, DMA_TO_DEV); ASC_TC_PUT(regs, len, asc->is24bit); #ifdef DEBUG if (asc_debug > 2) printf("asc_dma_out: buflen %d, len %d\n", state->buflen, len); #endif /* check for next chunk */ state->flags |= DMA_IN_PROGRESS; if (len != state->buflen) { regs->asc_cmd = ASC_CMD_XFER_INFO | ASC_CMD_DMA; readback(regs->asc_cmd); asc->script = &asc_scripts[SCRIPT_CONTINUE_OUT]; return (0); } return (1); } /* ARGSUSED */ static int asc_last_dma_out(asc, status, ss, ir) register asc_softc_t asc; register int status, ss, ir; { register asc_regmap_t *regs = asc->regs; register State *state = &asc->st[asc->target]; register int len, fifo; ASC_TC_GET(regs, len); fifo = regs->asc_flags & ASC_FLAGS_FIFO_CNT; #ifdef DEBUG if (asc_debug > 2) printf("asc_last_dma_out: buflen %d dmalen %d tc %d fifo %d\n", state->buflen, state->dmalen, len, fifo); #endif if (fifo) { len += fifo; regs->asc_cmd = ASC_CMD_FLUSH; readback(regs->asc_cmd); } state->flags &= ~DMA_IN_PROGRESS; len = state->dmalen - len; state->buflen -= len; return (1); } /* ARGSUSED */ static int asc_resume_out(asc, status, ss, ir) register asc_softc_t asc; register int status, ss, ir; { register asc_regmap_t *regs = asc->regs; register State *state = &asc->st[asc->target]; register int len; /* setup for this chunk */ len = state->buflen; #ifdef DEBUG if (asc_logp == asc_log) asc_log[NLOG - 1].resid = len; else asc_logp[-1].resid = len; #endif if (len > state->dmaBufSize) len = state->dmaBufSize; state->dmalen = len; #ifdef DEBUG if (asc_logp == asc_log) asc_log[NLOG - 1].resid = len; else asc_logp[-1].resid = len; #endif DMA_START(asc->dma, (caddr_t)state->buf, len, DMA_TO_DEV); ASC_TC_PUT(regs, len, asc->is24bit); #ifdef DEBUG if (asc_debug > 2) printf("asc_resume_out: buflen %d, len %d\n", state->buflen, len); #endif /* check for next chunk */ state->flags |= DMA_IN_PROGRESS; if (len != state->buflen) { regs->asc_cmd = ASC_CMD_XFER_INFO | ASC_CMD_DMA; readback(regs->asc_cmd); asc->script = &asc_scripts[SCRIPT_CONTINUE_OUT]; return (0); } return (1); } /* ARGSUSED */ static int asc_resume_dma_out(asc, status, ss, ir) register asc_softc_t asc; register int status, ss, ir; { register asc_regmap_t *regs = asc->regs; register State *state = &asc->st[asc->target]; register int len, off; /* setup to finish writing this chunk */ len = state->dmaresid; off = state->dmalen - len; if (off & 1) { printf("asc_resume_dma_out: odd xfer dmalen %d len %d off %d\n", state->dmalen, len, off); /* XXX */ regs->asc_fifo = ((u_char *)state->buf)[off]; /*XXX Need to flush Cache ? */ off++; len--; } DMA_START(asc->dma, (caddr_t)state->buf + off, len, DMA_TO_DEV); ASC_TC_PUT(regs, len, asc->is24bit); #ifdef DEBUG if (asc_debug > 2) printf("asc_resume_dma_out: buflen %d dmalen %d len %d off %d\n", state->dmalen, state->buflen, len, off); #endif /* check for next chunk */ state->flags |= DMA_IN_PROGRESS; if (state->dmalen != state->buflen) { regs->asc_cmd = ASC_CMD_XFER_INFO | ASC_CMD_DMA; readback(regs->asc_cmd); asc->script = &asc_scripts[SCRIPT_CONTINUE_OUT]; return (0); } return (1); } /* ARGSUSED */ static int asc_sendsync(asc, status, ss, ir) register asc_softc_t asc; register int status, ss, ir; { register asc_regmap_t *regs = asc->regs; register State *state = &asc->st[asc->target]; /* send the extended synchronous negotiation message */ regs->asc_fifo = SCSI_EXTENDED_MSG; wbflush(); regs->asc_fifo = 3; wbflush(); regs->asc_fifo = SCSI_SYNCHRONOUS_XFER; wbflush(); regs->asc_fifo = SCSI_MIN_PERIOD; wbflush(); regs->asc_fifo = ASC_MAX_OFFSET; /* state to resume after we see the sync reply message */ state->script = asc->script + 2; state->msglen = 0; return (1); } /* ARGSUSED */ static int asc_replysync(asc, status, ss, ir) register asc_softc_t asc; register int status, ss, ir; { register asc_regmap_t *regs = asc->regs; register State *state = &asc->st[asc->target]; #ifdef DEBUG if (asc_debug > 2) printf("asc_replysync: %x %x\n", asc_to_scsi_period[state->sync_period] * asc->tb_ticks, state->sync_offset); #endif /* send synchronous transfer in response to a request */ regs->asc_fifo = SCSI_EXTENDED_MSG; wbflush(); regs->asc_fifo = 3; wbflush(); regs->asc_fifo = SCSI_SYNCHRONOUS_XFER; wbflush(); regs->asc_fifo = asc_to_scsi_period[state->sync_period] * asc->tb_ticks; wbflush(); regs->asc_fifo = state->sync_offset; regs->asc_cmd = ASC_CMD_XFER_INFO; readback(regs->asc_cmd); /* return to the appropriate script */ if (!state->script) { #ifdef DEBUG asc_DumpLog("asc_replsync"); #endif panic("asc_replysync"); } asc->script = state->script; state->script = (script_t *)0; return (0); } /* ARGSUSED */ static int asc_msg_in(asc, status, ss, ir) register asc_softc_t asc; register int status, ss, ir; { register asc_regmap_t *regs = asc->regs; register State *state = &asc->st[asc->target]; register int msg; int i; /* read one message byte */ msg = regs->asc_fifo; #ifdef DEBUG if (asc_logp == asc_log) asc_log[NLOG - 1].msg = msg; else asc_logp[-1].msg = msg; #endif /* check for multi-byte message */ if (state->msglen != 0) { /* first byte is the message length */ if (state->msglen < 0) { state->msglen = msg; return (1); } if (state->msgcnt >= state->msglen) goto abort; state->msg_in[state->msgcnt++] = msg; /* did we just read the last byte of the message? */ if (state->msgcnt != state->msglen) return (1); /* process an extended message */ #ifdef DEBUG if (asc_debug > 2) printf("asc_msg_in: msg %x %x %x\n", state->msg_in[0], state->msg_in[1], state->msg_in[2]); #endif switch (state->msg_in[0]) { case SCSI_SYNCHRONOUS_XFER: state->flags |= DID_SYNC; state->sync_offset = state->msg_in[2]; /* convert SCSI period to ASC period */ i = state->msg_in[1] / asc->tb_ticks; if (i < asc->min_period) i = asc->min_period; else if (i >= asc->max_period) { /* can't do sync transfer, period too long */ printf("%s: SCSI device %d: sync xfer period too long (%d)\n", asc->sc_dev.dv_xname, asc->target, i); i = asc->max_period; state->sync_offset = 0; } if ((i * asc->tb_ticks) != state->msg_in[1]) i++; state->sync_period = i & 0x1F; /* * If this is a request, check minimums and * send back an acknowledge. */ if (!(state->flags & TRY_SYNC)) { regs->asc_cmd = ASC_CMD_SET_ATN; readback(regs->asc_cmd); if (state->sync_period < asc->min_period) state->sync_period = asc->min_period; if (state->sync_offset > ASC_MAX_OFFSET) state->sync_offset = ASC_MAX_OFFSET; asc->script = &asc_scripts[SCRIPT_REPLY_SYNC]; regs->asc_syn_p = state->sync_period; readback(regs->asc_syn_p); regs->asc_syn_o = state->sync_offset; readback(regs->asc_syn_o); regs->asc_cmd = ASC_CMD_MSG_ACPT; readback(regs->asc_cmd); return (0); } regs->asc_syn_p = state->sync_period; readback(regs->asc_syn_p); regs->asc_syn_o = state->sync_offset; readback(regs->asc_syn_o); goto done; default: printf("%s: SCSI device %d: rejecting extended message 0x%x\n", asc->sc_dev.dv_xname, asc->target, state->msg_in[0]); goto reject; } } /* process first byte of a message */ #ifdef DEBUG if (asc_debug > 2) printf("asc_msg_in: msg %x\n", msg); #endif switch (msg) { #if 0 case SCSI_MESSAGE_REJECT: printf(" did not like SYNCH xfer "); /* XXX */ state->flags |= DID_SYNC; regs->asc_cmd = ASC_CMD_MSG_ACPT; readback(regs->asc_cmd); status = asc_wait(regs, ASC_CSR_INT); ir = regs->asc_intr; /* some just break out here, some dont */ if (ASC_PHASE(status) == ASC_PHASE_MSG_OUT) { regs->asc_fifo = SCSI_ABORT; regs->asc_cmd = ASC_CMD_XFER_INFO; readback(regs->asc_cmd); status = asc_wait(regs, ASC_CSR_INT); ir = regs->asc_intr; } if (ir & ASC_INT_DISC) { asc_end(asc, status, 0, ir); return (0); } goto status; #endif /* 0 */ case SCSI_EXTENDED_MSG: /* read an extended message */ /* setup to read message length next */ state->msglen = -1; state->msgcnt = 0; return (1); case SCSI_NO_OP: break; case SCSI_SAVE_DATA_POINTER: /* expect another message */ return (1); case SCSI_RESTORE_POINTERS: /* * Need to do the following if resuming synchonous data in * on an odd byte boundary. regs->asc_cnfg2 |= ASC_CNFG2_RFB; */ break; case SCSI_DISCONNECT: if (state->flags & DISCONN) goto abort; state->flags |= DISCONN; regs->asc_cmd = ASC_CMD_MSG_ACPT; readback(regs->asc_cmd); asc->script = &asc_scripts[SCRIPT_DISCONNECT]; return (0); default: printf("%s: SCSI device %d: rejecting message 0x%x\n", asc->sc_dev.dv_xname, asc->target, msg); reject: /* request a message out before acknowledging this message */ state->msg_out = SCSI_MESSAGE_REJECT; regs->asc_cmd = ASC_CMD_SET_ATN; readback(regs->asc_cmd); } done: /* return to original script */ regs->asc_cmd = ASC_CMD_MSG_ACPT; readback(regs->asc_cmd); if (!state->script) { abort: #ifdef DEBUG asc_DumpLog("asc_msg_in"); #endif panic("asc_msg_in"); } asc->script = state->script; state->script = (script_t *)0; return (0); } /* ARGSUSED */ static int asc_disconnect(asc, status, ss, ir) asc_softc_t asc; int status, ss, ir; { #ifdef DIAGNOSTIC if (!(asc->st[asc->target].flags & DISCONN)) { printf("asc_disconnect: device %d: DISCONN not set!\n", asc->target); } #endif /* DIAGNOSTIC */ asc->target = -1; asc->state = ASC_STATE_RESEL; return (1); } #ifdef DEBUG /* * Dump the log buffer. */ static void asc_DumpLog(str) char *str; { register struct asc_log *lp; register u_int status; printf("asc: %s: cmd %x bn %d cnt %d\n", str, asc_debug_cmd, asc_debug_bn, asc_debug_sz); lp = asc_logp; do { status = lp->status; printf("asc%d tgt %d status %x ss %x ir %x cond %d:%x msg %x resid %d\n", status >> 24, lp->target, (status >> 16) & 0xFF, (status >> 8) & 0xFF, status & 0XFF, lp->state, asc_scripts[lp->state].condition, lp->msg, lp->resid); if (++lp >= &asc_log[NLOG]) lp = asc_log; } while (lp != asc_logp); } #endif /* DEBUG */
XWJACK/WeChatPlugin-MacOS
Other/Headers/EmoticonMsgInfo.h
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <objc/NSObject.h> #import "PBCoding-Protocol.h" @class NSString; @interface EmoticonMsgInfo : NSObject <PBCoding> { BOOL _disableExtern; unsigned int msgStatus; unsigned int msgImgStatus; unsigned int msgCreateTime; int _m_uiStartPos; int _m_uiTotalLen; int _reDownloadCount; NSString *m_nsServerID; NSString *m_nsMD5; NSString *fromUsrName; long long mesSvrID; NSString *toUsrName; NSString *msgContent; NSString *msgPushContent; NSString *msgSource; NSString *cdnUrl; NSString *aesKey; NSString *encryptUrl; NSString *chatName; NSString *tpUrlString; NSString *authKey; NSString *externUrl; NSString *externMd5; } + (void)initialize; + (void)_initPBTableOfEmoticonMsgInfo; @property(nonatomic) BOOL disableExtern; // @synthesize disableExtern=_disableExtern; @property(nonatomic) int reDownloadCount; // @synthesize reDownloadCount=_reDownloadCount; @property(nonatomic) int m_uiTotalLen; // @synthesize m_uiTotalLen=_m_uiTotalLen; @property(nonatomic) int m_uiStartPos; // @synthesize m_uiStartPos=_m_uiStartPos; @property(retain, nonatomic) NSString *externMd5; // @synthesize externMd5; @property(retain, nonatomic) NSString *externUrl; // @synthesize externUrl; @property(copy, nonatomic) NSString *authKey; // @synthesize authKey; @property(copy, nonatomic) NSString *tpUrlString; // @synthesize tpUrlString; @property(copy, nonatomic) NSString *chatName; // @synthesize chatName; @property(copy, nonatomic) NSString *encryptUrl; // @synthesize encryptUrl; @property(copy, nonatomic) NSString *aesKey; // @synthesize aesKey; @property(copy, nonatomic) NSString *cdnUrl; // @synthesize cdnUrl; @property(copy, nonatomic) NSString *msgSource; // @synthesize msgSource; @property(copy, nonatomic) NSString *msgPushContent; // @synthesize msgPushContent; @property(nonatomic) unsigned int msgCreateTime; // @synthesize msgCreateTime; @property(nonatomic) unsigned int msgImgStatus; // @synthesize msgImgStatus; @property(nonatomic) unsigned int msgStatus; // @synthesize msgStatus; @property(copy, nonatomic) NSString *msgContent; // @synthesize msgContent; @property(copy, nonatomic) NSString *toUsrName; // @synthesize toUsrName; @property(nonatomic) long long mesSvrID; // @synthesize mesSvrID; @property(copy, nonatomic) NSString *fromUsrName; // @synthesize fromUsrName; @property(copy, nonatomic) NSString *m_nsMD5; // @synthesize m_nsMD5; @property(copy, nonatomic) NSString *m_nsServerID; // @synthesize m_nsServerID; - (void).cxx_destruct; - (BOOL)hasTpDownloadInfo; - (BOOL)canCdnDownload; - (BOOL)hasEncryptDownloadInfo; - (BOOL)hasWxAMDownloadInfo; - (id)emoticonPath; - (id)clientMsgId; - (void)parseForBaseDownloadInfoFromMessageData:(id)arg1; @property(readonly, copy) NSString *description; - (const map_24f1cf24 *)getValueTagIndexMap; - (id)getValueTypeTable; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
karpovichDima/JDBC_oAuth2
src/main/java/com/dazito/oauthexample/model/FileEntity.java
<reponame>karpovichDima/JDBC_oAuth2 package com.dazito.oauthexample.model; import lombok.Getter; import lombok.Setter; import javax.persistence.*; import java.util.UUID; @Entity @Getter @Setter @DiscriminatorValue("FILE") public class FileEntity extends FileElement { }
Samdooo/Peio
src/Peio/GUI/Animation.h
<filename>src/Peio/GUI/Animation.h #pragma once #include "GUIHeader.h" #include "..\Array.h" #include "..\Clock.h" #include <functional> namespace Peio::GUI { struct PEIO_GUI_EXPORT Animation { virtual void Reset(double offset = 0.0); virtual double Update(); virtual void Cancel(); virtual void End(); virtual _NODISCARD double GetProgress() const noexcept; double duration = 0.0; double offset = 0.0; protected: bool running = false; double curOffset = 0.0; Clock<double> clock = {}; }; }
jerebenitez/IFE-simpact-openfoam
src/mainp/fixval.h
<filename>src/mainp/fixval.h SUBROUTINE fixval(iwrit,ndime,ndofn,ifpre,nvfix,rot_free,iffix,label) !*** APPLY fixities IMPLICIT NONE LOGICAL, INTENT(IN) :: rot_free INTEGER (kind=4), INTENT(IN) :: iwrit,ndime,ndofn,label(:) INTEGER (kind=4), INTENT(IN OUT) :: ifpre(:,:),iffix(:) INTEGER (kind=4), INTENT(OUT) :: nvfix END SUBROUTINE fixval
OmarElsahragty/portfolio
src/http/errors/Boom.Errors.js
import boom from "boom"; import { SERVER_ERROR } from "./constants"; class BoomHttpErrors { notFound(message) { return boom.notFound(message); } unauthorized(message) { return boom.unauthorized(message); } badData(message) { return boom.badData(message); } badRequest(message) { return boom.badRequest(message); } isHttpError(err) { return boom.isBoom(err); } handleError(err) { if (err.isServer) { console.error("❌ ", { SERVER_ERROR: err }); return SERVER_ERROR; } else return err.output.payload; } } export default BoomHttpErrors;
UKGovernmentBEIS/PRS-Exemptions-Register
NdsBeisSharedModel/src/main/java/com/northgateps/nds/beis/api/metadata/GdipGdarFieldMetadataTagApplicator.java
package com.northgateps.nds.beis.api.metadata; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.northgateps.nds.platform.application.api.metadata.AbstractFieldMetadataTagApplicator; import com.northgateps.nds.platform.application.api.validation.ValidationContext; import com.northgateps.nds.platform.application.api.validation.ValidationEvaluator; import com.northgateps.nds.platform.logger.NdsLogger; /** * Add pattern and title attribute to html input control * * @author yogesh.bhalerao */ public class GdipGdarFieldMetadataTagApplicator extends AbstractFieldMetadataTagApplicator { private static final NdsLogger logger = NdsLogger.getLogger(GdipGdarFieldMetadataTagApplicator.class); private String message = GdipGdarReferenceNumberFieldValidator.DEFAULT_MESSAGE; /** * Implement HTML5 "pattern" and "title" attribute. */ @Override public void apply(Object tag, ValidationContext<?> validationContext) { try { String regEx = ValidationEvaluator.getRegEx(new GdipGdarReferenceNumberFieldValidator(), validationContext); Method m = tag.getClass().getMethod("setPattern", String.class); m.invoke(tag, regEx); } catch (NoSuchMethodException e) { // There may be no such method, it's not an error. Just do nothing } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) { logger.error("Falied to set pattern property of tag", e); } try { Method m = tag.getClass().getMethod("setTitle", String.class); m.invoke(tag, message); } catch (NoSuchMethodException e) { // There may be no such method, it's not an error. Just do nothing } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) { logger.error("Falied to set title property of tag", e); } } }
davewhiiite/uvc
firmware/uvc_controller/mbed-os/features/FEATURE_EXPERIMENTAL_API/FEATURE_PSA/TARGET_MBED_PSA_SRV/services/attestation/psa_inject_attestation_key_impl.c
/* * Copyright (c) 2018-2019 ARM Limited. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "psa_inject_attestation_key_impl.h" #define ECDSA_P256_KEY_SIZE_IN_BYTES 32 #define PSA_ATTESTATION_PRIVATE_KEY_ID 17 psa_status_t psa_attestation_inject_key_impl(const uint8_t *key_data, size_t key_data_length, psa_key_type_t type, uint8_t *public_key_data, size_t public_key_data_size, size_t *public_key_data_length) { psa_status_t status = PSA_SUCCESS; size_t key_data_bits = ECDSA_P256_KEY_SIZE_IN_BYTES * 8; psa_key_handle_t handle = 0; psa_key_id_t key_id = PSA_ATTESTATION_PRIVATE_KEY_ID; psa_key_lifetime_t lifetime = PSA_KEY_LIFETIME_PERSISTENT; psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; psa_key_usage_t usage = PSA_KEY_USAGE_EXPORT | PSA_KEY_USAGE_SIGN | PSA_KEY_USAGE_VERIFY; psa_key_type_t public_type; size_t bits; size_t exported_size = 0; psa_key_type_t type_key; #if defined(MBEDTLS_ECP_C) status = psa_open_key(key_id, &handle); if (status == PSA_SUCCESS) { /* The key already has been injected */ goto exit; } psa_set_key_usage_flags(&attributes, usage); psa_set_key_algorithm(&attributes, PSA_ALG_DETERMINISTIC_ECDSA(PSA_ALG_SHA_256)); psa_set_key_type(&attributes, type); psa_set_key_bits(&attributes, key_data_bits); psa_set_key_lifetime(&attributes, lifetime); psa_set_key_id(&attributes, key_id); if (! PSA_KEY_TYPE_IS_ECC_KEY_PAIR(type)) { return (PSA_ERROR_INVALID_ARGUMENT); } if (key_data != NULL) { if (key_data_length != ECDSA_P256_KEY_SIZE_IN_BYTES) { status = PSA_ERROR_INVALID_ARGUMENT; goto exit; } status = psa_import_key(&attributes, key_data, key_data_length, &handle); if (status != PSA_SUCCESS) { goto exit; } } else { /* generating key pair */ key_data_bits = ECDSA_P256_KEY_SIZE_IN_BYTES * 8; status = psa_generate_key(&attributes, &handle); if (status != PSA_SUCCESS) { goto exit; } } status = psa_get_key_attributes(handle, &attributes); if (status != PSA_SUCCESS) { goto exit; } type_key = psa_get_key_type(&attributes); public_type = PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type_key); bits = psa_get_key_bits(&attributes); exported_size = PSA_KEY_EXPORT_MAX_SIZE(public_type, bits); status = psa_export_public_key(handle, public_key_data, public_key_data_size, public_key_data_length); if (status != PSA_SUCCESS) { goto exit; } if (*public_key_data_length > exported_size) { status = PSA_ERROR_INVALID_ARGUMENT; goto exit; } exit: psa_close_key(handle); return (status); #endif /* MBEDTLS_ECP_C */ return (PSA_ERROR_NOT_SUPPORTED); }
fasten-project/core
analyzer/restapi-plugin/src/main/java/eu/fasten/analyzer/restapiplugin/GraphResolverInitializer.java
package eu.fasten.analyzer.restapiplugin; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; public class GraphResolverInitializer { public static void sendRequestToInitGraphResolver() { RestTemplate restTemplate = new RestTemplate(); try { restTemplate.getForObject(KnowledgeBaseConnector.initDepGraphRequest, String.class); } catch (RestClientException ignored) {} } }
Dielam/MMIT
MMIT/src/test/java/com/mmit/negocio/jugadores/TOAJugadorEquipoTestNG.java
/* * Copyright (C) 2018 Your Organisation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mmit.negocio.jugadores; import com.mmit.negocio.equipos.EquipoTrans; import junit.framework.Assert; import static org.testng.Assert.*; import org.testng.annotations.Test; public class TOAJugadorEquipoTestNG { public TOAJugadorEquipoTestNG() { } // TODO add test methods here. // The methods must be annotated with annotation @Test. For example: // // @Test // public void hello() {} @Test public void TestNGTOAJugadorEquipo(){ try{ JugadorTrans jt = new JugadorTrans(1, "manolo", "juarez", 10, 10, 10.0, 10.0, "Alero", 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, "derecha"); EquipoTrans et = new EquipoTrans(1, "pepe", 10, 10, 40, 40, 20, 20, 5, 6, 2, 5, 4, 12, 3, 9, 8, 3, 5); new TOAJugadorEquipo(jt, et); }catch(Exception e){ Assert.fail(); } } @Test public void TestNGGetIdJugador(){ JugadorTrans jt = new JugadorTrans(1, "manolo", "juarez", 10, 10, 10.0, 10.0, "Alero", 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, "derecha"); EquipoTrans et = new EquipoTrans(1, "pepe", 10, 10, 40, 40, 20, 20, 5, 6, 2, 5, 4, 12, 3, 9, 8, 3, 5); TOAJugadorEquipo instance = new TOAJugadorEquipo(jt, et); int result = instance.getIdJugador(); assertEquals(result, 1); } @Test public void TestNGGetNombreJugador(){ JugadorTrans jt = new JugadorTrans(1, "manolo", "juarez", 10, 10, 10.0, 10.0, "Alero", 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, "derecha"); EquipoTrans et = new EquipoTrans(1, "pepe", 10, 10, 40, 40, 20, 20, 5, 6, 2, 5, 4, 12, 3, 9, 8, 3, 5); TOAJugadorEquipo instance = new TOAJugadorEquipo(jt, et); String result = instance.getNombreJugador(); assertEquals(result, "manolo"); } @Test public void TestNGGetApellidosJugador(){ JugadorTrans jt = new JugadorTrans(1, "manolo", "juarez", 10, 10, 10.0, 10.0, "Alero", 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, "derecha"); EquipoTrans et = new EquipoTrans(1, "pepe", 10, 10, 40, 40, 20, 20, 5, 6, 2, 5, 4, 12, 3, 9, 8, 3, 5); TOAJugadorEquipo instance = new TOAJugadorEquipo(jt, et); String result = instance.getApellidosJugador(); assertEquals(result, "juarez"); } @Test public void TestNGGetIdEquipo(){ JugadorTrans jt = new JugadorTrans(1, "manolo", "juarez", 10, 10, 10.0, 10.0, "Alero", 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, "derecha"); EquipoTrans et = new EquipoTrans(1, "pepe", 10, 10, 40, 40, 20, 20, 5, 6, 2, 5, 4, 12, 3, 9, 8, 3, 5); TOAJugadorEquipo instance = new TOAJugadorEquipo(jt, et); int result = instance.getIdEquipo(); assertEquals(result, 1); } @Test public void TestNGGetNombreEquipo(){ JugadorTrans jt = new JugadorTrans(1, "manolo", "juarez", 10, 10, 10.0, 10.0, "Alero", 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, "derecha"); EquipoTrans et = new EquipoTrans(1, "pepe", 10, 10, 40, 40, 20, 20, 5, 6, 2, 5, 4, 12, 3, 9, 8, 3, 5); TOAJugadorEquipo instance = new TOAJugadorEquipo(jt, et); String result = instance.getNombreEquipo(); assertEquals(result, "pepe"); } @Test public void TestNGGetEquipo(){ JugadorTrans jt = new JugadorTrans(1, "manolo", "juarez", 10, 10, 10.0, 10.0, "Alero", 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, "derecha"); EquipoTrans et = new EquipoTrans(1, "pepe", 10, 10, 40, 40, 20, 20, 5, 6, 2, 5, 4, 12, 3, 9, 8, 3, 5); TOAJugadorEquipo instance = new TOAJugadorEquipo(jt, et); EquipoTrans result = instance.getEquipo(); assertEquals(result, et); } @Test public void TestNGGetJugador(){ JugadorTrans jt = new JugadorTrans(1, "manolo", "juarez", 10, 10, 10.0, 10.0, "Alero", 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, "derecha"); EquipoTrans et = new EquipoTrans(1, "pepe", 10, 10, 40, 40, 20, 20, 5, 6, 2, 5, 4, 12, 3, 9, 8, 3, 5); TOAJugadorEquipo instance = new TOAJugadorEquipo(jt, et); JugadorTrans result = instance.getJugador(); assertEquals(result, jt); } }
ZintrulCre/LeetCode_Archiver
LeetCode/python3/1022.py
<filename>LeetCode/python3/1022.py class Solution: def sumRootToLeaf(self, root: TreeNode) -> int: mod = 10 ** 9 + 7 def Sum(node: TreeNode, curr: int) -> int: if not node.left and not node.right: return curr * 2 + node.val % mod sum = 0 sum += Sum(node.left, curr * 2 + node.val % mod) if node.left else 0 sum += Sum(node.right, curr * 2 + node.val % mod) if node.right else 0 return sum if not root: return 0 return Sum(root, 0)
jsuo/XVim2
XVim2/XcodeHeader/IDESourceEditor/DVTTextReplacable-Protocol.h
<reponame>jsuo/XVim2 // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 30 2018 09:30:25). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <IDESourceEditor/NSObject-Protocol.h> @class NSArray, NSString, NSURL; @protocol DVTTextReplacable <NSObject> - (BOOL)replaceFindResults:(NSArray *)arg1 withString:(NSString *)arg2 withError:(id *)arg3; @optional - (BOOL)replaceFindResults:(NSArray *)arg1 inSelection:(struct _NSRange)arg2 withString:(NSString *)arg3 withError:(id *)arg4; - (BOOL)replaceTextWithContentsOfURL:(NSURL *)arg1 error:(id *)arg2; @end
SINTEF/simapy
src/sima/simo/thrustloss.py
<filename>src/sima/simo/thrustloss.py # Generated with ThrustLoss # from enum import Enum from enum import auto class ThrustLoss(Enum): """""" NONE = auto() SURFACE = auto() def label(self): if self == ThrustLoss.NONE: return "None" if self == ThrustLoss.SURFACE: return "Surface"
alexman111/Containers
java7/src/main/java/deltix/containers/interfaces/BinaryArrayReadWrite.java
<filename>java7/src/main/java/deltix/containers/interfaces/BinaryArrayReadWrite.java package deltix.containers.interfaces; public interface BinaryArrayReadWrite extends BinaryArrayReadOnly { BinaryArrayReadWrite assign(byte[] bytes); BinaryArrayReadWrite append(byte[] bytes); BinaryArrayReadWrite assign(byte[] bytes, int offset, int count); BinaryArrayReadWrite append(byte[] bytes, int offset, int count); BinaryArrayReadWrite assign(BinaryArrayReadOnly str); BinaryArrayReadWrite append(BinaryArrayReadOnly str); /*TODO: Strictly recommended to override*/ @Override BinaryArrayReadWrite clone(); /*TODO: implement only these methods*/ BinaryArrayReadWrite set(int index, byte x); BinaryArrayReadWrite append(byte b); BinaryArrayReadWrite clear(); }
endowp/Python101
08/08_P14.py
<reponame>endowp/Python101 n=int(input()) dg={} #group di={} #รุ่น dd={} #ภาค t=() namet=() for i in range(n): info = input() t+=(info,) name, g, i, d = info.strip().split() namet+=(name, ) if g not in dg: dg[g] = {name} else: dg[g].add(name) if i not in di: di[i] = {name} else: di[i].add(name) if d not in dd: dd[d] = {name} else: dd[d].add(name) find = input().split() intersec = namet for f in find: if f in dg: intersec = set(intersec) & dg[f] elif f in di: intersec = set(intersec) & di[f] elif f in dd: intersec = set(intersec) & dd[f] else: intersec=() if len(intersec)>0: for subt in sorted(t): for inter in intersec: if inter == subt.split()[0]: print(subt) else: print("Not Found")
blackmiaool/kexie_game
old/js/scenes/save.js
var backto; var scene = new sys.Scene({ id: "save", dom_id: "scene_save", init: function () { angular.module('home_app') .controller("save_controller", ["$rootScope", "$scope", function ($rootScope, $scope) { $scope.buttons = []; $rootScope.$on("save_pre_enter", (args, params) => { console.log("enter"); let [save_this, backto_this] = params; save = save_this; backto = backto_this; if (save == "save") { $scope.title = "存档"; } else { $scope.title = "读档"; } load_records(); if(!$scope.$$phase) $scope.$digest(); }) // setInterval(()=>{console.log($scope.buttons)},1000) for (var i = 0; i < 6; i++) { $scope.buttons[i] = {} } var save, backto; var storage_name = "kexiegamesave"; function getProgressName(index) { return "progress" + index } function getSaveName(index) { return "Save" + index } function getSaveText(index) { return local_load(getSaveName(index)) } function saveSaveText(index) { var time = new Date(); time = time.toLocaleString(); local_set(getSaveName(index), time) //console.log(local_load(getSaveName(index))) // $(this).text(time) } function save_all() { common.local.set(storage_name, $scope.buttons); } var save_record = index => { if ($scope.buttons[index].version) { if (confirm("是否确定覆盖存档?")) { } else { return; } } var date = new Date; var time_string = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); $scope.buttons[index] = { version: sys.config.version, data: v, title: time_string, } save_all(); load_records(); } var load_record = function (index) { if ($scope.buttons[index].version) { angular.element("#scene_home").scope().v = $scope.buttons[index].data; v = $scope.buttons[index].data; sys.to_scene("home"); } // toscene("home") } function load_records() { var record = common.local.get(storage_name); if (!record) { save_all(); } $scope.buttons = record; // angular.element("#scene_home").scope().$digest(); } $scope.go_back = function () { sys.to_scene(backto ? backto : "home"); } $scope.get_btn_text = function (index) { } $scope.handle = function (index) { if (save == "save") { save_record(index); } else { load_record(index); } } }]) }, enter: function () {} })
ktotheoz/pixellight
Base/PLMath/src/Graph/GraphPath.cpp
/*********************************************************\ * File: GraphPath.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "PLMath/Graph/GraphNode.h" #include "PLMath/Graph/GraphPath.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] using namespace PLCore; namespace PLMath { //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Constructor */ GraphPath::GraphPath(const String &sName, ResourceManager<GraphPath> *pManager) : Resource<GraphPath>(sName, pManager), m_pOwnerGraph(nullptr), m_bClosed(false) { } /** * @brief * Constructor */ GraphPath::GraphPath(Graph *pOwnerGraph) : m_pOwnerGraph(pOwnerGraph), m_bClosed(false) { } /** * @brief * Destructor */ GraphPath::~GraphPath() { } /** * @brief * Returns the owner graph of the path */ Graph *GraphPath::GetOwnerGraph() const { return m_pOwnerGraph; } //[-------------------------------------------------------] //[ Nodes ] //[-------------------------------------------------------] /** * @brief * Returns the number of nodes */ uint32 GraphPath::GetNumOfNodes() const { return m_lstNodes.GetNumOfElements(); } /** * @brief * Adds a node */ bool GraphPath::AddNode(GraphNode &cNode) { return (m_lstNodes.Add(&cNode) != nullptr); } /** * @brief * Removes a node */ bool GraphPath::RemoveNode(uint32 nNode) { // Remove node itself? if (!m_pOwnerGraph) { GraphNode *pNode = m_lstNodes[nNode]; if (pNode) delete pNode; } // Remove node from list return m_lstNodes.RemoveAtIndex(nNode); } /** * @brief * Returns a node */ const GraphNode *GraphPath::GetNode(uint32 nID) const { return m_lstNodes[nID]; } /** * @brief * Returns a node */ GraphNode *GraphPath::GetNode(uint32 nID) { return m_lstNodes[nID]; } //[-------------------------------------------------------] //[ Tools ] //[-------------------------------------------------------] /** * @brief * Returns the length of the path */ float GraphPath::GetLength() const { float fLength = 0.0f; { // Get path length const GraphNode *pLastNode = nullptr; Iterator<GraphNode*> cIterator = m_lstNodes.GetIterator(); while (cIterator.HasNext()) { const GraphNode *pNode = cIterator.Next(); if (pLastNode) fLength += pNode->GetDistance(*pLastNode); pLastNode = pNode; } } // If closed add the distance from the first to the last node if (m_bClosed) fLength += m_lstNodes[0]->GetDistance(*m_lstNodes[m_lstNodes.GetNumOfElements()-1]); // Return the path length return fLength; } /** * @brief * Returns whether the path is closed or not */ bool GraphPath::IsClosed() const { return m_bClosed; } /** * @brief * Sets if the path is closed or not */ void GraphPath::SetClosed(bool bClosed) { m_bClosed = bClosed; } /** * @brief * Calculates the position at the given node index */ Vector3 GraphPath::GetPosByNodeIndex(float fNodeIndex, bool bLinear) const { // [TODO] Refactor the implementation // Check bounding if (!m_lstNodes.GetNumOfElements()) return Vector3::Zero; // Error! if (m_lstNodes.GetNumOfElements() == 1) return m_lstNodes[0]->GetPos(); if (!m_bClosed) { // Clamp if (fNodeIndex <= 0.0f) return m_lstNodes[0]->GetPos(); if (fNodeIndex >= m_lstNodes.GetNumOfElements()-3) return m_lstNodes[m_lstNodes.GetNumOfElements()-2]->GetPos(); } // Wrap while (fNodeIndex < 0) fNodeIndex += m_lstNodes.GetNumOfElements(); while (fNodeIndex > m_lstNodes.GetNumOfElements()) fNodeIndex -= m_lstNodes.GetNumOfElements(); // Set valid nodes uint32 nCurrentNode = static_cast<uint32>(fNodeIndex); uint32 nNextNode = nCurrentNode+1; if (nNextNode > m_lstNodes.GetNumOfElements()-1) nNextNode = m_bClosed ? 0 : nNextNode-1; float fProgress = fNodeIndex-nCurrentNode; // Interpolate if (bLinear) { return (m_lstNodes[nCurrentNode])->GetPos()+ (m_lstNodes[nNextNode]->GetPos()-m_lstNodes[nCurrentNode]->GetPos())*fProgress; } else { // Catmull rom curve const Vector3 &vP1 = m_lstNodes[nCurrentNode]->GetPos(); const Vector3 &vP2 = m_lstNodes[nNextNode]->GetPos(); nNextNode = nNextNode+1; if (nNextNode > m_lstNodes.GetNumOfElements()-1) nNextNode = m_bClosed ? 0 : nNextNode-1; const Vector3 &vP3 = m_lstNodes[nNextNode]->GetPos(); nNextNode = nNextNode+1; if (nNextNode > m_lstNodes.GetNumOfElements()-1) nNextNode = m_bClosed ? 0 : nNextNode-1; const Vector3 &vP4 = m_lstNodes[nNextNode]->GetPos(); float t = fProgress; float t2 = t*t; float t3 = t2*t; float t1 = (1-t)*(1-t); return Vector3((-t*t1*vP1.x + (2-5*t2+3*t3)*vP2.x + t*(1+4*t-3*t2)*vP3.x - t2*(1-t)*vP4.x)/2, (-t*t1*vP1.y + (2-5*t2+3*t3)*vP2.y + t*(1+4*t-3*t2)*vP3.y - t2*(1-t)*vP4.y)/2, (-t*t1*vP1.z + (2-5*t2+3*t3)*vP2.z + t*(1+4*t-3*t2)*vP3.z - t2*(1-t)*vP4.z)/2); } } /** * @brief * Calculates the position by using percentage along the path */ Vector3 GraphPath::GetPosByPercentageAlongPath(float fPercentageAlongPath, bool bLinear) const { // [TODO] Under construction // Check bounding if (!m_lstNodes.GetNumOfElements()) return Vector3::Zero; // Error! if (m_lstNodes.GetNumOfElements() == 1) return m_lstNodes[0]->GetPos(); // Linear interpolation? if (bLinear) { // Clamp to 0-1 if (fPercentageAlongPath >= 0.0f) fPercentageAlongPath = fPercentageAlongPath-static_cast<int>(fPercentageAlongPath); else fPercentageAlongPath = 1+fPercentageAlongPath-static_cast<int>(fPercentageAlongPath); // Get the total path length and current length on path float fTotalPathLength = GetLength(); float fLengthOnPath = fPercentageAlongPath*fTotalPathLength; // We need to find the to nodes we are currently between // Get path length float fLength = 0.0f; float fPreviousLength = 0.0f; float fDistanceBetweenNodes = 0.0f; const GraphNode *pLastNode = nullptr; Iterator<GraphNode*> cIterator = m_lstNodes.GetIterator(); while (cIterator.HasNext() && fLength < fLengthOnPath) { // Backup the current length on path fPreviousLength = fLength; const GraphNode *pNode = cIterator.Next(); if (pLastNode) { fDistanceBetweenNodes = pNode->GetDistance(*pLastNode); fLength += fDistanceBetweenNodes; if (fLength >= fLengthOnPath) { // Get current and next node const GraphNode *pCurrentNode = pLastNode; const GraphNode *pNextNode = pNode; float fDistance = fLengthOnPath-fPreviousLength; float fPercentageBetweenNodes = fDistanceBetweenNodes ? fDistance/fDistanceBetweenNodes : 0.0f; // Interpolate return pCurrentNode->GetPos()+(pNextNode->GetPos()-pCurrentNode->GetPos())*fPercentageBetweenNodes; } } // Backup the current node pLastNode = pNode; } // Handle the case of closed path if (m_bClosed) { const GraphNode *pNode = m_lstNodes[0]; if (pLastNode) { fDistanceBetweenNodes = pNode->GetDistance(*pLastNode); fLength += fDistanceBetweenNodes; if (fLength >= fLengthOnPath) { // Get current and next node const GraphNode *pCurrentNode = pLastNode; const GraphNode *pNextNode = pNode; float fDistance = fLengthOnPath-fPreviousLength; float fPercentageBetweenNodes = (fDistanceBetweenNodes ? fDistance/fDistanceBetweenNodes : 0.0f)-1; // Interpolate return pCurrentNode->GetPos()+(pNextNode->GetPos()-pCurrentNode->GetPos())*fPercentageBetweenNodes; } } } // None linear } else { } // Error, return the position of the first path node return m_lstNodes[0]->GetPos(); } //[-------------------------------------------------------] //[ Public virtual PLCore::Resource functions ] //[-------------------------------------------------------] GraphPath &GraphPath::operator =(const GraphPath &cSource) { // Unload the old path Unload(); // Call base implementation *static_cast<Resource<GraphPath>*>(this) = cSource; // Copy data m_pOwnerGraph = cSource.m_pOwnerGraph; m_bClosed = cSource.m_bClosed; if (m_pOwnerGraph) { // Only copy node links m_lstNodes = cSource.m_lstNodes; } else { // Copy nodes Iterator<GraphNode*> cIterator = cSource.m_lstNodes.GetIterator(); while (cIterator.HasNext()) AddNode(*(new GraphNode(*cIterator.Next()))); } // Return this return *this; } //[-------------------------------------------------------] //[ Public virtual PLCore::Loadable functions ] //[-------------------------------------------------------] bool GraphPath::Unload() { // Clear nodes if (!m_pOwnerGraph) { Iterator<GraphNode*> cIterator = m_lstNodes.GetIterator(); while (cIterator.HasNext()) delete cIterator.Next(); } m_lstNodes.Clear(); // Reset data m_pOwnerGraph = nullptr; m_bClosed = false; // Call base implementation return Resource<GraphPath>::Unload(); } String GraphPath::GetLoadableTypeName() const { static const String sString = "GraphPath"; return sString; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLMath
user3301/TrialOfTheGrasses
Go/ValidPalindromeII.go
package gosoln func ValidPalindromeII(s string) bool { re := []rune(s) l, r := 0, len(s)-1 for l < r { if re[l] == re[r] { l++ r-- } else { return isPalindrome(re[l+1:r+1]) || isPalindrome(re[l:r]) } } return true } func isPalindrome(re []rune) bool { l, r := 0, len(re)-1 for l < r { if re[l] == re[r] { l++ r-- } else { return false } } return true }
hxlzp/Travel
app/src/main/java/com/example/hxl/travel/presenter/contract/AddressLinkerContract.java
package com.example.hxl.travel.presenter.contract; import android.content.Context; import com.example.hxl.travel.base.BasePresenter; import com.example.hxl.travel.base.BaseView; import com.example.hxl.travel.model.bean.User; import java.util.List; /** * Created by hxl on 2017/8/23 0023 at haichou. */ public interface AddressLinkerContract { interface View extends BaseView<Presenter> { boolean isActive(); Context getAddressLinkerContext(); void showData(List<User> datas); void showPregress(); void hideProgress(); } interface Presenter extends BasePresenter{ void getData(); } }
CuteShaun/frontend-2019-homeworks
submissions/Roman-Halenko/js-oop-frogger/js/app.js
// Enemies our player must avoid const Enemy = function(x, y) { // Variables applied to each of our instances go here, // we've provided one for you to get started // The image/sprite for our enemies, this uses // a helper we've provided to easily load images this.x = x; this.y = y; this.width = 80; this.speed = randomSpeed(80, 290); this.edge = {right: 500, left: -101} this.sprite = 'images/enemy-bug.png'; }; function randomSpeed(min, max) { return Math.random() * (max - min) + min; } // Update the enemy's position, required method for game // Parameter: dt, a time delta between ticks Enemy.prototype.update = function(dt) { if (this.x < this.edge.right) { this.x += dt * this.speed; } else { this.x = this.edge.left; this.speed = randomSpeed(100, 300); } }; // Draw the enemy on the screen, required method for game Enemy.prototype.render = function() { ctx.drawImage(Resources.get(this.sprite), this.x, this.y); }; // Now write your own player class // This class requires an update(), render() and // a handleInput() method. const Player = function() { this.width = 80; this.sprite = 'images/char-boy.png'; this.x = 202; this.y = 400; this.stepX = 101; this.stepY = 84; this.edge = {top: -20, right: 404, bottom: 400, left: 0}; }; Player.prototype.render = function() { ctx.drawImage(Resources.get(this.sprite), this.x, this.y); }; Player.prototype.toBegin = function(d) { if (d === 0) { this.x = 202; this.y = 400; } else { let that = this; setTimeout(function () { that.x = 202; that.y = 400; }, d); } }; Player.prototype.update = function() { if (this.y === this.edge.top) { this.toBegin(400); } this.checkEnemyCollision(); }; Player.prototype.checkEnemyCollision = function() { allEnemies.forEach( e => { let that = this; if (e.y === that.y && that.x <= e.x + e.width && that.x + that.width >= e.x) { that.toBegin(0); } }) }; Player.prototype.handleInput = function(key) { if (key === 'left' && this.x !== this.edge.left) { this.x -= this.stepX; } else if (key === 'right' && this.x !== this.edge.right) { this.x += this.stepX; } else if (key === 'down' && this.y !== this.edge.bottom) { this.y += this.stepY; } else if (key === 'up' && this.y !== this.edge.top) { this.y -= this.stepY; } }; // Now instantiate your objects. // Place all enemy objects in an array called allEnemies // Place the player object in a variable called player const enemy1 = new Enemy(-101, 64), enemy2 = new Enemy(-101, 148), enemy3 = new Enemy(-101, 232); const allEnemies = [enemy1, enemy2, enemy3]; const player = new Player(); // This listens for key presses and sends the keys to your // Player.handleInput() method. You don't need to modify this. document.addEventListener('keyup', function(e) { const allowedKeys = { 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; player.handleInput(allowedKeys[e.keyCode]); });
jiripetrlik/droolsjbpm-integration
kie-remote/kie-remote-client/src/main/java/org/kie/remote/client/api/RemoteRuntimeEngineFactory.java
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.kie.remote.client.api; import java.util.Properties; import javax.jms.ConnectionFactory; import javax.jms.Queue; import javax.naming.InitialContext; import javax.naming.NamingException; import org.kie.api.runtime.manager.RuntimeEngine; import org.kie.remote.client.api.exception.RemoteCommunicationException; import org.kie.remote.services.ws.command.generated.CommandWebService; /** * This factory class is the starting point for building and configuring {@link RuntimeEngine} instances * that can interact with the remote API. * </p> * The main use for this class will be to create builder instances (see * {@link #newJmsBuilder()} and {@link #newRestBuilder()}). These builder instances * can then be used to directly configure and create a {@link RuntimeEngine} instance that will * act as a client to the remote (REST or JMS) API. */ public abstract class RemoteRuntimeEngineFactory { /** * Create a new {@link RemoteJmsRuntimeEngineBuilder} instance * to configure and buid a remote API client {@link RuntimeEngine} instance. * @return A {@link RemoteJmsRuntimeEngineBuilder} instance */ public static RemoteJmsRuntimeEngineBuilder newJmsBuilder() { return org.kie.remote.client.internal.RemoteRuntimeEngineFactory.newJmsBuilder(); } /** * Create a new {@link RemoteRestRuntimeEngineBuilder} instance * to configure and buid a remote API client {@link RuntimeEngine} instance. * @return A {@link RemoteRestRuntimeEngineBuilder} instance */ public static RemoteRestRuntimeEngineBuilder newRestBuilder() { return org.kie.remote.client.internal.RemoteRuntimeEngineFactory.newRestBuilder(); } /** * Create a new {@link RemoteWebserviceClientBuilder} instance * to configure and buid a remote client for the {@link CommandWebService}. * @return A {@link RemoteWebserviceClientBuilder} instance */ public static RemoteWebserviceClientBuilder<RemoteWebserviceClientBuilder, CommandWebService> newCommandWebServiceClientBuilder() { return org.kie.remote.client.internal.RemoteRuntimeEngineFactory.newCommandWebServiceClientBuilder(); } /** * @return a new (remote client) {@link RuntimeEngine} instance. * @see {@link RemoteRuntimeEngineBuilder#buildRuntimeEngine()} */ public abstract RuntimeEngine newRuntimeEngine(); /** * Retrieves the (remote) {@link InitialContext} from the JBoss AS server instance in order * to be able to retrieve the {@link ConnectionFactory} and {@link Queue} instances to communicate * with the workbench, console or BPMS instance. * * @param jbossServerHostName The hostname of the jboss server instance * @param user A user permitted to retrieve the remote {@link InitialContext} * @param password The password for the user specified * @return a remote {@link InitialContext} instance */ public static InitialContext getRemoteJbossInitialContext(String jbossServerHostName, String user, String password) { Properties initialProps = new Properties(); initialProps.setProperty(InitialContext.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory"); initialProps.setProperty(InitialContext.PROVIDER_URL, "remote://"+ jbossServerHostName + ":4447"); initialProps.setProperty(InitialContext.SECURITY_PRINCIPAL, user); initialProps.setProperty(InitialContext.SECURITY_CREDENTIALS, password); for (Object keyObj : initialProps.keySet()) { String key = (String) keyObj; System.setProperty(key, (String) initialProps.get(key)); } try { return new InitialContext(initialProps); } catch (NamingException e) { throw new RemoteCommunicationException("Unable to create " + InitialContext.class.getSimpleName(), e); } } }