text
stringlengths
2
1.04M
meta
dict
package org.apache.geode.test.dunit.internal; import java.io.IOException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import org.apache.geode.test.version.VmConfiguration; public interface ChildVMLauncher { ProcessHolder launchVM(VmConfiguration configuration, int vmNum, boolean bouncedVM, int remoteStubPort) throws IOException; RemoteDUnitVMIF getStub(int i) throws RemoteException, NotBoundException, InterruptedException; }
{ "content_hash": "9bc23615c7a5c9ac1a87667dc2e970cc", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 97, "avg_line_length": 29.3125, "alnum_prop": 0.8230277185501066, "repo_name": "jdeppe-pivotal/geode", "id": "6adddfe4e99142e7b869ca112fdf0578bb54bf40", "size": "1258", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "geode-dunit/src/main/java/org/apache/geode/test/dunit/internal/ChildVMLauncher.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "104031" }, { "name": "Dockerfile", "bytes": "15956" }, { "name": "Go", "bytes": "40709" }, { "name": "Groovy", "bytes": "41916" }, { "name": "HTML", "bytes": "4037680" }, { "name": "Java", "bytes": "33151406" }, { "name": "JavaScript", "bytes": "1780821" }, { "name": "Python", "bytes": "29801" }, { "name": "Ruby", "bytes": "1801" }, { "name": "SCSS", "bytes": "2677" }, { "name": "Shell", "bytes": "275617" } ], "symlink_target": "" }
using System; using UnityEngine; namespace UnityEditor.VFX.Operator { [VFXInfo(category = "Sampling")] class SampleTextureCubeArray : VFXOperator { override public string name { get { return "Sample TextureCubeArray"; } } public class InputProperties { [Tooltip("The texture to sample from.")] public CubemapArray texture = null; [Tooltip("The texture coordinate used for the sampling.")] public Vector3 uvw = Vector3.zero; [Min(0), Tooltip("The array slice to sample from.")] public float slice = 0.0f; [Min(0), Tooltip("The mip level to sample from.")] public float mipLevel = 0.0f; } public class OutputProperties { public Vector4 s = Vector4.zero; } protected override sealed VFXExpression[] BuildExpression(VFXExpression[] inputExpression) { return new[] { new VFXExpressionSampleTextureCubeArray(inputExpression[0], inputExpression[1], inputExpression[2], inputExpression[3]) }; } } }
{ "content_hash": "0f2bba1220cf7feecbe32647378bae82", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 149, "avg_line_length": 33.666666666666664, "alnum_prop": 0.6147614761476148, "repo_name": "Unity-Technologies/ScriptableRenderLoop", "id": "5b300e655b0ee33bbb75e04cdbe4f72d9f7232cb", "size": "1111", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "com.unity.visualeffectgraph/Editor/Models/Operators/Implementations/SampleTextureCubeArray.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "9056" }, { "name": "C#", "bytes": "2152773" }, { "name": "GLSL", "bytes": "13708" }, { "name": "HLSL", "bytes": "833428" }, { "name": "ShaderLab", "bytes": "231099" } ], "symlink_target": "" }
package org.apache.ignite.internal.processors.cache; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.internal.IgniteClientReconnectAbstractTest; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.processors.cache.persistence.CheckpointState; import org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.testframework.GridTestUtils.SF; import org.junit.Ignore; import org.junit.Test; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL; import static org.apache.ignite.cache.CacheMode.PARTITIONED; import static org.apache.ignite.cluster.ClusterState.ACTIVE; import static org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager.CACHE_DATA_FILENAME; /** * Concurrent and advanced tests for WAL state change. */ @SuppressWarnings("unchecked") public class WalModeChangeAdvancedSelfTest extends WalModeChangeCommonAbstractSelfTest { /** * Constructor. */ public WalModeChangeAdvancedSelfTest() { super(false); } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { cleanPersistenceDir(); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { super.afterTest(); stopAllGrids(); cleanPersistenceDir(); } /** * Verifies that node with consistent partitions (fully synchronized with disk on a previous checkpoint) * starts successfully even if WAL for that cache group is globally disabled. * * <p> * Test scenario: * </p> * <ol> * <li> * Start a cluster from one server node, activate cluster. * </li> * <li> * Create new cache. Disable WAL for the cache and put some data to it. * </li> * <li> * Trigger checkpoint and wait for it finish. Restart node. * </li> * <li> * Verify that node starts successfully and data is presented in the cache. * </li> * </ol> * * @throws Exception If failed. */ @Test public void testConsistentDataPreserved() throws Exception { Ignite srv = startGrid(config(SRV_1, false, false)); srv.cluster().state(ACTIVE); IgniteCache cache1 = srv.getOrCreateCache(cacheConfig(CACHE_NAME, PARTITIONED, TRANSACTIONAL)); srv.cluster().disableWal(CACHE_NAME); for (int i = 0; i < 10; i++) cache1.put(i, i); GridCacheDatabaseSharedManager dbMrg0 = (GridCacheDatabaseSharedManager) ((IgniteEx)srv).context().cache().context().database(); dbMrg0.forceCheckpoint("cp").futureFor(CheckpointState.FINISHED).get(); stopGrid(SRV_1); srv = startGrid(config(SRV_1, false, false)); assertForAllNodes(CACHE_NAME, false); cache1 = srv.cache(CACHE_NAME); for (int i = 0; i < 10; i++) assertNotNull(cache1.get(i)); } /** * If user manually clears corrupted files when node was down, node detects this and not enters maintenance mode * (although still need another restart to get back to normal operations). * * <p> * Test scenario: * <ol> * <li> * Start server node, create cache, disable WAL for the cache, put some keys to it. * </li> * <li> * Stop server node, remove checkpoint end markers from cp directory * to make node think it has failed in the middle of checkpoint. * </li> * <li> * Start the node, verify it fails to start because of corrupted PDS of the cache. * </li> * <li> * Clean data directory of the cache, start node again, verify it doesn't report maintenance mode. * </li> * <li> * Restart node and verify it is in normal operations mode. * </li> * </ol> * </p> * * * @throws Exception If failed. */ @Test public void testMaintenanceIsSkippedIfWasFixedManuallyOnDowntime() throws Exception { IgniteEx srv = startGrid(config(SRV_1, false, false)); File cacheToClean = cacheDir(srv, CACHE_NAME); String ig0Folder = srv.context().pdsFolderResolver().resolveFolders().folderName(); File dbDir = U.resolveWorkDirectory(srv.configuration().getWorkDirectory(), "db", false); File ig0LfsDir = new File(dbDir, ig0Folder); File ig0CpDir = new File(ig0LfsDir, "cp"); srv.cluster().state(ACTIVE); IgniteCache cache1 = srv.getOrCreateCache(cacheConfig(CACHE_NAME, PARTITIONED, TRANSACTIONAL)); srv.cluster().disableWal(CACHE_NAME); for (int i = 0; i < 10; i++) cache1.put(i, i); stopAllGrids(true); File[] cpMarkers = ig0CpDir.listFiles(); for (File cpMark : cpMarkers) { if (cpMark.getName().contains("-END")) cpMark.delete(); } // Node should fail as its PDS may be corrupted because of disabled WAL GridTestUtils.assertThrows(null, () -> startGrid(config(SRV_1, false, false)), Exception.class, null); cleanCacheDir(cacheToClean); // Node should start successfully and not enter maintenance mode as MaintenanceRecord will be cleaned // automatically because corrupted PDS was deleted during downtime srv = startGrid(config(SRV_1, false, false)); assertFalse(srv.context().maintenanceRegistry().isMaintenanceMode()); stopAllGrids(false); // After restart node works normal mode even without executing maintenance action to clear corrupted PDS srv = startGrid(config(SRV_1, false, false)); assertFalse(srv.context().maintenanceRegistry().isMaintenanceMode()); srv.cluster().state(ACTIVE); cache1 = srv.getOrCreateCache(CACHE_NAME); assertEquals(0, cache1.size()); } /** * Test cache cleanup on restart. * * @throws Exception If failed. */ @Test public void testCacheCleanup() throws Exception { Ignite srv = startGrid(config(SRV_1, false, false)); File cacheToClean = cacheDir(srv, CACHE_NAME_2); srv.cluster().state(ACTIVE); IgniteCache cache1 = srv.getOrCreateCache(cacheConfig(CACHE_NAME, PARTITIONED, TRANSACTIONAL)); IgniteCache cache2 = srv.getOrCreateCache(cacheConfig(CACHE_NAME_2, PARTITIONED, TRANSACTIONAL)); assertForAllNodes(CACHE_NAME, true); assertForAllNodes(CACHE_NAME_2, true); for (int i = 0; i < 10; i++) { cache1.put(i, i); cache2.put(i, i); } srv.cluster().disableWal(CACHE_NAME); assertForAllNodes(CACHE_NAME, false); assertForAllNodes(CACHE_NAME_2, true); for (int i = 10; i < 20; i++) { cache1.put(i, i); cache2.put(i, i); } srv.cluster().disableWal(CACHE_NAME_2); assertForAllNodes(CACHE_NAME, false); assertForAllNodes(CACHE_NAME_2, false); for (int i = 20; i < 30; i++) { cache1.put(i, i); cache2.put(i, i); } assertEquals(cache1.size(), 30); assertEquals(cache2.size(), 30); srv.cluster().enableWal(CACHE_NAME); assertForAllNodes(CACHE_NAME, true); assertForAllNodes(CACHE_NAME_2, false); assertEquals(cache1.size(), 30); assertEquals(cache2.size(), 30); stopAllGrids(true); cleanCacheDir(cacheToClean); srv = startGrid(config(SRV_1, false, false)); srv.cluster().state(ACTIVE); cache1 = srv.cache(CACHE_NAME); cache2 = srv.cache(CACHE_NAME_2); assertForAllNodes(CACHE_NAME, true); assertForAllNodes(CACHE_NAME_2, false); assertEquals(30, cache1.size()); assertEquals(0, cache2.size()); } /** */ private File cacheDir(Ignite ig, String cacheName) throws IgniteCheckedException { String igFolder = ((IgniteEx)ig).context().pdsFolderResolver().resolveFolders().folderName(); File dbDir = U.resolveWorkDirectory(ig.configuration().getWorkDirectory(), "db", false); File igPdsFolder = new File(dbDir, igFolder); return new File(igPdsFolder, "cache-" + cacheName); } /** */ private void cleanCacheDir(File cacheDir) { for (File f : cacheDir.listFiles()) { if (!f.getName().equals(CACHE_DATA_FILENAME)) f.delete(); } } /** * Test simple node join. * * @throws Exception If failed. */ @Test public void testJoin() throws Exception { checkJoin(false); } /** * Test simple node join when operations is performed from coordinator. * * @throws Exception If failed. */ @Test public void testJoinCoordinator() throws Exception { checkJoin(true); } /** * Check node join behavior. * * @param crdFiltered {@code True} if first node is coordinator. * @throws Exception If failed. */ private void checkJoin(boolean crdFiltered) throws Exception { // Start node and disable WAL. Ignite srv = startGrid(config(SRV_1, false, crdFiltered)); srv.cluster().state(ACTIVE); srv.getOrCreateCache(cacheConfig(PARTITIONED)); assertForAllNodes(CACHE_NAME, true); if (!crdFiltered) { srv.cluster().disableWal(CACHE_NAME); assertForAllNodes(CACHE_NAME, false); } // Start other nodes. IgniteEx ig2 = startGrid(config(SRV_2, false, false)); File ig2CacheDir = cacheDir(ig2, CACHE_NAME); if (crdFiltered) srv.cluster().disableWal(CACHE_NAME); assertForAllNodes(CACHE_NAME, false); startGrid(config(SRV_3, false, !crdFiltered)); assertForAllNodes(CACHE_NAME, false); startGrid(config(CLI, true, false)); assertForAllNodes(CACHE_NAME, false); // Stop nodes and restore WAL state on the first node. stopGrid(SRV_2, true); stopGrid(SRV_3, true); stopGrid(CLI, true); if (!crdFiltered) { srv.cluster().enableWal(CACHE_NAME); assertForAllNodes(CACHE_NAME, true); } cleanCacheDir(ig2CacheDir); // Start other nodes again. startGrid(config(SRV_2, false, false)); if (crdFiltered) srv.cluster().enableWal(CACHE_NAME); assertForAllNodes(CACHE_NAME, true); startGrid(config(SRV_3, false, !crdFiltered)); assertForAllNodes(CACHE_NAME, true); startGrid(config(CLI, true, false)); assertForAllNodes(CACHE_NAME, true); } /** * Test server restart (non-coordinator). * * @throws Exception If failed. */ @Test public void testServerRestartNonCoordinator() throws Exception { checkNodeRestart(false); } /** * Test server restart (coordinator). * * @throws Exception If failed. */ @Ignore("https://issues.apache.org/jira/browse/IGNITE-7472") @Test public void testServerRestartCoordinator() throws Exception { checkNodeRestart(true); } /** * Test coordinator node migration. * * @param failCrd Whether to fail coordinator nodes. * @throws Exception If failed. */ public void checkNodeRestart(boolean failCrd) throws Exception { startGrid(config(SRV_1, false, false)); startGrid(config(SRV_2, false, false)); Ignite cli = startGrid(config(CLI, true, false)); cli.cluster().state(ACTIVE); cli.getOrCreateCache(cacheConfig(PARTITIONED)); final AtomicInteger restartCnt = new AtomicInteger(); final int restarts = SF.applyLB(5, 3); Thread t = new Thread(new Runnable() { @Override public void run() { boolean firstOrSecond = true; while (restartCnt.get() < restarts) { String victimName; if (failCrd) { victimName = firstOrSecond ? SRV_1 : SRV_2; firstOrSecond = !firstOrSecond; } else victimName = SRV_2; try { File cacheDir = cacheDir(grid(victimName), CACHE_NAME); stopGrid(victimName); cleanCacheDir(cacheDir); startGrid(config(victimName, false, false)); Thread.sleep(200); } catch (Exception e) { throw new RuntimeException(); } restartCnt.incrementAndGet(); log.info(">>> Finished restart: " + restartCnt.get()); } } }); t.start(); boolean state = true; while (restartCnt.get() < restarts && !Thread.currentThread().isInterrupted()) { try { if (state) cli.cluster().disableWal(CACHE_NAME); else cli.cluster().enableWal(CACHE_NAME); state = !state; } catch (IgniteException ignore) { // Possible disconnect, re-try. } } } /** * Test client re-connect. * * @throws Exception If failed. */ @Test public void testClientReconnect() throws Exception { final Ignite srv = startGrid(config(SRV_1, false, false)); Ignite cli = startGrid(config(CLI, true, false)); cli.cluster().state(ACTIVE); cli.getOrCreateCache(cacheConfig(PARTITIONED)); final AtomicBoolean done = new AtomicBoolean(); // Start load. IgniteInternalFuture<?> fut = GridTestUtils.runAsync(() -> { boolean state = false; while (!done.get()) { try { if (state) cli.cluster().enableWal(CACHE_NAME); else cli.cluster().disableWal(CACHE_NAME); } catch (IgniteException e) { String msg = e.getMessage(); assert msg.startsWith("Client node disconnected") || msg.startsWith("Client node was disconnected") || msg.contains("client is disconnected") : e.getMessage(); } finally { state = !state; } } }, "wal-load-" + cli.name()); // Now perform multiple client reconnects. try { for (int i = 1; i <= 10; i++) { Thread.sleep(ThreadLocalRandom.current().nextLong(200, 1000)); IgniteClientReconnectAbstractTest.reconnectClientNode(log, cli, srv, new Runnable() { @Override public void run() { // No-op. } }); log.info(">>> Finished iteration: " + i); } } finally { done.set(true); } fut.get(); } /** * Test client re-connect. * * @throws Exception If failed. */ @Test public void testCacheDestroy() throws Exception { final Ignite srv = startGrid(config(SRV_1, false, false)); Ignite cli = startGrid(config(CLI, true, false)); cli.cluster().state(ACTIVE); srv.createCache(cacheConfig(PARTITIONED)); final AtomicBoolean done = new AtomicBoolean(); // Start load. IgniteInternalFuture<?> fut = GridTestUtils.runAsync(() -> { boolean state = false; while (!done.get()) { try { if (state) cli.cluster().enableWal(CACHE_NAME); else cli.cluster().disableWal(CACHE_NAME); } catch (IgniteException e) { String msg = e.getMessage(); assert msg.startsWith("Cache doesn't exist") || msg.startsWith("Failed to change WAL mode because some caches no longer exist") : e.getMessage(); } finally { state = !state; } } }, "wal-load-" + cli.name()); try { // Now perform multiple client reconnects. for (int i = 1; i <= 20; i++) { Thread.sleep(ThreadLocalRandom.current().nextLong(200, 1000)); srv.destroyCache(CACHE_NAME); Thread.sleep(100); srv.createCache(cacheConfig(PARTITIONED)); log.info(">>> Finished iteration: " + i); } } finally { done.set(true); } fut.get(); } /** * Test that concurrent enable/disable events doesn't leave to hangs. * * @throws Exception If failed. */ @Test public void testConcurrentOperations() throws Exception { final Ignite srv1 = startGrid(config(SRV_1, false, false)); final Ignite srv2 = startGrid(config(SRV_2, false, false)); final Ignite srv3 = startGrid(config(SRV_3, false, true)); final Ignite cli = startGrid(config(CLI, true, false)); final Ignite cacheCli = startGrid(config(CLI_2, true, false)); cacheCli.cluster().state(ACTIVE); final IgniteCache cache = cacheCli.getOrCreateCache(cacheConfig(PARTITIONED)); for (int i = 1; i <= SF.applyLB(3, 2); i++) { // Start pushing requests. Collection<Ignite> walNodes = new ArrayList<>(); walNodes.add(srv1); walNodes.add(srv2); walNodes.add(srv3); walNodes.add(cli); final AtomicBoolean done = new AtomicBoolean(); final CountDownLatch latch = new CountDownLatch(walNodes.size() + 1); for (Ignite node : walNodes) { final Ignite node0 = node; Thread t = new Thread(new Runnable() { @Override public void run() { checkConcurrentOperations(done, node0); latch.countDown(); } }); t.setName("wal-load-" + node0.name()); t.start(); } // Do some cache loading in the mean time. Thread t = new Thread(new Runnable() { @Override public void run() { int i = 0; while (!done.get()) cache.put(i, i++); latch.countDown(); } }); t.setName("cache-load"); t.start(); Thread.sleep(SF.applyLB(20_000, 2_000)); done.set(true); log.info(">>> Stopping iteration: " + i); latch.await(); log.info(">>> Iteration finished: " + i); } } /** * Check concurrent operations. * * @param done Done flag. * @param node Node. */ private static void checkConcurrentOperations(AtomicBoolean done, Ignite node) { ThreadLocalRandom rnd = ThreadLocalRandom.current(); boolean state = rnd.nextBoolean(); while (!done.get()) { if (state) node.cluster().enableWal(CACHE_NAME); else node.cluster().disableWal(CACHE_NAME); state = !state; } try { Thread.sleep(rnd.nextLong(200, 1000)); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
{ "content_hash": "3043d7d4239ddf838e85e6bd30abc9bf", "timestamp": "", "source": "github", "line_count": 691, "max_line_length": 136, "avg_line_length": 30.021707670043416, "alnum_prop": 0.5608098336948663, "repo_name": "samaitra/ignite", "id": "9eb3b7cea892189dede35a6e9c882c9ff45037bc", "size": "21559", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modules/core/src/test/java/org/apache/ignite/internal/processors/cache/WalModeChangeAdvancedSelfTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "61105" }, { "name": "C", "bytes": "5286" }, { "name": "C#", "bytes": "6347391" }, { "name": "C++", "bytes": "3684371" }, { "name": "CSS", "bytes": "281251" }, { "name": "Dockerfile", "bytes": "16105" }, { "name": "Groovy", "bytes": "15081" }, { "name": "HTML", "bytes": "821135" }, { "name": "Java", "bytes": "42055482" }, { "name": "JavaScript", "bytes": "1785625" }, { "name": "M4", "bytes": "21724" }, { "name": "Makefile", "bytes": "121296" }, { "name": "PHP", "bytes": "486991" }, { "name": "PLpgSQL", "bytes": "623" }, { "name": "PowerShell", "bytes": "11639" }, { "name": "Python", "bytes": "342274" }, { "name": "Scala", "bytes": "1386030" }, { "name": "Shell", "bytes": "615962" }, { "name": "TSQL", "bytes": "6130" }, { "name": "TypeScript", "bytes": "476855" } ], "symlink_target": "" }
<?php $url = "https://github.com/sandreas/m4b-tool"; $html = file_get_contents($url); libxml_use_internal_errors(true); $doc = new DOMDocument(); $doc->loadHTML($html); $xpath = new DOMXPath($doc); $bodyNode = $xpath->query('//article')->item(0); $readmeHtml = $doc->saveHTML($bodyNode); $templateFile = __DIR__ . "/build-homepage-template.html"; $template = file_get_contents($templateFile); $replacements = [ "<div class=\"m4b-tool\">" => "<div class=\"m4b-tool\">" . $readmeHtml, "https://" => "//" ]; // $homepageHtml = str_replace("<div class=\"m4b-tool\">", "<div class=\"m4b-tool\">".$readmeHtml, $template); $homepageHtml = strtr($template, $replacements); file_put_contents(__DIR__ . "/../homepage/index.html", $homepageHtml);
{ "content_hash": "efb1dfe9fa7b84dcdfeda3cf5ed1995a", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 110, "avg_line_length": 26.928571428571427, "alnum_prop": 0.636604774535809, "repo_name": "sandreas/m4b-tool", "id": "feb22ae4331af5749624b137e2b603a2a2a72f52", "size": "754", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/build-homepage.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "55" }, { "name": "Dockerfile", "bytes": "2242" }, { "name": "HTML", "bytes": "101904" }, { "name": "PHP", "bytes": "883040" }, { "name": "Shell", "bytes": "1691" } ], "symlink_target": "" }
require "test_helper" class CreateCategoriesTest < ActionDispatch::IntegrationTest def setup @user = User.create(username: "adminstrator", email: "adminstrator@mail.com", password: "potato", admin: true) end test "get new category form and create category" do sign_in_as(@user, "potato") get new_category_path assert_template "categories/new" assert_difference "Category.count", 1 do post_via_redirect categories_path, category: {name: "sports"} end assert_template "categories/index" assert_match "sports", response.body end test "invalid category submission results in failure" do sign_in_as(@user, "potato") get new_category_path assert_template "categories/new" assert_no_difference "Category.count" do post categories_path, category: {name: " "} end assert_template "categories/new" assert_select "h2.panel-title" assert_select "div.panel-body" end end
{ "content_hash": "2be11722489af51b6cc73a962457b097", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 114, "avg_line_length": 30.806451612903224, "alnum_prop": 0.6984293193717277, "repo_name": "xNavid/potato-blog", "id": "5b40846d9114ad11667e668dc29385e08aef2122", "size": "955", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/integration/create_categories_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3246" }, { "name": "HTML", "bytes": "20645" }, { "name": "JavaScript", "bytes": "694" }, { "name": "Ruby", "bytes": "34467" } ], "symlink_target": "" }
(function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports", "module"], factory); } else if (typeof exports !== "undefined" && typeof module !== "undefined") { factory(exports, module); } else { var mod = { exports: {} }; factory(mod.exports, mod); global.aui_en_GB = mod.exports; } })(this, function (exports, module) { "use strict"; module.exports = { "ajs.datepicker.localisations.day-names.sunday": "Sunday", "ajs.datepicker.localisations.day-names.monday": "Monday", "ajs.datepicker.localisations.day-names.tuesday": "Tuesday", "ajs.datepicker.localisations.day-names.wednesday": "Wednesday", "ajs.datepicker.localisations.day-names.thursday": "Thursday", "ajs.datepicker.localisations.day-names.friday": "Friday", "ajs.datepicker.localisations.day-names.saturday": "Saturday", "ajs.datepicker.localisations.day-names-min.sunday": "Sun", "ajs.datepicker.localisations.day-names-min.monday": "Mon", "ajs.datepicker.localisations.day-names-min.tuesday": "Tue", "ajs.datepicker.localisations.day-names-min.wednesday": "Wed", "ajs.datepicker.localisations.day-names-min.thursday": "Thu", "ajs.datepicker.localisations.day-names-min.friday": "Fri", "ajs.datepicker.localisations.day-names-min.saturday": "Sat", "ajs.datepicker.localisations.first-day": 1, "ajs.datepicker.localisations.is-RTL": false, "ajs.datepicker.localisations.month-names.january": "January", "ajs.datepicker.localisations.month-names.february": "February", "ajs.datepicker.localisations.month-names.march": "March", "ajs.datepicker.localisations.month-names.april": "April", "ajs.datepicker.localisations.month-names.may": "May", "ajs.datepicker.localisations.month-names.june": "June", "ajs.datepicker.localisations.month-names.july": "July", "ajs.datepicker.localisations.month-names.august": "August", "ajs.datepicker.localisations.month-names.september": "September", "ajs.datepicker.localisations.month-names.october": "October", "ajs.datepicker.localisations.month-names.november": "November", "ajs.datepicker.localisations.month-names.december": "December", "ajs.datepicker.localisations.show-month-after-year": false, "ajs.datepicker.localisations.year-suffix": null }; }); //# sourceMappingURL=../../../../js/aui/internal/i18n/aui_en_GB.js.map
{ "content_hash": "b5d45549d644607ca54c81c1f0abc8c0", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 81, "avg_line_length": 52.89795918367347, "alnum_prop": 0.6585648148148148, "repo_name": "parambirs/aui-demos", "id": "58debf2e0434400d8c439ec6c77438445887917b", "size": "2592", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "node_modules/@atlassian/aui/lib/js/aui/internal/i18n/aui_en_GB.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "132297" }, { "name": "JavaScript", "bytes": "84263" } ], "symlink_target": "" }
<?php class Task_User_Create extends Minion_Task { protected $_options = array( 'username' => NULL, 'password' => NULL, 'email' => NULL ); protected function _execute(array $params) { try { $params['password_confirm'] = $params['password']; $user = ORM::factory('User') ->create_user($params, array_keys($this->_options)); Minion_CLI::write('User created: '.$params['username']); } catch (ORM_Validation_Exception $e) { $errors = $e->errors(); foreach ($errors as $key => $values) { Minion_CLI::write(Minion_CLI::color($key.' failed check: '.$values[0], 'red')); } } } }
{ "content_hash": "c6324844d95a41436ec74d3575b41be1", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 83, "avg_line_length": 20.322580645161292, "alnum_prop": 0.5968253968253968, "repo_name": "ahutchings/kohana-modules.com", "id": "d313f8436f9710984bebefe58518355ae283e8af", "size": "630", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/classes/Task/User/Create.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "23260" }, { "name": "JavaScript", "bytes": "31635" }, { "name": "PHP", "bytes": "89144" }, { "name": "Ruby", "bytes": "355" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "219271ef710a72acc182ab463a211f6d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "5a14667e757098ed6fd0647ad4ade776acc73ef1", "size": "200", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Liparis/Liparis decurrens/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<component name="libraryTable"> <library name="animated-vector-drawable-24.2.1"> <CLASSES> <root url="jar://$USER_HOME$/.android/build-cache/09496d3b02da3d256208efbd295ea9cba0bd509e/output/jars/classes.jar!/" /> <root url="file://$USER_HOME$/.android/build-cache/09496d3b02da3d256208efbd295ea9cba0bd509e/output/res" /> </CLASSES> <JAVADOC /> <SOURCES> <root url="jar://$USER_HOME$/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/animated-vector-drawable/24.2.1/animated-vector-drawable-24.2.1-sources.jar!/" /> </SOURCES> </library> </component>
{ "content_hash": "4897a2701c66a3771659177d2d82aa5f", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 190, "avg_line_length": 51.083333333333336, "alnum_prop": 0.7128874388254486, "repo_name": "xuan86883/coolweather", "id": "8c82dba7dc7dc898f6660a9ea0e3647445a7e3fe", "size": "613", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/libraries/animated_vector_drawable_24_2_1.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "31849" } ], "symlink_target": "" }
using System; namespace BizHawk.Emulation.Common { public interface ICoreFileProvider { /// <summary> /// Produces a path to the requested file, expected to be parallel to the running rom. for example: cue+bin files or sfc+pcm (MSU-1 games) /// </summary> [Obsolete] string PathSubfile(string fname); /// <summary> /// produces a path that contains emulation related dll and exe files /// </summary> /// <returns></returns> string DllPath(); /// <summary> /// produces a path that contains saveram... because libretro cores need it /// </summary> /// <returns></returns> string GetRetroSaveRAMDirectory(); /// <summary> /// produces a path for use as a libretro system path (different for each core) /// </summary> string GetRetroSystemPath(); string GetGameBasePath(); #region EmuLoadHelper api /// <summary> /// get path to a firmware /// </summary> /// <param name="sysID"></param> /// <param name="firmwareID"></param> /// <param name="required">if true, result is guaranteed to be valid; else null is possible if not foun</param> /// <param name="msg">message to show if fail to get</param> /// <returns></returns> [Obsolete] string GetFirmwarePath(string sysID, string firmwareID, bool required, string msg = null); /// <summary> /// get a firmware as a byte array /// </summary> /// <param name="sysID"></param> /// <param name="firmwareID"></param> /// <param name="required">if true, result is guaranteed to be valid; else null is possible if not found</param> /// <param name="msg">message to show if fail to get</param> /// <returns></returns> byte[] GetFirmware(string sysID, string firmwareID, bool required, string msg = null); byte[] GetFirmwareWithGameInfo(string sysID, string firmwareID, bool required, out GameInfo gi, string msg = null); #endregion } }
{ "content_hash": "e5f981982f7629ac54c340e15d6ebd3b", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 140, "avg_line_length": 30.704918032786885, "alnum_prop": 0.6732514682327816, "repo_name": "superusercode/RTC3", "id": "937db343387deeb2df7c6642007970b59cb26705", "size": "1875", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Real-Time Corruptor/BizHawk_RTC/BizHawk.Emulation.Common/Interfaces/ICoreFileProvider.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "273687" }, { "name": "Batchfile", "bytes": "18810" }, { "name": "C", "bytes": "26790735" }, { "name": "C#", "bytes": "13499009" }, { "name": "C++", "bytes": "14428468" }, { "name": "CMake", "bytes": "39873" }, { "name": "GLSL", "bytes": "6610" }, { "name": "HTML", "bytes": "420498" }, { "name": "Inno Setup", "bytes": "3199" }, { "name": "Java", "bytes": "13302" }, { "name": "Limbo", "bytes": "15313" }, { "name": "Lua", "bytes": "303246" }, { "name": "M4", "bytes": "836" }, { "name": "Makefile", "bytes": "147790" }, { "name": "NSIS", "bytes": "3447" }, { "name": "Objective-C", "bytes": "207179" }, { "name": "Perl", "bytes": "78" }, { "name": "Python", "bytes": "34858" }, { "name": "Roff", "bytes": "5448" }, { "name": "Shell", "bytes": "26787" }, { "name": "SourcePawn", "bytes": "7395" } ], "symlink_target": "" }
var webpack = require('webpack'); var FunctionModulePlugin = require('webpack/lib/FunctionModulePlugin'); var NodeTemplatePlugin = require('webpack/lib/node/NodeTemplatePlugin'); var TcpPolyfillPlugin = require('./TcpPolyfillPlugin'); var TlsStubPlugin = require('./TlsStubPlugin'); module.exports = function(isBrowser) { var config = { entry: ['./src/index'], output: { library: 'RethinkdbWebsocketClient', libraryTarget: 'umd', path: __dirname + '/../dist', filename: isBrowser ? 'index.js' : 'node.js' }, plugins: [], module: { loaders: [ //{ test: /\.js$/, loaders: ['babel', 'eslint'], exclude: /node_modules/ } { test: /\.js$/, loaders: ['babel', 'eslint'] } ] } }; if (!isBrowser) { config.plugins.push(new webpack.ProvidePlugin({WebSocket: 'ws'})); } // Very similar behavior to setting config.target to 'node', except it doesn't // set the 'net' or 'tls' modules as external. That way, we can use // TcpPolyfillPlugin and TlsStubPlugin to override those modules. // // For node.js target, we leave tls in externals because it's needed for ws. config.target = function(compiler) { var nodeNatives = Object.keys(process.binding('natives')); var mocks = ['net']; if (isBrowser) { mocks.push('tls'); } var externals = nodeNatives.filter(function(x) { return mocks.indexOf(x) < 0; }); compiler.apply( new NodeTemplatePlugin(config.output, false), new FunctionModulePlugin(config.output), new webpack.ExternalsPlugin('commonjs', externals), new webpack.LoaderTargetPlugin('node'), new TcpPolyfillPlugin(/node_modules\/rethinkdb/), new TlsStubPlugin(/node_modules\/rethinkdb/) ); }; return config; };
{ "content_hash": "d2512eb6b08393462b49d619fccd1d9f", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 82, "avg_line_length": 33.166666666666664, "alnum_prop": 0.6437744276940257, "repo_name": "babakness/rethinkdb-websocket-client", "id": "027022bcee8c41e4e81b0e102159bc750642ae06", "size": "1791", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webpack/base.config.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "853014" } ], "symlink_target": "" }
package gg.uhc.fancyfreeze.uhc; import gg.uhc.fancyfreeze.announcer.GlobalAnnouncer; public class UhcAnnouncer implements GlobalAnnouncer { protected final UhcModule module; public UhcAnnouncer(UhcModule module) { this.module = module; } @Override public void announceState() { module.announceState(); } }
{ "content_hash": "b16b45912028b8c41c8f760b32062bae", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 54, "avg_line_length": 18.57894736842105, "alnum_prop": 0.7025495750708215, "repo_name": "Eluinhost/FancyFreeze", "id": "f1a4d71839f1c6cfacd3ffce1b8a0102c32fcd61", "size": "1604", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugin/src/main/java/gg/uhc/fancyfreeze/uhc/UhcAnnouncer.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "138965" } ], "symlink_target": "" }
import inspect import itertools from collections import OrderedDict import six from decorator import decorator class ValidationFailure(object): def __init__(self, func, args): self.func = func self.__dict__.update(args) def __repr__(self): return u'ValidationFailure(func={func}, args={args})'.format( func=self.func.__name__, args=dict( [(k, v) for (k, v) in self.__dict__.items() if k != 'func'] ) ) def __str__(self): return repr(self) def __unicode__(self): return repr(self) def __bool__(self): return False def __nonzero__(self): return False def func_args_as_dict(func, args, kwargs): """ Return given function's positional and key value arguments as an ordered dictionary. """ arg_names = list( OrderedDict.fromkeys( itertools.chain( inspect.getargspec(func)[0], kwargs.keys() ) ) ) return OrderedDict( list(six.moves.zip(arg_names, args)) + list(kwargs.items()) ) def validator(func, *args, **kwargs): """ A decorator that makes given function validator. Whenever the given function is called and returns ``False`` value this decorator returns :class:`ValidationFailure` object. Example:: >>> @validator ... def even(value): ... return not (value % 2) >>> even(4) True >>> even(5) ValidationFailure(func=even, args={'value': 5}) :param func: function to decorate :param args: positional function arguments :param kwargs: key value function arguments """ def wrapper(func, *args, **kwargs): value = func(*args, **kwargs) if not value: return ValidationFailure( func, func_args_as_dict(func, args, kwargs) ) return True return decorator(wrapper, func)
{ "content_hash": "1f8556259808735b5a724a10126ef9ae", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 76, "avg_line_length": 23.86904761904762, "alnum_prop": 0.5600997506234414, "repo_name": "williamfeng323/py-web", "id": "6a892fcb0c4f5e3ca7fe30a752276ce381d6328e", "size": "2005", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "flask/lib/python3.6/site-packages/validators/utils.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "39957" }, { "name": "CSS", "bytes": "6270" }, { "name": "HTML", "bytes": "6046" }, { "name": "JavaScript", "bytes": "6264" }, { "name": "Mako", "bytes": "10018" }, { "name": "Python", "bytes": "15554131" }, { "name": "Shell", "bytes": "6007" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>eval documentation</title> <link rel="stylesheet" type="text/css" href="../../index.css" /> <link rel="stylesheet" type="text/css" href="../../highlight.css" /> <script type="text/javascript" src="../../index.js"></script> </head> <body class="property" id="component_74"> <div id="outer"> <div id="header"> <a class="ctype" href="../../index.html">property</a> <span> <a class="valtype" href="../../property/function/index.html">Function</a> <span class="valsep">|</span> </span> <span class="breadcrumbs"> <span class="delimiter">.</span><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval" class="breadcrumb property">eval</a> </span> </div> <div id="TOC"> </div> <div id="content"> <h1 class="signature"> eval ( ) { </h1> <!-- basic document info --> <div id="details"> <div class="clear"></div> </div> <div class="children"> </div> </div> </div> <div id="footer"> This document was generated with <a href="https://github.com/shenanigans/node-doczar">doczar</a> at <span class="time">3:55pm</span> on <span class="date">8/14/2015</span> </div> </body> </html>
{ "content_hash": "f40d6f6e78ad4f97a733e5aa0b55b398", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 180, "avg_line_length": 32.208333333333336, "alnum_prop": 0.48771021992238034, "repo_name": "shenanigans/node-sublayer", "id": "0b22839e84a5716a878f85b79fe58086d1b11613", "size": "1546", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "static/docs/generated/property/eval/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "19097" }, { "name": "HTML", "bytes": "7637111" }, { "name": "JavaScript", "bytes": "2783424" } ], "symlink_target": "" }
{% extends "xblog/blog_base.html" %} {% block maincontent %} <form action="" method="post">{% csrf_token %} <button type="submit">Save</button> </form> {% endblock %}
{ "content_hash": "b04f11482951afefef9f52440da6ea38", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 46, "avg_line_length": 22.125, "alnum_prop": 0.6045197740112994, "repo_name": "rubeon/django-xblog", "id": "a6d7d2442ec3977dfad1a57ea3fc36c5f8767cd0", "size": "177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xblog/templates/xblog/author_form.html", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "73797" }, { "name": "HTML", "bytes": "11830" }, { "name": "JavaScript", "bytes": "498" }, { "name": "Python", "bytes": "242211" } ], "symlink_target": "" }
package org.vaadin.grid.enhancements.client.cellrenderers.combobox.common; import com.google.gwt.user.cellview.client.CellList; public interface CellListResources extends CellList.Resources { // @Source("cellList.css") CellList.Style cellListStyle(); }
{ "content_hash": "6e12fdd8e02e45714e0dd35f633c1da9", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 74, "avg_line_length": 28.555555555555557, "alnum_prop": 0.8093385214007782, "repo_name": "bonprix/vaadin-grid-enhancements", "id": "3c4d2fd12908b7447d0b0ee363faef74293cdcfe", "size": "257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GridEnhancements/src/main/java/org/vaadin/grid/enhancements/client/cellrenderers/combobox/common/CellListResources.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11156" }, { "name": "Java", "bytes": "191037" } ], "symlink_target": "" }
@interface IDEWorkspaceSharedSettings : IDEWorkspaceSettings { } @property BOOL autocreateContextsIfNeeded; - (id)settingsOwnership; @end
{ "content_hash": "7aeddb19eab4e9f52236e532c22589d7", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 60, "avg_line_length": 15.666666666666666, "alnum_prop": 0.8156028368794326, "repo_name": "wczekalski/Distraction-Free-Xcode-plugin", "id": "b6718a90bc616d66ae3be53b0cb1938696001dc1", "size": "328", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Archived/v1/WCDistractionFreeXcodePlugin/Headers/Frameworks/IDEFoundation/IDEWorkspaceSharedSettings.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "81011" }, { "name": "C++", "bytes": "588495" }, { "name": "DTrace", "bytes": "1835" }, { "name": "Objective-C", "bytes": "10151940" }, { "name": "Ruby", "bytes": "1105" } ], "symlink_target": "" }
define([ 'dojo/_base/declare', 'dijit/_WidgetsInTemplateMixin', 'dojo/text!/static/sqleditor/widgets/templates/fileManagerDialog.html', 'dijit/form/ValidationTextBox', 'dijit/form/DropDownButton' ], function (declare, _WidgetsInTemplateMixin, fileManagerDialogMarkup) { return declare(_WidgetsInTemplateMixin, { templateString: fileManagerDialogMarkup, parseOnLoad: true }); });
{ "content_hash": "91d0b34fd1d359e5abc796ebf8b13d4f", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 75, "avg_line_length": 28.4, "alnum_prop": 0.7136150234741784, "repo_name": "accessrichard/sqleditor", "id": "0f70186248465830fcb346b558ebf361022bb7a6", "size": "426", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "static/sqleditor/widgets/_FileDialogMixin.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2259" }, { "name": "JavaScript", "bytes": "106928" }, { "name": "Python", "bytes": "54054" } ], "symlink_target": "" }
<?php /** * CFmpActiveFinder implements eager loading and lazy loading of related active records. * * When used in eager loading, this class provides the same set of find methods as * {@link CActiveRecord}. * * Overwrite default CActiveFinder * * * @author Romain Dunand <romain_pro@dunand.m> * @package extensions.yiifmpdb * @since 1.1.14 */ class CFmpActiveFinder extends CComponent { /** * @var boolean join all tables all at once. Defaults to false. * This property is internally used. */ public $joinAll=false; /** * @var boolean whether the base model has limit or offset. * This property is internally used. */ public $baseLimited=false; private $_joinCount=0; private $_joinTree; private $_builder; /** * Constructor. * A join tree is built up based on the declared relationships between active record classes. * @param CActiveRecord $model the model that initiates the active finding process * @param mixed $with the relation names to be actively looked for */ public function __construct($model,$with) { $this->_builder=$model->getCommandBuilder(); $this->_joinTree=new CFmpJoinElement($this,$model); $this->buildJoinTree($this->_joinTree,$with); } /** * Do not call this method. This method is used internally to perform the relational query * based on the given DB criteria. * @param CDbCriteria $criteria the DB criteria * @param boolean $all whether to bring back all records * @return mixed the query result */ public function query($criteria,$all=false) { $this->joinAll=$criteria->together===true; if($criteria->alias!='') { $this->_joinTree->tableAlias=$criteria->alias; $this->_joinTree->rawTableAlias=$this->_builder->getSchema()->quoteTableName($criteria->alias); } $this->_joinTree->find($criteria); $this->_joinTree->afterFind(); if($all) { $result = array_values($this->_joinTree->records); if ($criteria->index!==null) { $index=$criteria->index; $array=array(); foreach($result as $object) $array[$object->$index]=$object; $result=$array; } } elseif(count($this->_joinTree->records)) $result = reset($this->_joinTree->records); else $result = null; $this->destroyJoinTree(); return $result; } /** * This method is internally called. * @param string $sql the SQL statement * @param array $params parameters to be bound to the SQL statement * @return CActiveRecord */ public function findBySql($sql,$params=array()) { Yii::trace(get_class($this->_joinTree->model).'.findBySql() eagerly','system.db.ar.CActiveRecord'); if(($row=$this->_builder->createSqlCommand($sql,$params)->queryRow())!==false) { $baseRecord=$this->_joinTree->model->populateRecord($row,false); $this->_joinTree->findWithBase($baseRecord); $this->_joinTree->afterFind(); $this->destroyJoinTree(); return $baseRecord; } else $this->destroyJoinTree(); } /** * This method is internally called. * @param string $sql the SQL statement * @param array $params parameters to be bound to the SQL statement * @return CActiveRecord[] */ public function findAllBySql($sql,$params=array()) { Yii::trace(get_class($this->_joinTree->model).'.findAllBySql() eagerly','system.db.ar.CActiveRecord'); if(($rows=$this->_builder->createSqlCommand($sql,$params)->queryAll())!==array()) { $baseRecords=$this->_joinTree->model->populateRecords($rows,false); $this->_joinTree->findWithBase($baseRecords); $this->_joinTree->afterFind(); $this->destroyJoinTree(); return $baseRecords; } else { $this->destroyJoinTree(); return array(); } } /** * This method is internally called. * @param CDbCriteria $criteria the query criteria * @return string */ public function count($criteria) { Yii::trace(get_class($this->_joinTree->model).'.count() eagerly','system.db.ar.CActiveRecord'); $this->joinAll=$criteria->together!==true; $alias=$criteria->alias===null ? 't' : $criteria->alias; $this->_joinTree->tableAlias=$alias; $this->_joinTree->rawTableAlias=$this->_builder->getSchema()->quoteTableName($alias); $n=$this->_joinTree->count($criteria); $this->destroyJoinTree(); return $n; } /** * Finds the related objects for the specified active record. * This method is internally invoked by {@link CActiveRecord} to support lazy loading. * @param CActiveRecord $baseRecord the base record whose related objects are to be loaded */ public function lazyFind($baseRecord) { $this->_joinTree->lazyFind($baseRecord); if(!empty($this->_joinTree->children)) { foreach($this->_joinTree->children as $child) $child->afterFind(); } $this->destroyJoinTree(); } /** * Given active record class name returns new model instance. * * @param string $className active record class name * @return CActiveRecord active record model instance * * @since 1.1.14 */ public function getModel($className) { return CActiveRecord::model($className); } private function destroyJoinTree() { if($this->_joinTree!==null) $this->_joinTree->destroy(); $this->_joinTree=null; } /** * Builds up the join tree representing the relationships involved in this query. * @param CFmpJoinElement $parent the parent tree node * @param mixed $with the names of the related objects relative to the parent tree node * @param array $options additional query options to be merged with the relation * @throws CDbException if given parent tree node is an instance of {@link CFmpStatElement} * or relation is not defined in the given parent's tree node model class */ private function buildJoinTree($parent,$with,$options=null) { if($parent instanceof CFmpStatElement) throw new CDbException(Yii::t('yii','The STAT relation "{name}" cannot have child relations.', array('{name}'=>$parent->relation->name))); if(is_string($with)) { if(($pos=strrpos($with,'.'))!==false) { $parent=$this->buildJoinTree($parent,substr($with,0,$pos)); $with=substr($with,$pos+1); } // named scope $scopes=array(); if(($pos=strpos($with,':'))!==false) { $scopes=explode(':',substr($with,$pos+1)); $with=substr($with,0,$pos); } if(isset($parent->children[$with]) && $parent->children[$with]->master===null) return $parent->children[$with]; if(($relation=$parent->model->getActiveRelation($with))===null) throw new CDbException(Yii::t('yii','Relation "{name}" is not defined in active record class "{class}".', array('{class}'=>get_class($parent->model), '{name}'=>$with))); $relation=clone $relation; $model=$this->getModel($relation->className); if($relation instanceof CActiveRelation) { $oldAlias=$model->getTableAlias(false,false); if(isset($options['alias'])) $model->setTableAlias($options['alias']); elseif($relation->alias===null) $model->setTableAlias($relation->name); else $model->setTableAlias($relation->alias); } if(!empty($relation->scopes)) $scopes=array_merge($scopes,(array)$relation->scopes); // no need for complex merging if(!empty($options['scopes'])) $scopes=array_merge($scopes,(array)$options['scopes']); // no need for complex merging $model->resetScope(false); $criteria=$model->getDbCriteria(); $criteria->scopes=$scopes; $model->beforeFindInternal(); $model->applyScopes($criteria); // select has a special meaning in stat relation, so we need to ignore select from scope or model criteria if($relation instanceof CStatRelation) $criteria->select='*'; $relation->mergeWith($criteria,true); // dynamic options if($options!==null) $relation->mergeWith($options); if($relation instanceof CActiveRelation) $model->setTableAlias($oldAlias); if($relation instanceof CStatRelation) return new CFmpStatElement($this,$relation,$parent); else { if(isset($parent->children[$with])) { $element=$parent->children[$with]; $element->relation=$relation; } else $element=new CFmpJoinElement($this,$relation,$parent,++$this->_joinCount); if(!empty($relation->through)) { $slave=$this->buildJoinTree($parent,$relation->through,array('select'=>'')); $slave->master=$element; $element->slave=$slave; } $parent->children[$with]=$element; if(!empty($relation->with)) $this->buildJoinTree($element,$relation->with); return $element; } } // $with is an array, keys are relation name, values are relation spec foreach($with as $key=>$value) { if(is_string($value)) // the value is a relation name $this->buildJoinTree($parent,$value); elseif(is_string($key) && is_array($value)) $this->buildJoinTree($parent,$key,$value); } } } /** * CFmpJoinElement represents a tree node in the join tree created by {@link CFmpActiveFinder}. * * @author Qiang Xue <qiang.xue@gmail.com> * @package system.db.ar * @since 1.0 */ class CFmpJoinElement { /** * @var integer the unique ID of this tree node */ public $id; /** * @var CActiveRelation the relation represented by this tree node */ public $relation; /** * @var CActiveRelation the master relation */ public $master; /** * @var CActiveRelation the slave relation */ public $slave; /** * @var CActiveRecord the model associated with this tree node */ public $model; /** * @var array list of active records found by the queries. They are indexed by primary key values. */ public $records=array(); /** * @var array list of child join elements */ public $children=array(); /** * @var array list of stat elements */ public $stats=array(); /** * @var string table alias for this join element */ public $tableAlias; /** * @var string the quoted table alias for this element */ public $rawTableAlias; private $_finder; private $_builder; private $_parent; private $_pkAlias; // string or name=>alias private $_columnAliases=array(); // name=>alias private $_joined=false; private $_table; private $_related=array(); // PK, relation name, related PK => true /** * Constructor. * @param CFmpActiveFinder $finder the finder * @param mixed $relation the relation (if the third parameter is not null) * or the model (if the third parameter is null) associated with this tree node. * @param CFmpJoinElement $parent the parent tree node * @param integer $id the ID of this tree node that is unique among all the tree nodes */ public function __construct($finder,$relation,$parent=null,$id=0) { $this->_finder=$finder; $this->id=$id; if($parent!==null) { $this->relation=$relation; $this->_parent=$parent; $this->model=$this->_finder->getModel($relation->className); $this->_builder=$this->model->getCommandBuilder(); $this->tableAlias=$relation->alias===null?$relation->name:$relation->alias; $this->rawTableAlias=$this->_builder->getSchema()->quoteTableName($this->tableAlias); $this->_table=$this->model->getTableSchema(); } else // root element, the first parameter is the model. { $this->model=$relation; $this->_builder=$relation->getCommandBuilder(); $this->_table=$relation->getTableSchema(); $this->tableAlias=$this->model->getTableAlias(); $this->rawTableAlias=$this->_builder->getSchema()->quoteTableName($this->tableAlias); } // set up column aliases, such as t1_c2 $table=$this->_table; if($this->model->getDbConnection()->getDriverName()==='oci') // Issue 482 $prefix='T'.$id.'_C'; else $prefix='t'.$id.'_c'; foreach($table->getColumnNames() as $key=>$name) { $alias=$prefix.$key; $this->_columnAliases[$name]=$alias; if($table->primaryKey===$name) $this->_pkAlias=$alias; elseif(is_array($table->primaryKey) && in_array($name,$table->primaryKey)) $this->_pkAlias[$name]=$alias; } } /** * Removes references to child elements and finder to avoid circular references. * This is internally used. */ public function destroy() { if(!empty($this->children)) { foreach($this->children as $child) $child->destroy(); } unset($this->_finder, $this->_parent, $this->model, $this->relation, $this->master, $this->slave, $this->records, $this->children, $this->stats); } /** * Performs the recursive finding with the criteria. * @param CDbCriteria $criteria the query criteria */ public function find($criteria=null) { if($this->_parent===null) // root element { $query=new CFmpJoinQuery($this,$criteria); $this->_finder->baseLimited=($criteria->offset>=0 || $criteria->limit>=0); $this->buildQuery($query); $this->_finder->baseLimited=false; $this->runQuery($query); } elseif(!$this->_joined && !empty($this->_parent->records)) // not joined before { $query=new CFmpJoinQuery($this->_parent); $this->_joined=true; $query->join($this); $this->buildQuery($query); $this->_parent->runQuery($query); } foreach($this->children as $child) // find recursively $child->find(); foreach($this->stats as $stat) $stat->query(); } /** * Performs lazy find with the specified base record. * @param CActiveRecord $baseRecord the active record whose related object is to be fetched. */ public function lazyFind($baseRecord) { if(is_string($this->_table->primaryKey)) $this->records[$baseRecord->{$this->_table->primaryKey}]=$baseRecord; else { $pk=array(); foreach($this->_table->primaryKey as $name) $pk[$name]=$baseRecord->$name; $this->records[serialize($pk)]=$baseRecord; } foreach($this->stats as $stat) $stat->query(); if(!$this->children) return; $params=array(); foreach($this->children as $child) if(is_array($child->relation->params)) $params=array_merge($params,$child->relation->params); $query=new CFmpJoinQuery($child); $query->selects=array($child->getColumnSelect($child->relation->select)); $query->conditions=array( $child->relation->condition, $child->relation->on, ); $query->groups[]=$child->relation->group; $query->joins[]=$child->relation->join; $query->havings[]=$child->relation->having; $query->orders[]=$child->relation->order; $query->params=$params; $query->elements[$child->id]=true; if($child->relation instanceof CHasManyRelation) { $query->limit=$child->relation->limit; $query->offset=$child->relation->offset; } $child->applyLazyCondition($query,$baseRecord); $this->_joined=true; $child->_joined=true; $this->_finder->baseLimited=false; $child->buildQuery($query); $child->runQuery($query); foreach($child->children as $c) $c->find(); if(empty($child->records)) return; if($child->relation instanceof CHasOneRelation || $child->relation instanceof CBelongsToRelation) $baseRecord->addRelatedRecord($child->relation->name,reset($child->records),false); else // has_many and many_many { foreach($child->records as $record) { if($child->relation->index!==null) $index=$record->{$child->relation->index}; else $index=true; $baseRecord->addRelatedRecord($child->relation->name,$record,$index); } } } /** * Apply Lazy Condition * @param CFmpJoinQuery $query represents a JOIN SQL statements * @param CActiveRecord $record the active record whose related object is to be fetched. * @throws CDbException if relation in active record class is not specified correctly */ private function applyLazyCondition($query,$record) { $schema=$this->_builder->getSchema(); $parent=$this->_parent; if($this->relation instanceof CManyManyRelation) { $joinTableName=$this->relation->getJunctionTableName(); if(($joinTable=$schema->getTable($joinTableName))===null) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is not specified correctly: the join table "{joinTable}" given in the foreign key cannot be found in the database.', array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name, '{joinTable}'=>$joinTableName))); $fks=$this->relation->getJunctionForeignKeys(); $joinAlias=$schema->quoteTableName($this->relation->name.'_'.$this->tableAlias); $parentCondition=array(); $childCondition=array(); $count=0; $params=array(); $fkDefined=true; foreach($fks as $i=>$fk) { if(isset($joinTable->foreignKeys[$fk])) // FK defined { list($tableName,$pk)=$joinTable->foreignKeys[$fk]; if(!isset($parentCondition[$pk]) && $schema->compareTableNames($parent->_table->rawName,$tableName)) { $val = $joinTable->getColumn($fk)->typecast($record->$pk); $parentCondition[$pk]=$joinAlias.'.'.$schema->quoteColumnName($fk).'='.$val; //$params[':ypl'.$count]=$record->$pk; $count++; } elseif(!isset($childCondition[$pk]) && $schema->compareTableNames($this->_table->rawName,$tableName)) $childCondition[$pk]=$this->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk); else { $fkDefined=false; break; } } else { $fkDefined=false; break; } } if(!$fkDefined) { $parentCondition=array(); $childCondition=array(); $count=0; $params=array(); foreach($fks as $i=>$fk) { if($i<count($parent->_table->primaryKey)) { $pk=is_array($parent->_table->primaryKey) ? $parent->_table->primaryKey[$i] : $parent->_table->primaryKey; $val = $parent->_table->getColumn($pk)->typecast($record->$pk); $parentCondition[$pk]=$joinAlias.'.'.$schema->quoteColumnName($fk).'='.$val; //$params[':ypl'.$count]=$record->$pk; $count++; } else { $j=$i-count($parent->_table->primaryKey); $pk=is_array($this->_table->primaryKey) ? $this->_table->primaryKey[$j] : $this->_table->primaryKey; $childCondition[$pk]=$this->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk); } } } if($parentCondition!==array() && $childCondition!==array()) { $join='INNER JOIN '.$joinTable->rawName.' '.$joinAlias.' ON '; $join.='('.implode(') AND (',$parentCondition).') AND ('.implode(') AND (',$childCondition).')'; if(!empty($this->relation->on)) $join.=' AND ('.$this->relation->on.')'; $query->joins[]=$join; foreach($params as $name=>$value) $query->params[$name]=$value; } else throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an incomplete foreign key. The foreign key must consist of columns referencing both joining tables.', array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name))); } else { $element=$this; while(true) { $condition=$element->relation->condition; if(!empty($condition)) $query->conditions[]=$condition; $query->params=array_merge($query->params,$element->relation->params); if($element->slave!==null) { $query->joins[]=$element->slave->joinOneMany($element->slave,$element->relation->foreignKey,$element,$parent); $element=$element->slave; } else break; } $fks=is_array($element->relation->foreignKey) ? $element->relation->foreignKey : preg_split('/\s*,\s*/',$element->relation->foreignKey,-1,PREG_SPLIT_NO_EMPTY); $prefix=$element->getColumnPrefix(); $params=array(); foreach($fks as $i=>$fk) { if(!is_int($i)) { $pk=$fk; $fk=$i; } if($element->relation instanceof CBelongsToRelation) { if(is_int($i)) { if(isset($parent->_table->foreignKeys[$fk])) // FK defined $pk=$parent->_table->foreignKeys[$fk][1]; elseif(is_array($element->_table->primaryKey)) // composite PK $pk=$element->_table->primaryKey[$i]; else $pk=$element->_table->primaryKey; } $params[$pk]=$record->$fk; } else { if(is_int($i)) { if(isset($element->_table->foreignKeys[$fk])) // FK defined $pk=$element->_table->foreignKeys[$fk][1]; elseif(is_array($parent->_table->primaryKey)) // composite PK $pk=$parent->_table->primaryKey[$i]; else $pk=$parent->_table->primaryKey; } $params[$fk]=$record->$pk; } } $count=0; foreach($params as $name=>$value) { $value = $element->_table->getColumn($name)->typecast($value); $query->conditions[]=$prefix.$schema->quoteColumnName($name).'='.$value; /*$test = $element->_table->columns->$pk; $query->params[':ypl'.$count]=$value;*/ $count++; } } } /** * Performs the eager loading with the base records ready. * @param mixed $baseRecords the available base record(s). */ public function findWithBase($baseRecords) { if(!is_array($baseRecords)) $baseRecords=array($baseRecords); if(is_string($this->_table->primaryKey)) { foreach($baseRecords as $baseRecord) $this->records[$baseRecord->{$this->_table->primaryKey}]=$baseRecord; } else { foreach($baseRecords as $baseRecord) { $pk=array(); foreach($this->_table->primaryKey as $name) $pk[$name]=$baseRecord->$name; $this->records[serialize($pk)]=$baseRecord; } } $query=new CFmpJoinQuery($this); $this->buildQuery($query); if(count($query->joins)>1) $this->runQuery($query); foreach($this->children as $child) $child->find(); foreach($this->stats as $stat) $stat->query(); } /** * Count the number of primary records returned by the join statement. * @param CDbCriteria $criteria the query criteria * @return string number of primary records. Note: type is string to keep max. precision. */ public function count($criteria=null) { $query=new CFmpJoinQuery($this,$criteria); // ensure only one big join statement is used $this->_finder->baseLimited=false; $this->_finder->joinAll=true; $this->buildQuery($query); $query->limit=$query->offset=-1; if(!empty($criteria->group) || !empty($criteria->having)) { $query->orders = array(); $command=$query->createCommand($this->_builder); $sql=$command->getText(); $sql="SELECT COUNT(*) FROM ({$sql}) sq"; $command->setText($sql); $command->params=$query->params; return $command->queryScalar(); } else { $select=is_array($criteria->select) ? implode(',',$criteria->select) : $criteria->select; if($select!=='*' && !strncasecmp($select,'count',5)) $query->selects=array($select); elseif(is_string($this->_table->primaryKey)) { $prefix=$this->getColumnPrefix(); $schema=$this->_builder->getSchema(); $column=$prefix.$schema->quoteColumnName($this->_table->primaryKey); $query->selects=array("COUNT(DISTINCT $column)"); } else $query->selects=array("COUNT(*)"); $query->orders=$query->groups=$query->havings=array(); $command=$query->createCommand($this->_builder); return $command->queryScalar(); } } /** * Calls {@link CActiveRecord::afterFind} of all the records. */ public function afterFind() { foreach($this->records as $record) $record->afterFindInternal(); foreach($this->children as $child) $child->afterFind(); $this->children = null; } /** * Builds the join query with all descendant HAS_ONE and BELONGS_TO nodes. * @param CFmpJoinQuery $query the query being built up */ public function buildQuery($query) { foreach($this->children as $child) { if($child->master!==null) $child->_joined=true; elseif($child->relation instanceof CHasOneRelation || $child->relation instanceof CBelongsToRelation || $this->_finder->joinAll || $child->relation->together || (!$this->_finder->baseLimited && $child->relation->together===null)) { $child->_joined=true; $query->join($child); $child->buildQuery($query); } } } /** * Executes the join query and populates the query results. * @param CFmpJoinQuery $query the query to be executed. */ public function runQuery($query) { $command=$query->createCommand($this->_builder); foreach($command->queryAll() as $row) $this->populateRecord($query,$row); } /** * Populates the active records with the query data. * @param CFmpJoinQuery $query the query executed * @param array $row a row of data * @return CActiveRecord the populated record */ private function populateRecord($query,$row) { // determine the primary key value if(is_string($this->_pkAlias)) // single key { if(isset($row[$this->_pkAlias])) $pk=$row[$this->_pkAlias]; else // no matching related objects return null; } else // is_array, composite key { $pk=array(); foreach($this->_pkAlias as $name=>$alias) { if(isset($row[$alias])) $pk[$name]=$row[$alias]; else // no matching related objects return null; } $pk=serialize($pk); } // retrieve or populate the record according to the primary key value if(isset($this->records[$pk])) $record=$this->records[$pk]; else { $attributes=array(); $aliases=array_flip($this->_columnAliases); foreach($row as $alias=>$value) { if(isset($aliases[$alias])) $attributes[$aliases[$alias]]=$value; } $record=$this->model->populateRecord($attributes,false); foreach($this->children as $child) { if(!empty($child->relation->select)) $record->addRelatedRecord($child->relation->name,null,$child->relation instanceof CHasManyRelation); } $this->records[$pk]=$record; } // populate child records recursively foreach($this->children as $child) { if(!isset($query->elements[$child->id]) || empty($child->relation->select)) continue; $childRecord=$child->populateRecord($query,$row); if($child->relation instanceof CHasOneRelation || $child->relation instanceof CBelongsToRelation) $record->addRelatedRecord($child->relation->name,$childRecord,false); else // has_many and many_many { // need to double check to avoid adding duplicated related objects if($childRecord instanceof CActiveRecord) $fpk=serialize($childRecord->getPrimaryKey()); else $fpk=0; if(!isset($this->_related[$pk][$child->relation->name][$fpk])) { if($childRecord instanceof CActiveRecord && $child->relation->index!==null) $index=$childRecord->{$child->relation->index}; else $index=true; $record->addRelatedRecord($child->relation->name,$childRecord,$index); $this->_related[$pk][$child->relation->name][$fpk]=true; } } } return $record; } /** * @return string the table name and the table alias (if any). This can be used directly in SQL query without escaping. */ public function getTableNameWithAlias() { if($this->tableAlias!==null) return $this->_table->rawName . ' ' . $this->rawTableAlias; else return $this->_table->rawName; } /** * Generates the list of columns to be selected. * Columns will be properly aliased and primary keys will be added to selection if they are not specified. * @param mixed $select columns to be selected. Defaults to '*', indicating all columns. * @throws CDbException if active record class is trying to select an invalid column * @return string the column selection */ public function getColumnSelect($select='*') { $schema=$this->_builder->getSchema(); $prefix=$this->getColumnPrefix(); $columns=array(); if($select==='*') { foreach($this->_table->getColumnNames() as $name) $columns[]=$prefix.$schema->quoteColumnName($name).' AS '.$schema->quoteColumnName($this->_columnAliases[$name]); } else { if(is_string($select)) $select=explode(',',$select); $selected=array(); foreach($select as $name) { $name=trim($name); $matches=array(); if(($pos=strrpos($name,'.'))!==false) $key=substr($name,$pos+1); else $key=$name; $key=trim($key,'\'"`'); if($key==='*') { foreach($this->_table->columns as $name=>$column) { $alias=$this->_columnAliases[$name]; if(!isset($selected[$alias])) { $columns[]=$prefix.$column->rawName.' AS '.$schema->quoteColumnName($alias); $selected[$alias]=1; } } continue; } if(isset($this->_columnAliases[$key])) // simple column names { $columns[]=$prefix.$schema->quoteColumnName($key).' AS '.$schema->quoteColumnName($this->_columnAliases[$key]); $selected[$this->_columnAliases[$key]]=1; } elseif(preg_match('/^(.*?)\s+AS\s+(\w+)$/im',$name,$matches)) // if the column is already aliased { $alias=$matches[2]; if(!isset($this->_columnAliases[$alias]) || $this->_columnAliases[$alias]!==$alias) { $this->_columnAliases[$alias]=$alias; $columns[]=$name; $selected[$alias]=1; } } else throw new CDbException(Yii::t('yii','Active record "{class}" is trying to select an invalid column "{column}". Note, the column must exist in the table or be an expression with alias.', array('{class}'=>get_class($this->model), '{column}'=>$name))); } // add primary key selection if they are not selected if(is_string($this->_pkAlias) && !isset($selected[$this->_pkAlias])) $columns[]=$prefix.$schema->quoteColumnName($this->_table->primaryKey).' AS '.$schema->quoteColumnName($this->_pkAlias); elseif(is_array($this->_pkAlias)) { foreach($this->_table->primaryKey as $name) if(!isset($selected[$name])) $columns[]=$prefix.$schema->quoteColumnName($name).' AS '.$schema->quoteColumnName($this->_pkAlias[$name]); } } return implode(', ',$columns); } /** * @return string the primary key selection */ public function getPrimaryKeySelect() { $schema=$this->_builder->getSchema(); $prefix=$this->getColumnPrefix(); $columns=array(); if(is_string($this->_pkAlias)) $columns[]=$prefix.$schema->quoteColumnName($this->_table->primaryKey).' AS '.$schema->quoteColumnName($this->_pkAlias); elseif(is_array($this->_pkAlias)) { foreach($this->_pkAlias as $name=>$alias) $columns[]=$prefix.$schema->quoteColumnName($name).' AS '.$schema->quoteColumnName($alias); } return implode(', ',$columns); } /** * @return string the condition that specifies only the rows with the selected primary key values. */ public function getPrimaryKeyRange() { if(empty($this->records)) return ''; $values=array_keys($this->records); if(is_array($this->_table->primaryKey)) { foreach($values as &$value) $value=unserialize($value); } return $this->_builder->createInCondition($this->_table,$this->_table->primaryKey,$values,$this->getColumnPrefix()); } /** * @return string the column prefix for column reference disambiguation */ public function getColumnPrefix() { if($this->tableAlias!==null) return $this->rawTableAlias.'.'; else return $this->_table->rawName.'.'; } /** * @throws CDbException if relation in active record class is not specified correctly * @return string the join statement (this node joins with its parent) */ public function getJoinCondition() { $parent=$this->_parent; if($this->relation instanceof CManyManyRelation) { $schema=$this->_builder->getSchema(); $joinTableName=$this->relation->getJunctionTableName(); if(($joinTable=$schema->getTable($joinTableName))===null) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is not specified correctly: the join table "{joinTable}" given in the foreign key cannot be found in the database.', array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name, '{joinTable}'=>$joinTableName))); $fks=$this->relation->getJunctionForeignKeys(); return $this->joinManyMany($joinTable,$fks,$parent); } else { $fks=is_array($this->relation->foreignKey) ? $this->relation->foreignKey : preg_split('/\s*,\s*/',$this->relation->foreignKey,-1,PREG_SPLIT_NO_EMPTY); if($this->slave!==null) { if($this->relation instanceof CBelongsToRelation) { $fks=array_flip($fks); $pke=$this->slave; $fke=$this; } else { $pke=$this; $fke=$this->slave; } } elseif($this->relation instanceof CBelongsToRelation) { $pke=$this; $fke=$parent; } else { $pke=$parent; $fke=$this; } return $this->joinOneMany($fke,$fks,$pke,$parent); } } /** * Generates the join statement for one-many relationship. * This works for HAS_ONE, HAS_MANY and BELONGS_TO. * @param CFmpJoinElement $fke the join element containing foreign keys * @param array $fks the foreign keys * @param CFmpJoinElement $pke the join element contains primary keys * @param CFmpJoinElement $parent the parent join element * @return string the join statement * @throws CDbException if a foreign key is invalid */ private function joinOneMany($fke,$fks,$pke,$parent) { $schema=$this->_builder->getSchema(); $joins=array(); if(is_string($fks)) $fks=preg_split('/\s*,\s*/',$fks,-1,PREG_SPLIT_NO_EMPTY); foreach($fks as $i=>$fk) { if(!is_int($i)) { $pk=$fk; $fk=$i; } if(!isset($fke->_table->columns[$fk])) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key "{key}". There is no such column in the table "{table}".', array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name, '{key}'=>$fk, '{table}'=>$fke->_table->name))); if(is_int($i)) { if(isset($fke->_table->foreignKeys[$fk]) && $schema->compareTableNames($pke->_table->rawName, $fke->_table->foreignKeys[$fk][0])) $pk=$fke->_table->foreignKeys[$fk][1]; else // FK constraints undefined { if(is_array($pke->_table->primaryKey)) // composite PK $pk=$pke->_table->primaryKey[$i]; else $pk=$pke->_table->primaryKey; } } $joins[]=$fke->getColumnPrefix().$schema->quoteColumnName($fk) . '=' . $pke->getColumnPrefix().$schema->quoteColumnName($pk); } if(!empty($this->relation->on)) $joins[]=$this->relation->on; return $this->relation->joinType . ' ' . $this->getTableNameWithAlias() . ' ON (' . implode(') AND (',$joins).')'; } /** * Generates the join statement for many-many relationship. * @param CDbTableSchema $joinTable the join table * @param array $fks the foreign keys * @param CFmpJoinElement $parent the parent join element * @return string the join statement * @throws CDbException if a foreign key is invalid */ private function joinManyMany($joinTable,$fks,$parent) { $schema=$this->_builder->getSchema(); $joinAlias=$schema->quoteTableName($this->relation->name.'_'.$this->tableAlias); $parentCondition=array(); $childCondition=array(); $fkDefined=true; foreach($fks as $i=>$fk) { if(!isset($joinTable->columns[$fk])) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key "{key}". There is no such column in the table "{table}".', array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name, '{key}'=>$fk, '{table}'=>$joinTable->name))); if(isset($joinTable->foreignKeys[$fk])) { list($tableName,$pk)=$joinTable->foreignKeys[$fk]; if(!isset($parentCondition[$pk]) && $schema->compareTableNames($parent->_table->rawName,$tableName)) $parentCondition[$pk]=$parent->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk); elseif(!isset($childCondition[$pk]) && $schema->compareTableNames($this->_table->rawName,$tableName)) $childCondition[$pk]=$this->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk); else { $fkDefined=false; break; } } else { $fkDefined=false; break; } } if(!$fkDefined) { $parentCondition=array(); $childCondition=array(); foreach($fks as $i=>$fk) { if($i<count($parent->_table->primaryKey)) { $pk=is_array($parent->_table->primaryKey) ? $parent->_table->primaryKey[$i] : $parent->_table->primaryKey; $parentCondition[$pk]=$parent->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk); } else { $j=$i-count($parent->_table->primaryKey); $pk=is_array($this->_table->primaryKey) ? $this->_table->primaryKey[$j] : $this->_table->primaryKey; $childCondition[$pk]=$this->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk); } } } if($parentCondition!==array() && $childCondition!==array()) { $join=$this->relation->joinType.' '.$joinTable->rawName.' '.$joinAlias; $join.=' ON ('.implode(') AND (',$parentCondition).')'; $join.=' '.$this->relation->joinType.' '.$this->getTableNameWithAlias(); $join.=' ON ('.implode(') AND (',$childCondition).')'; if(!empty($this->relation->on)) $join.=' AND ('.$this->relation->on.')'; return $join; } else throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an incomplete foreign key. The foreign key must consist of columns referencing both joining tables.', array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name))); } } /** * CFmpJoinQuery represents a JOIN SQL statement. * * @author Qiang Xue <qiang.xue@gmail.com> * @package system.db.ar * @since 1.0 */ class CFmpJoinQuery { /** * @var array list of column selections */ public $selects=array(); /** * @var boolean whether to select distinct result set */ public $distinct=false; /** * @var array list of join statement */ public $joins=array(); /** * @var array list of WHERE clauses */ public $conditions=array(); /** * @var array list of ORDER BY clauses */ public $orders=array(); /** * @var array list of GROUP BY clauses */ public $groups=array(); /** * @var array list of HAVING clauses */ public $havings=array(); /** * @var integer row limit */ public $limit=-1; /** * @var integer row offset */ public $offset=-1; /** * @var array list of query parameters */ public $params=array(); /** * @var array list of join element IDs (id=>true) */ public $elements=array(); /** * Constructor. * @param CFmpJoinElement $joinElement The root join tree. * @param CDbCriteria $criteria the query criteria */ public function __construct($joinElement,$criteria=null) { if($criteria!==null) { $this->selects[]=$joinElement->getColumnSelect($criteria->select); $this->joins[]=$joinElement->getTableNameWithAlias(); $this->joins[]=$criteria->join; $this->conditions[]=$criteria->condition; $this->orders[]=$criteria->order; $this->groups[]=$criteria->group; $this->havings[]=$criteria->having; $this->limit=$criteria->limit; $this->offset=$criteria->offset; $this->params=$criteria->params; if(!$this->distinct && $criteria->distinct) $this->distinct=true; } else { $this->selects[]=$joinElement->getPrimaryKeySelect(); $this->joins[]=$joinElement->getTableNameWithAlias(); $this->conditions[]=$joinElement->getPrimaryKeyRange(); } $this->elements[$joinElement->id]=true; } /** * Joins with another join element * @param CFmpJoinElement $element the element to be joined */ public function join($element) { if($element->slave!==null) $this->join($element->slave); if(!empty($element->relation->select)) $this->selects[]=$element->getColumnSelect($element->relation->select); $this->conditions[]=$element->relation->condition; $this->orders[]=$element->relation->order; $this->joins[]=$element->getJoinCondition(); $this->joins[]=$element->relation->join; $this->groups[]=$element->relation->group; $this->havings[]=$element->relation->having; if(is_array($element->relation->params)) { if(is_array($this->params)) $this->params=array_merge($this->params,$element->relation->params); else $this->params=$element->relation->params; } $this->elements[$element->id]=true; } /** * Creates the SQL statement. * @param CDbCommandBuilder $builder the command builder * @return CDbCommand DB command instance representing the SQL statement */ public function createCommand($builder) { $sql=($this->distinct ? 'SELECT DISTINCT ':'SELECT ') . implode(', ',$this->selects); $sql.=' FROM ' . implode(' ',$this->joins); $conditions=array(); foreach($this->conditions as $condition) if($condition!=='') $conditions[]=$condition; if($conditions!==array()) $sql.=' WHERE (' . implode(') AND (',$conditions).')'; $groups=array(); foreach($this->groups as $group) if($group!=='') $groups[]=$group; if($groups!==array()) $sql.=' GROUP BY ' . implode(', ',$groups); $havings=array(); foreach($this->havings as $having) if($having!=='') $havings[]=$having; if($havings!==array()) $sql.=' HAVING (' . implode(') AND (',$havings).')'; $orders=array(); foreach($this->orders as $order) if($order!=='') $orders[]=$order; if($orders!==array()) $sql.=' ORDER BY ' . implode(', ',$orders); $sql=$builder->applyLimit($sql,$this->limit,$this->offset); $command=$builder->getDbConnection()->createCommand($sql); $builder->bindValues($command,$this->params); return $command; } } /** * CFmpStatElement represents STAT join element for {@link CFmpActiveFinder}. * * @author Qiang Xue <qiang.xue@gmail.com> * @package system.db.ar */ class CFmpStatElement { /** * @var CActiveRelation the relation represented by this tree node */ public $relation; private $_finder; private $_parent; /** * Constructor. * @param CFmpActiveFinder $finder the finder * @param CStatRelation $relation the STAT relation * @param CFmpJoinElement $parent the join element owning this STAT element */ public function __construct($finder,$relation,$parent) { $this->_finder=$finder; $this->_parent=$parent; $this->relation=$relation; $parent->stats[]=$this; } /** * Performs the STAT query. */ public function query() { if(preg_match('/^\s*(.*?)\((.*)\)\s*$/',$this->relation->foreignKey,$matches)) $this->queryManyMany($matches[1],$matches[2]); else $this->queryOneMany(); } private function queryOneMany() { $relation=$this->relation; $model=$this->_finder->getModel($relation->className); $builder=$model->getCommandBuilder(); $schema=$builder->getSchema(); $table=$model->getTableSchema(); $parent=$this->_parent; $pkTable=$parent->model->getTableSchema(); $fks=preg_split('/\s*,\s*/',$relation->foreignKey,-1,PREG_SPLIT_NO_EMPTY); if(count($fks)!==count($pkTable->primaryKey)) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key. The columns in the key must match the primary keys of the table "{table}".', array('{class}'=>get_class($parent->model), '{relation}'=>$relation->name, '{table}'=>$pkTable->name))); // set up mapping between fk and pk columns $map=array(); // pk=>fk foreach($fks as $i=>$fk) { if(!isset($table->columns[$fk])) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key "{key}". There is no such column in the table "{table}".', array('{class}'=>get_class($parent->model), '{relation}'=>$relation->name, '{key}'=>$fk, '{table}'=>$table->name))); if(isset($table->foreignKeys[$fk])) { list($tableName,$pk)=$table->foreignKeys[$fk]; if($schema->compareTableNames($pkTable->rawName,$tableName)) $map[$pk]=$fk; else throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with a foreign key "{key}" that does not point to the parent table "{table}".', array('{class}'=>get_class($parent->model), '{relation}'=>$relation->name, '{key}'=>$fk, '{table}'=>$pkTable->name))); } else // FK constraints undefined { if(is_array($pkTable->primaryKey)) // composite PK $map[$pkTable->primaryKey[$i]]=$fk; else $map[$pkTable->primaryKey]=$fk; } } $records=$this->_parent->records; $join=empty($relation->join)?'' : ' '.$relation->join; $where=empty($relation->condition)?' WHERE ' : ' WHERE ('.$relation->condition.') AND '; $group=empty($relation->group)?'' : ', '.$relation->group; $having=empty($relation->having)?'' : ' HAVING ('.$relation->having.')'; $order=empty($relation->order)?'' : ' ORDER BY '.$relation->order; $c=$schema->quoteColumnName('c'); $s=$schema->quoteColumnName('s'); $tableAlias=$model->getTableAlias(true); // generate and perform query if(count($fks)===1) // single column FK { $col=$tableAlias.'.'.$table->columns[$fks[0]]->rawName; $sql="SELECT $col AS $c, {$relation->select} AS $s FROM {$table->rawName} ".$tableAlias.$join .$where.'('.$builder->createInCondition($table,$fks[0],array_keys($records),$tableAlias.'.').')' ." GROUP BY $col".$group .$having.$order; $command=$builder->getDbConnection()->createCommand($sql); if(is_array($relation->params)) $builder->bindValues($command,$relation->params); $stats=array(); foreach($command->queryAll() as $row) $stats[$row['c']]=$row['s']; } else // composite FK { $keys=array_keys($records); foreach($keys as &$key) { $key2=unserialize($key); $key=array(); foreach($pkTable->primaryKey as $pk) $key[$map[$pk]]=$key2[$pk]; } $cols=array(); foreach($pkTable->primaryKey as $n=>$pk) { $name=$tableAlias.'.'.$table->columns[$map[$pk]]->rawName; $cols[$name]=$name.' AS '.$schema->quoteColumnName('c'.$n); } $sql='SELECT '.implode(', ',$cols).", {$relation->select} AS $s FROM {$table->rawName} ".$tableAlias.$join .$where.'('.$builder->createInCondition($table,$fks,$keys,$tableAlias.'.').')' .' GROUP BY '.implode(', ',array_keys($cols)).$group .$having.$order; $command=$builder->getDbConnection()->createCommand($sql); if(is_array($relation->params)) $builder->bindValues($command,$relation->params); $stats=array(); foreach($command->queryAll() as $row) { $key=array(); foreach($pkTable->primaryKey as $n=>$pk) $key[$pk]=$row['c'.$n]; $stats[serialize($key)]=$row['s']; } } // populate the results into existing records foreach($records as $pk=>$record) $record->addRelatedRecord($relation->name,isset($stats[$pk])?$stats[$pk]:$relation->defaultValue,false); } /* * @param string $joinTableName jointablename * @param string $keys keys */ private function queryManyMany($joinTableName,$keys) { $relation=$this->relation; $model=$this->_finder->getModel($relation->className); $table=$model->getTableSchema(); $builder=$model->getCommandBuilder(); $schema=$builder->getSchema(); $pkTable=$this->_parent->model->getTableSchema(); $tableAlias=$model->getTableAlias(true); if(($joinTable=$builder->getSchema()->getTable($joinTableName))===null) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is not specified correctly: the join table "{joinTable}" given in the foreign key cannot be found in the database.', array('{class}'=>get_class($this->_parent->model), '{relation}'=>$relation->name, '{joinTable}'=>$joinTableName))); $fks=preg_split('/\s*,\s*/',$keys,-1,PREG_SPLIT_NO_EMPTY); if(count($fks)!==count($table->primaryKey)+count($pkTable->primaryKey)) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an incomplete foreign key. The foreign key must consist of columns referencing both joining tables.', array('{class}'=>get_class($this->_parent->model), '{relation}'=>$relation->name))); $joinCondition=array(); $map=array(); $fkDefined=true; foreach($fks as $i=>$fk) { if(!isset($joinTable->columns[$fk])) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key "{key}". There is no such column in the table "{table}".', array('{class}'=>get_class($this->_parent->model), '{relation}'=>$relation->name, '{key}'=>$fk, '{table}'=>$joinTable->name))); if(isset($joinTable->foreignKeys[$fk])) { list($tableName,$pk)=$joinTable->foreignKeys[$fk]; if(!isset($joinCondition[$pk]) && $schema->compareTableNames($table->rawName,$tableName)) $joinCondition[$pk]=$tableAlias.'.'.$schema->quoteColumnName($pk).'='.$joinTable->rawName.'.'.$schema->quoteColumnName($fk); elseif(!isset($map[$pk]) && $schema->compareTableNames($pkTable->rawName,$tableName)) $map[$pk]=$fk; else { $fkDefined=false; break; } } else { $fkDefined=false; break; } } if(!$fkDefined) { $joinCondition=array(); $map=array(); foreach($fks as $i=>$fk) { if($i<count($pkTable->primaryKey)) { $pk=is_array($pkTable->primaryKey) ? $pkTable->primaryKey[$i] : $pkTable->primaryKey; $map[$pk]=$fk; } else { $j=$i-count($pkTable->primaryKey); $pk=is_array($table->primaryKey) ? $table->primaryKey[$j] : $table->primaryKey; $joinCondition[$pk]=$tableAlias.'.'.$schema->quoteColumnName($pk).'='.$joinTable->rawName.'.'.$schema->quoteColumnName($fk); } } } if($joinCondition===array() || $map===array()) throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an incomplete foreign key. The foreign key must consist of columns referencing both joining tables.', array('{class}'=>get_class($this->_parent->model), '{relation}'=>$relation->name))); $records=$this->_parent->records; $cols=array(); foreach(is_string($pkTable->primaryKey)?array($pkTable->primaryKey):$pkTable->primaryKey as $n=>$pk) { $name=$joinTable->rawName.'.'.$schema->quoteColumnName($map[$pk]); $cols[$name]=$name.' AS '.$schema->quoteColumnName('c'.$n); } $keys=array_keys($records); if(is_array($pkTable->primaryKey)) { foreach($keys as &$key) { $key2=unserialize($key); $key=array(); foreach($pkTable->primaryKey as $pk) $key[$map[$pk]]=$key2[$pk]; } } $join=empty($relation->join)?'' : ' '.$relation->join; $where=empty($relation->condition)?'' : ' WHERE ('.$relation->condition.')'; $group=empty($relation->group)?'' : ', '.$relation->group; $having=empty($relation->having)?'' : ' AND ('.$relation->having.')'; $order=empty($relation->order)?'' : ' ORDER BY '.$relation->order; $sql='SELECT '.$this->relation->select.' AS '.$schema->quoteColumnName('s').', '.implode(', ',$cols) .' FROM '.$table->rawName.' '.$tableAlias.' INNER JOIN '.$joinTable->rawName .' ON ('.implode(') AND (',$joinCondition).')'.$join .$where .' GROUP BY '.implode(', ',array_keys($cols)).$group .' HAVING ('.$builder->createInCondition($joinTable,$map,$keys).')' .$having.$order; $command=$builder->getDbConnection()->createCommand($sql); if(is_array($relation->params)) $builder->bindValues($command,$relation->params); $stats=array(); foreach($command->queryAll() as $row) { if(is_array($pkTable->primaryKey)) { $key=array(); foreach($pkTable->primaryKey as $n=>$k) $key[$k]=$row['c'.$n]; $stats[serialize($key)]=$row['s']; } else $stats[$row['c0']]=$row['s']; } foreach($records as $pk=>$record) $record->addRelatedRecord($relation->name,isset($stats[$pk])?$stats[$pk]:$this->relation->defaultValue,false); } }
{ "content_hash": "b83807c0f1d51805ab1c132530d3e229", "timestamp": "", "source": "github", "line_count": 1638, "max_line_length": 219, "avg_line_length": 31.702686202686202, "alnum_prop": 0.641837894047642, "repo_name": "airmoi/yiifmpdb", "id": "de8f54bae2001320dc50b164688c39207fd8a0b0", "size": "52118", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CFmpActiveFinder.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "96788" } ], "symlink_target": "" }
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.2.1. ## Development server Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. ## Code scaffolding Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|module`. ## Build Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build. ## Running unit tests Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). ## Running end-to-end tests Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). Before running the tests make sure you are serving the app via `ng serve`. ## Further help To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).
{ "content_hash": "0b1505c8bcf22b39a979e2d5c806a0b9", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 153, "avg_line_length": 41, "alnum_prop": 0.7476547842401501, "repo_name": "Taha-Di-Nero/Leave-management", "id": "e411267f3851ecb5ba19ba838eb76f1d119be0d1", "size": "1078", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Coverage/webapp/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "125275" }, { "name": "CSS", "bytes": "75236" }, { "name": "HTML", "bytes": "73066" }, { "name": "JavaScript", "bytes": "1123" }, { "name": "PowerShell", "bytes": "257" }, { "name": "TypeScript", "bytes": "701389" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en" xml:lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="https://iigkid.github.io/jekyll-mexpro-roxanna/images/favicon.ico"> <title>ABA Seguros Extended/Upgraded Mexican Insurance Endorsement</title> <meta name="description" content="The ABA Seguros Plus extended or upgraded optional mexican insurance endorsement offers top quality coverage, high limits, GAP, great customer service."> <link rel="canonical" href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/coverage/aba-seguros-extended.html"> <link rel="alternate" hreflang="en" href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/coverage/aba-seguros-extended.html"> <link rel="alternate" hreflang="es-MX" href="https://iigkid.github.io/jekyll-mexpro-roxanna/mx/aba-seguros-cobertura-extendida.html"> <link rel="alternate" type="application/rss+xml" title="Mexpro Mexico Insurance Professionals" href="https://iigkid.github.io/jekyll-mexpro-roxanna/feed.xml"> <script> window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date; ga('create', 'UA-3065776-3', 'auto'); ga('require', 'autotrack'); ga('send', 'pageview'); </script> <!-- Script for tracking GSS-Search in Analtyics --> <script> _gaq = {}; _gaq.push = function() { ga('send', 'pageview', arguments[0][1]); }; </script> <link type="text/css" rel="stylesheet" href="/jekyll-mexpro-roxanna/assets/main-bd695a7df6bba672e6a620e2dc0cedd0a81c0283a40307b363cdec8b408b2272.css"> </head> <body class="basic"> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <div itemscope itemtype="https://schema.org/Organization"> <a itemprop="url" class="navbar-brand" href="https://iigkid.github.io/jekyll-mexpro-roxanna" title="Mexpro Logo"><img itemprop="logo" class="hidden-xs logo-fixed" src="https://iigkid.github.io/jekyll-mexpro-roxanna/images/mexpro-2017logo.png" alt="Mexpro Logo" width="257" height="70"><img itemprop="logo" class="hidden-lg hidden-md hidden-sm logo-fixed" src="https://iigkid.github.io/jekyll-mexpro-roxanna/images/mexpro-2017logo-mobile.png" alt="Mexpro Logo" width="227" height="61"></a> </div> <div class="search hidden-md hidden-lg"> <a href="#" class="st-search-show-outputs"><span class="glyphicon glyphicon-search"></span></a> </div> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div class="mobphonenav hidden-md hidden-lg" itemscope itemtype="https://schema.org/ContactPoint"> <button type="button" onclick="location.href='tel:+18556397761'" class="btn btn-mobile"> <span class="glyphicon glyphicon-earphone"></span><span itemprop="telephone" contactType="customer support" areaServed="US, CA, MX" ContactOption="TollFree" availableLanguage="English, Spanish">1-855-MEXPRO1</span></button> </div> <!-- / mobile phone number --> </div> <!-- /navbar-header --> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <div class="row row1"> <ul class="nav navbar-nav navbar-right"> <!--<li role="presentation" class=""> <a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/contact-mexican-insurance-online.html">Contact Us</a> </li> <li class="navdivider"></li>--> <li role="presentation" class=""> <a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mx/aba-seguros-cobertura-extendida.html">Español</a> </li> <li class="navdivider"></li> <li role="presentation" class="phone" itemscope itemtype="https://schema.org/ContactPoint"> <a href="tel:+18556397761" rel="nofollow" title="Call Mexpro"><span class="glyphicon glyphicon-earphone"></span> <span itemprop="telephone" contactType="customer support" areaServed="US, CA, MX" ContactOption="TollFree" availableLanguage="English, Spanish">1-855-MexPro1</span></a> </li> <li class="navdivider"></li> <li role="presentation" class=" st-search-show-outputs"> <a href="#" class="st-search-show-outputs"><span class="glyphicon glyphicon-search"></span> Search Mexpro</a> </li> </ul> </div> <!-- /row1 --> <div class="row row2"> <ul class="nav navbar-nav"> <li role="presentation" class=""> <a href="https://iigkid.github.io/jekyll-mexpro-roxanna?utm_source=nav2&utm_medium=www&utm_campaign=navhomepage" title="Home Page">Home</a> </li> <li class="navdivider"></li> <li class=" hidden-md hidden-lg"> <a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mx/aba-seguros-cobertura-extendida.html">Español</a> </li> <li role="presentation" class="hidden-md hidden-lg"><button class="btn btn-buy btn-xs" onclick="location.href='https://www.mexpro.com/en-US/quotes/new/?agtdst=buytopnav#/'" type="button"><span class="glyphicon glyphicon-shopping-cart" aria-hidden="true"></span> BUY NOW</button></li> <li role="presentation" class="hidden-md hidden-lg"><button type="button" class="btn btn-login btn-xs" data-href="#customer-login-topnav" data-toggle="modal" data-target="#customer-login-topnav"><span class="glyphicon glyphicon-lock" aria-hidden="true"></span> LOG IN</button></li> <li role="presentation" class="dropdown"> <a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/auto/?utm_source=nav2&utm_medium=www&utm_campaign=navautopage" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">Insurance <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/auto/?utm_source=nav2&utm_medium=www&utm_campaign=navautopage" title="Mexico auto vehicle insurance">Auto</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/motorcycle/?utm_source=nav2&utm_medium=www&utm_campaign=navmotopage" title="Mexico motorcycle insurance">Motorcycle</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/rv/?utm_source=nav2&utm_medium=www&utm_campaign=navrvpage" title="Mexico RV insurance">RV</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/short-term-us-auto-insurance/?utm_source=nav2&utm_medium=www&utm_campaign=navnbpage" title="Insurance for tourists in USA">USA Tourist Auto</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/resident-auto/?utm_source=nav2&utm_medium=www&utm_campaign=navresautopage" title="Mexican auto insurance for residents of Mexico">Mexico Resident Auto</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/home-insurance/?utm_source=nav2&utm_medium=www&utm_campaign=navhomepage" title="Mexico Home, Condo, Townhome insurance">Homeowners</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/boat/?utm_source=nav2&utm_medium=www&utm_campaign=navboatpage" title="Boat, jet ski, watercraft insurance">Boat/Watercraft</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/international-health/?utm_source=nav2&utm_medium=www&utm_campaign=navmedpage" title="International travel health insurance">Travel Health</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/emergency-evacuation/?utm_source=nav2&utm_medium=www&utm_campaign=navevacpage" title="International travel health insurance">Travel Medical Evacuation</a></li> </ul> </li> <li class="navdivider"></li> <li role="presentation" class=""> <a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/customer-service/?utm_source=nav2&utm_medium=www&utm_campaign=navcustsvcpage" title="Customer Service">Customer Service</a> </li> <li class="navdivider"></li> <li role="presentation" class=""> <a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/claims/instructions.html?utm_source=nav2&utm_medium=www&utm_campaign=navclaimpage" title="Mexico insurance claims">Claims</a> </li> <li class="navdivider"></li> <!--<li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">FAQ <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Mexico Tourist Auto</a></li> <li><a href="#">Home, Condo, Townhome</a></li> <li><a href="#">Boat &amp; Personal Watercraft</a></li> <li><a href="#">Travel Health Insurance</a></li> <li><a href="#">USA Tourist Auto</a></li> <li><a href="#">Mexican Resident Auto</a></li> </ul> </li> <li class="navdivider"></li>--> <li role="presentation" class=""> <a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/about-mexico-car-insurance-pros.html?utm_source=nav2&utm_medium=www&utm_campaign=navaboutpage" title="About Mexpro">About</a> </li> <li role="presentation" class="hidden-sm hidden-md hidden-lg phone" itemscope itemtype="https://schema.org/ContactPoint"> <a href="tel:+18556397761" rel="nofollow" title="Call Mexpro"><span class="glyphicon glyphicon-earphone"></span> <span itemprop="telephone" contactType="customer support" areaServed="US, CA, MX" ContactOption="TollFree" availableLanguage="English, Spanish">1-855-MexPro1</span></a> </li> </ul> <ul class="nav-btn"> <li><button type="button" class="btn btn-login btn-xs" data-href="#customer-login-topnav" data-toggle="modal" data-target="#customer-login-topnav"><span class="glyphicon glyphicon-lock" aria-hidden="true"></span> LOG IN</button></li> <li><button class="btn btn-buy btn-xs" onclick="location.href='https://www.mexpro.com/en-US/quotes/new/?agtdst=buytopnav#/'" type="button"><span class="glyphicon glyphicon-shopping-cart" aria-hidden="true"></span> BUY NOW</button></li> </ul> </div> <!-- / row2 --> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> <!-- Customer Login top nav modal/popup --> <div class="modal fade" id="customer-login-topnav" tabindex="-1" role="dialog" aria-labelledby="customer-login-header" aria-hidden="true"> <div class="modal-dialog"> <form action="https://www.mexpro.com/client_login/do/login.mhtml?aff_id=2149&amp;agtdst=logintopnav" method="POST" name="log-in"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">x</button> <h2 id="customer-login-header">Purchased With Us Before?</h2> </div> <div class="modal-body"> <p>If you purchased with us before, you can quickly re-issue a new policy.<br><a href="https://www.mexpro.com/client_login/retrieve_password.mhtml?aff_id=2149&amp;agtdst=forgotpwtopnav" target="_blank">Click here to set up a password</a>. <p>Already Have Your Password?</p> <fieldset> <input type="text" class="form-control cl_username" name="username" placeholder="Email"> <br> <input type="password" class="form-control cl_password" name="password" placeholder="Password"> </fieldset> </div> <div class="modal-footer"> <button type="button" class="btn btn-close" data-dismiss="modal" aria-hidden="true">Close</button> <input type="submit" class="btn btn-primary" value="Login" > </div> </div> </form> </div> </div> <div id="content"> <div class="container-fluid"> <div class="row"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h1>ABA Seguros Auto Extended/Optional Endorsement</h1> <p><span class="aba"></span>When shown as covered on the face sheet of the policy, and upon payment of the corresponding premium, <em>this endorsement modifies coverage and limits as follows</em>:</p> <ol> <li><p><strong>Increased Limits for Civil Liability for Property Damage and for Bodily Injury to Third Parties</strong><br>The Combined Single Limit for Property Damage Liability/Bodily Injury Liability limit is increased to US $500,000.</p></li> <li><p><strong>Increased Medical Expenses for Occupants of the Insured Vehicle</strong><br>The limit for Medical Expenses is increased to US $15,000 per person, US $75,000 per accident.</p></li> <li><p><strong>Guaranteed Bond and Legal Assistance</strong><br>The company legal representative will post bond or deposit the guarantee before the Agent of the Public Ministry Office and/or Penal Judge up to US $300,000 to obtain the provisional release of the Driver, and/or the release of the covered vehicle and to guarantee the repair of the damaged third party property.</p></li> <li><p><strong>Increased Cost of Repair</strong><br>With prior agreement of the Company, the Insured may proceed to repair the vehicle outside Mexico. Instead of Mexican labor rates, the Company will require at least two estimates and will pay the actual labor costs incurred in the USA or Canada, not to exceed $100 per hour for any type of vehicle (only if covered for collision and upon payment of the corresponding premium). Vehicles will be considered a total loss at the option of the Company.</p></li> <li><p><strong>Fixed Deductibles</strong><br>Deductibles for collision and total theft are fixed at US $500 and US $1000 respectively. The deductible for ATV's and UTV's is $2000 USD while self-propelled and/or decoupled from the towing unit.</p></li> <li><p><strong>Partial Theft</strong><br>Theft of parts and accessories that are permanently attached to the insured vehicle, excluding video and sound reproducing equipment, personal property, or objects contained in the vehicle. This coverage is subject to the fixed deductible of US $500 for theft.</p></li> <li><p><strong>Vandalism</strong><br>Intentional and malicious damage to or destruction of the insured vehicle. This coverage is subject to a fixed deductible of US $500.</p></li> <li><p><strong>Deductible Waiver in Accidents with Third Parties at Fault</strong><br>If the insured is involved in an accident in which an uninsured third party is at fault, as determined by the corresponding Mexican legal authorities, and damage is sustained to the insured vehicle, the company will pay for damages to the insured vehicle and waive the corresponding deductible.</p><p>The Insured, however, must fully cooperate with the Company in order to retain the corresponding right of recovery against the third party responsible for the accident.</p></li> <li><p><strong><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/coverage/gap.html">Gap Coverage</a></strong><br>In case of total theft or loss of the insured vehicle with a loan or lease on the vehicle, the company will pay the unpaid net balance of the loan or lease, even if the <a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/coverage/vehicle-value.html">Actual Cash Value</a> of the vehicle is less than the loan or lease amount. In no event shall The Company’s liability under this clause exceed the Actual Cash Value of the vehicle multiplied by 1.15. This coverage applies ONLY when the insured amount of the vehicle as listed on the declarations page is equal to or greater than the Actual Cash Value of the vehicle</p></li> </ol> <h2>Coverage Details – ABA Seguros – Extended</h2> <p><strong>Section 1 (Collision):</strong><br>This includes coverage for collision, overturning, glass breakage, and is subject to the deductible.</p> <p><strong>Section 2 (Theft):</strong><br>This coverage includes total theft of the vehicle. Note that partial theft is only covered in Mexico with the purchase of an extended coverage option.</p> <p><strong>Extended Coverage:</strong><br>The Extended policy has a more comprehensive coverage package than that of the standard policy. While coverage varies by carrier it typically provides coverage for vandalism, partial theft, US Labor Rates, and much more.</p> <p><strong>Vandalism:</strong><br>This policy provides coverage for vandalism and is subject to a $500 USD deductible.</p> <p><strong>Partial Theft:</strong><br>This policy provides coverage for partial theft and is subject to a $500 USD deductible.</p> <p><strong>Deductibles:</strong><br>Deductibles are $500 for collision and $1,000 for total theft. The deductible for ATV's and UTV's is $2000 USD while self-propelled and/or decoupled from the towing unit.</p> <p><strong>Additional Extended Coverage:</strong><br>Deductibles are $500 for partial theft and vandalism.</p> <p><strong>US Repair:</strong><br>Your vehicle can be repaired in the US. However, the labor rate will vary based on the policy you purchase. Standard coverage will pay a labor rate equal to the going Mexican labor rate. The extended coverage will have an increased labor rate.</p> <p><strong>US Labor Rate:</strong><br>The policy will pay a higher rate per hour for repairs rather than the lower Mexican labor rates. The rates will be increased to $100 USD per hour regardless of the type of vehicle.</p> <p><strong>Uninsured Motorist Deductible Waiver:</strong><br>If you are involved in an accident in which an uninsured third party is at fault, as determined by the legal authorities, and you sustain damage to your vehicle, the insurer will pay for damages to your vehicle and waive your deductible.</p> <p><strong>3rd Party Liability:</strong><br>In the event of an accident, this coverage protects you from bodily injury or property damages to third parties. This does not provide coverage to passengers inside the insured vehicle. We recommend purchasing the highest limits you can afford, but no less than $500,000 CSL.</p> <p><strong>Legal Assistance:</strong><br>This policy will provide an amount equal to the liability limit, in legal assistance for a covered loss in the event you need bail bonds or legal assistance.</p> <p><strong>Medical Payments:</strong><br>This policy will pay medical expenses as a result of a covered vehicle accident of $15,000 USD per person / $75,000 USD per accident. Coverage is afforded to the driver and occupants in the vehicle at the time of the accident.</p> <p><strong>Travel Assistance:</strong><br>This package includes the <a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/mexvisit.html">MexVisit&reg; extended travel assistance</a> package.</p> <p><strong>Medical Evacuation:</strong><br>This policy includes the MexVisit&reg; extended travel assistance package which includes limited medical evacuation for certain situations; please see the terms and conditions for more detail.</p> <p><strong>Roadside Assistance:</strong><br>This policy includes the MexVisit&reg; extended travel assistance package which includes roadside assistance for certain situations; please see the terms and conditions for more detail.</p> <p><strong>Rental Car:</strong><br>This policy includes the MexVisit&reg; extended travel assistance package which provides a rental car for certain situations; please see the terms and conditions for more detail.</p> <p><strong>GAP Coverage:</strong><br>The Company pays the 'GAP' or difference between the Actual Cash Value of the vehicle and the unpaid net balance of the loan or lease up to 15%, if the amount owed is equal to or greater than the Actual Cash Value of the vehicle.</p> <p><strong>Policy Terms and Conditions:</strong><br>As always, review the <a href="https://iigkid.github.io/jekyll-mexpro-roxanna/pdf/ABA_toc.pdf">Terms &amp; Conditions</a> of your policy before purchasing.</p> </div> </div> </div> </div> </div> <link type="text/css" rel="stylesheet" href="/jekyll-mexpro-roxanna/assets/coverage-6f1df053a39635765ac69ecde61971235550813eadbda101dd119e2c1507fdb1.css"> </div> <footer> <div class="container"> <div class="col-xs-12 bot-menu"> <div class="col-md-5 col-xs-12"> <h5>Mexico Insurance</h5> <ul class="col-md-6 col-xs-12"> <li class="title">Vehicle Insurance</li> <li><a href="https://www.mexpro.com/en-US/quotes/new/?agtdst=footauto" title="Auto, RV, Motorcycle Insurance Quote">Mexico Tourist Auto</a></li> <li><a href="http://www.nationalunitysecuretransactionma.com/nuevo/inscribe.php?a=b6769fb6897300b3dfddc232635dccf9" title="Tourist Auto Insurance in the USA" target="_blank">USA Tourist Auto</a></li> <li><a href="https://www.tupoliza.mx/?fx=QGyNBuscy0Z3dQ3igd0ENw%3D%3D" title="Mexican Resident Auto Insurance" target="_blank">Mexico Resident Auto</a></li> </ul> <ul class="col-md-6 col-xs-12"> <li class="title">Specialty Insurance</li> <li><a href="https://www.mexpro.com/mexico-wc/quote/?aff_id=2149&amp;lang=en&amp;agtdst=footwc" title="Boat Insurance Quote">Boat &amp; Personal Watercraft</a></li> <li><a href="https://www.mexpro.com/mexico-home-owners/quote/?aff_id=2149&amp;lang=en&amp;agtdst=foothome" title="Homeowners Insurance Quote">Mexico Homeowners</a></li> <li><a href="https://producer.imglobal.com/international-insurance-plans.aspx?imgac=19048" title="Travel Health Insurance Quote" target="_blank">Travel Health Insurance</a></li> <li><a href="https://travelmedevac.com/" title="Travel Medical Evacuation" target="_blank">Travel Medical Evacuation</a></li> </ul> </div> <div class="col-md-3 col-xs-12"> <h5>Mexico Travel Tips</h5> <ul> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/vehicle-import-permit.html?utm_source=foot&amp;utm_medium=www&amp;utm_campaign=foottip" title="Temporary Importation Permit">Temporary Importation Permits</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/mexvisit.html?utm_source=foot&amp;utm_medium=www&amp;utm_campaign=footroadside" title="Mexico Roadside Assitance">MexVisit Travel Assistance</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/beforeyougo.html?utm_source=foot&amp;utm_medium=www&amp;utm_campaign=footbfyougo" title="Before Going Mexico Tips">Before You Go</a></li> <!--<li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/auto/reasons.html?utm_source=foot&amp;utm_medium=www&amp;utm_campaign=footreasons" title="Why Need Mexico Insurance">Why You Need Mexico Insurance</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/coverage/us-canadian-auto.html?utm_source=foot&amp;utm_medium=www&amp;utm_campaign=footpolicy" title="Insurance Coverage">Does Your Car Insurance Cover You in Mexico?</a></li>--> </ul> </div> <div class="col-md-2 col-xs-12"> <h5>About Mexpro</h5> <ul> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/about-mexico-car-insurance-pros.html?utm_source=foot&amp;utm_medium=www&amp;utm_campaign=footabout" title="About Mexpro">About Us</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/customer-service/?utm_source=foot&amp;utm_medium=www&amp;utm_campaign=footcustsvc">Customer Service</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/claims/instructions.html?utm_source=foot&amp;utm_medium=www&amp;utm_campaign=footclaims" title="Insurance Claims">Claims</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/faq.html?utm_source=foot&amp;utm_medium=www&amp;utm_campaign=footfaqs" title="Mexpro FAQs">FAQs</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/blog/?utm_source=foot&amp;utm_medium=www&amp;utm_campaign=footblog" title="Mexpro Blog">Blog</a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/contact-mexican-insurance-online.html?utm_source=foot&amp;utm_medium=www&amp;utm_campaign=footcontact" title="Contact Mexpro">Contact Us</a></li> </ul> </div> <div class="col-md-2 col-xs-12"> <ul> <li><a href="https://www.mexpro.com/en-US/quotes/new/?agtdst=footbuyonline" title="Auto, RV, Motorcycle Insurance Quote"><span class="buyonline"></span><h5>Buy Online</h5></a></li> <li itemscope itemtype="https://schema.org/ContactPoint"><a href="tel:+18556397761" rel="nofollow" title="Call Mexpro"><span class="callus"></span><span itemprop="telephone" contactType="customer support" areaServed="US, CA, MX" ContactOption="TollFree" availableLanguage="English, Spanish"></span><p>Call Us</p></a></li> <li><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/contact-mexican-insurance-online.html?utm_source=foot&amp;utm_medium=www&amp;utm_campaign=footvisitus"><span class="visitus"></span><h5>Visit Our Office</h5></a></li> </ul> </div> </div> <!-- End bottom menu --> <div class="foot col-xs-12"> <!-- Toll free number & social media for mobile only --> <div class="tollsoc hidden-md hidden-lg"> <ul> <li itemscope itemtype="https://schema.org/ContactPoint"><a href="tel:+18556397761" rel="nofollow" title="Call Mexpro"><span itemprop="telephone" contactType="customer support" areaServed="US, CA, MX" ContactOption="TollFree" availableLanguage="English, Spanish"><span class="glyphicon glyphicon-earphone"></span> 1-855-MexPro1</span></a> Toll Free</li> <li><a class="social fb" href="https://www.facebook.com/Mexprocom" title="Mexpro on Facebook" target="_blank"></a></li> <li><a class="social twit" href="https://twitter.com/MexicoInsurance" title="Mexpro on Twitter" target="_blank"></a></li> <li><a class="social gplus" href="https://plus.google.com/+Mexpro" title="Mexpro on Google Plus" target="_blank"></a></li> </ul> </div> <!-- End toll free number & social media --> <!-- End NAP --> <div class="nap col-md-8 col-sm-12"> <ul> <li itemscope itemtype="https://schema.org/Corporation">&copy;1999 - 2018 <span itemprop="brand">Mexpro - Mexico Insurance Professionals</span></li> <li>DBA Mexico &amp; RV Insurance Services</li> <li>CA License Number 0D06599</li> <li itemscope itemtype="https://schema.org/PostalAddress"><span itemprop="streetAddress">214 East Birch Avenue</span>, <span itemprop="addressLocality">Flagstaff</span>, <span itemprop="addressRegion">Arizona</span> <span itemprop="postalCode">86001</span></li> <li itemscope itemtype="https://schema.org/ContactPoint"><a href="tel:+19282149750" rel="nofollow" title="Call Mexpro"><span itemprop="telephone" contactType="customer support" areaServed="US" availableLanguage="English, Spanish">+1-928-214-9750</span></a></li> <li class="nobullet"><a href="https://iigkid.github.io/jekyll-mexpro-roxanna/mexico/sitemap.html">Site Map</a></li> </ul> </div> <!-- End NAP --> <!-- Toll free number & social media for all except mobile --> <div class="tollsoc col-md-4 hidden-xs hidden-sm"> <ul> <li itemscope itemtype="https://schema.org/ContactPoint"><a href="tel:+18556397761" rel="nofollow" title="Call Mexpro"><span itemprop="telephone" contactType="customer support" areaServed="US, CA, MX" ContactOption="TollFree" availableLanguage="English, Spanish"><span class="glyphicon glyphicon-earphone"></span> 1-855-MexPro1</span></a> Toll Free</li> <li><a class="social fb" href="https://www.facebook.com/Mexprocom" title="Mexpro on Facebook" target="_blank"></a></li> <li><a class="social twit" href="https://twitter.com/MexicoInsurance" title="Mexpro on Twitter" target="_blank"></a></li> <li><a class="social gplus" href="https://plus.google.com/+Mexpro" title="Mexpro on Google Plus" target="_blank"></a></li> </ul> </div> <!-- End toll free number & social media --> </div> <!-- End foot --> </div> <!-- End container --> </footer> <link type="text/css" rel="stylesheet" href="/jekyll-mexpro-roxanna/assets/bottom-5e274eb7234ad380d4e9aec88919e1c21649e8009a6d9a1175534c7756b173f1.css"> <!-- Latest compiled and minified JavaScript --> <script type="text/javascript" src="/jekyll-mexpro-roxanna/assets/main-f26c7693d033a606a5b2b601616c4b1936253766791f09978351720595e434e5.js"></script> <!-- Swiftype Search JS --> <script> (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){ (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t); e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e); })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st'); _st('install','qfhkCh7NCQ659JkNCx-z','2.0.0'); </script> <!-- Hamburger Menu Fix --> <!-- Allows for menu to close when clicked. --> <script> jQuery(document).ready(function () { jQuery(document).on('click touchstart', function (event) { var clickover = $(event.target); event.stopPropagation(); var _opened = $(".navbar-collapse").hasClass("navbar-collapse collapse in"); if(_opened === true && !clickover.parent().parent().hasClass("phone")){ if(!clickover.hasClass("navbar-toggle") && !clickover.hasClass("dropdown-toggle") && !clickover.hasClass("navbar-nav") && !clickover.hasClass("phone") && event.target.tagName != "A"){ jQuery("button.navbar-toggle").click(); } } }); }); </script> </body> </html>
{ "content_hash": "bb1278d49be74d9a6dd0f0589639bc23", "timestamp": "", "source": "github", "line_count": 342, "max_line_length": 781, "avg_line_length": 89.92397660818713, "alnum_prop": 0.6874552903687325, "repo_name": "iigkid/jekyll-mexpro", "id": "0f4752902964347439f33de94c619e0404594e35", "size": "30764", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/mexico/coverage/aba-seguros-extended.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "69853" }, { "name": "CoffeeScript", "bytes": "61" }, { "name": "HTML", "bytes": "1749113" }, { "name": "Ruby", "bytes": "2201" }, { "name": "Shell", "bytes": "288" } ], "symlink_target": "" }
namespace aura { class TestScreen; class Window; class WindowTreeHost; namespace client { class DefaultCaptureClient; class FocusClient; } } namespace content { class BrowserContext; } namespace gfx { class Insets; class Size; } #if defined(OS_CHROMEOS) namespace ui { class UserActivityPowerManagerNotifier; } #endif namespace wm { class CompoundEventFilter; class CursorManager; class FocusRules; class InputMethodEventFilter; class UserActivityDetector; } namespace extensions { class Extension; class ShellAppWindow; class ShellAppWindowController; // Handles desktop-related tasks for app_shell. class ShellDesktopController : public aura::client::WindowTreeClient, public aura::WindowTreeHostObserver #if defined(OS_CHROMEOS) , public ui::DisplayConfigurator::Observer #endif { public: ShellDesktopController(); virtual ~ShellDesktopController(); // Returns the single instance of the desktop. (Stateless functions like // ShellAppWindowCreateFunction need to be able to access the desktop, so // we need a singleton somewhere). static ShellDesktopController* instance(); aura::WindowTreeHost* host() { return host_.get(); } // Creates the window that hosts the app. void CreateRootWindow(); // Sets the controller to create/close the app windows. Takes the ownership of // |app_window_controller|. void SetAppWindowController(ShellAppWindowController* app_window_controller); // Creates a new app window and adds it to the desktop. The desktop maintains // ownership of the window. The window must be closed before |extension| is // destroyed. ShellAppWindow* CreateAppWindow(content::BrowserContext* context, const Extension* extension); // Closes and destroys the app windows. void CloseAppWindows(); // Sets the screen's work area insets. void SetDisplayWorkAreaInsets(const gfx::Insets& insets); // Overridden from aura::client::WindowTreeClient: virtual aura::Window* GetDefaultParent(aura::Window* context, aura::Window* window, const gfx::Rect& bounds) OVERRIDE; #if defined(OS_CHROMEOS) // ui::DisplayConfigurator::Observer overrides. virtual void OnDisplayModeChanged(const std::vector< ui::DisplayConfigurator::DisplayState>& displays) OVERRIDE; #endif // aura::WindowTreeHostObserver overrides: virtual void OnHostCloseRequested(const aura::WindowTreeHost* host) OVERRIDE; protected: // Creates and sets the aura clients and window manager stuff. Subclass may // initialize different sets of the clients. virtual void InitWindowManager(); // Creates a focus rule that is to be used in the InitWindowManager. virtual wm::FocusRules* CreateFocusRules(); private: // Closes and destroys the root window hosting the app. void DestroyRootWindow(); // Returns the dimensions (in pixels) of the primary display, or an empty size // if the dimensions can't be determined or no display is connected. gfx::Size GetPrimaryDisplaySize(); #if defined(OS_CHROMEOS) scoped_ptr<ui::DisplayConfigurator> display_configurator_; #endif scoped_ptr<aura::TestScreen> test_screen_; scoped_ptr<aura::WindowTreeHost> host_; scoped_ptr<wm::CompoundEventFilter> root_window_event_filter_; scoped_ptr<aura::client::DefaultCaptureClient> capture_client_; scoped_ptr<wm::InputMethodEventFilter> input_method_filter_; scoped_ptr<aura::client::FocusClient> focus_client_; scoped_ptr<wm::CursorManager> cursor_manager_; scoped_ptr<wm::UserActivityDetector> user_activity_detector_; #if defined(OS_CHROMEOS) scoped_ptr<ui::UserActivityPowerManagerNotifier> user_activity_notifier_; #endif // The desktop supports a single app window. scoped_ptr<ShellAppWindowController> app_window_controller_; DISALLOW_COPY_AND_ASSIGN(ShellDesktopController); }; } // namespace extensions #endif // EXTENSIONS_SHELL_BROWSER_SHELL_DESKTOP_CONTROLLER_H_
{ "content_hash": "78b50dae8e4127e6d8e88b97d91b37bd", "timestamp": "", "source": "github", "line_count": 139, "max_line_length": 80, "avg_line_length": 29.532374100719423, "alnum_prop": 0.7235079171741778, "repo_name": "7kbird/chrome", "id": "90ba2eb2efd15122855b5449e8b711d365175ae2", "size": "4677", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "extensions/shell/browser/shell_desktop_controller.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "35318" }, { "name": "Batchfile", "bytes": "7198" }, { "name": "C", "bytes": "3677808" }, { "name": "C++", "bytes": "212205607" }, { "name": "CSS", "bytes": "871288" }, { "name": "HTML", "bytes": "24532775" }, { "name": "Java", "bytes": "5466890" }, { "name": "JavaScript", "bytes": "17937570" }, { "name": "Makefile", "bytes": "37731" }, { "name": "Objective-C", "bytes": "1120421" }, { "name": "Objective-C++", "bytes": "7054476" }, { "name": "PHP", "bytes": "97817" }, { "name": "PLpgSQL", "bytes": "218361" }, { "name": "Perl", "bytes": "69392" }, { "name": "Protocol Buffer", "bytes": "388742" }, { "name": "Python", "bytes": "6953688" }, { "name": "Shell", "bytes": "465194" }, { "name": "Standard ML", "bytes": "4131" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "15206" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="wrap_content" android:paddingBottom="10dp" android:layout_gravity="center" android:paddingLeft="10dp" android:paddingRight="10dp" android:paddingTop="30dp" android:orientation="vertical" android:background="@color/app_bg_color"> <LinearLayout android:orientation="vertical" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center" android:gravity="center" android:id="@+id/begindate" > <TextView android:id="@+id/beginText" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center" android:gravity="center" android:layout_marginTop="20dp" android:textColor="@color/black" android:text="见证日期" /> <LinearLayout android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center_horizontal" android:paddingLeft="12dp" android:paddingRight="12dp" android:paddingTop="20dp"> <kankan.wheel.widget.WheelView android:id="@+id/month" android:layout_height="wrap_content" android:layout_width="140dp"/> <kankan.wheel.widget.WheelView android:id="@+id/day" android:layout_height="wrap_content" android:layout_width="140dp"/> </LinearLayout> </LinearLayout> <LinearLayout android:id="@+id/enddate" android:orientation="vertical" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center" android:gravity="center" > <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center" android:gravity="center" android:layout_marginTop="20dp" android:textColor="@color/black" android:text="时间" /> <LinearLayout android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center_horizontal" android:paddingLeft="12dp" android:paddingRight="12dp" android:paddingTop="20dp"> <kankan.wheel.widget.WheelView android:id="@+id/hour" android:layout_height="wrap_content" android:layout_width="140dp"/> <kankan.wheel.widget.WheelView android:id="@+id/mins" android:layout_height="wrap_content" android:layout_width="140dp"/> </LinearLayout> </LinearLayout> <Button android:id="@+id/done" style="@style/common_btn" android:layout_width="match_parent" android:layout_margin="10dp" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="确认" /> </LinearLayout>
{ "content_hash": "9f3f67710542b91c143ae205c60cb2af", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 72, "avg_line_length": 33.5, "alnum_prop": 0.6255954271197205, "repo_name": "cdut007/PMS_TASK", "id": "c76c975f86c939911986f92b5feb0cc0ffc19d4a", "size": "3165", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TaskTrackerPMS/res/layout/time_date_layout.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1033339" } ], "symlink_target": "" }
/* histexpand.c -- history expansion. */ /* Copyright (C) 1989, 1992 Free Software Foundation, Inc. This file contains the GNU History Library (the Library), a set of routines for managing the text of previously typed lines. The Library 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 2, or (at your option) any later version. The 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 General Public License for more details. The GNU General Public License is often shipped with GNU software, and is generally kept in a file called COPYING or LICENSE. If you do not have a copy of the license, write to the Free Software Foundation, 59 Temple Place, Suite 330, Boston, MA 02111 USA. */ #define READLINE_LIBRARY #if defined (HAVE_CONFIG_H) # include <config.h> #endif #include <stdio.h> #if defined (HAVE_STDLIB_H) # include <stdlib.h> #else # include "ansi_stdlib.h" #endif /* HAVE_STDLIB_H */ #if defined (HAVE_UNISTD_H) # ifndef _MINIX # include <sys/types.h> # endif # include <unistd.h> #endif #if defined (HAVE_STRING_H) # include <string.h> #else # include <strings.h> #endif /* !HAVE_STRING_H */ #include "history.h" #include "histlib.h" #include "rlshell.h" #include "xmalloc.h" #define HISTORY_WORD_DELIMITERS " \t\n;&()|<>" #define HISTORY_QUOTE_CHARACTERS "\"'`" typedef int _hist_search_func_t __P((const char *, int)); static char error_pointer; static char *subst_lhs; static char *subst_rhs; static int subst_lhs_len; static int subst_rhs_len; static char *get_history_word_specifier __P((char *, char *, int *)); static char *history_find_word __P((char *, int)); static char *quote_breaks __P((char *)); /* Variables exported by this file. */ /* The character that represents the start of a history expansion request. This is usually `!'. */ char history_expansion_char = '!'; /* The character that invokes word substitution if found at the start of a line. This is usually `^'. */ char history_subst_char = '^'; /* During tokenization, if this character is seen as the first character of a word, then it, and all subsequent characters upto a newline are ignored. For a Bourne shell, this should be '#'. Bash special cases the interactive comment character to not be a comment delimiter. */ char history_comment_char = '\0'; /* The list of characters which inhibit the expansion of text if found immediately following history_expansion_char. */ char *history_no_expand_chars = " \t\n\r="; /* If set to a non-zero value, single quotes inhibit history expansion. The default is 0. */ int history_quotes_inhibit_expansion = 0; /* Used to split words by history_tokenize_internal. */ char *history_word_delimiters = HISTORY_WORD_DELIMITERS; /* If set, this points to a function that is called to verify that a particular history expansion should be performed. */ rl_linebuf_func_t *history_inhibit_expansion_function; /* **************************************************************** */ /* */ /* History Expansion */ /* */ /* **************************************************************** */ /* Hairy history expansion on text, not tokens. This is of general use, and thus belongs in this library. */ /* The last string searched for by a !?string? search. */ static char *search_string; /* The last string matched by a !?string? search. */ static char *search_match; /* Return the event specified at TEXT + OFFSET modifying OFFSET to point to after the event specifier. Just a pointer to the history line is returned; NULL is returned in the event of a bad specifier. You pass STRING with *INDEX equal to the history_expansion_char that begins this specification. DELIMITING_QUOTE is a character that is allowed to end the string specification for what to search for in addition to the normal characters `:', ` ', `\t', `\n', and sometimes `?'. So you might call this function like: line = get_history_event ("!echo:p", &index, 0); */ char * get_history_event (string, caller_index, delimiting_quote) const char *string; int *caller_index; int delimiting_quote; { register int i; register char c; HIST_ENTRY *entry; int which, sign, local_index, substring_okay; _hist_search_func_t *search_func; char *temp; /* The event can be specified in a number of ways. !! the previous command !n command line N !-n current command-line minus N !str the most recent command starting with STR !?str[?] the most recent command containing STR All values N are determined via HISTORY_BASE. */ i = *caller_index; if (string[i] != history_expansion_char) return ((char *)NULL); /* Move on to the specification. */ i++; sign = 1; substring_okay = 0; #define RETURN_ENTRY(e, w) \ return ((e = history_get (w)) ? e->line : (char *)NULL) /* Handle !! case. */ if (string[i] == history_expansion_char) { i++; which = history_base + (history_length - 1); *caller_index = i; RETURN_ENTRY (entry, which); } /* Hack case of numeric line specification. */ if (string[i] == '-') { sign = -1; i++; } if (_rl_digit_p (string[i])) { /* Get the extent of the digits and compute the value. */ for (which = 0; _rl_digit_p (string[i]); i++) which = (which * 10) + _rl_digit_value (string[i]); *caller_index = i; if (sign < 0) which = (history_length + history_base) - which; RETURN_ENTRY (entry, which); } /* This must be something to search for. If the spec begins with a '?', then the string may be anywhere on the line. Otherwise, the string must be found at the start of a line. */ if (string[i] == '?') { substring_okay++; i++; } /* Only a closing `?' or a newline delimit a substring search string. */ for (local_index = i; c = string[i]; i++) if ((!substring_okay && (whitespace (c) || c == ':' || (history_search_delimiter_chars && member (c, history_search_delimiter_chars)) || string[i] == delimiting_quote)) || string[i] == '\n' || (substring_okay && string[i] == '?')) break; which = i - local_index; temp = xmalloc (1 + which); if (which) strncpy (temp, string + local_index, which); temp[which] = '\0'; if (substring_okay && string[i] == '?') i++; *caller_index = i; #define FAIL_SEARCH() \ do { \ history_offset = history_length; free (temp) ; return (char *)NULL; \ } while (0) /* If there is no search string, try to use the previous search string, if one exists. If not, fail immediately. */ if (*temp == '\0' && substring_okay) { if (search_string) { free (temp); temp = savestring (search_string); } else FAIL_SEARCH (); } search_func = substring_okay ? history_search : history_search_prefix; while (1) { local_index = (*search_func) (temp, -1); if (local_index < 0) FAIL_SEARCH (); if (local_index == 0 || substring_okay) { entry = current_history (); history_offset = history_length; /* If this was a substring search, then remember the string that we matched for word substitution. */ if (substring_okay) { FREE (search_string); search_string = temp; FREE (search_match); search_match = history_find_word (entry->line, local_index); } else free (temp); return (entry->line); } if (history_offset) history_offset--; else FAIL_SEARCH (); } #undef FAIL_SEARCH #undef RETURN_ENTRY } /* Function for extracting single-quoted strings. Used for inhibiting history expansion within single quotes. */ /* Extract the contents of STRING as if it is enclosed in single quotes. SINDEX, when passed in, is the offset of the character immediately following the opening single quote; on exit, SINDEX is left pointing to the closing single quote. */ static void hist_string_extract_single_quoted (string, sindex) char *string; int *sindex; { register int i; for (i = *sindex; string[i] && string[i] != '\''; i++) ; *sindex = i; } static char * quote_breaks (s) char *s; { register char *p, *r; char *ret; int len = 3; for (p = s; p && *p; p++, len++) { if (*p == '\'') len += 3; else if (whitespace (*p) || *p == '\n') len += 2; } r = ret = xmalloc (len); *r++ = '\''; for (p = s; p && *p; ) { if (*p == '\'') { *r++ = '\''; *r++ = '\\'; *r++ = '\''; *r++ = '\''; p++; } else if (whitespace (*p) || *p == '\n') { *r++ = '\''; *r++ = *p++; *r++ = '\''; } else *r++ = *p++; } *r++ = '\''; *r = '\0'; return ret; } static char * hist_error(s, start, current, errtype) char *s; int start, current, errtype; { char *temp; const char *emsg; int ll, elen; ll = current - start; switch (errtype) { case EVENT_NOT_FOUND: emsg = "event not found"; elen = 15; break; case BAD_WORD_SPEC: emsg = "bad word specifier"; elen = 18; break; case SUBST_FAILED: emsg = "substitution failed"; elen = 19; break; case BAD_MODIFIER: emsg = "unrecognized history modifier"; elen = 29; break; case NO_PREV_SUBST: emsg = "no previous substitution"; elen = 24; break; default: emsg = "unknown expansion error"; elen = 23; break; } temp = xmalloc (ll + elen + 3); strncpy (temp, s + start, ll); temp[ll] = ':'; temp[ll + 1] = ' '; strcpy (temp + ll + 2, emsg); return (temp); } /* Get a history substitution string from STR starting at *IPTR and return it. The length is returned in LENPTR. A backslash can quote the delimiter. If the string is the empty string, the previous pattern is used. If there is no previous pattern for the lhs, the last history search string is used. If IS_RHS is 1, we ignore empty strings and set the pattern to "" anyway. subst_lhs is not changed if the lhs is empty; subst_rhs is allowed to be set to the empty string. */ static char * get_subst_pattern (str, iptr, delimiter, is_rhs, lenptr) char *str; int *iptr, delimiter, is_rhs, *lenptr; { register int si, i, j, k; char *s = (char *) NULL; i = *iptr; for (si = i; str[si] && str[si] != delimiter; si++) if (str[si] == '\\' && str[si + 1] == delimiter) si++; if (si > i || is_rhs) { s = xmalloc (si - i + 1); for (j = 0, k = i; k < si; j++, k++) { /* Remove a backslash quoting the search string delimiter. */ if (str[k] == '\\' && str[k + 1] == delimiter) k++; s[j] = str[k]; } s[j] = '\0'; if (lenptr) *lenptr = j; } i = si; if (str[i]) i++; *iptr = i; return s; } static void postproc_subst_rhs () { char *new; int i, j, new_size; new = xmalloc (new_size = subst_rhs_len + subst_lhs_len); for (i = j = 0; i < subst_rhs_len; i++) { if (subst_rhs[i] == '&') { if (j + subst_lhs_len >= new_size) new = xrealloc (new, (new_size = new_size * 2 + subst_lhs_len)); strcpy (new + j, subst_lhs); j += subst_lhs_len; } else { /* a single backslash protects the `&' from lhs interpolation */ if (subst_rhs[i] == '\\' && subst_rhs[i + 1] == '&') i++; if (j >= new_size) new = xrealloc (new, new_size *= 2); new[j++] = subst_rhs[i]; } } new[j] = '\0'; free (subst_rhs); subst_rhs = new; subst_rhs_len = j; } /* Expand the bulk of a history specifier starting at STRING[START]. Returns 0 if everything is OK, -1 if an error occurred, and 1 if the `p' modifier was supplied and the caller should just print the returned string. Returns the new index into string in *END_INDEX_PTR, and the expanded specifier in *RET_STRING. */ static int history_expand_internal (string, start, end_index_ptr, ret_string, current_line) char *string; int start, *end_index_ptr; char **ret_string; char *current_line; /* for !# */ { int i, n, starting_index; int substitute_globally, want_quotes, print_only; char *event, *temp, *result, *tstr, *t, c, *word_spec; int result_len; result = xmalloc (result_len = 128); i = start; /* If it is followed by something that starts a word specifier, then !! is implied as the event specifier. */ if (member (string[i + 1], ":$*%^")) { char fake_s[3]; int fake_i = 0; i++; fake_s[0] = fake_s[1] = history_expansion_char; fake_s[2] = '\0'; event = get_history_event (fake_s, &fake_i, 0); } else if (string[i + 1] == '#') { i += 2; event = current_line; } else { int quoted_search_delimiter = 0; /* If the character before this `!' is a double or single quote, then this expansion takes place inside of the quoted string. If we have to search for some text ("!foo"), allow the delimiter to end the search string. */ if (i && (string[i - 1] == '\'' || string[i - 1] == '"')) quoted_search_delimiter = string[i - 1]; event = get_history_event (string, &i, quoted_search_delimiter); } if (event == 0) { *ret_string = hist_error (string, start, i, EVENT_NOT_FOUND); free (result); return (-1); } /* If a word specifier is found, then do what that requires. */ starting_index = i; word_spec = get_history_word_specifier (string, event, &i); /* There is no such thing as a `malformed word specifier'. However, it is possible for a specifier that has no match. In that case, we complain. */ if (word_spec == (char *)&error_pointer) { *ret_string = hist_error (string, starting_index, i, BAD_WORD_SPEC); free (result); return (-1); } /* If no word specifier, than the thing of interest was the event. */ temp = word_spec ? savestring (word_spec) : savestring (event); FREE (word_spec); /* Perhaps there are other modifiers involved. Do what they say. */ want_quotes = substitute_globally = print_only = 0; starting_index = i; while (string[i] == ':') { c = string[i + 1]; if (c == 'g') { substitute_globally = 1; i++; c = string[i + 1]; } switch (c) { default: *ret_string = hist_error (string, i+1, i+2, BAD_MODIFIER); free (result); free (temp); return -1; case 'q': want_quotes = 'q'; break; case 'x': want_quotes = 'x'; break; /* :p means make this the last executed line. So we return an error state after adding this line to the history. */ case 'p': print_only++; break; /* :t discards all but the last part of the pathname. */ case 't': tstr = strrchr (temp, '/'); if (tstr) { tstr++; t = savestring (tstr); free (temp); temp = t; } break; /* :h discards the last part of a pathname. */ case 'h': tstr = strrchr (temp, '/'); if (tstr) *tstr = '\0'; break; /* :r discards the suffix. */ case 'r': tstr = strrchr (temp, '.'); if (tstr) *tstr = '\0'; break; /* :e discards everything but the suffix. */ case 'e': tstr = strrchr (temp, '.'); if (tstr) { t = savestring (tstr); free (temp); temp = t; } break; /* :s/this/that substitutes `that' for the first occurrence of `this'. :gs/this/that substitutes `that' for each occurrence of `this'. :& repeats the last substitution. :g& repeats the last substitution globally. */ case '&': case 's': { char *new_event; int delimiter, failed, si, l_temp; if (c == 's') { if (i + 2 < (int)strlen (string)) delimiter = string[i + 2]; else break; /* no search delimiter */ i += 3; t = get_subst_pattern (string, &i, delimiter, 0, &subst_lhs_len); /* An empty substitution lhs with no previous substitution uses the last search string as the lhs. */ if (t) { FREE (subst_lhs); subst_lhs = t; } else if (!subst_lhs) { if (search_string && *search_string) { subst_lhs = savestring (search_string); subst_lhs_len = strlen (subst_lhs); } else { subst_lhs = (char *) NULL; subst_lhs_len = 0; } } FREE (subst_rhs); subst_rhs = get_subst_pattern (string, &i, delimiter, 1, &subst_rhs_len); /* If `&' appears in the rhs, it's supposed to be replaced with the lhs. */ if (member ('&', subst_rhs)) postproc_subst_rhs (); } else i += 2; /* If there is no lhs, the substitution can't succeed. */ if (subst_lhs_len == 0) { *ret_string = hist_error (string, starting_index, i, NO_PREV_SUBST); free (result); free (temp); return -1; } l_temp = strlen (temp); /* Ignore impossible cases. */ if (subst_lhs_len > l_temp) { *ret_string = hist_error (string, starting_index, i, SUBST_FAILED); free (result); free (temp); return (-1); } /* Find the first occurrence of THIS in TEMP. */ si = 0; for (failed = 1; (si + subst_lhs_len) <= l_temp; si++) if (STREQN (temp+si, subst_lhs, subst_lhs_len)) { int len = subst_rhs_len - subst_lhs_len + l_temp; new_event = xmalloc (1 + len); strncpy (new_event, temp, si); strncpy (new_event + si, subst_rhs, subst_rhs_len); strncpy (new_event + si + subst_rhs_len, temp + si + subst_lhs_len, l_temp - (si + subst_lhs_len)); new_event[len] = '\0'; free (temp); temp = new_event; failed = 0; if (substitute_globally) { si += subst_rhs_len; l_temp = strlen (temp); substitute_globally++; continue; } else break; } if (substitute_globally > 1) { substitute_globally = 0; continue; /* don't want to increment i */ } if (failed == 0) continue; /* don't want to increment i */ *ret_string = hist_error (string, starting_index, i, SUBST_FAILED); free (result); free (temp); return (-1); } } i += 2; } /* Done with modfiers. */ /* Believe it or not, we have to back the pointer up by one. */ --i; if (want_quotes) { char *x; if (want_quotes == 'q') x = sh_single_quote (temp); else if (want_quotes == 'x') x = quote_breaks (temp); else x = savestring (temp); free (temp); temp = x; } n = strlen (temp); if (n >= result_len) result = xrealloc (result, n + 2); strcpy (result, temp); free (temp); *end_index_ptr = i; *ret_string = result; return (print_only); } /* Expand the string STRING, placing the result into OUTPUT, a pointer to a string. Returns: -1) If there was an error in expansion. 0) If no expansions took place (or, if the only change in the text was the de-slashifying of the history expansion character) 1) If expansions did take place 2) If the `p' modifier was given and the caller should print the result If an error ocurred in expansion, then OUTPUT contains a descriptive error message. */ #define ADD_STRING(s) \ do \ { \ int sl = strlen (s); \ j += sl; \ if (j >= result_len) \ { \ while (j >= result_len) \ result_len += 128; \ result = xrealloc (result, result_len); \ } \ strcpy (result + j - sl, s); \ } \ while (0) #define ADD_CHAR(c) \ do \ { \ if (j >= result_len - 1) \ result = xrealloc (result, result_len += 64); \ result[j++] = c; \ result[j] = '\0'; \ } \ while (0) int history_expand (hstring, output) char *hstring; char **output; { register int j; int i, r, l, passc, cc, modified, eindex, only_printing; char *string; /* The output string, and its length. */ int result_len; char *result; /* Used when adding the string. */ char *temp; if (output == 0) return 0; /* Setting the history expansion character to 0 inhibits all history expansion. */ if (history_expansion_char == 0) { *output = savestring (hstring); return (0); } /* Prepare the buffer for printing error messages. */ result = xmalloc (result_len = 256); result[0] = '\0'; only_printing = modified = 0; l = strlen (hstring); /* Grovel the string. Only backslash and single quotes can quote the history escape character. We also handle arg specifiers. */ /* Before we grovel forever, see if the history_expansion_char appears anywhere within the text. */ /* The quick substitution character is a history expansion all right. That is to say, "^this^that^" is equivalent to "!!:s^this^that^", and in fact, that is the substitution that we do. */ if (hstring[0] == history_subst_char) { string = xmalloc (l + 5); string[0] = string[1] = history_expansion_char; string[2] = ':'; string[3] = 's'; strcpy (string + 4, hstring); l += 4; } else { string = hstring; /* If not quick substitution, still maybe have to do expansion. */ /* `!' followed by one of the characters in history_no_expand_chars is NOT an expansion. */ for (i = 0; string[i]; i++) { cc = string[i + 1]; /* The history_comment_char, if set, appearing that the beginning of a word signifies that the rest of the line should not have history expansion performed on it. Skip the rest of the line and break out of the loop. */ if (history_comment_char && string[i] == history_comment_char && (i == 0 || member (string[i - 1], history_word_delimiters))) { while (string[i]) i++; break; } else if (string[i] == history_expansion_char) { if (!cc || member (cc, history_no_expand_chars)) continue; /* If the calling application has set history_inhibit_expansion_function to a function that checks for special cases that should not be history expanded, call the function and skip the expansion if it returns a non-zero value. */ else if (history_inhibit_expansion_function && (*history_inhibit_expansion_function) (string, i)) continue; else break; } /* XXX - at some point, might want to extend this to handle double quotes as well. */ else if (history_quotes_inhibit_expansion && string[i] == '\'') { /* If this is bash, single quotes inhibit history expansion. */ i++; hist_string_extract_single_quoted (string, &i); } else if (history_quotes_inhibit_expansion && string[i] == '\\') { /* If this is bash, allow backslashes to quote single quotes and the history expansion character. */ if (cc == '\'' || cc == history_expansion_char) i++; } } if (string[i] != history_expansion_char) { free (result); *output = savestring (string); return (0); } } /* Extract and perform the substitution. */ for (passc = i = j = 0; i < l; i++) { int tchar = string[i]; if (passc) { passc = 0; ADD_CHAR (tchar); continue; } if (tchar == history_expansion_char) tchar = -3; else if (tchar == history_comment_char) tchar = -2; switch (tchar) { default: ADD_CHAR (string[i]); break; case '\\': passc++; ADD_CHAR (tchar); break; case '\'': { /* If history_quotes_inhibit_expansion is set, single quotes inhibit history expansion. */ if (history_quotes_inhibit_expansion) { int quote, slen; quote = i++; hist_string_extract_single_quoted (string, &i); slen = i - quote + 2; temp = xmalloc (slen); strncpy (temp, string + quote, slen); temp[slen - 1] = '\0'; ADD_STRING (temp); free (temp); } else ADD_CHAR (string[i]); break; } case -2: /* history_comment_char */ if (i == 0 || member (string[i - 1], history_word_delimiters)) { temp = xmalloc (l - i + 1); strcpy (temp, string + i); ADD_STRING (temp); free (temp); i = l; } else ADD_CHAR (string[i]); break; case -3: /* history_expansion_char */ cc = string[i + 1]; /* If the history_expansion_char is followed by one of the characters in history_no_expand_chars, then it is not a candidate for expansion of any kind. */ if (member (cc, history_no_expand_chars)) { ADD_CHAR (string[i]); break; } #if defined (NO_BANG_HASH_MODIFIERS) /* There is something that is listed as a `word specifier' in csh documentation which means `the expanded text to this point'. That is not a word specifier, it is an event specifier. If we don't want to allow modifiers with `!#', just stick the current output line in again. */ if (cc == '#') { if (result) { temp = xmalloc (1 + strlen (result)); strcpy (temp, result); ADD_STRING (temp); free (temp); } i++; break; } #endif r = history_expand_internal (string, i, &eindex, &temp, result); if (r < 0) { *output = temp; free (result); if (string != hstring) free (string); return -1; } else { if (temp) { modified++; if (*temp) ADD_STRING (temp); free (temp); } only_printing = r == 1; i = eindex; } break; } } *output = result; if (string != hstring) free (string); if (only_printing) { add_history (result); return (2); } return (modified != 0); } /* Return a consed string which is the word specified in SPEC, and found in FROM. NULL is returned if there is no spec. The address of ERROR_POINTER is returned if the word specified cannot be found. CALLER_INDEX is the offset in SPEC to start looking; it is updated to point to just after the last character parsed. */ static char * get_history_word_specifier (spec, from, caller_index) char *spec, *from; int *caller_index; { register int i = *caller_index; int first, last; int expecting_word_spec = 0; char *result; /* The range of words to return doesn't exist yet. */ first = last = 0; result = (char *)NULL; /* If we found a colon, then this *must* be a word specification. If it isn't, then it is an error. */ if (spec[i] == ':') { i++; expecting_word_spec++; } /* Handle special cases first. */ /* `%' is the word last searched for. */ if (spec[i] == '%') { *caller_index = i + 1; return (search_match ? savestring (search_match) : savestring ("")); } /* `*' matches all of the arguments, but not the command. */ if (spec[i] == '*') { *caller_index = i + 1; result = history_arg_extract (1, '$', from); return (result ? result : savestring ("")); } /* `$' is last arg. */ if (spec[i] == '$') { *caller_index = i + 1; return (history_arg_extract ('$', '$', from)); } /* Try to get FIRST and LAST figured out. */ if (spec[i] == '-') first = 0; else if (spec[i] == '^') first = 1; else if (_rl_digit_p (spec[i]) && expecting_word_spec) { for (first = 0; _rl_digit_p (spec[i]); i++) first = (first * 10) + _rl_digit_value (spec[i]); } else return ((char *)NULL); /* no valid `first' for word specifier */ if (spec[i] == '^' || spec[i] == '*') { last = (spec[i] == '^') ? 1 : '$'; /* x* abbreviates x-$ */ i++; } else if (spec[i] != '-') last = first; else { i++; if (_rl_digit_p (spec[i])) { for (last = 0; _rl_digit_p (spec[i]); i++) last = (last * 10) + _rl_digit_value (spec[i]); } else if (spec[i] == '$') { i++; last = '$'; } else if (!spec[i] || spec[i] == ':') /* could be modifier separator */ last = -1; /* x- abbreviates x-$ omitting word `$' */ } *caller_index = i; if (last >= first || last == '$' || last < 0) result = history_arg_extract (first, last, from); return (result ? result : (char *)&error_pointer); } /* Extract the args specified, starting at FIRST, and ending at LAST. The args are taken from STRING. If either FIRST or LAST is < 0, then make that arg count from the right (subtract from the number of tokens, so that FIRST = -1 means the next to last token on the line). If LAST is `$' the last arg from STRING is used. */ char * history_arg_extract (first, last, string) int first, last; const char *string; { register int i, len; char *result; int size, offset; char **list; /* XXX - think about making history_tokenize return a struct array, each struct in array being a string and a length to avoid the calls to strlen below. */ if ((list = history_tokenize (string)) == NULL) return ((char *)NULL); for (len = 0; list[len]; len++) ; if (last < 0) last = len + last - 1; if (first < 0) first = len + first - 1; if (last == '$') last = len - 1; if (first == '$') first = len - 1; last++; if (first >= len || last > len || first < 0 || last < 0 || first > last) result = ((char *)NULL); else { for (size = 0, i = first; i < last; i++) size += strlen (list[i]) + 1; result = xmalloc (size + 1); result[0] = '\0'; for (i = first, offset = 0; i < last; i++) { strcpy (result + offset, list[i]); offset += strlen (list[i]); if (i + 1 < last) { result[offset++] = ' '; result[offset] = 0; } } } for (i = 0; i < len; i++) free (list[i]); free (list); return (result); } #define slashify_in_quotes "\\`\"$" /* Parse STRING into tokens and return an array of strings. If WIND is not -1 and INDP is not null, we also want the word surrounding index WIND. The position in the returned array of strings is returned in *INDP. */ static char ** history_tokenize_internal (string, wind, indp) const char *string; int wind, *indp; { char **result; register int i, start, result_index, size; int len, delimiter; /* If we're searching for a string that's not part of a word (e.g., " "), make sure we set *INDP to a reasonable value. */ if (indp && wind != -1) *indp = -1; /* Get a token, and stuff it into RESULT. The tokens are split exactly where the shell would split them. */ for (i = result_index = size = 0, result = (char **)NULL; string[i]; ) { delimiter = 0; /* Skip leading whitespace. */ for (; string[i] && whitespace (string[i]); i++) ; if (string[i] == 0 || string[i] == history_comment_char) return (result); start = i; if (member (string[i], "()\n")) { i++; goto got_token; } if (member (string[i], "<>;&|$")) { int peek = string[i + 1]; if (peek == string[i] && peek != '$') { if (peek == '<' && string[i + 2] == '-') i++; i += 2; goto got_token; } else { if ((peek == '&' && (string[i] == '>' || string[i] == '<')) || ((peek == '>') && (string[i] == '&')) || ((peek == '(') && (string[i] == '$'))) { i += 2; goto got_token; } } if (string[i] != '$') { i++; goto got_token; } } /* Get word from string + i; */ if (member (string[i], HISTORY_QUOTE_CHARACTERS)) delimiter = string[i++]; for (; string[i]; i++) { if (string[i] == '\\' && string[i + 1] == '\n') { i++; continue; } if (string[i] == '\\' && delimiter != '\'' && (delimiter != '"' || member (string[i], slashify_in_quotes))) { i++; continue; } if (delimiter && string[i] == delimiter) { delimiter = 0; continue; } if (!delimiter && (member (string[i], history_word_delimiters))) break; if (!delimiter && member (string[i], HISTORY_QUOTE_CHARACTERS)) delimiter = string[i]; } got_token: /* If we are looking for the word in which the character at a particular index falls, remember it. */ if (indp && wind != -1 && wind >= start && wind < i) *indp = result_index; len = i - start; if (result_index + 2 >= size) result = (char **)xrealloc (result, ((size += 10) * sizeof (char *))); result[result_index] = xmalloc (1 + len); strncpy (result[result_index], string + start, len); result[result_index][len] = '\0'; result[++result_index] = (char *)NULL; } return (result); } /* Return an array of tokens, much as the shell might. The tokens are parsed out of STRING. */ char ** history_tokenize (string) const char *string; { return (history_tokenize_internal (string, -1, (int *)NULL)); } /* Find and return the word which contains the character at index IND in the history line LINE. Used to save the word matched by the last history !?string? search. */ static char * history_find_word (line, ind) char *line; int ind; { char **words, *s; int i, wind; words = history_tokenize_internal (line, ind, &wind); if (wind == -1 || words == 0) return ((char *)NULL); s = words[wind]; for (i = 0; i < wind; i++) free (words[i]); for (i = wind + 1; words[i]; i++) free (words[i]); free (words); return s; }
{ "content_hash": "b3a2091f2726f5a1934e2d608c0e9de6", "timestamp": "", "source": "github", "line_count": 1371, "max_line_length": 82, "avg_line_length": 24.61487964989059, "alnum_prop": 0.5714878359557887, "repo_name": "impedimentToProgress/UCI-BlueChip", "id": "1c8a1d9d3e31b6c2ae3b19960ea20398b4f60153", "size": "33747", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "snapgear_linux/user/bash/lib/readline/histexpand.c", "mode": "33261", "license": "mit", "language": [ { "name": "AGS Script", "bytes": "25338" }, { "name": "ASP", "bytes": "4526" }, { "name": "Ada", "bytes": "1075367" }, { "name": "Assembly", "bytes": "2137017" }, { "name": "Awk", "bytes": "133306" }, { "name": "Bison", "bytes": "399484" }, { "name": "BlitzBasic", "bytes": "101509" }, { "name": "C", "bytes": "288543995" }, { "name": "C++", "bytes": "7495614" }, { "name": "CSS", "bytes": "2128" }, { "name": "Clojure", "bytes": "3747" }, { "name": "Common Lisp", "bytes": "239683" }, { "name": "Elixir", "bytes": "790" }, { "name": "Emacs Lisp", "bytes": "45827" }, { "name": "Erlang", "bytes": "171340" }, { "name": "GAP", "bytes": "3002" }, { "name": "Groff", "bytes": "4517911" }, { "name": "Groovy", "bytes": "26513" }, { "name": "HTML", "bytes": "8141161" }, { "name": "Java", "bytes": "481441" }, { "name": "JavaScript", "bytes": "339345" }, { "name": "Logos", "bytes": "16160" }, { "name": "M", "bytes": "2443" }, { "name": "Makefile", "bytes": "1309237" }, { "name": "Max", "bytes": "3812" }, { "name": "Nemerle", "bytes": "966202" }, { "name": "Objective-C", "bytes": "376270" }, { "name": "OpenEdge ABL", "bytes": "69290" }, { "name": "PHP", "bytes": "11533" }, { "name": "PLSQL", "bytes": "8464" }, { "name": "Pascal", "bytes": "54420" }, { "name": "Perl", "bytes": "6498220" }, { "name": "Perl6", "bytes": "4155" }, { "name": "Prolog", "bytes": "62574" }, { "name": "Python", "bytes": "24287" }, { "name": "QMake", "bytes": "8619" }, { "name": "R", "bytes": "25999" }, { "name": "Ruby", "bytes": "31311" }, { "name": "SAS", "bytes": "15573" }, { "name": "Scala", "bytes": "1506" }, { "name": "Scilab", "bytes": "23534" }, { "name": "Shell", "bytes": "6951414" }, { "name": "Smalltalk", "bytes": "2661" }, { "name": "Stata", "bytes": "7930" }, { "name": "Tcl", "bytes": "1518344" }, { "name": "TeX", "bytes": "1574651" }, { "name": "UnrealScript", "bytes": "20822" }, { "name": "VHDL", "bytes": "37384578" }, { "name": "Verilog", "bytes": "376626" }, { "name": "Visual Basic", "bytes": "180" }, { "name": "XS", "bytes": "24500" }, { "name": "XSLT", "bytes": "5872" } ], "symlink_target": "" }
package org.drools.modelcompiler.builder.generator.drlxparse; import java.util.Arrays; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import com.github.javaparser.ast.expr.BinaryExpr; import com.github.javaparser.ast.expr.Expression; import org.drools.modelcompiler.builder.generator.DRLIdGenerator; public class MultipleDrlxParseSuccess extends AbstractDrlxParseSuccess { private final BinaryExpr.Operator operator; private final DrlxParseSuccess[] results; public MultipleDrlxParseSuccess( BinaryExpr.Operator operator, DrlxParseSuccess... results ) { this.operator = operator; this.results = results; } public BinaryExpr.Operator getOperator() { return operator; } public DrlxParseSuccess[] getResults() { return results; } @Override public boolean isTemporal() { return Stream.of(results).anyMatch( DrlxParseSuccess::isTemporal ); } @Override public Optional<Expression> getImplicitCastExpression() { return Optional.empty(); } @Override public DrlxParseResult combineWith( DrlxParseResult other, BinaryExpr.Operator operator ) { throw new UnsupportedOperationException(); } @Override public String getExprId(DRLIdGenerator exprIdGenerator) { return Arrays.stream(results).map(s -> s.getExprId(exprIdGenerator)).collect(Collectors.joining()); } @Override public DrlxParseResult setOriginalDrlConstraint(String originalDrlConstraint) { return this; } @Override public String getOriginalDrlConstraint() { return Arrays.stream(results).map(DrlxParseResult::getOriginalDrlConstraint).collect(Collectors.joining()); } @Override public boolean isPredicate() { return Stream.of(results).allMatch( DrlxParseSuccess::isPredicate); } @Override public String getExprBinding() { return null; } @Override public Expression getExpr() { return new BinaryExpr( results[0].getExpr(), results[1].getExpr(), operator ); } @Override public boolean isRequiresSplit() { return false; } }
{ "content_hash": "68cf7554e34286825e14b23bc680a7e4", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 115, "avg_line_length": 27.17283950617284, "alnum_prop": 0.7074057246706043, "repo_name": "jomarko/drools", "id": "8a5a938a69ad3abe4387ef0809fef078007042de", "size": "2794", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "drools-model/drools-model-compiler/src/main/java/org/drools/modelcompiler/builder/generator/drlxparse/MultipleDrlxParseSuccess.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "16820" }, { "name": "ASL", "bytes": "9582" }, { "name": "Batchfile", "bytes": "2554" }, { "name": "CSS", "bytes": "1969" }, { "name": "GAP", "bytes": "198103" }, { "name": "HTML", "bytes": "8245" }, { "name": "Java", "bytes": "42823510" }, { "name": "Python", "bytes": "4555" }, { "name": "Ruby", "bytes": "491" }, { "name": "Shell", "bytes": "1120" }, { "name": "XSLT", "bytes": "24302" } ], "symlink_target": "" }
<?php namespace Doctrine\Tests\DBAL\Functional; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Types\Type; use PDO; class DataAccessTest extends \Doctrine\Tests\DbalFunctionalTestCase { static private $generated = false; protected function setUp() { parent::setUp(); if (self::$generated === false) { /* @var $sm \Doctrine\DBAL\Schema\AbstractSchemaManager */ $table = new \Doctrine\DBAL\Schema\Table("fetch_table"); $table->addColumn('test_int', 'integer'); $table->addColumn('test_string', 'string'); $table->addColumn('test_datetime', 'datetime', array('notnull' => false)); $table->setPrimaryKey(array('test_int')); $sm = $this->_conn->getSchemaManager(); $sm->createTable($table); $this->_conn->insert('fetch_table', array('test_int' => 1, 'test_string' => 'foo', 'test_datetime' => '2010-01-01 10:10:10')); self::$generated = true; } } public function testPrepareWithBindValue() { $sql = "SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?"; $stmt = $this->_conn->prepare($sql); self::assertInstanceOf('Doctrine\DBAL\Statement', $stmt); $stmt->bindValue(1, 1); $stmt->bindValue(2, 'foo'); $stmt->execute(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); $row = array_change_key_case($row, \CASE_LOWER); self::assertEquals(array('test_int' => 1, 'test_string' => 'foo'), $row); } public function testPrepareWithBindParam() { $paramInt = 1; $paramStr = 'foo'; $sql = "SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?"; $stmt = $this->_conn->prepare($sql); self::assertInstanceOf('Doctrine\DBAL\Statement', $stmt); $stmt->bindParam(1, $paramInt); $stmt->bindParam(2, $paramStr); $stmt->execute(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); $row = array_change_key_case($row, \CASE_LOWER); self::assertEquals(array('test_int' => 1, 'test_string' => 'foo'), $row); } public function testPrepareWithFetchAll() { $paramInt = 1; $paramStr = 'foo'; $sql = "SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?"; $stmt = $this->_conn->prepare($sql); self::assertInstanceOf('Doctrine\DBAL\Statement', $stmt); $stmt->bindParam(1, $paramInt); $stmt->bindParam(2, $paramStr); $stmt->execute(); $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); $rows[0] = array_change_key_case($rows[0], \CASE_LOWER); self::assertEquals(array('test_int' => 1, 'test_string' => 'foo'), $rows[0]); } /** * @group DBAL-228 */ public function testPrepareWithFetchAllBoth() { $paramInt = 1; $paramStr = 'foo'; $sql = "SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?"; $stmt = $this->_conn->prepare($sql); self::assertInstanceOf('Doctrine\DBAL\Statement', $stmt); $stmt->bindParam(1, $paramInt); $stmt->bindParam(2, $paramStr); $stmt->execute(); $rows = $stmt->fetchAll(\PDO::FETCH_BOTH); $rows[0] = array_change_key_case($rows[0], \CASE_LOWER); self::assertEquals(array('test_int' => 1, 'test_string' => 'foo', 0 => 1, 1 => 'foo'), $rows[0]); } public function testPrepareWithFetchColumn() { $paramInt = 1; $paramStr = 'foo'; $sql = "SELECT test_int FROM fetch_table WHERE test_int = ? AND test_string = ?"; $stmt = $this->_conn->prepare($sql); self::assertInstanceOf('Doctrine\DBAL\Statement', $stmt); $stmt->bindParam(1, $paramInt); $stmt->bindParam(2, $paramStr); $stmt->execute(); $column = $stmt->fetchColumn(); self::assertEquals(1, $column); } public function testPrepareWithIterator() { $paramInt = 1; $paramStr = 'foo'; $sql = "SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?"; $stmt = $this->_conn->prepare($sql); self::assertInstanceOf('Doctrine\DBAL\Statement', $stmt); $stmt->bindParam(1, $paramInt); $stmt->bindParam(2, $paramStr); $stmt->execute(); $rows = array(); $stmt->setFetchMode(\PDO::FETCH_ASSOC); foreach ($stmt as $row) { $rows[] = array_change_key_case($row, \CASE_LOWER); } self::assertEquals(array('test_int' => 1, 'test_string' => 'foo'), $rows[0]); } public function testPrepareWithQuoted() { $table = 'fetch_table'; $paramInt = 1; $paramStr = 'foo'; $sql = "SELECT test_int, test_string FROM " . $this->_conn->quoteIdentifier($table) . " ". "WHERE test_int = " . $this->_conn->quote($paramInt) . " AND test_string = " . $this->_conn->quote($paramStr); $stmt = $this->_conn->prepare($sql); self::assertInstanceOf('Doctrine\DBAL\Statement', $stmt); } public function testPrepareWithExecuteParams() { $paramInt = 1; $paramStr = 'foo'; $sql = "SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?"; $stmt = $this->_conn->prepare($sql); self::assertInstanceOf('Doctrine\DBAL\Statement', $stmt); $stmt->execute(array($paramInt, $paramStr)); $row = $stmt->fetch(\PDO::FETCH_ASSOC); self::assertNotFalse($row); $row = array_change_key_case($row, \CASE_LOWER); self::assertEquals(array('test_int' => 1, 'test_string' => 'foo'), $row); } public function testFetchAll() { $sql = "SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?"; $data = $this->_conn->fetchAll($sql, array(1, 'foo')); self::assertCount(1, $data); $row = $data[0]; self::assertCount(2, $row); $row = array_change_key_case($row, \CASE_LOWER); self::assertEquals(1, $row['test_int']); self::assertEquals('foo', $row['test_string']); } /** * @group DBAL-209 */ public function testFetchAllWithTypes() { $datetimeString = '2010-01-01 10:10:10'; $datetime = new \DateTime($datetimeString); $sql = "SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?"; $data = $this->_conn->fetchAll($sql, array(1, $datetime), array(PDO::PARAM_STR, Type::DATETIME)); self::assertCount(1, $data); $row = $data[0]; self::assertCount(2, $row); $row = array_change_key_case($row, \CASE_LOWER); self::assertEquals(1, $row['test_int']); self::assertStringStartsWith($datetimeString, $row['test_datetime']); } /** * @group DBAL-209 * @expectedException \Doctrine\DBAL\DBALException */ public function testFetchAllWithMissingTypes() { if ($this->_conn->getDriver() instanceof \Doctrine\DBAL\Driver\Mysqli\Driver || $this->_conn->getDriver() instanceof \Doctrine\DBAL\Driver\SQLSrv\Driver) { $this->markTestSkipped('mysqli and sqlsrv actually supports this'); } $datetimeString = '2010-01-01 10:10:10'; $datetime = new \DateTime($datetimeString); $sql = "SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?"; $data = $this->_conn->fetchAll($sql, array(1, $datetime)); } public function testFetchBoth() { $sql = "SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?"; $row = $this->_conn->executeQuery($sql, array(1, 'foo'))->fetch(\PDO::FETCH_BOTH); self::assertNotFalse($row); $row = array_change_key_case($row, \CASE_LOWER); self::assertEquals(1, $row['test_int']); self::assertEquals('foo', $row['test_string']); self::assertEquals(1, $row[0]); self::assertEquals('foo', $row[1]); } public function testFetchNoResult() { self::assertFalse( $this->_conn->executeQuery('SELECT test_int FROM fetch_table WHERE test_int = ?', [-1])->fetch() ); } public function testFetchAssoc() { $sql = "SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?"; $row = $this->_conn->fetchAssoc($sql, array(1, 'foo')); self::assertNotFalse($row); $row = array_change_key_case($row, \CASE_LOWER); self::assertEquals(1, $row['test_int']); self::assertEquals('foo', $row['test_string']); } public function testFetchAssocWithTypes() { $datetimeString = '2010-01-01 10:10:10'; $datetime = new \DateTime($datetimeString); $sql = "SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?"; $row = $this->_conn->fetchAssoc($sql, array(1, $datetime), array(PDO::PARAM_STR, Type::DATETIME)); self::assertNotFalse($row); $row = array_change_key_case($row, \CASE_LOWER); self::assertEquals(1, $row['test_int']); self::assertStringStartsWith($datetimeString, $row['test_datetime']); } /** * @expectedException \Doctrine\DBAL\DBALException */ public function testFetchAssocWithMissingTypes() { if ($this->_conn->getDriver() instanceof \Doctrine\DBAL\Driver\Mysqli\Driver || $this->_conn->getDriver() instanceof \Doctrine\DBAL\Driver\SQLSrv\Driver) { $this->markTestSkipped('mysqli and sqlsrv actually supports this'); } $datetimeString = '2010-01-01 10:10:10'; $datetime = new \DateTime($datetimeString); $sql = "SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?"; $row = $this->_conn->fetchAssoc($sql, array(1, $datetime)); } public function testFetchArray() { $sql = "SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?"; $row = $this->_conn->fetchArray($sql, array(1, 'foo')); self::assertEquals(1, $row[0]); self::assertEquals('foo', $row[1]); } public function testFetchArrayWithTypes() { $datetimeString = '2010-01-01 10:10:10'; $datetime = new \DateTime($datetimeString); $sql = "SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?"; $row = $this->_conn->fetchArray($sql, array(1, $datetime), array(PDO::PARAM_STR, Type::DATETIME)); self::assertNotFalse($row); $row = array_change_key_case($row, \CASE_LOWER); self::assertEquals(1, $row[0]); self::assertStringStartsWith($datetimeString, $row[1]); } /** * @expectedException \Doctrine\DBAL\DBALException */ public function testFetchArrayWithMissingTypes() { if ($this->_conn->getDriver() instanceof \Doctrine\DBAL\Driver\Mysqli\Driver || $this->_conn->getDriver() instanceof \Doctrine\DBAL\Driver\SQLSrv\Driver) { $this->markTestSkipped('mysqli and sqlsrv actually supports this'); } $datetimeString = '2010-01-01 10:10:10'; $datetime = new \DateTime($datetimeString); $sql = "SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?"; $row = $this->_conn->fetchArray($sql, array(1, $datetime)); } public function testFetchColumn() { $sql = "SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?"; $testInt = $this->_conn->fetchColumn($sql, array(1, 'foo'), 0); self::assertEquals(1, $testInt); $sql = "SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?"; $testString = $this->_conn->fetchColumn($sql, array(1, 'foo'), 1); self::assertEquals('foo', $testString); } public function testFetchColumnWithTypes() { $datetimeString = '2010-01-01 10:10:10'; $datetime = new \DateTime($datetimeString); $sql = "SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?"; $column = $this->_conn->fetchColumn($sql, array(1, $datetime), 1, array(PDO::PARAM_STR, Type::DATETIME)); self::assertNotFalse($column); self::assertStringStartsWith($datetimeString, $column); } /** * @expectedException \Doctrine\DBAL\DBALException */ public function testFetchColumnWithMissingTypes() { if ($this->_conn->getDriver() instanceof \Doctrine\DBAL\Driver\Mysqli\Driver || $this->_conn->getDriver() instanceof \Doctrine\DBAL\Driver\SQLSrv\Driver) { $this->markTestSkipped('mysqli and sqlsrv actually supports this'); } $datetimeString = '2010-01-01 10:10:10'; $datetime = new \DateTime($datetimeString); $sql = "SELECT test_int, test_datetime FROM fetch_table WHERE test_int = ? AND test_datetime = ?"; $column = $this->_conn->fetchColumn($sql, array(1, $datetime), 1); } /** * @group DDC-697 */ public function testExecuteQueryBindDateTimeType() { $sql = 'SELECT count(*) AS c FROM fetch_table WHERE test_datetime = ?'; $stmt = $this->_conn->executeQuery($sql, array(1 => new \DateTime('2010-01-01 10:10:10')), array(1 => Type::DATETIME) ); self::assertEquals(1, $stmt->fetchColumn()); } /** * @group DDC-697 */ public function testExecuteUpdateBindDateTimeType() { $datetime = new \DateTime('2010-02-02 20:20:20'); $sql = 'INSERT INTO fetch_table (test_int, test_string, test_datetime) VALUES (?, ?, ?)'; $affectedRows = $this->_conn->executeUpdate($sql, array(1 => 50, 2 => 'foo', 3 => $datetime), array(1 => PDO::PARAM_INT, 2 => PDO::PARAM_STR, 3 => Type::DATETIME) ); self::assertEquals(1, $affectedRows); self::assertEquals(1, $this->_conn->executeQuery( 'SELECT count(*) AS c FROM fetch_table WHERE test_datetime = ?', array(1 => $datetime), array(1 => Type::DATETIME) )->fetchColumn()); } /** * @group DDC-697 */ public function testPrepareQueryBindValueDateTimeType() { $sql = 'SELECT count(*) AS c FROM fetch_table WHERE test_datetime = ?'; $stmt = $this->_conn->prepare($sql); $stmt->bindValue(1, new \DateTime('2010-01-01 10:10:10'), Type::DATETIME); $stmt->execute(); self::assertEquals(1, $stmt->fetchColumn()); } /** * @group DBAL-78 */ public function testNativeArrayListSupport() { for ($i = 100; $i < 110; $i++) { $this->_conn->insert('fetch_table', array('test_int' => $i, 'test_string' => 'foo' . $i, 'test_datetime' => '2010-01-01 10:10:10')); } $stmt = $this->_conn->executeQuery('SELECT test_int FROM fetch_table WHERE test_int IN (?)', array(array(100, 101, 102, 103, 104)), array(Connection::PARAM_INT_ARRAY)); $data = $stmt->fetchAll(PDO::FETCH_NUM); self::assertCount(5, $data); self::assertEquals(array(array(100), array(101), array(102), array(103), array(104)), $data); $stmt = $this->_conn->executeQuery('SELECT test_int FROM fetch_table WHERE test_string IN (?)', array(array('foo100', 'foo101', 'foo102', 'foo103', 'foo104')), array(Connection::PARAM_STR_ARRAY)); $data = $stmt->fetchAll(PDO::FETCH_NUM); self::assertCount(5, $data); self::assertEquals(array(array(100), array(101), array(102), array(103), array(104)), $data); } /** * @dataProvider getTrimExpressionData */ public function testTrimExpression($value, $position, $char, $expectedResult) { $sql = 'SELECT ' . $this->_conn->getDatabasePlatform()->getTrimExpression($value, $position, $char) . ' AS trimmed ' . 'FROM fetch_table'; $row = $this->_conn->fetchAssoc($sql); $row = array_change_key_case($row, CASE_LOWER); self::assertEquals($expectedResult, $row['trimmed']); } public function getTrimExpressionData() { return array( array('test_string', AbstractPlatform::TRIM_UNSPECIFIED, false, 'foo'), array('test_string', AbstractPlatform::TRIM_LEADING, false, 'foo'), array('test_string', AbstractPlatform::TRIM_TRAILING, false, 'foo'), array('test_string', AbstractPlatform::TRIM_BOTH, false, 'foo'), array('test_string', AbstractPlatform::TRIM_UNSPECIFIED, "'f'", 'oo'), array('test_string', AbstractPlatform::TRIM_UNSPECIFIED, "'o'", 'f'), array('test_string', AbstractPlatform::TRIM_UNSPECIFIED, "'.'", 'foo'), array('test_string', AbstractPlatform::TRIM_LEADING, "'f'", 'oo'), array('test_string', AbstractPlatform::TRIM_LEADING, "'o'", 'foo'), array('test_string', AbstractPlatform::TRIM_LEADING, "'.'", 'foo'), array('test_string', AbstractPlatform::TRIM_TRAILING, "'f'", 'foo'), array('test_string', AbstractPlatform::TRIM_TRAILING, "'o'", 'f'), array('test_string', AbstractPlatform::TRIM_TRAILING, "'.'", 'foo'), array('test_string', AbstractPlatform::TRIM_BOTH, "'f'", 'oo'), array('test_string', AbstractPlatform::TRIM_BOTH, "'o'", 'f'), array('test_string', AbstractPlatform::TRIM_BOTH, "'.'", 'foo'), array("' foo '", AbstractPlatform::TRIM_UNSPECIFIED, false, 'foo'), array("' foo '", AbstractPlatform::TRIM_LEADING, false, 'foo '), array("' foo '", AbstractPlatform::TRIM_TRAILING, false, ' foo'), array("' foo '", AbstractPlatform::TRIM_BOTH, false, 'foo'), array("' foo '", AbstractPlatform::TRIM_UNSPECIFIED, "'f'", ' foo '), array("' foo '", AbstractPlatform::TRIM_UNSPECIFIED, "'o'", ' foo '), array("' foo '", AbstractPlatform::TRIM_UNSPECIFIED, "'.'", ' foo '), array("' foo '", AbstractPlatform::TRIM_UNSPECIFIED, "' '", 'foo'), array("' foo '", AbstractPlatform::TRIM_LEADING, "'f'", ' foo '), array("' foo '", AbstractPlatform::TRIM_LEADING, "'o'", ' foo '), array("' foo '", AbstractPlatform::TRIM_LEADING, "'.'", ' foo '), array("' foo '", AbstractPlatform::TRIM_LEADING, "' '", 'foo '), array("' foo '", AbstractPlatform::TRIM_TRAILING, "'f'", ' foo '), array("' foo '", AbstractPlatform::TRIM_TRAILING, "'o'", ' foo '), array("' foo '", AbstractPlatform::TRIM_TRAILING, "'.'", ' foo '), array("' foo '", AbstractPlatform::TRIM_TRAILING, "' '", ' foo'), array("' foo '", AbstractPlatform::TRIM_BOTH, "'f'", ' foo '), array("' foo '", AbstractPlatform::TRIM_BOTH, "'o'", ' foo '), array("' foo '", AbstractPlatform::TRIM_BOTH, "'.'", ' foo '), array("' foo '", AbstractPlatform::TRIM_BOTH, "' '", 'foo'), ); } /** * @group DDC-1014 */ public function testDateArithmetics() { $p = $this->_conn->getDatabasePlatform(); $sql = 'SELECT '; $sql .= $p->getDateDiffExpression('test_datetime', $p->getCurrentTimestampSQL()) .' AS diff, '; $sql .= $p->getDateAddSecondsExpression('test_datetime', 1) .' AS add_seconds, '; $sql .= $p->getDateSubSecondsExpression('test_datetime', 1) .' AS sub_seconds, '; $sql .= $p->getDateAddMinutesExpression('test_datetime', 5) .' AS add_minutes, '; $sql .= $p->getDateSubMinutesExpression('test_datetime', 5) .' AS sub_minutes, '; $sql .= $p->getDateAddHourExpression('test_datetime', 3) .' AS add_hour, '; $sql .= $p->getDateSubHourExpression('test_datetime', 3) .' AS sub_hour, '; $sql .= $p->getDateAddDaysExpression('test_datetime', 10) .' AS add_days, '; $sql .= $p->getDateSubDaysExpression('test_datetime', 10) .' AS sub_days, '; $sql .= $p->getDateAddWeeksExpression('test_datetime', 1) .' AS add_weeks, '; $sql .= $p->getDateSubWeeksExpression('test_datetime', 1) .' AS sub_weeks, '; $sql .= $p->getDateAddMonthExpression('test_datetime', 2) .' AS add_month, '; $sql .= $p->getDateSubMonthExpression('test_datetime', 2) .' AS sub_month, '; $sql .= $p->getDateAddQuartersExpression('test_datetime', 3) .' AS add_quarters, '; $sql .= $p->getDateSubQuartersExpression('test_datetime', 3) .' AS sub_quarters, '; $sql .= $p->getDateAddYearsExpression('test_datetime', 6) .' AS add_years, '; $sql .= $p->getDateSubYearsExpression('test_datetime', 6) .' AS sub_years '; $sql .= 'FROM fetch_table'; $row = $this->_conn->fetchAssoc($sql); $row = array_change_key_case($row, CASE_LOWER); $diff = (strtotime('2010-01-01') - strtotime(date('Y-m-d'))) / 3600 / 24; self::assertEquals($diff, $row['diff'], "Date difference should be approx. ".$diff." days.", 1); self::assertEquals('2010-01-01 10:10:11', date('Y-m-d H:i:s', strtotime($row['add_seconds'])), "Adding second should end up on 2010-01-01 10:10:11"); self::assertEquals('2010-01-01 10:10:09', date('Y-m-d H:i:s', strtotime($row['sub_seconds'])), "Subtracting second should end up on 2010-01-01 10:10:09"); self::assertEquals('2010-01-01 10:15:10', date('Y-m-d H:i:s', strtotime($row['add_minutes'])), "Adding minutes should end up on 2010-01-01 10:15:10"); self::assertEquals('2010-01-01 10:05:10', date('Y-m-d H:i:s', strtotime($row['sub_minutes'])), "Subtracting minutes should end up on 2010-01-01 10:05:10"); self::assertEquals('2010-01-01 13:10', date('Y-m-d H:i', strtotime($row['add_hour'])), "Adding date should end up on 2010-01-01 13:10"); self::assertEquals('2010-01-01 07:10', date('Y-m-d H:i', strtotime($row['sub_hour'])), "Subtracting date should end up on 2010-01-01 07:10"); self::assertEquals('2010-01-11', date('Y-m-d', strtotime($row['add_days'])), "Adding date should end up on 2010-01-11"); self::assertEquals('2009-12-22', date('Y-m-d', strtotime($row['sub_days'])), "Subtracting date should end up on 2009-12-22"); self::assertEquals('2010-01-08', date('Y-m-d', strtotime($row['add_weeks'])), "Adding week should end up on 2010-01-08"); self::assertEquals('2009-12-25', date('Y-m-d', strtotime($row['sub_weeks'])), "Subtracting week should end up on 2009-12-25"); self::assertEquals('2010-03-01', date('Y-m-d', strtotime($row['add_month'])), "Adding month should end up on 2010-03-01"); self::assertEquals('2009-11-01', date('Y-m-d', strtotime($row['sub_month'])), "Subtracting month should end up on 2009-11-01"); self::assertEquals('2010-10-01', date('Y-m-d', strtotime($row['add_quarters'])), "Adding quarters should end up on 2010-04-01"); self::assertEquals('2009-04-01', date('Y-m-d', strtotime($row['sub_quarters'])), "Subtracting quarters should end up on 2009-10-01"); self::assertEquals('2016-01-01', date('Y-m-d', strtotime($row['add_years'])), "Adding years should end up on 2016-01-01"); self::assertEquals('2004-01-01', date('Y-m-d', strtotime($row['sub_years'])), "Subtracting years should end up on 2004-01-01"); } public function testLocateExpression() { $platform = $this->_conn->getDatabasePlatform(); $sql = 'SELECT '; $sql .= $platform->getLocateExpression('test_string', "'oo'") .' AS locate1, '; $sql .= $platform->getLocateExpression('test_string', "'foo'") .' AS locate2, '; $sql .= $platform->getLocateExpression('test_string', "'bar'") .' AS locate3, '; $sql .= $platform->getLocateExpression('test_string', 'test_string') .' AS locate4, '; $sql .= $platform->getLocateExpression("'foo'", 'test_string') .' AS locate5, '; $sql .= $platform->getLocateExpression("'barfoobaz'", 'test_string') .' AS locate6, '; $sql .= $platform->getLocateExpression("'bar'", 'test_string') .' AS locate7, '; $sql .= $platform->getLocateExpression('test_string', "'oo'", 2) .' AS locate8, '; $sql .= $platform->getLocateExpression('test_string', "'oo'", 3) .' AS locate9 '; $sql .= 'FROM fetch_table'; $row = $this->_conn->fetchAssoc($sql); $row = array_change_key_case($row, CASE_LOWER); self::assertEquals(2, $row['locate1']); self::assertEquals(1, $row['locate2']); self::assertEquals(0, $row['locate3']); self::assertEquals(1, $row['locate4']); self::assertEquals(1, $row['locate5']); self::assertEquals(4, $row['locate6']); self::assertEquals(0, $row['locate7']); self::assertEquals(2, $row['locate8']); self::assertEquals(0, $row['locate9']); } public function testQuoteSQLInjection() { $sql = "SELECT * FROM fetch_table WHERE test_string = " . $this->_conn->quote("bar' OR '1'='1"); $rows = $this->_conn->fetchAll($sql); self::assertCount(0, $rows, "no result should be returned, otherwise SQL injection is possible"); } /** * @group DDC-1213 */ public function testBitComparisonExpressionSupport() { $this->_conn->exec('DELETE FROM fetch_table'); $platform = $this->_conn->getDatabasePlatform(); $bitmap = array(); for ($i = 2; $i < 9; $i = $i + 2) { $bitmap[$i] = array( 'bit_or' => ($i | 2), 'bit_and' => ($i & 2) ); $this->_conn->insert('fetch_table', array( 'test_int' => $i, 'test_string' => json_encode($bitmap[$i]), 'test_datetime' => '2010-01-01 10:10:10' )); } $sql[] = 'SELECT '; $sql[] = 'test_int, '; $sql[] = 'test_string, '; $sql[] = $platform->getBitOrComparisonExpression('test_int', 2) . ' AS bit_or, '; $sql[] = $platform->getBitAndComparisonExpression('test_int', 2) . ' AS bit_and '; $sql[] = 'FROM fetch_table'; $stmt = $this->_conn->executeQuery(implode(PHP_EOL, $sql)); $data = $stmt->fetchAll(PDO::FETCH_ASSOC); self::assertCount(4, $data); self::assertEquals(count($bitmap), count($data)); foreach ($data as $row) { $row = array_change_key_case($row, CASE_LOWER); self::assertArrayHasKey('test_int', $row); $id = $row['test_int']; self::assertArrayHasKey($id, $bitmap); self::assertArrayHasKey($id, $bitmap); self::assertArrayHasKey('bit_or', $row); self::assertArrayHasKey('bit_and', $row); self::assertEquals($row['bit_or'], $bitmap[$id]['bit_or']); self::assertEquals($row['bit_and'], $bitmap[$id]['bit_and']); } } public function testSetDefaultFetchMode() { $stmt = $this->_conn->query("SELECT * FROM fetch_table"); $stmt->setFetchMode(\PDO::FETCH_NUM); $row = array_keys($stmt->fetch()); self::assertCount(0, array_filter($row, function($v) { return ! is_numeric($v); }), "should be no non-numerical elements in the result."); } /** * @group DBAL-1091 */ public function testFetchAllStyleObject() { $this->setupFixture(); $sql = 'SELECT test_int, test_string, test_datetime FROM fetch_table'; $stmt = $this->_conn->prepare($sql); $stmt->execute(); $results = $stmt->fetchAll(\PDO::FETCH_OBJ); self::assertCount(1, $results); self::assertInstanceOf('stdClass', $results[0]); self::assertEquals( 1, property_exists($results[0], 'test_int') ? $results[0]->test_int : $results[0]->TEST_INT ); self::assertEquals( 'foo', property_exists($results[0], 'test_string') ? $results[0]->test_string : $results[0]->TEST_STRING ); self::assertStringStartsWith( '2010-01-01 10:10:10', property_exists($results[0], 'test_datetime') ? $results[0]->test_datetime : $results[0]->TEST_DATETIME ); } /** * @group DBAL-196 */ public function testFetchAllSupportFetchClass() { $this->skipOci8AndMysqli(); $this->setupFixture(); $sql = "SELECT test_int, test_string, test_datetime FROM fetch_table"; $stmt = $this->_conn->prepare($sql); $stmt->execute(); $results = $stmt->fetchAll( \PDO::FETCH_CLASS, __NAMESPACE__.'\\MyFetchClass' ); self::assertCount(1, $results); self::assertInstanceOf(__NAMESPACE__.'\\MyFetchClass', $results[0]); self::assertEquals(1, $results[0]->test_int); self::assertEquals('foo', $results[0]->test_string); self::assertStringStartsWith('2010-01-01 10:10:10', $results[0]->test_datetime); } /** * @group DBAL-241 */ public function testFetchAllStyleColumn() { $sql = "DELETE FROM fetch_table"; $this->_conn->executeUpdate($sql); $this->_conn->insert('fetch_table', array('test_int' => 1, 'test_string' => 'foo')); $this->_conn->insert('fetch_table', array('test_int' => 10, 'test_string' => 'foo')); $sql = "SELECT test_int FROM fetch_table"; $rows = $this->_conn->query($sql)->fetchAll(\PDO::FETCH_COLUMN); self::assertEquals(array(1, 10), $rows); } /** * @group DBAL-214 */ public function testSetFetchModeClassFetchAll() { $this->skipOci8AndMysqli(); $this->setupFixture(); $sql = "SELECT * FROM fetch_table"; $stmt = $this->_conn->query($sql); $stmt->setFetchMode(\PDO::FETCH_CLASS, __NAMESPACE__ . '\\MyFetchClass'); $results = $stmt->fetchAll(); self::assertCount(1, $results); self::assertInstanceOf(__NAMESPACE__.'\\MyFetchClass', $results[0]); self::assertEquals(1, $results[0]->test_int); self::assertEquals('foo', $results[0]->test_string); self::assertStringStartsWith('2010-01-01 10:10:10', $results[0]->test_datetime); } /** * @group DBAL-214 */ public function testSetFetchModeClassFetch() { $this->skipOci8AndMysqli(); $this->setupFixture(); $sql = "SELECT * FROM fetch_table"; $stmt = $this->_conn->query($sql); $stmt->setFetchMode(\PDO::FETCH_CLASS, __NAMESPACE__ . '\\MyFetchClass'); $results = array(); while ($row = $stmt->fetch()) { $results[] = $row; } self::assertCount(1, $results); self::assertInstanceOf(__NAMESPACE__.'\\MyFetchClass', $results[0]); self::assertEquals(1, $results[0]->test_int); self::assertEquals('foo', $results[0]->test_string); self::assertStringStartsWith('2010-01-01 10:10:10', $results[0]->test_datetime); } /** * @group DBAL-257 */ public function testEmptyFetchColumnReturnsFalse() { $this->_conn->beginTransaction(); $this->_conn->exec('DELETE FROM fetch_table'); self::assertFalse($this->_conn->fetchColumn('SELECT test_int FROM fetch_table')); self::assertFalse($this->_conn->query('SELECT test_int FROM fetch_table')->fetchColumn()); $this->_conn->rollBack(); } /** * @group DBAL-339 */ public function testSetFetchModeOnDbalStatement() { $sql = "SELECT test_int, test_string FROM fetch_table WHERE test_int = ? AND test_string = ?"; $stmt = $this->_conn->executeQuery($sql, array(1, "foo")); $stmt->setFetchMode(\PDO::FETCH_NUM); $row = $stmt->fetch(); self::assertArrayHasKey(0, $row); self::assertArrayHasKey(1, $row); self::assertFalse($stmt->fetch()); } /** * @group DBAL-435 */ public function testEmptyParameters() { $sql = "SELECT * FROM fetch_table WHERE test_int IN (?)"; $stmt = $this->_conn->executeQuery($sql, array(array()), array(\Doctrine\DBAL\Connection::PARAM_INT_ARRAY)); $rows = $stmt->fetchAll(); self::assertEquals(array(), $rows); } /** * @group DBAL-1028 */ public function testFetchColumnNullValue() { $this->_conn->executeUpdate( 'INSERT INTO fetch_table (test_int, test_string) VALUES (?, ?)', array(2, 'foo') ); self::assertNull( $this->_conn->fetchColumn('SELECT test_datetime FROM fetch_table WHERE test_int = ?', array(2)) ); } /** * @group DBAL-1028 */ public function testFetchColumnNonExistingIndex() { if ($this->_conn->getDriver()->getName() === 'pdo_sqlsrv') { $this->markTestSkipped( 'Test does not work for pdo_sqlsrv driver as it throws a fatal error for a non-existing column index.' ); } self::assertNull( $this->_conn->fetchColumn('SELECT test_int FROM fetch_table WHERE test_int = ?', array(1), 1) ); } /** * @group DBAL-1028 */ public function testFetchColumnNoResult() { self::assertFalse( $this->_conn->fetchColumn('SELECT test_int FROM fetch_table WHERE test_int = ?', array(-1)) ); } private function setupFixture() { $this->_conn->exec('DELETE FROM fetch_table'); $this->_conn->insert('fetch_table', array( 'test_int' => 1, 'test_string' => 'foo', 'test_datetime' => '2010-01-01 10:10:10' )); } private function skipOci8AndMysqli() { if (isset($GLOBALS['db_type']) && $GLOBALS['db_type'] == "oci8") { $this->markTestSkipped("Not supported by OCI8"); } if ('mysqli' == $this->_conn->getDriver()->getName()) { $this->markTestSkipped('Mysqli driver dont support this feature.'); } } } class MyFetchClass { public $test_int, $test_string, $test_datetime; }
{ "content_hash": "3e61f16dfaf83dd989188425ad6dc5e5", "timestamp": "", "source": "github", "line_count": 874, "max_line_length": 163, "avg_line_length": 39.55949656750572, "alnum_prop": 0.5701807664497469, "repo_name": "gencer/dbal", "id": "6df4814f6e59bb120daa79c08692a462dc953a9f", "size": "34575", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/Doctrine/Tests/DBAL/Functional/DataAccessTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "2525029" }, { "name": "Shell", "bytes": "1898" } ], "symlink_target": "" }
<section style="margin: 100px 0 0 250px"> <div class="label label-info">This section tries to show the coexistence between summerbreeze DTOs and breeze DB objects.</div> <div class="label label-important">You can create a product using a DTO or a DB object.</div> <div> <h2 class="page-title" style="margin-top: 20px;">Add Product</h2> <span>(using DTO object)</span></div> <div class="navbar-form pull-left"> <div class="row"> <div class="span4"> <input type="text" class="form-control" style="width: 200px;" placeholder="Product Name"> </div> </div> <div class="row"> <div class="span4"> <input type="text" class="form-control" style="width: 200px;" placeholder="Picture Url"> </div> </div> <div class="row"> <div class="span4"> <div class="input-append"> <input class="span2" id="appendedInput" type="text" placeholder="Price" maxlength="4"> <span class="add-on">.00</span> </div> </div> </div> <div class="row"> <div class="span4"> <button type="submit" id="addBtnDTO" class="btn btn-default" style="width: 210px;">Add</button> </div> </div> </div> <div class="navbar-form pull-left" style="margin-top: -75px;"> <div class="row"> <div class="span4"> <h2 class="page-title">Add Product</h2> <span>(using DB object)</span> <br /> <input type="text" class="form-control" style="width: 200px;" placeholder="Product Name"> </div> </div> <div class="row"> <div class="span4"> <input type="text" class="form-control" style="width: 200px;" placeholder="Picture Url"> </div> </div> <div class="row"> <div class="span4"> <input type="text" class="form-control" style="width: 200px;" placeholder="Tags"> </div> </div> <div class="row"> <div class="span4"> <div class="input-append"> <input class="span2" id="Text1" type="text" placeholder="Price" maxlength="4"> <span class="add-on">.00</span> </div> </div> </div> <div class="row"> <div class="span4"> <button type="submit" id="addBtnDB" class="btn btn-default" style="width: 210px;">Add</button> </div> </div> </div> </section>
{ "content_hash": "7f820f75a00bb61810bde46a8474126a", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 131, "avg_line_length": 40.65151515151515, "alnum_prop": 0.5001863585538576, "repo_name": "dotnetricardo/SummerBreeze", "id": "02f5e8c7776a38bfd15fa454dbc7824ac718291d", "size": "2685", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SummerBreezeDemo/SummerBreezeDemo/App/views/add.html", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "106" }, { "name": "C#", "bytes": "36836" }, { "name": "CSS", "bytes": "322732" }, { "name": "JavaScript", "bytes": "5351587" }, { "name": "PowerShell", "bytes": "68403" }, { "name": "Puppet", "bytes": "4329" } ], "symlink_target": "" }
.timeline-record-bar { position: absolute; height: 12px; } .timeline-record-bar > .segment { position: absolute; height: 100%; background-color: hsl(0, 0%, 88%); border: 1px solid hsl(0, 0%, 78%); border-radius: 3px; min-width: 4px; z-index: 1; } .timeline-record-bar:not(.has-inactive-segment) > .segment { left: 0; width: 100%; } .timeline-record-bar > .segment.inactive { z-index: 0; } .timeline-record-bar > .segment.inactive, .timeline-record-bar.unfinished > .segment { border-top-right-radius: 0 !important; border-bottom-right-radius: 0 !important; border-right: none; } .timeline-record-bar.has-inactive-segment > .segment:not(.inactive) { border-top-left-radius: 0 !important; border-bottom-left-radius: 0 !important; } :matches(:focus, .force-focus) .selected .timeline-record-bar > .segment { background-color: white !important; border: none !important; } :matches(:focus, .force-focus) .selected .timeline-record-bar > .segment.inactive { background-color: hsl(215, 63%, 85%) !important; } :matches(:focus, .force-focus) .selected .timeline-record-bar.has-inactive-segment > .segment:not(.inactive) { border-left: 1px solid hsla(215, 67%, 53%, 0.7) !important; } .timeline-record-bar.timeline-record-type-network > .segment { background-color: hsl(207, 63%, 67%); border-color: hsl(202, 55%, 51%); } .timeline-record-bar.timeline-record-type-network > .segment.inactive { background-color: hsl(208, 66%, 79%); border-color: hsl(202, 57%, 68%); } .timeline-record-bar.timeline-record-type-layout > .segment { background-color: hsl(0, 65%, 75%); border-color: hsl(0, 54%, 62%); } .timeline-record-bar.timeline-record-type-layout.layout-timeline-record-paint > .segment, .timeline-record-bar.timeline-record-type-layout.layout-timeline-record-composite > .segment { background-color: hsl(76, 49%, 60%); border-color: hsl(79, 45%, 51%); } .timeline-record-bar.timeline-record-type-script > .segment { background-color: hsl(269, 65%, 74%); border-color: hsl(273, 33%, 58%); }
{ "content_hash": "a92c8e5b591a12678bab8806c07367d3", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 110, "avg_line_length": 27.584415584415584, "alnum_prop": 0.6685499058380414, "repo_name": "artygus/webkit-webinspector", "id": "45d5dfe96ca11621ad445268483de8f18299c631", "size": "3478", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/WebInspectorUI/latest/Views/TimelineRecordBar.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1009335" }, { "name": "HTML", "bytes": "103706" }, { "name": "JavaScript", "bytes": "12679719" } ], "symlink_target": "" }
(function() { var app = angular.module('starter', ['ionic', 'ngSQLite', 'ionicLazyLoad', 'angular-image-404', 'ngCordova', 'jett.ionic.filter.bar', 'oc.lazyLoad', 'starter.services', 'starter.router', 'starter.directives' ]); /** * # 设置APP项目配置文件 * @class angular.constant * @author GadflyBSD */ app.constant('configs', { db_name: 'app_ionic.db', url: { restful: 'http://gadfly.cn/manage.php?s=/Restful/angular.html', upload: 'http://gadfly.cn/manage.php?s=/File/uploadPicture.html', }, state: { home: 'app.home', my: 'app.my', login: 'app.login', register: 'app.register' }, model: { user: 'appUser' } }); /** * # RUN * @class angular.run * @author GadflyBSD */ app.run(function(service, $rootScope, $ionicPlatform){ if(!service.isInitialRun()){ service.sqlite({ type: 'createTableFromJson', file: 'www/json/position.json' }).then(function(){ service.setInitialRun(true); }, function(error){ console.log(error) }); } $ionicPlatform.ready(function () { if(window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard){ cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); cordova.plugins.Keyboard.disableScroll(true); } if(window.StatusBar){ window.StatusBar.styleDefault(); window.StatusBar.styleLightContent(); } /*if (unit.isEmptyObject($window.localStorage.device)) { var device = $cordovaDevice.getDevice(); $window.localStorage.setItem("device", JSON.stringify(device)); }*/ }); }); /** * # Config * @class angular.config * @author GadflyBSD */ app.config(function($stateProvider, $urlRouterProvider, $httpProvider, $ionicConfigProvider) { $httpProvider.defaults.headers = { post: {'Content-Type': 'application/x-www-form-urlencoded'}, get: {'Content-Type': 'application/x-www-form-urlencoded'}, put: {'Content-Type': 'application/x-www-form-urlencoded'}, delete: {'Content-Type': 'application/x-www-form-urlencoded'} } $httpProvider.defaults.transformRequest = function (obj) { var str = []; for (var p in obj) { str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&"); }; $ionicConfigProvider.platform.android.tabs.style('standard'); $ionicConfigProvider.platform.android.tabs.position('bottom'); $ionicConfigProvider.platform.android.navBar.alignTitle('center'); $ionicConfigProvider.platform.android.backButton.previousTitleText('').icon('ion-android-arrow-back'); $ionicConfigProvider.platform.android.views.transition('android'); }); }());
{ "content_hash": "0bc6b2494b7a92c4f93f27b4b7c6bd66", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 104, "avg_line_length": 29.08888888888889, "alnum_prop": 0.6684491978609626, "repo_name": "GadflyBSD/thinkAPP", "id": "3f190f1cb6092b3ac1992a20e5089a3d7d714b20", "size": "2634", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app_www/javascript/starter.js", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "203" }, { "name": "CSS", "bytes": "9007346" }, { "name": "CoffeeScript", "bytes": "167262" }, { "name": "HTML", "bytes": "6664000" }, { "name": "JavaScript", "bytes": "56599756" }, { "name": "Makefile", "bytes": "3249" }, { "name": "PHP", "bytes": "1530338" }, { "name": "Shell", "bytes": "1217" }, { "name": "Smarty", "bytes": "8226" } ], "symlink_target": "" }
/** * Populate DB with sample data on server start * to disable, edit config/environment/index.js, and set `seedDB: false` */ 'use strict'; var User = require('../models/user.model'); var config = require('./environment'); var userEmail = config.adminUser; var userPass = config.adminPass; User.find({}).remove(function() { User.create({ provider: 'local', role: 'admin', name: 'Admin', email: userEmail, password: userPass }, function() { console.log('finished populating users'); } ); });
{ "content_hash": "20f5bb23df59ee3d4a691fc8add5ae5e", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 72, "avg_line_length": 21.36, "alnum_prop": 0.6423220973782772, "repo_name": "MagRelo/weatherbot", "id": "8188bc6b348a136dbc83f595475a27c6e587f489", "size": "534", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dist/server/config/seed.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1302" }, { "name": "JavaScript", "bytes": "59170" } ], "symlink_target": "" }
 #include <aws/cloudsearch/model/DefineSuggesterRequest.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> using namespace Aws::CloudSearch::Model; using namespace Aws::Utils; DefineSuggesterRequest::DefineSuggesterRequest() : m_domainNameHasBeenSet(false), m_suggesterHasBeenSet(false) { } Aws::String DefineSuggesterRequest::SerializePayload() const { Aws::StringStream ss; ss << "Action=DefineSuggester&"; if(m_domainNameHasBeenSet) { ss << "DomainName=" << StringUtils::URLEncode(m_domainName.c_str()) << "&"; } if(m_suggesterHasBeenSet) { m_suggester.OutputToStream(ss, "Suggester"); } ss << "Version=2013-01-01"; return ss.str(); } void DefineSuggesterRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const { uri.SetQueryString(SerializePayload()); }
{ "content_hash": "9434b262e8e371a181f582dbdcb4b214", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 79, "avg_line_length": 22.342105263157894, "alnum_prop": 0.7196702002355713, "repo_name": "jt70471/aws-sdk-cpp", "id": "6ddc49a2b9371c0e4c9b17f9d235314fd7846cf3", "size": "968", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "aws-cpp-sdk-cloudsearch/source/model/DefineSuggesterRequest.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "13452" }, { "name": "C++", "bytes": "278594037" }, { "name": "CMake", "bytes": "653931" }, { "name": "Dockerfile", "bytes": "5555" }, { "name": "HTML", "bytes": "4471" }, { "name": "Java", "bytes": "302182" }, { "name": "Python", "bytes": "110380" }, { "name": "Shell", "bytes": "4674" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.skyscreamer</groupId> <artifactId>yoga-demos</artifactId> <version>1.0.7-SNAPSHOT</version> </parent> <artifactId>yoga-demo-shared</artifactId> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.skyscreamer</groupId> <artifactId>yoga-core</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.skyscreamer</groupId> <artifactId>yoga-hibernate</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.5.1-Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.5.1-Final</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.3.166</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.5.8</version> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.8.0.GA</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20090211</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.6.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.skyscreamer</groupId> <artifactId>jsonassert</artifactId> <version>0.9.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>14.0.1</version> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <dependency> <groupId>org.tuckey</groupId> <artifactId>urlrewritefilter</artifactId> <version>3.2.0</version> </dependency> <!-- These are added so that configuration is easier in the children. --> <dependency> <groupId>org.mortbay.jetty</groupId> <artifactId>servlet-api-2.5</artifactId> <version>6.0.2</version> </dependency> <dependency> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty</artifactId> <version>6.1.24</version> </dependency> <dependency> <groupId>org.mortbay.jetty</groupId> <artifactId>jsp-api-2.1</artifactId> <version>6.1.14</version> </dependency> <dependency> <groupId>tomcat</groupId> <artifactId>jasper-compiler-jdt</artifactId> <version>5.5.15</version> </dependency> <dependency> <groupId>tomcat</groupId> <artifactId>jasper-compiler</artifactId> <version>5.5.15</version> </dependency> <dependency> <groupId>tomcat</groupId> <artifactId>jasper-runtime</artifactId> <version>5.5.15</version> </dependency> </dependencies> <repositories> <repository> <id>jboss-public-repository-group</id> <name>JBoss Public Repository Group</name> <url>http://repository.jboss.org/nexus/content/groups/public/</url> <layout>default</layout> <releases> <enabled>true</enabled> <updatePolicy>never</updatePolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>never</updatePolicy> </snapshots> </repository> <repository> <id>terracotta-releases</id> <url>http://www.terracotta.org/download/reflector/releases</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>jboss-public-repository-group</id> <name>JBoss Public Repository Group</name> <url>http://repository.jboss.org/nexus/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> </project>
{ "content_hash": "9cd93b865b3beda20e0df6101b799976", "timestamp": "", "source": "github", "line_count": 191, "max_line_length": 204, "avg_line_length": 35.23560209424084, "alnum_prop": 0.549925705794948, "repo_name": "skyscreamer/yoga", "id": "c903d006e3a2fe0fd01a861fa6db44890bb45198", "size": "6730", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "yoga-demos/yoga-demo-shared/pom.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "15422" }, { "name": "Java", "bytes": "272680" }, { "name": "JavaScript", "bytes": "188192" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mathcomp-fingroup: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">8.11.dev / mathcomp-fingroup - 1.6.2</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> mathcomp-fingroup <small> 1.6.2 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-02-20 10:20:10 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-02-20 10:20:10 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.11.dev Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.0 Official release 4.09.0 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; name: &quot;coq-mathcomp-fingroup&quot; version: &quot;1.6.2&quot; maintainer: &quot;Mathematical Components &lt;mathcomp-dev@sympa.inria.fr&gt;&quot; homepage: &quot;http://math-comp.github.io/math-comp/&quot; bug-reports: &quot;Mathematical Components &lt;mathcomp-dev@sympa.inria.fr&gt;&quot; license: &quot;CeCILL-B&quot; build: [ make &quot;-C&quot; &quot;mathcomp/fingroup&quot; &quot;-j&quot; &quot;%{jobs}%&quot; ] install: [ make &quot;-C&quot; &quot;mathcomp/fingroup&quot; &quot;install&quot; ] remove: [ &quot;sh&quot; &quot;-c&quot; &quot;rm -rf &#39;%{lib}%/coq/user-contrib/mathcomp/fingroup&#39;&quot; ] depends: [ &quot;ocaml&quot; &quot;coq-mathcomp-ssreflect&quot; {= &quot;1.6.2&quot;} ] tags: [ &quot;keyword:finite groups&quot; &quot;keyword:small scale reflection&quot; &quot;keyword:mathematical components&quot; &quot;keyword:odd order theorem&quot; ] authors: [ &quot;Jeremy Avigad &lt;&gt;&quot; &quot;Andrea Asperti &lt;&gt;&quot; &quot;Stephane Le Roux &lt;&gt;&quot; &quot;Yves Bertot &lt;&gt;&quot; &quot;Laurence Rideau &lt;&gt;&quot; &quot;Enrico Tassi &lt;&gt;&quot; &quot;Ioana Pasca &lt;&gt;&quot; &quot;Georges Gonthier &lt;&gt;&quot; &quot;Sidi Ould Biha &lt;&gt;&quot; &quot;Cyril Cohen &lt;&gt;&quot; &quot;Francois Garillot &lt;&gt;&quot; &quot;Alexey Solovyev &lt;&gt;&quot; &quot;Russell O&#39;Connor &lt;&gt;&quot; &quot;Laurent Théry &lt;&gt;&quot; &quot;Assia Mahboubi &lt;&gt;&quot; ] synopsis: &quot;Mathematical Components Library on finite groups&quot; description: &quot;&quot;&quot; This library contains definitions and theorems about finite groups, group quotients, group morphisms, group presentation, group action...&quot;&quot;&quot; url { src: &quot;http://github.com/math-comp/math-comp/archive/mathcomp-1.6.2.tar.gz&quot; checksum: &quot;md5=cf10cb16f1ac239a9d52c029a4e00f66&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-mathcomp-fingroup.1.6.2 coq.8.11.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.dev). The following dependencies couldn&#39;t be met: - coq-mathcomp-fingroup -&gt; coq-mathcomp-ssreflect = 1.6.2 -&gt; coq &lt; 8.6~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-fingroup.1.6.2</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "c4ba26ebecfc6dc6fd01f58bd5a38161", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 554, "avg_line_length": 46.472727272727276, "alnum_prop": 0.5612936880542514, "repo_name": "coq-bench/coq-bench.github.io", "id": "95c84dc58b7b524cd3dea30f6d5d6548e66c7cc4", "size": "7671", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.09.0-2.0.5/extra-dev/8.11.dev/mathcomp-fingroup/1.6.2.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php namespace Applisun\CompteBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Applisun\CompteBundle\Entity\Category; use Applisun\CompteBundle\Form\CategoryType; /** * Category controller. * */ class CategoryController extends Controller { /** * Lists all Category entities. * */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $entities = $em->getRepository('ApplisunCompteBundle:Category')->findAll(); return $this->render('ApplisunCompteBundle:Category:index.html.twig', array( 'entities' => $entities, )); } /** * Creates a new Category entity. * */ public function createAction(Request $request) { $entity = new Category(); $form = $this->createCreateForm($entity); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('category')); } return $this->render('ApplisunCompteBundle:Category:new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), )); } /** * Creates a form to create a Category entity. * * @param Category $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createCreateForm(Category $entity) { $form = $this->createForm(new CategoryType(), $entity, array( 'action' => $this->generateUrl('category_create'), 'method' => 'POST', )); $form->add('submit', 'submit', array('label' => 'Create')); return $form; } /** * Displays a form to create a new Category entity. * */ public function newAction() { $entity = new Category(); $form = $this->createCreateForm($entity); return $this->render('ApplisunCompteBundle:Category:new.html.twig', array( 'entity' => $entity, 'form' => $form->createView(), )); } /** * Finds and displays a Category entity. * */ public function showAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('ApplisunCompteBundle:Category')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Category entity.'); } $deleteForm = $this->createDeleteForm($id); return $this->render('ApplisunCompteBundle:Category:show.html.twig', array( 'entity' => $entity, 'delete_form' => $deleteForm->createView(), )); } /** * Displays a form to edit an existing Category entity. * */ public function editAction($id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('ApplisunCompteBundle:Category')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Category entity.'); } $editForm = $this->createEditForm($entity); return $this->render('ApplisunCompteBundle:Category:edit.html.twig', array( 'entity' => $entity, 'edit_form' => $editForm->createView(), )); } /** * Creates a form to edit a Category entity. * * @param Category $entity The entity * * @return \Symfony\Component\Form\Form The form */ private function createEditForm(Category $entity) { $form = $this->createForm(new CategoryType(), $entity, array( 'action' => $this->generateUrl('category_update', array('id' => $entity->getId())), 'method' => 'POST', )); $form->add('submit', 'submit', array('label' => 'Update')); return $form; } /** * Edits an existing Category entity. * */ public function updateAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('ApplisunCompteBundle:Category')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Category entity.'); } $editForm = $this->createEditForm($entity); $editForm->handleRequest($request); if ($editForm->isValid()) { $em->flush(); return $this->redirect($this->generateUrl('category')); } return $this->render('ApplisunCompteBundle:Category:edit.html.twig', array( 'entity' => $entity, 'edit_form' => $editForm->createView(), )); } /** * Deletes a Category entity. * */ public function deleteAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('ApplisunCompteBundle:Category')->find($id); if (!$entity) { throw $this->createNotFoundException('Impossible de trouver Category entity.'); } $em->remove($entity); $em->flush(); $request->getSession()->getFlashBag()->add('success', 'Category supprimée avec succès.'); return $this->redirect($this->generateUrl('category')); } /** * Creates a form to delete a Category entity by id. * * @param mixed $id The entity id * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm($id) { return $this->createFormBuilder() ->setAction($this->generateUrl('category_delete', array('id' => $id))) ->setMethod('DELETE') ->add('submit', 'submit', array('label' => 'Delete')) ->getForm() ; } }
{ "content_hash": "e77b50702187df2df59adf56ee214dcd", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 107, "avg_line_length": 27.929906542056074, "alnum_prop": 0.5546260665885896, "repo_name": "frederic3476/compte", "id": "8176544a1ac380ecea401fe9e5323cb6a42bb7f8", "size": "5979", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Applisun/CompteBundle/Controller/CategoryController.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "Batchfile", "bytes": "385" }, { "name": "CSS", "bytes": "302656" }, { "name": "HTML", "bytes": "177926" }, { "name": "JavaScript", "bytes": "1529386" }, { "name": "PHP", "bytes": "209623" }, { "name": "Shell", "bytes": "617" } ], "symlink_target": "" }
/* label, h1, h2, h3, h4, h5, h6, td, th, .text { -webkit-touch-callout: none; -webkit-user-select: none; } */ html { -webkit-user-select: none; } #splash{ position: fixed; width: 100%; height: 100%; left: 0; top: 0; background: #004D60; z-index: 0; } #logo-area{ display: inline-block; position: relative; top: 10%; font-size: 20pt; font-style: bold; color: white; text-align: center; } .clean-input { color: #333 !important; padding: 5px !important; border: none !important; border-bottom: solid thin #ccc !important; box-shadow: none !important; border-radius: 10px !important; outline: none !important; } .clean-input:focus { outline: 0 !important; outline-width: 0 !important; border-bottom-color: rgba(82, 168, 236, 0.8) !important; } .main-content{ padding-top: 25px; } .animated { -webkit-transition: height 0.2s; -moz-transition: height 0.2s; transition: height 0.2s; } .onoffswitch { position: relative; width: 90px; -webkit-user-select:none; -moz-user-select:none; -ms-user-select: none; } .onoffswitch-checkbox { display: none; } .onoffswitch-label { display: block; overflow: hidden; cursor: pointer; border: 2px solid #999999; border-radius: 0px; } .onoffswitch-inner { width: 200%; margin-left: -100%; -moz-transition: margin 0.3s ease-in 0s; -webkit-transition: margin 0.3s ease-in 0s; -o-transition: margin 0.3s ease-in 0s; transition: margin 0.3s ease-in 0s; } .onoffswitch-inner:before, .onoffswitch-inner:after { float: left; width: 50%; height: 30px; padding: 0; line-height: 26px; font-size: 14px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; border: 2px solid transparent; background-clip: padding-box; } .onoffswitch-inner:before { content: ""; padding-left: 10px; background-color: #3186F5; color: #FFFFFF; } .onoffswitch-inner:after { content: ""; padding-right: 10px; background-color: #CCCCCC; color: #333333; text-align: right; } .onoffswitch-switch { width: 25px; margin: 0px; background: #000000; position: absolute; top: 0; bottom: 0; right: 65px; -moz-transition: all 0.3s ease-in 0s; -webkit-transition: all 0.3s ease-in 0s; -o-transition: all 0.3s ease-in 0s; transition: all 0.3s ease-in 0s; } .onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner { margin-left: 0; } .onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch { right: 0px; }
{ "content_hash": "e1dc4f18aeebf4778525bb23d657cda7", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 96, "avg_line_length": 24.88679245283019, "alnum_prop": 0.6614859742228961, "repo_name": "tuanpembual/Testing", "id": "a92964ff33a178dd1b460fed38d8edefdd2f6a3c", "size": "2638", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jokoapp/lib/workspace.css", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "7263" }, { "name": "CSS", "bytes": "141303" }, { "name": "JavaScript", "bytes": "1082652" }, { "name": "Ruby", "bytes": "503" }, { "name": "Shell", "bytes": "68489" }, { "name": "Vala", "bytes": "336559" } ], "symlink_target": "" }
.. This is auto-generated from `CHANGELOG.md`. Do not edit this file directly. :Date: November 30, 2021 .. contents:: :depth: 3 .. Revision history for Pantable ============================= - v0.14.2: Support pandoc 2.15–16 - improve test matrix in GitHub Actions - update dependency constraints - v0.14.1: identical to v0.14.2 - v0.14.0: Support pandoc 2.14 - close #61 - requires panflute >= 2.1 - add ``environment.yml`` for an example conda environment running pantable - remove ``pantable.util.PandocVersion`` as it is merged upstream in ``panflute.tools.PandocVersion``. - v0.13.6: Fix #57; update dependencies. - v0.13.5: Fix a division error when all widths are zero. - v0.13.4: Fix converting from native table that contains footnotes. See #58. - v0.13.3: packaging change only: allow Python4 - v0.13.2: packaging change only: specified required versions for all dependencies including extras - v0.13.1: util.py: fix ``iter_convert_texts_markdown_to_panflute`` - v0.13:added pandoc 2.11.0.4+ & panflute 2+ support - pandoc 2.10 introduces a new table AST. This version provides complete support of all features supported in the pandoc AST. Hence, older pandoc versions are no longer supported. Install ``pantable=0.12.4`` if you need to use ``pandoc<2.10``. - deprecated ``pipe_tables``, ``grid_tables``, ``raw_markdown`` options in pantable, which were introduced in v0.12. pantable v0.13 has a much better way to process markdown cells that these are no longer needed. - slight changes on markdown output which should be functionally identical. Both changes in pandoc and pantable cause this. See commit eadc6fb. - add ``short-caption``, ``alignment-cells``, ``fancy_table``, ``format``, ``ms``, ``ns_head``. See docs for details. - v0.12.4: Require panflute<2 explicitly - panflute 2 is released to support pandoc API 1.22. This release ensures that version control is correct when people specify pantable==0.12 in the future. - v0.12.3: Fixes test and CI; update on supported Python versions - migrate from Travis CI to GitHub Actions - supported Python versions are now 3.5-3.8, pypy3 - minor update in README - v0.12.2: Add ``grid_tables`` - v0.12.1: add ``include-encoding``, ``csv-kwargs`` - closes #36, #38. See doc for details on this new keys. - v0.12: Drop Python 2 support; enhance CSV with markdown performance - Dropping Python2 support, existing Python 2 users should be fine with pip>=9.0. See https://python3statement.org/practicalities/. - add ``pipe_tables``, ``raw_markdown`` options. See README for details. This for example will speed up CSV with markdown cells a lot (trading correctness for speed though.)
{ "content_hash": "119f1382f8c2b0afc199aa9b5acb5ad2", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 247, "avg_line_length": 48.19298245614035, "alnum_prop": 0.7084091736439753, "repo_name": "ickc/pantable", "id": "74d6c65eb0b551bef355ef3bcfa5819186ccfcf1", "size": "2749", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CHANGELOG.rst", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Makefile", "bytes": "4567" }, { "name": "Python", "bytes": "100802" } ], "symlink_target": "" }
<?php namespace Everon\Component\Utils\Popo; use Everon\Component\Utils\Collection\ArrayableInterface; interface PopoInterface extends ArrayableInterface { /** * @return array */ public function getData(); /** * @param array $data */ public function setData(array $data); }
{ "content_hash": "6ee15540dc0ce4d93268939995c51996", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 57, "avg_line_length": 15.8, "alnum_prop": 0.6645569620253164, "repo_name": "oliwierptak/everon-utils", "id": "a1f98aa66290a0e06f00634ebedd110bb815850f", "size": "545", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "src/Popo/PopoInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "27289" } ], "symlink_target": "" }
<?php defined('BX_DOL') or die('hack attempt'); class BxSMTPDb extends BxDolModuleDb { function __construct(&$oConfig) { parent::__construct($oConfig); } } /** @} */
{ "content_hash": "4c248d4fb7354a4bbf2851f4bd7808fb", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 47, "avg_line_length": 15.75, "alnum_prop": 0.582010582010582, "repo_name": "camperjz/trident", "id": "f31199cfafcfb9c3ac2afdb377a1cf14bf8d1f75", "size": "402", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "modules/boonex/smtpmailer/updates/8.0.2_8.0.3/source/classes/BxSMTPDb.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1763" }, { "name": "CSS", "bytes": "1481231" }, { "name": "HTML", "bytes": "690596" }, { "name": "JavaScript", "bytes": "4916309" }, { "name": "PHP", "bytes": "28451148" }, { "name": "Shell", "bytes": "1265" } ], "symlink_target": "" }
package es.tid.pce.computingEngine.algorithms.wson; import java.net.Inet4Address; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.jgrapht.GraphPath; import org.jgrapht.alg.KShortestPaths; import org.jgrapht.graph.SimpleDirectedWeightedGraph; import es.tid.pce.computingEngine.ComputingRequest; import es.tid.pce.computingEngine.ComputingResponse; import es.tid.pce.computingEngine.algorithms.AlgorithmReservation; import es.tid.pce.computingEngine.algorithms.ComputingAlgorithm; import es.tid.pce.computingEngine.algorithms.PCEPUtils; import es.tid.pce.computingEngine.algorithms.wson.wa.FirstFit; import es.tid.pce.pcep.constructs.EndPoint; import es.tid.pce.pcep.constructs.EndPointAndRestrictions; import es.tid.pce.pcep.constructs.P2MPEndpoints; import es.tid.pce.pcep.constructs.P2PEndpoints; import es.tid.pce.pcep.constructs.Path; import es.tid.pce.pcep.constructs.Request; import es.tid.pce.pcep.constructs.Response; import es.tid.pce.pcep.objects.EndPoints; import es.tid.pce.pcep.objects.EndPointsIPv4; import es.tid.pce.pcep.objects.ExplicitRouteObject; import es.tid.pce.pcep.objects.GeneralizedEndPoints; import es.tid.pce.pcep.objects.NoPath; import es.tid.pce.pcep.objects.ObjectParameters; import es.tid.pce.pcep.objects.RequestParameters; import es.tid.pce.pcep.objects.tlvs.NoPathTLV; import es.tid.pce.server.wson.ReservationManager; import es.tid.rsvp.RSVPProtocolViolationException; import es.tid.rsvp.constructs.gmpls.DWDMWavelengthLabel; import es.tid.rsvp.objects.subobjects.GeneralizedLabelEROSubobject; import es.tid.rsvp.objects.subobjects.IPv4prefixEROSubobject; import es.tid.rsvp.objects.subobjects.UnnumberIfIDEROSubobject; import es.tid.tedb.DomainTEDB; import es.tid.tedb.IntraDomainEdge; import es.tid.tedb.TEDB; import es.tid.tedb.WSONInformation; public class KSP_FF_Algorithm implements ComputingAlgorithm { private WSONInformation WSONInfo; private Logger log=LoggerFactory.getLogger("PCEServer"); private DomainTEDB ted; private GenericLambdaReservation reserv; private ReservationManager reservationManager; private KSP_FF_AlgorithmPreComputation preComp; private ComputingRequest pathReq; public KSP_FF_Algorithm(ComputingRequest pathReq,TEDB ted, ReservationManager reservationManager ){ //this.num_lambdas=((DomainTEDB)ted).getNumLambdas(); this.pathReq=pathReq; this.reservationManager=reservationManager; this.ted=(DomainTEDB)ted; } public ComputingResponse call(){ //Time stamp of the start of the algorithm; long tiempoini =System.nanoTime(); log.debug("Starting KSPprecomp Algorithm"); //Create the response message //It will contain either the path or noPath ComputingResponse m_resp=new ComputingResponse(); m_resp.setEncodingType(pathReq.getEcodingType()); //The request that needs to be solved Request req=pathReq.getRequestList().get(0); //Request Id, needed for the response long reqId=req.getRequestParameters().getRequestID(); log.info("Request id: "+reqId+", getting endpoints"); //Start creating the response Response response=new Response(); RequestParameters rp = new RequestParameters(); rp.setBidirect(req.getRequestParameters().isBidirect()); rp.setRequestID(reqId); response.setRequestParameters(rp); m_resp.addResponse(response); EndPoints EP= req.getEndPoints(); Object source_router_id_addr = null; Object dest_router_id_addr = null; if (EP.getOT()==ObjectParameters.PCEP_OBJECT_TYPE_ENDPOINTS_IPV4){ EndPointsIPv4 ep=(EndPointsIPv4) req.getEndPoints(); source_router_id_addr=ep.getSourceIP(); dest_router_id_addr=ep.getDestIP(); }else if (EP.getOT()==ObjectParameters.PCEP_OBJECT_TYPE_ENDPOINTS_IPV6){ }else if (EP.getOT()==ObjectParameters.PCEP_OBJECT_TYPE_GENERALIZED_ENDPOINTS){ GeneralizedEndPoints gep=(GeneralizedEndPoints) req.getEndPoints(); if(gep.getGeneralizedEndPointsType()==ObjectParameters.PCEP_GENERALIZED_END_POINTS_TYPE_P2P){ P2PEndpoints p2pep= gep.getP2PEndpoints(); EndPoint sourceep=p2pep.getSourceEndPoint(); EndPoint destep=p2pep.getDestinationEndPoint(); source_router_id_addr=sourceep.getEndPointIPv4TLV().IPv4address; dest_router_id_addr=destep.getEndPointIPv4TLV().IPv4address; } if(gep.getGeneralizedEndPointsType()==ObjectParameters.PCEP_GENERALIZED_END_POINTS_TYPE_P2MP_NEW_LEAVES){ P2MPEndpoints p2mpep= gep.getP2MPEndpoints(); EndPointAndRestrictions epandrest=p2mpep.getEndPointAndRestrictions(); EndPoint sourceep=epandrest.getEndPoint(); source_router_id_addr=sourceep.getEndPointIPv4TLV().IPv4address; int cont=0; while (cont<=p2mpep.getEndPointAndRestrictionsList().size()){ //esto est� mal epandrest=p2mpep.getEndPointAndRestrictionsList().get(cont); EndPoint destep=epandrest.getEndPoint(); source_router_id_addr=sourceep.getEndPointIPv4TLV().IPv4address; dest_router_id_addr=destep.getEndPointIPv4TLV().IPv4address; } } } //Now, check if the source and destination are in the TED. log.debug("Source: "+source_router_id_addr+"; Destination:"+dest_router_id_addr); if (!(((ted.containsVertex(source_router_id_addr))&&(ted.containsVertex(dest_router_id_addr))))){ log.warn("Source or destination are NOT in the TED"); NoPath noPath= new NoPath(); noPath.setNatureOfIssue(ObjectParameters.NOPATH_NOPATH_SAT_CONSTRAINTS); NoPathTLV noPathTLV=new NoPathTLV(); if (!((ted.containsVertex(source_router_id_addr)))){ log.debug("Unknown source"); noPathTLV.setUnknownSource(true); } if (!((ted.containsVertex(dest_router_id_addr)))){ log.debug("Unknown destination"); noPathTLV.setUnknownDestination(true); } noPath.setNoPathTLV(noPathTLV); response.setNoPath(noPath); return m_resp; } boolean nopath=false;//Initially, we still have no path int lambda_chosen=0;//We begin with lambda index 0 GraphPath<Object,IntraDomainEdge> gp_chosen=null; boolean noLambda = true; SimpleDirectedWeightedGraph<Object, IntraDomainEdge> Graph; int k = 1; log.debug("Starting the selection of the path"); KShortestPaths<Object,IntraDomainEdge> ksp = new KShortestPaths<Object,IntraDomainEdge> (preComp.getNetworkGraph(), source_router_id_addr, k); List<GraphPath<Object,IntraDomainEdge>> routeList = ksp.getPaths(dest_router_id_addr); //list of the path edges if (routeList.isEmpty()==true){ nopath = true; log.info("No path found"); NoPath noPath= new NoPath(); noPath.setNatureOfIssue(ObjectParameters.NOPATH_NOPATH_SAT_CONSTRAINTS); NoPathTLV noPathTLV=new NoPathTLV(); noPath.setNoPathTLV(noPathTLV); response.setNoPath(noPath); return m_resp; } int j =0; if (nopath==false){ for (j=0; j<routeList.size(); j++) { gp_chosen = routeList.get(j); Path path=new Path(); ExplicitRouteObject ero= new ExplicitRouteObject(); List<IntraDomainEdge> edge_list=gp_chosen.getEdgeList(); //FirstFit returns the lambda for the path lambda_chosen = FirstFit.getLambda(edge_list); //FF returns "-1" in case there is no lambda free for path if (lambda_chosen == -1) { noLambda = true; continue; } noLambda = false; //in case there is a lambda free for path int i; for (i=0;i<edge_list.size();i++){ UnnumberIfIDEROSubobject eroso= new UnnumberIfIDEROSubobject(); eroso.setRouterID((Inet4Address)edge_list.get(i).getSource()); eroso.setInterfaceID(edge_list.get(i).getSrc_if_id()); eroso.setLoosehop(false); ero.addEROSubobject(eroso); GeneralizedLabelEROSubobject genLabel= new GeneralizedLabelEROSubobject(); ero.addEROSubobject(genLabel); //ITU-T Format DWDMWavelengthLabel WDMlabel=new DWDMWavelengthLabel(); WDMlabel.setGrid(preComp.getWSONInfo().getGrid()); WDMlabel.setChannelSpacing(preComp.getWSONInfo().getCs()); WDMlabel.setN(lambda_chosen+preComp.getWSONInfo().getnMin()); WDMlabel.setIdentifier(0); try { WDMlabel.encode(); } catch (RSVPProtocolViolationException e) { // TODO Auto-generated catch block e.printStackTrace(); } genLabel.setLabel(WDMlabel.getBytes()); } IPv4prefixEROSubobject eroso= new IPv4prefixEROSubobject(); eroso.setIpv4address((Inet4Address)edge_list.get(edge_list.size()-1).getTarget()); eroso.setPrefix(32); ero.addEROSubobject(eroso); path.setEro(ero); PCEPUtils.completeMetric(path, req, edge_list); response.addPath(path); //FIXME: RESERVATION NEEDS TO BE IMPROVED!!! LinkedList<Object> sourceVertexList=new LinkedList<Object>(); LinkedList<Object> targetVertexList=new LinkedList<Object>(); for (i=0;i<edge_list.size();i++){ sourceVertexList.add(edge_list.get(i).getSource()); targetVertexList.add(edge_list.get(i).getTarget()); } if (req.getReservation()!=null){ reserv= new GenericLambdaReservation(); reserv.setResp(m_resp); reserv.setLambda_chosen(lambda_chosen); reserv.setReservation(req.getReservation()); reserv.setSourceVertexList(sourceVertexList); reserv.setTargetVertexList(targetVertexList); if (rp.isBidirect() == true){ reserv.setBidirectional(true); } else{ reserv.setBidirectional(false); } reserv.setReservationManager(reservationManager); } break; } } long tiempofin =System.nanoTime(); long tiempotot=tiempofin-tiempoini; log.info("Ha tardado "+tiempotot+" nanosegundos"); if (noLambda == true){ log.debug("No path found"); NoPath noPath= new NoPath(); noPath.setNatureOfIssue(ObjectParameters.NOPATH_NOPATH_SAT_CONSTRAINTS); NoPathTLV noPathTLV=new NoPathTLV(); noPath.setNoPathTLV(noPathTLV); response.setNoPath(noPath); return m_resp; } return m_resp; } public void setPreComp(KSP_FF_AlgorithmPreComputation preComp) { this.preComp = preComp; } public AlgorithmReservation getReserv() { return reserv; } }
{ "content_hash": "29a15aeab97b2915e75404a5260afda7", "timestamp": "", "source": "github", "line_count": 286, "max_line_length": 144, "avg_line_length": 35.41608391608391, "alnum_prop": 0.736696613683483, "repo_name": "telefonicaid/netphony-pce", "id": "5c2ec30fb36d96512f95b3b431952da48e4aa332", "size": "10131", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/es/tid/pce/computingEngine/algorithms/wson/KSP_FF_Algorithm.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1854336" } ], "symlink_target": "" }
package com.example.android.persistence.migrations; import androidx.annotation.MainThread; /** * Callback used in notifying when the user has been updated. */ public interface UpdateUserCallback { /** * Method called when the user was updated. * * @param user the updated user. */ @MainThread void onUserUpdated(User user); }
{ "content_hash": "d38533469e8bbb38f77aa6cb5708bb60", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 61, "avg_line_length": 19.210526315789473, "alnum_prop": 0.6876712328767123, "repo_name": "android/architecture-components-samples", "id": "d29589c20269f5ace947c142748a0359f0cb44e8", "size": "984", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "PersistenceMigrationsSample/app/src/main/java/com/example/android/persistence/migrations/UpdateUserCallback.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "240380" }, { "name": "Kotlin", "bytes": "520626" }, { "name": "RenderScript", "bytes": "2642" }, { "name": "Shell", "bytes": "2978" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "25f443350869a85d8690802f8880079e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "e86b59d0bb4df2f5cc4fedd0c8d76410e7502675", "size": "184", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Eriocaulaceae/Syngonanthus/Syngonanthus ruprechtianus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
class TasController < ApplicationController include TasHelper before_filter :authorize_only_for_admin layout 'assignment_content' def index end def populate render json: get_tas_table_info end def new @user = Ta.new end def edit @user = Ta.find_by_id(params[:id]) end def destroy @user = Ta.find(params[:id]) if @user && @user.destroy flash_message(:success, I18n.t('tas.delete.success', user_name: @user.user_name)) else flash_message(:error, I18n.t('tas.delete.error')) end redirect_to action: :index end def update @user = Ta.find_by_id(params[:user][:id]) # update_attributes supplied by ActiveRecords if @user.update_attributes(user_params) flash(:success, I18n.t('tas.update.success', user_name: @user.user_name)) redirect_to action: :index else flash_message(:error, I18n.t('tas.update.error')) render :edit end end def create # Default attributes: role = TA or role = STUDENT # params[:user] is a hash of values passed to the controller # by the HTML form with the help of ActiveView::Helper:: @user = Ta.new(user_params) # Return unless the save is successful; save inherted from # active records--creates a new record if the model is new, otherwise # updates the existing record if @user.save flash_message(:success, I18n.t('tas.create.success', user_name: @user.user_name)) redirect_to action: 'index' # Redirect else flash_message(:error, I18n.t('tas.create.error')) render :new end end #downloads users with the given role as a csv list def download_ta_list #find all the users tas = Ta.order(:user_name) case params[:format] when 'csv' output = MarkusCSV.generate(tas) do |ta| [ta.user_name,ta.last_name,ta.first_name] end format = 'text/csv' when 'xml' output = tas.to_xml format = 'text/xml' else # Raise exception? output = tas.to_xml format = 'text/xml' end send_data(output, type: format, filename: "ta_list.#{params[:format]}", disposition: 'attachment') end def upload_ta_list if params[:userlist] User.transaction do processed_users = [] result = MarkusCSV.parse(params[:userlist], skip_blanks: true, row_sep: :auto, encoding: params[:encoding]) do |row| next if CSV.generate_line(row).strip.empty? raise CSVInvalidLineError if processed_users.include?(row[0]) raise CSVInvalidLineError if User.add_user(Ta, row).nil? processed_users.push(row[0]) end unless result[:invalid_lines].empty? flash_message(:error, result[:invalid_lines]) end unless result[:valid_lines].empty? flash_message(:success, result[:valid_lines]) end end else flash_message(:error, I18n.t('csv.invalid_csv')) end redirect_to action: 'index' end def refresh_graph @assignment = Assignment.find(params[:assignment]) @current_ta = Ta.find(params[:id]) end private def user_params params.require(:user).permit(:user_name, :last_name, :first_name) end end
{ "content_hash": "f149cd787ec4a317b12b0da6a2819e54", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 73, "avg_line_length": 27.696, "alnum_prop": 0.5932986712882726, "repo_name": "arkon/Markus", "id": "39c02ac8fbe58cc9299d9930fef95cf0ffd5848c", "size": "3462", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/tas_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "270" }, { "name": "C", "bytes": "15162" }, { "name": "C++", "bytes": "3255" }, { "name": "CSS", "bytes": "118512" }, { "name": "HTML", "bytes": "600405" }, { "name": "Java", "bytes": "433411" }, { "name": "JavaScript", "bytes": "1424103" }, { "name": "Makefile", "bytes": "1233" }, { "name": "PHP", "bytes": "1518" }, { "name": "Pascal", "bytes": "1960" }, { "name": "Python", "bytes": "141717" }, { "name": "Ruby", "bytes": "2051906" }, { "name": "Shell", "bytes": "8978" }, { "name": "SourcePawn", "bytes": "257" } ], "symlink_target": "" }
#ifndef __CCSTRING_H__ #define __CCSTRING_H__ #if (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY) #include <string.h> #endif #include <stdarg.h> #include <string> #include <functional> #include "CCObject.h" NS_CC_BEGIN /** * @addtogroup data_structures * @{ */ class CC_DLL String : public Object, public Clonable { public: String(); String(const char* str); String(const std::string& str); String(const String& str); virtual ~String(); /* override assignment operator */ String& operator= (const String& other); /** init a string with format, it's similar with the c function 'sprintf' */ bool initWithFormat(const char* format, ...) CC_FORMAT_PRINTF(2, 3); /** convert to int value */ int intValue() const; /** convert to unsigned int value */ unsigned int uintValue() const; /** convert to float value */ float floatValue() const; /** convert to double value */ double doubleValue() const; /** convert to bool value */ bool boolValue() const; /** get the C string */ const char* getCString() const; /** get the length of string */ unsigned int length() const; /** compare to a c string */ int compare(const char *) const; /** append additional characters at the end of its current value */ void append(const std::string& str); /** append(w/ format) additional characters at the end of its current value */ void appendWithFormat(const char* format, ...); /** split a string */ Array* componentsSeparatedByString(const char *delimiter); /* override functions */ virtual bool isEqual(const Object* pObject); /** create a string with std string, you can also pass a c string pointer because the default constructor of std::string can access a c string pointer. * @return A String pointer which is an autorelease object pointer, * it means that you needn't do a release operation unless you retain it. */ static String* create(const std::string& str); /** create a string with format, it's similar with the c function 'sprintf', the default buffer size is (1024*100) bytes, * if you want to change it, you should modify the kMaxStringLen macro in String.cpp file. * @return A String pointer which is an autorelease object pointer, * it means that you needn't do a release operation unless you retain it. */ static String* createWithFormat(const char* format, ...) CC_FORMAT_PRINTF(1, 2); /** create a string with binary data * @return A String pointer which is an autorelease object pointer, * it means that you needn't do a release operation unless you retain it. */ static String* createWithData(const unsigned char* pData, unsigned long nLen); /** create a string with a file, * @return A String pointer which is an autorelease object pointer, * it means that you needn't do a release operation unless you retain it. */ static String* createWithContentsOfFile(const char* filename); virtual void acceptVisitor(DataVisitor &visitor); virtual String* clone() const; private: /** only for internal use */ bool initWithFormatAndValist(const char* format, va_list ap); public: std::string _string; }; struct StringCompare : public std::binary_function<String *, String *, bool> { public: bool operator() (String * a, String * b) const { return strcmp(a->getCString(), b->getCString()) < 0; } }; #define StringMake(str) String::create(str) #define ccs StringMake // end of data_structure group /// @} NS_CC_END #endif //__CCSTRING_H__
{ "content_hash": "d64352d15d7211e8557c1f27d5abe62b", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 156, "avg_line_length": 29.752, "alnum_prop": 0.6547458994353321, "repo_name": "qq2588258/floweers", "id": "f8c085bd9dc541f1e74e5d2a8e1d38a4a1436a3d", "size": "4957", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "libs/cocos2dx/cocoa/CCString.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3106673" }, { "name": "C++", "bytes": "6976740" }, { "name": "CSS", "bytes": "8089" }, { "name": "Java", "bytes": "71280" }, { "name": "JavaScript", "bytes": "12570" }, { "name": "Lua", "bytes": "567417" }, { "name": "Makefile", "bytes": "99272" }, { "name": "Objective-C", "bytes": "376842" }, { "name": "Objective-C++", "bytes": "231534" }, { "name": "Shell", "bytes": "13201" } ], "symlink_target": "" }
flake8 --max-line-length 120 --max-complexity 10 django_crud flake1=$? echo "flake django_crud exit code: ${flake1}" flake8 --max-line-length 120 --max-complexity 10 tests/ flake2=$? echo "flake tests exit code: ${flake2}" flake8 --max-line-length 120 --max-complexity 10 example_site/ flake3=$? echo "flake example_site exit code: ${flake3}" exit $((${flake1} + ${flake2} + ${flake3}))
{ "content_hash": "c2f0fdb257ec1b0b086b4bca5d61dba0", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 63, "avg_line_length": 39.8, "alnum_prop": 0.6834170854271356, "repo_name": "samuelcolvin/django-crud", "id": "cfd1a5c631461435816eae54ed71ecd56e49c80f", "size": "418", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lint.sh", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1234" }, { "name": "HTML", "bytes": "9515" }, { "name": "JavaScript", "bytes": "76" }, { "name": "Python", "bytes": "62167" }, { "name": "Shell", "bytes": "418" } ], "symlink_target": "" }
package io.scif.util; import static org.junit.Assert.assertEquals; import io.scif.FormatException; import io.scif.ImageMetadata; import io.scif.Reader; import io.scif.SCIFIO; import io.scif.io.location.TestImgLocation; import java.io.IOException; import org.junit.AfterClass; import org.junit.Test; import org.scijava.io.location.Location; /** * Unit tests for {@link FormatTools}. * * @author Mark Hiner */ public class FormatToolsTest { // -- Fields -- private static final SCIFIO scifio = new SCIFIO(); @AfterClass public static void dispose() { scifio.dispose(); } // -- Indexed color tests -- /** * Tests that the correct values are given by the various * {@link FormatTools#defaultMinMax} signatures. */ @Test public void testDefaultMinMax() throws FormatException, IOException { final Location sampleImage = TestImgLocation.builder().name("8bit-unsigned") .pixelType("int8").indexed(true).planarDims(3).lengths(50, 50, 1).axes( "X", "Y", "Channel").build(); final Reader reader = scifio.initializer().initializeReader(sampleImage); final ImageMetadata iMeta = reader.getMetadata().get(0); iMeta.setBitsPerPixel(7); // Test min/max computation using ImageMetadat directly assertEquals((long) -Math.pow(2, 6), FormatTools.defaultMinMax(iMeta)[0]); assertEquals((long) Math.pow(2, 6) - 1, FormatTools.defaultMinMax( iMeta)[1]); // Test min/max computation using bits per pixel assertEquals((long) -Math.pow(2, 6), FormatTools.defaultMinMax(iMeta .getPixelType(), iMeta.getBitsPerPixel())[0]); assertEquals((long) Math.pow(2, 6) - 1, FormatTools.defaultMinMax(iMeta .getPixelType(), iMeta.getBitsPerPixel())[1]); // Test min/max computation using bits per pixel assertEquals((long) -Math.pow(2, 7), FormatTools.defaultMinMax(iMeta .getPixelType(), -1)[0]); assertEquals((long) Math.pow(2, 7) - 1, FormatTools.defaultMinMax(iMeta .getPixelType(), -1)[1]); // Test min/max computation using pixel type assertEquals((long) -Math.pow(2, 7), FormatTools.defaultMinMax(iMeta .getPixelType())[0]); assertEquals((long) Math.pow(2, 7) - 1, FormatTools.defaultMinMax(iMeta .getPixelType())[1]); } }
{ "content_hash": "4804036a0c1f609d7c18a11d5df8dc8b", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 78, "avg_line_length": 28.855263157894736, "alnum_prop": 0.7154582763337893, "repo_name": "scifio/scifio", "id": "48a32d04866841657943c8f7a0d261e162ad69bc", "size": "3648", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/io/scif/util/FormatToolsTest.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Java", "bytes": "2611059" } ], "symlink_target": "" }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MacroSharp { public class MacroCSharpSyntaxRewriter : CSharpSyntaxRewriter { private const int MaxListRecursion = 20; protected TransformContext Context => _context; public virtual SyntaxNode Run(TransformContext context) { _context = context; return Visit(context.SyntaxNode); } private struct ListData { public List<SyntaxNode> PrependedNodes; public List<SyntaxNode> AppendedNodes; } public override SyntaxList<TNode> VisitList<TNode>(SyntaxList<TNode> list) { _listDataIndex += 1; List<SyntaxNode> alternate = null; for (int i = 0, n = list.Count; i < n; i++) { var item = list[i]; var visited = this.VisitListElement(item); var prepended = _listData[_listDataIndex].PrependedNodes; var appended = _listData[_listDataIndex].AppendedNodes; if (item != visited || (prepended != null && prepended.Count > 0) || (appended != null && appended.Count > 0)) { if (alternate == null) { alternate = new List<SyntaxNode>(n); for (int j = 0; j < i; ++j) alternate.Add(list[j]); } if (prepended != null && prepended.Count > 0) { alternate.AddRange(prepended); prepended.Clear(); } if (visited != null && !visited.IsKind(SyntaxKind.None)) alternate.Add(visited); if (appended != null && appended.Count > 0) { alternate.AddRange(appended); appended.Clear(); } } else if (alternate != null && visited != null && !visited.IsKind(SyntaxKind.None)) alternate.Add(visited); } _listDataIndex -= 1; if (alternate != null) return SyntaxFactory.List(alternate); return list; } public void AddAfterCurrentNode(SyntaxNode node) { if (_listData[_listDataIndex].AppendedNodes == null) _listData[_listDataIndex].AppendedNodes = new List<SyntaxNode>(); _listData[_listDataIndex].AppendedNodes.Add(node); } public void AddBeforeCurrentNode(SyntaxNode node) { if (_listData[_listDataIndex].PrependedNodes == null) _listData[_listDataIndex].PrependedNodes = new List<SyntaxNode>(); _listData[_listDataIndex].PrependedNodes.Add(node); } private TransformContext _context; private int _listDataIndex = -1; private ListData[] _listData = new ListData[MaxListRecursion]; } }
{ "content_hash": "54f283ab477d0f78fdc2466acc30acc8", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 98, "avg_line_length": 33.1530612244898, "alnum_prop": 0.5164666051092643, "repo_name": "russpowers/MacroSharp", "id": "5e122f217e90b551937b0ae3b7c43142ffb38f3f", "size": "3251", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MacroSharp/MacroCSharpSyntaxRewriter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "386653" } ], "symlink_target": "" }
package org.wso2.carbon.apimgt.gateway.handlers.security.keys; import org.wso2.carbon.apimgt.api.model.URITemplate; import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException; import org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO; import java.util.ArrayList; import java.util.List; /** * Represents the interface used by the APIKeyValidator to interact with the API * key manager. Different implementations of this interface may employ different * techniques/protocols to communicate with the actual key management server. */ public interface APIKeyDataStore { /** * Validate the given API key for the specified API context and version. * * @param context Context of an API * @param apiVersion A valid version of the API * @param apiKey An API key string - Not necessarily a valid key * @return an APIKeyValidationInfoDTO instance containing key validation data * @throws org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException on error */ //public APIKeyValidationInfoDTO getAPIKeyData(String context, String apiVersion, // String apiKey, String clientDomain) throws APISecurityException; /** * Validate the given API key for the specified API context and version. * * @param context Context of an API * @param apiVersion A valid version of the API * @param apiKey An API key string - Not necessarily a valid key * @param requiredAuthenticationLevel - type of key. can be one of 'Application or Application_User' * @param tenantDomain teantDomain of API * @param keyManagers list of key managers assigned to API * @return an APIKeyValidationInfoDTO instance containing key validation data * @throws org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException on error */ APIKeyValidationInfoDTO getAPIKeyData(String context, String apiVersion, String apiKey, String requiredAuthenticationLevel, String clientDomain, String matchingResource, String httpVerb, String tenantDomain, List<String> keyManagers) throws APISecurityException; /** * Get API Resource URI Templates * * @param context Context of an API * @param apiVersion A valid version of the API * @return an APIKeyValidationInfoDTO instance containing key validation data * @throws org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException on error */ ArrayList<URITemplate> getAllURITemplates(String context, String apiVersion) throws APISecurityException; /** * Get API Product Resource URI Templates * * @param context Context of an API Product * @param apiVersion A valid version of the API Product * @return an APIKeyValidationInfoDTO instance containing key validation data * @throws org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException on error */ ArrayList<URITemplate> getAPIProductURITemplates(String context, String apiVersion) throws APISecurityException; /** * Validate API subscriptions. * * @param context Context of an API * @param version A valid version of the API * @param consumerKey consumer key * @param keyManager * @return an APIKeyValidationInfoDTO instance containing key validation data * @throws org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException on error */ APIKeyValidationInfoDTO validateSubscription(String context, String version, String consumerKey, String tenantDomain, String keyManager) throws APISecurityException; /** * Clean up any resources allocated to this API key data store instance. */ void cleanup(); }
{ "content_hash": "042b18b119ad08db4eada15f0e4efe1c", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 116, "avg_line_length": 44.68181818181818, "alnum_prop": 0.7044760935910478, "repo_name": "nuwand/carbon-apimgt", "id": "4eef71c368558ea8c47709d25c18578f4acf1a41", "size": "4529", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/apimgt/org.wso2.carbon.apimgt.gateway/src/main/java/org/wso2/carbon/apimgt/gateway/handlers/security/keys/APIKeyDataStore.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "11203" }, { "name": "CSS", "bytes": "1846223" }, { "name": "HTML", "bytes": "1894358" }, { "name": "Java", "bytes": "14364942" }, { "name": "JavaScript", "bytes": "12096798" }, { "name": "PLSQL", "bytes": "177203" }, { "name": "Shell", "bytes": "33403" }, { "name": "TSQL", "bytes": "505779" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Ann. Univ. fenn. Aboënsis, Ser. A 1(no. 1): (1922) #### Original name Tuburcinia ranunculi-auricomi f. ranunculi-auricomi ### Remarks null
{ "content_hash": "c6be370c1829bd961d019f52064d4bdf", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 51, "avg_line_length": 15.538461538461538, "alnum_prop": 0.7029702970297029, "repo_name": "mdoering/backbone", "id": "949069dc9dd3233fe95f0f39aaceb73be1add8e1", "size": "275", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Ustilaginomycetes/Urocystidiales/Urocystidaceae/Urocystis/Tuburcinia ranunculi-auricomi/Tuburcinia ranunculi-auricomi ranunculi-auricomi/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php /** * Date: 2016/3/31 */ namespace Test; use DesignPatterns\Behavioral\Mediator\Mediator; use DesignPatterns\Behavioral\Mediator\Subsystem\Client; use DesignPatterns\Behavioral\Mediator\Subsystem\Database; use DesignPatterns\Behavioral\Mediator\Subsystem\Server; class MediatorTest { protected $client; protected function setUp() { $media = new Mediator(); $this->client = new Client($media); $media->setColleague(new Database($media), $this->client, new Server($media)); } public function test() { echo '<div>Mediator Test</div>'; $this->setUp(); $this->client->request(); } } /** * 中介者模式的优点和缺点都非常明显, 即使使用中介者模式, 也难以忽略文档的规范作用。 */
{ "content_hash": "4335fe678e627e7cd54a9897f8e80fe0", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 86, "avg_line_length": 20.62857142857143, "alnum_prop": 0.6592797783933518, "repo_name": "fyzzy1943/design-pattern-learn-php-", "id": "90c8478a2644fce01da22bbcac68089894364f41", "size": "802", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/MediatorTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "23163" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Roestelia fraxinites Schwein. ### Remarks null
{ "content_hash": "2a1fc36292a6ce4e3e8cc23160f38846", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 29, "avg_line_length": 10.307692307692308, "alnum_prop": 0.7164179104477612, "repo_name": "mdoering/backbone", "id": "1c1f2a2a2a87f9586ed3407dd233b0b671f4935d", "size": "187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Pucciniomycetes/Pucciniales/Pucciniaceae/Roestelia/Roestelia fraxinites/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('interactive', '0005_auto_20161006_2258'), ] operations = [ migrations.RenameField( model_name='settings', old_name='max_influencers', new_name='max_following', ), migrations.RenameField( model_name='settings', old_name='min_influencers', new_name='min_following', ), ]
{ "content_hash": "280ef9767a2f9b7ba6d07b5211a8a908", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 51, "avg_line_length": 23.17391304347826, "alnum_prop": 0.5647279549718575, "repo_name": "adminq80/Interactive_estimation", "id": "449e4e9e23a722ecbc2fe072c7935bc59cf97e47", "size": "606", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "game/interactive/migrations/0006_auto_20161007_0051.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7033" }, { "name": "HTML", "bytes": "56962" }, { "name": "JavaScript", "bytes": "21105" }, { "name": "Nginx", "bytes": "2324" }, { "name": "Python", "bytes": "274453" }, { "name": "Shell", "bytes": "8085" } ], "symlink_target": "" }
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim:expandtab:shiftwidth=2:tabstop=2:cin: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef __nsContentHandlerAppImpl_h__ #define __nsContentHandlerAppImpl_h__ #include <contentaction/contentaction.h> #include "nsString.h" #include "nsIMIMEInfo.h" class nsContentHandlerApp : public nsIHandlerApp { public: NS_DECL_ISUPPORTS NS_DECL_NSIHANDLERAPP nsContentHandlerApp(nsString aName, nsCString aType, ContentAction::Action& aAction); virtual ~nsContentHandlerApp() { } protected: nsString mName; nsCString mType; nsString mDetailedDescription; ContentAction::Action mAction; }; #endif
{ "content_hash": "85f411e1623ea8c1cf41ce48ff4a98c0", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 87, "avg_line_length": 28.3, "alnum_prop": 0.7396937573616019, "repo_name": "wilebeast/FireFox-OS", "id": "8ace9a2cd4d097891a45ca4ef78a1dfe17dde60b", "size": "849", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "B2G/gecko/uriloader/exthandler/nsContentHandlerApp.h", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import defaultPlugins from 'ember-template-compiler/plugins'; import TransformActionSyntax from '../plugins/transform-action-syntax'; import TransformInputTypeSyntax from '../plugins/transform-input-type-syntax'; import TransformAttrsIntoArgs from '../plugins/transform-attrs-into-args'; import TransformEachInIntoEach from '../plugins/transform-each-in-into-each'; import TransformHasBlockSyntax from '../plugins/transform-has-block-syntax'; import assign from 'ember-metal/assign'; export const PLUGINS = [ ...defaultPlugins, // the following are ember-glimmer specific TransformActionSyntax, TransformInputTypeSyntax, TransformAttrsIntoArgs, TransformEachInIntoEach, TransformHasBlockSyntax ]; let USER_PLUGINS = []; export default function compileOptions(options) { options = options || {}; options = assign({}, options); if (!options.plugins) { options.plugins = { ast: [...USER_PLUGINS, ...PLUGINS] }; } else { let potententialPugins = [...USER_PLUGINS, ...PLUGINS]; let pluginsToAdd = potententialPugins.filter((plugin) => { return options.plugins.ast.indexOf(plugin) === -1; }); options.plugins.ast = options.plugins.ast.slice().concat(pluginsToAdd); } return options; } export function registerPlugin(type, PluginClass) { if (type !== 'ast') { throw new Error(`Attempting to register ${PluginClass} as "${type}" which is not a valid Glimmer plugin type.`); } if (USER_PLUGINS.indexOf(PluginClass) === -1) { USER_PLUGINS = [PluginClass, ...USER_PLUGINS]; } } export function removePlugin(type, PluginClass) { if (type !== 'ast') { throw new Error(`Attempting to unregister ${PluginClass} as "${type}" which is not a valid Glimmer plugin type.`); } USER_PLUGINS = USER_PLUGINS.filter((plugin) => plugin !== PluginClass); }
{ "content_hash": "40dfca27cdb7fb1e2b02f6c121619e69", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 118, "avg_line_length": 34.264150943396224, "alnum_prop": 0.7142070484581498, "repo_name": "lan0/ember.js", "id": "c73603bd5a68c7c41b43580fa9fe3a13e5582ccd", "size": "1816", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/ember-glimmer-template-compiler/lib/system/compile-options.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "7457" }, { "name": "JavaScript", "bytes": "3298970" }, { "name": "Ruby", "bytes": "1925" }, { "name": "Shell", "bytes": "2529" } ], "symlink_target": "" }
use Config::Properties; use MIME::Base64; use JSON; use REST::Client; use HTML::Entities; # **************************************************************************** # Main # **************************************************************************** open my $PROPERTIES, '<', "./generate-gadget-xml.properties" or die "Unable to open configuration file: $!"; $properties = Config::Properties->new(); $properties->load($PROPERTIES); close ($PROPERTIES); my $gadgetDir = $properties->getProperty("gadgetDir"); # Set the URL, credentials, and headers for the REST calls my $url = $properties->getProperty("url"); my $user = $properties->getProperty("username"); my $pass = $properties->getProperty("password"); my $headers = { Authorization => 'Basic '. encode_base64($user . ':' . $pass), 'Content-type' => 'application/json' }; my $rest = REST::Client->new({host => "$url"}); my $templateXML, $projectPlanListXML = ""; my $defaultList = "0|0"; my $dataType = "enum"; my @projectPlanList; my $arr_index = 0; open $INXML, '<', "./template-activity-summary.xml" or die "Cannot open: $!"; $templateXML = join('',<$INXML>); close($INXML); $rest->GET("/index.php?/api/v2/get_projects", $headers ); my $project_data = decode_json( $rest->responseContent() ); if ($rest->responseCode() != 200) { printf("\nAPI call returned %s\n Error message: %s\n", $rest->responseCode(), $project_data->{error}); exit(1); } # Loop through all of the projects for my $project_node ( @$project_data ) { # Ignore completed projects if ($project_node->{'is_completed'} == 0) { $rest->GET("/index.php?/api/v2/get_plans/" . $project_node->{'id'}, $headers ); my $plan_data = decode_json( $rest->responseContent() ); if ($rest->responseCode() != 200) { printf("\nAPI call returned %s\n Error message: %s\n", $rest->responseCode(), $plan_data->{error}); exit(1); } # Loop through all of the plans for my $plan_node ( @$plan_data ) { # Ignore completed plans if ($plan_node->{'is_completed'} == 0) { $projectPlanList[$arr_index][0] = $project_node->{'id'}; $projectPlanList[$arr_index][1] = encode_entities($project_node->{'name'}); $projectPlanList[$arr_index][2] = $plan_node->{'id'}; $projectPlanList[$arr_index][3] = encode_entities($plan_node->{'name'}); $arr_index++; } } } } # Sort by project name, plan name @projectPlanList = sort { lc($a->[1]) cmp lc($b->[1])||lc($a->[3]) cmp lc($b->[3]) } (@projectPlanList); # Loop through all of the projects and plans to generate the UserPref XML for (my $i = 0; $i < $arr_index; $i++) { $projectPlanListXML .= "\n <EnumValue value=\"$projectPlanList[$i][0]|$projectPlanList[$i][2]\" display_value=\"($projectPlanList[$i][1]) $projectPlanList[$i][3]\"/>"; if ($defaultList eq "0|0") { $defaultList = "$projectPlanList[$i][0]|$projectPlanList[$i][2]"; } } if ($defaultList eq "0|0") { $dataType = "hidden"; } $templateXML =~ s/<%DEFAULTLIST%>/$defaultList/g; $templateXML =~ s/<%PROJECTPLANLIST%>/$projectPlanListXML/g; $templateXML =~ s/<%DATATYPE%>/$dataType/g; open $OUTXML, '>', "$gadgetDir/testrail-activity-summary.xml" or die "Cannot open: $!"; print($OUTXML "$templateXML"); close($OUTXML);
{ "content_hash": "135ab45feb974bb1b72c7459495fcd56", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 175, "avg_line_length": 36.57142857142857, "alnum_prop": 0.5892427884615384, "repo_name": "zenoss/testrail-jira-gadgets", "id": "0a83ad5d8978a66a837e02a5265b4264d299add3", "size": "3609", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/generate-activity-gadget-xml.pl", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "83827" }, { "name": "Perl", "bytes": "21779" } ], "symlink_target": "" }
/** * @license Highcharts JS v9.3.3 (2022-02-01) * * Highcharts Drilldown module * * Author: Torstein Honsi * License: www.highcharts.com/license * */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/modules/drilldown', ['highcharts'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'Extensions/Drilldown.js', [_modules['Core/Animation/AnimationUtilities.js'], _modules['Core/Axis/Axis.js'], _modules['Core/Chart/Chart.js'], _modules['Core/Color/Color.js'], _modules['Series/Column/ColumnSeries.js'], _modules['Core/FormatUtilities.js'], _modules['Core/Globals.js'], _modules['Core/DefaultOptions.js'], _modules['Core/Series/Point.js'], _modules['Core/Series/Series.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Renderer/SVG/SVGRenderer.js'], _modules['Core/Axis/Tick.js'], _modules['Core/Utilities.js']], function (A, Axis, Chart, Color, ColumnSeries, F, H, D, Point, Series, SeriesRegistry, SVGRenderer, Tick, U) { /* * * * Highcharts Drilldown module * * Author: Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ var animObject = A.animObject; var format = F.format; var noop = H.noop; var defaultOptions = D.defaultOptions; var seriesTypes = SeriesRegistry.seriesTypes; var addEvent = U.addEvent, removeEvent = U.removeEvent, extend = U.extend, fireEvent = U.fireEvent, merge = U.merge, objectEach = U.objectEach, pick = U.pick, syncTimeout = U.syncTimeout; /** * Gets fired when a drilldown point is clicked, before the new series is added. * Note that when clicking a category label to trigger multiple series * drilldown, one `drilldown` event is triggered per point in the category. * * @callback Highcharts.DrilldownCallbackFunction * * @param {Highcharts.Chart} this * The chart where the event occurs. * * @param {Highcharts.DrilldownEventObject} e * The drilldown event. */ /** * The event arguments when a drilldown point is clicked. * * @interface Highcharts.DrilldownEventObject */ /** * If a category label was clicked, which index. * @name Highcharts.DrilldownEventObject#category * @type {number|undefined} */ /** * The original browser event (usually click) that triggered the drilldown. * @name Highcharts.DrilldownEventObject#originalEvent * @type {global.Event|undefined} */ /** * Prevents the default behaviour of the event. * @name Highcharts.DrilldownEventObject#preventDefault * @type {Function} */ /** * The originating point. * @name Highcharts.DrilldownEventObject#point * @type {Highcharts.Point} */ /** * If a category label was clicked, this array holds all points corresponding to * the category. Otherwise it is set to false. * @name Highcharts.DrilldownEventObject#points * @type {boolean|Array<Highcharts.Point>|undefined} */ /** * Options for the new series. If the event is utilized for async drilldown, the * seriesOptions are not added, but rather loaded async. * @name Highcharts.DrilldownEventObject#seriesOptions * @type {Highcharts.SeriesOptionsType|undefined} */ /** * The event target. * @name Highcharts.DrilldownEventObject#target * @type {Highcharts.Chart} */ /** * The event type. * @name Highcharts.DrilldownEventObject#type * @type {"drilldown"} */ /** * This gets fired after all the series have been drilled up. This is especially * usefull in a chart with multiple drilldown series. * * @callback Highcharts.DrillupAllCallbackFunction * * @param {Highcharts.Chart} this * The chart where the event occurs. * * @param {Highcharts.DrillupAllEventObject} e * The final drillup event. */ /** * The event arguments when all the series have been drilled up. * * @interface Highcharts.DrillupAllEventObject */ /** * Prevents the default behaviour of the event. * @name Highcharts.DrillupAllEventObject#preventDefault * @type {Function} */ /** * The event target. * @name Highcharts.DrillupAllEventObject#target * @type {Highcharts.Chart} */ /** * The event type. * @name Highcharts.DrillupAllEventObject#type * @type {"drillupall"} */ /** * Gets fired when drilling up from a drilldown series. * * @callback Highcharts.DrillupCallbackFunction * * @param {Highcharts.Chart} this * The chart where the event occurs. * * @param {Highcharts.DrillupEventObject} e * The drillup event. */ /** * The event arguments when drilling up from a drilldown series. * * @interface Highcharts.DrillupEventObject */ /** * Prevents the default behaviour of the event. * @name Highcharts.DrillupEventObject#preventDefault * @type {Function} */ /** * Options for the new series. * @name Highcharts.DrillupEventObject#seriesOptions * @type {Highcharts.SeriesOptionsType|undefined} */ /** * The event target. * @name Highcharts.DrillupEventObject#target * @type {Highcharts.Chart} */ /** * The event type. * @name Highcharts.DrillupEventObject#type * @type {"drillup"} */ var PieSeries = seriesTypes.pie, ddSeriesId = 1; // Add language extend(defaultOptions.lang, /** * @optionparent lang */ { /** * The text for the button that appears when drilling down, linking back * to the parent series. The parent series' name is inserted for * `{series.name}`. * * @since 3.0.8 * @product highcharts highmaps * @requires modules/drilldown * * @private */ drillUpText: '◁ Back to {series.name}' }); /** * Options for drill down, the concept of inspecting increasingly high * resolution data through clicking on chart items like columns or pie slices. * * The drilldown feature requires the drilldown.js file to be loaded, * found in the modules directory of the download package, or online at * [code.highcharts.com/modules/drilldown.js * ](https://code.highcharts.com/modules/drilldown.js). * * @product highcharts highmaps * @requires modules/drilldown * @optionparent drilldown * @sample {highcharts} highcharts/series-organization/drilldown * Organization chart drilldown */ defaultOptions.drilldown = { /** * When this option is false, clicking a single point will drill down * all points in the same category, equivalent to clicking the X axis * label. * * @sample {highcharts} highcharts/drilldown/allowpointdrilldown-false/ * Don't allow point drilldown * * @type {boolean} * @default true * @since 4.1.7 * @product highcharts * @apioption drilldown.allowPointDrilldown */ /** * An array of series configurations for the drill down. Each series * configuration uses the same syntax as the [series](#series) option set. * These drilldown series are hidden by default. The drilldown series is * linked to the parent series' point by its `id`. * * @type {Array<Highcharts.SeriesOptionsType>} * @since 3.0.8 * @product highcharts highmaps * @apioption drilldown.series */ /** * Additional styles to apply to the X axis label for a point that * has drilldown data. By default it is underlined and blue to invite * to interaction. * * In styled mode, active label styles can be set with the * `.highcharts-drilldown-axis-label` class. * * @sample {highcharts} highcharts/drilldown/labels/ * Label styles * * @type {Highcharts.CSSObject} * @default { "cursor": "pointer", "color": "#003399", "fontWeight": "bold", "textDecoration": "underline" } * @since 3.0.8 * @product highcharts highmaps */ activeAxisLabelStyle: { /** @ignore-option */ cursor: 'pointer', /** @ignore-option */ color: "#003399" /* highlightColor100 */, /** @ignore-option */ fontWeight: 'bold', /** @ignore-option */ textDecoration: 'underline' }, /** * Additional styles to apply to the data label of a point that has * drilldown data. By default it is underlined and blue to invite to * interaction. * * In styled mode, active data label styles can be applied with the * `.highcharts-drilldown-data-label` class. * * @sample {highcharts} highcharts/drilldown/labels/ * Label styles * * @type {Highcharts.CSSObject} * @default { "cursor": "pointer", "color": "#003399", "fontWeight": "bold", "textDecoration": "underline" } * @since 3.0.8 * @product highcharts highmaps */ activeDataLabelStyle: { cursor: 'pointer', color: "#003399" /* highlightColor100 */, fontWeight: 'bold', textDecoration: 'underline' }, /** * Set the animation for all drilldown animations. Animation of a drilldown * occurs when drilling between a column point and a column series, * or a pie slice and a full pie series. Drilldown can still be used * between series and points of different types, but animation will * not occur. * * The animation can either be set as a boolean or a configuration * object. If `true`, it will use the 'swing' jQuery easing and a duration * of 500 ms. If used as a configuration object, the following properties * are supported: * * - `duration`: The duration of the animation in milliseconds. * * - `easing`: A string reference to an easing function set on the `Math` * object. See * [the easing demo](https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-animation-easing/). * * @type {boolean|Partial<Highcharts.AnimationOptionsObject>} * @since 3.0.8 * @product highcharts highmaps */ animation: { /** @internal */ duration: 500 }, /** * Options for the drill up button that appears when drilling down on a * series. The text for the button is defined in * [lang.drillUpText](#lang.drillUpText). * * @sample {highcharts} highcharts/drilldown/drillupbutton/ * Drill up button * @sample {highmaps} highcharts/drilldown/drillupbutton/ * Drill up button * * @since 3.0.8 * @product highcharts highmaps */ drillUpButton: { /** * What box to align the button to. Can be either `plotBox` or * `spacingBox`. * * @type {Highcharts.ButtonRelativeToValue} * @default plotBox * @since 3.0.8 * @product highcharts highmaps * @apioption drilldown.drillUpButton.relativeTo */ /** * A collection of attributes for the button. The object takes SVG * attributes like `fill`, `stroke`, `stroke-width` or `r`, the border * radius. The theme also supports `style`, a collection of CSS * properties for the text. Equivalent attributes for the hover state * are given in `theme.states.hover`. * * In styled mode, drill-up button styles can be applied with the * `.highcharts-drillup-button` class. * * @sample {highcharts} highcharts/drilldown/drillupbutton/ * Button theming * @sample {highmaps} highcharts/drilldown/drillupbutton/ * Button theming * * @type {Object} * @since 3.0.8 * @product highcharts highmaps * @apioption drilldown.drillUpButton.theme */ /** * Positioning options for the button within the `relativeTo` box. * Available properties are `x`, `y`, `align` and `verticalAlign`. * * @type {Highcharts.AlignObject} * @since 3.0.8 * @product highcharts highmaps */ position: { /** * Vertical alignment of the button. * * @type {Highcharts.VerticalAlignValue} * @default top * @product highcharts highmaps * @apioption drilldown.drillUpButton.position.verticalAlign */ /** * Horizontal alignment. * * @type {Highcharts.AlignValue} */ align: 'right', /** * The X offset of the button. */ x: -10, /** * The Y offset of the button. */ y: 10 } } }; /** * Fires when a drilldown point is clicked, before the new series is added. This * event is also utilized for async drilldown, where the seriesOptions are not * added by option, but rather loaded async. Note that when clicking a category * label to trigger multiple series drilldown, one `drilldown` event is * triggered per point in the category. * * Event arguments: * * - `category`: If a category label was clicked, which index. * * - `originalEvent`: The original browser event (usually click) that triggered * the drilldown. * * - `point`: The originating point. * * - `points`: If a category label was clicked, this array holds all points * corresponding to the category. * * - `seriesOptions`: Options for the new series. * * @sample {highcharts} highcharts/drilldown/async/ * Async drilldown * * @type {Highcharts.DrilldownCallbackFunction} * @since 3.0.8 * @product highcharts highmaps * @context Highcharts.Chart * @requires modules/drilldown * @apioption chart.events.drilldown */ /** * Fires when drilling up from a drilldown series. * * @type {Highcharts.DrillupCallbackFunction} * @since 3.0.8 * @product highcharts highmaps * @context Highcharts.Chart * @requires modules/drilldown * @apioption chart.events.drillup */ /** * In a chart with multiple drilldown series, this event fires after all the * series have been drilled up. * * @type {Highcharts.DrillupAllCallbackFunction} * @since 4.2.4 * @product highcharts highmaps * @context Highcharts.Chart * @requires modules/drilldown * @apioption chart.events.drillupall */ /** * The `id` of a series in the [drilldown.series](#drilldown.series) array to * use for a drilldown for this point. * * @sample {highcharts} highcharts/drilldown/basic/ * Basic drilldown * * @type {string} * @since 3.0.8 * @product highcharts * @requires modules/drilldown * @apioption series.line.data.drilldown */ /** * A general fadeIn method. * * @requires module:modules/drilldown * * @function Highcharts.SVGElement#fadeIn * * @param {boolean|Partial<Highcharts.AnimationOptionsObject>} [animation] * The animation options for the element fade. */ SVGRenderer.prototype.Element.prototype.fadeIn = function (animation) { this .attr({ opacity: 0.1, visibility: 'inherit' }) .animate({ opacity: pick(this.newOpacity, 1) // newOpacity used in maps }, animation || { duration: 250 }); }; /** * Add a series to the chart as drilldown from a specific point in the parent * series. This method is used for async drilldown, when clicking a point in a * series should result in loading and displaying a more high-resolution series. * When not async, the setup is simpler using the * [drilldown.series](https://api.highcharts.com/highcharts/drilldown.series) * options structure. * * @sample highcharts/drilldown/async/ * Async drilldown * * @function Highcharts.Chart#addSeriesAsDrilldown * * @param {Highcharts.Point} point * The point from which the drilldown will start. * * @param {Highcharts.SeriesOptionsType} options * The series options for the new, detailed series. */ Chart.prototype.addSeriesAsDrilldown = function (point, options) { this.addSingleSeriesAsDrilldown(point, options); this.applyDrilldown(); }; Chart.prototype.addSingleSeriesAsDrilldown = function (point, ddOptions) { var oldSeries = point.series, xAxis = oldSeries.xAxis, yAxis = oldSeries.yAxis, newSeries, pointIndex, levelSeries = [], levelSeriesOptions = [], level, levelNumber, last, colorProp; colorProp = this.styledMode ? { colorIndex: pick(point.colorIndex, oldSeries.colorIndex) } : { color: point.color || oldSeries.color }; if (!this.drilldownLevels) { this.drilldownLevels = []; } levelNumber = oldSeries.options._levelNumber || 0; // See if we can reuse the registered series from last run last = this.drilldownLevels[this.drilldownLevels.length - 1]; if (last && last.levelNumber !== levelNumber) { last = void 0; } ddOptions = extend(extend({ _ddSeriesId: ddSeriesId++ }, colorProp), ddOptions); pointIndex = oldSeries.points.indexOf(point); // Record options for all current series oldSeries.chart.series.forEach(function (series) { if (series.xAxis === xAxis && !series.isDrilling) { series.options._ddSeriesId = series.options._ddSeriesId || ddSeriesId++; series.options._colorIndex = series.userOptions._colorIndex; series.options._levelNumber = series.options._levelNumber || levelNumber; // #3182 if (last) { levelSeries = last.levelSeries; levelSeriesOptions = last.levelSeriesOptions; } else { levelSeries.push(series); // (#10597) series.purgedOptions = merge({ _ddSeriesId: series.options._ddSeriesId, _levelNumber: series.options._levelNumber, selected: series.options.selected }, series.userOptions); levelSeriesOptions.push(series.purgedOptions); } } }); // Add a record of properties for each drilldown level level = extend({ levelNumber: levelNumber, seriesOptions: oldSeries.options, seriesPurgedOptions: oldSeries.purgedOptions, levelSeriesOptions: levelSeriesOptions, levelSeries: levelSeries, shapeArgs: point.shapeArgs, // no graphic in line series with markers disabled bBox: point.graphic ? point.graphic.getBBox() : {}, color: point.isNull ? Color.parse(colorProp.color).setOpacity(0).get() : colorProp.color, lowerSeriesOptions: ddOptions, pointOptions: oldSeries.options.data[pointIndex], pointIndex: pointIndex, oldExtremes: { xMin: xAxis && xAxis.userMin, xMax: xAxis && xAxis.userMax, yMin: yAxis && yAxis.userMin, yMax: yAxis && yAxis.userMax }, resetZoomButton: this.resetZoomButton }, colorProp); // Push it to the lookup array this.drilldownLevels.push(level); // Reset names to prevent extending (#6704) if (xAxis && xAxis.names) { xAxis.names.length = 0; } newSeries = level.lowerSeries = this.addSeries(ddOptions, false); newSeries.options._levelNumber = levelNumber + 1; if (xAxis) { xAxis.oldPos = xAxis.pos; xAxis.userMin = xAxis.userMax = null; yAxis.userMin = yAxis.userMax = null; } // Run fancy cross-animation on supported and equal types if (oldSeries.type === newSeries.type) { newSeries.animate = (newSeries.animateDrilldown || noop); newSeries.options.animation = true; } }; Chart.prototype.applyDrilldown = function () { var drilldownLevels = this.drilldownLevels, levelToRemove; if (drilldownLevels && drilldownLevels.length > 0) { // #3352, async loading levelToRemove = drilldownLevels[drilldownLevels.length - 1].levelNumber; this.drilldownLevels.forEach(function (level) { if (level.levelNumber === levelToRemove) { level.levelSeries.forEach(function (series) { // Not removed, not added as part of a multi-series // drilldown if (series.options && series.options._levelNumber === levelToRemove) { series.remove(false); } }); } }); } // We have a reset zoom button. Hide it and detatch it from the chart. It // is preserved to the layer config above. if (this.resetZoomButton) { this.resetZoomButton.hide(); delete this.resetZoomButton; } this.pointer.reset(); this.redraw(); this.showDrillUpButton(); fireEvent(this, 'afterDrilldown'); }; Chart.prototype.getDrilldownBackText = function () { var drilldownLevels = this.drilldownLevels, lastLevel; if (drilldownLevels && drilldownLevels.length > 0) { // #3352, async loading lastLevel = drilldownLevels[drilldownLevels.length - 1]; lastLevel.series = lastLevel.seriesOptions; return format(this.options.lang.drillUpText || '', lastLevel); } }; Chart.prototype.showDrillUpButton = function () { var chart = this, backText = this.getDrilldownBackText(), buttonOptions = chart.options.drilldown.drillUpButton, attr, states, alignTo = (buttonOptions.relativeTo === 'chart' || buttonOptions.relativeTo === 'spacingBox' ? null : 'scrollablePlotBox'); if (!this.drillUpButton) { attr = buttonOptions.theme; states = attr && attr.states; this.drillUpButton = this.renderer .button(backText, null, null, function () { chart.drillUp(); }, attr, states && states.hover, states && states.select) .addClass('highcharts-drillup-button') .attr({ align: buttonOptions.position.align, zIndex: 7 }) .add() .align(buttonOptions.position, false, alignTo); } else { this.drillUpButton.attr({ text: backText }) .align(); } }; /** * When the chart is drilled down to a child series, calling `chart.drillUp()` * will drill up to the parent series. * * @requires modules/drilldown * * @function Highcharts.Chart#drillUp * * @sample {highcharts} highcharts/drilldown/programmatic * Programmatic drilldown */ Chart.prototype.drillUp = function () { if (!this.drilldownLevels || this.drilldownLevels.length === 0) { return; } var chart = this, drilldownLevels = chart.drilldownLevels, levelNumber = drilldownLevels[drilldownLevels.length - 1].levelNumber, i = drilldownLevels.length, chartSeries = chart.series, seriesI, level, oldSeries, newSeries, oldExtremes, addSeries = function (seriesOptions) { var addedSeries; chartSeries.forEach(function (series) { if (series.options._ddSeriesId === seriesOptions._ddSeriesId) { addedSeries = series; } }); addedSeries = addedSeries || chart.addSeries(seriesOptions, false); if (addedSeries.type === oldSeries.type && addedSeries.animateDrillupTo) { addedSeries.animate = addedSeries.animateDrillupTo; } if (seriesOptions === level.seriesPurgedOptions) { newSeries = addedSeries; } }; while (i--) { level = drilldownLevels[i]; if (level.levelNumber === levelNumber) { drilldownLevels.pop(); // Get the lower series by reference or id oldSeries = level.lowerSeries; if (!oldSeries.chart) { // #2786 seriesI = chartSeries.length; // #2919 while (seriesI--) { if (chartSeries[seriesI].options.id === level.lowerSeriesOptions.id && chartSeries[seriesI].options._levelNumber === levelNumber + 1) { // #3867 oldSeries = chartSeries[seriesI]; break; } } } oldSeries.xData = []; // Overcome problems with minRange (#2898) level.levelSeriesOptions.forEach(addSeries); fireEvent(chart, 'drillup', { seriesOptions: level.seriesPurgedOptions || level.seriesOptions }); this.resetZoomButton && this.resetZoomButton.destroy(); // #8095 if (newSeries.type === oldSeries.type) { newSeries.drilldownLevel = level; newSeries.options.animation = chart.options.drilldown.animation; if (oldSeries.animateDrillupFrom && oldSeries.chart) { // #2919 oldSeries.animateDrillupFrom(level); } } newSeries.options._levelNumber = levelNumber; oldSeries.remove(false); // Reset the zoom level of the upper series if (newSeries.xAxis) { oldExtremes = level.oldExtremes; newSeries.xAxis.setExtremes(oldExtremes.xMin, oldExtremes.xMax, false); newSeries.yAxis.setExtremes(oldExtremes.yMin, oldExtremes.yMax, false); } // We have a resetZoomButton tucked away for this level. Attatch // it to the chart and show it. if (level.resetZoomButton) { chart.resetZoomButton = level.resetZoomButton; chart.resetZoomButton.show(); } } } this.redraw(); if (this.drilldownLevels.length === 0) { this.drillUpButton = this.drillUpButton.destroy(); } else { this.drillUpButton.attr({ text: this.getDrilldownBackText() }) .align(); } this.ddDupes.length = []; // #3315 // Fire a once-off event after all series have been drilled up (#5158) fireEvent(chart, 'drillupall'); }; /* eslint-disable no-invalid-this */ // Add update function to be called internally from Chart.update // (#7600, #12855) addEvent(Chart, 'afterInit', function () { var chart = this; chart.drilldown = { update: function (options, redraw) { merge(true, chart.options.drilldown, options); if (pick(redraw, true)) { chart.redraw(); } } }; }); // Shift the drillUpButton to make the space for resetZoomButton, #8095. addEvent(Chart, 'afterShowResetZoom', function () { var chart = this, bbox = chart.resetZoomButton && chart.resetZoomButton.getBBox(), buttonOptions = (chart.options.drilldown && chart.options.drilldown.drillUpButton); if (this.drillUpButton && bbox && buttonOptions && buttonOptions.position && buttonOptions.position.x) { this.drillUpButton.align({ x: buttonOptions.position.x - bbox.width - 10, y: buttonOptions.position.y, align: buttonOptions.position.align }, false, buttonOptions.relativeTo || 'plotBox'); } }); addEvent(Chart, 'render', function () { (this.xAxis || []).forEach(function (axis) { axis.ddPoints = {}; axis.series.forEach(function (series) { var i, xData = series.xData || [], points = series.points, p; for (i = 0; i < xData.length; i++) { p = series.options.data[i]; // The `drilldown` property can only be set on an array or an // object if (typeof p !== 'number') { // Convert array to object (#8008) p = series.pointClass.prototype.optionsToObject .call({ series: series }, p); if (p.drilldown) { if (!axis.ddPoints[xData[i]]) { axis.ddPoints[xData[i]] = []; } var index = i - (series.cropStart || 0); axis.ddPoints[xData[i]].push((points && index >= 0 && index < points.length) ? points[index] : true); } } } }); // Add drillability to ticks, and always keep it drillability updated // (#3951) objectEach(axis.ticks, Tick.prototype.drillable); }); }); /** * When drilling up, keep the upper series invisible until the lower series has * moved into place. * * @private * @function Highcharts.ColumnSeries#animateDrillupTo * @param {boolean} [init=false] * Whether to initialize animation */ ColumnSeries.prototype.animateDrillupTo = function (init) { if (!init) { var newSeries_1 = this, level_1 = newSeries_1.drilldownLevel; // First hide all items before animating in again this.points.forEach(function (point) { var dataLabel = point.dataLabel; if (point.graphic) { // #3407 point.graphic.hide(); } if (dataLabel) { // The data label is initially hidden, make sure it is not faded // in (#6127) dataLabel.hidden = dataLabel.attr('visibility') === 'hidden'; if (!dataLabel.hidden) { dataLabel.hide(); if (point.connector) { point.connector.hide(); } } } }); // Do dummy animation on first point to get to complete syncTimeout(function () { if (newSeries_1.points) { // May be destroyed in the meantime, #3389 // Unable to drillup with nodes, #13711 var pointsWithNodes_1 = []; newSeries_1.data.forEach(function (el) { pointsWithNodes_1.push(el); }); if (newSeries_1.nodes) { pointsWithNodes_1 = pointsWithNodes_1.concat(newSeries_1.nodes); } pointsWithNodes_1.forEach(function (point, i) { // Fade in other points var verb = i === (level_1 && level_1.pointIndex) ? 'show' : 'fadeIn', inherit = verb === 'show' ? true : void 0, dataLabel = point.dataLabel; if (point.graphic) { // #3407 point.graphic[verb](inherit); } if (dataLabel && !dataLabel.hidden) { // #6127 dataLabel.fadeIn(); // #7384 if (point.connector) { point.connector.fadeIn(); } } }); } }, Math.max(this.chart.options.drilldown.animation.duration - 50, 0)); // Reset to prototype delete this.animate; } }; ColumnSeries.prototype.animateDrilldown = function (init) { var series = this, chart = this.chart, drilldownLevels = chart.drilldownLevels, animateFrom, animationOptions = animObject(chart.options.drilldown.animation), xAxis = this.xAxis, styledMode = chart.styledMode; if (!init) { drilldownLevels.forEach(function (level) { if (series.options._ddSeriesId === level.lowerSeriesOptions._ddSeriesId) { animateFrom = level.shapeArgs; if (!styledMode) { // Add the point colors to animate from animateFrom.fill = level.color; } } }); animateFrom.x += pick(xAxis.oldPos, xAxis.pos) - xAxis.pos; this.points.forEach(function (point) { var animateTo = point.shapeArgs; if (!styledMode) { // Add the point colors to animate to animateTo.fill = point.color; } if (point.graphic) { point.graphic .attr(animateFrom) .animate(extend(point.shapeArgs, { fill: point.color || series.color }), animationOptions); } if (point.dataLabel) { point.dataLabel.fadeIn(animationOptions); } }); // Reset to prototype delete this.animate; } }; /** * When drilling up, pull out the individual point graphics from the lower * series and animate them into the origin point in the upper series. * * @private * @function Highcharts.ColumnSeries#animateDrillupFrom * @param {Highcharts.DrilldownLevelObject} level * Level container * @return {void} */ ColumnSeries.prototype.animateDrillupFrom = function (level) { var animationOptions = animObject(this.chart.options.drilldown.animation), group = this.group, // For 3d column series all columns are added to one group // so we should not delete the whole group. #5297 removeGroup = group !== this.chart.columnGroup, series = this; // Cancel mouse events on the series group (#2787) series.trackerGroups.forEach(function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key].on('mouseover'); } }); if (removeGroup) { delete this.group; } this.points.forEach(function (point) { var graphic = point.graphic, animateTo = level.shapeArgs, complete = function () { graphic.destroy(); if (group && removeGroup) { group = group.destroy(); } }; if (graphic && animateTo) { delete point.graphic; if (!series.chart.styledMode) { animateTo.fill = level.color; } if (animationOptions.duration) { graphic.animate(animateTo, merge(animationOptions, { complete: complete })); } else { graphic.attr(animateTo); complete(); } } }); }; if (PieSeries) { extend(PieSeries.prototype, { animateDrillupTo: ColumnSeries.prototype.animateDrillupTo, animateDrillupFrom: ColumnSeries.prototype.animateDrillupFrom, animateDrilldown: function (init) { var level = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1], animationOptions = this.chart.options.drilldown.animation; if (this.is('item')) { animationOptions.duration = 0; } // Unable to drill down in the horizontal item series #13372 if (this.center) { var animateFrom_1 = level.shapeArgs, start_1 = animateFrom_1.start, angle = animateFrom_1.end - start_1, startAngle_1 = angle / this.points.length, styledMode_1 = this.chart.styledMode; if (!init) { this.points.forEach(function (point, i) { var animateTo = point.shapeArgs; if (!styledMode_1) { animateFrom_1.fill = level.color; animateTo.fill = point.color; } if (point.graphic) { point.graphic .attr(merge(animateFrom_1, { start: start_1 + i * startAngle_1, end: start_1 + (i + 1) * startAngle_1 }))[animationOptions ? 'animate' : 'attr'](animateTo, animationOptions); } }); // Reset to prototype delete this.animate; } } } }); } /** * Perform drilldown on a point instance. The [drilldown](https://api.highcharts.com/highcharts/series.line.data.drilldown) * property must be set on the point options. * * To drill down multiple points in the same category, use * `Axis.drilldownCategory` instead. * * @requires modules/drilldown * * @function Highcharts.Point#doDrilldown * * @sample {highcharts} highcharts/drilldown/programmatic * Programmatic drilldown */ Point.prototype.doDrilldown = function () { this.runDrilldown(); }; Point.prototype.runDrilldown = function (holdRedraw, category, originalEvent) { var series = this.series, chart = series.chart, drilldown = chart.options.drilldown; var i = (drilldown.series || []).length, seriesOptions; if (!chart.ddDupes) { chart.ddDupes = []; } while (i-- && !seriesOptions) { if (drilldown.series[i].id === this.drilldown && chart.ddDupes.indexOf(this.drilldown) === -1) { seriesOptions = drilldown.series[i]; chart.ddDupes.push(this.drilldown); } } // Fire the event. If seriesOptions is undefined, the implementer can check // for seriesOptions, and call addSeriesAsDrilldown async if necessary. fireEvent(chart, 'drilldown', { point: this, seriesOptions: seriesOptions, category: category, originalEvent: originalEvent, points: (typeof category !== 'undefined' && this.series.xAxis.getDDPoints(category).slice(0)) }, function (e) { var chart = e.point.series && e.point.series.chart, seriesOptions = e.seriesOptions; if (chart && seriesOptions) { if (holdRedraw) { chart.addSingleSeriesAsDrilldown(e.point, seriesOptions); } else { chart.addSeriesAsDrilldown(e.point, seriesOptions); } } }); }; /** * Drill down to a given category. This is the same as clicking on an axis * label. If multiple series with drilldown are present, all will drill down to * the given category. * * See also `Point.doDrilldown` for drilling down on a single point instance. * * @function Highcharts.Axis#drilldownCategory * * @sample {highcharts} highcharts/drilldown/programmatic * Programmatic drilldown * * @param {number} x * The index of the category * @param {global.MouseEvent} [originalEvent] * The original event, used internally. */ Axis.prototype.drilldownCategory = function (x, originalEvent) { this.getDDPoints(x).forEach(function (point) { if (point && point.series && point.series.visible && point.runDrilldown) { // #3197 point.runDrilldown(true, x, originalEvent); } }); this.chart.applyDrilldown(); }; /** * Return drillable points for this specific X value. * * @private * @function Highcharts.Axis#getDDPoints * @param {number} x * Tick position * @return {Array<(false|Highcharts.Point)>} * Drillable points */ Axis.prototype.getDDPoints = function (x) { return (this.ddPoints && this.ddPoints[x] || []); }; /** * Make a tick label drillable, or remove drilling on update. * * @private * @function Highcharts.Axis#drillable */ Tick.prototype.drillable = function () { var pos = this.pos, label = this.label, axis = this.axis, isDrillable = axis.coll === 'xAxis' && axis.getDDPoints, ddPointsX = isDrillable && axis.getDDPoints(pos), styledMode = axis.chart.styledMode; if (isDrillable) { if (label && ddPointsX && ddPointsX.length) { label.drillable = true; if (!label.basicStyles && !styledMode) { label.basicStyles = merge(label.styles); } label.addClass('highcharts-drilldown-axis-label'); // #12656 - avoid duplicate of attach event if (label.removeOnDrillableClick) { removeEvent(label.element, 'click'); } label.removeOnDrillableClick = addEvent(label.element, 'click', function (e) { e.preventDefault(); axis.drilldownCategory(pos, e); }); if (!styledMode) { label.css(axis.chart.options.drilldown.activeAxisLabelStyle); } } else if (label && label.drillable && label.removeOnDrillableClick) { if (!styledMode) { label.styles = {}; // reset for full overwrite of styles label.css(label.basicStyles); } label.removeOnDrillableClick(); // #3806 label.removeClass('highcharts-drilldown-axis-label'); } } }; // On initialization of each point, identify its label and make it clickable. // Also, provide a list of points associated to that label. addEvent(Point, 'afterInit', function () { var point = this; if (point.drilldown && !point.unbindDrilldownClick) { // Add the click event to the point point.unbindDrilldownClick = addEvent(point, 'click', handlePointClick); } return point; }); addEvent(Point, 'update', function (e) { var point = this, options = e.options || {}; if (options.drilldown && !point.unbindDrilldownClick) { // Add the click event to the point point.unbindDrilldownClick = addEvent(point, 'click', handlePointClick); } else if (!options.drilldown && options.drilldown !== void 0 && point.unbindDrilldownClick) { point.unbindDrilldownClick = point.unbindDrilldownClick(); } }); var handlePointClick = function (e) { var point = this, series = point.series; if (series.xAxis && series.chart.options.drilldown.allowPointDrilldown === false) { // #5822, x changed series.xAxis.drilldownCategory(point.x, e); } else { point.runDrilldown(void 0, void 0, e); } }; addEvent(Series, 'afterDrawDataLabels', function () { var css = this.chart.options.drilldown.activeDataLabelStyle, renderer = this.chart.renderer, styledMode = this.chart.styledMode; this.points.forEach(function (point) { var dataLabelsOptions = point.options.dataLabels, pointCSS = pick(point.dlOptions, dataLabelsOptions && dataLabelsOptions.style, {}); if (point.drilldown && point.dataLabel) { if (css.color === 'contrast' && !styledMode) { pointCSS.color = renderer.getContrast(point.color || this.color); } if (dataLabelsOptions && dataLabelsOptions.color) { pointCSS.color = dataLabelsOptions.color; } point.dataLabel .addClass('highcharts-drilldown-data-label'); if (!styledMode) { point.dataLabel .css(css) .css(pointCSS); } } }, this); }); var applyCursorCSS = function (element, cursor, addClass, styledMode) { element[addClass ? 'addClass' : 'removeClass']('highcharts-drilldown-point'); if (!styledMode) { element.css({ cursor: cursor }); } }; // Mark the trackers with a pointer addEvent(Series, 'afterDrawTracker', function () { var styledMode = this.chart.styledMode; this.points.forEach(function (point) { if (point.drilldown && point.graphic) { applyCursorCSS(point.graphic, 'pointer', true, styledMode); } }); }); addEvent(Point, 'afterSetState', function () { var styledMode = this.series.chart.styledMode; if (this.drilldown && this.series.halo && this.state === 'hover') { applyCursorCSS(this.series.halo, 'pointer', true, styledMode); } else if (this.series.halo) { applyCursorCSS(this.series.halo, 'auto', false, styledMode); } }); // After zooming out, shift the drillUpButton to the previous position, #8095. addEvent(Chart, 'selection', function (event) { if (event.resetSelection === true && this.drillUpButton) { var buttonOptions = (this.options.drilldown && this.options.drilldown.drillUpButton); if (buttonOptions && buttonOptions.position) { this.drillUpButton.align({ x: buttonOptions.position.x, y: buttonOptions.position.y, align: buttonOptions.position.align }, false, buttonOptions.relativeTo || 'plotBox'); } } }); addEvent(Chart, 'drillup', function () { if (this.resetZoomButton) { this.resetZoomButton = this.resetZoomButton.destroy(); } }); }); _registerModule(_modules, 'masters/modules/drilldown.src.js', [], function () { }); }));
{ "content_hash": "76d6ae4532a553e37ad171932789fb10", "timestamp": "", "source": "github", "line_count": 1266, "max_line_length": 681, "avg_line_length": 43.79462875197472, "alnum_prop": 0.488384676430272, "repo_name": "cdnjs/cdnjs", "id": "4a3a71e5ad56f0c7f5d2ef7fd2a81b5876f1c953", "size": "55446", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/highcharts/9.3.3/modules/drilldown.src.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
using System; using System.Runtime.CompilerServices; namespace CilJs.Runtime.TranslatorServices { [JsIgnore] [AttributeUsage(AttributeTargets.Method)] public class JsReplaceAttribute : Attribute { public JsReplaceAttribute(string replacement) { Replacement = replacement; } public string Replacement { get; set; } } }
{ "content_hash": "dd38e34ab4b333881ae5618015e5e0ee", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 53, "avg_line_length": 22.58823529411765, "alnum_prop": 0.671875, "repo_name": "markusjohnsson/cil.js", "id": "ad3d979a074bf170150c1591ec718de52867824c", "size": "384", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CilJs.Corlib/CilJs.Runtime.TranslatorServices/JsReplaceAttribute.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "580020" }, { "name": "HTML", "bytes": "252" }, { "name": "JavaScript", "bytes": "2094796" }, { "name": "Shell", "bytes": "90" }, { "name": "TypeScript", "bytes": "20322" } ], "symlink_target": "" }
from tlp.models import NumericParameter from unittest.mock import MagicMock from unittest import TestCase class TestNumericParameter(TestCase): def test_should_cast_value_to_string_on_set_value(self): parameter = NumericParameter('TEST') parameter.value = 256.5 self.assertEqual('256.5', parameter._value) def test_should_cast_value_to_int_on_get_value(self): parameter = NumericParameter('TEST') parameter._value = '512.5' self.assertEqual(512.5, parameter.value) def test_should_remove_decimal_places_for_integer_numbers(self): parameter = NumericParameter('TEST') parameter.value = float(245.0) self.assertEqual('245', parameter._value) def test_parameter_should_clone_itself(self): param = NumericParameter('Test', reboot_needed=True) param.initialize(True, 111) clone = param.clone() self.assertEqual(param.reboot_needed, clone.reboot_needed) self.assertEqual(param._active, clone._active) self.assertEqual(param._value, clone._value) self.assertEqual(param.name, clone.name) def test_should_notify_when_set_value(self): param = NumericParameter('TEST') param.initialize(True, '123') param.notify_changes = MagicMock() param.value = 321 self.assertTrue(param.notify_changes.called) def test_parameter_should_not_notify_when_set_value_with_same_value(self): param = NumericParameter('TEST') param.initialize(True, '123') param.notify_changes = MagicMock() param.value = 123 self.assertFalse(param.notify_changes.called)
{ "content_hash": "13ccb27b347aacf0342c52eb8db8b759", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 78, "avg_line_length": 35.46808510638298, "alnum_prop": 0.6730653869226155, "repo_name": "fholiveira/tlpconfig", "id": "c1ed203c4349638539cf0cb6cc81680545961342", "size": "1667", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/models/parameters/test_numeric.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "351" }, { "name": "Python", "bytes": "70377" } ], "symlink_target": "" }
* List paths of all the json file ```bash cat something.json | jq -c 'path(..)|[.[]|tostring]|join("/")' ``` * Filter array based on an argument in the object ```bash cat something.json | jq '.[] | select(.name=="Tom")' ``` * Filter array based on an argument matching a regex ```bash cat something.json | jq '.[] | select(.city|test("[Rr]amat"))' ``` * Use variables from bash within jq ```bash cat something.json | jq --arg name "$name" '.[] | select(.name==$name)' ```
{ "content_hash": "476c0ecd45dcff8c8e6d813a1f2864d7", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 71, "avg_line_length": 21.727272727272727, "alnum_prop": 0.6213389121338913, "repo_name": "tomklino/cheat-sheets", "id": "320f3bc30e3223a9135daf491bf8ff7d8247fb41", "size": "484", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jq.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "68705" } ], "symlink_target": "" }
mip-miaotu-register 注册 标题|内容 ----|---- 类型|通用 支持布局|responsive,fixed-height,fill,container,fixed 所需脚本|https://c.mipcdn.com/static/v1/mip-miaotu-register/mip-miaotu-register.js ## 示例 ### 基本用法 ```html <mip-miaotu-register> <mip-form id="form-register" name="form-register" url="" method=""> <div class="reg-first" id="reg_first"> <div class="inp-user"> <input type="text" name="registerName" id="registerName" placeholder="请输入手机号" maxlength="11"> <span class="error"></span> </div> <div class="inp-val"> <input type="text" name="registerValidate" id="registerValidate" placeholder="请输入验证码"> <input type="button" class="get-val clickme-get-countdown" value="免费获取验证码" id="regGetVal"> <span class="error"></span> </div> <div class="btn-login"> <input type="button" id="btnNextStep" value="下一步"> </div> </div> <div class="reg-second" id="reg_second"> <div class="inp-pwd"> <input type="password" name="registerPassword" id="registerPassword" placeholder="请输入密码"> <span class="error"></span> </div> <div class="inp-repwd"> <input type="password" name="registerRepassword" id="registerRepassword" placeholder="请再次确认"> <span class="error"></span> </div> <div class="btn-login"> <input type="submit" id="btnSubmit" value="确定"> </div> </div> </mip-form> </mip-miaotu-register> ```
{ "content_hash": "4cc1515e4566c50c0e4df73bd8430c8a", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 109, "avg_line_length": 34.765957446808514, "alnum_prop": 0.5465116279069767, "repo_name": "mipengine/mip-extensions-platform", "id": "b3c6afcec2c58b4dd15747d22aa8d9a184ab5587", "size": "1773", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mip-miaotu-register/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "966670" }, { "name": "HTML", "bytes": "24624" }, { "name": "JavaScript", "bytes": "11914398" } ], "symlink_target": "" }
<?php namespace Magento\CatalogInventory\Block\Stockqty; /** * Unit test for DefaultStockqty */ class DefaultStockqtyTest extends \PHPUnit_Framework_TestCase { /** * @var \Magento\CatalogInventory\Block\Stockqty\DefaultStockqty */ protected $block; /** * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject */ protected $registryMock; /** * @var \Magento\CatalogInventory\Api\StockStateInterface|\PHPUnit_Framework_MockObject_MockObject */ protected $stockState; /** * @var \PHPUnit_Framework_MockObject_MockObject */ protected $stockRegistryMock; protected function setUp() { $objectManager = new \Magento\TestFramework\Helper\ObjectManager($this); $this->registryMock = $this->getMock('Magento\Framework\Registry', [], [], '', false); $this->stockState = $this->getMock( 'Magento\CatalogInventory\Api\StockStateInterface', [], [], '', false ); $this->stockRegistryMock = $this->getMockBuilder('Magento\CatalogInventory\Api\StockRegistryInterface') ->disableOriginalConstructor() ->getMock(); $this->block = $objectManager->getObject( 'Magento\CatalogInventory\Block\Stockqty\DefaultStockqty', [ 'registry' => $this->registryMock, 'stockState' => $this->stockState, 'stockRegistry' => $this->stockRegistryMock ] ); } protected function tearDown() { $this->block = null; } public function testGetIdentities() { $productTags = ['catalog_product_1']; $product = $this->getMock('Magento\Catalog\Model\Product', [], [], '', false); $product->expects($this->once())->method('getIdentities')->will($this->returnValue($productTags)); $this->registryMock->expects($this->once()) ->method('registry') ->with('current_product') ->will($this->returnValue($product)); $this->assertEquals($productTags, $this->block->getIdentities()); } /** * @param int $productStockQty * @param int|null $productId * @param int|null $websiteId * @param int|null $dataQty * @param int $expectedQty * @dataProvider getStockQtyDataProvider */ public function testGetStockQty($productStockQty, $productId, $websiteId, $dataQty, $expectedQty) { $this->assertNull($this->block->getData('product_stock_qty')); if ($dataQty) { $this->setDataArrayValue('product_stock_qty', $dataQty); } else { $product = $this->getMock( 'Magento\Catalog\Model\Product', ['getId', 'getStore', '__wakeup'], [], '', false ); $product->expects($this->any())->method('getId')->will($this->returnValue($productId)); $store = $this->getMock('Magento\Store\Model\Store', ['getWebsiteId', '__wakeup'], [], '', false); $store->expects($this->any())->method('getWebsiteId')->willReturn($websiteId); $product->expects($this->any())->method('getStore')->will($this->returnValue($store)); $this->registryMock->expects($this->any()) ->method('registry') ->with('current_product') ->will($this->returnValue($product)); if ($productId) { $this->stockState->expects($this->once()) ->method('getStockQty') ->with($this->equalTo($productId), $this->equalTo($websiteId)) ->will($this->returnValue($productStockQty)); } } $this->assertSame($expectedQty, $this->block->getStockQty()); $this->assertSame($expectedQty, $this->block->getData('product_stock_qty')); } public function te1stGetStockQtyLeft() { $productId = 1; $minQty = 0; $websiteId = 1; $stockQty = 2; $storeMock = $this->getMockBuilder('Magento\Store\Model\Store') ->disableOriginalConstructor() ->getMock(); $storeMock->expects($this->once()) ->method('getWebsiteId') ->willReturn($websiteId); $product = $this->getMock('Magento\Catalog\Model\Product', [], [], '', false); $product->expects($this->any()) ->method('getId') ->willReturn($productId); $product->expects($this->once()) ->method('getStore') ->willReturn($storeMock); $this->registryMock->expects($this->once()) ->method('registry') ->with('current_product') ->will($this->returnValue($product)); $stockItemMock = $this->getMockBuilder('Magento\CatalogInventory\Api\Data\StockItemInterface') ->disableOriginalConstructor() ->getMock(); $stockItemMock->expects($this->once()) ->method('getMinQty') ->willReturn($minQty); $this->stockRegistryMock->expects($this->once()) ->method('getStockItem') ->with($productId) ->willReturn($stockItemMock); $this->stockState->expects($this->once()) ->method('getStockQty') ->with($productId, $storeMock) ->willReturn($stockQty); $this->assertEquals($stockQty, $this->block->getStockQtyLeft()); } /** * @return array */ public function getStockQtyDataProvider() { return [ [ 'product qty' => 100, 'product id' => 5, 'website id' => 0, 'default qty' => null, 'expected qty' => 100, ], [ 'product qty' => 100, 'product id' => null, 'website id' => null, 'default qty' => null, 'expected qty' => 0 ], [ 'product qty' => null, 'product id' => null, 'website id' => null, 'default qty' => 50, 'expected qty' => 50 ], ]; } /** * @param string $key * @param string|float|int $value */ protected function setDataArrayValue($key, $value) { $property = new \ReflectionProperty($this->block, '_data'); $property->setAccessible(true); $dataArray = $property->getValue($this->block); $dataArray[$key] = $value; $property->setValue($this->block, $dataArray); } }
{ "content_hash": "a99f06b2addc0dad000499dfbc473766", "timestamp": "", "source": "github", "line_count": 198, "max_line_length": 111, "avg_line_length": 33.95454545454545, "alnum_prop": 0.5316079131340176, "repo_name": "webadvancedservicescom/magento", "id": "4b2c3f957ed94404a4ca01a9fbad57acacc4c948", "size": "6813", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dev/tests/unit/testsuite/Magento/CatalogInventory/Block/Stockqty/DefaultStockqtyTest.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "16380" }, { "name": "CSS", "bytes": "2592299" }, { "name": "HTML", "bytes": "9192193" }, { "name": "JavaScript", "bytes": "2874762" }, { "name": "PHP", "bytes": "41399372" }, { "name": "Shell", "bytes": "3084" }, { "name": "VCL", "bytes": "3547" }, { "name": "XSLT", "bytes": "19817" } ], "symlink_target": "" }
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.resources.commerce.customer; import com.mozu.api.ApiContext; import java.util.List; import java.util.ArrayList; import com.mozu.api.MozuClient; import com.mozu.api.MozuClientFactory; import com.mozu.api.MozuUrl; import com.mozu.api.Headers; import org.joda.time.DateTime; import com.mozu.api.security.AuthTicket; import org.apache.commons.lang.StringUtils; /** <summary> * Use the Customer Credits resource to manage the store credit associated with a customer account. Store credit can represent a static amount the customer can redeem at any of the tenant's sites, or a gift card registered for a customer account. At this time, gift card functionality is reserved for future use. * </summary> */ public class CreditResource { /// /// <see cref="Mozu.Api.ApiContext"/> /// private ApiContext _apiContext; public CreditResource(ApiContext apiContext) { _apiContext = apiContext; } /** * * <p><pre><code> * Credit credit = new Credit(); * CreditCollection creditCollection = credit.getCredits(); * </code></pre></p> * @return com.mozu.api.contracts.customer.credit.CreditCollection * @see com.mozu.api.contracts.customer.credit.CreditCollection */ public com.mozu.api.contracts.customer.credit.CreditCollection getCredits() throws Exception { return getCredits( null, null, null, null, null); } /** * * <p><pre><code> * Credit credit = new Credit(); * CreditCollection creditCollection = credit.getCredits( startIndex, pageSize, sortBy, filter, responseFields); * </code></pre></p> * @param filter A set of filter expressions representing the search parameters for a query. This parameter is optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for a list of supported filters. * @param pageSize When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with this parameter set to 25, to get the 51st through the 75th items, set startIndex to 50. * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. * @param sortBy The element to sort the results by and the channel in which the results appear. Either ascending (a-z) or descending (z-a) channel. Optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for more information. * @param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with pageSize set to 25, to get the 51st through the 75th items, set this parameter to 50. * @return com.mozu.api.contracts.customer.credit.CreditCollection * @see com.mozu.api.contracts.customer.credit.CreditCollection */ public com.mozu.api.contracts.customer.credit.CreditCollection getCredits(Integer startIndex, Integer pageSize, String sortBy, String filter, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.customer.credit.CreditCollection> client = com.mozu.api.clients.commerce.customer.CreditClient.getCreditsClient( startIndex, pageSize, sortBy, filter, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * * <p><pre><code> * Credit credit = new Credit(); * Credit credit = credit.getCredit( code); * </code></pre></p> * @param code User-defined code that uniqely identifies the channel group. * @return com.mozu.api.contracts.customer.credit.Credit * @see com.mozu.api.contracts.customer.credit.Credit */ public com.mozu.api.contracts.customer.credit.Credit getCredit(String code) throws Exception { return getCredit( code, null); } /** * * <p><pre><code> * Credit credit = new Credit(); * Credit credit = credit.getCredit( code, responseFields); * </code></pre></p> * @param code User-defined code that uniqely identifies the channel group. * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. * @return com.mozu.api.contracts.customer.credit.Credit * @see com.mozu.api.contracts.customer.credit.Credit */ public com.mozu.api.contracts.customer.credit.Credit getCredit(String code, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.customer.credit.Credit> client = com.mozu.api.clients.commerce.customer.CreditClient.getCreditClient( code, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * * <p><pre><code> * Credit credit = new Credit(); * Credit credit = credit.addCredit( credit); * </code></pre></p> * @param credit Properties of the store credit of gift card applied to a customer account. At this time, gift card functionality is reserved for future use. * @return com.mozu.api.contracts.customer.credit.Credit * @see com.mozu.api.contracts.customer.credit.Credit * @see com.mozu.api.contracts.customer.credit.Credit */ public com.mozu.api.contracts.customer.credit.Credit addCredit(com.mozu.api.contracts.customer.credit.Credit credit) throws Exception { return addCredit( credit, null, null); } /** * * <p><pre><code> * Credit credit = new Credit(); * Credit credit = credit.addCredit( credit, userId, responseFields); * </code></pre></p> * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. * @param userId Unique identifier of the user whose tenant scopes you want to retrieve. * @param credit Properties of the store credit of gift card applied to a customer account. At this time, gift card functionality is reserved for future use. * @return com.mozu.api.contracts.customer.credit.Credit * @see com.mozu.api.contracts.customer.credit.Credit * @see com.mozu.api.contracts.customer.credit.Credit */ public com.mozu.api.contracts.customer.credit.Credit addCredit(com.mozu.api.contracts.customer.credit.Credit credit, String userId, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.customer.credit.Credit> client = com.mozu.api.clients.commerce.customer.CreditClient.addCreditClient( credit, userId, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * * <p><pre><code> * Credit credit = new Credit(); * Credit credit = credit.associateCreditToShopper( code); * </code></pre></p> * @param code User-defined code that uniqely identifies the channel group. * @return com.mozu.api.contracts.customer.credit.Credit * @see com.mozu.api.contracts.customer.credit.Credit */ public com.mozu.api.contracts.customer.credit.Credit associateCreditToShopper(String code) throws Exception { return associateCreditToShopper( code, null); } /** * * <p><pre><code> * Credit credit = new Credit(); * Credit credit = credit.associateCreditToShopper( code, responseFields); * </code></pre></p> * @param code User-defined code that uniqely identifies the channel group. * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. * @return com.mozu.api.contracts.customer.credit.Credit * @see com.mozu.api.contracts.customer.credit.Credit */ public com.mozu.api.contracts.customer.credit.Credit associateCreditToShopper(String code, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.customer.credit.Credit> client = com.mozu.api.clients.commerce.customer.CreditClient.associateCreditToShopperClient( code, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * * <p><pre><code> * Credit credit = new Credit(); * credit.resendCreditCreatedEmail( code); * </code></pre></p> * @param code User-defined code that uniqely identifies the channel group. * @return */ public void resendCreditCreatedEmail(String code) throws Exception { resendCreditCreatedEmail( code, null); } /** * * <p><pre><code> * Credit credit = new Credit(); * credit.resendCreditCreatedEmail( code, userId); * </code></pre></p> * @param code User-defined code that uniqely identifies the channel group. * @param userId Unique identifier of the user whose tenant scopes you want to retrieve. * @return */ public void resendCreditCreatedEmail(String code, String userId) throws Exception { MozuClient client = com.mozu.api.clients.commerce.customer.CreditClient.resendCreditCreatedEmailClient( code, userId); client.setContext(_apiContext); client.executeRequest(); client.cleanupHttpConnection(); } /** * * <p><pre><code> * Credit credit = new Credit(); * Credit credit = credit.updateCredit( credit, code); * </code></pre></p> * @param code User-defined code that uniqely identifies the channel group. * @param credit Properties of the store credit of gift card applied to a customer account. At this time, gift card functionality is reserved for future use. * @return com.mozu.api.contracts.customer.credit.Credit * @see com.mozu.api.contracts.customer.credit.Credit * @see com.mozu.api.contracts.customer.credit.Credit */ public com.mozu.api.contracts.customer.credit.Credit updateCredit(com.mozu.api.contracts.customer.credit.Credit credit, String code) throws Exception { return updateCredit( credit, code, null); } /** * * <p><pre><code> * Credit credit = new Credit(); * Credit credit = credit.updateCredit( credit, code, responseFields); * </code></pre></p> * @param code User-defined code that uniqely identifies the channel group. * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. * @param credit Properties of the store credit of gift card applied to a customer account. At this time, gift card functionality is reserved for future use. * @return com.mozu.api.contracts.customer.credit.Credit * @see com.mozu.api.contracts.customer.credit.Credit * @see com.mozu.api.contracts.customer.credit.Credit */ public com.mozu.api.contracts.customer.credit.Credit updateCredit(com.mozu.api.contracts.customer.credit.Credit credit, String code, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.customer.credit.Credit> client = com.mozu.api.clients.commerce.customer.CreditClient.updateCreditClient( credit, code, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * * <p><pre><code> * Credit credit = new Credit(); * credit.deleteCredit( code); * </code></pre></p> * @param code User-defined code that uniqely identifies the channel group. * @return */ public void deleteCredit(String code) throws Exception { MozuClient client = com.mozu.api.clients.commerce.customer.CreditClient.deleteCreditClient( code); client.setContext(_apiContext); client.executeRequest(); client.cleanupHttpConnection(); } }
{ "content_hash": "d87f566b853f5c9156383c2e050edd20", "timestamp": "", "source": "github", "line_count": 275, "max_line_length": 312, "avg_line_length": 44.92, "alnum_prop": 0.7268679672953938, "repo_name": "Mozu/mozu-java", "id": "134137561d9b44fea5f35636a4467869bae511a7", "size": "12353", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "mozu-java-core/src/main/java/com/mozu/api/resources/commerce/customer/CreditResource.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "102" }, { "name": "Java", "bytes": "16379616" } ], "symlink_target": "" }
void TxConfirmStats::Initialize(std::vector<double>& defaultBuckets, unsigned int maxConfirms, double _decay) { decay = _decay; for (unsigned int i = 0; i < defaultBuckets.size(); i++) { buckets.push_back(defaultBuckets[i]); bucketMap[defaultBuckets[i]] = i; } confAvg.resize(maxConfirms); curBlockConf.resize(maxConfirms); unconfTxs.resize(maxConfirms); for (unsigned int i = 0; i < maxConfirms; i++) { confAvg[i].resize(buckets.size()); curBlockConf[i].resize(buckets.size()); unconfTxs[i].resize(buckets.size()); } oldUnconfTxs.resize(buckets.size()); curBlockTxCt.resize(buckets.size()); txCtAvg.resize(buckets.size()); curBlockVal.resize(buckets.size()); avg.resize(buckets.size()); } // Zero out the data for the current block void TxConfirmStats::ClearCurrent(unsigned int nBlockHeight) { for (unsigned int j = 0; j < buckets.size(); j++) { oldUnconfTxs[j] += unconfTxs[nBlockHeight%unconfTxs.size()][j]; unconfTxs[nBlockHeight%unconfTxs.size()][j] = 0; for (unsigned int i = 0; i < curBlockConf.size(); i++) curBlockConf[i][j] = 0; curBlockTxCt[j] = 0; curBlockVal[j] = 0; } } void TxConfirmStats::Record(int blocksToConfirm, double val) { // blocksToConfirm is 1-based if (blocksToConfirm < 1) return; unsigned int bucketindex = bucketMap.lower_bound(val)->second; for (size_t i = blocksToConfirm; i <= curBlockConf.size(); i++) { curBlockConf[i - 1][bucketindex]++; } curBlockTxCt[bucketindex]++; curBlockVal[bucketindex] += val; } void TxConfirmStats::UpdateMovingAverages() { for (unsigned int j = 0; j < buckets.size(); j++) { for (unsigned int i = 0; i < confAvg.size(); i++) confAvg[i][j] = confAvg[i][j] * decay + curBlockConf[i][j]; avg[j] = avg[j] * decay + curBlockVal[j]; txCtAvg[j] = txCtAvg[j] * decay + curBlockTxCt[j]; } } // returns -1 on error conditions double TxConfirmStats::EstimateMedianVal(int confTarget, double sufficientTxVal, double successBreakPoint, bool requireGreater, unsigned int nBlockHeight) { // Counters for a bucket (or range of buckets) double nConf = 0; // Number of tx's confirmed within the confTarget double totalNum = 0; // Total number of tx's that were ever confirmed int extraNum = 0; // Number of tx's still in mempool for confTarget or longer int maxbucketindex = buckets.size() - 1; // requireGreater means we are looking for the lowest feerate such that all higher // values pass, so we start at maxbucketindex (highest feerate) and look at successively // smaller buckets until we reach failure. Otherwise, we are looking for the highest // feerate such that all lower values fail, and we go in the opposite direction. unsigned int startbucket = requireGreater ? maxbucketindex : 0; int step = requireGreater ? -1 : 1; // We'll combine buckets until we have enough samples. // The near and far variables will define the range we've combined // The best variables are the last range we saw which still had a high // enough confirmation rate to count as success. // The cur variables are the current range we're counting. unsigned int curNearBucket = startbucket; unsigned int bestNearBucket = startbucket; unsigned int curFarBucket = startbucket; unsigned int bestFarBucket = startbucket; bool foundAnswer = false; unsigned int bins = unconfTxs.size(); // Start counting from highest(default) or lowest feerate transactions for (int bucket = startbucket; bucket >= 0 && bucket <= maxbucketindex; bucket += step) { curFarBucket = bucket; nConf += confAvg[confTarget - 1][bucket]; totalNum += txCtAvg[bucket]; for (unsigned int confct = confTarget; confct < GetMaxConfirms(); confct++) extraNum += unconfTxs[(nBlockHeight - confct)%bins][bucket]; extraNum += oldUnconfTxs[bucket]; // If we have enough transaction data points in this range of buckets, // we can test for success // (Only count the confirmed data points, so that each confirmation count // will be looking at the same amount of data and same bucket breaks) if (totalNum >= sufficientTxVal / (1 - decay)) { double curPct = nConf / (totalNum + extraNum); // Check to see if we are no longer getting confirmed at the success rate if (requireGreater && curPct < successBreakPoint) break; if (!requireGreater && curPct > successBreakPoint) break; // Otherwise update the cumulative stats, and the bucket variables // and reset the counters else { foundAnswer = true; nConf = 0; totalNum = 0; extraNum = 0; bestNearBucket = curNearBucket; bestFarBucket = curFarBucket; curNearBucket = bucket + step; } } } double median = -1; double txSum = 0; // Calculate the "average" feerate of the best bucket range that met success conditions // Find the bucket with the median transaction and then report the average feerate from that bucket // This is a compromise between finding the median which we can't since we don't save all tx's // and reporting the average which is less accurate unsigned int minBucket = bestNearBucket < bestFarBucket ? bestNearBucket : bestFarBucket; unsigned int maxBucket = bestNearBucket > bestFarBucket ? bestNearBucket : bestFarBucket; for (unsigned int j = minBucket; j <= maxBucket; j++) { txSum += txCtAvg[j]; } if (foundAnswer && txSum != 0) { txSum = txSum / 2; for (unsigned int j = minBucket; j <= maxBucket; j++) { if (txCtAvg[j] < txSum) txSum -= txCtAvg[j]; else { // we're in the right bucket median = avg[j] / txCtAvg[j]; break; } } } LogPrint("estimatefee", "%3d: For conf success %s %4.2f need feerate %s: %12.5g from buckets %8g - %8g Cur Bucket stats %6.2f%% %8.1f/(%.1f+%d mempool)\n", confTarget, requireGreater ? ">" : "<", successBreakPoint, requireGreater ? ">" : "<", median, buckets[minBucket], buckets[maxBucket], 100 * nConf / (totalNum + extraNum), nConf, totalNum, extraNum); return median; } void TxConfirmStats::Write(CAutoFile& fileout) { fileout << decay; fileout << buckets; fileout << avg; fileout << txCtAvg; fileout << confAvg; } void TxConfirmStats::Read(CAutoFile& filein) { // Read data file into temporary variables and do some very basic sanity checking std::vector<double> fileBuckets; std::vector<double> fileAvg; std::vector<std::vector<double> > fileConfAvg; std::vector<double> fileTxCtAvg; double fileDecay; size_t maxConfirms; size_t numBuckets; filein >> fileDecay; if (fileDecay <= 0 || fileDecay >= 1) throw std::runtime_error("Corrupt estimates file. Decay must be between 0 and 1 (non-inclusive)"); filein >> fileBuckets; numBuckets = fileBuckets.size(); if (numBuckets <= 1 || numBuckets > 1000) throw std::runtime_error("Corrupt estimates file. Must have between 2 and 1000 feerate buckets"); filein >> fileAvg; if (fileAvg.size() != numBuckets) throw std::runtime_error("Corrupt estimates file. Mismatch in feerate average bucket count"); filein >> fileTxCtAvg; if (fileTxCtAvg.size() != numBuckets) throw std::runtime_error("Corrupt estimates file. Mismatch in tx count bucket count"); filein >> fileConfAvg; maxConfirms = fileConfAvg.size(); if (maxConfirms <= 0 || maxConfirms > 6 * 24 * 7) // one week throw std::runtime_error("Corrupt estimates file. Must maintain estimates for between 1 and 1008 (one week) confirms"); for (unsigned int i = 0; i < maxConfirms; i++) { if (fileConfAvg[i].size() != numBuckets) throw std::runtime_error("Corrupt estimates file. Mismatch in feerate conf average bucket count"); } // Now that we've processed the entire feerate estimate data file and not // thrown any errors, we can copy it to our data structures decay = fileDecay; buckets = fileBuckets; avg = fileAvg; confAvg = fileConfAvg; txCtAvg = fileTxCtAvg; bucketMap.clear(); // Resize the current block variables which aren't stored in the data file // to match the number of confirms and buckets curBlockConf.resize(maxConfirms); for (unsigned int i = 0; i < maxConfirms; i++) { curBlockConf[i].resize(buckets.size()); } curBlockTxCt.resize(buckets.size()); curBlockVal.resize(buckets.size()); unconfTxs.resize(maxConfirms); for (unsigned int i = 0; i < maxConfirms; i++) { unconfTxs[i].resize(buckets.size()); } oldUnconfTxs.resize(buckets.size()); for (unsigned int i = 0; i < buckets.size(); i++) bucketMap[buckets[i]] = i; LogPrint("estimatefee", "Reading estimates: %u buckets counting confirms up to %u blocks\n", numBuckets, maxConfirms); } unsigned int TxConfirmStats::NewTx(unsigned int nBlockHeight, double val) { unsigned int bucketindex = bucketMap.lower_bound(val)->second; unsigned int blockIndex = nBlockHeight % unconfTxs.size(); unconfTxs[blockIndex][bucketindex]++; return bucketindex; } void TxConfirmStats::removeTx(unsigned int entryHeight, unsigned int nBestSeenHeight, unsigned int bucketindex) { //nBestSeenHeight is not updated yet for the new block int blocksAgo = nBestSeenHeight - entryHeight; if (nBestSeenHeight == 0) // the BlockPolicyEstimator hasn't seen any blocks yet blocksAgo = 0; if (blocksAgo < 0) { LogPrint("estimatefee", "Blockpolicy error, blocks ago is negative for mempool tx\n"); return; //This can't happen because we call this with our best seen height, no entries can have higher } if (blocksAgo >= (int)unconfTxs.size()) { if (oldUnconfTxs[bucketindex] > 0) oldUnconfTxs[bucketindex]--; else LogPrint("estimatefee", "Blockpolicy error, mempool tx removed from >25 blocks,bucketIndex=%u already\n", bucketindex); } else { unsigned int blockIndex = entryHeight % unconfTxs.size(); if (unconfTxs[blockIndex][bucketindex] > 0) unconfTxs[blockIndex][bucketindex]--; else LogPrint("estimatefee", "Blockpolicy error, mempool tx removed from blockIndex=%u,bucketIndex=%u already\n", blockIndex, bucketindex); } } void CBlockPolicyEstimator::removeTx(uint256 hash) { std::map<uint256, TxStatsInfo>::iterator pos = mapMemPoolTxs.find(hash); if (pos == mapMemPoolTxs.end()) { LogPrint("estimatefee", "Blockpolicy error mempool tx %s not found for removeTx\n", hash.ToString().c_str()); return; } unsigned int entryHeight = pos->second.blockHeight; unsigned int bucketIndex = pos->second.bucketIndex; feeStats.removeTx(entryHeight, nBestSeenHeight, bucketIndex); mapMemPoolTxs.erase(hash); } CBlockPolicyEstimator::CBlockPolicyEstimator(const CFeeRate& _minRelayFee) : nBestSeenHeight(0) { minTrackedFee = _minRelayFee < CFeeRate(MIN_FEERATE) ? CFeeRate(MIN_FEERATE) : _minRelayFee; std::vector<double> vfeelist; for (double bucketBoundary = minTrackedFee.GetFeePerK(); bucketBoundary <= MAX_FEERATE; bucketBoundary *= FEE_SPACING) { vfeelist.push_back(bucketBoundary); } vfeelist.push_back(INF_FEERATE); feeStats.Initialize(vfeelist, MAX_BLOCK_CONFIRMS, DEFAULT_DECAY); } void CBlockPolicyEstimator::processTransaction(const CTxMemPoolEntry& entry, bool fCurrentEstimate) { unsigned int txHeight = entry.GetHeight(); uint256 hash = entry.GetTx().GetHash(); if (mapMemPoolTxs.count(hash)) { LogPrint("estimatefee", "Blockpolicy error mempool tx %s already being tracked\n", hash.ToString().c_str()); return; } if (txHeight < nBestSeenHeight) { // Ignore side chains and re-orgs; assuming they are random they don't // affect the estimate. We'll potentially double count transactions in 1-block reorgs. return; } // Only want to be updating estimates when our blockchain is synced, // otherwise we'll miscalculate how many blocks its taking to get included. if (!fCurrentEstimate) return; if (!entry.WasClearAtEntry()) { // This transaction depends on other transactions in the mempool to // be included in a block before it will be able to be included, so // we shouldn't include it in our calculations return; } // Feerates are stored and reported as BTC-per-kb: CFeeRate feeRate(entry.GetFee(), entry.GetTxSize()); mapMemPoolTxs[hash].blockHeight = txHeight; mapMemPoolTxs[hash].bucketIndex = feeStats.NewTx(txHeight, (double)feeRate.GetFeePerK()); } void CBlockPolicyEstimator::processBlockTx(unsigned int nBlockHeight, const CTxMemPoolEntry& entry) { if (!entry.WasClearAtEntry()) { // This transaction depended on other transactions in the mempool to // be included in a block before it was able to be included, so // we shouldn't include it in our calculations return; } // How many blocks did it take for miners to include this transaction? // blocksToConfirm is 1-based, so a transaction included in the earliest // possible block has confirmation count of 1 int blocksToConfirm = nBlockHeight - entry.GetHeight(); if (blocksToConfirm <= 0) { // This can't happen because we don't process transactions from a block with a height // lower than our greatest seen height LogPrint("estimatefee", "Blockpolicy error Transaction had negative blocksToConfirm\n"); return; } // Feerates are stored and reported as BTC-per-kb: CFeeRate feeRate(entry.GetFee(), entry.GetTxSize()); feeStats.Record(blocksToConfirm, (double)feeRate.GetFeePerK()); } void CBlockPolicyEstimator::processBlock(unsigned int nBlockHeight, std::vector<CTxMemPoolEntry>& entries, bool fCurrentEstimate) { if (nBlockHeight <= nBestSeenHeight) { // Ignore side chains and re-orgs; assuming they are random // they don't affect the estimate. // And if an attacker can re-org the chain at will, then // you've got much bigger problems than "attacker can influence // transaction fees." return; } nBestSeenHeight = nBlockHeight; // Only want to be updating estimates when our blockchain is synced, // otherwise we'll miscalculate how many blocks its taking to get included. if (!fCurrentEstimate) return; // Clear the current block state feeStats.ClearCurrent(nBlockHeight); // Repopulate the current block states for (unsigned int i = 0; i < entries.size(); i++) processBlockTx(nBlockHeight, entries[i]); // Update all exponential averages with the current block state feeStats.UpdateMovingAverages(); LogPrint("estimatefee", "Blockpolicy after updating estimates for %u confirmed entries, new mempool map size %u\n", entries.size(), mapMemPoolTxs.size()); } CFeeRate CBlockPolicyEstimator::estimateFee(int confTarget) { // Return failure if trying to analyze a target we're not tracking // It's not possible to get reasonable estimates for confTarget of 1 if (confTarget <= 1 || (unsigned int)confTarget > feeStats.GetMaxConfirms()) return CFeeRate(0); double median = feeStats.EstimateMedianVal(confTarget, SUFFICIENT_FEETXS, MIN_SUCCESS_PCT, true, nBestSeenHeight); if (median < 0) return CFeeRate(0); return CFeeRate(median); } CFeeRate CBlockPolicyEstimator::estimateSmartFee(int confTarget, int *answerFoundAtTarget, const CTxMemPool& pool) { if (answerFoundAtTarget) *answerFoundAtTarget = confTarget; // Return failure if trying to analyze a target we're not tracking if (confTarget <= 0 || (unsigned int)confTarget > feeStats.GetMaxConfirms()) return CFeeRate(0); // It's not possible to get reasonable estimates for confTarget of 1 if (confTarget == 1) confTarget = 2; double median = -1; while (median < 0 && (unsigned int)confTarget <= feeStats.GetMaxConfirms()) { median = feeStats.EstimateMedianVal(confTarget++, SUFFICIENT_FEETXS, MIN_SUCCESS_PCT, true, nBestSeenHeight); } if (answerFoundAtTarget) *answerFoundAtTarget = confTarget - 1; // If mempool is limiting txs , return at least the min feerate from the mempool CAmount minPoolFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK(); if (minPoolFee > 0 && minPoolFee > median) return CFeeRate(minPoolFee); if (median < 0) return CFeeRate(0); return CFeeRate(median); } double CBlockPolicyEstimator::estimatePriority(int confTarget) { return -1; } double CBlockPolicyEstimator::estimateSmartPriority(int confTarget, int *answerFoundAtTarget, const CTxMemPool& pool) { if (answerFoundAtTarget) *answerFoundAtTarget = confTarget; // If mempool is limiting txs, no priority txs are allowed CAmount minPoolFee = pool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK(); if (minPoolFee > 0) return INF_PRIORITY; return -1; } void CBlockPolicyEstimator::Write(CAutoFile& fileout) { fileout << nBestSeenHeight; feeStats.Write(fileout); } void CBlockPolicyEstimator::Read(CAutoFile& filein, int nFileVersion) { int nFileBestSeenHeight; filein >> nFileBestSeenHeight; feeStats.Read(filein); nBestSeenHeight = nFileBestSeenHeight; if (nFileVersion < 139900) { TxConfirmStats priStats; priStats.Read(filein); } } FeeFilterRounder::FeeFilterRounder(const CFeeRate& minIncrementalFee) { CAmount minFeeLimit = minIncrementalFee.GetFeePerK() / 2; feeset.insert(0); for (double bucketBoundary = minFeeLimit; bucketBoundary <= MAX_FEERATE; bucketBoundary *= FEE_SPACING) { feeset.insert(bucketBoundary); } } CAmount FeeFilterRounder::round(CAmount currentMinFee) { std::set<double>::iterator it = feeset.lower_bound(currentMinFee); if ((it != feeset.begin() && insecure_rand.rand32() % 3 != 0) || it == feeset.end()) { it--; } return *it; }
{ "content_hash": "e451cded2f05e8a1a55cbf2ab1a23c7a", "timestamp": "", "source": "github", "line_count": 487, "max_line_length": 161, "avg_line_length": 38.90965092402464, "alnum_prop": 0.6600876035674705, "repo_name": "ahmedbodi/temp_vert", "id": "9eb831bc17c42efd26a475d6451583d7183f5c49", "size": "19380", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/policy/fees.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "28456" }, { "name": "C", "bytes": "693477" }, { "name": "C++", "bytes": "4841420" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50622" }, { "name": "Java", "bytes": "30290" }, { "name": "M4", "bytes": "185640" }, { "name": "Makefile", "bytes": "108460" }, { "name": "Objective-C", "bytes": "3892" }, { "name": "Objective-C++", "bytes": "7243" }, { "name": "Protocol Buffer", "bytes": "2328" }, { "name": "Python", "bytes": "1076463" }, { "name": "QMake", "bytes": "756" }, { "name": "Shell", "bytes": "48198" } ], "symlink_target": "" }
This is the code used to create my website. ### Version 1.0
{ "content_hash": "907d4c7c10204d5bcbe97587c2ff41ed", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 43, "avg_line_length": 15, "alnum_prop": 0.7166666666666667, "repo_name": "hasanayesha/hasanayesha.github.io", "id": "560b1c4d9a524cbcd3c7a84ff70dd1ccefdf095b", "size": "70", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "127063" }, { "name": "HTML", "bytes": "20728" }, { "name": "JavaScript", "bytes": "43258" }, { "name": "PHP", "bytes": "1090" } ], "symlink_target": "" }
package com.kc.shiptransport.mvp.contacts; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ExpandableListView; import com.chad.library.adapter.base.entity.MultiItemEntity; import com.kc.shiptransport.R; import com.kc.shiptransport.adapter.ExpandableItemAdapter; import com.kc.shiptransport.db.contacts.Contacts; import com.kc.shiptransport.entity.Level0Item; import com.kc.shiptransport.entity.Level1Item; import com.kc.shiptransport.entity.Level2Item; import com.kc.shiptransport.entity.Level3Item; import com.kc.shiptransport.entity.Level4Item; import com.kc.shiptransport.entity.Person; import org.litepal.crud.DataSupport; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; /** * @author 邱永恒 * @time 2017/8/14 10:19 * @desc ${TODD} */ public class ContactOrganFragment extends Fragment { @BindView(R.id.expand_list_view) ExpandableListView expandListView; @BindView(R.id.recycler_view) RecyclerView recyclerView; Unbinder unbinder; private ArrayList<MultiItemEntity> root; private ExpandableItemAdapter adapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_contact_organ, container, false); unbinder = ButterKnife.bind(this, view); initView(); initData(); return view; } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } private void initView() { recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); } /** * 初始化数据 */ private void initData() { root = generateData(); adapter = new ExpandableItemAdapter(getContext(), root); recyclerView.setAdapter(adapter); adapter.expand(0); } /** * 准备多级数据集 * * @return */ private ArrayList<MultiItemEntity> generateData() { // /** 1. 获取层级 */ // Cursor cursor = DataSupport.findBySQL("SELECT DISTINCT PId FROM Contacts"); // List<Map> maps = DBUtil.queryListMap(cursor); /** 1. 根目录 */ ArrayList<MultiItemEntity> res = new ArrayList<>(); /** 一级 */ List<Contacts> lv0List = DataSupport.where("PId = ?", String.valueOf(0)).find(Contacts.class); for (int i = 0; i < lv0List.size(); i++) { Level0Item lv0 = new Level0Item(lv0List.get(i).getDepartment()); /** 二级 */ List<Contacts> lv1List = DataSupport.where("PId = ?", String.valueOf(lv0List.get(i).getCId())).find(Contacts.class); for (int j = 0; j < lv1List.size(); j++) { Contacts contacts = lv1List.get(j); /** 判断是部门还是联系人 */ if (!TextUtils.isEmpty(contacts.getLoginName())) { /** 联系人 */ Person person = new Person(); person.setRownumber(contacts.getRownumber()); person.setItemID(contacts.getItemID()); person.setCId(contacts.getCId()); person.setPId(contacts.getPId()); person.setLoginName(contacts.getLoginName()); person.setEnglishName(contacts.getEnglishName()); person.setEmail(contacts.getEmail()); person.setDuties(contacts.getDuties()); person.setMobile(contacts.getMobile()); person.setTelephoneNumber(contacts.getTelephoneNumber()); person.setSex(contacts.getSex()); person.setDepartment(contacts.getDepartment()); person.setDisplayName(contacts.getDisplayName()); lv0.addSubItem(person); } else { /** 部门, 继续递归 */ Level1Item lv1 = new Level1Item(contacts.getDepartment()); lv0.addSubItem(lv1); /** 三级 */ List<Contacts> lv2List = DataSupport.where("PId = ?", String.valueOf(contacts.getCId())).find(Contacts.class); for (int k = 0; k < lv2List.size(); k++) { Contacts contacts2 = lv2List.get(k); /** 判断是部门还是联系人 */ if (!TextUtils.isEmpty(contacts2.getLoginName())) { /** 联系人 */ Person person = new Person(); person.setRownumber(contacts2.getRownumber()); person.setItemID(contacts2.getItemID()); person.setCId(contacts2.getCId()); person.setPId(contacts2.getPId()); person.setLoginName(contacts2.getLoginName()); person.setEnglishName(contacts2.getEnglishName()); person.setEmail(contacts2.getEmail()); person.setDuties(contacts2.getDuties()); person.setMobile(contacts2.getMobile()); person.setTelephoneNumber(contacts2.getTelephoneNumber()); person.setSex(contacts2.getSex()); person.setDepartment(contacts2.getDepartment()); person.setDisplayName(contacts2.getDisplayName()); lv1.addSubItem(person); } else { /** 部门, 继续递归 */ Level2Item lv2 = new Level2Item(contacts2.getDepartment()); lv1.addSubItem(lv2); /** 四级 */ List<Contacts> lv3List = DataSupport.where("PId = ?", String.valueOf(contacts2.getCId())).find(Contacts.class); for (int h = 0; h < lv3List.size(); h++) { Contacts contacts3 = lv3List.get(h); /** 判断是部门还是联系人 */ if (!TextUtils.isEmpty(contacts3.getLoginName())) { /** 联系人 */ Person person = new Person(); person.setRownumber(contacts3.getRownumber()); person.setItemID(contacts3.getItemID()); person.setCId(contacts3.getCId()); person.setPId(contacts3.getPId()); person.setLoginName(contacts3.getLoginName()); person.setEnglishName(contacts3.getEnglishName()); person.setEmail(contacts3.getEmail()); person.setDuties(contacts3.getDuties()); person.setMobile(contacts3.getMobile()); person.setTelephoneNumber(contacts3.getTelephoneNumber()); person.setSex(contacts3.getSex()); person.setDepartment(contacts3.getDepartment()); person.setDisplayName(contacts3.getDisplayName()); lv2.addSubItem(person); } else { /** 部门, 继续递归 */ Level3Item lv3 = new Level3Item(contacts3.getDepartment()); lv2.addSubItem(lv3); /** 五级 */ List<Contacts> lv4List = DataSupport.where("PId = ?", String.valueOf(contacts3.getCId())).find(Contacts.class); for (int g = 0; g < lv4List.size(); g++) { Contacts contacts4 = lv4List.get(g); /** 判断是部门还是联系人 */ if (!TextUtils.isEmpty(contacts4.getLoginName())) { /** 联系人 */ Person person = new Person(); person.setRownumber(contacts4.getRownumber()); person.setItemID(contacts4.getItemID()); person.setCId(contacts4.getCId()); person.setPId(contacts4.getPId()); person.setLoginName(contacts4.getLoginName()); person.setEnglishName(contacts4.getEnglishName()); person.setEmail(contacts4.getEmail()); person.setDuties(contacts4.getDuties()); person.setMobile(contacts4.getMobile()); person.setTelephoneNumber(contacts4.getTelephoneNumber()); person.setSex(contacts4.getSex()); person.setDepartment(contacts4.getDepartment()); person.setDisplayName(contacts4.getDisplayName()); lv3.addSubItem(person); } else { /** 部门, 停止递归 */ Level4Item lv4 = new Level4Item(contacts4.getDepartment()); lv3.addSubItem(lv4); } } } } } } } } res.add(lv0); } return res; } }
{ "content_hash": "c583c80213ebe0b7327f86b9d8202a78", "timestamp": "", "source": "github", "line_count": 223, "max_line_length": 147, "avg_line_length": 46.600896860986545, "alnum_prop": 0.49105080831408776, "repo_name": "qiu-yongheng/Ship", "id": "5fec3b4661ba60f90a5c1b372b6c7772d9860cbc", "size": "10608", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/kc/shiptransport/mvp/contacts/ContactOrganFragment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2949277" } ], "symlink_target": "" }
#ifndef BLORB_H #define BLORB_H /* blorb.h: Header file for Blorb library, version 1.0.2. Designed by Andrew Plotkin <erkyrath@eblong.com> http://www.eblong.com/zarf/blorb/index.html This is the header that a Z-machine interpreter should include. It defines everything that the interpreter has to know. */ /* Things you (the porter) have to edit: */ /* As you might expect, uint32 must be a 32-bit unsigned numeric type, and uint16 a 16-bit unsigned numeric type. You should also uncomment exactly one of the two ENDIAN definitions. */ /* #define BLORB_BIG_ENDIAN */ #define BLORB_LITTLE_ENDIAN typedef unsigned long uint32; typedef unsigned short uint16; /* End of things you have to edit. */ #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif /* Error type and error codes */ typedef int bb_err_t; #define bb_err_None (0) #define bb_err_CompileTime (1) #define bb_err_Alloc (2) #define bb_err_Read (3) #define bb_err_NotAMap (4) #define bb_err_Format (5) #define bb_err_NotFound (6) /* Methods for loading a chunk */ #define bb_method_DontLoad (0) #define bb_method_Memory (1) #define bb_method_FilePos (2) /* Four-byte constants */ /*#define bb_make_id(c1, c2, c3, c4) \ (((c1) << 24) | ((c2) << 16) | ((c3) << 8) | (c4)) */ #define bb_ID_Snd 1399743520 #define bb_ID_Exec 1165518179 #define bb_ID_Pict 1349084020 #define bb_ID_Copyright 677587232 #define bb_ID_AUTH 1096111176 #define bb_ID_ANNO 1095650895 #define bb_ID_ZCOD 1514360644 /* bb_result_t: Result when you try to load a chunk. */ typedef struct bb_result_struct { int chunknum; /* The chunk number (for use in bb_unload_chunk(), etc.) */ union { void *ptr; /* A pointer to the data (if you used bb_method_Memory) */ uint32 startpos; /* The position in the file (if you used bb_method_FilePos) */ } data; uint32 length; /* The length of the data */ } bb_result_t; /* bb_aux_sound_t: Extra data which may be associated with a sound. */ typedef struct bb_aux_sound_struct { char repeats; } bb_aux_sound_t; /* bb_aux_pict_t: Extra data which may be associated with an image. */ typedef struct bb_aux_pict_struct { uint32 ratnum, ratden; uint32 minnum, minden; uint32 maxnum, maxden; } bb_aux_pict_t; /* bb_resolution_t: The global resolution data. */ typedef struct bb_resolution_struct { uint32 px, py; uint32 minx, miny; uint32 maxx, maxy; } bb_resolution_t; /* bb_color_t: Guess what. */ typedef struct bb_color_struct { unsigned char red, green, blue; } bb_color_t; /* bb_palette_t: The palette data. */ typedef struct bb_palette_struct { int isdirect; union { int depth; /* The depth (if isdirect is TRUE). Either 16 or 32. */ struct { int numcolors; bb_color_t *colors; } table; /* The list of colors (if isdirect is FALSE). */ } data; } bb_palette_t; /* bb_zheader_t: Information to identify a Z-code file. */ typedef struct bb_zheader_struct { uint16 releasenum; /* Bytes $2-3 of header. */ char serialnum[6]; /* Bytes $12-17 of header. */ uint16 checksum; /* Bytes $1C-1D of header. */ /* The initpc field is not used by Blorb. */ } bb_zheader_t; /* bb_map_t: Holds the complete description of an open Blorb file. This type is opaque for normal interpreter use. */ typedef struct bb_map_struct bb_map_t; /* Function declarations. These functions are of fairly general use; they would apply to any Blorb file. */ extern bb_err_t bb_create_map(FILE *file, bb_map_t **newmap); extern bb_err_t bb_destroy_map(bb_map_t *map); extern char *bb_err_to_string(bb_err_t err); extern bb_err_t bb_load_chunk_by_type(bb_map_t *map, int method, bb_result_t *res, uint32 chunktype, int count); extern bb_err_t bb_load_chunk_by_number(bb_map_t *map, int method, bb_result_t *res, int chunknum); extern bb_err_t bb_unload_chunk(bb_map_t *map, int chunknum); extern bb_err_t bb_load_resource(bb_map_t *map, int method, bb_result_t *res, uint32 usage, int resnum); extern bb_err_t bb_count_resources(bb_map_t *map, uint32 usage, int *num, int *min, int *max); /* More function declarations. These functions are more or less specific to the Z-machine's use of Blorb. */ extern uint16 bb_get_release_num(bb_map_t *map); extern bb_zheader_t *bb_get_zheader(bb_map_t *map); extern bb_resolution_t *bb_get_resolution(bb_map_t *map); extern bb_err_t bb_get_palette(bb_map_t *map, bb_palette_t **res); extern bb_err_t bb_load_resource_pict(bb_map_t *map, int method, bb_result_t *res, int resnum, bb_aux_pict_t **auxdata); extern bb_err_t bb_load_resource_snd(bb_map_t *map, int method, bb_result_t *res, int resnum, bb_aux_sound_t **auxdata); #endif /* BLORB_H */
{ "content_hash": "8fdbe780afcc50cc2e951522c3818287", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 87, "avg_line_length": 31.36842105263158, "alnum_prop": 0.6791107382550335, "repo_name": "century-arcade/src", "id": "5a0694c214b9dc426f41a150dfed6bf94923b7b3", "size": "4768", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "zmachine/frotz/src/dos/blorb.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "811" }, { "name": "Batchfile", "bytes": "67232" }, { "name": "C", "bytes": "22268530" }, { "name": "C++", "bytes": "800699" }, { "name": "CSS", "bytes": "2096" }, { "name": "HTML", "bytes": "839789" }, { "name": "IGOR Pro", "bytes": "2358" }, { "name": "M4", "bytes": "12872" }, { "name": "Makefile", "bytes": "3268525" }, { "name": "NASL", "bytes": "5805" }, { "name": "Objective-C", "bytes": "577067" }, { "name": "PHP", "bytes": "2517" }, { "name": "Perl", "bytes": "80829" }, { "name": "Roff", "bytes": "2910746" }, { "name": "Shell", "bytes": "448030" }, { "name": "SourcePawn", "bytes": "2742" }, { "name": "Starlark", "bytes": "289" }, { "name": "TeX", "bytes": "317417" }, { "name": "sed", "bytes": "9621" } ], "symlink_target": "" }
#include "config.h" #include "ContentExtensionsBackend.h" #if ENABLE(CONTENT_EXTENSIONS) #include "Chrome.h" #include "ChromeClient.h" #include "CompiledContentExtension.h" #include "ContentExtension.h" #include "ContentExtensionsDebugging.h" #include "DFABytecodeInterpreter.h" #include "Document.h" #include "DocumentLoader.h" #include "ExtensionStyleSheets.h" #include "Frame.h" #include "FrameLoaderClient.h" #include "MainFrame.h" #include "Page.h" #include "ResourceLoadInfo.h" #include "URL.h" #include "UserContentController.h" #include <wtf/NeverDestroyed.h> #include <wtf/text/CString.h> namespace WebCore { namespace ContentExtensions { void ContentExtensionsBackend::addContentExtension(const String& identifier, Ref<CompiledContentExtension> compiledContentExtension) { ASSERT(!identifier.isEmpty()); if (identifier.isEmpty()) return; auto contentExtension = ContentExtension::create(identifier, WTFMove(compiledContentExtension)); m_contentExtensions.set(identifier, WTFMove(contentExtension)); } void ContentExtensionsBackend::removeContentExtension(const String& identifier) { m_contentExtensions.remove(identifier); } void ContentExtensionsBackend::removeAllContentExtensions() { m_contentExtensions.clear(); } std::pair<Vector<Action>, Vector<String>> ContentExtensionsBackend::actionsForResourceLoad(const ResourceLoadInfo& resourceLoadInfo) const { #if CONTENT_EXTENSIONS_PERFORMANCE_REPORTING double addedTimeStart = monotonicallyIncreasingTime(); #endif if (m_contentExtensions.isEmpty() || !resourceLoadInfo.resourceURL.isValid() || resourceLoadInfo.resourceURL.protocolIsData()) return { }; const String& urlString = resourceLoadInfo.resourceURL.string(); ASSERT_WITH_MESSAGE(urlString.isAllASCII(), "A decoded URL should only contain ASCII characters. The matching algorithm assumes the input is ASCII."); const auto urlCString = urlString.utf8(); Vector<Action> finalActions; Vector<String> stylesheetIdentifiers; ResourceFlags flags = resourceLoadInfo.getResourceFlags(); for (auto& contentExtension : m_contentExtensions.values()) { const CompiledContentExtension& compiledExtension = contentExtension->compiledExtension(); DFABytecodeInterpreter withoutConditionsInterpreter(compiledExtension.filtersWithoutConditionsBytecode(), compiledExtension.filtersWithoutConditionsBytecodeLength()); DFABytecodeInterpreter::Actions withoutConditionsActions = withoutConditionsInterpreter.interpret(urlCString, flags); URL topURL = resourceLoadInfo.mainDocumentURL; DFABytecodeInterpreter withConditionsInterpreter(compiledExtension.filtersWithConditionsBytecode(), compiledExtension.filtersWithConditionsBytecodeLength()); DFABytecodeInterpreter::Actions withConditionsActions = withConditionsInterpreter.interpretWithConditions(urlCString, flags, contentExtension->topURLActions(topURL)); const SerializedActionByte* actions = compiledExtension.actions(); const unsigned actionsLength = compiledExtension.actionsLength(); bool sawIgnorePreviousRules = false; const Vector<uint32_t>& universalWithConditions = contentExtension->universalActionsWithConditions(topURL); const Vector<uint32_t>& universalWithoutConditions = contentExtension->universalActionsWithoutConditions(); if (!withoutConditionsActions.isEmpty() || !withConditionsActions.isEmpty() || !universalWithConditions.isEmpty() || !universalWithoutConditions.isEmpty()) { Vector<uint32_t> actionLocations; actionLocations.reserveInitialCapacity(withoutConditionsActions.size() + withConditionsActions.size() + universalWithoutConditions.size() + universalWithConditions.size()); for (uint64_t actionLocation : withoutConditionsActions) actionLocations.uncheckedAppend(static_cast<uint32_t>(actionLocation)); for (uint64_t actionLocation : withConditionsActions) actionLocations.uncheckedAppend(static_cast<uint32_t>(actionLocation)); for (uint32_t actionLocation : universalWithoutConditions) actionLocations.uncheckedAppend(actionLocation); for (uint32_t actionLocation : universalWithConditions) actionLocations.uncheckedAppend(actionLocation); std::sort(actionLocations.begin(), actionLocations.end()); // Add actions in reverse order to properly deal with IgnorePreviousRules. for (unsigned i = actionLocations.size(); i; i--) { Action action = Action::deserialize(actions, actionsLength, actionLocations[i - 1]); action.setExtensionIdentifier(contentExtension->identifier()); if (action.type() == ActionType::IgnorePreviousRules) { sawIgnorePreviousRules = true; break; } finalActions.append(action); } } if (!sawIgnorePreviousRules) stylesheetIdentifiers.append(contentExtension->identifier()); } #if CONTENT_EXTENSIONS_PERFORMANCE_REPORTING double addedTimeEnd = monotonicallyIncreasingTime(); dataLogF("Time added: %f microseconds %s \n", (addedTimeEnd - addedTimeStart) * 1.0e6, resourceLoadInfo.resourceURL.string().utf8().data()); #endif return { WTFMove(finalActions), WTFMove(stylesheetIdentifiers) }; } void ContentExtensionsBackend::forEach(const WTF::Function<void(const String&, ContentExtension&)>& apply) { for (auto& pair : m_contentExtensions) apply(pair.key, pair.value); } StyleSheetContents* ContentExtensionsBackend::globalDisplayNoneStyleSheet(const String& identifier) const { const auto& contentExtension = m_contentExtensions.get(identifier); return contentExtension ? contentExtension->globalDisplayNoneStyleSheet() : nullptr; } BlockedStatus ContentExtensionsBackend::processContentExtensionRulesForLoad(const URL& url, ResourceType resourceType, DocumentLoader& initiatingDocumentLoader) { if (m_contentExtensions.isEmpty()) return { }; Document* currentDocument = nullptr; URL mainDocumentURL; if (Frame* frame = initiatingDocumentLoader.frame()) { currentDocument = frame->document(); if (initiatingDocumentLoader.isLoadingMainResource() && frame->isMainFrame() && resourceType == ResourceType::Document) mainDocumentURL = url; else if (Document* mainDocument = frame->mainFrame().document()) mainDocumentURL = mainDocument->url(); } ResourceLoadInfo resourceLoadInfo = { url, mainDocumentURL, resourceType }; auto actions = actionsForResourceLoad(resourceLoadInfo); bool willBlockLoad = false; bool willBlockCookies = false; bool willMakeHTTPS = false; HashSet<std::pair<String, String>> notifications; for (const auto& action : actions.first) { switch (action.type()) { case ContentExtensions::ActionType::BlockLoad: willBlockLoad = true; break; case ContentExtensions::ActionType::BlockCookies: willBlockCookies = true; break; case ContentExtensions::ActionType::CSSDisplayNoneSelector: if (resourceType == ResourceType::Document) initiatingDocumentLoader.addPendingContentExtensionDisplayNoneSelector(action.extensionIdentifier(), action.stringArgument(), action.actionID()); else if (currentDocument) currentDocument->extensionStyleSheets().addDisplayNoneSelector(action.extensionIdentifier(), action.stringArgument(), action.actionID()); break; case ContentExtensions::ActionType::Notify: notifications.add(std::make_pair(action.extensionIdentifier(), action.stringArgument())); break; case ContentExtensions::ActionType::MakeHTTPS: { if ((url.protocolIs("http") || url.protocolIs("ws")) && (!url.port() || isDefaultPortForProtocol(url.port().value(), url.protocol()))) willMakeHTTPS = true; break; } case ContentExtensions::ActionType::IgnorePreviousRules: RELEASE_ASSERT_NOT_REACHED(); } } for (const auto& identifier : actions.second) { if (auto* styleSheetContents = globalDisplayNoneStyleSheet(identifier)) { if (resourceType == ResourceType::Document) initiatingDocumentLoader.addPendingContentExtensionSheet(identifier, *styleSheetContents); else if (currentDocument) currentDocument->extensionStyleSheets().maybeAddContentExtensionSheet(identifier, *styleSheetContents); } } if (currentDocument) { if (willMakeHTTPS) { ASSERT(url.protocolIs("http") || url.protocolIs("ws")); String newProtocol = url.protocolIs("http") ? ASCIILiteral("https") : ASCIILiteral("wss"); currentDocument->addConsoleMessage(MessageSource::ContentBlocker, MessageLevel::Info, makeString("Content blocker promoted URL from ", url.string(), " to ", newProtocol)); } if (willBlockLoad) currentDocument->addConsoleMessage(MessageSource::ContentBlocker, MessageLevel::Info, makeString("Content blocker prevented frame displaying ", mainDocumentURL.string(), " from loading a resource from ", url.string())); } return { willBlockLoad, willBlockCookies, willMakeHTTPS, WTFMove(notifications) }; } BlockedStatus ContentExtensionsBackend::processContentExtensionRulesForPingLoad(const URL& url, const URL& mainDocumentURL) { if (m_contentExtensions.isEmpty()) return { }; ResourceLoadInfo resourceLoadInfo = { url, mainDocumentURL, ResourceType::Raw }; auto actions = actionsForResourceLoad(resourceLoadInfo); bool willBlockLoad = false; bool willBlockCookies = false; bool willMakeHTTPS = false; for (const auto& action : actions.first) { switch (action.type()) { case ContentExtensions::ActionType::BlockLoad: willBlockLoad = true; break; case ContentExtensions::ActionType::BlockCookies: willBlockCookies = true; break; case ContentExtensions::ActionType::MakeHTTPS: if ((url.protocolIs("http") || url.protocolIs("ws")) && (!url.port() || isDefaultPortForProtocol(url.port().value(), url.protocol()))) willMakeHTTPS = true; break; case ContentExtensions::ActionType::CSSDisplayNoneSelector: case ContentExtensions::ActionType::Notify: break; case ContentExtensions::ActionType::IgnorePreviousRules: RELEASE_ASSERT_NOT_REACHED(); } } return { willBlockLoad, willBlockCookies, willMakeHTTPS, { } }; } const String& ContentExtensionsBackend::displayNoneCSSRule() { static NeverDestroyed<const String> rule(MAKE_STATIC_STRING_IMPL("display:none !important;")); return rule; } void applyBlockedStatusToRequest(const BlockedStatus& status, Page* page, ResourceRequest& request) { if (page && !status.notifications.isEmpty()) page->chrome().client().contentRuleListNotification(request.url(), status.notifications); if (status.blockedCookies) request.setAllowCookies(false); if (status.madeHTTPS) { const URL& originalURL = request.url(); ASSERT(originalURL.protocolIs("http")); ASSERT(!originalURL.port() || isDefaultPortForProtocol(originalURL.port().value(), originalURL.protocol())); URL newURL = originalURL; newURL.setProtocol("https"); if (originalURL.port()) newURL.setPort(defaultPortForProtocol("https").value()); request.setURL(newURL); } } } // namespace ContentExtensions } // namespace WebCore #endif // ENABLE(CONTENT_EXTENSIONS)
{ "content_hash": "2d27103643755f9c87e910af6ec37b0b", "timestamp": "", "source": "github", "line_count": 270, "max_line_length": 231, "avg_line_length": 44.37407407407407, "alnum_prop": 0.7046156414322677, "repo_name": "gubaojian/trylearn", "id": "f811e9e97ed8ddd58af3e4dea97523149caac3ee", "size": "13340", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WebLayoutCore/Source/WebCore/contentextensions/ContentExtensionsBackend.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "AspectJ", "bytes": "623" }, { "name": "Assembly", "bytes": "1942" }, { "name": "Batchfile", "bytes": "6632" }, { "name": "C", "bytes": "6629351" }, { "name": "C++", "bytes": "57418677" }, { "name": "CMake", "bytes": "1269316" }, { "name": "CSS", "bytes": "99559" }, { "name": "HTML", "bytes": "283332" }, { "name": "Java", "bytes": "267448" }, { "name": "JavaScript", "bytes": "282026" }, { "name": "Makefile", "bytes": "164797" }, { "name": "Objective-C", "bytes": "956074" }, { "name": "Objective-C++", "bytes": "3645713" }, { "name": "Perl", "bytes": "192119" }, { "name": "Python", "bytes": "39191" }, { "name": "Ragel", "bytes": "128173" }, { "name": "Roff", "bytes": "26536" }, { "name": "Ruby", "bytes": "32784" }, { "name": "Shell", "bytes": "7177" }, { "name": "Vue", "bytes": "1776" }, { "name": "Yacc", "bytes": "11866" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "6162a3b0338c37e22f6f5ea44685a69d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "d3d90c37c21c7d9e2ea149b780dd07f2a7b752ef", "size": "218", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Saccharomycetes/Saccharomycetales/Debaryomyces/Schwanniomyces occidentalis/ Syn. Schwanniomyces ukrainicus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
dmg_package "OmniGraffle Professional 5" do volumes_dir "OmniGrafflePro" accept_eula true source "http://www.omnigroup.com/download/latest/omnigrafflepro" action :install owner node['current_user'] end gtemplate = "#{node['sprout']['home']}/Library/Application Support/OmniGraffle/Templates/Konigi-UX-Template.gtemplate" unless File.exists?(gtemplate) directory "#{node['sprout']['home']}/Library/Application Support/OmniGraffle/Templates" do owner node['current_user'] mode 0755 action :create recursive true end remote_file "#{Chef::Config[:file_cache_path]}/Konigi-UX-Template-2-5-1.gtemplate.zip" do source "http://media.konigi.com/tools/og-ux-template/Konigi-UX-Template-2-5-1.gtemplate.zip" owner node['current_user'] end execute "unzip Konigi-UX-Template-2-5-1.gtemplate.zip" do command "unzip #{Chef::Config[:file_cache_path]}/Konigi-UX-Template-2-5-1.gtemplate.zip -d #{Chef::Config[:file_cache_path]}/" user node['current_user'] end execute "move Konigi-UX-Template.gtemplate" do command "mv #{Chef::Config[:file_cache_path]}/Konigi-UX-Template.gtemplate #{Regexp.escape(gtemplate)}" user node['current_user'] end end gdiagramstyle = "#{node['sprout']['home']}/Library/Application Support/OmniGraffle/Diagram Styles/Konigi.gdiagramstyle" unless File.exists?(gdiagramstyle) directory "#{node['sprout']['home']}/Library/Application Support/OmniGraffle/Diagram Styles" do owner node['current_user'] mode 0755 action :create recursive true end remote_file "#{Chef::Config[:file_cache_path]}/Konigi.gdiagramstyle.zip" do source "http://media.konigi.com/tools/og-ux-template/Konigi.gdiagramstyle.zip" owner node['current_user'] end execute "unzip Konigi.gdiagramstyle.zip" do command "unzip #{Chef::Config[:file_cache_path]}/Konigi.gdiagramstyle.zip -d #{Chef::Config[:file_cache_path]}/" user node['current_user'] end execute "move Konigi.gdiagramstyle" do command "mv #{Chef::Config[:file_cache_path]}/Konigi.gdiagramstyle #{Regexp.escape(gdiagramstyle)}" user node['current_user'] end end stencils = "#{node['sprout']['home']}/Library/Application Support/OmniGraffle/Stencils/Konigi Wireframe Stencils v3" unless File.exists?(stencils) directory "#{node['sprout']['home']}/Library/Application Support/OmniGraffle/Stencils" do owner node['current_user'] mode 0755 action :create recursive true end remote_file "#{Chef::Config[:file_cache_path]}/Konigi-Wireframe-Stencils-v3-02.zip" do source "http://media.konigi.com/tools/og-wireframe-stencil/Konigi-Wireframe-Stencils-v3-02.zip" owner node['current_user'] end execute "unzip Konigi-Wireframe-Stencils-v3-02.zip" do command "unzip #{Chef::Config[:file_cache_path]}/Konigi-Wireframe-Stencils-v3-02.zip -d #{Chef::Config[:file_cache_path]}/" user node['current_user'] end execute "move Konigi.gdiagramstyle" do command "mv #{Chef::Config[:file_cache_path]}/#{Regexp.escape("Konigi Wireframe Stencils v3")} #{Regexp.escape("#{node['sprout']['home']}/Library/Application Support/OmniGraffle/Stencils/")}" user node['current_user'] end end
{ "content_hash": "5cbe7dadf418379c4bdda2dc8f3aec13", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 199, "avg_line_length": 40.97560975609756, "alnum_prop": 0.6818452380952381, "repo_name": "Yesware/sprout", "id": "b3b68479eebf8e61f74eccef61e54c86c8453546", "size": "3360", "binary": false, "copies": "1", "ref": "refs/heads/yesware", "path": "pivotal_workstation/recipes/omnigraffle.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "39278" }, { "name": "Ruby", "bytes": "157652" }, { "name": "Shell", "bytes": "1337" } ], "symlink_target": "" }
package com.android.tools.idea.gradle.output.parser; import com.android.ide.common.blame.Message; import com.android.ide.common.blame.SourceFilePosition; import com.android.ide.common.blame.parser.ParsingFailedException; import com.android.ide.common.blame.parser.PatternAwareOutputParser; import com.android.ide.common.blame.parser.util.OutputLineReader; import com.android.utils.ILogger; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.regex.Pattern; public class GradleOutputParser implements PatternAwareOutputParser { private static final Pattern ERROR_COUNT_PATTERN = Pattern.compile("[\\d]+ error(s)?"); @Override public boolean parse(@NotNull String line, @NotNull OutputLineReader reader, @NotNull List<Message> messages, @NotNull ILogger logger) throws ParsingFailedException { if (ignoreMessage(line)) { return true; } if (line.endsWith("is an incubating feature.") || line.contains("has been deprecated and is scheduled to be removed in Gradle")) { // These are warnings about using incubating/internal Gradle APIs. They do not add any value to our users. In fact, we got reports // that those warnings are confusing. // We just hide the message. return true; } if (line.startsWith("Total time: ") || line.startsWith("BUILD ")) { messages.add(new Message(Message.Kind.INFO, line, SourceFilePosition.UNKNOWN)); return true; } return false; } private static boolean ignoreMessage(@NotNull String line) { return line.trim().equalsIgnoreCase("FAILED") || ERROR_COUNT_PATTERN.matcher(line).matches(); } }
{ "content_hash": "a1243aa0b53dfa193ff45d996028db5d", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 136, "avg_line_length": 40.073170731707314, "alnum_prop": 0.7431527693244065, "repo_name": "consulo/consulo-android", "id": "5a4a37f174e9e454a24316de2f0597e2f2c25caa", "size": "2262", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "android/android/common/src/com/android/tools/idea/gradle/output/parser/GradleOutputParser.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5115" }, { "name": "C", "bytes": "138494" }, { "name": "C++", "bytes": "3748" }, { "name": "CSS", "bytes": "41095" }, { "name": "Emacs Lisp", "bytes": "4737" }, { "name": "Groovy", "bytes": "833183" }, { "name": "HTML", "bytes": "1162651" }, { "name": "Java", "bytes": "38558853" }, { "name": "JavaScript", "bytes": "3488" }, { "name": "Lex", "bytes": "12419" }, { "name": "Makefile", "bytes": "844" }, { "name": "Prolog", "bytes": "1222" }, { "name": "RenderScript", "bytes": "73022" }, { "name": "Shell", "bytes": "15030" }, { "name": "XSLT", "bytes": "23593" } ], "symlink_target": "" }
package com.wix.restaurants.reservations.builders; import com.openrest.v1_1.Contact; import com.wix.restaurants.TimeGuarantees; import com.wix.restaurants.i18n.Locale; import com.wix.restaurants.reservations.Reservation; import java.util.Date; import java.util.LinkedHashMap; public class ReservationBuilder { private final Reservation reservation = new Reservation(); public ReservationBuilder() { reservation.properties = new LinkedHashMap<>(); } public ReservationBuilder setDeveloper(String developer) { reservation.developer = developer; return this; } public ReservationBuilder setPlatform(String platform) { reservation.platform = platform; return this; } public ReservationBuilder setSource(String source) { reservation.source = source; return this; } public ReservationBuilder setRestaurant(String restaurantId) { reservation.restaurantId = restaurantId; return this; } public ReservationBuilder setLocale(Locale locale) { reservation.locale = locale; return this; } public ReservationBuilder setContact(Contact contact) { reservation.contact = contact; return this; } public ReservationBuilder setPartySize(int partySize) { reservation.partySize = partySize; return this; } public ReservationBuilder setTime(Date time) { reservation.timeGuarantee = TimeGuarantees.approximate; reservation.time = time; return this; } public ReservationBuilder setHeldUntil(Date heldUntil) { reservation.heldUntil = heldUntil; return this; } public ReservationBuilder setStatus(String status) { reservation.status = status; return this; } public ReservationBuilder setComment(String comment) { reservation.comment = comment; return this; } public Reservation build() { return reservation; } }
{ "content_hash": "b81c49f4ed47a4e0e08f7e6f5bbea1b1", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 66, "avg_line_length": 27.09090909090909, "alnum_prop": 0.6596356663470757, "repo_name": "wix/wix-restaurants-java-sdk", "id": "c538a3da237edef2ff9e9f6ea1bcc554643a7f39", "size": "2086", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wix-restaurants-java-client/src/main/java/com/wix/restaurants/reservations/builders/ReservationBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "49044" }, { "name": "Scala", "bytes": "39888" } ], "symlink_target": "" }
\section{Casi d'uso} I casi d'uso sono catalogati come: \begin{center} UC[numero][caso] \end{center} dove: \begin{itemize} \item \textit{UC} specifica che si sta parlando di un caso d'uso; \item \textit{numero} è assoluto e rappresenta un riferimento univoco al caso d'uso in questione; \item \textit{caso} individua eventuali diramazioni all'interno dello stesso caso d'uso. \end{itemize} \subsection{Framework}\label{Framework} \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/framework.png} \caption{Visione generale dei casi d'uso per il framwork} \end{figure} \UC{Istanziazione della bubble generica}{UC1.35} \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_35.png} \caption{\UCCaption{} Istanziazione della bubble generica} \end{figure} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può istanziare il contenitore \glossario{bubble generica}, il quale funge da contenitore dei vari elementi di input, output e di logica specificati all'interno del framework. \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework chiama il metodo per istanziare la bubble generica e la memoria ad essa associata. \item \textbf{Post-condizione:} \\È presente la bubble generica, compresa la sua memoria. \end{itemize} \UC{Interazione con database MongoDB}{UC2} \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/Database.png} \caption{\UCCaption{} Interazione con database MongoDB} \end{figure} \begin{itemize} \item \textbf{Attori:} \begin{itemize} \item Utilizzatore del framework; \item Database. \end{itemize} \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework interagisce con un database \glossario{MongoDB} esterno. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere l'indirizzo di un database MongoDB con cui si desidera interagire. \end{itemize} \item \textbf{Flusso principale degli eventi:} \begin{itemize} \item L'utilizzatore del framework si connette al database MongoDB \ref{UC1.00}. \item L'utilizzatore del framework effettua una lettura delle informazioni contenute all'interno del database MongoDB \ref{UC1.01}. \item L'utilizzatore del framework effettua una scrittura sul database MongoDB \ref{UC1.02}. \end{itemize} \item \textbf{Post-condizione:} \\L'utilizzatore del metodo ha interagito con il database. \end{itemize} \begin{samepage} \UCC[2]{Connessione a database MongoDB}{UC1.00} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_00.png} \caption{\UCCCaption{} Connessione a database MongoDB} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \begin{itemize} \item Utilizzatore del framework; \item Database. \end{itemize} \item \textbf{Scopo e descrizione:} \\Connettersi ad un database MongoDB esterno all'applicazione. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere l'indirizzo del database MongoDB a cui si desidera connettersi. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore passa l'indirizzo del database a cui connettersi al metodo che genera una connessione con il database MongoDB. \item \textbf{Scenari alternativi:} \\Non è possibile stabilire la connessione \ref{UC1.00.2}. \item \textbf{Post-condizione:} \\La bubble generica da cui è invocato il metodo è connessa al database. \end{itemize} \UCC[2]{Connessione a database MongoDB non possibile}{UC1.00.2} \begin{itemize} \item \textbf{Attori:} \begin{itemize} \item Utilizzatore del framework; \item Database. \end{itemize} \item \textbf{Scopo e descrizione:} \\Connettersi ad un database MongoDB esterno all'applicazione. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere l'indirizzo del database MongoDB a cui si desidera connettersi. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore passa l'indirizzo del database a cui connettersi al metodo che fallisce nel tentativo di stabilire una connessione con il database MongoDB. \item \textbf{Scenari alternativi:} \\La connessione avviene correttamente \ref{UC1.00}. \item \textbf{Post-condizione:} \\La bubble generica lancia un messaggio di errore e avvisa l'utente che la connessione non è riuscita. \end{itemize} \begin{samepage} \UCF{Lettura da database MongoDB}{UC1.01} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_01.png} \caption{\UCFCaption{} Lettura da database MongoDB} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \begin{itemize} \item Utilizzatore del framework; \item Database. \end{itemize} \item \textbf{Scopo e descrizione:} \\Prelevare dati dal database connesso alla bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item La bubble è connessa al database MongoDB \ref{UC1.00}. \item L'utilizzatore deve conoscere il nome della \glossario{collection} da cui prelevare i dati. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore chiama il metodo su una bubble, il quale gli ritorna un oggetto \glossario{JSON} letto dal database, eventualmente assegnabile ad un campo della \glossario{bubble memory}. \item \textbf{Post-condizione:} \\I dati sono prelevati dal database e sono pronti all'uso nella bubble. \end{itemize} \begin{samepage} \UCF{Scrittura su database MongoDB}{UC1.02} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_02.png} \caption{\UCFCaption{} Scrittura su database MongoDB} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \begin{itemize} \item Utilizzatore del framework; \item Database. \end{itemize} \item \textbf{Scopo e descrizione:} \\Scrittura dati nel database connesso alla bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item La bubble è connessa al database MongoDB \ref{UC1.00}. \item L'utilizzatore deve conoscere il nome della collection da cui prelevare i dati. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore chiama il metodo su una bubble passandogli un oggetto \glossario{JavaScript}, serializzabile in JSON, e il metodo lo salva nel database. \item \textbf{Post-condizione:} \\I dati sono scritti nel database collegato. \end{itemize} \UC{Effettuare operazioni sugli elementi}{UC3} \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/operazioni.png} \caption{\UCCaption{} Effettuare operazioni sugli elementi} \end{figure} \begin{itemize} \item \textbf{Attori:} \begin{itemize} \item Utilizzatore del framework; \item Rocket.Chat. \end{itemize} \item \textbf{Scopo e descrizione:} \\Effettuare una o più operazioni sugli elementi della bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \end{itemize} \item \textbf{Flusso principale degli eventi:} \begin{itemize} \item L'utilizzatore del framework crea un elemento \ref{UC3.01}. \item L'utilizzatore del framework aggiunge un elemento alla bubble \ref{UC1.04}. \item L'utilizzatore del framework rimuove un elemento dalla bubble \ref{UC1.03.1}. \item L'utilizzatore del framework modifica un elemento della bubble \ref{UC1.05.1}. \item L'utilizzatore del framework crea una notifica statica \ref{UC1.17}. \item L'utilizzatore del framework rende visualizzabile da un utente una notifica statica \ref{UC1.18}. \item L'utilizzatore del framework mostra un elemento grafico \ref{UC1.21}. \item L'utilizzatore del framework nasconde un elemento grafico \ref{UC1.22}. \item L'utilizzatore del framework imposta la posizione di un elemento grafico \ref{UC1.23}. \end{itemize} \item \textbf{Post-condizione:} \\Sono state apportate delle modifiche agli elementi della bubble. \end{itemize} \begin{samepage} \UCF{Creazione di un elemento}{UC3.01} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/creazione_elem.png} \caption{\UCFCaption{} Creazione di un elemento} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Costruzione di un elemento. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Disporre di tutte le risorse necessarie a creare l'elemento. \end{itemize} \item \textbf{Flusso principale degli eventi:} \begin{itemize} \item L'utilizzatore del framework crea un elemento di tipo Immagine \ref{UC1.25}. \item L'utilizzatore del framework crea un elemento di tipo TextView \ref{UC1.26}. \item L'utilizzatore del framework crea un elemento di tipo Label \ref{UC1.27}. \item L'utilizzatore del framework crea un elemento di tipo Grafico a torta \ref{UC1.28}. \item L'utilizzatore del framework crea un elemento di tipo Grafico a istogramma \ref{UC1.29}. \item L'utilizzatore del framework crea un elemento di tipo Checkbox \ref{UC1.30}. \item L'utilizzatore del framework crea un elemento di tipo Bottone radio \ref{UC1.31}. \item L'utilizzatore del framework crea un elemento di tipo Bottone \ref{UC1.32}. \item L'utilizzatore del framework crea un elemento di tipo TextEdit \ref{UC1.33}. \end{itemize} \item \textbf{Post-condizione:} \\È stato creato un elemento. \end{itemize} \begin{samepage} \UCFF{Immagine}{UC1.25} \nopagebreak %\begin{figure}[H] % \centering % \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_25.png} % \caption{\UCFFCaption{} Immagine} %\end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può creare un elemento immagine. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere un'immagine di cui fare la preview. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework crea un elemento immagine. \item \textbf{Post-condizione:} \\È stato creato un elemento immagine. \end{itemize} \begin{samepage} \UCFF{TextView}{UC1.26} \nopagebreak %\begin{figure}[H] % \centering % \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_26.png} % \caption{\UCFFCaption{} TextView} %\end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può creare un elemento \glossario{TextView}. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere un testo da visualizzare. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework crea l'elemento TextView specificando il testo da includere. \item \textbf{Post-condizione:} \\È stato creato un elemento TextView. \end{itemize} \begin{samepage} \UCFF{Label}{UC1.27} \nopagebreak %\begin{figure}[H] % \centering % \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_27.png} % \caption{\UCFFCaption{} Label} %\end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può creare un elemento \glossario{label}. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere un testo da visualizzare. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework crea l'elemento label specificando il testo da includere. \item \textbf{Post-condizione:} \\È stato creato un elemento label. \end{itemize} \begin{samepage} \UCFF{Grafico a torta}{UC1.28} \nopagebreak %\begin{figure}[H] % \centering % \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_28.png} % \caption{\UCFFCaption{} Grafico a torta} %\end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può creare un elemento "grafico a torta". \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Essere in possesso dei dati che si desidera visualizzare nel grafico. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework crea l'elemento specificando i dati da rappresentare nel grafico a torta. \item \textbf{Post-condizione:} \\È stato creato un elemento "grafico a torta". \end{itemize} \begin{samepage} \UCFF{Grafico a istogramma}{UC1.29} \nopagebreak %\begin{figure}[H] % \centering % \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_29.png} % \caption{\UCFFCaption{} Grafico a istogramma} %\end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può creare un elemento "grafico a istogramma". \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Essere in possesso dei dati che si desidera visualizzare nel grafico. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework crea l'elemento specificando i dati da rappresentare nel grafico a istogramma. \item \textbf{Post-condizione:} \\È stato creato un elemento "grafico a istogramma". \end{itemize} \begin{samepage} \UCFF{Checkbox}{UC1.30} \nopagebreak %\begin{figure}[H] % \centering % \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_30.png} % \caption{\UCFFCaption{} Checkbox} %\end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può creare un elemento \glossario{checkbox}. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework crea l'elemento checkbox. \item \textbf{Post-condizione:} \\È stato creato l'elemento checkbox. \end{itemize} \begin{samepage} \UCFF{Bottone Radio}{UC1.31} \nopagebreak %\begin{figure}[H] % \centering % \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_31.png} % \caption{\UCFFCaption{} Bottone Radio} %\end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può creare un elemento \glossario{bottone radio}. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework crea un elemento bottone radio. \item \textbf{Post-condizione:} \\È stato creato l'elemento bottone radio. \end{itemize} \begin{samepage} \UCFF{Bottone}{UC1.32} \nopagebreak %\begin{figure}[H] % \centering % \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_32.png} % \caption{\UCFFCaption{} Bottone} %\end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può creare un elemento \glossario{bottone}. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere la funzione da eseguire. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework crea l'elemento bottone specificando la funzione da assegnare ad esso. \item \textbf{Post-condizione:} \\È stato creato un elemento bottone \end{itemize} \begin{samepage} \UCFF{TextEdit}{UC1.33} \nopagebreak %\begin{figure}[H] % \centering % \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_33.png} % \caption{\UCFFCaption{} TextEdit} %\end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può creare un input testuale \glossario{TextEdit}. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework crea l'elemento TextEdit. \item \textbf{Post-condizione:} \\È stato creato l'elemento TextEdit. \end{itemize} \begin{samepage} \UCF{Aggiunta di un elemento}{UC1.04} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_04.png} \caption{\UCFCaption{} Aggiunta di un elemento} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Inserire nella bubble un elemento. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Aver istanziato un elemento. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore invoca il metodo sulla bubble indicando l'elemento da aggiungere e il metodo lo aggiunge alla bubble. \item \textbf{Post-condizione:} \\La bubble avrà al suo interno l'elemento passato al metodo. \end{itemize} \begin{samepage} \isfirsttrue \UCC[2]{Rimozione di un elemento presente}{UC1.03.1} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_03.png} \caption{\UCCCaption{} Rimozione di un elemento} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Rimuovere dalla bubble un \glossario{elemento}\footnote{Viene considerato elemento del framework un qualsiasi componente grafico (form, immagini, label ad esempio) o funzionale (notifiche, API).} specificato. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item La bubble possiede degli elementi. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore chiama il metodo, il quale rimuove l'elemento dalla bubble. \item \textbf{Scenari alternativi:} \\L'elemento che si vuole eliminare non è presente nella bubble \ref{UC1.03.2}. \item \textbf{Post-condizione:} \\La bubble non contiene l'elemento indicato da rimuovere. \end{itemize} \UCC[2]{Rimozione di un elemento non presente}{UC1.03.2} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Rimuovere dalla bubble un elemento specificato. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item La bubble possiede degli elementi. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore chiama il metodo, il quale, non trovando l'elemento, restituisce un messaggio di errore. \item \textbf{Scenari alternativi:} \\L'elemento è presente nella bubble \ref{UC1.03.1}. \item \textbf{Post-condizione:} \\La bubble non contiene l'elemento indicato da rimuovere e l'utilizzatore è stato avvisato della sua mancanza. \end{itemize} \begin{samepage} \isfirsttrue \UCC[2]{Modifica di un elemento presente}{UC1.05.1} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_05.png} \caption{\UCCCaption{} Modifica di un elemento} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Modificare un elemento di una bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item All'interno della bubble sono presenti degli elementi. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore invoca il metodo sulla bubble e il metodo modifica l'elemento. \item \textbf{Scenari alternativi:} \\L'elemento che si vuole modificare non è presente nella bubble \ref{UC1.05.2}. \item \textbf{Post-condizione:} \\La bubble contiene l'elemento modificato. \end{itemize} \UCC[2]{Modifica di un elemento non presente}{UC1.05.2} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Modificare un elemento di una bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item All'interno della bubble sono presenti degli elementi. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore invoca il metodo sulla bubble e il metodo, non trovando l'elemento da modificare, lancia un messaggio di errore. \item \textbf{Scenari alternativi:} \\L'elemento è presente nella bubble \ref{UC1.05.1}. \item \textbf{Post-condizione:} \\L'utilizzatore del metodo è a conoscenza che la modifica è fallita in quanto non era presente l'elemento da modificare. \end{itemize} \begin{samepage} \UCF{Creazione notifica statica}{UC1.17} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_17.png} \caption{\UCFCaption{} Creazione notifica statica} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework potrà creare una notifica statica specificandone il testo. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Essere in possesso del messaggio che si desidera notificare sotto forma di testo. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework chiama il metodo specificando il testo da visualizzare nella notifica statica. \item \textbf{Post-condizione:} \\Sul dispositivo sul quale si sta utilizzando Rocket.Chat sarà notificato il testo specificato nel metodo. \end{itemize} \begin{samepage} \UCF{Visualizza notifica statica}{UC1.18} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_18.png} \caption{\UCFCaption{} Visualizza notifica statica} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \begin{itemize} \item Utilizzatore del framework. \item Rocket.Chat. \end{itemize} \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può far visualizzare all'utente una notifica statica che visualizzi del testo. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Aver creato una notifica statica. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework fa visualizzare una certa notifica da lui creata. \item \textbf{Post-condizione:} \\La notifica contiene il valore del testo specificato. \end{itemize} \begin{samepage} \UCF{Mostra elemento grafico}{UC1.21} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_21.png} \caption{\UCFCaption{} Mostra elemento grafico} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \begin{itemize} \item Utilizzatore del framework. \item Rocket.Chat. \end{itemize} \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework potrà mostrare un \glossario{elemento grafico}\footnote{Esempi di elementi grafici sono: Label, Immagini, TextView.}. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere almeno un elemento grafico nella bubble. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework chiama il metodo specificando quale elemento grafico della bubble vuole mostrare. \item \textbf{Post-condizione:} \\L'elemento grafico specificato è visibile. \end{itemize} \begin{samepage} \UCF{Nascondi elemento grafico}{UC1.22} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_22.png} \caption{\UCFCaption{} Nascondi elemento grafico} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \begin{itemize} \item Utilizzatore del framework. \item Rocket.Chat. \end{itemize} \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework potrà nascondere un elemento grafico. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere almeno un elemento nella bubble. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework chiama il metodo specificando quale elemento grafico della bubble vuole nascondere. \item \textbf{Post-condizione:} \\L'elemento grafico specificato non è più visibile. \end{itemize} \begin{samepage} \UCF{Imposta posizione elemento grafico}{UC1.23} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_23.png} \caption{\UCFCaption{} Imposta posizione elemento grafico} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework; \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può specificare una posizione per un elemento grafico della bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere almeno un componente nella bubble. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework chiama il metodo specificando la posizione e l'elemento grafico di cui vuole fissare la posizione. \item \textbf{Post-condizione:} \\L'elemento grafico specificato si trova nella posizione specificata. \end{itemize} \begin{samepage} \isfirsttrue \UCC{Cambiamento di stato della bubble su proprietà esistente}{UC1.06.1} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_06.png} \caption{\UCCCaption{} Cambiamento di stato della bubble su proprietà esistente} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Modificare lo specifico stato della bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore invoca il metodo sulla bubble indicando il nuovo stato e il metodo esegue la modifica. \item \textbf{Scenari alternativi:} \\L'oggetto che si sta cercando di modificare non ha la proprietà cercata \ref{UC1.06.2}. \item \textbf{Post-condizione:} \\L'oggetto è stato modificato. \end{itemize} \UCC{Cambiamento di stato della bubble su proprietà non esistente}{UC1.06.2} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Modificare lo specifico stato della bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore invoca il metodo sulla bubble indicando il nuovo stato e il metodo, non trovando la proprietà cercata, restituisce un messaggio di errore. \item \textbf{Scenari alternativi:} \\L'oggetto che si sta cercando di modificare ha la proprietà cercata \ref{UC1.06.1}. \item \textbf{Post-condizione:} \\L'oggetto non è stato modificato. \end{itemize} \begin{samepage} \isfirsttrue \UCC{Chiamata API esterne disponibili}{UC1.07.1} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_07.png} \caption{\UCCCaption{} Chiamata API esterne disponibili} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \begin{itemize} \item Utilizzatore del framework; \item Server remoto. \end{itemize} \item \textbf{Scopo e descrizione:} \\Ottenere il risultato dell'interrogazione di un servizio esterno al framework tramite chiamata di \glossario{API}. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Conoscere l'URL del servizio desiderato. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\Il metodo prende l'indirizzo del servizio e ritorna in formato JSON il risultato della chiamata. \item \textbf{Scenari alternativi:} \\Il servizio che si sta cercando di contattare non è disponibile \ref{UC1.07.2}. \item \textbf{Post-condizione:} \\All'interno della logica della bubble è utilizzabile il risultato della consultazione del servizio. \end{itemize} \UCC{Chiamata API esterne non disponibili}{UC1.07.2} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Ottenere il risultato dell'interrogazione di un servizio esterno al framework tramite chiamata di API. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Conoscere l'URL del servizio desiderato. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\Il metodo prende l'indirizzo del servizio e, non trovandolo disponibile, ritorna un messaggio di errore. \item \textbf{Scenari alternativi:} \\Il servizio che si sta cercando di contattare è disponibile \ref{UC1.07.1}. \item \textbf{Post-condizione:} \\L'utilizzatore del metodo è stato avvisato della non disponibilità del servizio. \end{itemize} \UC{Controllo sul JSON}{UC1.12} \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_12.png} \caption{\UCCaption{} Controllo sul JSON} \end{figure} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Verificare che la struttura di un oggetto JSON sia compatibile con lo schema fornito. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere un oggetto JSON da validare. \item Avere lo schema attraverso cui validare l'oggetto JSON. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\Alla chiamata del metodo viene specificato il JSON da verificare e lo schema di dati rispetto al quale validare tale oggetto. Il metodo poi si occupa della validazione. \item \textbf{Post-condizione:} \\È noto se l'oggetto JSON è compatibile con la struttura indicata. \end{itemize} \UC{Settare le impostazioni della bubble}{UCimpostazioni} \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/Impostazioni.png} \caption{\UCCaption{} Settare le impostazioni della bubble} \end{figure} \begin{itemize} \item \textbf{Attori:} \begin{itemize} \item Utilizzatore del framework; \item Rocket.Chat. \end{itemize} \item \textbf{Scopo e descrizione:} \\Modificare le impostazioni della bubble per adattarle allo scopo della stessa. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica; \end{itemize} \item \textbf{Flusso principale degli eventi:} \begin{itemize} \item L'utente imposta un limite di interazioni per persona \ref{UC1.08}. \item L'utente imposta un limite di interazioni totali \ref{UC1.09}. \item L'utente imposta la durata della bubble \ref{UC1.13}. \item L'utente specifica l'orario di esecuzione \ref{UC1.16}. \item L'utente imposta una dimensione massima per i file \ref{UC1.11}. \end{itemize} \item \textbf{Post-condizione:} \\La bubble è stata configurata con le impostazioni definite. \end{itemize} \begin{samepage} \UCF{Limite interazioni per persona}{UC1.08} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_08.png} \caption{\UCFCaption{} Limite interazioni per persona} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Porre un limite superiore al numero delle interazioni che un utente di Rocket.Chat può avere con una stessa bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere almeno un \glossario{elemento di input} all'interno della bubble. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\Alla chiamata del metodo viene specificato il numero massimo di interazioni possibili per una persona con una singola istanza della bubble. \item \textbf{Post-condizione:} \\Il singolo utilizzatore della bubble come utente di Rocket.Chat non potrà interagire con la stessa istanza della bubble più volte di quelle specificate. \end{itemize} \begin{samepage} \UCF{Limite interazioni totali}{UC1.09} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_09.png} \caption{\UCFCaption{} Limite interazioni totali} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Porre un limite superiore al numero delle interazioni che tutti gli utenti possono avere con una stessa istanza della bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere almeno un elemento di input all'interno della bubble. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\Alla chiamata del metodo viene specificato il numero massimo di interazioni possibili per l'istanza della bubble. \item \textbf{Post-condizione:} \\La singola istanza della bubble ha un numero massimo di interazioni possibili condiviso tra tutti i suoi utenti. \end{itemize} \begin{samepage} \UCF{Durata della bubble}{UC1.13} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_13.png} \caption{\UCFCaption{} Durata della bubble} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Dare la possibilità all'utilizzatore del framework di impostare un limite temporale entro il quale la bubble smetterà di essere attiva. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\Alla chiamata del metodo viene specificato il tempo per il quale la bubble sarà attiva. \item \textbf{Post-condizione:} \\Al termine del periodo di tempo specificato dal metodo verrà invocata la sua terminazione secondo quanto specificato nel caso d'uso \ref{UC1.19} termina bubble. \end{itemize} \begin{samepage} \UCF{Esecuzione in orario specificato}{UC1.16} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_16.png} \caption{\UCFCaption{} Esecuzione in orario specificato} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \begin{itemize} \item Utilizzatore del framework. \item Rocket.Chat. \end{itemize} \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può fornire un orario per l'esecuzione della funzionalità della bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere la funzione di callback che si desidera eseguire all'orario specificato. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\Alla chiamata del metodo viene specificato l'orario di esecuzione della specifica funzionalità della bubble. \item \textbf{Post-condizione:} \\Nell'orario stabilito viene eseguita la funzionalità della bubble all'interno di Rocket.Chat. \end{itemize} \begin{samepage} \UCF{Dimensione massima del file}{UC1.11} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_11.png} \caption{\UCFCaption{} Dimensione massima del file} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Verificare che la dimensione dei file caricati in input sia minore o uguale a quella specificata. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere almeno un elemento di input all'interno della bubble. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\Alla chiamata del metodo viene specificata la dimensione massima accettata per i file di input. \item \textbf{Post-condizione:} \\È stata impostata una dimensione massima per i file allegabili. \end{itemize} \UC{Match con espressione regolare}{UC1.10} \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_10.png} \caption{\UCCaption{} Match con espressione regolare} \end{figure} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Verificare che l'input testuale di una bubble sia compatibile con un'espressione regolare data. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere almeno un elemento di input all'interno della bubble. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\Alla chiamata del metodo viene specificato l'elemento da verificare e l'espressione regolare in base a cui controllarlo. \item \textbf{Post-condizione:} \\È noto se l'input della bubble è corretto secondo l'espressione regolare. \end{itemize} \UC{Lista utenti partecipanti}{UC1.14} \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_14.png} \caption{\UCCaption{} Lista utenti partecipanti} \end{figure} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Possibilità di visualizzare gli utilizzatori correnti della bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\Alla chiamata del metodo viene specificato l'elenco degli utilizzatori correnti della bubble. \item \textbf{Post-condizione:} \\Viene restituita una lista di utilizzatori della bubble. \end{itemize} \begin{samepage} \UCC{Storico interazioni con la bubble per utente presente}{UC1.15.1} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_15.png} \caption{\UCCCaption{} Storico interazioni con la bubble per utente presente} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Dare la possibilità all'utilizzatore del framework di consultare lo storico delle interazioni che un singolo utente ha avuto con la bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere elementi di input all'interno della bubble. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\Alla chiamata del metodo viene specificato l'utente di cui si è interessati a conoscere lo storico delle interazioni. \item \textbf{Scenari alternativi:} \\Non è presente l'utente specificato all'interno della conversazione \ref{UC1.15.2}. \item \textbf{Post-condizione:} \\L'informazione relativa allo storico delle interazioni di un singolo utente con la bubble è noto all'interno della bubble stessa. \end{itemize} \UCC{Storico interazioni con la bubble per utente non presente}{UC1.15.2} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\Dare la possibilità all'utilizzatore del framework di consultare lo storico delle interazioni che un singolo utente ha avuto con la bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere elementi di input all'interno della bubble. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\Alla chiamata del metodo viene specificato l'utente di cui si è interessati a conoscere lo storico delle interazioni e il metodo, non trovando l'utente, restituisce un messaggio di errore. \item \textbf{Scenari alternativi:} \\È presente l'utente specificato all'interno della conversazione \ref{UC1.15.1}. \item \textbf{Post-condizione:} \\L'utilizzatore del metodo ha ricevuto un messaggio di errore che lo avvisa dell'assenza all'interno della conversazione dell'utente di cui aveva richiesto lo storico. \end{itemize} \begin{samepage} \isfirsttrue \UCC{Converti in PDF}{UC1.20.1} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_20.png} \caption{\UCCCaption{} Converti in PDF} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework potrà convertire il testo specificato in un \glossario{PDF}. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Possedere il testo da convertire in formato PDF. \item Conoscere il percorso in cui si desidera che il file sia salvato. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework chiama il metodo specificando il testo da convertire in PDF e il percorso in cui si desidera salvare il file. \item \textbf{Scenari alternativi:} \\Il salvataggio del file PDF non ha successo \ref{UC1.20.2}. \item \textbf{Post-condizione:} \\Un file PDF è stato creato nella posizione corretta e contiene il testo specificato. \end{itemize} \UCC{Conversione in PDF fallita}{UC1.20.2} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework potrà convertire il testo specificato in un PDF. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Possedere il testo da convertire in formato PDF. \item Conoscere il percorso in cui si desidera che il file sia salvato. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework chiama il metodo specificando il testo da convertire in PDF e il percorso in cui si desidera salvare il file, ma il salvataggio non avviene e l'utilizzatore del framework visualizza un messaggio d'errore. \item \textbf{Scenari alternativi:} \\Il salvataggio del file PDF ha successo \ref{UC1.20.2}. \item \textbf{Post-condizione:} \\L'utilizzatore del metodo ha ricevuto un messaggio di errore che lo avvisa che il file PDF non è stato salvato. \end{itemize} \begin{samepage} \isfirsttrue \UCC{File output}{UC1.24.1} \nopagebreak \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_24.png} \caption{\UCCCaption{} File output} \end{figure} \end{samepage} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può salvare l'output della bubble in un file. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere almeno un elemento nella bubble. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework chiama il metodo che specifica che l'output della bubble sia un file e le informazioni da salvare in esso. \item \textbf{Scenari alternativi:} \\Il salvataggio del file non ha successo, in tale caso verrà notificata la condizione anomala con un messaggio d'errore \ref{UC1.24.2}. \item \textbf{Post-condizione:} \\Verrà generato un file contenente l'informazione desiderata. \end{itemize} \UCC{Errore file output}{UC1.24.2} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può salvare l'output della bubble in un file, il salvataggio non va a buon fine e viene generato un messaggio d'errore. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \item Avere delle informazioni da esportare. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework chiama il metodo che specifica che l'output della bubble sia un file e le informazioni da salvare in esso, il salvataggio non va a buon fine e viene generato un messaggio d'errore. \item \textbf{Scenari alternativi:} \\Il salvataggio del file ha successo \ref{UC1.24.1}. \item \textbf{Post-condizione:} \\Viene generato un messaggio d'errore. \end{itemize} \UC{File input}{UC1.34} \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_34.png} \caption{\UCCaption{} File input} \end{figure} \begin{itemize} \item \textbf{Attori:} \\Utilizzatore del framework. \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework può richiedere l'input di un file. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework chiama il metodo che restituisce il file in input. \item \textbf{Post-condizione:} \\Il file è stato caricato e passato alla bubble. \end{itemize} \UC{Mostra bubble generica}{UC1.36} \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_36.png} \caption{\UCCaption{} Mostra bubble generica} \end{figure} \begin{itemize} \item \textbf{Attori:} \begin{itemize} \item Utilizzatore del framework. \item Rocket.Chat. \end{itemize} \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework, utilizzando questo metodo, rende la bubble visibile all'interno della chat. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework chiama il metodo. \item \textbf{Post-condizione:} \\La bubble specificata viene mostrata all'interno della chat. \end{itemize} \UC{Termina bubble}{UC1.19} \begin{figure}[H] \centering \includegraphics[width=15cm]{../../documenti/AnalisiDeiRequisiti/Diagrammi_img/usecase/uc1_19.png} \caption{\UCCaption{} Termina bubble} \end{figure} \begin{itemize} \item \textbf{Attori:} \begin{itemize} \item Utilizzatore del framework. \item Rocket.Chat. \end{itemize} \item \textbf{Scopo e descrizione:} \\L'utilizzatore del framework potrà terminare la bubble. \item \textbf{Precondizioni:} \begin{itemize} \item Avere già istanziato una bubble generica. \end{itemize} \item \textbf{Flusso principale degli eventi:} \\L'utilizzatore del framework chiama il metodo. \item \textbf{Post-condizione:} \\La bubble è stata terminata e quindi non sarà più possibile interagire con la stessa. L'interfaccia verrà aggiornata, disabilitando la possibilità di dare input e avere output dinamico ma mantenendo un'istantanea del suo ultimo stato. \end{itemize}
{ "content_hash": "d698fac066a1c98ef92eef49a6f2f54b", "timestamp": "", "source": "github", "line_count": 1304, "max_line_length": 237, "avg_line_length": 37.14800613496933, "alnum_prop": 0.763650626535373, "repo_name": "or-bit/Documentazione-progetto-Monolith", "id": "a97b15529f39fe2a85456c06f59ac730f3a6771e", "size": "48589", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "LaTex/documenti/AnalisiDeiRequisiti/capitolo-casiduso.tex", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "456" }, { "name": "Shell", "bytes": "16282" }, { "name": "TeX", "bytes": "1137948" } ], "symlink_target": "" }
"""Copyright 2015 Roger R Labbe Jr. filterpy library. http://github.com/rlabbe/filterpy Documentation at: https://filterpy.readthedocs.org Supporting book at: https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python This is licensed under an MIT license. See the readme.MD file for more information. """ __version__ = "1.2.1"
{ "content_hash": "bdcef5a7a141523f3e97dfa2bed98f5e", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 63, "avg_line_length": 21.125, "alnum_prop": 0.7544378698224852, "repo_name": "BrianGasberg/filterpy", "id": "ca58fc26840881965525c11c31781dc9f8121546", "size": "362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "filterpy/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "480" }, { "name": "Python", "bytes": "381424" }, { "name": "Shell", "bytes": "683" } ], "symlink_target": "" }
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-lettering-js', included: function (app) { // see: https://github.com/ember-cli/ember-cli/issues/3718 if (typeof app.import !== 'function' && app.app) { app = app.app; } this._super.included(app); app.import(app.bowerDirectory + '/letteringjs/jquery.lettering.js'); } };
{ "content_hash": "5ea978091431bbb06ef70a6f0707b560", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 72, "avg_line_length": 25.2, "alnum_prop": 0.6216931216931217, "repo_name": "joedaniels29/ember-cli-lettering-js", "id": "9d6756712c7d7ccc940bca30d312c80c19703148", "size": "378", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "313" }, { "name": "HTML", "bytes": "1761" }, { "name": "JavaScript", "bytes": "6604" } ], "symlink_target": "" }
package com.overload.text; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import javax.swing.JLabel; import javax.swing.border.EmptyBorder; import javax.swing.text.JTextComponent; /** * Handles prompts for text components that specify what the text component is for. * @author Odell */ public class PromptHandler implements FocusListener { private final JTextComponent textComp; private final JLabel overlay; private boolean enabled = false; /** * Creates a new prompt handler for the given text component. * @param textComp * the text component to handle. * @param text * the text to prompt over the component. */ public PromptHandler(final JTextComponent textComp, final String text) { this(textComp, text, Color.LIGHT_GRAY); } /** * Creates a new prompt handler for the given text component with a prompt color. * @param textComp * the text component to handle. * @param text * the text to prompt over the component. * @param color * the color of the prompt text. */ public PromptHandler(final JTextComponent textComp, final String text, final Color color) { if (textComp == null) throw new IllegalArgumentException("Component is null!"); this.textComp = textComp; overlay = new JLabel(); overlay.setText(text); overlay.setForeground(color); overlay.setFont(textComp.getFont()); overlay.setBorder(new EmptyBorder(overlay.getInsets())); overlay.setHorizontalAlignment(JLabel.LEADING); textComp.setLayout(new BorderLayout()); textComp.add(overlay); setEnabled(true); determinePrompt(); } /** * @return the text component that this PromptHandler is handling. */ public JTextComponent getComponent() { return textComp; } /** * @return the prompt text currently in use. */ public String getText() { return overlay.getText(); } /** * Sets a new text as prompt text. * @param text * the new prompt text. */ public void setText(final String text) { this.overlay.setText(text); } /** * @return the current color of the prompt text. */ public Color getColor() { return overlay.getForeground(); } /** * Sets a new text color for the prompt. * @param color * the new prompt text color. */ public void setColor(final Color color) { this.overlay.setForeground(color); } /** * @return whether this prompt handler is active over the component. */ public boolean isEnabled() { return enabled; } /** * Enables or disables prompt handling. * @param enabled * whether to enable or disable. */ public void setEnabled(final boolean enabled) { if (this.enabled == enabled) return; if (this.enabled = enabled) { textComp.addFocusListener(this); } else { setVisible(false); textComp.removeFocusListener(this); } } private boolean isVisible() { return overlay.isVisible(); } private void setVisible(final boolean visible) { this.overlay.setVisible(visible); } private void determinePrompt() { if (textComp.hasFocus()) { if (isVisible()) { setVisible(false); } } else { if (textComp.getText().length() <= 0) { setVisible(true); } } } @Override public void focusGained(FocusEvent fe) { if (!textComp.equals(fe.getSource())) return; determinePrompt(); } @Override public void focusLost(FocusEvent fe) { if (!textComp.equals(fe.getSource())) return; determinePrompt(); } }
{ "content_hash": "65237296ea36476c1ac66883aeab8091", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 92, "avg_line_length": 23.145569620253166, "alnum_prop": 0.6622914957615532, "repo_name": "meachware/game_machine", "id": "2746b8f08af99987004969fcbbda2db9f8eb7673", "size": "3657", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "java/src/main/java/com/overload/text/PromptHandler.java", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_60-ea) on Tue Aug 16 17:15:34 EDT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.wildfly.swarm.config.management.AuthorizationAccess (Public javadocs 2016.8.1 API)</title> <meta name="date" content="2016-08-16"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.wildfly.swarm.config.management.AuthorizationAccess (Public javadocs 2016.8.1 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2016.8.1</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/config/management/class-use/AuthorizationAccess.html" target="_top">Frames</a></li> <li><a href="AuthorizationAccess.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.wildfly.swarm.config.management.AuthorizationAccess" class="title">Uses of Class<br>org.wildfly.swarm.config.management.AuthorizationAccess</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">AuthorizationAccess</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config">org.wildfly.swarm.config</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.wildfly.swarm.config.management">org.wildfly.swarm.config.management</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.wildfly.swarm.config"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">AuthorizationAccess</a> in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a> that return <a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">AuthorizationAccess</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">AuthorizationAccess</a></code></td> <td class="colLast"><span class="typeNameLabel">ManagementCoreService.ManagementCoreServiceResources.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/ManagementCoreService.ManagementCoreServiceResources.html#authorizationAccess--">authorizationAccess</a></span>()</code> <div class="block">The access control definitions defining the access management restrictions.</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/package-summary.html">org.wildfly.swarm.config</a> with parameters of type <a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">AuthorizationAccess</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/ManagementCoreService.html" title="type parameter in ManagementCoreService">T</a></code></td> <td class="colLast"><span class="typeNameLabel">ManagementCoreService.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/ManagementCoreService.html#authorizationAccess-org.wildfly.swarm.config.management.AuthorizationAccess-">authorizationAccess</a></span>(<a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">AuthorizationAccess</a>&nbsp;value)</code> <div class="block">The access control definitions defining the access management restrictions.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.wildfly.swarm.config.management"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">AuthorizationAccess</a> in <a href="../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a> with type parameters of type <a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">AuthorizationAccess</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">AuthorizationAccess</a>&lt;T extends <a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">AuthorizationAccess</a>&lt;T&gt;&gt;</span></code> <div class="block">The access control definitions defining the access management restrictions.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccessConsumer.html" title="interface in org.wildfly.swarm.config.management">AuthorizationAccessConsumer</a>&lt;T extends <a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">AuthorizationAccess</a>&lt;T&gt;&gt;</span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>interface&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccessSupplier.html" title="interface in org.wildfly.swarm.config.management">AuthorizationAccessSupplier</a>&lt;T extends <a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">AuthorizationAccess</a>&gt;</span></code>&nbsp;</td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a> that return <a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">AuthorizationAccess</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">AuthorizationAccess</a></code></td> <td class="colLast"><span class="typeNameLabel">AuthorizationAccessSupplier.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccessSupplier.html#get--">get</a></span>()</code> <div class="block">Constructed instance of AuthorizationAccess resource</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="class in org.wildfly.swarm.config.management">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">WildFly Swarm API, 2016.8.1</div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/wildfly/swarm/config/management/class-use/AuthorizationAccess.html" target="_top">Frames</a></li> <li><a href="AuthorizationAccess.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2016 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "b8f569f2db4d7d4a83798dafc8f27fe7", "timestamp": "", "source": "github", "line_count": 234, "max_line_length": 484, "avg_line_length": 55.61538461538461, "alnum_prop": 0.6785769171661288, "repo_name": "wildfly-swarm/wildfly-swarm-javadocs", "id": "f616e454ef65a8ccf444b813e9113addd472bde5", "size": "13014", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2016.8.1/apidocs/org/wildfly/swarm/config/management/class-use/AuthorizationAccess.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
from beaker.cache import Cache from . import base class TestRedis(base.CacheManagerBaseTests): CACHE_ARGS = { 'type': 'ext:redis', 'url': 'redis://localhost:6379/13' } def test_client_reuse(self): cache1 = Cache('test1', **self.CACHE_ARGS) cli1 = cache1.namespace.client cache2 = Cache('test2', **self.CACHE_ARGS) cli2 = cache2.namespace.client self.assertTrue(cli1 is cli2)
{ "content_hash": "b62bdbaae1aaa2af3055c4066cbad1ce", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 50, "avg_line_length": 27.8125, "alnum_prop": 0.6224719101123596, "repo_name": "masayuko/beaker", "id": "19199388e232b88622d74122dbd7b94d5fd0fb36", "size": "445", "binary": false, "copies": "2", "ref": "refs/heads/rework2", "path": "tests/test_managers/test_ext_redis.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Makefile", "bytes": "2339" }, { "name": "Python", "bytes": "254143" } ], "symlink_target": "" }
Cross-platform access to IBM/HCL Notes/Domino C API methods from Java ## Features The project provides functionality that is not available in the classic Java API of HCL Notes/Domino or that is poorly implemented, for example: * **run DQL (Domino Query Language) queries against databases** on Domino V10 and return the result dynamically sorted * **view lookups using different key formats** (e.g. strings, numbers, dates, date ranges) and equality/**inequality searches (e.g. find less or greater than a search key)** * **decodes all available types of view column data types** (string, string list, number, number list, datetime, datetime list) **and row data** (e.g. just note id, UNID, counts, unread flag etc.) * read view data as **another Notes user** * extract **read access information for rows in a view** that Domino stores in the view index * **separation of Notes views and their data into multiple databases** (like programmatically creating private views and keeping them up-to-date incrementally) * **dynamic filtering of view rows based on a Note id list with paging support (this really rocks!)** * **reading categorized views** with expanded/collapsed entries and min/max level * read **design collection** with design elements in a database * **differential view reads** : on second view lookup, only read rows that have changed * support for view resorting (changing the collation in C API terms) * **direct attachment streaming to create and extract files** (HCL's Java API extracts files to temp disk space first to read attachment data and only supports adding files stored on disk as document attachments) * basic APIs to read note (document) item values like String/Double/Calendar single and multiple values * several APIs to write item values and attachments (needs more work) * **richtext item reading**: convenience method to extract text content, advanced API to read all CD records (IRichTextNavigator) * **richtext item writing**: create richtext items with text, images, doclinks, by rendering other notes and appending other richtet items * **add PNG images to richtext items**: something that cannot easily be done yet in the Notes Client UI * **richtext item conversion**: multi-level conversion of richtext item content, e.g. to **add/remove file hotspots (file icons with custom image that open file on click) independent from the actual file attachment** or do mail merge with richtext * **design richtext processing**: e.g. to **apply a string replacement and recompile formulas** for computed text/subforms or hotspots and **find all fields in a form** * **richtext-html conversion** with advanced quality and access to embedded images * **incremental data synchronization** with external databases or indexers. Generic design, sample implementation for [CQEngine](https://github.com/npgall/cqengine) and [SQLite](https://www.sqlite.org) * **quick check if a document is editable** by a specified user (without the need to scan through author items) * **fulltext index creation** with all available options * supports incremental synchronization of Domino databases by **reading noteid lists of modified and deleted documents** (HCL's Java API does not return ids of deleted docs) * searching NSF data with formula on the fly (NSFSearch in the C API) with all parameters and return values, e.g. **get summary buffer data for each document matching a formula and compute your own field values like the view indexer does** * quick reading of files and folders in the Domino data directory or in subdirectories (HCL's DbDirectory is slow for many DBs and does not support subdirectory scanning) * **run agents bypassing ECL checks**, pass an in-memory document for data exchange readable as `Session.DocumentContext` and redirect Agent output to a Java `Writer` * read/write replication data (change replica id and flags) * clearing the replication history * fast noteid / UNID bulk conversion with lookup of "modified in this file" property (part of the note OID - originator id) * compute @Usernameslist values for any Notes user on local and remote server * faster **formula execution on documents** with document modified/selected/deleted info, **more than 64K of result data and applied security** (e.g. no changes to Notes.ini) * **SSO token computation** (with tokens also working on Websphere) * APIs to **get/put/sync IDs with the ID Vault** and to **sign/encrypt/decrypt** documents and attachments * APIs to **read extended busytime information** like UNID/start/end of busytime entries (not just the freetime search that HCL provides) * APIs to **create/read/update Domino appointments** via iCal format and the option to only output selected fields into the generated iCal (e.g. only start/end/summary) and full meeting workflow action support (accept/decline invitation etc.) * APIs to **read and modify the ECL** * APIs to **read and write Out-of-Office information (OOO) of any user** * API to **read the item definition table** of a database (all fieldnames and fieldtypes, useful to track FT Search issues and provide fieldname typeahead) * **DXL exporter with the option to write the DXL into a stream** (Notes.jar classes fill up the Java heap with a giant DXL string) * **extended folder operations**, e.g. create/delete/move/copy with content/rename, creation of new folder with specifying where to get the design * **efficient lookup of documents without lookup views** by a value in the $Name field (see testcase TestNotePrimaryKey) * creation of **ghost notes** (documents that do not appear in any views) * API to **read the remote server console** and send commands. * **read/write access for the Notes Client workspace** (desktop8.nsk), e.g. read/write page and chicklet infos (titles, server, filename, tabindex, x, y, classic and modern icon), move pages with their icons, move replicas on top * **QueryResultsProcessor API to create JSON And QRP views** **Please note:** **The project gives access to some really low level functions of HCL Notes/Domino. Using them in the wrong way or sending unexpected parameter values might crash your application server, so make sure you know what you are doing and test your code on a local machine first!** One reason for open sourcing all this stuff was to get more hands on it and make it as robust as possible. ## Supported platforms The code should run in 32 and 64 bit Notes Client and Domino server environments on Windows, Linux and Mac. It is not expected to run without changes on other platforms, mainly because of little endian / big endian differences or memory alignments, but we don't currently have access to those platforms anyway. ## XPages Domino JNA can be used in XPages applications! See the [release](https://github.com/klehmann/domino-jna/releases) section for ready to install builds. Those work similar to the XPages Extension Libary. So you need to install the provided OSGi plugins both in Domino Designer and the Domino Server. Here are installation instructions how to do this: [link](http://www.tlcc.com/admin/tlccsite.nsf/pages/extension-lib). The API is available in the code editor after you activate the `com.mindoo.domino.jna.xsp.library` entry in the xsp.properties file. If you are having **trouble getting Domino JNA to work in Designer 9.0.1 FP10 or later**, see this blog posting for a workaround: [link](https://frostillic.us/blog/posts/058650E080E352178525832B00519D2C) In short, you need to add ```<notesdata>\workspace\applications\eclipse``` to your target platform (replace ```<notesdata>``` with your data directory path). ## Maven Domino JNA is available on Maven Central: [https://mvnrepository.com/artifact/com.mindoo.domino/domino-jna](https://mvnrepository.com/artifact/com.mindoo.domino/domino-jna). ```xml <dependency> <groupId>com.mindoo.domino</groupId> <artifactId>domino-jna</artifactId> <version>see Maven Central for latest version number</version> </dependency> ``` Snapshot releases may be provided on [https://oss.sonatype.org/content/repositories/snapshots](https://oss.sonatype.org/content/repositories/snapshots) for bug analysis purpose, e.g. via a Github issue. ## Standalone applications There is a [sample application](https://github.com/klehmann/domino-jna/tree/master/standalone-app-sample) available that demonstrates how to use Domino JNA in standalone Java applications. ## Usage Here is a code snippet for the API usage. It opens a database and filters view entries. ```java NotesGC.runWithAutoGC(new Callable<Object>() { public Object call() throws Exception { //open database with the same access rights as a lotus.domino.Session NotesDatabase dbData = new NotesDatabase(session, "", "fakenames.nsf"); //alternative: open database as another user (used for read and write access): //NotesDatabase dbData = new NotesDatabase("", "fakenames.nsf", "John Doe/Mindoo"); //open database as the server: //NotesDatabase dbData = new NotesDatabase("", "fakenames.nsf", ""); //open People view (in C API called collection) NotesCollection peopleView = dbData.openCollectionByName("People"); //read all note ids from the collection boolean includeCategoryIds = false; LinkedHashSet<Integer> allIds = peopleView.getAllIds(includeCategoryIds); //pick random note ids Integer[] allIdsArr = allIds.toArray(new Integer[allIds.size()]); Set<Integer> pickedNoteIds = new HashSet<Integer>(); while (pickedNoteIds.size() < 1000) { int randomIndex = (int) (Math.random() * allIdsArr.length); int randomNoteId = allIdsArr[randomIndex]; pickedNoteIds.add(randomNoteId); } //populate the collection's selected list with picked ids boolean clearPreviousSelection = true peopleView.select(pickedNoteIds, clearPreviousSelection); //next, traverse selected entries only, starting at position "0" (top of the view) String startPos = "0"; //skip from "0" to the first entry that we are allowed to read //(its position could be different from "1" caused by reader fields) int entriesToSkip = 1; //add all read entries to the result list int entriesToReturn = Integer.MAX_VALUE; //tell the API how to navigate in the view: from one entry in the selectedList //to the next one (in view ordering) EnumSet<Navigate> returnNavigator = EnumSet.of(Navigate.NEXT_SELECTED); //preload the maximum number of entries, can be useful when implementing //filter method in EntriesAsListCallback int bufferSize = Integer.MAX_VALUE; //tell the API which data we want to read (in this case note ids and column values map) EnumSet<ReadMask> returnData = EnumSet.of(ReadMask.NOTEID, ReadMask.SUMMARYVALUES); List<NotesViewEntryData> selectedEntries = peopleView.getAllEntries(startPos, entriesToSkip, returnNavigator, Integer.MAX_VALUE, returnData, new EntriesAsListCallback(entriesToReturn)); for (NotesViewEntryData currEntry : selectedEntries) { //check that all entries that we read were from our picked id list Assert.assertTrue("Entry read from view is contained in selected list", pickedNoteIds.contains(currEntry.getNoteId())); //read column values with their programmatic name String firstName = (String) currEntry.get("firstname"); String lastName = (String) currEntry.get("lastname"); //... } //now remove all read ids from pickedNoteIds and make sure that we found everything //we were searching for for (NotesViewEntryData currEntry : selectedEntries) { pickedNoteIds.remove(currEntry.getNoteId()); } Assert.assertTrue("All ids from the selected list can be found in the view", pickedNoteIds.isEmpty()); return null; } }); ``` Reducing the view to a specific selection (of note ids) is already the first big surprise, if you only know HCL's Java API for Domino. Comparable to reading fulltext search results, but a lot more powerful! And the cool thing is that Domino handles the filtering and even the paging for you (`entriesToSkip` parameter). so you don't have to waste time to read and skip data slowly in your own code. As you can see, all calls have to be wrapped in `NotesGC.runWithAutoGC` code blocks (which can also be nested). We do this to automatically collect allocated C handles and free them when the code block is done. In many cases, this should avoid manual recycling of API objects, but for some edge cases, objects like `NotesCollection` (which is the term for Notes View in the C API), `NotesNote` (a document) or `NotesIDTable` do have a `recycle()` method. When running in an XPages environment, `NotesGC.runWithAutoGC` can be omitted when the code processes a HTTP request (e.g. an XAgent). It is only required if you run code in separate threads, e.g. using the `SessionCloner` class. ## Further information * [New on Github: Domino JNA - Cross-platform access to IBM/HCL Notes/Domino C API methods from Java](http://www.mindoo.com/web/blog.nsf/dx/08.04.2016191137KLEN6U.htm?opendocument&comments) * [Big update for Domino JNA project on Github](http://www.mindoo.com/web/blog.nsf/dx/11.07.2016233301KLETA8.htm?opendocument&comments) * [New APIs for Domino JNA project, now available for XPages development](http://www.mindoo.com/web/blog.nsf/dx/16.01.2017082125KLEAMY.htm?opendocument&comments) * [Explore the hidden parts of an application](https://www.eknori.de/2018-01-29/explore-the-hidden-parts-of-an-application-ibmchampion/) * [Query Domino data and faceted search with Domino JNA (part 1) by Mark Leusink](http://linqed.eu/2018/10/02/query-domino-data-and-faceted-search-with-domino-jna-part-1/) * [Query Domino data and faceted search with Domino JNA (part 2) by Mark Leusink](http://linqed.eu/2018/10/08/query-domino-data-and-faceted-search-with-domino-jna-part-2/) * [Query Domino data with Domino JNA (part 3): REST API and infinite scroll by Mark Leusink](http://linqed.eu/2018/11/02/query-domino-data-with-domino-jna-part-3-rest-api-and-infinite-scroll/) ## Next steps This project is not done yet, this is just the beginning. Here are some of the things that we plan to do: * write [blog entries](http://blog.mindoo.com) explaining the API internals * add more API methods, e.g. for new DQL features of Domino 11 and 12 * write more testcases * add more syntactical sugar, hide complexity ## Licence The code is available under Apache 2.0 license. Copyright by [Mindoo GmbH](http://www.mindoo.com) ## Java Profiler For development, we are using [JProfiler Java profiler](https://www.ej-technologies.com/products/jprofiler/overview.html). It's the perfect tool to analyze performance bottlenecks and memory leaks. ![JProfiler logo](https://www.ej-technologies.com/images/product_banners/jprofiler_small.png) ## Creating your own build The following instructions are only relevant when you want to create your own Domino JNA release version. ### Registration of local Notes.jar, lwpd.commons.jar and lwpd.domino.napi.jar There are three JAR files that are part of every Notes Client installation and that are required to compile the Domino JNA code. On macOS, you can find the files in these locations: * /Applications/HCL Notes.app/Contents/Resources/jvm/lib/ext/Notes.jar * /Applications/HCL Notes.app/Contents/Eclipse/shared/eclipse/plugins/com.ibm.commons_-version-/lwpd.commons.jar * /Applications/HCL Notes.app/Contents/Eclipse/shared/eclipse/plugins/com.ibm.domino.napi_-version-/lwpd.domino.napi.jar On Windows you fine them here: * C:\Program Files (x86)\HCL\Notes\jvm\lib\ext\Notes.jar * C:\Program Files (x86)\HCL\Notes\osgi\shared\eclipse\plugins\com.ibm.commons_-version-\lwpd.commons.jar * C:\Program Files (x86)\HCL\Notes\osgi\shared\eclipse\plugins\com.ibm.domino.napi_-version-\lwpd.domino.napi.jar These files need to be registered as Maven artifacts with the right groupId / artifactId on the local machine, because they are not available on Maven Central (com.ibm.commons is there, but outdated). **For the Mac, use this syntax (replace "-version-" with the right version on your machine):** ``` mvn install:install-file -Dfile="/Applications/HCL Notes.app/Contents/Resources/jvm/lib/ext/Notes.jar" -DgroupId=com.ibm -DartifactId=domino-api-binaries -Dversion=11.0.0 -Dpackaging=jar mvn install:install-file -Dfile="/Applications/HCL Notes.app/Contents/Eclipse/shared/eclipse/plugins/com.ibm.commons_-version-/lwpd.commons.jar" -DgroupId=com.ibm -DartifactId=ibm-commons -Dversion=11.0.0 -Dpackaging=jar mvn install:install-file -Dfile="/Applications/HCL Notes.app/Contents/Eclipse/shared/eclipse/plugins/com.ibm.domino.napi_-version-/lwpd.domino.napi.jar" -DgroupId=com.ibm -DartifactId=napi -Dversion=11.0.0 -Dpackaging=jar ``` **For Windows, use this syntax (replace "-version-" with the right version on your machine):** ``` mvn install:install-file -Dfile="C:\Program Files (x86)\HCL\Notes\jvm\lib\ext\Notes.jar" -DgroupId=com.ibm -DartifactId=domino-api-binaries -Dversion=11.0.0 -Dpackaging=jar mvn install:install-file -Dfile="C:\Program Files (x86)\HCL\Notes\osgi\shared\eclipse\plugins\com.ibm.commons_-version-\lwpd.commons.jar" -DgroupId=com.ibm -DartifactId=ibm-commons -Dversion=11.0.0 -Dpackaging=jar mvn install:install-file -Dfile="C:\Program Files (x86)\HCL\Notes\osgi\shared\eclipse\plugins\com.ibm.domino.napi_-version-\lwpd.domino.napi.jar" -DgroupId=com.ibm -DartifactId=napi -Dversion=11.0.0 -Dpackaging=jar ``` ### Maven build **Mac:** On Mac, use this syntax to build Domino JNA against the Notes Client: ``` mvn -DJVMPARAMS=-d64 -DDOMINOOSGIDIR=/Applications/HCL\ Notes.app/Contents/MacOS -DDOMINODIR=/Applications/HCL\ Notes.app/Contents/MacOS -DNOTESINI=~/Library/Preferences/Notes\ Preferences clean install -Dmaven.test.skip=true ``` **Windows:** To build against the HCL Notes Client on Windows use this syntax: ``` mvn -DJVMPARAMS= -DDOMINOOSGIDIR="C:\Program Files (x86)\HCL\Notes\osgi" -DDOMINODIR="C:\Program Files (x86)\HCL\Notes" -DNOTESINI="C:\Program Files (x86)\HCL\Notes\Notes.ini" clean install -Dmaven.test.skip=true ``` After the build is done, the directory `target/lib` contains all recursive dependencies required to use the library, e.g. JNA and Apache tool libraries. ### Running the test cases The project contains a number of test cases that demonstrate how the API is used. The project is not ready to run the tests automatically as part of the build. That's why they are disabled by default and should only be run manually for now. We are still working on the tests to make the more robust and let them set up their required test environment. In addition there are issues in macOS when running the tests via Surefire plugin, because DYLD_LIBRARY_PATH is not allowed to be set via bash scripts anymore, causing load errors for libnotes.dylib, libxml.dylib and others. #### Sample databases The test cases use sample databases that we provide for download and will update from time to time depending on the requirements of newer testcases. You can download the two sample databases fakenames.nsf and fakenames-views.nsf from this URL: **[Download Link](https://mindoo-my.sharepoint.com/:u:/g/personal/karsten_lehmann_mindoo_de/EQBTfJNeqeNFlcRzEVC5OaYB0xLhMHKg0pzm60qlVQrbMA?e=OVThA4)** Next, place them in the data folder of your HCL Notes Client. fakenames.nsf is a directory database that contains about 40,000 sample documents and some additional lookup views, fakenames-views.nsf uses the same database design, but does not contain any data. We use fakenames-views.nsf to demonstrate indexing of external Domino data (take a local view and incrementally pull data from an external NSF database, like the Notes Client does with private views). In Eclipse, make sure to add the following environment variables (with the right paths for your machine) to the Run Configurations to run testcases: **Windows:** ``` PATH = C:\Program Files (x86)\IBM\Notes ``` **Mac:** ``` DYLD_LIBRARY_PATH=/Applications/HCL Notes.app/Contents/MacOS Notes_ExecDirectory=/Applications/HCL Notes.app/Contents/MacOS NOTESBIN=/Applications/HCL Notes.app/Contents/MacOS NotesINI=/Users/klehmann/Library/Preferences/Notes Preferences PATH=/Applications/HCL Notes.app/Contents/MacOS ``` ### Creating XPages plugin build The projects `com.mindoo.domino.jna.xsp.build` and `domino-target` contain build scripts to use Domino JNA in XPages applications, similar to HCL's XPages Extension Library. Please use the following steps to create a build or just download a binary build from the "releases" section. **1. Target platform** To create the build, you first need to create the Eclipse target platform that we will compile against. This step is only required once. In project `domino-target`, call `mvn clean install` with the same parameters described above (`JVMPARAMS`, `DOMINOOSGIDIR`, `DOMINODIR` and `NOTESINI`). When the build is done, the directory `domino-target/target/repository` contains a P2 Update Site containing the features and plugins of the installed HCL Notes Client that can be used by Maven/Tycho. **2. Build Update Site** Next call `mvn clean install` (also with parameters `JVMPARAMS`, `DOMINOOSGIDIR`, `DOMINODIR` and `NOTESINI`) in project `com.mindoo.domino.jna.xsp.build`. This copies the current Domino JNA source code from project `domino-jna` into two Eclipse plugins `com.mindoo.domino.jna.xsp/jna-src` and `com.mindoo.domino.jna.xsp.source/jna-src` and starts the compilation. `com.mindoo.domino.jna.xsp` provides the extension library for XPages and `com.mindoo.domino.jna.xsp.source` provides the source code for the Java editor of HCL Domino Designer. You can find the created Update Site in directory `com.mindoo.domino.jna.xsp-updatesite/target/site`. ## Dependencies The code uses the following open source projects: [metadata-extractor](https://github.com/drewnoakes/metadata-extractor) for image file metadata extraction, available under Apache 2.0 license [Apache Commons Collections 4](https://commons.apache.org/proper/commons-collections/) for case insensitive maps, available under Apache 2.0 license [ICU4J](http://site.icu-project.org/home/why-use-icu4j) for LMBCS - Java String conversion without C API calls, [license](https://github.com/unicode-org/icu/blob/master/icu4c/LICENSE)
{ "content_hash": "df305ccb50ec43b5d4c4ece8a3374182", "timestamp": "", "source": "github", "line_count": 351, "max_line_length": 274, "avg_line_length": 63.35042735042735, "alnum_prop": 0.7721262817053427, "repo_name": "klehmann/domino-jna", "id": "99fa5992cdb09e97ea1fcf76b137a0f52225c525", "size": "22249", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "4878523" } ], "symlink_target": "" }
package org.contikios.cooja.mspmote.interfaces; import java.util.Collection; import org.apache.log4j.Logger; import org.jdom.Element; import org.contikios.cooja.ClassDescription; import org.contikios.cooja.Mote; import org.contikios.cooja.RadioPacket; import org.contikios.cooja.Simulation; import org.contikios.cooja.interfaces.CustomDataRadio; import org.contikios.cooja.interfaces.Position; import org.contikios.cooja.interfaces.Radio; import org.contikios.cooja.mspmote.MspMote; import org.contikios.cooja.mspmote.MspMoteTimeEvent; import org.contikios.cooja.mspmote.interfaces.CC2420RadioPacketConverter; import se.sics.mspsim.chip.CC2520; import se.sics.mspsim.chip.ChannelListener; import se.sics.mspsim.chip.RFListener; import se.sics.mspsim.core.Chip; import se.sics.mspsim.core.OperatingModeListener; /** * MSPSim CC2520 radio to COOJA wrapper. * * @author Fredrik Osterlind */ @ClassDescription("IEEE CC2520 Radio") public class CC2520Radio extends Radio implements CustomDataRadio { private static Logger logger = Logger.getLogger(CC2520Radio.class); /** * Cross-level: * Inter-byte delay for delivering cross-level packet bytes. */ public static final long DELAY_BETWEEN_BYTES = (long) (1000.0*Simulation.MILLISECOND/(250000.0/8.0)); /* us. Corresponds to 250kbit/s */ private RadioEvent lastEvent = RadioEvent.UNKNOWN; private final MspMote mote; private final CC2520 radio; private boolean isInterfered = false; private boolean isTransmitting = false; private boolean isReceiving = false; private byte lastOutgoingByte; private byte lastIncomingByte; private RadioPacket lastOutgoingPacket = null; private RadioPacket lastIncomingPacket = null; public CC2520Radio(Mote m) { this.mote = (MspMote)m; this.radio = this.mote.getCPU().getChip(CC2520.class); if (radio == null) { throw new IllegalStateException("Mote is not equipped with an IEEE CC2520 radio"); } radio.addRFListener(new RFListener() { int len = 0; int expLen = 0; byte[] buffer = new byte[127 + 15]; public void receivedByte(byte data) { if (!isTransmitting()) { lastEvent = RadioEvent.TRANSMISSION_STARTED; isTransmitting = true; len = 0; /*logger.debug("----- CC2520 TRANSMISSION STARTED -----");*/ setChanged(); notifyObservers(); } if (len >= buffer.length) { /* Bad size packet, too large */ logger.debug("Error: bad size: " + len + ", dropping outgoing byte: " + data); return; } /* send this byte to all nodes */ lastOutgoingByte = data; lastEvent = RadioEvent.CUSTOM_DATA_TRANSMITTED; setChanged(); notifyObservers(); buffer[len++] = data; if (len == 6) { // System.out.println("## CC2520 Packet of length: " + data + " expected..."); expLen = data + 6; } if (len == expLen) { /*logger.debug("----- CC2520 CUSTOM DATA TRANSMITTED -----");*/ len -= 4; /* preamble */ len -= 1; /* synch */ len -= radio.getFooterLength(); /* footer */ final byte[] packetdata = new byte[len]; System.arraycopy(buffer, 4+1, packetdata, 0, len); lastOutgoingPacket = new RadioPacket() { public byte[] getPacketData() { return packetdata; } }; /*logger.debug("----- CC2520 PACKET TRANSMITTED -----");*/ setChanged(); notifyObservers(); /*logger.debug("----- CC2520 TRANSMISSION FINISHED -----");*/ isTransmitting = false; lastEvent = RadioEvent.TRANSMISSION_FINISHED; setChanged(); notifyObservers(); len = 0; } } }); radio.addOperatingModeListener(new OperatingModeListener() { public void modeChanged(Chip source, int mode) { if (radio.isReadyToReceive()) { lastEvent = RadioEvent.HW_ON; setChanged(); notifyObservers(); } else { radioOff(); } } }); radio.addChannelListener(new ChannelListener() { public void channelChanged(int channel) { /* XXX Currently assumes zero channel switch time */ lastEvent = RadioEvent.UNKNOWN; setChanged(); notifyObservers(); } }); } private void radioOff() { /* Radio was turned off during transmission. * May for example happen if watchdog triggers */ if (isTransmitting()) { logger.warn("Turning off radio while transmitting, ending packet prematurely"); /* Simulate end of packet */ lastOutgoingPacket = new RadioPacket() { public byte[] getPacketData() { return new byte[0]; } }; lastEvent = RadioEvent.PACKET_TRANSMITTED; /*logger.debug("----- CC2520 PACKET TRANSMITTED -----");*/ setChanged(); notifyObservers(); /* Register that transmission ended in radio medium */ /*logger.debug("----- CC2520 TRANSMISSION FINISHED -----");*/ isTransmitting = false; lastEvent = RadioEvent.TRANSMISSION_FINISHED; setChanged(); notifyObservers(); } lastEvent = RadioEvent.HW_OFF; setChanged(); notifyObservers(); } /* Packet radio support */ public RadioPacket getLastPacketTransmitted() { return lastOutgoingPacket; } public RadioPacket getLastPacketReceived() { return lastIncomingPacket; } public void setReceivedPacket(RadioPacket packet) { logger.fatal("TODO Implement me!"); } /* Custom data radio support */ public Object getLastCustomDataTransmitted() { return lastOutgoingByte; } public Object getLastCustomDataReceived() { return lastIncomingByte; } public void receiveCustomData(Object data) { if (!(data instanceof Byte)) { logger.fatal("Bad custom data: " + data); return; } lastIncomingByte = (Byte) data; final byte inputByte; if (isInterfered()) { inputByte = (byte)0xFF; } else { inputByte = lastIncomingByte; } mote.getSimulation().scheduleEvent(new MspMoteTimeEvent(mote, 0) { public void execute(long t) { super.execute(t); radio.receivedByte(inputByte); mote.requestImmediateWakeup(); } }, mote.getSimulation().getSimulationTime()); } /* General radio support */ public boolean isTransmitting() { return isTransmitting; } public boolean isReceiving() { return isReceiving; } public boolean isInterfered() { return isInterfered; } public int getChannel() { return radio.getActiveChannel(); } public int getFrequency() { return radio.getActiveFrequency(); } public void signalReceptionStart() { isReceiving = true; lastEvent = RadioEvent.RECEPTION_STARTED; /*logger.debug("----- CC2520 RECEPTION STARTED -----");*/ setChanged(); notifyObservers(); } public void signalReceptionEnd() { /* Deliver packet data */ isReceiving = false; isInterfered = false; lastEvent = RadioEvent.RECEPTION_FINISHED; /*logger.debug("----- CC2520 RECEPTION FINISHED -----");*/ setChanged(); notifyObservers(); } public RadioEvent getLastEvent() { return lastEvent; } public void interfereAnyReception() { isInterfered = true; isReceiving = false; lastIncomingPacket = null; lastEvent = RadioEvent.RECEPTION_INTERFERED; /*logger.debug("----- CC2520 RECEPTION INTERFERED -----");*/ setChanged(); notifyObservers(); } public double getCurrentOutputPower() { return radio.getOutputPower(); } public int getCurrentOutputPowerIndicator() { return 100; // return radio.getOutputPowerIndicator(); } public int getOutputPowerIndicatorMax() { return 100; // return 31; } double currentSignalStrength = 0; /** * Last 8 received signal strengths */ private double[] rssiLast = new double[8]; private int rssiLastCounter = 0; public double getCurrentSignalStrength() { return currentSignalStrength; } public void setCurrentSignalStrength(final double signalStrength) { if (signalStrength == currentSignalStrength) { return; /* ignored */ } currentSignalStrength = signalStrength; if (rssiLastCounter == 0) { getMote().getSimulation().scheduleEvent(new MspMoteTimeEvent(mote, 0) { public void execute(long t) { super.execute(t); /* Update average */ System.arraycopy(rssiLast, 1, rssiLast, 0, 7); rssiLast[7] = currentSignalStrength; double avg = 0; for (double v: rssiLast) { avg += v; } avg /= rssiLast.length; radio.setRSSI((int) avg); rssiLastCounter--; if (rssiLastCounter > 0) { mote.getSimulation().scheduleEvent(this, t+DELAY_BETWEEN_BYTES/2); } } }, mote.getSimulation().getSimulationTime()); } rssiLastCounter = 8; } public void setLQI(int lqi){ radio.setLQI(lqi); } public int getLQI(){ return radio.getLQI(); } public Mote getMote() { return mote; } public Position getPosition() { return mote.getInterfaces().getPosition(); } public Collection<Element> getConfigXML() { return null; } public void setConfigXML(Collection<Element> configXML, boolean visAvailable) { } public boolean isRadioOn() { if (radio.isReadyToReceive()) { return true; } if (radio.getMode() == CC2520.MODE_POWER_OFF) { return false; } if (radio.getMode() == CC2520.MODE_TXRX_OFF) { return false; } return true; } public boolean canReceiveFrom(CustomDataRadio radio) { if (radio.getClass().equals(this.getClass())) { return true; } return false; } }
{ "content_hash": "6db6034430ec31981931bfb1249e3892", "timestamp": "", "source": "github", "line_count": 378, "max_line_length": 93, "avg_line_length": 26.298941798941797, "alnum_prop": 0.6324313449351172, "repo_name": "Mfrielink/Project-Domotica-PowerModule", "id": "3c8bbb65872335481354dd33a5b922e5e87ce553", "size": "9941", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Contiki/GccApplication1/contiki/tools/cooja/apps/mspsim/src/org/contikios/cooja/mspmote/interfaces/CC2520Radio.java", "mode": "33188", "license": "mit", "language": [ { "name": "Awk", "bytes": "95" }, { "name": "C", "bytes": "13924401" }, { "name": "C++", "bytes": "914247" }, { "name": "CSS", "bytes": "10705" }, { "name": "D", "bytes": "377478" }, { "name": "Gnuplot", "bytes": "3141" }, { "name": "Java", "bytes": "2806759" }, { "name": "JavaScript", "bytes": "14044" }, { "name": "Makefile", "bytes": "93690" }, { "name": "Objective-C", "bytes": "3769" }, { "name": "Perl", "bytes": "89010" }, { "name": "Python", "bytes": "427565" }, { "name": "Shell", "bytes": "7672" }, { "name": "XSLT", "bytes": "4947" } ], "symlink_target": "" }
require 'simplecov' SimpleCov.start $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'huginn_agent' require 'huginn_agent/cli' require 'huginn_agent/spec_runner' def capture(stream) begin stream = stream.to_s eval "$#{stream} = StringIO.new" yield result = eval("$#{stream}").string ensure eval("$#{stream} = #{stream.upcase}") end result end RSpec.configure do |c| c.filter_run focus: true c.run_all_when_everything_filtered = true end
{ "content_hash": "0c4c25e899b0eee9675cde20d9e0fd27", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 58, "avg_line_length": 19.64, "alnum_prop": 0.670061099796334, "repo_name": "huginn/huginn_agent", "id": "12de333c363eafd28f9595e68f74b57e153e785a", "size": "491", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/spec_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "17011" } ], "symlink_target": "" }
/*globals require */ /** * @license angular-bootstrap-datetimepicker * Copyright 2016 Knight Rider Consulting, Inc. http://www.knightrider.com * License: MIT */ /** This file is intentionally named browserify.test.js so that it is not picked up by the karma runner **/ var angular = require('angular'); var tapeTest = require('tape'); tapeTest('can load module after requiring', function (t) { 'use strict'; function loadModule() { angular.module('ui.bootstrap.datetimepicker'); } t.throws(loadModule); require('../../'); t.doesNotThrow(loadModule); t.end(); });
{ "content_hash": "6a265035248c6e11347d9d9014ad7451", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 107, "avg_line_length": 24.625, "alnum_prop": 0.6869712351945855, "repo_name": "olojiang/AngularJsDemo", "id": "064253a6d24cfa68ee06eb73e31c16ed19beec35", "size": "591", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/angular-bootstrap-datetimepicker/test/commonjs/browserify.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "212" }, { "name": "HTML", "bytes": "76101" }, { "name": "JavaScript", "bytes": "47942" } ], "symlink_target": "" }
package org.guvnor.tools.preferences; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.guvnor.tools.Activator; import org.guvnor.tools.Messages; import org.guvnor.tools.utils.PlatformUtils; /** * Page for setting Guvnor preferences. */ public class GuvnorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private Text guvnorURLTemplate; private Button savePassword; private Combo decorationIconLoc; private Button incChangeIndicator; private Button incRevision; private Button incDateStamp; public GuvnorPreferencePage() { } public GuvnorPreferencePage(String title) { super(title); } public GuvnorPreferencePage(String title, ImageDescriptor image) { super(title, image); } @Override protected Control createContents(Composite parent) { Composite composite = PlatformUtils.createComposite(parent, 1); Group group = new Group(composite, SWT.NONE); GridData data = new GridData(GridData.FILL_HORIZONTAL); group.setLayoutData(data); GridLayout layout = new GridLayout(); layout.numColumns = 1; group.setLayout(layout); group.setText(Messages.getString("prepage.repository.connections")); //$NON-NLS-1$ Composite doubleLine = PlatformUtils.createComposite(group, 2); new Label(doubleLine, SWT.NONE).setText(Messages.getString("prepage.guvnor.url.template")); //$NON-NLS-1$ guvnorURLTemplate = new Text(doubleLine, SWT.BORDER); guvnorURLTemplate.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); guvnorURLTemplate.setText(getGuvnorTemplatePref()); savePassword = new Button(group, SWT.CHECK); savePassword.setText(Messages.getString("prepage.save.passwords")); //$NON-NLS-1$ savePassword.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); savePassword.setSelection(true); group = new Group(composite, SWT.NONE); data = new GridData(GridData.FILL_HORIZONTAL); group.setLayoutData(data); layout = new GridLayout(); layout.numColumns = 1; group.setLayout(layout); group.setText(Messages.getString("prepage.file.decoration")); //$NON-NLS-1$ doubleLine = PlatformUtils.createComposite(group, 2); new Label(doubleLine, SWT.NONE).setText(Messages.getString("prepage.decoration.location")); //$NON-NLS-1$ decorationIconLoc = new Combo(doubleLine, SWT.BORDER | SWT.DROP_DOWN); String[] locs = IGuvnorPreferenceConstants.OVERLAY_LOCATIONS; for (int i = 0; i < locs.length; i++) { decorationIconLoc.add(locs[i]); } decorationIconLoc.select(getOverlayLocationPref()); Group textDec = new Group(group, SWT.NONE); data = new GridData(GridData.FILL_HORIZONTAL); textDec.setLayoutData(data); layout = new GridLayout(); layout.numColumns = 1; textDec.setLayout(layout); textDec.setText(Messages.getString("prepage.decoration.text")); //$NON-NLS-1$ incChangeIndicator = new Button(textDec, SWT.CHECK); incChangeIndicator.setText(Messages.getString("prepage.include.change.indicator")); //$NON-NLS-1$ incChangeIndicator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); incChangeIndicator.setSelection(shouldShowChangeIndicator()); incRevision = new Button(textDec, SWT.CHECK); incRevision.setText(Messages.getString("prepage.include.revision")); //$NON-NLS-1$ incRevision.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); incRevision.setSelection(shouldShowRevision()); incDateStamp = new Button(textDec, SWT.CHECK); incDateStamp.setText(Messages.getString("prepage.include.date.time.stamp")); //$NON-NLS-1$ incDateStamp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); incDateStamp.setSelection(shouldShowTimeDateStamp()); return composite; } @Override protected IPreferenceStore doGetPreferenceStore() { return Activator.getDefault().getPreferenceStore(); } public void init(IWorkbench workbench) { } @Override protected void performDefaults() { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); String defaultLoc = store.getDefaultString(IGuvnorPreferenceConstants.GUVNOR_LOC_TEMPLATE_PREF); if(defaultLoc == null || "".equals(defaultLoc)){ defaultLoc = IGuvnorPreferenceConstants.GUVNOR_LOC_TEMPLATE_DEFAULT; } store.putValue(IGuvnorPreferenceConstants.GUVNOR_LOC_TEMPLATE_PREF, defaultLoc); guvnorURLTemplate.setText(defaultLoc); store.putValue(IGuvnorPreferenceConstants.SAVE_PASSWORDS_PREF, String.valueOf(true)); savePassword.setSelection(true); store.putValue(IGuvnorPreferenceConstants.OVERLAY_LOCATION_PREF, String.valueOf(IGuvnorPreferenceConstants.OVERLAY_LOCATION_DEFAULT)); decorationIconLoc.select(IGuvnorPreferenceConstants.OVERLAY_LOCATION_DEFAULT); store.putValue(IGuvnorPreferenceConstants.SHOW_CHANGE_INDICATOR_PREF, String.valueOf(true)); incChangeIndicator.setSelection(true); store.putValue(IGuvnorPreferenceConstants.SHOW_REVISION_PREF, String.valueOf(true)); incRevision.setSelection(true); store.putValue(IGuvnorPreferenceConstants.SHOW_DATETIME_PREF, String.valueOf(true)); incDateStamp.setSelection(true); PlatformUtils.updateDecoration(); super.performDefaults(); } @Override public boolean performOk() { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); store.putValue(IGuvnorPreferenceConstants.GUVNOR_LOC_TEMPLATE_PREF, guvnorURLTemplate.getText()); store.putValue(IGuvnorPreferenceConstants.SAVE_PASSWORDS_PREF, String.valueOf(savePassword.getSelection())); store.putValue(IGuvnorPreferenceConstants.OVERLAY_LOCATION_PREF, String.valueOf(decorationIconLoc.getSelectionIndex())); store.putValue(IGuvnorPreferenceConstants.SHOW_CHANGE_INDICATOR_PREF, String.valueOf(incChangeIndicator.getSelection())); store.putValue(IGuvnorPreferenceConstants.SHOW_REVISION_PREF, String.valueOf(incRevision.getSelection())); store.putValue(IGuvnorPreferenceConstants.SHOW_DATETIME_PREF, String.valueOf(incDateStamp.getSelection())); PlatformUtils.updateDecoration(); return super.performOk(); } public static String getGuvnorTemplatePref() { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); String res = null; if (!store.contains(IGuvnorPreferenceConstants.GUVNOR_LOC_TEMPLATE_PREF)) { res = IGuvnorPreferenceConstants.GUVNOR_LOC_TEMPLATE_DEFAULT; store.putValue(IGuvnorPreferenceConstants.GUVNOR_LOC_TEMPLATE_PREF, res); } else { res = store.getString(IGuvnorPreferenceConstants.GUVNOR_LOC_TEMPLATE_PREF); } return res; } public static boolean shouldSavePasswords() { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); boolean res = true; if (!store.contains(IGuvnorPreferenceConstants.SAVE_PASSWORDS_PREF)) { store.putValue(IGuvnorPreferenceConstants.SAVE_PASSWORDS_PREF, String.valueOf(true)); } else { res = store.getBoolean(IGuvnorPreferenceConstants.SAVE_PASSWORDS_PREF); } return res; } public static int getOverlayLocationPref() { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); int res = 0; if (!store.contains(IGuvnorPreferenceConstants.OVERLAY_LOCATION_PREF)) { store.putValue(IGuvnorPreferenceConstants.OVERLAY_LOCATION_PREF, String.valueOf(IGuvnorPreferenceConstants.OVERLAY_LOCATION_DEFAULT)); res = IGuvnorPreferenceConstants.OVERLAY_LOCATION_DEFAULT; } else { res = store.getInt(IGuvnorPreferenceConstants.OVERLAY_LOCATION_PREF); } return res; } public static boolean shouldShowChangeIndicator() { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); boolean res = true; if (!store.contains(IGuvnorPreferenceConstants.SHOW_CHANGE_INDICATOR_PREF)) { store.putValue(IGuvnorPreferenceConstants.SHOW_CHANGE_INDICATOR_PREF, String.valueOf(true)); } else { res = store.getBoolean(IGuvnorPreferenceConstants.SHOW_CHANGE_INDICATOR_PREF); } return res; } public static boolean shouldShowRevision() { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); boolean res = true; if (!store.contains(IGuvnorPreferenceConstants.SHOW_REVISION_PREF)) { store.putValue(IGuvnorPreferenceConstants.SHOW_REVISION_PREF, String.valueOf(true)); } else { res = store.getBoolean(IGuvnorPreferenceConstants.SHOW_REVISION_PREF); } return res; } public static boolean shouldShowTimeDateStamp() { IPreferenceStore store = Activator.getDefault().getPreferenceStore(); boolean res = true; if (!store.contains(IGuvnorPreferenceConstants.SHOW_DATETIME_PREF)) { store.putValue(IGuvnorPreferenceConstants.SHOW_DATETIME_PREF, String.valueOf(true)); } else { res = store.getBoolean(IGuvnorPreferenceConstants.SHOW_DATETIME_PREF); } return res; } }
{ "content_hash": "5b5ebe7ecc951e786118955262344eca", "timestamp": "", "source": "github", "line_count": 250, "max_line_length": 113, "avg_line_length": 41.516, "alnum_prop": 0.6918778302341266, "repo_name": "droolsjbpm/droolsjbpm-tools", "id": "b2c74a0d730e026a102dde4132d3c1fde8e8ebc4", "size": "10999", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "drools-eclipse/org.guvnor.tools/src/org/guvnor/tools/preferences/GuvnorPreferencePage.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "16322" }, { "name": "Java", "bytes": "3935583" } ], "symlink_target": "" }
package br.com.chicobentojr.minhaeiro.activity; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import java.util.ArrayList; import java.util.Calendar; import br.com.chicobentojr.minhaeiro.R; import br.com.chicobentojr.minhaeiro.adapters.PeriodoPagerAdapter; import br.com.chicobentojr.minhaeiro.models.Movimentacao; import br.com.chicobentojr.minhaeiro.utils.P; public class PeriodoActivity extends AppCompatActivity { private PeriodoPagerAdapter pagerAdapter; private ViewPager viewPager; private TabLayout tabLayout; private ArrayList<Calendar> periodos; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_periodo); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); viewPager = (ViewPager) findViewById(R.id.container); tabLayout = (TabLayout) findViewById(R.id.tabs); } @Override protected void onResume() { super.onResume(); carregarPeriodos(); abrirPeriodoMaisRecente(); } public void carregarPeriodos() { periodos = Movimentacao.obterPeriodos(P.getUsuarioInstance().Movimentacao); pagerAdapter = new PeriodoPagerAdapter(getSupportFragmentManager(), periodos, this); viewPager.setAdapter(pagerAdapter); tabLayout.setupWithViewPager(viewPager); } public void abrirPeriodoMaisRecente() { viewPager.setCurrentItem(periodos.size() - 1); } }
{ "content_hash": "bee2f8ba12fb64d42e6c5c103eb9df87", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 92, "avg_line_length": 32.018181818181816, "alnum_prop": 0.740488358886996, "repo_name": "chicobentojr/minhaeiro", "id": "68275c4062e14ae418e411546a7ac0d13e9a940b", "size": "1761", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/br/com/chicobentojr/minhaeiro/activity/PeriodoActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "118636" } ], "symlink_target": "" }
read -p "Username Account going to be unlock: " User passwd -u $User echo "===============================================" echo "Sunan | Explore Network Unlimited" echo "===============================================" echo ""
{ "content_hash": "47d95f1ca5428d844a3a3d627c6254fe", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 54, "avg_line_length": 32.714285714285715, "alnum_prop": 0.4104803493449782, "repo_name": "ExploresNetworkUnlimited/VirtualPrivateServer", "id": "5244e5f2a3312fe9d28893bc5c62be6c8c7b1dad", "size": "311", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "06.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "21789" }, { "name": "Shell", "bytes": "21036" } ], "symlink_target": "" }
'use strict'; var keywords = require('../keywords'); var deepEqual= require('../../utils/object').deepEqual; var hasOwnProperty = require('../../utils/object').hasOwnProperty; function factory (type, config, load, typed, math) { var compile = load(require('./compile')).compile; /** * Node */ function Node() { if (!(this instanceof Node)) { throw new SyntaxError('Constructor must be called with the new operator'); } } /** * Evaluate the node * @param {Object} [scope] Scope to read/write variables * @return {*} Returns the result */ Node.prototype.eval = function(scope) { return this.compile().eval(scope); }; Node.prototype.type = 'Node'; Node.prototype.isNode = true; Node.prototype.comment = ''; /** * Compile the node to javascript code * @return {{eval: function}} expr Returns an object with a function 'eval', * which can be invoked as expr.eval([scope]), * where scope is an optional object with * variables. */ Node.prototype.compile = function () { // TODO: calling compile(math) is deprecated since version 2.0.0. Remove this warning some day if (arguments.length > 0) { throw new Error('Calling compile(math) is deprecated. Call the function as compile() instead.'); } // definitions globally available inside the closure of the compiled expressions var defs = { math: math.expression.mathWithTransform, args: {}, // can be filled with names of FunctionAssignment arguments _validateScope: _validateScope }; // will be used to put local function arguments var args = {}; var code = compile(this, defs, args); var defsCode = Object.keys(defs).map(function (name) { return ' var ' + name + ' = defs["' + name + '"];'; }); var factoryCode = defsCode.join(' ') + 'return {' + ' "eval": function (scope) {' + ' if (scope) _validateScope(scope);' + ' scope = scope || {};' + ' return ' + code + ';' + ' }' + '};'; var factory = new Function('defs', factoryCode); return factory(defs); }; /** * Execute a callback for each of the child nodes of this node * @param {function(child: Node, path: string, parent: Node)} callback */ Node.prototype.forEach = function (callback) { // must be implemented by each of the Node implementations throw new Error('Cannot run forEach on a Node interface'); }; /** * Create a new Node having it's childs be the results of calling * the provided callback function for each of the childs of the original node. * @param {function(child: Node, path: string, parent: Node): Node} callback * @returns {OperatorNode} Returns a transformed copy of the node */ Node.prototype.map = function (callback) { // must be implemented by each of the Node implementations throw new Error('Cannot run map on a Node interface'); }; /** * Validate whether an object is a Node, for use with map * @param {Node} node * @returns {Node} Returns the input if it's a node, else throws an Error * @protected */ Node.prototype._ifNode = function (node) { if (!type.isNode(node)) { throw new TypeError('Callback function must return a Node'); } return node; }; /** * Recursively traverse all nodes in a node tree. Executes given callback for * this node and each of its child nodes. * @param {function(node: Node, path: string, parent: Node)} callback * A callback called for every node in the node tree. */ Node.prototype.traverse = function (callback) { // execute callback for itself callback(this, null, null); // recursively traverse over all childs of a node function _traverse(node, callback) { node.forEach(function (child, path, parent) { callback(child, path, parent); _traverse(child, callback); }); } _traverse(this, callback); }; /** * Recursively transform a node tree via a transform function. * * For example, to replace all nodes of type SymbolNode having name 'x' with a * ConstantNode with value 2: * * var res = Node.transform(function (node, path, parent) { * if (node && node.isSymbolNode) && (node.name == 'x')) { * return new ConstantNode(2); * } * else { * return node; * } * }); * * @param {function(node: Node, path: string, parent: Node) : Node} callback * A mapping function accepting a node, and returning * a replacement for the node or the original node. * Signature: callback(node: Node, index: string, parent: Node) : Node * @return {Node} Returns the original node or its replacement */ Node.prototype.transform = function (callback) { // traverse over all childs function _transform (node, callback) { return node.map(function(child, path, parent) { var replacement = callback(child, path, parent); return _transform(replacement, callback); }); } var replacement = callback(this, null, null); return _transform(replacement, callback); }; /** * Find any node in the node tree matching given filter function. For example, to * find all nodes of type SymbolNode having name 'x': * * var results = Node.filter(function (node) { * return (node && node.isSymbolNode) && (node.name == 'x'); * }); * * @param {function(node: Node, path: string, parent: Node) : Node} callback * A test function returning true when a node matches, and false * otherwise. Function signature: * callback(node: Node, index: string, parent: Node) : boolean * @return {Node[]} nodes An array with nodes matching given filter criteria */ Node.prototype.filter = function (callback) { var nodes = []; this.traverse(function (node, path, parent) { if (callback(node, path, parent)) { nodes.push(node); } }); return nodes; }; // TODO: deprecated since version 1.1.0, remove this some day Node.prototype.find = function () { throw new Error('Function Node.find is deprecated. Use Node.filter instead.'); }; // TODO: deprecated since version 1.1.0, remove this some day Node.prototype.match = function () { throw new Error('Function Node.match is deprecated. See functions Node.filter, Node.transform, Node.traverse.'); }; /** * Create a shallow clone of this node * @return {Node} */ Node.prototype.clone = function () { // must be implemented by each of the Node implementations throw new Error('Cannot clone a Node interface'); }; /** * Create a deep clone of this node * @return {Node} */ Node.prototype.cloneDeep = function () { return this.map(function (node) { return node.cloneDeep(); }); }; /** * Deep compare this node with another node. * @param {Node} other * @return {boolean} Returns true when both nodes are of the same type and * contain the same values (as do their childs) */ Node.prototype.equals = function (other) { return other ? deepEqual(this, other) : false }; /** * Get string representation. (wrapper function) * * This function can get an object of the following form: * { * handler: //This can be a callback function of the form * // "function callback(node, options)"or * // a map that maps function names (used in FunctionNodes) * // to callbacks * parenthesis: "keep" //the parenthesis option (This is optional) * } * * @param {Object} [options] * @return {string} */ Node.prototype.toString = function (options) { var customString; if (options && typeof options === 'object') { switch (typeof options.handler) { case 'object': case 'undefined': break; case 'function': customString = options.handler(this, options); break; default: throw new TypeError('Object or function expected as callback'); } } if (typeof customString !== 'undefined') { return customString; } return this._toString(options); }; /** * Get HTML representation. (wrapper function) * * This function can get an object of the following form: * { * handler: //This can be a callback function of the form * // "function callback(node, options)" or * // a map that maps function names (used in FunctionNodes) * // to callbacks * parenthesis: "keep" //the parenthesis option (This is optional) * } * * @param {Object} [options] * @return {string} */ Node.prototype.toHTML = function (options) { var customString; if (options && typeof options === 'object') { switch (typeof options.handler) { case 'object': case 'undefined': break; case 'function': customString = options.handler(this, options); break; default: throw new TypeError('Object or function expected as callback'); } } if (typeof customString !== 'undefined') { return customString; } return this.toHTML(options); }; /** * Internal function to generate the string output. * This has to be implemented by every Node * * @throws {Error} */ Node.prototype._toString = function () { //must be implemented by each of the Node implementations throw new Error('_toString not implemented for ' + this.type); }; /** * Get LaTeX representation. (wrapper function) * * This function can get an object of the following form: * { * handler: //This can be a callback function of the form * // "function callback(node, options)"or * // a map that maps function names (used in FunctionNodes) * // to callbacks * parenthesis: "keep" //the parenthesis option (This is optional) * } * * @param {Object} [options] * @return {string} */ Node.prototype.toTex = function (options) { var customTex; if (options && typeof options == 'object') { switch (typeof options.handler) { case 'object': case 'undefined': break; case 'function': customTex = options.handler(this, options); break; default: throw new TypeError('Object or function expected as callback'); } } if (typeof customTex !== 'undefined') { return customTex; } return this._toTex(options); }; /** * Internal function to generate the LaTeX output. * This has to be implemented by every Node * * @param {Object} [options] * @throws {Error} */ Node.prototype._toTex = function (options) { //must be implemented by each of the Node implementations throw new Error('_toTex not implemented for ' + this.type); }; /** * Get identifier. * @return {string} */ Node.prototype.getIdentifier = function () { return this.type; }; /** * Get the content of the current Node. * @return {Node} node **/ Node.prototype.getContent = function () { return this; }; /** * Validate the symbol names of a scope. * Throws an error when the scope contains an illegal symbol. * @param {Object} scope */ function _validateScope(scope) { for (var symbol in scope) { if (hasOwnProperty(scope, symbol)) { if (symbol in keywords) { throw new Error('Scope contains an illegal symbol, "' + symbol + '" is a reserved keyword'); } } } } return Node; } exports.name = 'Node'; exports.path = 'expression.node'; exports.math = true; // request access to the math namespace as 5th argument of the factory function exports.factory = factory;
{ "content_hash": "c21146edbc93e4461d3c5367d8da604a", "timestamp": "", "source": "github", "line_count": 404, "max_line_length": 116, "avg_line_length": 30.10148514851485, "alnum_prop": 0.6012663432283529, "repo_name": "Alekcy/vacancy-analysis", "id": "4b171444909a3f565cd9a418a4b5632459eda190", "size": "12161", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "node_modules/mathjs/lib/expression/node/Node.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "10743" }, { "name": "PHP", "bytes": "8231" }, { "name": "Vue", "bytes": "14047" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" style="@style/SessionCardContainer"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:id="@+id/transmission_session_connections_expander" style="@style/CardHeaderExpander" > <TextView style="@style/CardHeaderExpanderText" android:text="@string/session_settings_connections" /> <View android:id="@+id/transmission_session_connections_expander_image" style="@style/CardHeaderExpanderImageCollapse" /> </LinearLayout> <TableLayout android:id="@+id/transmission_session_connections_content" style="@style/CardContent" > <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView style="@style/CardHeading" android:text="@string/session_settings_connections" android:layout_span="2" /> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" android:descendantFocusability="beforeDescendants" android:focusable="true" android:focusableInTouchMode="true" android:gravity="center" > <TextView style="@style/CardTextColumn" android:text="@string/session_settings_peer_port" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="4dp" android:orientation="horizontal"> <EditText android:id="@+id/transmission_session_peer_port" android:inputType="number" android:layout_width="0dp" android:layout_weight="1" style="@style/CardEntry" > </EditText> <Button style="@style/CardButton" android:id="@+id/transmission_session_port_test" android:layout_width="wrap_content" android:ellipsize="end" android:text="@string/session_settings_port_test"/> </LinearLayout> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView style="@style/CardTextColumn" android:text="@string/session_settings_encryption" /> <Spinner android:id="@+id/transmission_session_encryption" android:layout_width="wrap_content" android:layout_height="wrap_content" android:entries="@array/session_settings_encryption" /> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" > <CheckBox android:id="@+id/transmission_session_random_port" android:layout_span="2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/session_settings_random_port" /> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" > <CheckBox android:id="@+id/transmission_session_port_forwarding" android:layout_span="2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/session_settings_port_forwarding" /> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView style="@style/CardHeading" android:text="@string/session_settings_protocol" android:layout_span="2" /> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" > <CheckBox android:id="@+id/transmission_session_peer_exchange" android:layout_span="2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/session_settings_peer_exchange" /> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" > <CheckBox android:id="@+id/transmission_session_hash_table" android:layout_span="2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/session_settings_distributed_hash_table" /> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" > <CheckBox android:id="@+id/transmission_session_local_discovery" android:layout_span="2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/session_settings_local_discovery" /> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" > <CheckBox android:id="@+id/transmission_session_utp" android:layout_span="2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/session_settings_utp" /> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView style="@style/CardHeading" android:text="@string/session_settings_blocklist" android:layout_span="2" /> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" > <CheckBox android:id="@+id/transmission_session_blocklist_check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_span="2" android:text="@string/session_settings_blocklist_enable" /> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" android:focusable="true" android:focusableInTouchMode="true" android:descendantFocusability="beforeDescendants" > <TextView style="@style/CardTextColumn" android:text="@string/session_settings_blocklist_url" /> <EditText android:id="@+id/transmission_session_blocklist_url" android:inputType="textNoSuggestions|textVisiblePassword" style="@style/CardEntry" > </EditText> </TableRow> <TableRow android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="bottom" > <TextView style="@style/CardTextColumn" android:id="@+id/transmission_session_blocklist_size" android:text="@string/session_settings_blocklist_count_format" /> <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <Button android:id="@+id/transmission_session_blocklist_update" style="@style/CardButton" android:ellipsize="end" android:text="@string/session_settings_blocklist_update" /> </FrameLayout> </TableRow> </TableLayout> </LinearLayout> </android.support.v7.widget.CardView>
{ "content_hash": "f06f8719da354336018a736cdcad66db", "timestamp": "", "source": "github", "line_count": 248, "max_line_length": 86, "avg_line_length": 36.854838709677416, "alnum_prop": 0.5089715536105033, "repo_name": "urandom/gearshift", "id": "3a176c4c50ac11ef5bdf8b3ee07d599802916179", "size": "9140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gearshift/src/main/res/layout/transmission_session_connections.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "934520" }, { "name": "Shell", "bytes": "1137" } ], "symlink_target": "" }
FROM balenalib/nuc-debian:bullseye-build # A few reasons for installing distribution-provided OpenJDK: # # 1. Oracle. Licensing prevents us from redistributing the official JDK. # # 2. Compiling OpenJDK also requires the JDK to be installed, and it gets # really hairy. # # For some sample build times, see Debian's buildd logs: # https://buildd.debian.org/status/logs.php?pkg=openjdk-11 RUN apt-get update && apt-get install -y --no-install-recommends \ bzip2 \ unzip \ xz-utils \ && rm -rf /var/lib/apt/lists/* # Default to UTF-8 file.encoding ENV LANG C.UTF-8 # add a simple script that can auto-detect the appropriate JAVA_HOME value # based on whether the JDK or only the JRE is installed RUN { \ echo '#!/bin/sh'; \ echo 'set -e'; \ echo; \ echo 'dirname "$(dirname "$(readlink -f "$(which javac || which java)")")"'; \ } > /usr/local/bin/docker-java-home \ && chmod +x /usr/local/bin/docker-java-home # do some fancy footwork to create a JAVA_HOME that's cross-architecture-safe RUN ln -svT "/usr/lib/jvm/java-11-openjdk-$(dpkg --print-architecture)" /docker-java-home ENV JAVA_HOME /docker-java-home RUN set -ex; \ \ # deal with slim variants not having man page directories (which causes "update-alternatives" to fail) if [ ! -d /usr/share/man/man1 ]; then \ mkdir -p /usr/share/man/man1; \ fi; \ \ apt-get update; \ apt-get install -y --no-install-recommends \ openjdk-11-jre-headless \ ; \ rm -rf /var/lib/apt/lists/*; \ \ rm -vf /usr/local/bin/java; \ \ # ca-certificates-java does not work on src:openjdk-11: (https://bugs.debian.org/914424, https://bugs.debian.org/894979, https://salsa.debian.org/java-team/ca-certificates-java/commit/813b8c4973e6c4bb273d5d02f8d4e0aa0b226c50#d4b95d176f05e34cd0b718357c532dc5a6d66cd7_54_56) keytool -importkeystore -srckeystore /etc/ssl/certs/java/cacerts -destkeystore /etc/ssl/certs/java/cacerts.jks -deststoretype JKS -srcstorepass changeit -deststorepass changeit -noprompt; \ mv /etc/ssl/certs/java/cacerts.jks /etc/ssl/certs/java/cacerts; \ /var/lib/dpkg/info/ca-certificates-java.postinst configure; \ \ # verify that "docker-java-home" returns what we expect [ "$(readlink -f "$JAVA_HOME")" = "$(docker-java-home)" ]; \ \ # update-alternatives so that future installs of other OpenJDK versions don't change /usr/bin/java update-alternatives --get-selections | awk -v home="$(readlink -f "$JAVA_HOME")" 'index($3, home) == 1 { $2 = "manual"; print | "update-alternatives --set-selections" }'; \ # ... and verify that it actually worked for one of the alternatives we care about update-alternatives --query java | grep -q 'Status: manual' CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Debian Bullseye \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nOpenJDK v11-jre \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "9c3cf61b364a931161ac304e465915b3", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 696, "avg_line_length": 52.49295774647887, "alnum_prop": 0.7153206332170646, "repo_name": "resin-io-library/base-images", "id": "994dd4d56ea269274593525b35b4bd1cc2e73be8", "size": "3748", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "balena-base-images/openjdk/nuc/debian/bullseye/11-jre/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "71234697" }, { "name": "JavaScript", "bytes": "13096" }, { "name": "Shell", "bytes": "12051936" }, { "name": "Smarty", "bytes": "59789" } ], "symlink_target": "" }
<?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $this->call(UsersTableSeeder::class); $this->call(ClientsTableSeeder::class); $this->call(LangsTableSeeder::class); } }
{ "content_hash": "0592e97b0acbbf1ade9be3ddf2367ce3", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 47, "avg_line_length": 18.444444444444443, "alnum_prop": 0.5933734939759037, "repo_name": "thinkh/sefrengo-ng", "id": "0e02569c424fcc55c50b976cc2bf0ef323c6a097", "size": "332", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "database/seeds/DatabaseSeeder.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "553" }, { "name": "HTML", "bytes": "18367" }, { "name": "PHP", "bytes": "78391" }, { "name": "Vue", "bytes": "563" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <!--Import Google Icon Font--> <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection" /> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="icon" href="https://docs.google.com/uc?id=0B34Vvn653iTiRTBzVXh1WlAxeVE"> <title> Ben Burdess </title> <link rel="stylesheet" type="text/css" href="/Users/rps/Documents/materialize/css/style.css" /> </head> <ul id="dropdown1" class="dropdown-content"> <li><a href="one.html">Triangles</a></li> <li class="divider"></li> <li><a href="two.html">For Robotics</a></li> <li class="divider"></li> <li><a href="three.html">Msc.</a></li> </ul> <div class="navbar-fixed"> <nav class="teal"> <div class="nav-wrapper"> <a href="index.html" class="brand-logo"> <img class="img tooltipped" data-position="Right" " class="Potato " data-delay="50 " data-tooltip= "Home Button!" src="https://docs.google.com/uc?id=0B34Vvn653iTiRTBzVXh1WlAxeVE"> </a> <ul class="right hide-on-med-and-down"> <li><a href="about.html">About Me</a></li> <li><a href="extra.html">Contact Me</a></li> <!-- Dropdown Trigger --> <li><a class="dropdown-button" href="designs.html" data-activates="dropdown1">Designs<i class="material-icons right">arrow_drop_down</i></a></li> </ul> </div> </div> </nav> </body> <body> <div class="container"> <div class="row"> <div class="align-center" class="white"> <div class="row"> </div> <div class="row"> </div> <div class="row"> </div> <div class="row"> </div> <h1 class="header center teal-text text-lighten-2">Email: benburdess@yahoo.com</h1> <h1 class="header center teal-text text-lighten-2 ">Discord: Benji#3021</h1> <h2 class="header center teal-text text-lighten-2">Follow Me!</h2> <div class="row center "> <a href="https://twitter.com/ben_burdess" class="btn btn-floating btn-large pulse "><i class="material-icons ">thumbs_up_down</i></a> </div> </div> </row> <br><br> </div> <div class="row"> </div> </div> <div id="index-banner" class="parallax-container"> <div class="section no-pad-bot"> <div class="container"> <div class="section"> </div> <div class="section"> </div> <div class="section white"> <h1 class="header center teal-text text-lighten-2">Goodbye</h1> <div class="row center"> </div> </div> <br><br> </div> <br><br> </div> <div class="parallax"><img src="https://docs.google.com/uc?id=0B34Vvn653iTieHNkOVAxUGoyWnM" alt="Unsplashed background img 1" style="display: block; transform: translate3d(-50%, 232px, 0px);"></div> <div class="section"> </div> <div class="section"> </div> <div class="section"> </div> <div class="section"> </div> </div> <footer class="page-footer teal"> <div class="container"> <div class="col l6 s12 "> <h5 class="white-text">About</h5> <p class="grey-text text-lighten-4 ">Fulltime Student and Person. </p> <h5 class="white-text"> Follow Me: </h5> <a href="https://twitter.com/ben_burdess" class="btn btn-floating btn-large pulse "><i class="material-icons ">thumbs_up_down</i></a> </div> <div class="section "> </div> <div class="section "> </div> <!--Import jQuery before materialize.js--> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script type="text/javascript" src="js/materialize.min.js"></script> <script type="text/javascript" src="js/init.js"></script> </body> </html>
{ "content_hash": "0abd4044616737badbcd41445fc9d432", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 237, "avg_line_length": 38.059322033898304, "alnum_prop": 0.5468715208194166, "repo_name": "BenjiShamata/BenjiShamata.github.io", "id": "181ecf98dc98909861e804afec73abf313b200df", "size": "4491", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "extra.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "164021" }, { "name": "HTML", "bytes": "61386" }, { "name": "JavaScript", "bytes": "326753" } ], "symlink_target": "" }
import subprocess import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 def main(): ret = [] sysargs = None cmdarg = demisto.args()['cmd'] if 'sysargs' in demisto.args(): sysargs = demisto.args()['sysargs'] if sysargs is None: output = None try: cmd_list = cmdarg.split() output = subprocess.check_output(cmd_list, shell=False) except subprocess.CalledProcessError as e: output = e.output ret.append(output) else: ret.append(subprocess.check_output([cmdarg, sysargs])) ret = [r.decode('utf-8') for r in ret] # type:ignore[union-attr] ec = {'Command': cmdarg, 'Results': ret[0]} demisto.results({ 'Type': entryTypes['note'], 'ContentsFormat': formats['json'], 'Contents': ret, 'HumanReadable': ret[0], 'EntryContext': {'CommandResults': ec} }) if __name__ in ('__main__', '__builtin__', 'builtins'): main() sys.exit(0)
{ "content_hash": "f64c2d6c31e2ca7eea4dd2b8794eabfc", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 72, "avg_line_length": 26, "alnum_prop": 0.573076923076923, "repo_name": "VirusTotal/content", "id": "c873e574ab02aee0064f0f82ea09d40527304de2", "size": "1040", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Packs/CommonScripts/Scripts/RunDockerCommand/RunDockerCommand.py", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "2146" }, { "name": "HTML", "bytes": "205901" }, { "name": "JavaScript", "bytes": "1584075" }, { "name": "PowerShell", "bytes": "442288" }, { "name": "Python", "bytes": "47594464" }, { "name": "Rich Text Format", "bytes": "480911" }, { "name": "Shell", "bytes": "108066" }, { "name": "YARA", "bytes": "1185" } ], "symlink_target": "" }
/** * This file is part of the CernVM File System */ #include "cvmfs_config.h" #include "swissknife_history.h" #include <ctime> #include "hash.h" #include "util.h" #include "manifest_fetch.h" #include "download.h" #include "signature.h" #include "history.h" #include "catalog_rw.h" #include "upload.h" using namespace std; // NOLINT /** * Checks if the given path looks like a remote path */ static bool IsRemote(const string &repository) { return repository.substr(0, 7) == "http://"; } /** * Retrieves a history db hash from manifest. */ static bool GetHistoryDbHash(const string &repository_url, const string &repository_name, const hash::Any &expected_root_hash, hash::Any *historydb_hash) { manifest::ManifestEnsemble manifest_ensemble; manifest::Manifest *manifest = NULL; if (IsRemote(repository_url)) { manifest::Failures retval; retval = manifest::Fetch(repository_url, repository_name, 0, NULL, &manifest_ensemble); if (retval != manifest::kFailOk) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to fetch repository manifest (%d)", retval); } manifest = manifest_ensemble.manifest; } else { manifest = manifest::Manifest::LoadFile(repository_url + "/.cvmfspublished"); } if (!manifest) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to load repository manifest"); return false; } // Compare base hash with hash in manifest (make sure we operate on the) // right history file if (expected_root_hash != manifest->catalog_hash()) { LogCvmfs(kLogCvmfs, kLogStderr, "wrong manifest, expected catalog %s, found catalog %s", expected_root_hash.ToString().c_str(), manifest->catalog_hash().ToString().c_str()); return false; } *historydb_hash = manifest->history(); return true; } static bool FetchTagList(const string &repository_url, const hash::Any &history_hash, const std::string tmp_path, history::Database *history_db, history::TagList *tag_list) { int retval; if (!history_hash.IsNull()) { const string url = repository_url + "/data" + history_hash.MakePath(1, 2) + "H"; download::JobInfo download_history(&url, true, false, &tmp_path, &history_hash); retval = download::Fetch(&download_history); if (retval != download::kFailOk) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to download history (%d)", retval); return false; } } retval = history_db->Open(tmp_path, sqlite::kDbOpenReadWrite); assert(retval); retval = tag_list->Load(history_db); assert(retval); return true; } int swissknife::CommandTag::Main(const swissknife::ArgumentList &args) { const string repository_url = MakeCanonicalPath(*args.find('r')->second); const string repository_name = *args.find('n')->second; const string repository_key_path = *args.find('k')->second; const string history_path = *args.find('o')->second; const hash::Any base_hash(hash::kSha1, hash::HexPtr(*args.find('b')->second)); const hash::Any trunk_hash(hash::kSha1, hash::HexPtr(*args.find('t')->second)); const unsigned trunk_revision = String2Uint64(*args.find('i')->second); hash::Any tag_hash = trunk_hash; string delete_tag; if (args.find('d') != args.end()) { delete_tag = *args.find('d')->second; } if (args.find('h') != args.end()) { tag_hash = hash::Any(hash::kSha1, hash::HexPtr(*args.find('h')->second)); } history::Tag new_tag; if (args.find('a') != args.end()) { vector<string> fields = SplitString(*args.find('a')->second, '@'); new_tag.name = fields[0]; new_tag.root_hash = trunk_hash; // might be changed later new_tag.revision = trunk_revision; // might be changed later new_tag.timestamp = time(NULL); if (fields.size() > 1) { new_tag.channel = static_cast<history::UpdateChannel>(String2Uint64(fields[1])); } if (fields.size() > 2) new_tag.description = fields[2]; } bool list_only = false; if (args.find('l') != args.end()) list_only = true; hash::Any history_hash; history::Database tag_db; history::TagList tag_list; int retval; // Download & verify manifest signature::Init(); retval = signature::LoadPublicRsaKeys(repository_key_path); if (!retval) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to load public repository key %s", repository_key_path.c_str()); return 1; } download::Init(1, true); int result = 1; retval = GetHistoryDbHash(repository_url, repository_name, base_hash, &history_hash); if (!retval) goto tag_fini; // Download history database / create new history database if (history_hash.IsNull()) { if (list_only) { LogCvmfs(kLogCvmfs, kLogStdout, "no history"); result = 0; goto tag_fini; } retval = history::Database::Create(history_path, repository_name); if (!retval) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to create history database"); goto tag_fini; } } retval = FetchTagList(repository_url, history_hash, history_path, &tag_db, &tag_list); if (!retval) goto tag_fini; if (list_only) { LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak, "%s", tag_list.List().c_str()); result = 0; goto tag_fini; } // Add / Remove tag to history database if (delete_tag != "") { LogCvmfs(kLogHistory, kLogStdout, "Removing tag %s", delete_tag.c_str()); tag_list.Remove(delete_tag); } if (new_tag.name != "") { if (tag_hash != trunk_hash) { history::Tag existing_tag; bool exists = tag_list.FindHash(tag_hash, &existing_tag); if (!exists) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to find hash %s in tag list", tag_hash.ToString().c_str()); goto tag_fini; } tag_list.Remove(new_tag.name); new_tag.root_hash = tag_hash; new_tag.revision = existing_tag.revision; } retval = tag_list.Insert(new_tag); assert(retval == history::TagList::kFailOk); } // Update trunk, trunk-previous tag { history::Tag trunk_previous; bool trunk_found = tag_list.FindTag("trunk", &trunk_previous); tag_list.Remove("trunk-previous"); tag_list.Remove("trunk"); history::Tag tag_trunk( "trunk", trunk_hash, trunk_revision, time(NULL), history::kChannelTrunk, "latest published snapshot, automatically updated"); retval = tag_list.Insert(tag_trunk); assert(retval == history::TagList::kFailOk); if (trunk_found) { trunk_previous.name = "trunk-previous"; trunk_previous.description = "published next to trunk, automatically updated"; retval = tag_list.Insert(trunk_previous); assert(retval == history::TagList::kFailOk); } } //LogCvmfs(kLogCvmfs, kLogStdout, "%s", tag_list.List().c_str()); retval = tag_list.Store(&tag_db); assert(retval); result = 0; tag_fini: signature::Fini(); download::Fini(); return result; } int swissknife::CommandRollback::Main(const swissknife::ArgumentList &args) { const string spooler_definition = *args.find('r')->second; const upload::SpoolerDefinition sd(spooler_definition); upload::Spooler *spooler = upload::Spooler::Construct(sd); assert(spooler); const string repository_url = MakeCanonicalPath(*args.find('u')->second); const string repository_name = *args.find('n')->second; const string repository_key_path = *args.find('k')->second; const string history_path = *args.find('o')->second; const hash::Any base_hash(hash::kSha1, hash::HexPtr(*args.find('b')->second)); const string target_tag_name = *args.find('t')->second; const string manifest_path = *args.find('m')->second; const string temp_dir = *args.find('d')->second; hash::Any history_hash; history::Database tag_db; history::TagList tag_list; history::Tag target_tag; history::Tag trunk_tag; string catalog_path; catalog::WritableCatalog *catalog = NULL; manifest::Manifest *manifest = NULL; hash::Any hash_republished_catalog(hash::kSha1); int retval; // Download & verify manifest & history database signature::Init(); retval = signature::LoadPublicRsaKeys(repository_key_path); if (!retval) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to load public repository key %s", repository_key_path.c_str()); return 1; } download::Init(1, true); int result = 1; retval = GetHistoryDbHash(repository_url, repository_name, base_hash, &history_hash); if (!retval) goto rollback_fini; if (history_hash.IsNull()) { LogCvmfs(kLogCvmfs, kLogStderr, "no history"); goto rollback_fini; } retval = FetchTagList(repository_url, history_hash, history_path, &tag_db, &tag_list); if (!retval) goto rollback_fini; // Verify rollback tag retval = tag_list.FindTag(target_tag_name, &target_tag); if (!retval) { LogCvmfs(kLogCvmfs, kLogStderr, "tag %s does not exist", target_tag_name.c_str()); goto rollback_fini; } retval = tag_list.FindTag("trunk", &trunk_tag); assert(retval); assert(trunk_tag.revision >= target_tag.revision); if (target_tag.revision == trunk_tag.revision) { LogCvmfs(kLogCvmfs, kLogStderr, "not rolling back to trunk revision (%u)", trunk_tag.revision); goto rollback_fini; } { // Download rollback destination catalog FILE *f = CreateTempFile(temp_dir + "/cvmfs", 0600, "w", &catalog_path); assert(f); fclose(f); const string catalog_url = repository_url + "/data" + target_tag.root_hash.MakePath(1, 2) + "C"; download::JobInfo download_catalog(&catalog_url, true, false, &catalog_path, &target_tag.root_hash); retval = download::Fetch(&download_catalog); if (retval != download::kFailOk) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to download catalog (%d)", retval); goto rollback_fini; } } // Update timestamp and revision catalog = catalog::WritableCatalog::AttachFreely("", catalog_path, target_tag.root_hash); assert(catalog); catalog->UpdateLastModified(); catalog->SetRevision(trunk_tag.revision + 1); // Upload catalog if (!zlib::CompressPath2Path(catalog->database_path(), catalog->database_path() + ".compressed", &hash_republished_catalog)) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to compress catalog (%d)"); delete catalog; unlink(catalog_path.c_str()); goto rollback_fini; } spooler->Upload(catalog->database_path() + ".compressed", "data" + hash_republished_catalog.MakePath(1, 2) + "C"); spooler->WaitForUpload(); spooler->WaitForTermination(); unlink((catalog->database_path() + ".compressed").c_str()); manifest = new manifest::Manifest(hash_republished_catalog, ""); manifest->set_ttl(catalog->GetTTL()); manifest->set_revision(catalog->GetRevision()); retval = manifest->Export(manifest_path); assert(retval); delete catalog; unlink(catalog_path.c_str()); delete manifest; // Remove all entries including destination catalog from history tag_list.Rollback(target_tag.revision); // Add new trunk tag / updated named tag to history target_tag.revision = trunk_tag.revision + 1; target_tag.timestamp = time(NULL); target_tag.root_hash = hash_republished_catalog; trunk_tag.revision = target_tag.revision; trunk_tag.timestamp = target_tag.timestamp; trunk_tag.root_hash = target_tag.root_hash; if (target_tag.name != "trunk-previous") tag_list.Insert(target_tag); tag_list.Insert(trunk_tag); retval = tag_list.Store(&tag_db); assert(retval); LogCvmfs(kLogHistory, kLogStdout, "Previous trunk was %s, previous history database was %s", base_hash.ToString().c_str(), history_hash.ToString().c_str()); result = 0; rollback_fini: delete spooler; signature::Fini(); download::Fini(); return result; }
{ "content_hash": "ea554941b04658c6dbc11caf0480ff47", "timestamp": "", "source": "github", "line_count": 372, "max_line_length": 81, "avg_line_length": 33.295698924731184, "alnum_prop": 0.6303891490392378, "repo_name": "bbockelm/cvmfs", "id": "f7c1ea44afee1c74a3ca9e6a6328c5ff5179a1b3", "size": "12386", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cvmfs/swissknife_history.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "5451978" }, { "name": "C++", "bytes": "1404277" }, { "name": "Perl", "bytes": "3436370" }, { "name": "Python", "bytes": "162360" }, { "name": "Shell", "bytes": "244104" } ], "symlink_target": "" }
module ActiveRecord module Reflection class AssociationReflection #:nodoc: def reverse_for?(klass) reverse_matches_for(klass).empty? ? false : true end attr_writer :reverse def reverse if @reverse.nil? and not self.options[:polymorphic] reverse_matches = reverse_matches_for(self.class_name.constantize) rescue nil # grab first association, or make a wild guess @reverse = reverse_matches.blank? ? false : reverse_matches.first.name end @reverse end protected def reverse_matches_for(klass) reverse_matches = [] # stage 1 filter: collect associations that point back to this model and use the same primary_key_name klass.reflect_on_all_associations.each do |assoc| if self.options[:through] # only iterate has_many :through associations next unless assoc.options[:through] next unless assoc.through_reflection.klass == self.through_reflection.klass else # skip over has_many :through associations next if assoc.options[:through] next unless assoc.options[:polymorphic] or assoc.class_name.constantize == self.active_record case [assoc.macro, self.macro].find_all{|m| m == :has_and_belongs_to_many}.length # if both are a habtm, then match them based on the join table when 2 next unless assoc.options[:join_table] == self.options[:join_table] # if only one is a habtm, they do not match when 1 next # otherwise, match them based on the primary_key_name when 0 next unless assoc.primary_key_name.to_sym == self.primary_key_name.to_sym end end reverse_matches << assoc end # stage 2 filter: name-based matching (association name vs self.active_record.to_s) reverse_matches.find_all do |assoc| self.active_record.to_s.underscore.include? assoc.name.to_s.pluralize.singularize end if reverse_matches.length > 1 reverse_matches end end end end
{ "content_hash": "386e9bbd50a83aa3e0236f9c3b65d2d4", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 112, "avg_line_length": 36.645161290322584, "alnum_prop": 0.5981514084507042, "repo_name": "xiviwo/config_track", "id": "d17e119bb252e52de8a27b6c39928a286da97c4a", "size": "2272", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "vendor/plugins/activescaffold/lib/extensions/reverse_associations.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2147" }, { "name": "CSS", "bytes": "33596" }, { "name": "HTML", "bytes": "10570" }, { "name": "JavaScript", "bytes": "108209" }, { "name": "Ruby", "bytes": "81934" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "9ebc761687700c03c8c8cbd5a03fb4cf", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "f61503c25589d2b5614fb6ac1021af13e8990fe2", "size": "188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Santalales/Olacaceae/Olax/Olax minquartioides/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.hazelcast.cp.event.impl; import com.hazelcast.cp.CPMember; import com.hazelcast.cp.event.CPMembershipEvent; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import java.io.IOException; /** * Implementation of {@link CPMembershipEvent}. * * @since 4.1 */ public class CPMembershipEventImpl implements CPMembershipEvent, IdentifiedDataSerializable { private EventType type; private CPMember member; public CPMembershipEventImpl() { } public CPMembershipEventImpl(CPMember member, EventType type) { this.type = type; this.member = member; } public CPMembershipEventImpl(CPMember member, byte eventType) { this.type = toEventType(eventType); this.member = member; } @Override public CPMember getMember() { return member; } @Override public EventType getType() { return type; } @Override public int getFactoryId() { return CpEventDataSerializerHook.F_ID; } @Override public int getClassId() { return CpEventDataSerializerHook.MEMBERSHIP_EVENT; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeObject(member); out.writeUTF(type.name()); } @Override public void readData(ObjectDataInput in) throws IOException { member = in.readObject(); type = EventType.valueOf(in.readUTF()); } @Override public String toString() { return "CPMembershipEvent{" + "type=" + type + ", member=" + member + '}'; } private static EventType toEventType(byte eventType) { switch (eventType) { case MEMBER_ADDED: return EventType.ADDED; case MEMBER_REMOVED: return EventType.REMOVED; default: throw new IllegalArgumentException("Unknown event type: " + eventType); } } }
{ "content_hash": "45d7c419a5dd8dab08b46e49880433d1", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 93, "avg_line_length": 24.30952380952381, "alnum_prop": 0.6518119490695397, "repo_name": "mdogan/hazelcast", "id": "523b924b994f64affeba0f70d310fbea48e84cc0", "size": "2667", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hazelcast/src/main/java/com/hazelcast/cp/event/impl/CPMembershipEventImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1862" }, { "name": "C", "bytes": "3721" }, { "name": "Java", "bytes": "45797218" }, { "name": "Shell", "bytes": "30002" } ], "symlink_target": "" }
// Copyright (c) 2000 Max-Planck-Institute Saarbruecken (Germany). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // 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. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // // // Author(s) : Susan Hert <hert@mpi-sb.mpg.de> /* Node of a rotation tree, used for computing the visibility graph of a set of non-intersecting segments in a graph Associated with each node in the rotation tree is the following information - the coordinates of the associated segment endpoint - a pointer to the parent - a pointer to the left sibling - a pointer to the right sibling - a pointer to the rightmost child. */ #ifndef CGAL_ROTATION_TREE_NODE_H #define CGAL_ROTATION_TREE_NODE_H #include <utility> #include <CGAL/vector.h> namespace CGAL { template <class Traits> class Rotation_tree_2; template <class Traits> class Rotation_tree_node_2 : public Traits::Point_2 { public: typedef typename Traits::Point_2 Base_point; typedef Rotation_tree_node_2<Traits> Self; typedef internal::vector< Self > Tree; typedef typename Tree::iterator Tree_iterator; typedef std::pair<Tree_iterator, bool> Node_ref; Rotation_tree_node_2(Base_point p) : Base_point(p) { _parent.second = false; _left_sibling.second = false; _right_sibling.second = false; _rightmost_child.second = false; } bool has_left_sibling() const { return _left_sibling.second; } Tree_iterator left_sibling() const { return _left_sibling.first; } bool has_right_sibling() const { return _right_sibling.second; } Tree_iterator right_sibling() const { return _right_sibling.first; } bool has_parent() const { return _parent.second; } Tree_iterator parent() const { return _parent.first; } bool has_children() const { return _rightmost_child.second; } Tree_iterator rightmost_child() const { return _rightmost_child.first; } void set_left_sibling(Tree_iterator ls) { _left_sibling.first = ls; _left_sibling.second = true; } void clear_left_sibling() { _left_sibling.second = false; } void set_right_sibling(Tree_iterator rs) { _right_sibling.first = rs; _right_sibling.second = true; } void clear_right_sibling() { _right_sibling.second = false; } void set_parent(Tree_iterator p) { _parent.first = p; _parent.second = true; } void clear_parent() { _parent.second = false; } void set_rightmost_child(Tree_iterator c) { _rightmost_child.first = c; _rightmost_child.second = true; } void clear_rightmost_child() { _rightmost_child.second = false; } bool is_a_leaf() { return !_rightmost_child.second; } private: Node_ref _parent; Node_ref _left_sibling; Node_ref _right_sibling; Node_ref _rightmost_child; }; #ifdef CGAL_PARTITION_DEBUG template <class Traits> std::ostream& operator<<(std::ostream& os, const Rotation_tree_node_2<Traits>& node) { os << node.x() << " " << node.y() << " "; if (node.has_parent()) os << " parent " << (*node.parent()).x() << " " << (*node.parent()).y() << " "; if (node.has_left_sibling()) os << " left sibling " << (*node.left_sibling()).x() << " " << (*node.left_sibling()).y() << " "; if (node.has_right_sibling()) os << " right sibling " << (*node.right_sibling()).x() << " " << (*node.right_sibling()).y() << " "; if (node.has_children()) os << " rightmost child " << (*node.rightmost_child()).x() << " " << (*node.rightmost_child()).y(); return os; } #endif // CGAL_PARTITION_DEBUG } #endif // CGAL_ROTATION_NODE_TREE_H
{ "content_hash": "c405eb20e96d8ced7be188ff5289f5db", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 79, "avg_line_length": 25.850299401197606, "alnum_prop": 0.6231179059532083, "repo_name": "hlzz/dotfiles", "id": "1d6bf3c16c875f06c9d4bccba8194a43e19df41e", "size": "4317", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "graphics/cgal/Partition_2/include/CGAL/Partition_2/Rotation_tree_node_2.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "1240" }, { "name": "Arc", "bytes": "38" }, { "name": "Assembly", "bytes": "449468" }, { "name": "Batchfile", "bytes": "16152" }, { "name": "C", "bytes": "102303195" }, { "name": "C++", "bytes": "155056606" }, { "name": "CMake", "bytes": "7200627" }, { "name": "CSS", "bytes": "179330" }, { "name": "Cuda", "bytes": "30026" }, { "name": "D", "bytes": "2152" }, { "name": "Emacs Lisp", "bytes": "14892" }, { "name": "FORTRAN", "bytes": "5276" }, { "name": "Forth", "bytes": "3637" }, { "name": "GAP", "bytes": "14495" }, { "name": "GLSL", "bytes": "438205" }, { "name": "Gnuplot", "bytes": "327" }, { "name": "Groff", "bytes": "518260" }, { "name": "HLSL", "bytes": "965" }, { "name": "HTML", "bytes": "2003175" }, { "name": "Haskell", "bytes": "10370" }, { "name": "IDL", "bytes": "2466" }, { "name": "Java", "bytes": "219109" }, { "name": "JavaScript", "bytes": "1618007" }, { "name": "Lex", "bytes": "119058" }, { "name": "Lua", "bytes": "23167" }, { "name": "M", "bytes": "1080" }, { "name": "M4", "bytes": "292475" }, { "name": "Makefile", "bytes": "7112810" }, { "name": "Matlab", "bytes": "1582" }, { "name": "NSIS", "bytes": "34176" }, { "name": "Objective-C", "bytes": "65312" }, { "name": "Objective-C++", "bytes": "269995" }, { "name": "PAWN", "bytes": "4107117" }, { "name": "PHP", "bytes": "2690" }, { "name": "Pascal", "bytes": "5054" }, { "name": "Perl", "bytes": "485508" }, { "name": "Pike", "bytes": "1338" }, { "name": "Prolog", "bytes": "5284" }, { "name": "Python", "bytes": "16799659" }, { "name": "QMake", "bytes": "89858" }, { "name": "Rebol", "bytes": "291" }, { "name": "Ruby", "bytes": "21590" }, { "name": "Scilab", "bytes": "120244" }, { "name": "Shell", "bytes": "2266191" }, { "name": "Slash", "bytes": "1536" }, { "name": "Smarty", "bytes": "1368" }, { "name": "Swift", "bytes": "331" }, { "name": "Tcl", "bytes": "1911873" }, { "name": "TeX", "bytes": "11981" }, { "name": "Verilog", "bytes": "3893" }, { "name": "VimL", "bytes": "595114" }, { "name": "XSLT", "bytes": "62675" }, { "name": "Yacc", "bytes": "307000" }, { "name": "eC", "bytes": "366863" } ], "symlink_target": "" }
using Hach.Library.Services.Caching; using Hach.Library.Services.Mail; using Hach.Library.Services.Mapping.Base; using Hach.Library.Services.Mapping.Geolocation; using Hach.Library.Services.Serialization.Base; using Hach.Library.Services.Thread; using Hach.Library.Services.Web; namespace Hach.Library.Services.Facade { /// <summary> /// Facade to handle all predefined Services /// </summary> /// <author> /// Christian Hahn, Sep-2016 /// </author> public interface IPredefinedServiceFacade { #region Properties /// <summary> /// Reference to the Url Request Parameter Service /// </summary> IRequestParameterService RequestParameterService { get; } /// <summary> /// Reference to the Request Service /// </summary> IRequestService RequestService { get; } /// <summary> /// Reference to a mapping Service /// </summary> IMappingService MappingService { get; } /// <summary> /// Reference to a geolocation mapping Service /// </summary> IGeolocationMappingService GeolocationMappingService { get; } /// <summary> /// Reference to a Caching Service /// </summary> ICachingService CachingService { get; } /// <summary> /// Reference to a Serialization Service /// </summary> ISerializationService SerializationService { get; } /// <summary> /// Reference to a Thread Service /// </summary> IThreadService ThreadService { get; } /// <summary> /// Reference to a Mail Service /// </summary> IMailService MailService { get; } #endregion } }
{ "content_hash": "f25af5e47b861f75537f4cb39a8bab7a", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 69, "avg_line_length": 27.873015873015873, "alnum_prop": 0.6047835990888383, "repo_name": "Chris1415/Hach.Library", "id": "29558d25bd61fda7553a065ee15aac5ebab37fab", "size": "1758", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Hach.Library/Hach.Library/Services/Facade/IPredefinedServiceFacade.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "746" }, { "name": "C#", "bytes": "128654" }, { "name": "PowerShell", "bytes": "97133" } ], "symlink_target": "" }
package org.sbbs.demo.service; import org.sbbs.base.service.BaseTreeManager; import org.sbbs.demo.model.DemoTreeNode; public interface DemoTreeNodeManager extends BaseTreeManager<DemoTreeNode, Long> { // public List processNodeIsLeaf(List list); // public void rebuildNestSetTree(); // public int buildNestTreeFromAdjacency(Long id,int leftNmuber); }
{ "content_hash": "bf735d5fe47e57818d01ce8080f609a4", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 66, "avg_line_length": 30.083333333333332, "alnum_prop": 0.7950138504155124, "repo_name": "fdcmessenger/framework", "id": "ed53ef7b315021acfab2e103306efff3ac01be46", "size": "361", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "service/src/main/java/org/sbbs/demo/service/DemoTreeNodeManager.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "234552" }, { "name": "HTML", "bytes": "902343" }, { "name": "Java", "bytes": "360396" }, { "name": "JavaScript", "bytes": "1944782" }, { "name": "PHP", "bytes": "27273" }, { "name": "SQLPL", "bytes": "1449" } ], "symlink_target": "" }
<?php /** Zend_Loader */ require_once 'Zend/Loader.php'; /** * Autoloader stack and namespace autoloader * * @uses Zend_Loader_Autoloader * @package Zend_Loader * @subpackage Autoloader * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) * @license New BSD {@link http://framework.zend.com/license/new-bsd} */ class Zend_Loader_Autoloader { /** * @var Zend_Loader_Autoloader Singleton instance */ protected static $_instance; /** * @var array Concrete autoloader callback implementations */ protected $_autoloaders = array(); /** * @var array Default autoloader callback */ protected $_defaultAutoloader = array('Zend_Loader', 'loadClass'); /** * @var bool Whether or not to act as a fallback autoloader */ protected $_fallbackAutoloader = false; /** * @var array Callback for internal autoloader implementation */ protected $_internalAutoloader; /** * @var array Supported namespaces 'Zend' and 'ZendX' by default. */ protected $_namespaces = array( 'Zend_' => true, 'ZendX_' => true, ); /** * @var array Namespace-specific autoloaders */ protected $_namespaceAutoloaders = array(); /** * @var bool Whether or not to suppress file not found warnings */ protected $_suppressNotFoundWarnings = true; /** * Retrieve singleton instance * * @return Zend_Loader_Autoloader */ public static function getInstance() { if (null === self::$_instance) { self::$_instance = new self(); } return self::$_instance; } /** * Reset the singleton instance * * @return void */ public static function resetInstance() { self::$_instance = null; } /** * Autoload a class * * @param string $class * @return bool */ public static function autoload($class) { $self = self::getInstance(); foreach ($self->getClassAutoloaders($class) as $autoloader) { if ($autoloader instanceof Zend_Loader_Autoloader_Interface) { if ($autoloader->autoload($class)) { return true; } } elseif (is_string($autoloader)) { if ($autoloader($class)) { return true; } } elseif (is_array($autoloader)) { $object = array_shift($autoloader); $method = array_shift($autoloader); if (call_user_func(array($object, $method), $class)) { return true; } } } return false; } /** * Set the default autoloader implementation * * @param string|array $callback PHP callback * @return void */ public function setDefaultAutoloader($callback) { if (!is_callable($callback)) { throw new Zend_Loader_Exception('Invalid callback specified for default autoloader'); } $this->_defaultAutoloader = $callback; return $this; } /** * Retrieve the default autoloader callback * * @return string|array PHP Callback */ public function getDefaultAutoloader() { return $this->_defaultAutoloader; } /** * Set several autoloader callbacks at once * * @param array $autoloaders Array of PHP callbacks (or Zend_Loader_Autoloader_Interface implementations) to act as autoloaders * @return Zend_Loader_Autoloader */ public function setAutoloaders(array $autoloaders) { $this->_autoloaders = $autoloaders; return $this; } /** * Get attached autoloader implementations * * @return array */ public function getAutoloaders() { return $this->_autoloaders; } /** * Return all autoloaders for a given namespace * * @param string $namespace * @return array */ public function getNamespaceAutoloaders($namespace) { $namespace = (string) $namespace; if (!array_key_exists($namespace, $this->_namespaceAutoloaders)) { return array(); } return $this->_namespaceAutoloaders[$namespace]; } /** * Register a namespace to autoload * * @param string $namespace * @return Zend_Loader_Autoloader */ public function registerNamespace($namespace) { if (is_string($namespace)) { $namespace = (array) $namespace; } elseif (!is_array($namespace)) { throw new Zend_Loader_Exception('Invalid namespace provided'); } foreach ($namespace as $ns) { if (!isset($this->_namespaces[$ns])) { $this->_namespaces[$ns] = true; } } return $this; } /** * Unload a registered autoload namespace * * @param string $namespace * @return Zend_Loader_Autoloader */ public function unregisterNamespace($namespace) { if (is_string($namespace)) { $namespace = (array) $namespace; } elseif (!is_array($namespace)) { throw new Zend_Loader_Exception('Invalid namespace provided'); } foreach ($namespace as $ns) { if (isset($this->_namespaces[$ns])) { unset($this->_namespaces[$ns]); } } return $this; } /** * Get a list of registered autoload namespaces * * @return array */ public function getRegisteredNamespaces() { return array_keys($this->_namespaces); } /** * Get or set the value of the "suppress not found warnings" flag * * @param null|bool $flag * @return bool|Zend_Loader_Autoloader Returns boolean if no argument is passed, object instance otherwise */ public function suppressNotFoundWarnings($flag = null) { if (null === $flag) { return $this->_suppressNotFoundWarnings; } $this->_suppressNotFoundWarnings = (bool) $flag; return $this; } /** * Indicate whether or not this autoloader should be a fallback autoloader * * @param bool $flag * @return Zend_Loader_Autoloader */ public function setFallbackAutoloader($flag) { $this->_fallbackAutoloader = (bool) $flag; return $this; } /** * Is this instance acting as a fallback autoloader? * * @return bool */ public function isFallbackAutoloader() { return $this->_fallbackAutoloader; } /** * Get autoloaders to use when matching class * * Determines if the class matches a registered namespace, and, if so, * returns only the autoloaders for that namespace. Otherwise, it returns * all non-namespaced autoloaders. * * @param string $class * @return array Array of autoloaders to use */ public function getClassAutoloaders($class) { $namespace = false; $autoloaders = array(); // Add concrete namespaced autoloaders foreach (array_keys($this->_namespaceAutoloaders) as $ns) { if ('' == $ns) { continue; } if (0 === strpos($class, $ns)) { $namespace = $ns; $autoloaders = $autoloaders + $this->getNamespaceAutoloaders($ns); break; } } // Add internal namespaced autoloader foreach ($this->getRegisteredNamespaces() as $ns) { if (0 === strpos($class, $ns)) { $namespace = $ns; $autoloaders[] = $this->_internalAutoloader; break; } } // Add non-namespaced autoloaders $autoloaders = $autoloaders + $this->getNamespaceAutoloaders(''); // Add fallback autoloader if (!$namespace && $this->isFallbackAutoloader()) { $autoloaders[] = $this->_internalAutoloader; } return $autoloaders; } /** * Add an autoloader to the beginning of the stack * * @param object|array|string $callback PHP callback or Zend_Loader_Autoloader_Interface implementation * @param string|array $namespace Specific namespace(s) under which to register callback * @return Zend_Loader_Autoloader */ public function unshiftAutoloader($callback, $namespace = '') { $autoloaders = $this->getAutoloaders(); array_unshift($autoloaders, $callback); $this->setAutoloaders($autoloaders); $namespace = (array) $namespace; foreach ($namespace as $ns) { $autoloaders = $this->getNamespaceAutoloaders($ns); array_unshift($autoloaders, $callback); $this->_setNamespaceAutoloaders($autoloaders, $ns); } return $this; } /** * Append an autoloader to the autoloader stack * * @param object|array|string $callback PHP callback or Zend_Loader_Autoloader_Interface implementation * @param string|array $namespace Specific namespace(s) under which to register callback * @return Zend_Loader_Autoloader */ public function pushAutoloader($callback, $namespace = '') { $autoloaders = $this->getAutoloaders(); array_push($autoloaders, $callback); $this->setAutoloaders($autoloaders); $namespace = (array) $namespace; foreach ($namespace as $ns) { $autoloaders = $this->getNamespaceAutoloaders($ns); array_push($autoloaders, $callback); $this->_setNamespaceAutoloaders($autoloaders, $ns); } return $this; } /** * Remove an autoloader from the autoloader stack * * @param object|array|string $callback PHP callback or Zend_Loader_Autoloader_Interface implementation * @param null|string|array $namespace Specific namespace(s) from which to remove autoloader * @return Zend_Loader_Autoloader */ public function removeAutoloader($callback, $namespace = null) { if (null === $namespace) { $autoloaders = $this->getAutoloaders(); if (false !== ($index = array_search($callback, $autoloaders, true))) { unset($autoloaders[$index]); $this->setAutoloaders($autoloaders); } foreach ($this->_namespaceAutoloaders as $ns => $autoloaders) { if (false !== ($index = array_search($callback, $autoloaders, true))) { unset($autoloaders[$index]); $this->_setNamespaceAutoloaders($autoloaders, $ns); } } } else { $namespace = (array) $namespace; foreach ($namespace as $ns) { $autoloaders = $this->getNamespaceAutoloaders($ns); if (false !== ($index = array_search($callback, $autoloaders, true))) { unset($autoloaders[$index]); $this->_setNamespaceAutoloaders($autoloaders, $ns); } } } return $this; } /** * Constructor * * Registers instance with spl_autoload stack * * @return void */ protected function __construct() { spl_autoload_register(array(__CLASS__, 'autoload')); $this->_internalAutoloader = array($this, '_autoload'); } /** * Internal autoloader implementation * * @param string $class * @return bool */ protected function _autoload($class) { $callback = $this->getDefaultAutoloader(); if ($this->suppressNotFoundWarnings()) { try { @call_user_func($callback, $class); return $class; } catch (Zend_Exception $e) { return false; } } return call_user_func($callback, $class); } /** * Set autoloaders for a specific namespace * * @param array $autoloaders * @param string $namespace * @return Zend_Loader_Autoloader */ protected function _setNamespaceAutoloaders(array $autoloaders, $namespace = '') { $namespace = (string) $namespace; $this->_namespaceAutoloaders[$namespace] = $autoloaders; return $this; } }
{ "content_hash": "55d3f5afe9748b6eab3fffa4acbef490", "timestamp": "", "source": "github", "line_count": 444, "max_line_length": 132, "avg_line_length": 28.306306306306308, "alnum_prop": 0.55975493316359, "repo_name": "tolu/liu-bookbox", "id": "448cd53ae8844fe19b9d350a8a8255a586490832", "size": "13338", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lib/vendor/Zend/Loader/Autoloader.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "56262" }, { "name": "JavaScript", "bytes": "293074" }, { "name": "PHP", "bytes": "4207819" }, { "name": "Shell", "bytes": "3583" } ], "symlink_target": "" }
module Locomotive module Extensions module Page module Templatized extend ActiveSupport::Concern included do ## fields ## field :templatized, type: Boolean, default: false field :templatized_from_parent, type: Boolean, default: false field :target_klass_name ## validations ## validates_presence_of :target_klass_name, if: :templatized? validate :ensure_target_klass_name_security ## callbacks ## before_validation :get_templatized_from_parent before_validation :ensure_target_klass_name_security after_validation :set_slug_if_templatized after_save :propagate_templatized ## scopes ## scope :templatized, where(templatized: true) ## virtual attributes ## attr_accessor :content_entry end # Return the content type specified by the target_klass_name property. # # @return [ Object ] The content type or nil if not found # def content_type if self.target_klass_name =~ /^Locomotive::ContentEntry([a-z0-9]+)$/ @content_type ||= self.site.content_types.find($1) else nil end end # Return the class specified by the target_klass_name property # # @example # # page.target_klass_name = 'Locomotive::ContentEntry12345' # page.target_klass # <Locomotive::ContentEntry12345...> # # @return [ Class ] The target class # def target_klass target_klass_name.constantize end # Return the slug related to the target_klass. # In other words, it returns the slug of the target content type. # # @return [ String ] The slug of the target class / content type. Nil if no target klass matching a content type # def target_klass_slug self.content_type.try(:slug) end # Set the target klass from the slug of a content type # # @param [ String ] slug The slug of the content type # # @return [ Object ] The content type or nil if not found # def target_klass_slug=(slug) if @content_type = self.site.content_types.where(slug: slug).first self.target_klass_name = @content_type.entries_class_name end @content_type end # Give the name which can be used in a liquid template in order # to reference an entry. It uses the slug property if the target klass # is a Locomotive content type or the class name itself for the other classes. # # @example # # page.target_klass_name = 'Locomotive::ContentEntry12345' # related to the content type Articles # page.target_entry_name = 'article' # # page.target_klass_name = 'OurProduct' # page.target_entry_name = 'our_product' # # @return [ String ] The name in lowercase and underscored # def target_entry_name if self.content_type self.content_type.slug.singularize else self.target_klass_name.underscore end end # Find the entry both specified by the target klass and identified by the permalink # # @param [ String ] permalink The permalink of the entry # # @return [ Object ] The document # def fetch_target_entry(permalink) target_klass.find_by_permalink(permalink) end # Find all the ordered entries of the target klass filtered or not # by the conditions passed in parameter. # # @param [ Hash ] conditions The conditions used to filter the entries (optional) # # @return [ Object ] The documents # def fetch_target_entries(conditions = {}) if self.content_type self.content_type.ordered_entries(conditions) else [] end end protected def get_templatized_from_parent return if self.parent.nil? if self.parent.templatized? self.templatized = self.templatized_from_parent = true self.target_klass_name = self.parent.target_klass_name elsif !self.templatized? self.templatized = self.templatized_from_parent = false self.target_klass_name = nil end end def set_slug_if_templatized self.slug = 'content_type_template' if self.templatized? && !self.templatized_from_parent? end # Make sure the target_klass is owned by the site OR # if it belongs to the models allowed by the application # thanks to the models_for_templatization option. # def ensure_target_klass_name_security return if !self.templatized? || self.target_klass_name.blank? if self.target_klass_name =~ /^Locomotive::ContentEntry([a-z0-9]+)$/ content_type = Locomotive::ContentType.find($1) if content_type.site_id != self.site_id self.errors.add :target_klass_name, :security end elsif !Locomotive.config.models_for_templatization.include?(self.target_klass_name) self.errors.add :target_klass_name, :security end end # Set the templatized, templatized_from_parent properties of # the children of the current page ONLY IF the templatized # attribute got changed. # def propagate_templatized return unless self.templatized_changed? selector = { 'parent_ids' => { '$in' => [self._id] } } operations = { '$set' => { 'templatized' => self.templatized, 'templatized_from_parent' => self.templatized, 'target_klass_name' => self.target_klass_name } } self.collection.find(selector).update(operations, multi: true) end end end end end
{ "content_hash": "5b474548095cb05cb41ae166197ce301", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 120, "avg_line_length": 33.869565217391305, "alnum_prop": 0.5754172015404364, "repo_name": "supercodes/locomotivecms", "id": "13538ed8017471b378a6eebb3f542b7a5db12fdb", "size": "6232", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/locomotive/extensions/page/templatized.rb", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "38100" }, { "name": "CoffeeScript", "bytes": "104047" }, { "name": "JavaScript", "bytes": "13375" }, { "name": "Perl", "bytes": "19581" }, { "name": "Racket", "bytes": "21" }, { "name": "Ruby", "bytes": "647606" }, { "name": "Shell", "bytes": "1546" } ], "symlink_target": "" }
// // Vector // #include "liquid.internal.h" #define VECTOR(name) LIQUID_CONCAT(liquid_vectorf,name) #define T float #define TP float #define T_COMPLEX 0 #include "vector_trig.proto.c"
{ "content_hash": "25b3696acadc2f2cf98636edfaab7bea", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 58, "avg_line_length": 14.3125, "alnum_prop": 0.5938864628820961, "repo_name": "jgaeddert/liquid-dsp", "id": "8ab60b5c1c73d5db22ea18ab9760ac0f987ece70", "size": "1355", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/vector/src/vectorf_trig.port.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "181" }, { "name": "C", "bytes": "5103497" }, { "name": "C++", "bytes": "557039" }, { "name": "M4", "bytes": "47089" }, { "name": "MATLAB", "bytes": "29973" }, { "name": "Python", "bytes": "10196" }, { "name": "Shell", "bytes": "14525" } ], "symlink_target": "" }
package cn.flyaudio.widgetswitch.alltools; public final class FlyConstant { public static final int WAHT_STATUS_VALUE = 10;// 信使Message what值 /** Key模块通信 **/ public static final int MODE_CONTROL_ID = 196862;// ControlID public static final byte MODE_CONTROL_TYPE = (byte) 0XFE;// ControlType public static final int FAN_OPEN = 1;// 打开风扇 public static final int FAN_CLOSE = 2;// 关闭风扇 public static final int FAN_AUTO = 3;// 关闭风扇 public static final int LCD_HIGH = 4; public static final int LCD_MID = 5; public static final int LCD_LOW = 6; public static final int LCD_CLOSE = 7; public static final int SEEK_INC = 23; public static final int SEEK_DEC = 20; public static final int VOL_MUTE = 14;// 客戶端 MUTE值 public static final int VOL_INC = 15;// 客戶端 键VOL+值 public static final int VOL_DEC = 16;// 客戶端 键VOL-值 /** UI参数结构 **/ public static final int NAVI_VOL_CLOSE = 40; public static final int NAVI_VOL_PALY = 41; public static final int REQUESTVOICE_STOP = 42; public static final int REQUESTVOICE_PALY = 43; public static final int DORMANCY = 44; public static final int RESTART = 45; public static final int RESTORESET = 46; public static final int UPGRADE = 47; public static final int IDLE = 48; public static final int RINGING = 49; public static final int OFFHOOK = 50; public static final int SCREEN_BLACK = 51; public static final int SCREEN_DIM = 52; public static final int SCREEN_MEDIUM = 53; public static final int SCREEN_LIGHT = 54; public static final int MEDIA_STOP = 55; public static final int MEDIA_PALY = 56; public static final int MEDIA_PAUSE = 57; public static final int POWER_ON = 58; public static final int POWER_OFF = 59; public static final int ACC_ON = 60; public static final int ACC_OFF = 61; public static final int RESERVED_POWER_ON = 62; public static final int RESERVED_POWER_OFF = 63; public static final int UI_MODE_CONTROL_ID = 0;// ControlID for UI public static final byte UI_MODE_CONTROL_TYPE = (byte) 0XFF;// ControlType /** MP3 模块 **/ public static final int MP3_STOP = 30; public static final int MP3_PLAY = 31; public static final int MP3_PAUSE = 32; public static final int MP3_TOTALTIME = 33; public static final int MP3_CURRENT_PLAYTIME = 34; public static final int MP3_MODE_CONTROL_ID = 721150;// ControlID for MP3 public static final byte MP3_MODE_CONTROL_TYPE = (byte) 0XFE;// ControlType /** GPS模块通信 凯立德导航消息 **/ public static final int GPS_MODE_CONTROL_ID = 1118462;// ControlID for GPS public static final byte GPS_MODE_CONTROL_TYPE = (byte) 0XFE;// ControlType /** service模块通信(ControlID为0xFF00FE,UI操作为必须为0xFE) **/ public static final int SERV_MODE_CONTROL_ID = 16711934; public static final byte SERV_MODE_CONTROL_TYPE = (byte) 0XFE; /** externalCtrl模块通信 (1) 语音信息 **/ public static final int EXTER_MODE_CONTROL_ID = 16515073; public static final byte EXTER_MODE_CONTROL_TYPE = (byte) 0XFE; // 音量具体大小控制 public static final int VOLUM_MAX = 68; public static final int VOLUM_MIN = 69; // 收音机控制 public static final int RADIO_CLOSE = 70; public static final int RADIO_OPEN = 71; public static final int RADIO_SCAN = 72; public static final int RADIO_SCAN_PLUS = 73; public static final int RADIO_SCAN_MINUS = 74; public static final int RADIO_SCAN_STOP = 75; public static final int RADIO_SCAN_REPEAT = 76; public static final int RADIO_SCAN_PLUS_REPEAT = 77; public static final int RADIO_SCAN_MINUS_REPEAT = 78; // 碟机播放控制 public static final int DVD_STOP = 80; public static final int DVD_PAUSE = 81; public static final int DVD_PLAY = 82; public static final int DVD_REWIND = 83; public static final int DVD_FORWARD = 84; public static final int DVD_ORDER_CYCLE = 85; public static final int DVD_SHUFFLE = 86; public static final int DVD_SINGLE_CYCLE = 87; public static final int DVD_SCAN_CONTROL = 88; // 车身控制 public static final int DORMER = 90; public static final int TRUNK = 91; public static final int NEAR_LIGHTS = 92; public static final int FAR_LIGHTS = 93; public static final int FOG_LIGHTS = 94; public static final int FRONT_FOG_LIGHTS = 95; public static final int BEHIND_FOG_LIGHTS = 96; public static final int GALLERY_LIGHTS = 97; public static final int WARNING_LIGHTS = 98; public static final int CAR_WINDOWS = 99; public static final int ON = 100; public static final int OFF = 101; // 飞歌应用管理 public static final int NAVI = 110; public static final int DVD = 111; public static final int RADIO = 112; public static final int MEDIA = 113; public static final int BLUETOOTH = 114; public static final int SYNC = 115; public static final int DRIVING_RECORD = 116; public static final int TV = 117; public static final int TIRE = 118; public static final int BLUETOOTH_MUSIC = 119; public static final int SYSTEM_SET = 120; public static final int ENTERTAINMENT = 121; public static final int AUXI_INPUT = 122; public static final int IPOD = 123; public static final int AIR_CINDITION = 124; public static final int CAR_INFO = 125; // 空调控制 public static final int INC_TEMP = 130; public static final int DEC_TEMP = 131; public static final int CRYOGEN = 132; public static final int HEATING = 133; public static final int DEHUMIDIFICATION = 134; public static final int DEFROST = 135; public static final int UP_BLOW = 136; public static final int DOWN_BLOW = 137; public static final int SWEPT = 138; public static final int MAX_WIND = 139; public static final int MIN_WIND = 140; public static final int HIGH_WIND = 141; public static final int LOW_WIND = 142; public static final int PLUS_WIND = 143; public static final int MINUS_WIND = 144; // 模拟面板KEY功能控制 public static final int PANEL_PWR_VO = 149; public static final int PANEL_VOL_MUTE = 150; public static final int PANEL_VOL_OPEN = 151; public static final int PANEL_VOL_INC = 152; public static final int PANEL_VOL_DEC = 153; public static final int PANEL_PREVIOUS = 160; public static final int PANEL_NEXT = 161; public static final int PANEL_SEEK = 154; public static final int PANEL_NAVI = 155; public static final int PANEL_TUNE_AUDIO = 156; public static final int PANEL_DVD = 157; // 降噪模块模块切换 public static final int NOISE_REDUCTION = 170;// 降噪 public static final int ECHO_CANCEL = 171;// 回声消除 public static final int WAKE = 172;// 唤醒 public static final int DIRECT_RECORD = 173;// 关闭所用功能直接录音 }
{ "content_hash": "7969992351492a4f1b62100816572c37", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 76, "avg_line_length": 38.32335329341317, "alnum_prop": 0.734375, "repo_name": "a7859696/AWidgetMy", "id": "4e1a84f0853f88c60b809457ab78a2b953c987ad", "size": "6678", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/cn/flyaudio/widgetswitch/alltools/FlyConstant.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "159855" }, { "name": "Makefile", "bytes": "559" } ], "symlink_target": "" }