Dataset Preview
Duplicate
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code:   DatasetGenerationError
Exception:    ArrowInvalid
Message:      JSON parse error: Missing a closing quotation mark in string. in row 24
Traceback:    Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 145, in _generate_tables
                  dataset = json.load(f)
                File "/usr/local/lib/python3.9/json/__init__.py", line 293, in load
                  return loads(fp.read(),
                File "/usr/local/lib/python3.9/json/__init__.py", line 346, in loads
                  return _default_decoder.decode(s)
                File "/usr/local/lib/python3.9/json/decoder.py", line 340, in decode
                  raise JSONDecodeError("Extra data", s, end)
              json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 1451)
              
              During handling of the above exception, another exception occurred:
              
              Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1995, in _prepare_split_single
                  for _, table in generator:
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 148, in _generate_tables
                  raise e
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 122, in _generate_tables
                  pa_table = paj.read_json(
                File "pyarrow/_json.pyx", line 308, in pyarrow._json.read_json
                File "pyarrow/error.pxi", line 154, in pyarrow.lib.pyarrow_internal_check_status
                File "pyarrow/error.pxi", line 91, in pyarrow.lib.check_status
              pyarrow.lib.ArrowInvalid: JSON parse error: Missing a closing quotation mark in string. in row 24
              
              The above exception was the direct cause of the following exception:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1529, in compute_config_parquet_and_info_response
                  parquet_operations = convert_to_parquet(builder)
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1154, in convert_to_parquet
                  builder.download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1027, in download_and_prepare
                  self._download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1122, in _download_and_prepare
                  self._prepare_split(split_generator, **prepare_split_kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1882, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2038, in _prepare_split_single
                  raise DatasetGenerationError("An error occurred while generating the dataset") from e
              datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

text
string
meta
dict
<?php /** Zend_Dojo_Form_Decorator_DijitContainer */ // require_once 'Zend/Dojo/Form/Decorator/DijitContainer.php'; /** * ContentPane * * Render a dijit ContentPane * * @uses Zend_Dojo_Form_Decorator_DijitContainer * @package Zend_Dojo * @subpackage Form_Decorator * @copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ class Zend_Dojo_Form_Decorator_ContentPane extends Zend_Dojo_Form_Decorator_DijitContainer { /** * View helper * @var string */ protected $_helper = 'ContentPane'; }
{ "content_hash": "62739719d3c401c27c81fbf0b1461d87", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 90, "avg_line_length": 25.115384615384617, "alnum_prop": 0.6707503828483921, "repo_name": "ProfilerTeam/Profiler", "id": "d2c1a1a282972c4770c5a77139405f32b4d25abe", "size": "1314", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "protected/vendors/Zend/Dojo/Form/Decorator/ContentPane.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "427" }, { "name": "Batchfile", "bytes": "431" }, { "name": "CSS", "bytes": "326435" }, { "name": "HTML", "bytes": "917" }, { "name": "JavaScript", "bytes": "581447" }, { "name": "PHP", "bytes": "7311409" }, { "name": "Shell", "bytes": "41" } ] }
<eml xmlns:ns0="eml://ecoinformatics.org/eml-2.1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" packageId="knb-lter-europe-deims.13167.13461" system="knb-lter-europe-deims" xsi:schemaLocation="eml://ecoinformatics.org/eml-2.1.1 https://code.ecoinformatics.org/code/eml/tags/RELEASE_EML_2_1_1/eml.xsd"> <access authSystem="knb" order="allowFirst" scope="document"> <allow> <principal>uid=Hungary,o=LTER-Europe,dc=ecoinformatics,dc=org</principal> <permission>all</permission> </allow> <allow> <principal>public</principal> <permission>read</permission> </allow> </access> <dataset id="knb-lter-europe-deims.13167.13461" system="knb-lter-europe-deims"> <alternateIdentifier>752eb03a-92fa-11e2-b534-005056ab003f</alternateIdentifier> <title>Sikfokut LTER (Hungary) - vascular plant species list - EnvEurope A5</title> <creator> <individualName> <givenName>Ilona</givenName> <surName>Meszaros</surName> </individualName> <organizationName>aaa LTER</organizationName> <electronicMailAddress>immeszaros@unideb.hu</electronicMailAddress> </creator> <creator> <individualName> <givenName>Maria</givenName> <surName>Papp</surName> </individualName> <organizationName>University of Debrecen</organizationName> <electronicMailAddress>papp.maria@science.unideb.hu</electronicMailAddress> </creator> <creator> <individualName> <givenName>Imre</givenName> <surName>Karasz</surName> </individualName> <organizationName>Eszterh&#225;zy Karoly College, Eger</organizationName> <electronicMailAddress>karasz@ektf.hu</electronicMailAddress> </creator> <creator> <individualName> <givenName>Tamas</givenName> <surName>Misik</surName> </individualName> <organizationName>Eszterh&#225;zy Karoly College, Eger</organizationName> <electronicMailAddress>misikt@ektf.hu</electronicMailAddress> </creator> <creator> <individualName> <givenName>Viktor</givenName> <surName>Ol&#225;h</surName> </individualName> <organizationName>University of Debrecen, Faculty of Science and Technology, Dpt. Botany</organizationName> <address> <deliveryPoint>Egyetem t&#233;r 1.</deliveryPoint> <city>Debrecen</city> <country>Hungary</country> </address> <electronicMailAddress>olahviktor@gmail.com</electronicMailAddress> </creator> <metadataProvider> <individualName> <givenName>Ilona</givenName> <surName>Meszaros</surName> </individualName> <organizationName>aaa LTER</organizationName> <electronicMailAddress>immeszaros@unideb.hu</electronicMailAddress> </metadataProvider> <metadataProvider> <individualName> <givenName>Tamas</givenName> <surName>Misik</surName> </individualName> <organizationName>Eszterh&#225;zy Karoly College, Eger</organizationName> <electronicMailAddress>misikt@ektf.hu</electronicMailAddress> </metadataProvider> <metadataProvider> <individualName> <givenName>Imre</givenName> <surName>Karasz</surName> </individualName> <organizationName>Eszterh&#225;zy Karoly College, Eger</organizationName> <electronicMailAddress>karasz@ektf.hu</electronicMailAddress> </metadataProvider> <metadataProvider> <individualName> <givenName>Maria</givenName> <surName>Papp</surName> </individualName> <organizationName>University of Debrecen</organizationName> <electronicMailAddress>papp.maria@science.unideb.hu</electronicMailAddress> </metadataProvider> <metadataProvider> <individualName> <givenName>Viktor</givenName> <surName>Ol&#225;h</surName> </individualName> <organizationName>University of Debrecen, Faculty of Science and Technology, Dpt. Botany</organizationName> <address> <deliveryPoint>Egyetem t&#233;r 1.</deliveryPoint> <city>Debrecen</city> <country>Hungary</country> </address> <electronicMailAddress>olahviktor@gmail.com</electronicMailAddress> </metadataProvider> <pubDate>2013-03-22</pubDate> <language>eng</language><abstract> <section> <para>This dataset contains the vascular plant species list of Sikfokut LTER site (Hungary).The list was composed of the results of a Multisite Experiment in 2007 and 2008, tree and shrub inventory in 2012, and herb layer assessment in 2012, respectively.Tree layer was assessed by M&#233;sz&#225;ros Ilona.Shrub layer was assessed by Misik Tam&#225;s and K&#225;r&#225;sz Imre.Herb layer was assessed by Papp M&#225;ria.</para> </section> </abstract> <keywordSet> <keyword>LTER Site</keyword> <keyword>Species list</keyword> <keywordThesaurus>EnvEurope Thesaurus;2012-08-13;version 3.0;http://vocabs.lter-europe.net/EnvThes3.html</keywordThesaurus> </keywordSet> <additionalInfo> <section> <title>Metadata date</title> <para>2013-04-09 00:00:00</para> </section> <section> <title>Dataset access and use constraints</title> <para>Principal:EnvEurope (LTER-Europe) has granted a permission of type:Other restrictions according to rules defined in itellectual rights</para> </section> </additionalInfo> <intellectualRights> <section> <para>Co-authorship on publications resulting from use of the dataset</para> </section> <section> <para>The opportunity to collaborate on the project using the dataset</para> </section> </intellectualRights> <distribution> <online> <url function="information">ftp://ftp.umweltbundesamt.at/KnownUsers/2253_2/EnvEurope_DataCollection/2012/</url> </online> </distribution> <coverage> <geographicCoverage> <geographicDescription> Sikfokut LTER</geographicDescription> <boundingCoordinates> <westBoundingCoordinate>20.44041</westBoundingCoordinate> <eastBoundingCoordinate>20.45191</eastBoundingCoordinate> <northBoundingCoordinate>47.93130</northBoundingCoordinate> <southBoundingCoordinate>47.92445</southBoundingCoordinate> <boundingAltitudes> <altitudeMinimum>275</altitudeMinimum> <altitudeMaximum>330</altitudeMaximum> <altitudeUnits>meter</altitudeUnits> </boundingAltitudes> </boundingCoordinates> </geographicCoverage> <temporalCoverage> <rangeOfDates> <beginDate> <calendarDate>2007-07-01</calendarDate> </beginDate> <endDate> <calendarDate>2013-03-22</calendarDate> </endDate> </rangeOfDates> </temporalCoverage> </coverage> <contact> <individualName> <givenName>Ilona</givenName> <surName>Meszaros</surName> </individualName> <organizationName>aaa LTER</organizationName> <electronicMailAddress>immeszaros@unideb.hu</electronicMailAddress> </contact> <contact> <individualName> <givenName>Maria</givenName> <surName>Papp</surName> </individualName> <organizationName>University of Debrecen</organizationName> <electronicMailAddress>papp.maria@science.unideb.hu</electronicMailAddress> </contact> <contact> <individualName> <givenName>Imre</givenName> <surName>Karasz</surName> </individualName> <organizationName>Eszterh&#225;zy Karoly College, Eger</organizationName> <electronicMailAddress>karasz@ektf.hu</electronicMailAddress> </contact> <contact> <individualName> <givenName>Tamas</givenName> <surName>Misik</surName> </individualName> <organizationName>Eszterh&#225;zy Karoly College, Eger</organizationName> <electronicMailAddress>misikt@ektf.hu</electronicMailAddress> </contact> <contact> <individualName> <givenName>Viktor</givenName> <surName>Ol&#225;h</surName> </individualName> <organizationName>University of Debrecen, Faculty of Science and Technology, Dpt. Botany</organizationName> <address> <deliveryPoint>Egyetem t&#233;r 1.</deliveryPoint> <city>Debrecen</city> <country>Hungary</country> </address> <electronicMailAddress>olahviktor@gmail.com</electronicMailAddress> </contact> <methods> <methodStep> <description> <section> <para> <literalLayout>Vascular plants' species list was composed using results of a Multisite Experiment (MSE) in summer in 2007 and 2008, and tree and shrub inventory of the site's 1 ha permanent plot in 2012, respectively. Herb layer was assessed using 20 0.5x2m rectangular plots.</literalLayout> </para> </section> </description> <instrumentation>Permanent vegetation plots.</instrumentation> </methodStep> <sampling> <studyExtent> <description> <section> <para>Most vegetation assessments were done in the 1 ha permanent plot of Sikfokut LTER site which has been used since 1972 for similar purposes. Canopy trees were assessed by Ilona M&#233;sz&#225;ros and Viktor Ol&#225;h. Data on shrub layer was provided by Imre K&#225;r&#225;sz and Tam&#225;s Misik. Data on herb layer was provided by M&#225;ria Papp. Further species were added to the list according to the species list composed during a Multisite Experiment in 2007-2008. This experiment was conducted within the borders of the site, ~300 m from the permanent 1 ha plot and used 20 0.5x1m plots.</para> </section> </description> </studyExtent> <samplingDescription>continual</samplingDescription> </sampling> </methods> </dataset> </eml>
{ "content_hash": "7598b218d0c9fda747165afc74b8bc42", "timestamp": "", "source": "github", "line_count": 236, "max_line_length": 428, "avg_line_length": 36.22457627118644, "alnum_prop": 0.7977541232892736, "repo_name": "NCEAS/metadig", "id": "383bda6fd2638a353ac6ab424b812eab85e371fd", "size": "8549", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "collections/DataOne/LTER_EUROPE/EML/xml/03871-metadata.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "2361" }, { "name": "Python", "bytes": "42696" }, { "name": "Shell", "bytes": "5798" }, { "name": "XSLT", "bytes": "207495" } ] }
int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([JBAppDelegate class])); } }
{ "content_hash": "12b8cf8b15f1e9df5689347926fc00ef", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 92, "avg_line_length": 26.666666666666668, "alnum_prop": 0.6625, "repo_name": "alonecuzzo/MTDelay", "id": "1ee32ab299af415904b5021a4b5f78c2d9eae374", "size": "340", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MTDelay/MTDelay/main.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "539" }, { "name": "Objective-C", "bytes": "82420" }, { "name": "Ruby", "bytes": "183" }, { "name": "Shell", "bytes": "3552" } ] }
<?php namespace Drupal\menu_ui\Tests; use Drupal\block\Entity\Block; use Drupal\Component\Serialization\Json; use Drupal\Component\Utility\Unicode; use Drupal\Core\Menu\MenuLinkInterface; use Drupal\Core\Url; use Drupal\menu_link_content\Entity\MenuLinkContent; use Drupal\system\Entity\Menu; use Drupal\node\Entity\Node; /** * Add a custom menu, add menu links to the custom menu and Tools menu, check * their data, and delete them using the UI. * * @group menu_ui */ class MenuTest extends MenuWebTestBase { /** * Modules to enable. * * @var array */ public static $modules = array('node', 'block', 'contextual', 'help', 'path', 'test_page_test'); /** * A user with administration rights. * * @var \Drupal\user\UserInterface */ protected $adminUser; /** * An authenticated user. * * @var \Drupal\user\UserInterface */ protected $authenticatedUser; /** * Array of placed menu blocks keyed by block ID. * * @var array */ protected $blockPlacements; /** * A test menu. * * @var \Drupal\system\Entity\Menu */ protected $menu; /** * An array of test menu links. * * @var \Drupal\menu_link_content\MenuLinkContentInterface[] */ protected $items; protected function setUp() { parent::setUp(); $this->drupalPlaceBlock('page_title_block'); $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article')); // Create users. $this->adminUser = $this->drupalCreateUser(array('access administration pages', 'administer blocks', 'administer menu', 'create article content')); $this->authenticatedUser = $this->drupalCreateUser(array()); } /** * Tests menu functionality using the admin and user interfaces. */ function testMenu() { // Log in the user. $this->drupalLogin($this->adminUser); $this->items = array(); $this->menu = $this->addCustomMenu(); $this->doMenuTests(); $this->doTestMenuBlock(); $this->addInvalidMenuLink(); $this->addCustomMenuCRUD(); // Verify that the menu links rebuild is idempotent and leaves the same // number of links in the table. /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */ $menu_link_manager = \Drupal::service('plugin.manager.menu.link'); $before_count = $menu_link_manager->countMenuLinks(NULL); $menu_link_manager->rebuild(); $after_count = $menu_link_manager->countMenuLinks(NULL); $this->assertIdentical($before_count, $after_count, 'MenuLinkManager::rebuild() does not add more links'); // Do standard user tests. // Log in the user. $this->drupalLogin($this->authenticatedUser); $this->verifyAccess(403); foreach ($this->items as $item) { // Menu link URIs are stored as 'internal:/node/$nid'. $node = Node::load(str_replace('internal:/node/', '', $item->link->uri)); $this->verifyMenuLink($item, $node); } // Log in the administrator. $this->drupalLogin($this->adminUser); // Verify delete link exists and reset link does not exist. $this->drupalGet('admin/structure/menu/manage/' . $this->menu->id()); $this->assertLinkByHref(Url::fromRoute('entity.menu_link_content.delete_form', ['menu_link_content' => $this->items[0]->id()])->toString()); $this->assertNoLinkByHref(Url::fromRoute('menu_ui.link_reset', ['menu_link_plugin' => $this->items[0]->getPluginId()])->toString()); // Check delete and reset access. $this->drupalGet('admin/structure/menu/item/' . $this->items[0]->id() . '/delete'); $this->assertResponse(200); $this->drupalGet('admin/structure/menu/link/' . $this->items[0]->getPluginId() . '/reset'); $this->assertResponse(403); // Delete menu links. foreach ($this->items as $item) { $this->deleteMenuLink($item); } // Delete custom menu. $this->deleteCustomMenu(); // Modify and reset a standard menu link. $instance = $this->getStandardMenuLink(); $old_weight = $instance->getWeight(); // Edit the static menu link. $edit = array(); $edit['weight'] = 10; $id = $instance->getPluginId(); $this->drupalPostForm("admin/structure/menu/link/$id/edit", $edit, t('Save')); $this->assertResponse(200); $this->assertText('The menu link has been saved.'); $menu_link_manager->resetDefinitions(); $instance = $menu_link_manager->createInstance($instance->getPluginId()); $this->assertEqual($edit['weight'], $instance->getWeight(), 'Saving an existing link updates the weight.'); $this->resetMenuLink($instance, $old_weight); } /** * Adds a custom menu using CRUD functions. */ function addCustomMenuCRUD() { // Add a new custom menu. $menu_name = substr(hash('sha256', $this->randomMachineName(16)), 0, MENU_MAX_MENU_NAME_LENGTH_UI); $label = $this->randomMachineName(16); $menu = Menu::create(array( 'id' => $menu_name, 'label' => $label, 'description' => 'Description text', )); $menu->save(); // Assert the new menu. $this->drupalGet('admin/structure/menu/manage/' . $menu_name); $this->assertRaw($label, 'Custom menu was added.'); // Edit the menu. $new_label = $this->randomMachineName(16); $menu->set('label', $new_label); $menu->save(); $this->drupalGet('admin/structure/menu/manage/' . $menu_name); $this->assertRaw($new_label, 'Custom menu was edited.'); } /** * Creates a custom menu. * * @return \Drupal\system\Entity\Menu * The custom menu that has been created. */ function addCustomMenu() { // Try adding a menu using a menu_name that is too long. $this->drupalGet('admin/structure/menu/add'); $menu_name = substr(hash('sha256', $this->randomMachineName(16)), 0, MENU_MAX_MENU_NAME_LENGTH_UI + 1); $label = $this->randomMachineName(16); $edit = array( 'id' => $menu_name, 'description' => '', 'label' => $label, ); $this->drupalPostForm('admin/structure/menu/add', $edit, t('Save')); // Verify that using a menu_name that is too long results in a validation // message. $this->assertRaw(t('@name cannot be longer than %max characters but is currently %length characters long.', array( '@name' => t('Menu name'), '%max' => MENU_MAX_MENU_NAME_LENGTH_UI, '%length' => Unicode::strlen($menu_name), ))); // Change the menu_name so it no longer exceeds the maximum length. $menu_name = substr(hash('sha256', $this->randomMachineName(16)), 0, MENU_MAX_MENU_NAME_LENGTH_UI); $edit['id'] = $menu_name; $this->drupalPostForm('admin/structure/menu/add', $edit, t('Save')); // Verify that no validation error is given for menu_name length. $this->assertNoRaw(t('@name cannot be longer than %max characters but is currently %length characters long.', array( '@name' => t('Menu name'), '%max' => MENU_MAX_MENU_NAME_LENGTH_UI, '%length' => Unicode::strlen($menu_name), ))); // Verify that the confirmation message is displayed. $this->assertRaw(t('Menu %label has been added.', array('%label' => $label))); $this->drupalGet('admin/structure/menu'); $this->assertText($label, 'Menu created'); // Confirm that the custom menu block is available. $this->drupalGet('admin/structure/block/list/' . $this->config('system.theme')->get('default')); $this->clickLinkPartialName('Place block'); $this->assertText($label); // Enable the block. $block = $this->drupalPlaceBlock('system_menu_block:' . $menu_name); $this->blockPlacements[$menu_name] = $block->id(); return Menu::load($menu_name); } /** * Deletes the locally stored custom menu. * * This deletes the custom menu that is stored in $this->menu and performs * tests on the menu delete user interface. */ function deleteCustomMenu() { $menu_name = $this->menu->id(); $label = $this->menu->label(); // Delete custom menu. $this->drupalPostForm("admin/structure/menu/manage/$menu_name/delete", array(), t('Delete')); $this->assertResponse(200); $this->assertRaw(t('The menu %title has been deleted.', array('%title' => $label)), 'Custom menu was deleted'); $this->assertNull(Menu::load($menu_name), 'Custom menu was deleted'); // Test if all menu links associated with the menu were removed from // database. $result = entity_load_multiple_by_properties('menu_link_content', array('menu_name' => $menu_name)); $this->assertFalse($result, 'All menu links associated with the custom menu were deleted.'); // Make sure there's no delete button on system menus. $this->drupalGet('admin/structure/menu/manage/main'); $this->assertNoRaw('edit-delete', 'The delete button was not found'); // Try to delete the main menu. $this->drupalGet('admin/structure/menu/manage/main/delete'); $this->assertText(t('You are not authorized to access this page.')); } /** * Tests menu functionality. */ function doMenuTests() { $menu_name = $this->menu->id(); // Test the 'Add link' local action. $this->drupalGet(Url::fromRoute('entity.menu.edit_form', ['menu' => $menu_name])); $this->clickLink(t('Add link')); $link_title = $this->randomString(); $this->drupalPostForm(NULL, array('link[0][uri]' => '/', 'title[0][value]' => $link_title), t('Save')); $this->assertUrl(Url::fromRoute('entity.menu.edit_form', ['menu' => $menu_name])); // Test the 'Edit' operation. $this->clickLink(t('Edit')); $this->assertFieldByName('title[0][value]', $link_title); $link_title = $this->randomString(); $this->drupalPostForm(NULL, array('title[0][value]' => $link_title), t('Save')); $this->assertUrl(Url::fromRoute('entity.menu.edit_form', ['menu' => $menu_name])); // Test the 'Delete' operation. $this->clickLink(t('Delete')); $this->assertRaw(t('Are you sure you want to delete the custom menu link %item?', array('%item' => $link_title))); $this->drupalPostForm(NULL, array(), t('Delete')); $this->assertUrl(Url::fromRoute('entity.menu.edit_form', ['menu' => $menu_name])); // Add nodes to use as links for menu links. $node1 = $this->drupalCreateNode(array('type' => 'article')); $node2 = $this->drupalCreateNode(array('type' => 'article')); $node3 = $this->drupalCreateNode(array('type' => 'article')); $node4 = $this->drupalCreateNode(array('type' => 'article')); // Create a node with an alias. $node5 = $this->drupalCreateNode(array( 'type' => 'article', 'path' => array( 'alias' => '/node5', ), )); // Verify add link button. $this->drupalGet('admin/structure/menu'); $this->assertLinkByHref('admin/structure/menu/manage/' . $menu_name . '/add', 0, "The add menu link button URL is correct"); // Verify form defaults. $this->doMenuLinkFormDefaultsTest(); // Add menu links. $item1 = $this->addMenuLink('', '/node/' . $node1->id(), $menu_name, TRUE); $item2 = $this->addMenuLink($item1->getPluginId(), '/node/' . $node2->id(), $menu_name, FALSE); $item3 = $this->addMenuLink($item2->getPluginId(), '/node/' . $node3->id(), $menu_name); // Hierarchy // <$menu_name> // - item1 // -- item2 // --- item3 $this->assertMenuLink($item1->getPluginId(), array( 'children' => array($item2->getPluginId(), $item3->getPluginId()), 'parents' => array($item1->getPluginId()), // We assert the language code here to make sure that the language // selection element degrades gracefully without the Language module. 'langcode' => 'en', )); $this->assertMenuLink($item2->getPluginId(), array( 'children' => array($item3->getPluginId()), 'parents' => array($item2->getPluginId(), $item1->getPluginId()), // See above. 'langcode' => 'en', )); $this->assertMenuLink($item3->getPluginId(), array( 'children' => array(), 'parents' => array($item3->getPluginId(), $item2->getPluginId(), $item1->getPluginId()), // See above. 'langcode' => 'en', )); // Verify menu links. $this->verifyMenuLink($item1, $node1); $this->verifyMenuLink($item2, $node2, $item1, $node1); $this->verifyMenuLink($item3, $node3, $item2, $node2); // Add more menu links. $item4 = $this->addMenuLink('', '/node/' . $node4->id(), $menu_name); $item5 = $this->addMenuLink($item4->getPluginId(), '/node/' . $node5->id(), $menu_name); // Create a menu link pointing to an alias. $item6 = $this->addMenuLink($item4->getPluginId(), '/node5', $menu_name, TRUE, '0'); // Hierarchy // <$menu_name> // - item1 // -- item2 // --- item3 // - item4 // -- item5 // -- item6 $this->assertMenuLink($item4->getPluginId(), array( 'children' => array($item5->getPluginId(), $item6->getPluginId()), 'parents' => array($item4->getPluginId()), // See above. 'langcode' => 'en', )); $this->assertMenuLink($item5->getPluginId(), array( 'children' => array(), 'parents' => array($item5->getPluginId(), $item4->getPluginId()), 'langcode' => 'en', )); $this->assertMenuLink($item6->getPluginId(), array( 'children' => array(), 'parents' => array($item6->getPluginId(), $item4->getPluginId()), 'route_name' => 'entity.node.canonical', 'route_parameters' => array('node' => $node5->id()), 'url' => '', // See above. 'langcode' => 'en', )); // Modify menu links. $this->modifyMenuLink($item1); $this->modifyMenuLink($item2); // Toggle menu links. $this->toggleMenuLink($item1); $this->toggleMenuLink($item2); // Move link and verify that descendants are updated. $this->moveMenuLink($item2, $item5->getPluginId(), $menu_name); // Hierarchy // <$menu_name> // - item1 // - item4 // -- item5 // --- item2 // ---- item3 // -- item6 $this->assertMenuLink($item1->getPluginId(), array( 'children' => array(), 'parents' => array($item1->getPluginId()), // See above. 'langcode' => 'en', )); $this->assertMenuLink($item4->getPluginId(), array( 'children' => array($item5->getPluginId(), $item6->getPluginId(), $item2->getPluginId(), $item3->getPluginId()), 'parents' => array($item4->getPluginId()), // See above. 'langcode' => 'en', )); $this->assertMenuLink($item5->getPluginId(), array( 'children' => array($item2->getPluginId(), $item3->getPluginId()), 'parents' => array($item5->getPluginId(), $item4->getPluginId()), // See above. 'langcode' => 'en', )); $this->assertMenuLink($item2->getPluginId(), array( 'children' => array($item3->getPluginId()), 'parents' => array($item2->getPluginId(), $item5->getPluginId(), $item4->getPluginId()), // See above. 'langcode' => 'en', )); $this->assertMenuLink($item3->getPluginId(), array( 'children' => array(), 'parents' => array($item3->getPluginId(), $item2->getPluginId(), $item5->getPluginId(), $item4->getPluginId()), // See above. 'langcode' => 'en', )); // Add 102 menu links with increasing weights, then make sure the last-added // item's weight doesn't get changed because of the old hardcoded delta=50. $items = array(); for ($i = -50; $i <= 51; $i++) { $items[$i] = $this->addMenuLink('', '/node/' . $node1->id(), $menu_name, TRUE, strval($i)); } $this->assertMenuLink($items[51]->getPluginId(), array('weight' => '51')); // Disable a link and then re-enable the link via the overview form. $this->disableMenuLink($item1); $edit = array(); $edit['links[menu_plugin_id:' . $item1->getPluginId() . '][enabled]'] = TRUE; $this->drupalPostForm('admin/structure/menu/manage/' . $item1->getMenuName(), $edit, t('Save')); // Mark item2, item4 and item5 as expanded. // This is done in order to show them on the frontpage. $item2->expanded->value = 1; $item2->save(); $item4->expanded->value = 1; $item4->save(); $item5->expanded->value = 1; $item5->save(); // Verify in the database. $this->assertMenuLink($item1->getPluginId(), array('enabled' => 1)); // Add an external link. $item7 = $this->addMenuLink('', 'https://www.drupal.org', $menu_name); $this->assertMenuLink($item7->getPluginId(), array('url' => 'https://www.drupal.org')); // Add <front> menu item. $item8 = $this->addMenuLink('', '/', $menu_name); $this->assertMenuLink($item8->getPluginId(), array('route_name' => '<front>')); $this->drupalGet(''); $this->assertResponse(200); // Make sure we get routed correctly. $this->clickLink($item8->getTitle()); $this->assertResponse(200); // Check invalid menu link parents. $this->checkInvalidParentMenuLinks(); // Save menu links for later tests. $this->items[] = $item1; $this->items[] = $item2; } /** * Ensures that the proper default values are set when adding a menu link */ protected function doMenuLinkFormDefaultsTest() { $this->drupalGet("admin/structure/menu/manage/tools/add"); $this->assertResponse(200); $this->assertFieldByName('title[0][value]', ''); $this->assertFieldByName('link[0][uri]', ''); $this->assertNoFieldChecked('edit-expanded-value'); $this->assertFieldChecked('edit-enabled-value'); $this->assertFieldByName('description[0][value]', ''); $this->assertFieldByName('weight[0][value]', 0); } /** * Adds and removes a menu link with a query string and fragment. */ function testMenuQueryAndFragment() { $this->drupalLogin($this->adminUser); // Make a path with query and fragment on. $path = '/test-page?arg1=value1&arg2=value2'; $item = $this->addMenuLink('', $path); $this->drupalGet('admin/structure/menu/item/' . $item->id() . '/edit'); $this->assertFieldByName('link[0][uri]', $path, 'Path is found with both query and fragment.'); // Now change the path to something without query and fragment. $path = '/test-page'; $this->drupalPostForm('admin/structure/menu/item/' . $item->id() . '/edit', array('link[0][uri]' => $path), t('Save')); $this->drupalGet('admin/structure/menu/item/' . $item->id() . '/edit'); $this->assertFieldByName('link[0][uri]', $path, 'Path no longer has query or fragment.'); // Use <front>#fragment and ensure that saving it does not lose its content. $path = '<front>?arg1=value#fragment'; $item = $this->addMenuLink('', $path); $this->drupalGet('admin/structure/menu/item/' . $item->id() . '/edit'); $this->assertFieldByName('link[0][uri]', $path, 'Path is found with both query and fragment.'); $this->drupalPostForm('admin/structure/menu/item/' . $item->id() . '/edit', array(), t('Save')); $this->drupalGet('admin/structure/menu/item/' . $item->id() . '/edit'); $this->assertFieldByName('link[0][uri]', $path, 'Path is found with both query and fragment.'); } /** * Tests renaming the built-in menu. */ function testSystemMenuRename() { $this->drupalLogin($this->adminUser); $edit = array( 'label' => $this->randomMachineName(16), ); $this->drupalPostForm('admin/structure/menu/manage/main', $edit, t('Save')); // Make sure menu shows up with new name in block addition. $default_theme = $this->config('system.theme')->get('default'); $this->drupalget('admin/structure/block/list/' . $default_theme); $this->clickLinkPartialName('Place block'); $this->assertText($edit['label']); } /** * Tests that menu items pointing to unpublished nodes are editable. */ function testUnpublishedNodeMenuItem() { $this->drupalLogin($this->drupalCreateUser(array('access administration pages', 'administer blocks', 'administer menu', 'create article content', 'bypass node access'))); // Create an unpublished node. $node = $this->drupalCreateNode(array( 'type' => 'article', 'status' => NODE_NOT_PUBLISHED, )); $item = $this->addMenuLink('', '/node/' . $node->id()); $this->modifyMenuLink($item); // Test that a user with 'administer menu' but without 'bypass node access' // cannot see the menu item. $this->drupalLogout(); $this->drupalLogin($this->adminUser); $this->drupalGet('admin/structure/menu/manage/' . $item->getMenuName()); $this->assertNoText($item->getTitle(), "Menu link pointing to unpublished node is only visible to users with 'bypass node access' permission"); // The cache contexts associated with the (in)accessible menu links are // bubbled. See DefaultMenuLinkTreeManipulators::menuLinkCheckAccess(). $this->assertCacheContext('user.permissions'); } /** * Tests the contextual links on a menu block. */ public function testBlockContextualLinks() { $this->drupalLogin($this->drupalCreateUser(array('administer menu', 'access contextual links', 'administer blocks'))); $custom_menu = $this->addCustomMenu(); $this->addMenuLink('', '/', $custom_menu->id()); $block = $this->drupalPlaceBlock('system_menu_block:' . $custom_menu->id(), array('label' => 'Custom menu', 'provider' => 'system')); $this->drupalGet('test-page'); $id = 'block:block=' . $block->id() . ':langcode=en|menu:menu=' . $custom_menu->id() . ':langcode=en'; // @see \Drupal\contextual\Tests\ContextualDynamicContextTest:assertContextualLinkPlaceHolder() $this->assertRaw('<div data-contextual-id="' . $id . '"></div>', format_string('Contextual link placeholder with id @id exists.', array('@id' => $id))); // Get server-rendered contextual links. // @see \Drupal\contextual\Tests\ContextualDynamicContextTest:renderContextualLinks() $post = array('ids[0]' => $id); $response = $this->drupalPost('contextual/render', 'application/json', $post, array('query' => array('destination' => 'test-page'))); $this->assertResponse(200); $json = Json::decode($response); $this->assertIdentical($json[$id], '<ul class="contextual-links"><li class="block-configure"><a href="' . base_path() . 'admin/structure/block/manage/' . $block->id() . '">Configure block</a></li><li class="entitymenuedit-form"><a href="' . base_path() . 'admin/structure/menu/manage/' . $custom_menu->id() . '">Edit menu</a></li></ul>'); } /** * Adds a menu link using the UI. * * @param string $parent * Optional parent menu link id. * @param string $path * The path to enter on the form. Defaults to the front page. * @param string $menu_name * Menu name. Defaults to 'tools'. * @param bool $expanded * Whether or not this menu link is expanded. Setting this to TRUE should * test whether it works when we do the authenticatedUser tests. Defaults * to FALSE. * @param string $weight * Menu weight. Defaults to 0. * * @return \Drupal\menu_link_content\Entity\MenuLinkContent * A menu link entity. */ function addMenuLink($parent = '', $path = '/', $menu_name = 'tools', $expanded = FALSE, $weight = '0') { // View add menu link page. $this->drupalGet("admin/structure/menu/manage/$menu_name/add"); $this->assertResponse(200); $title = '!link_' . $this->randomMachineName(16); $edit = array( 'link[0][uri]' => $path, 'title[0][value]' => $title, 'description[0][value]' => '', 'enabled[value]' => 1, 'expanded[value]' => $expanded, 'menu_parent' => $menu_name . ':' . $parent, 'weight[0][value]' => $weight, ); // Add menu link. $this->drupalPostForm(NULL, $edit, t('Save')); $this->assertResponse(200); $this->assertText('The menu link has been saved.'); $menu_links = entity_load_multiple_by_properties('menu_link_content', array('title' => $title)); $menu_link = reset($menu_links); $this->assertTrue($menu_link, 'Menu link was found in database.'); $this->assertMenuLink($menu_link->getPluginId(), array('menu_name' => $menu_name, 'children' => array(), 'parent' => $parent)); return $menu_link; } /** * Attempts to add menu link with invalid path or no access permission. */ function addInvalidMenuLink() { foreach (array('access' => '/admin/people/permissions') as $type => $link_path) { $edit = array( 'link[0][uri]' => $link_path, 'title[0][value]' => 'title', ); $this->drupalPostForm("admin/structure/menu/manage/{$this->menu->id()}/add", $edit, t('Save')); $this->assertRaw(t("The path '@link_path' is inaccessible.", array('@link_path' => $link_path)), 'Menu link was not created'); } } /** * Tests that parent options are limited by depth when adding menu links. */ function checkInvalidParentMenuLinks() { $last_link = NULL; $created_links = array(); // Get the max depth of the tree. $menu_link_tree = \Drupal::service('menu.link_tree'); $max_depth = $menu_link_tree->maxDepth(); // Create a maximum number of menu links, each a child of the previous. for ($i = 0; $i <= $max_depth - 1; $i++) { $parent = $last_link ? 'tools:' . $last_link->getPluginId() : 'tools:'; $title = 'title' . $i; $edit = array( 'link[0][uri]' => '/', 'title[0][value]' => $title, 'menu_parent' => $parent, 'description[0][value]' => '', 'enabled[value]' => 1, 'expanded[value]' => FALSE, 'weight[0][value]' => '0', ); $this->drupalPostForm("admin/structure/menu/manage/{$this->menu->id()}/add", $edit, t('Save')); $menu_links = entity_load_multiple_by_properties('menu_link_content', array('title' => $title)); $last_link = reset($menu_links); $created_links[] = 'tools:' . $last_link->getPluginId(); } // The last link cannot be a parent in the new menu link form. $this->drupalGet('admin/structure/menu/manage/admin/add'); $value = 'tools:' . $last_link->getPluginId(); $this->assertNoOption('edit-menu-parent', $value, 'The invalid option is not there.'); // All but the last link can be parents in the new menu link form. array_pop($created_links); foreach ($created_links as $key => $link) { $this->assertOption('edit-menu-parent', $link, 'The valid option number ' . ($key + 1) . ' is there.'); } } /** * Verifies a menu link using the UI. * * @param \Drupal\menu_link_content\Entity\MenuLinkContent $item * Menu link. * @param object $item_node * Menu link content node. * @param \Drupal\menu_link_content\Entity\MenuLinkContent $parent * Parent menu link. * @param object $parent_node * Parent menu link content node. */ function verifyMenuLink(MenuLinkContent $item, $item_node, MenuLinkContent $parent = NULL, $parent_node = NULL) { // View home page. $this->drupalGet(''); $this->assertResponse(200); // Verify parent menu link. if (isset($parent)) { // Verify menu link. $title = $parent->getTitle(); $this->assertLink($title, 0, 'Parent menu link was displayed'); // Verify menu link link. $this->clickLink($title); $title = $parent_node->label(); $this->assertTitle(t("@title | Drupal", array('@title' => $title)), 'Parent menu link link target was correct'); } // Verify menu link. $title = $item->getTitle(); $this->assertLink($title, 0, 'Menu link was displayed'); // Verify menu link link. $this->clickLink($title); $title = $item_node->label(); $this->assertTitle(t("@title | Drupal", array('@title' => $title)), 'Menu link link target was correct'); } /** * Changes the parent of a menu link using the UI. * * @param \Drupal\menu_link_content\MenuLinkContentInterface $item * The menu link item to move. * @param int $parent * The id of the new parent. * @param string $menu_name * The menu the menu link will be moved to. */ function moveMenuLink(MenuLinkContent $item, $parent, $menu_name) { $mlid = $item->id(); $edit = array( 'menu_parent' => $menu_name . ':' . $parent, ); $this->drupalPostForm("admin/structure/menu/item/$mlid/edit", $edit, t('Save')); $this->assertResponse(200); } /** * Modifies a menu link using the UI. * * @param \Drupal\menu_link_content\Entity\MenuLinkContent $item * Menu link entity. */ function modifyMenuLink(MenuLinkContent $item) { $item->title->value = $this->randomMachineName(16); $mlid = $item->id(); $title = $item->getTitle(); // Edit menu link. $edit = array(); $edit['title[0][value]'] = $title; $this->drupalPostForm("admin/structure/menu/item/$mlid/edit", $edit, t('Save')); $this->assertResponse(200); $this->assertText('The menu link has been saved.'); // Verify menu link. $this->drupalGet('admin/structure/menu/manage/' . $item->getMenuName()); $this->assertText($title, 'Menu link was edited'); } /** * Resets a standard menu link using the UI. * * @param \Drupal\Core\Menu\MenuLinkInterface $menu_link * The Menu link. * @param int $old_weight * Original title for menu link. */ function resetMenuLink(MenuLinkInterface $menu_link, $old_weight) { // Reset menu link. $this->drupalPostForm("admin/structure/menu/link/{$menu_link->getPluginId()}/reset", array(), t('Reset')); $this->assertResponse(200); $this->assertRaw(t('The menu link was reset to its default settings.'), 'Menu link was reset'); // Verify menu link. $instance = \Drupal::service('plugin.manager.menu.link')->createInstance($menu_link->getPluginId()); $this->assertEqual($old_weight, $instance->getWeight(), 'Resets to the old weight.'); } /** * Deletes a menu link using the UI. * * @param \Drupal\menu_link_content\Entity\MenuLinkContent $item * Menu link. */ function deleteMenuLink(MenuLinkContent $item) { $mlid = $item->id(); $title = $item->getTitle(); // Delete menu link. $this->drupalPostForm("admin/structure/menu/item/$mlid/delete", array(), t('Delete')); $this->assertResponse(200); $this->assertRaw(t('The menu link %title has been deleted.', array('%title' => $title)), 'Menu link was deleted'); // Verify deletion. $this->drupalGet(''); $this->assertNoText($title, 'Menu link was deleted'); } /** * Alternately disables and enables a menu link. * * @param \Drupal\menu_link_content\Entity\MenuLinkContent $item * Menu link. */ function toggleMenuLink(MenuLinkContent $item) { $this->disableMenuLink($item); // Verify menu link is absent. $this->drupalGet(''); $this->assertNoText($item->getTitle(), 'Menu link was not displayed'); $this->enableMenuLink($item); // Verify menu link is displayed. $this->drupalGet(''); $this->assertText($item->getTitle(), 'Menu link was displayed'); } /** * Disables a menu link. * * @param \Drupal\menu_link_content\Entity\MenuLinkContent $item * Menu link. */ function disableMenuLink(MenuLinkContent $item) { $mlid = $item->id(); $edit['enabled[value]'] = FALSE; $this->drupalPostForm("admin/structure/menu/item/$mlid/edit", $edit, t('Save')); // Unlike most other modules, there is no confirmation message displayed. // Verify in the database. $this->assertMenuLink($item->getPluginId(), array('enabled' => 0)); } /** * Enables a menu link. * * @param \Drupal\menu_link_content\Entity\MenuLinkContent $item * Menu link. */ function enableMenuLink(MenuLinkContent $item) { $mlid = $item->id(); $edit['enabled[value]'] = TRUE; $this->drupalPostForm("admin/structure/menu/item/$mlid/edit", $edit, t('Save')); // Verify in the database. $this->assertMenuLink($item->getPluginId(), array('enabled' => 1)); } /** * Tests if administrative users other than user 1 can access the menu parents * AJAX callback. */ public function testMenuParentsJsAccess() { $admin = $this->drupalCreateUser(array('administer menu')); $this->drupalLogin($admin); // Just check access to the callback overall, the POST data is irrelevant. $this->drupalGetAjax('admin/structure/menu/parents'); $this->assertResponse(200); // Do standard user tests. // Log in the user. $this->drupalLogin($this->authenticatedUser); $this->drupalGetAjax('admin/structure/menu/parents'); $this->assertResponse(403); } /** * Returns standard menu link. * * @return \Drupal\Core\Menu\MenuLinkInterface * A menu link plugin. */ private function getStandardMenuLink() { // Retrieve menu link id of the Log out menu link, which will always be on // the front page. /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */ $menu_link_manager = \Drupal::service('plugin.manager.menu.link'); $instance = $menu_link_manager->getInstance(['id' => 'user.logout']); $this->assertTrue((bool) $instance, 'Standard menu link was loaded'); return $instance; } /** * Verifies the logged in user has the desired access to various menu pages. * * @param int $response * (optional) The expected HTTP response code. Defaults to 200. */ private function verifyAccess($response = 200) { // View menu help page. $this->drupalGet('admin/help/menu'); $this->assertResponse($response); if ($response == 200) { $this->assertText(t('Menu'), 'Menu help was displayed'); } // View menu build overview page. $this->drupalGet('admin/structure/menu'); $this->assertResponse($response); if ($response == 200) { $this->assertText(t('Menus'), 'Menu build overview page was displayed'); } // View tools menu customization page. $this->drupalGet('admin/structure/menu/manage/' . $this->menu->id()); $this->assertResponse($response); if ($response == 200) { $this->assertText(t('Tools'), 'Tools menu page was displayed'); } // View menu edit page for a static link. $item = $this->getStandardMenuLink(); $this->drupalGet('admin/structure/menu/link/' . $item->getPluginId() . '/edit'); $this->assertResponse($response); if ($response == 200) { $this->assertText(t('Edit menu item'), 'Menu edit page was displayed'); } // View add menu page. $this->drupalGet('admin/structure/menu/add'); $this->assertResponse($response); if ($response == 200) { $this->assertText(t('Menus'), 'Add menu page was displayed'); } } /** * Tests menu block settings. */ protected function doTestMenuBlock() { $menu_id = $this->menu->id(); $block_id = $this->blockPlacements[$menu_id]; $this->drupalGet('admin/structure/block/manage/' . $block_id); $this->drupalPostForm(NULL, [ 'settings[depth]' => 3, 'settings[level]' => 2, ], t('Save block')); $block = Block::load($block_id); $settings = $block->getPlugin()->getConfiguration(); $this->assertEqual($settings['depth'], 3); $this->assertEqual($settings['level'], 2); // Reset settings. $block->getPlugin()->setConfigurationValue('depth', 0); $block->getPlugin()->setConfigurationValue('level', 1); $block->save(); } }
{ "content_hash": "de0fff65efef669da82e04514d1eed6d", "timestamp": "", "source": "github", "line_count": 961, "max_line_length": 342, "avg_line_length": 36.85015608740895, "alnum_prop": 0.6220596955920142, "repo_name": "MGApcDev/MGApcDevCom", "id": "f640cc749a6c4130db66ee14b8cecbd59a273b33", "size": "35413", "binary": false, "copies": "73", "ref": "refs/heads/master", "path": "core/modules/menu_ui/src/Tests/MenuTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "7927" }, { "name": "CSS", "bytes": "513186" }, { "name": "HTML", "bytes": "599529" }, { "name": "JavaScript", "bytes": "938091" }, { "name": "PHP", "bytes": "31007665" }, { "name": "Shell", "bytes": "49920" }, { "name": "Visual Basic", "bytes": "2202" } ] }
package client.gui; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.plaf.basic.BasicButtonUI; import client.platform.ClientConfigDefaults.CK; /** * A helper used in FS2 to create tabs with close buttons and changeable labels. * * The constructor for this class MUST be called! * * @author gary */ @SuppressWarnings("serial") public abstract class TabItem extends JPanel { public enum FS2Tab {FILES, CHAT, PEERS, DOWNLOADS, STATS, UPLOADS, SETTINGS} static Icon closeInactive; static Icon closeActive; final JTabbedPane pane; private TabLabelComponent label; final protected MainFrame frame; final protected FS2Tab type; public int getIndex() { return pane.indexOfTabComponent(label); } public void activateTab() { pane.setSelectedIndex(getIndex()); } public boolean isActiveTab() { return pane.getSelectedIndex()==getIndex(); } public FS2Tab getType() { return type; } public TabItem(JTabbedPane pane, MainFrame frame, String initialCaption, FS2Tab type, ImageIcon icon) { this.pane = pane; this.frame = frame; this.type = type; frame.instantiatedTabs.put(type, this); //Initialises static icons if they havent been already: if (closeInactive==null) { ImageIcon cd = frame.gui.util.getImage("close-disable"); ImageIcon ca = frame.gui.util.getImage("close"); if (cd!=null) { closeInactive = cd; } if (cd!=null) { closeActive = ca; } } label = new TabLabelComponent(initialCaption, icon); addToTabs(); } public void addToTabs() { frame.openTabs.put(type, this); pane.addTab(null, this); pane.setTabComponentAt(pane.getTabCount()-1, label); activateTab(); } private class TabLabelComponent extends JPanel implements ActionListener, MouseListener{ JLabel caption; JButton closer; public TabLabelComponent(String initialCaption, ImageIcon icon) { setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); setOpaque(false); closer = new JButton(closeInactive); caption = new JLabel(initialCaption, icon, JLabel.LEFT); caption.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 6)); closer.setUI(new BasicButtonUI()); closer.setPreferredSize(new Dimension(closeInactive.getIconWidth()+2, closeInactive.getIconHeight()+2)); closer.setBorder(BorderFactory.createEmptyBorder()); add(caption); add(closer); closer.addActionListener(this); closer.addMouseListener(this); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource()==closer) { int tabIndex = pane.indexOfTabComponent(this); if (tabIndex!=-1) { pane.removeTabAt(tabIndex); frame.gui.conf.deleteKey(CK.OPEN_TABS+"/"+type.toString()); frame.openTabs.remove(type); } } } @Override public void mouseClicked(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) { closer.setIcon(closeActive); frame.setStatusHint("Click here to close the '"+caption.getText()+"' tab"); } @Override public void mouseExited(MouseEvent e) { closer.setIcon(closeInactive); } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} } /** * Set the label for this tab. * @param title */ public void setLabel(String title) { this.label.caption.setText(title); } /** * When this is set to true this tab is closable (with a little 'x') otherwise it is unclosable. * @param closable */ public void setClosable(boolean closable) { label.closer.setVisible(closable); if (closable) { label.caption.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 6)); } else { label.caption.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); } } void shutdown() { //A subclass should override this if they need to stop a timer, close a socket etc. //This is closed at application shutdown/update NOT when the tab is closed. } }
{ "content_hash": "9ae5a1f92d3d64d55b366b5452cd7e7c", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 107, "avg_line_length": 25.241176470588236, "alnum_prop": 0.7163831274761128, "repo_name": "bs2609/fs2", "id": "22e84b727818e5a210318a32602907467859fd60", "size": "4291", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/client/gui/TabItem.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "829636" } ] }
#ifndef TRCharts_Impl_CategoryAxisImpl_cpp #define TRCharts_Impl_CategoryAxisImpl_cpp #include <TRCharts/Impl/CategoryAxisImpl.hpp> Charts::CategoryAxis::CategoryAxis(void) { } Charts::CategoryAxis::~CategoryAxis(void) { } std::vector<Charts::Axis::Tick> Charts::CategoryAxis::getTicks(void) const { return std::vector<Tick>(); } Charts::Range Charts::CategoryAxis::getLayoutRange(void) const { return Range(); } #endif
{ "content_hash": "e1db0fb712e65df14f5d34d168230021", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 74, "avg_line_length": 15.03448275862069, "alnum_prop": 0.7454128440366973, "repo_name": "thomsonreuters/TRCharts", "id": "d2f9407099539e47a543d854d8465ea946fbc46a", "size": "1189", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Charts/TRCharts/TRCharts/Impl/CategoryAxisImpl.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5418" }, { "name": "C++", "bytes": "3313416" }, { "name": "CMake", "bytes": "1566" }, { "name": "Java", "bytes": "421721" }, { "name": "Makefile", "bytes": "2679" }, { "name": "Objective-C", "bytes": "334981" }, { "name": "Objective-C++", "bytes": "510699" }, { "name": "Shell", "bytes": "2273" } ] }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright 2012 Red Hat, Inc. and/or its affiliates. ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.jbpm</groupId> <artifactId>jbpm-wb-forms</artifactId> <version>7.17.0-SNAPSHOT</version> </parent> <artifactId>jbpm-wb-forms-api</artifactId> <packaging>jar</packaging> <name>jBPM Workbench - Forms API</name> <properties> <java.module.name>org.jbpm.wb.forms.api</java.module.name> </properties> <dependencies> <dependency> <groupId>org.jbpm</groupId> <artifactId>jbpm-wb-common-api</artifactId> </dependency> <dependency> <groupId>org.jbpm</groupId> <artifactId>jbpm-wb-human-tasks-api</artifactId> </dependency> <dependency> <groupId>org.jbpm</groupId> <artifactId>jbpm-wb-process-runtime-api</artifactId> </dependency> <dependency> <groupId>org.kie.workbench.forms</groupId> <artifactId>kie-wb-common-dynamic-forms-api</artifactId> </dependency> <dependency> <groupId>org.jboss.errai</groupId> <artifactId>errai-bus</artifactId> </dependency> <dependency> <groupId>org.jboss.errai</groupId> <artifactId>errai-common</artifactId> </dependency> <dependency> <groupId>org.kie</groupId> <artifactId>kie-internal</artifactId> </dependency> <!-- hack to disable sisu annotation processing (that scans client side types) --> <dependency> <groupId>org.eclipse.sisu</groupId> <artifactId>org.eclipse.sisu.inject</artifactId> <scope>runtime</scope> </dependency> </dependencies> </project>
{ "content_hash": "8d310cf2b03361c26fe35e6ddae8816f", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 105, "avg_line_length": 32.18666666666667, "alnum_prop": 0.6855840927920464, "repo_name": "nmirasch/jbpm-console-ng", "id": "1f77bf826ff8abb77ef6668c43d548a4f55213ea", "size": "2414", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jbpm-wb-forms/jbpm-wb-forms-api/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "40775" }, { "name": "HTML", "bytes": "135134" }, { "name": "Java", "bytes": "3766628" }, { "name": "Visual Basic", "bytes": "18136" } ] }
FROM balenalib/hummingboard-ubuntu:eoan-run # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # install python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ netbase \ && rm -rf /var/lib/apt/lists/* # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.6.12 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.0.1 ENV SETUPTOOLS_VERSION 56.0.0 RUN set -x \ && buildDeps=' \ curl \ ' \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \ && echo "80d7da46d9de7727c1912630fe74a0e45c61b6fa58a1eaba08a772ac81bae8b9 Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH 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 curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.sh 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: ARM v7 \nOS: Ubuntu eoan \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.6.12, Pip v21.0.1, Setuptools v56.0.0 \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": "a1f7badadcce959c99039e9f3d39243a", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 707, "avg_line_length": 51.8974358974359, "alnum_prop": 0.7082509881422925, "repo_name": "nghiant2710/base-images", "id": "d6d4e555dc7bcf22b4a8c6b36b8da3aaada1cd64", "size": "4069", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/python/hummingboard/ubuntu/eoan/3.6.12/run/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ] }
/* * Sync adapters are required such that the models can connect to a * persistence strategy of your choosing. */ function S4() { return ((1 + Math.random()) * 65536 | 0).toString(16).substring(1); } function guid() { return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4(); } function InitAdapter(config) { Cloud = require("ti.cloud"); Cloud.debug = !0; config.Cloud = Cloud; } function Sync(method, model, options) { var object_name = model.config.adapter.collection_name; //determine which sync method to call based on the //collection type in the model if (object_name === "photos") { processACSPhotos(model, method, options); } else if (object_name === "users") { processACSUsers(model, method, options); } else if (object_name === "reviews"){ processACSComments(model, method, opts); } } /** * this is a separate handler for when the object being processed * is an ACS Photo */ function processACSPhotos(model, method, options) { switch (method) { case "create": // include attributes into the params for ACS Cloud.Photos.create(model.toJSON(), function(e) { if (e.success) { // save the meta data with object model.meta = e.meta; // return the individual photo object found options.success(e.photos[0]); // trigger fetch for UI updates model.trigger("fetch"); } else { Ti.API.error("Photos.create " + e.message); options.error(e.error && e.message || e); } }); break; case "read": model.id && (options.data.photo_id = model.id); var method = model.id ? Cloud.Photos.show : Cloud.Photos.query; method((options.data || {}), function(e) { if (e.success) { model.meta = e.meta; if (e.photos.length === 1) { options.success(e.photos[0]); } else { options.success(e.photos); } model.trigger("fetch"); return; } else { Ti.API.error("Cloud.Photos.query " + e.message); options.error(e.error && e.message || e); } }); break; case "update": case "delete": // Not currently implemented, let the user know alert("Not Implemented Yet"); break; } } /** * This function will get or update user data from ACS */ function processACSUsers(model, method, options) { switch (method) { case "update": var params = model.toJSON(); //uses ACS to update the user data Cloud.Users.update(params, function(e) { if (e.success) { //the model in this case is a user model.meta = e.meta; //the first element of the users array contains the current user options.success && options.success(e.users[0]); model.trigger("fetch"); } else { //no bueno Ti.API.error("Cloud.Users.update " + e.message); options.error && options.error(e.error && e.message || e); } } ); break; /* this comes from the authors repo, but doesn't appear in this chapter yet * leaving it here for now case "read": options.data = options.data || {}; model.id && (options.data.user_id = model.id); var readMethod = model.id ? Cloud.Users.show : Cloud.Users.query; readMethod(options.data || {}, function(e) { if (e.success) { model.meta = e.meta; 1 === e.users.length ? options.success(e.users[0]) : options.success(e.users); model.trigger("fetch"); return; } Ti.API.error("Cloud.Users.query " + e.message); options.error && options.error(e.error && e.message || e); } ); break; */ } } /** * Process ACS Comments (reviews) - map to the REST function calls (CRUD) */ function processACSComments(model, method, opts) { switch (method) { case "create": var params = model.toJSON(); Cloud.Reviews.create(params, function(e) { if (e.success) { model.meta = e.meta; opts.success && opts.success(e.reviews[0]); model.trigger("fetch"); } else { Ti.API.error("Comments.create " + e.message); opts.error && opts.error(e.message || e); } }); break; case "read": Cloud.Reviews.query((opts.data || {}), function(e) { if (e.success) { model.meta = e.meta; if (e.reviews.length === 1) { opts.success && opts.success(e.reviews[0]); } else { opts.success && opts.success(e.reviews); } model.trigger("fetch"); return; } else { Ti.API.error("Reviews.query " + e.message); opts.error && opts.error(e.message || e); } }); break; case "update": var params = {}; // look for the review id in opts or on model params.review_id = model.id || (opts.data && opts.data.id); // get the id of the associated photo params.photo_id = opts.data && opts.data.photo_id; Cloud.Reviews.remove(params, function(e) { if (e.success) { model.meta = e.meta; opts.success && opts.success(model.attributes); model.trigger("fetch"); return; } Ti.API.error(e); opts.error && opts.error(e.error && e.message || e); }); break; case "delete": break; } } var _ = require("alloy/underscore")._; module.exports.sync = Sync; module.exports.beforeModelCreate = function(config) { config = config || {}; config.data = {}; InitAdapter(config); return config; }; module.exports.afterModelCreate = function(Model) { Model = Model || {}; Model.prototype.config.Model = Model; return Model; };
{ "content_hash": "f86ba625d8256b71f6ff4062024e156f", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 87, "avg_line_length": 25.36697247706422, "alnum_prop": 0.5916817359855334, "repo_name": "am934743/chapter7", "id": "509730080e62c4668a278184161247ef9739c0cb", "size": "5530", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/lib/alloy/sync/acs.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "120494" }, { "name": "C++", "bytes": "13079" }, { "name": "CSS", "bytes": "1276" }, { "name": "JavaScript", "bytes": "288301" }, { "name": "Makefile", "bytes": "1359734" }, { "name": "Objective-C", "bytes": "3411305" }, { "name": "Objective-C++", "bytes": "8645" }, { "name": "Python", "bytes": "5251" }, { "name": "Shell", "bytes": "1272" } ] }
<h1>Contact Page</h1> <div> If you have any idea contact me <p>email: {{contactMe.email}}</p> <p>github: {{contactMe.github}}</p> </div>
{ "content_hash": "1905081cb56549a204f03b8ca0e94a0c", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 39, "avg_line_length": 24.666666666666668, "alnum_prop": 0.6081081081081081, "repo_name": "swapnilnakate7/AngularJsTemplate", "id": "7e3df711d340f3b490e878056e226866b53d9bd9", "size": "148", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/templates/contact.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "197526" }, { "name": "HTML", "bytes": "5828" }, { "name": "JavaScript", "bytes": "7975" }, { "name": "SCSS", "bytes": "541" } ] }
'use strict'; var Q = require('q'); var fs = require('fs'); var path = require('path'); var shell = require('shelljs'); var unorm = require('unorm'); var plist = require('plist'); var URL = require('url'); var events = require('cordova-common').events; var xmlHelpers = require('cordova-common').xmlHelpers; var ConfigParser = require('cordova-common').ConfigParser; var CordovaError = require('cordova-common').CordovaError; var PlatformJson = require('cordova-common').PlatformJson; var PlatformMunger = require('cordova-common').ConfigChanges.PlatformMunger; var PluginInfoProvider = require('cordova-common').PluginInfoProvider; var FileUpdater = require('cordova-common').FileUpdater; var projectFile = require('./projectFile'); // launch storyboard and related constants var LAUNCHIMAGE_BUILD_SETTING = 'ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME'; var LAUNCHIMAGE_BUILD_SETTING_VALUE = 'LaunchImage'; var UI_LAUNCH_STORYBOARD_NAME = 'UILaunchStoryboardName'; var CDV_LAUNCH_STORYBOARD_NAME = 'CDVLaunchScreen'; var IMAGESET_COMPACT_SIZE_CLASS = 'compact'; var CDV_ANY_SIZE_CLASS = 'any'; module.exports.prepare = function (cordovaProject, options) { var self = this; var platformJson = PlatformJson.load(this.locations.root, 'ios'); var munger = new PlatformMunger('ios', this.locations.root, platformJson, new PluginInfoProvider()); this._config = updateConfigFile(cordovaProject.projectConfig, munger, this.locations); // Update own www dir with project's www assets and plugins' assets and js-files return Q.when(updateWww(cordovaProject, this.locations)) .then(function () { // update project according to config.xml changes. return updateProject(self._config, self.locations); }) .then(function () { updateIcons(cordovaProject, self.locations); updateSplashScreens(cordovaProject, self.locations); updateLaunchStoryboardImages(cordovaProject, self.locations); updateFileResources(cordovaProject, self.locations); }) .then(function () { events.emit('verbose', 'Prepared iOS project successfully'); }); }; module.exports.clean = function (options) { // A cordovaProject isn't passed into the clean() function, because it might have // been called from the platform shell script rather than the CLI. Check for the // noPrepare option passed in by the non-CLI clean script. If that's present, or if // there's no config.xml found at the project root, then don't clean prepared files. var projectRoot = path.resolve(this.root, '../..'); var projectConfigFile = path.join(projectRoot, 'config.xml'); if ((options && options.noPrepare) || !fs.existsSync(projectConfigFile) || !fs.existsSync(this.locations.configXml)) { return Q(); } var projectConfig = new ConfigParser(this.locations.configXml); var self = this; return Q().then(function () { cleanWww(projectRoot, self.locations); cleanIcons(projectRoot, projectConfig, self.locations); cleanSplashScreens(projectRoot, projectConfig, self.locations); cleanLaunchStoryboardImages(projectRoot, projectConfig, self.locations); cleanFileResources(projectRoot, projectConfig, self.locations); }); }; /** * Updates config files in project based on app's config.xml and config munge, * generated by plugins. * * @param {ConfigParser} sourceConfig A project's configuration that will * be merged into platform's config.xml * @param {ConfigChanges} configMunger An initialized ConfigChanges instance * for this platform. * @param {Object} locations A map of locations for this platform * * @return {ConfigParser} An instance of ConfigParser, that * represents current project's configuration. When returned, the * configuration is already dumped to appropriate config.xml file. */ function updateConfigFile (sourceConfig, configMunger, locations) { events.emit('verbose', 'Generating platform-specific config.xml from defaults for iOS at ' + locations.configXml); // First cleanup current config and merge project's one into own // Overwrite platform config.xml with defaults.xml. shell.cp('-f', locations.defaultConfigXml, locations.configXml); // Then apply config changes from global munge to all config files // in project (including project's config) configMunger.reapply_global_munge().save_all(); events.emit('verbose', 'Merging project\'s config.xml into platform-specific iOS config.xml'); // Merge changes from app's config.xml into platform's one var config = new ConfigParser(locations.configXml); xmlHelpers.mergeXml(sourceConfig.doc.getroot(), config.doc.getroot(), 'ios', /* clobber= */true); config.write(); return config; } /** * Logs all file operations via the verbose event stream, indented. */ function logFileOp (message) { events.emit('verbose', ' ' + message); } /** * Updates platform 'www' directory by replacing it with contents of * 'platform_www' and app www. Also copies project's overrides' folder into * the platform 'www' folder * * @param {Object} cordovaProject An object which describes cordova project. * @param {boolean} destinations An object that contains destinations * paths for www files. */ function updateWww (cordovaProject, destinations) { var sourceDirs = [ path.relative(cordovaProject.root, cordovaProject.locations.www), path.relative(cordovaProject.root, destinations.platformWww) ]; // If project contains 'merges' for our platform, use them as another overrides var merges_path = path.join(cordovaProject.root, 'merges', 'ios'); if (fs.existsSync(merges_path)) { events.emit('verbose', 'Found "merges/ios" folder. Copying its contents into the iOS project.'); sourceDirs.push(path.join('merges', 'ios')); } var targetDir = path.relative(cordovaProject.root, destinations.www); events.emit( 'verbose', 'Merging and updating files from [' + sourceDirs.join(', ') + '] to ' + targetDir); FileUpdater.mergeAndUpdateDir( sourceDirs, targetDir, { rootDir: cordovaProject.root }, logFileOp); } /** * Cleans all files from the platform 'www' directory. */ function cleanWww (projectRoot, locations) { var targetDir = path.relative(projectRoot, locations.www); events.emit('verbose', 'Cleaning ' + targetDir); // No source paths are specified, so mergeAndUpdateDir() will clear the target directory. FileUpdater.mergeAndUpdateDir( [], targetDir, { rootDir: projectRoot, all: true }, logFileOp); } /** * Updates project structure and AndroidManifest according to project's configuration. * * @param {ConfigParser} platformConfig A project's configuration that will * be used to update project * @param {Object} locations A map of locations for this platform (In/Out) */ function updateProject (platformConfig, locations) { // CB-6992 it is necessary to normalize characters // because node and shell scripts handles unicode symbols differently // We need to normalize the name to NFD form since iOS uses NFD unicode form var name = unorm.nfd(platformConfig.name()); var version = platformConfig.version(); var displayName = platformConfig.shortName && platformConfig.shortName(); var originalName = path.basename(locations.xcodeCordovaProj); // Update package id (bundle id) var plistFile = path.join(locations.xcodeCordovaProj, originalName + '-Info.plist'); var infoPlist = plist.parse(fs.readFileSync(plistFile, 'utf8')); // Update version (bundle version) infoPlist['CFBundleShortVersionString'] = version; var CFBundleVersion = platformConfig.getAttribute('ios-CFBundleVersion') || default_CFBundleVersion(version); infoPlist['CFBundleVersion'] = CFBundleVersion; if (platformConfig.getAttribute('defaultlocale')) { infoPlist['CFBundleDevelopmentRegion'] = platformConfig.getAttribute('defaultlocale'); } if (displayName) { infoPlist['CFBundleDisplayName'] = displayName; } // replace Info.plist ATS entries according to <access> and <allow-navigation> config.xml entries var ats = writeATSEntries(platformConfig); if (Object.keys(ats).length > 0) { infoPlist['NSAppTransportSecurity'] = ats; } else { delete infoPlist['NSAppTransportSecurity']; } handleOrientationSettings(platformConfig, infoPlist); updateProjectPlistForLaunchStoryboard(platformConfig, infoPlist); /* eslint-disable no-tabs */ // Write out the plist file with the same formatting as Xcode does var info_contents = plist.build(infoPlist, { indent: ' ', offset: -1 }); /* eslint-enable no-tabs */ info_contents = info_contents.replace(/<string>[\s\r\n]*<\/string>/g, '<string></string>'); fs.writeFileSync(plistFile, info_contents, 'utf-8'); events.emit('verbose', 'Wrote out iOS Bundle Version "' + version + '" to ' + plistFile); return handleBuildSettings(platformConfig, locations, infoPlist).then(function () { if (name === originalName) { events.emit('verbose', 'iOS Product Name has not changed (still "' + originalName + '")'); return Q(); } else { // CB-11712 <name> was changed, we don't support it' var errorString = 'The product name change (<name> tag) in config.xml is not supported dynamically.\n' + 'To change your product name, you have to remove, then add your ios platform again.\n' + 'Make sure you save your plugins beforehand using `cordova plugin save`.\n' + '\tcordova plugin save\n' + '\tcordova platform rm ios\n' + '\tcordova platform add ios\n' ; return Q.reject(new CordovaError(errorString)); } }); } function handleOrientationSettings (platformConfig, infoPlist) { switch (getOrientationValue(platformConfig)) { case 'portrait': infoPlist['UIInterfaceOrientation'] = [ 'UIInterfaceOrientationPortrait' ]; infoPlist['UISupportedInterfaceOrientations'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown' ]; infoPlist['UISupportedInterfaceOrientations~ipad'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown' ]; break; case 'landscape': infoPlist['UIInterfaceOrientation'] = [ 'UIInterfaceOrientationLandscapeLeft' ]; infoPlist['UISupportedInterfaceOrientations'] = [ 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ]; infoPlist['UISupportedInterfaceOrientations~ipad'] = [ 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ]; break; case 'all': infoPlist['UIInterfaceOrientation'] = [ 'UIInterfaceOrientationPortrait' ]; infoPlist['UISupportedInterfaceOrientations'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ]; infoPlist['UISupportedInterfaceOrientations~ipad'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ]; break; case 'default': infoPlist['UISupportedInterfaceOrientations'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ]; infoPlist['UISupportedInterfaceOrientations~ipad'] = [ 'UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight' ]; delete infoPlist['UIInterfaceOrientation']; } } function handleBuildSettings (platformConfig, locations, infoPlist) { var pkg = platformConfig.getAttribute('ios-CFBundleIdentifier') || platformConfig.packageName(); var targetDevice = parseTargetDevicePreference(platformConfig.getPreference('target-device', 'ios')); var deploymentTarget = platformConfig.getPreference('deployment-target', 'ios'); var needUpdatedBuildSettingsForLaunchStoryboard = checkIfBuildSettingsNeedUpdatedForLaunchStoryboard(platformConfig, infoPlist); var swiftVersion = platformConfig.getPreference('SwiftVersion', 'ios'); var project; try { project = projectFile.parse(locations); } catch (err) { return Q.reject(new CordovaError('Could not parse ' + locations.pbxproj + ': ' + err)); } var origPkg = project.xcode.getBuildProperty('PRODUCT_BUNDLE_IDENTIFIER'); // no build settings provided and we don't need to update build settings for launch storyboards, // then we don't need to parse and update .pbxproj file if (origPkg === pkg && !targetDevice && !deploymentTarget && !needUpdatedBuildSettingsForLaunchStoryboard && !swiftVersion) { return Q(); } if (origPkg !== pkg) { events.emit('verbose', 'Set PRODUCT_BUNDLE_IDENTIFIER to ' + pkg + '.'); project.xcode.updateBuildProperty('PRODUCT_BUNDLE_IDENTIFIER', pkg); } if (targetDevice) { events.emit('verbose', 'Set TARGETED_DEVICE_FAMILY to ' + targetDevice + '.'); project.xcode.updateBuildProperty('TARGETED_DEVICE_FAMILY', targetDevice); } if (deploymentTarget) { events.emit('verbose', 'Set IPHONEOS_DEPLOYMENT_TARGET to "' + deploymentTarget + '".'); project.xcode.updateBuildProperty('IPHONEOS_DEPLOYMENT_TARGET', deploymentTarget); } if (swiftVersion) { events.emit('verbose', 'Set SwiftVersion to "' + swiftVersion + '".'); project.xcode.updateBuildProperty('SWIFT_VERSION', swiftVersion); } updateBuildSettingsForLaunchStoryboard(project.xcode, platformConfig, infoPlist); project.write(); return Q(); } function mapIconResources (icons, iconsDir) { // See https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/IconMatrix.html // for launch images sizes reference. var platformIcons = [ { dest: 'icon-20.png', width: 20, height: 20 }, { dest: 'icon-20@2x.png', width: 40, height: 40 }, { dest: 'icon-20@3x.png', width: 60, height: 60 }, { dest: 'icon-40.png', width: 40, height: 40 }, { dest: 'icon-40@2x.png', width: 80, height: 80 }, { dest: 'icon-50.png', width: 50, height: 50 }, { dest: 'icon-50@2x.png', width: 100, height: 100 }, { dest: 'icon-60@2x.png', width: 120, height: 120 }, { dest: 'icon-60@3x.png', width: 180, height: 180 }, { dest: 'icon-72.png', width: 72, height: 72 }, { dest: 'icon-72@2x.png', width: 144, height: 144 }, { dest: 'icon-76.png', width: 76, height: 76 }, { dest: 'icon-76@2x.png', width: 152, height: 152 }, { dest: 'icon-83.5@2x.png', width: 167, height: 167 }, { dest: 'icon-1024.png', width: 1024, height: 1024 }, { dest: 'icon-29.png', width: 29, height: 29 }, { dest: 'icon-29@2x.png', width: 58, height: 58 }, { dest: 'icon-29@3x.png', width: 87, height: 87 }, { dest: 'icon.png', width: 57, height: 57 }, { dest: 'icon@2x.png', width: 114, height: 114 }, { dest: 'icon-24@2x.png', width: 48, height: 48 }, { dest: 'icon-27.5@2x.png', width: 55, height: 55 }, { dest: 'icon-44@2x.png', width: 88, height: 88 }, { dest: 'icon-86@2x.png', width: 172, height: 172 }, { dest: 'icon-98@2x.png', width: 196, height: 196 } ]; var pathMap = {}; platformIcons.forEach(function (item) { var icon = icons.getBySize(item.width, item.height) || icons.getDefault(); if (icon) { var target = path.join(iconsDir, item.dest); pathMap[target] = icon.src; } }); return pathMap; } function getIconsDir (projectRoot, platformProjDir) { var iconsDir; var xcassetsExists = folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/')); if (xcassetsExists) { iconsDir = path.join(platformProjDir, 'Images.xcassets/AppIcon.appiconset/'); } else { iconsDir = path.join(platformProjDir, 'Resources/icons/'); } return iconsDir; } function updateIcons (cordovaProject, locations) { var icons = cordovaProject.projectConfig.getIcons('ios'); if (icons.length === 0) { events.emit('verbose', 'This app does not have icons defined'); return; } var platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj); var iconsDir = getIconsDir(cordovaProject.root, platformProjDir); var resourceMap = mapIconResources(icons, iconsDir); events.emit('verbose', 'Updating icons at ' + iconsDir); FileUpdater.updatePaths( resourceMap, { rootDir: cordovaProject.root }, logFileOp); } function cleanIcons (projectRoot, projectConfig, locations) { var icons = projectConfig.getIcons('ios'); if (icons.length > 0) { var platformProjDir = path.relative(projectRoot, locations.xcodeCordovaProj); var iconsDir = getIconsDir(projectRoot, platformProjDir); var resourceMap = mapIconResources(icons, iconsDir); Object.keys(resourceMap).forEach(function (targetIconPath) { resourceMap[targetIconPath] = null; }); events.emit('verbose', 'Cleaning icons at ' + iconsDir); // Source paths are removed from the map, so updatePaths() will delete the target files. FileUpdater.updatePaths( resourceMap, { rootDir: projectRoot, all: true }, logFileOp); } } function mapSplashScreenResources (splashScreens, splashScreensDir) { var platformSplashScreens = [ { dest: 'Default~iphone.png', width: 320, height: 480 }, { dest: 'Default@2x~iphone.png', width: 640, height: 960 }, { dest: 'Default-Portrait~ipad.png', width: 768, height: 1024 }, { dest: 'Default-Portrait@2x~ipad.png', width: 1536, height: 2048 }, { dest: 'Default-Landscape~ipad.png', width: 1024, height: 768 }, { dest: 'Default-Landscape@2x~ipad.png', width: 2048, height: 1536 }, { dest: 'Default-568h@2x~iphone.png', width: 640, height: 1136 }, { dest: 'Default-667h.png', width: 750, height: 1334 }, { dest: 'Default-736h.png', width: 1242, height: 2208 }, { dest: 'Default-Landscape-736h.png', width: 2208, height: 1242 }, { dest: 'Default-2436h.png', width: 1125, height: 2436 }, { dest: 'Default-Landscape-2436h.png', width: 2436, height: 1125 } ]; var pathMap = {}; platformSplashScreens.forEach(function (item) { var splash = splashScreens.getBySize(item.width, item.height); if (splash) { var target = path.join(splashScreensDir, item.dest); pathMap[target] = splash.src; } }); return pathMap; } function getSplashScreensDir (projectRoot, platformProjDir) { var splashScreensDir; var xcassetsExists = folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/')); if (xcassetsExists) { splashScreensDir = path.join(platformProjDir, 'Images.xcassets/LaunchImage.launchimage/'); } else { splashScreensDir = path.join(platformProjDir, 'Resources/splash/'); } return splashScreensDir; } function updateSplashScreens (cordovaProject, locations) { var splashScreens = cordovaProject.projectConfig.getSplashScreens('ios'); if (splashScreens.length === 0) { events.emit('verbose', 'This app does not have splash screens defined'); return; } var platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj); var splashScreensDir = getSplashScreensDir(cordovaProject.root, platformProjDir); var resourceMap = mapSplashScreenResources(splashScreens, splashScreensDir); events.emit('verbose', 'Updating splash screens at ' + splashScreensDir); FileUpdater.updatePaths( resourceMap, { rootDir: cordovaProject.root }, logFileOp); } function cleanSplashScreens (projectRoot, projectConfig, locations) { var splashScreens = projectConfig.getSplashScreens('ios'); if (splashScreens.length > 0) { var platformProjDir = path.relative(projectRoot, locations.xcodeCordovaProj); var splashScreensDir = getSplashScreensDir(projectRoot, platformProjDir); var resourceMap = mapIconResources(splashScreens, splashScreensDir); Object.keys(resourceMap).forEach(function (targetSplashPath) { resourceMap[targetSplashPath] = null; }); events.emit('verbose', 'Cleaning splash screens at ' + splashScreensDir); // Source paths are removed from the map, so updatePaths() will delete the target files. FileUpdater.updatePaths( resourceMap, { rootDir: projectRoot, all: true }, logFileOp); } } function updateFileResources (cordovaProject, locations) { const platformDir = path.relative(cordovaProject.root, locations.root); const files = cordovaProject.projectConfig.getFileResources('ios'); const project = projectFile.parse(locations); // if there are resource-file elements in config.xml if (files.length === 0) { events.emit('verbose', 'This app does not have additional resource files defined'); return; } let resourceMap = {}; files.forEach(function (res) { let src = res.src; let target = res.target; if (!target) { target = src; } let targetPath = path.join(project.resources_dir, target); targetPath = path.relative(cordovaProject.root, targetPath); if (!fs.existsSync(targetPath)) { project.xcode.addResourceFile(target); } else { events.emit('warn', 'Overwriting existing resource file at ' + targetPath); } resourceMap[targetPath] = src; }); events.emit('verbose', 'Updating resource files at ' + platformDir); FileUpdater.updatePaths( resourceMap, { rootDir: cordovaProject.root }, logFileOp); project.write(); } function cleanFileResources (projectRoot, projectConfig, locations) { const platformDir = path.relative(projectRoot, locations.root); const files = projectConfig.getFileResources('ios', true); if (files.length > 0) { events.emit('verbose', 'Cleaning resource files at ' + platformDir); const project = projectFile.parse(locations); var resourceMap = {}; files.forEach(function (res) { let src = res.src; let target = res.target; if (!target) { target = src; } let targetPath = path.join(project.resources_dir, target); targetPath = path.relative(projectRoot, targetPath); const resfile = path.join('Resources', path.basename(targetPath)); project.xcode.removeResourceFile(resfile); resourceMap[targetPath] = null; }); FileUpdater.updatePaths( resourceMap, { rootDir: projectRoot, all: true }, logFileOp); project.write(); } } /** * Returns an array of images for each possible idiom, scale, and size class. The images themselves are * located in the platform's splash images by their pattern (@scale~idiom~sizesize). All possible * combinations are returned, but not all will have a `filename` property. If the latter isn't present, * the device won't attempt to load an image matching the same traits. If the filename is present, * the device will try to load the image if it corresponds to the traits. * * The resulting return looks like this: * * [ * { * idiom: 'universal|ipad|iphone', * scale: '1x|2x|3x', * width: 'any|com', * height: 'any|com', * filename: undefined|'Default@scale~idiom~widthheight.png', * src: undefined|'path/to/original/matched/image/from/splash/screens.png', * target: undefined|'path/to/asset/library/Default@scale~idiom~widthheight.png' * }, ... * ] * * @param {Array<Object>} splashScreens splash screens as defined in config.xml for this platform * @param {string} launchStoryboardImagesDir project-root/Images.xcassets/LaunchStoryboard.imageset/ * @return {Array<Object>} */ function mapLaunchStoryboardContents (splashScreens, launchStoryboardImagesDir) { var platformLaunchStoryboardImages = []; var idioms = ['universal', 'ipad', 'iphone']; var scalesForIdiom = { universal: ['1x', '2x', '3x'], ipad: ['1x', '2x'], iphone: ['1x', '2x', '3x'] }; var sizes = ['com', 'any']; idioms.forEach(function (idiom) { scalesForIdiom[idiom].forEach(function (scale) { sizes.forEach(function (width) { sizes.forEach(function (height) { var item = { idiom: idiom, scale: scale, width: width, height: height }; /* examples of the search pattern: * scale ~ idiom ~ width height * @2x ~ universal ~ any any * @3x ~ iphone ~ com any * @2x ~ ipad ~ com any */ var searchPattern = '@' + scale + '~' + idiom + '~' + width + height; /* because old node versions don't have Array.find, the below is * functionally equivalent to this: * var launchStoryboardImage = splashScreens.find(function(item) { * return item.src.indexOf(searchPattern) >= 0; * }); */ var launchStoryboardImage = splashScreens.reduce(function (p, c) { return (c.src.indexOf(searchPattern) >= 0) ? c : p; }, undefined); if (launchStoryboardImage) { item.filename = 'Default' + searchPattern + '.png'; item.src = launchStoryboardImage.src; item.target = path.join(launchStoryboardImagesDir, item.filename); } platformLaunchStoryboardImages.push(item); }); }); }); }); return platformLaunchStoryboardImages; } /** * Returns a dictionary representing the source and destination paths for the launch storyboard images * that need to be copied. * * The resulting return looks like this: * * { * 'target-path': 'source-path', * ... * } * * @param {Array<Object>} splashScreens splash screens as defined in config.xml for this platform * @param {string} launchStoryboardImagesDir project-root/Images.xcassets/LaunchStoryboard.imageset/ * @return {Object} */ function mapLaunchStoryboardResources (splashScreens, launchStoryboardImagesDir) { var platformLaunchStoryboardImages = mapLaunchStoryboardContents(splashScreens, launchStoryboardImagesDir); var pathMap = {}; platformLaunchStoryboardImages.forEach(function (item) { if (item.target) { pathMap[item.target] = item.src; } }); return pathMap; } /** * Builds the object that represents the contents.json file for the LaunchStoryboard image set. * * The resulting return looks like this: * * { * images: [ * { * idiom: 'universal|ipad|iphone', * scale: '1x|2x|3x', * width-class: undefined|'compact', * height-class: undefined|'compact' * }, ... * ], * info: { * author: 'Xcode', * version: 1 * } * } * * A bit of minor logic is used to map from the array of images returned from mapLaunchStoryboardContents * to the format requried by Xcode. * * @param {Array<Object>} splashScreens splash screens as defined in config.xml for this platform * @param {string} launchStoryboardImagesDir project-root/Images.xcassets/LaunchStoryboard.imageset/ * @return {Object} */ function getLaunchStoryboardContentsJSON (splashScreens, launchStoryboardImagesDir) { var platformLaunchStoryboardImages = mapLaunchStoryboardContents(splashScreens, launchStoryboardImagesDir); var contentsJSON = { images: [], info: { author: 'Xcode', version: 1 } }; contentsJSON.images = platformLaunchStoryboardImages.map(function (item) { var newItem = { idiom: item.idiom, scale: item.scale }; // Xcode doesn't want any size class property if the class is "any" // If our size class is "com", Xcode wants "compact". if (item.width !== CDV_ANY_SIZE_CLASS) { newItem['width-class'] = IMAGESET_COMPACT_SIZE_CLASS; } if (item.height !== CDV_ANY_SIZE_CLASS) { newItem['height-class'] = IMAGESET_COMPACT_SIZE_CLASS; } // Xcode doesn't want a filename property if there's no image for these traits if (item.filename) { newItem.filename = item.filename; } return newItem; }); return contentsJSON; } /** * Determines if the project's build settings may need to be updated for launch storyboard support * */ function checkIfBuildSettingsNeedUpdatedForLaunchStoryboard (platformConfig, infoPlist) { var hasLaunchStoryboardImages = platformHasLaunchStoryboardImages(platformConfig); var hasLegacyLaunchImages = platformHasLegacyLaunchImages(platformConfig); var currentLaunchStoryboard = infoPlist[UI_LAUNCH_STORYBOARD_NAME]; if (hasLaunchStoryboardImages && currentLaunchStoryboard === CDV_LAUNCH_STORYBOARD_NAME && !hasLegacyLaunchImages) { // don't need legacy launch images if we are using our launch storyboard // so we do need to update the project file events.emit('verbose', 'Need to update build settings because project is using our launch storyboard.'); return true; } else if (hasLegacyLaunchImages && !currentLaunchStoryboard) { // we do need to ensure legacy launch images are used if there's no launch storyboard present // so we do need to update the project file events.emit('verbose', 'Need to update build settings because project is using legacy launch images and no storyboard.'); return true; } events.emit('verbose', 'No need to update build settings for launch storyboard support.'); return false; } function updateBuildSettingsForLaunchStoryboard (proj, platformConfig, infoPlist) { var hasLaunchStoryboardImages = platformHasLaunchStoryboardImages(platformConfig); var hasLegacyLaunchImages = platformHasLegacyLaunchImages(platformConfig); var currentLaunchStoryboard = infoPlist[UI_LAUNCH_STORYBOARD_NAME]; if (hasLaunchStoryboardImages && currentLaunchStoryboard === CDV_LAUNCH_STORYBOARD_NAME && !hasLegacyLaunchImages) { // don't need legacy launch images if we are using our launch storyboard events.emit('verbose', 'Removed ' + LAUNCHIMAGE_BUILD_SETTING + ' because project is using our launch storyboard.'); proj.removeBuildProperty(LAUNCHIMAGE_BUILD_SETTING); } else if (hasLegacyLaunchImages && !currentLaunchStoryboard) { // we do need to ensure legacy launch images are used if there's no launch storyboard present events.emit('verbose', 'Set ' + LAUNCHIMAGE_BUILD_SETTING + ' to ' + LAUNCHIMAGE_BUILD_SETTING_VALUE + ' because project is using legacy launch images and no storyboard.'); proj.updateBuildProperty(LAUNCHIMAGE_BUILD_SETTING, LAUNCHIMAGE_BUILD_SETTING_VALUE); } else { events.emit('verbose', 'Did not update build settings for launch storyboard support.'); } } function splashScreensHaveLaunchStoryboardImages (contentsJSON) { /* do we have any launch images do we have for our launch storyboard? * Again, for old Node versions, the below code is equivalent to this: * return !!contentsJSON.images.find(function (item) { * return item.filename !== undefined; * }); */ return !!contentsJSON.images.reduce(function (p, c) { return (c.filename !== undefined) ? c : p; }, undefined); } function platformHasLaunchStoryboardImages (platformConfig) { var splashScreens = platformConfig.getSplashScreens('ios'); var contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, ''); // note: we don't need a file path here; we're just counting return splashScreensHaveLaunchStoryboardImages(contentsJSON); } function platformHasLegacyLaunchImages (platformConfig) { var splashScreens = platformConfig.getSplashScreens('ios'); return !!splashScreens.reduce(function (p, c) { return (c.width !== undefined || c.height !== undefined) ? c : p; }, undefined); } /** * Updates the project's plist based upon our launch storyboard images. If there are no images, then we should * fall back to the regular launch images that might be supplied (that is, our app will be scaled on an iPad Pro), * and if there are some images, we need to alter the UILaunchStoryboardName property to point to * CDVLaunchScreen. * * There's some logic here to avoid overwriting changes the user might have made to their plist if they are using * their own launch storyboard. */ function updateProjectPlistForLaunchStoryboard (platformConfig, infoPlist) { var currentLaunchStoryboard = infoPlist[UI_LAUNCH_STORYBOARD_NAME]; events.emit('verbose', 'Current launch storyboard ' + currentLaunchStoryboard); var hasLaunchStoryboardImages = platformHasLaunchStoryboardImages(platformConfig); if (hasLaunchStoryboardImages && !currentLaunchStoryboard) { // only change the launch storyboard if we have images to use AND the current value is blank // if it's not blank, we've either done this before, or the user has their own launch storyboard events.emit('verbose', 'Changing info plist to use our launch storyboard'); infoPlist[UI_LAUNCH_STORYBOARD_NAME] = CDV_LAUNCH_STORYBOARD_NAME; return; } if (!hasLaunchStoryboardImages && currentLaunchStoryboard === CDV_LAUNCH_STORYBOARD_NAME) { // only revert to using the launch images if we have don't have any images for the launch storyboard // but only clear it if current launch storyboard is our storyboard; the user might be using their // own storyboard instead. events.emit('verbose', 'Changing info plist to use legacy launch images'); delete infoPlist[UI_LAUNCH_STORYBOARD_NAME]; return; } events.emit('verbose', 'Not changing launch storyboard setting in info plist.'); } /** * Returns the directory for the Launch Storyboard image set, if image sets are being used. If they aren't * being used, returns null. * * @param {string} projectRoot The project's root directory * @param {string} platformProjDir The platform's project directory */ function getLaunchStoryboardImagesDir (projectRoot, platformProjDir) { var launchStoryboardImagesDir; var xcassetsExists = folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/')); if (xcassetsExists) { launchStoryboardImagesDir = path.join(platformProjDir, 'Images.xcassets/LaunchStoryboard.imageset/'); } else { // if we don't have a asset library for images, we can't do the storyboard. launchStoryboardImagesDir = null; } return launchStoryboardImagesDir; } /** * Update the images for the Launch Storyboard and updates the image set's contents.json file appropriately. * * @param {Object} cordovaProject The cordova project * @param {Object} locations A dictionary containing useful location paths */ function updateLaunchStoryboardImages (cordovaProject, locations) { var splashScreens = cordovaProject.projectConfig.getSplashScreens('ios'); var platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj); var launchStoryboardImagesDir = getLaunchStoryboardImagesDir(cordovaProject.root, platformProjDir); if (launchStoryboardImagesDir) { var resourceMap = mapLaunchStoryboardResources(splashScreens, launchStoryboardImagesDir); var contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, launchStoryboardImagesDir); events.emit('verbose', 'Updating launch storyboard images at ' + launchStoryboardImagesDir); FileUpdater.updatePaths( resourceMap, { rootDir: cordovaProject.root }, logFileOp); events.emit('verbose', 'Updating Storyboard image set contents.json'); fs.writeFileSync(path.join(cordovaProject.root, launchStoryboardImagesDir, 'Contents.json'), JSON.stringify(contentsJSON, null, 2)); } } /** * Removes the images from the launch storyboard's image set and updates the image set's contents.json * file appropriately. * * @param {string} projectRoot Path to the project root * @param {Object} projectConfig The project's config.xml * @param {Object} locations A dictionary containing useful location paths */ function cleanLaunchStoryboardImages (projectRoot, projectConfig, locations) { var splashScreens = projectConfig.getSplashScreens('ios'); var platformProjDir = path.relative(projectRoot, locations.xcodeCordovaProj); var launchStoryboardImagesDir = getLaunchStoryboardImagesDir(projectRoot, platformProjDir); if (launchStoryboardImagesDir) { var resourceMap = mapLaunchStoryboardResources(splashScreens, launchStoryboardImagesDir); var contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, launchStoryboardImagesDir); Object.keys(resourceMap).forEach(function (targetPath) { resourceMap[targetPath] = null; }); events.emit('verbose', 'Cleaning storyboard image set at ' + launchStoryboardImagesDir); // Source paths are removed from the map, so updatePaths() will delete the target files. FileUpdater.updatePaths( resourceMap, { rootDir: projectRoot, all: true }, logFileOp); // delete filename from contents.json contentsJSON.images.forEach(function (image) { image.filename = undefined; }); events.emit('verbose', 'Updating Storyboard image set contents.json'); fs.writeFileSync(path.join(projectRoot, launchStoryboardImagesDir, 'Contents.json'), JSON.stringify(contentsJSON, null, 2)); } } /** * Queries ConfigParser object for the orientation <preference> value. Warns if * global preference value is not supported by platform. * * @param {Object} platformConfig ConfigParser object * * @return {String} Global/platform-specific orientation in lower-case * (or empty string if both are undefined). */ function getOrientationValue (platformConfig) { var ORIENTATION_DEFAULT = 'default'; var orientation = platformConfig.getPreference('orientation'); if (!orientation) { return ''; } orientation = orientation.toLowerCase(); // Check if the given global orientation is supported if (['default', 'portrait', 'landscape', 'all'].indexOf(orientation) >= 0) { return orientation; } events.emit('warn', 'Unrecognized value for Orientation preference: ' + orientation + '. Defaulting to value: ' + ORIENTATION_DEFAULT + '.'); return ORIENTATION_DEFAULT; } /* Parses all <access> and <allow-navigation> entries and consolidates duplicates (for ATS). Returns an object with a Hostname as the key, and the value an object with properties: { Hostname, // String NSExceptionAllowsInsecureHTTPLoads, // boolean NSIncludesSubdomains, // boolean NSExceptionMinimumTLSVersion, // String NSExceptionRequiresForwardSecrecy, // boolean NSRequiresCertificateTransparency, // boolean // the three below _only_ show when the Hostname is '*' // if any of the three are set, it disables setting NSAllowsArbitraryLoads // (Apple already enforces this in ATS) NSAllowsArbitraryLoadsInWebContent, // boolean (default: false) NSAllowsLocalNetworking, // boolean (default: false) NSAllowsArbitraryLoadsForMedia, // boolean (default:false) } */ function processAccessAndAllowNavigationEntries (config) { var accesses = config.getAccesses(); var allow_navigations = config.getAllowNavigations(); return allow_navigations // we concat allow_navigations and accesses, after processing accesses .concat(accesses.map(function (obj) { // map accesses to a common key interface using 'href', not origin obj.href = obj.origin; delete obj.origin; return obj; })) // we reduce the array to an object with all the entries processed (key is Hostname) .reduce(function (previousReturn, currentElement) { var options = { minimum_tls_version: currentElement.minimum_tls_version, requires_forward_secrecy: currentElement.requires_forward_secrecy, requires_certificate_transparency: currentElement.requires_certificate_transparency, allows_arbitrary_loads_for_media: currentElement.allows_arbitrary_loads_in_media || currentElement.allows_arbitrary_loads_for_media, allows_arbitrary_loads_in_web_content: currentElement.allows_arbitrary_loads_in_web_content, allows_local_networking: currentElement.allows_local_networking }; var obj = parseWhitelistUrlForATS(currentElement.href, options); if (obj) { // we 'union' duplicate entries var item = previousReturn[obj.Hostname]; if (!item) { item = {}; } for (var o in obj) { if (obj.hasOwnProperty(o)) { item[o] = obj[o]; } } previousReturn[obj.Hostname] = item; } return previousReturn; }, {}); } /* Parses a URL and returns an object with these keys: { Hostname, // String NSExceptionAllowsInsecureHTTPLoads, // boolean (default: false) NSIncludesSubdomains, // boolean (default: false) NSExceptionMinimumTLSVersion, // String (default: 'TLSv1.2') NSExceptionRequiresForwardSecrecy, // boolean (default: true) NSRequiresCertificateTransparency, // boolean (default: false) // the three below _only_ apply when the Hostname is '*' // if any of the three are set, it disables setting NSAllowsArbitraryLoads // (Apple already enforces this in ATS) NSAllowsArbitraryLoadsInWebContent, // boolean (default: false) NSAllowsLocalNetworking, // boolean (default: false) NSAllowsArbitraryLoadsForMedia, // boolean (default:false) } null is returned if the URL cannot be parsed, or is to be skipped for ATS. */ function parseWhitelistUrlForATS (url, options) { // @todo 'url.parse' was deprecated since v11.0.0. Use 'url.URL' constructor instead. var href = URL.parse(url); // eslint-disable-line var retObj = {}; retObj.Hostname = href.hostname; // Guiding principle: we only set values in retObj if they are NOT the default if (url === '*') { retObj.Hostname = '*'; var val; val = (options.allows_arbitrary_loads_in_web_content === 'true'); if (options.allows_arbitrary_loads_in_web_content && val) { // default is false retObj.NSAllowsArbitraryLoadsInWebContent = true; } val = (options.allows_arbitrary_loads_for_media === 'true'); if (options.allows_arbitrary_loads_for_media && val) { // default is false retObj.NSAllowsArbitraryLoadsForMedia = true; } val = (options.allows_local_networking === 'true'); if (options.allows_local_networking && val) { // default is false retObj.NSAllowsLocalNetworking = true; } return retObj; } if (!retObj.Hostname) { // check origin, if it allows subdomains (wildcard in hostname), we set NSIncludesSubdomains to YES. Default is NO var subdomain1 = '/*.'; // wildcard in hostname var subdomain2 = '*://*.'; // wildcard in hostname and protocol var subdomain3 = '*://'; // wildcard in protocol only if (!href.pathname) { return null; } else if (href.pathname.indexOf(subdomain1) === 0) { retObj.NSIncludesSubdomains = true; retObj.Hostname = href.pathname.substring(subdomain1.length); } else if (href.pathname.indexOf(subdomain2) === 0) { retObj.NSIncludesSubdomains = true; retObj.Hostname = href.pathname.substring(subdomain2.length); } else if (href.pathname.indexOf(subdomain3) === 0) { retObj.Hostname = href.pathname.substring(subdomain3.length); } else { // Handling "scheme:*" case to avoid creating of a blank key in NSExceptionDomains. return null; } } if (options.minimum_tls_version && options.minimum_tls_version !== 'TLSv1.2') { // default is TLSv1.2 retObj.NSExceptionMinimumTLSVersion = options.minimum_tls_version; } var rfs = (options.requires_forward_secrecy === 'true'); if (options.requires_forward_secrecy && !rfs) { // default is true retObj.NSExceptionRequiresForwardSecrecy = false; } var rct = (options.requires_certificate_transparency === 'true'); if (options.requires_certificate_transparency && rct) { // default is false retObj.NSRequiresCertificateTransparency = true; } // if the scheme is HTTP, we set NSExceptionAllowsInsecureHTTPLoads to YES. Default is NO if (href.protocol === 'http:') { retObj.NSExceptionAllowsInsecureHTTPLoads = true; } else if (!href.protocol && href.pathname.indexOf('*:/') === 0) { // wilcard in protocol retObj.NSExceptionAllowsInsecureHTTPLoads = true; } return retObj; } /* App Transport Security (ATS) writer from <access> and <allow-navigation> tags in config.xml */ function writeATSEntries (config) { var pObj = processAccessAndAllowNavigationEntries(config); var ats = {}; for (var hostname in pObj) { if (pObj.hasOwnProperty(hostname)) { var entry = pObj[hostname]; // Guiding principle: we only set values if they are available if (hostname === '*') { // always write this, for iOS 9, since in iOS 10 it will be overriden if // any of the other three keys are written ats['NSAllowsArbitraryLoads'] = true; // at least one of the overriding keys is present if (entry.NSAllowsArbitraryLoadsInWebContent) { ats['NSAllowsArbitraryLoadsInWebContent'] = true; } if (entry.NSAllowsArbitraryLoadsForMedia) { ats['NSAllowsArbitraryLoadsForMedia'] = true; } if (entry.NSAllowsLocalNetworking) { ats['NSAllowsLocalNetworking'] = true; } continue; } var exceptionDomain = {}; for (var key in entry) { if (entry.hasOwnProperty(key) && key !== 'Hostname') { exceptionDomain[key] = entry[key]; } } if (!ats['NSExceptionDomains']) { ats['NSExceptionDomains'] = {}; } ats['NSExceptionDomains'][hostname] = exceptionDomain; } } return ats; } function folderExists (folderPath) { try { var stat = fs.statSync(folderPath); return stat && stat.isDirectory(); } catch (e) { return false; } } // Construct a default value for CFBundleVersion as the version with any // -rclabel stripped=. function default_CFBundleVersion (version) { return version.split('-')[0]; } // Converts cordova specific representation of target device to XCode value function parseTargetDevicePreference (value) { if (!value) return null; var map = { 'universal': '"1,2"', 'handset': '"1"', 'tablet': '"2"' }; if (map[value.toLowerCase()]) { return map[value.toLowerCase()]; } events.emit('warn', 'Unrecognized value for target-device preference: ' + value + '.'); return null; }
{ "content_hash": "f7c8543b2c5bbf373ebc43a565518a5c", "timestamp": "", "source": "github", "line_count": 1155, "max_line_length": 221, "avg_line_length": 42.754978354978356, "alnum_prop": 0.6590458061641894, "repo_name": "shazron/cordova-ios", "id": "a15380ed618da18b7fce0f70513fca0f67c9f19b", "size": "50197", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bin/templates/scripts/cordova/lib/prepare.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "10594" }, { "name": "C", "bytes": "472" }, { "name": "CSS", "bytes": "3719" }, { "name": "CoffeeScript", "bytes": "3772" }, { "name": "HTML", "bytes": "5522" }, { "name": "JavaScript", "bytes": "331816" }, { "name": "MATLAB", "bytes": "383" }, { "name": "Objective-C", "bytes": "301785" }, { "name": "Python", "bytes": "3956" }, { "name": "Shell", "bytes": "11380" } ] }
* [#4464](https://github.com/bbatsov/rubocop/pull/4464): Add `EnforcedStyleForEmptyBraces` parameter to `Layout/SpaceBeforeBlockBraces` cop. ([@palkan][]) * [#4453](https://github.com/bbatsov/rubocop/pull/4453): New cop `Style/RedundantConditional` checks for conditionals that return true/false. ([@petehamilton][]) * [#4448](https://github.com/bbatsov/rubocop/pull/4448): Add new `TapFormatter`. ([@cyberdelia][]) * Add new `Style/HeredocDelimiters` cop. ([@drenmi][]) * [#4153](https://github.com/bbatsov/rubocop/issues/4153): New cop `Lint/ReturnInVoidContext` checks for the use of a return with a value in a context where it will be ignored. ([@harold-s][]) * Add auto-correct support to `Lint/ScriptPermission`. ([@rrosenblum][]) * [#4514](https://github.com/bbatsov/rubocop/pull/4514): Add configuration options to `Style/YodaCondition` to support checking all comparison operators or equality operators only. ([@smakagon][]) * Add new `Lint/BooleanSymbol` cop. ([@droptheplot][]) * Make `Rails/PluralizationGrammar` use singular methods for `-1` / `-1.0`. ([@promisedlandt][]) * [#4541](https://github.com/bbatsov/rubocop/pull/4541): Add new `Rails/HasManyOrHasOneDependent` cop. ([@oboxodo][]) * Add new `Style/Dir` cop. ([@drenmi][]) * Add new `Style/HeredocDelimiterCase` cop. ([@drenmi][]) * [#2943](https://github.com/bbatsov/rubocop/pull/2943): Add new `Lint/RescueWithoutErrorClass` cop. ([@drenmi][]) * [#4568](https://github.com/bbatsov/rubocop/pull/4568): Fix autocorrection for `Style/TrailingUnderscoreVariable`. ([@smakagon][]) * [#4586](https://github.com/bbatsov/rubocop/pull/4586): Add new `Performance/UnfreezeString` cop. ([@pocke][]) * [#2976](https://github.com/bbatsov/rubocop/issues/2976): Add `Whitelist` configuration option to `Style/NestedParenthesizedCalls` cop. ([@drenmi][]) * [#3965](https://github.com/bbatsov/rubocop/issues/3965): Add new `Style/DoublePipeEquals` cop. ([@donjar][]) * Make `rake new_cop` create parent directories if they do not already exist. ([@highb][]) * [#4368](https://github.com/bbatsov/rubocop/issues/4368): Make `Performance/HashEachMethod` inspect send nodes with any receiver. ([@gohdaniel15][]) * [#4508](https://github.com/bbatsov/rubocop/issues/4508): Add new `Style/ReturnNil` cop. ([@donjar][]) * [#4629](https://github.com/bbatsov/rubocop/issues/4629): Add Metrics/MethodLength cop for `define_method`. ([@jekuta][]) * [#4702](https://github.com/bbatsov/rubocop/pull/4702): Add new `Lint/UriEscapeUnescape` cop. ([@koic][]) * [#4696](https://github.com/bbatsov/rubocop/pull/4696): Add new `Performance/UriDefaultParser` cop. ([@koic][]) * [#4694](https://github.com/bbatsov/rubocop/pull/4694): Add new `Lint/UriRegexp` cop. ([@koic][]) * Add new `Style/MinMax` cop. ([@drenmi][]) * [#4720](https://github.com/bbatsov/rubocop/pull/4720): Add new `Bundler/InsecureProtocolSource` cop. ([@koic][]) * [#4708](https://github.com/bbatsov/rubocop/pull/4708): Add new `Lint/RedundantWithIndex` cop`. ([@koic][]) ### Bug fixes * [#4709](https://github.com/bbatsov/rubocop/pull/4709): Use cached remote config on network failure. ([@kristjan][]) * [#4688](https://github.com/bbatsov/rubocop/pull/4688): Accept yoda condition which isn't commutative. ([@fujimura][]) * [#4676](https://github.com/bbatsov/rubocop/issues/4676): Make `Style/RedundantConditional` cop work with elsif. ([@akhramov][]) * [#4656](https://github.com/bbatsov/rubocop/issues/4656): Modify `Style/ConditionalAssignment` autocorrection to work with unbracketed arrays. ([@akhramov][]) * [#4615](https://github.com/bbatsov/rubocop/pull/4615): Don't consider `<=>` a comparison method. ([@iGEL][]) * [#4664](https://github.com/bbatsov/rubocop/pull/4664): Fix typos in Rails/HttpPositionalArguments. ([@JoeCohen][]) * [#4618](https://github.com/bbatsov/rubocop/pull/4618): Fix `Lint/FormatParameterMismatch` false positive if format string includes `%%5B` (CGI encoded left bracket). ([@barthez][]) * [#4604](https://github.com/bbatsov/rubocop/pull/4604): Fix `Style/LambdaCall` to autocorrect `obj.call` to `obj.`. ([@iGEL][]) * [#4443](https://github.com/bbatsov/rubocop/pull/4443): Prevent `Style/YodaCondition` from breaking `not LITERAL`. ([@pocke][]) * [#4434](https://github.com/bbatsov/rubocop/issues/4434): Prevent bad auto-correct in `Style/Alias` for non-literal arguments. ([@drenmi][]) * [#4451](https://github.com/bbatsov/rubocop/issues/4451): Make `Style/AndOr` cop aware of comparison methods. ([@drenmi][]) * [#4457](https://github.com/bbatsov/rubocop/pull/4457): Fix false negative in `Lint/Void` with initialize and setter methods. ([@pocke][]) * [#4418](https://github.com/bbatsov/rubocop/issues/4418): Register an offense in `Style/ConditionalAssignment` when the assignment line is the longest line, and it does not exceed the max line length. ([@rrosenblum][]) * [#4491](https://github.com/bbatsov/rubocop/issues/4491): Prevent bad auto-correct in `Style/EmptyElse` for nested `if`. ([@pocke][]) * [#4485](https://github.com/bbatsov/rubocop/pull/4485): Handle 304 status for remote config files. ([@daniloisr][]) * [#4529](https://github.com/bbatsov/rubocop/pull/4529): Make `Lint/UnreachableCode` aware of `if` and `case`. ([@pocke][]) * [#4469](https://github.com/bbatsov/rubocop/issues/4469): Include permissions in file cache. ([@pocke][]) * [#4270](https://github.com/bbatsov/rubocop/issues/4270): Fix false positive in `Performance/RegexpMatch` for named captures. ([@pocke][]) * [#4525](https://github.com/bbatsov/rubocop/pull/4525): Fix regexp for checking comment config of `rubocop:disable all` in `Lint/UnneededDisable`. ([@meganemura][]) * [#4555](https://github.com/bbatsov/rubocop/issues/4555): Make `Style/VariableName` aware of optarg, kwarg and other arguments. ([@pocke][]) * [#4481](https://github.com/bbatsov/rubocop/issues/4481): Prevent `Style/WordArray` and `Style/SymbolArray` from registering offenses where percent arrays don't work. ([@drenmi][]) * [#4447](https://github.com/bbatsov/rubocop/issues/4447): Prevent `Layout/EmptyLineBetweenDefs` from removing too many lines. ([@drenmi][]) * [#3892](https://github.com/bbatsov/rubocop/issues/3892): Make `Style/NumericPredicate` ignore numeric comparison of global variables. ([@drenmi][]) * [#4101](https://github.com/bbatsov/rubocop/issues/4101): Skip auto-correct for literals with trailing comment and chained method call in `Layout/Multiline*BraceLayout`. ([@jonas054][]) * [#4518](https://github.com/bbatsov/rubocop/issues/4518): Fix bug where `Style/SafeNavigation` does not register an offense when there are chained method calls. ([@rrosenblum][]) * [#3040](https://github.com/bbatsov/rubocop/issues/3040): Ignore safe navigation in `Rails/Delegate`. ([@cgriego][]) * [#4587](https://github.com/bbatsov/rubocop/pull/4587): Fix false negative for void unary operators in `Lint/Void` cop. ([@pocke][]) * [#4589](https://github.com/bbatsov/rubocop/issues/4589): Fix false positive in `Performance/RegexpMatch` cop for `=~` is in a class method. ([@pocke][]) * [#4578](https://github.com/bbatsov/rubocop/issues/4578): Fix false positive in `Lint/FormatParameterMismatch` for format with "asterisk" (`*`) width and precision. ([@smakagon][]) * [#4285](https://github.com/bbatsov/rubocop/issues/4285): Make `Lint/DefEndAlignment` aware of multiple modifiers. ([@drenmi][]) * [#4634](https://github.com/bbatsov/rubocop/issues/4634): Handle heredoc that contains empty lines only in `Layout/IndentHeredoc` cop. ([@pocke][]) * [#4646](https://github.com/bbatsov/rubocop/issues/4646): Make `Lint/Debugger` aware of `Kernel` and cbase. ([@pocke][]) * [#4643](https://github.com/bbatsov/rubocop/issues/4643): Modify `Style/InverseMethods` to not register a separate offense for an inverse method nested inside of the block of an inverse method offense. ([@rrosenblum][]) * [#4593](https://github.com/bbatsov/rubocop/issues/4593): Fix false positive in `Rails/SaveBang` when `save/update_attribute` is used with a `case` statement. ([@theRealNG][]) * [#4322](https://github.com/bbatsov/rubocop/issues/4322): Fix Style/MultilineMemoization from autocorrecting to invalid ruby. ([@dpostorivo][]) * [#4722](https://github.com/bbatsov/rubocop/pull/4722): Fix `rake new_cop` problem that doesn't add `require` line. ([@koic][]) * [#4723](https://github.com/bbatsov/rubocop/issues/4723): Fix `RaiseArgs` auto-correction issue for `raise` with 3 arguments. ([@smakagon][]) ### Changes * [#4470](https://github.com/bbatsov/rubocop/issues/4470): Improve the error message for `Lint/AssignmentInCondition`. ([@brandonweiss][]) * [#4553](https://github.com/bbatsov/rubocop/issues/4553): Add `node_modules` to default excludes. ([@iainbeeston][]) * [#4445](https://github.com/bbatsov/rubocop/pull/4445): Make `Style/Encoding` cop enabled by default. ([@deivid-rodriguez][]) * [#4452](https://github.com/bbatsov/rubocop/pull/4452): Add option to `Rails/Delegate` for enforcing the prefixed method name case. ([@klesse413][]) * [#4493](https://github.com/bbatsov/rubocop/pull/4493): Make `Lint/Void` cop aware of `Enumerable#each` and `for`. ([@pocke][]) * [#4492](https://github.com/bbatsov/rubocop/pull/4492): Make `Lint/DuplicateMethods` aware of `alias` and `alias_method`. ([@pocke][]) * [#4478](https://github.com/bbatsov/rubocop/issues/4478): Fix confusing message of `Performance/Caller` cop. ([@pocke][]) * [#4543](https://github.com/bbatsov/rubocop/pull/4543): Make `Lint/DuplicateMethods` aware of `attr_*` methods. ([@pocke][]) * [#4550](https://github.com/bbatsov/rubocop/pull/4550): Mark `RuboCop::CLI#run` as a public API. ([@yujinakayama][]) * [#4551](https://github.com/bbatsov/rubocop/pull/4551): Make `Performance/Caller` aware of `caller_locations`. ([@pocke][]) * Rename `Style/HeredocDelimiters` to `Style/HeredocDelimiterNaming`. ([@drenmi][]) * [#4157](https://github.com/bbatsov/rubocop/issues/4157): Enhance offense message for `Style/RedudantReturn` cop. ([@gohdaniel15][]) * [#4521](https://github.com/bbatsov/rubocop/issues/4521): Move naming related cops into their own `Naming` department. ([@drenmi][]) * [#4600](https://github.com/bbatsov/rubocop/pull/4600): Make `Style/RedundantSelf` aware of arguments of a block. ([@Envek][]) * [#4658](https://github.com/bbatsov/rubocop/issues/4658): Disable auto-correction for `Performance/TimesMap` by default. ([@Envek][]) [@palkan]: https://github.com/palkan [@petehamilton]: https://github.com/petehamilton [@cyberdelia]: https://github.com/cyberdelia [@drenmi]: https://github.com/drenmi [@harold-s]: https://github.com/harold-s [@rrosenblum]: https://github.com/rrosenblum [@smakagon]: https://github.com/smakagon [@droptheplot]: https://github.com/droptheplot [@promisedlandt]: https://github.com/promisedlandt [@oboxodo]: https://github.com/oboxodo [@pocke]: https://github.com/pocke [@donjar]: https://github.com/donjar [@highb]: https://github.com/highb [@gohdaniel15]: https://github.com/gohdaniel15 [@jekuta]: https://github.com/jekuta [@koic]: https://github.com/koic [@kristjan]: https://github.com/kristjan [@fujimura]: https://github.com/fujimura [@akhramov]: https://github.com/akhramov [@iGEL]: https://github.com/iGEL [@JoeCohen]: https://github.com/JoeCohen [@barthez]: https://github.com/barthez [@daniloisr]: https://github.com/daniloisr [@meganemura]: https://github.com/meganemura [@jonas054]: https://github.com/jonas054 [@cgriego]: https://github.com/cgriego [@theRealNG]: https://github.com/theRealNG [@dpostorivo]: https://github.com/dpostorivo [@brandonweiss]: https://github.com/brandonweiss [@iainbeeston]: https://github.com/iainbeeston [@deivid-rodriguez]: https://github.com/deivid-rodriguez [@klesse413]: https://github.com/klesse413 [@yujinakayama]: https://github.com/yujinakayama [@Envek]: https://github.com/Envek
{ "content_hash": "5fb1a6fdf76c9138653a7e3470c10fea", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 220, "avg_line_length": 97.85833333333333, "alnum_prop": 0.7240057906838117, "repo_name": "pocke/rubocop", "id": "11d658389b0d42c88316c6720d4cd6187396fcac", "size": "11761", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "relnotes/v0.50.0.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "355" }, { "name": "HTML", "bytes": "7106" }, { "name": "Ruby", "bytes": "4489361" } ] }
{-| Module : Day10 Description : <http://adventofcode.com/2016/day/10 Day 10: Balance Bots> -} {-# LANGUAGE RecordWildCards, ViewPatterns #-} {-# OPTIONS_HADDOCK ignore-exports #-} module Day10 (main) where import Common (readDataFile) import Data.Char (isDigit) import Data.Either (partitionEithers) import Data.List (sort) import Data.Map.Strict (Map, assocs, empty, insert, insertWith, lookup) import Prelude hiding (lookup) import System.IO.Unsafe (unsafePerformIO) import Text.ParserCombinators.ReadP (ReadP, (+++), munch, readP_to_S, string) input :: [String] input = lines $ unsafePerformIO $ readDataFile "day10.txt" data Initial i e = Initial { bot :: i, value :: e } data Instruction i j = Instruction { src :: i, low :: Either i j, high :: Either i j } parse :: (Read i, Read j, Read e) => ReadP (Either (Initial i e) (Instruction i j)) parse = (Left <$> initial) +++ (Right <$> instruction) where initial = do value <- string "value " >> read <$> munch isDigit bot <- string " goes to bot " >> read <$> munch isDigit return Initial {..} instruction = do src <- parseBot <* string " gives low to " low <- (Left <$> parseBot) +++ (Right <$> parseOutput) string " and high to " high <- (Left <$> parseBot) +++ (Right <$> parseOutput) return Instruction {..} parseBot = string "bot " >> read <$> munch isDigit parseOutput = string "output " >> read <$> munch isDigit insertSorted :: (Ord i, Ord e) => e -> i -> Map i [e] -> Map i [e] insertSorted e i = insertWith ((.) sort . (++)) i [e] initialize :: (Ord i, Ord e) => [Initial i e] -> Map i [e] initialize = foldr (\Initial {..} -> insertSorted value bot) empty step :: (Ord i, Ord j, Ord e) => [Instruction i j] -> (Map i [e], Map j [e]) -> (Map i [e], Map j [e]) step instructions (bots, outputs) = foldr emit (bots', outputs) targets where (foldr (uncurry insert) bots -> bots', concat -> targets) = unzip [ ((bot, rest), [(low, value0), (high, value1)]) | Instruction {src = bot@((`lookup` bots) -> Just (value0:value1:rest)), ..} <- instructions ] emit (Left bot, value) (bots, outputs) = (insertSorted value bot bots, outputs) emit (Right output, value) (bots, outputs) = (bots, insertSorted value output outputs) main :: IO () main = do let get (readP_to_S parse -> (i, ""):_) = i :: Either (Initial Int Int) (Instruction Int Int) (setup, instructions) = partitionEithers $ map get input (bots, outputs) = unzip $ iterate (step instructions) (initialize setup, empty) print $ fst $ head $ bots >>= filter ((==) [17, 61] . snd) . assocs print $ head [ value0 * value1 * value2 | Just (value0:_) <- lookup 0 <$> outputs , Just (value1:_) <- lookup 1 <$> outputs , Just (value2:_) <- lookup 2 <$> outputs ]
{ "content_hash": "a250129167d353284e3c4271250fb69e", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 98, "avg_line_length": 43.27272727272727, "alnum_prop": 0.6116946778711485, "repo_name": "ephemient/aoc2016", "id": "a6227663f858879e0d16764eb5e9a197cb481b85", "size": "2856", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/Day10.hs", "mode": "33188", "license": "mit", "language": [ { "name": "Haskell", "bytes": "58479" } ] }
import { httpBackend } from 'api/common/http-backend' import { NEVER, Observable } from 'rxjs' import { tap } from 'rxjs/operators' import { AppConfig } from './config.types' export { AppConfig } let configValue: AppConfig | null = null export function config(): Readonly<AppConfig> { if (configValue) { return configValue } throw new Error('Assertion error: attempt to config access before loading') } export const CONFIG_URL = 'config.json' export function initializeConfig(): Observable<unknown> { if (configValue) { // eslint-disable-next-line no-console -- here console is ok console.warn('app config already loaded') return NEVER } return httpBackend .request<AppConfig>({ method: 'GET', url: CONFIG_URL, }) .pipe( tap(resp => { configValue = resp.body }) ) }
{ "content_hash": "9dbcbeed431f6bfb1d7777903e2ec3b3", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 79, "avg_line_length": 25.666666666666668, "alnum_prop": 0.6093073593073594, "repo_name": "rodmax/react-playground", "id": "09bd2132734d89f2cbb94731599064ca01936ee0", "size": "924", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/modules/core/config/config.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "102" }, { "name": "EJS", "bytes": "307" }, { "name": "HTML", "bytes": "363" }, { "name": "Handlebars", "bytes": "2153" }, { "name": "JavaScript", "bytes": "26910" }, { "name": "SCSS", "bytes": "4202" }, { "name": "Shell", "bytes": "1380" }, { "name": "TypeScript", "bytes": "73516" } ] }
@import url('https://fonts.googleapis.com/css?family=Open+Sans:300,400,700'); body { width:100%; height:100%; font-family: 'Open Sans', sans-serif; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .btn { background: #2B9AF3; color: #fff; font-size: 13px; padding: 12px 30px; border-radius: 30px; border: none; transition: all 2s ease; } .btn:hover, .btn:focus { background: #2586d4; color:#fff; outline: none; } .ucTabBtnGroup .btn-default, .ucTabBtnGroup .btn-default:hover, .ucTabBtnGroup .btn-default:focus { background-color: #FFFFFF; border: 1px solid #CCCCCC; } .ucTabBtnGroup .btn-default.active { background-color: #2586d4; } .UC_SetupContainerCls { width: 1000px; overflow: hidden; transform: translateX(-50%) translateY(-50%); position: absolute; top: 50%; left: 50%; } .input-container { margin-top:10px; } /* form { margin: 0 auto; width: 300px; margin-top: 300px; } */ .UC_SetupContainerCls { display: none; } .ucSetupProgressSteps { margin: 80px 0; padding: 0; } .ucSetupProgressSteps li { display: inline-block; list-style: none; text-align: center; position: relative; color: #9ea1a2; font-weight:300; padding: 0 45px; } .ucSetupProgressSteps li:first-child { padding-left:0; } .ucSetupProgressSteps li:last-child { padding-right:0; } .ucSetupProgressSteps li span { display: block; width: 40px; height: 40px; border: 2px solid #e8eced; background:#fff; margin: 0 auto; line-height: 38px; border-radius: 50%; margin-bottom: 10px; } .ucSetupProgressSteps li.active span { border-color: #2B9AF3; color: #2B9AF3; font-weight: 500; } .ucSetupProgressSteps li.active { color: #2B9AF3; } .ucSetupProgressSteps li:after { content: ''; width: 125%; height: 2px; background: #e8eced; position: absolute; left: -50%; top: 20px; z-index: -1; } .ucSetupProgressSteps li:first-child:after { width:0%; } .ucWelcomeContent { padding:50px 30px; text-align:center; } .ucWelcomeContent img { margin:0 auto; display: block; } .ucWelcomeContent h2 { font-weight: 400; text-align: center; } .ucWelcomeContent h5 { font-weight: 400; color: #a4aeba; font-style: italic; text-align: center; } .ucWelcomeContent p { font-size:13px; line-height:22px; text-align:center; margin: 25px 0; } .ucSetupProgressStepsWrapper { width:1000px; margin:0 auto; position: relative; } .ucCopyright { text-align: center; position: absolute; bottom: 30px; left: 0; right: 0; } #UC_Setup_Database h2, #UC_Setup_SMTP h2, #UC_Setup_User h2, #UC_Setup_App h2 { font-size:32px; font-weight:300; color: #788f9d; text-align: center; margin: 0 auto 30px; } .UC_SetupContainerCls input[type="text"], .UC_SetupContainerCls input[type="email"], .UC_SetupContainerCls input[type="password"] { border:none; border-bottom: 1px solid #e8eced; box-shadow: none; border-radius: 0; font-weight: 400; font-size: 13px; text-align: left; margin-bottom: 5px; } .UC_SetupContainerCls .form-group .btn { margin: 10px 0; padding: 8px 30px !important; } .UC_SetupLogo { text-align: center; } .UC_SetupLogo img { margin-bottom: 20px; } .UC_SetupLogo.mongoDB img { width: 150px; margin-bottom: 10px; }
{ "content_hash": "fe08aa5704d22840e6fe23c643931c92", "timestamp": "", "source": "github", "line_count": 211, "max_line_length": 129, "avg_line_length": 15.957345971563981, "alnum_prop": 0.675081675081675, "repo_name": "produle/usercomio", "id": "7105699bf82249b7a860d58ed05c2a5525e81470", "size": "3502", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "WebContent/css/internal/usersetup.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "61342" }, { "name": "HTML", "bytes": "94615" }, { "name": "JavaScript", "bytes": "317142" }, { "name": "Shell", "bytes": "495" } ] }
using System; namespace Microsoft.TeamFoundation.WorkItemTracking.Client { public static class DataTypeConverter { public static object Convert(string value, string type) { switch (type) { case "System.Int32": return System.Convert.ToInt32(value); case "System.Boolean": return string.Equals(value.ToLowerInvariant(), "true"); case "System.Guid": return Guid.ParseExact(value, "N"); case "System.DateTime": return DateTime.Parse(value); default: return value; } } } }
{ "content_hash": "12ba2afc18848dd2e44870a738f34fb6", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 75, "avg_line_length": 28.88, "alnum_prop": 0.5, "repo_name": "Indomitable/monodevelop-tfs-addin", "id": "b02a5e1c83ee5e18cfe8f595f323ae6667b7bb8b", "size": "1943", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "MonoDevelop.VersionControl.TFS/Microsoft.TeamFoundation.WorkItemTracking.Client/DataTypeConverter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "896243" } ] }
"""Tests for the boolean substitution classes.""" from launch import LaunchContext from launch.substitutions import AllSubstitution from launch.substitutions import AndSubstitution from launch.substitutions import AnySubstitution from launch.substitutions import NotSubstitution from launch.substitutions import OrSubstitution from launch.substitutions.substitution_failure import SubstitutionFailure import pytest def test_not_substitution(): lc = LaunchContext() assert NotSubstitution('true').perform(lc) == 'false' assert NotSubstitution('false').perform(lc) == 'true' assert NotSubstitution('1').perform(lc) == 'false' assert NotSubstitution('0').perform(lc) == 'true' with pytest.raises(SubstitutionFailure): NotSubstitution('not-condition-expression').perform(lc) def test_and_substitution(): lc = LaunchContext() assert AndSubstitution('true', 'true').perform(lc) == 'true' assert AndSubstitution('true', 'false').perform(lc) == 'false' assert AndSubstitution('false', 'true').perform(lc) == 'false' assert AndSubstitution('false', 'false').perform(lc) == 'false' assert AndSubstitution('true', '1').perform(lc) == 'true' assert AndSubstitution('true', '0').perform(lc) == 'false' assert AndSubstitution('false', '1').perform(lc) == 'false' assert AndSubstitution('false', '0').perform(lc) == 'false' assert AndSubstitution('1', 'true').perform(lc) == 'true' assert AndSubstitution('1', 'false').perform(lc) == 'false' assert AndSubstitution('0', 'true').perform(lc) == 'false' assert AndSubstitution('0', 'false').perform(lc) == 'false' assert AndSubstitution('1', '1').perform(lc) == 'true' assert AndSubstitution('1', '0').perform(lc) == 'false' assert AndSubstitution('0', '1').perform(lc) == 'false' assert AndSubstitution('0', '0').perform(lc) == 'false' with pytest.raises(SubstitutionFailure): AndSubstitution('not-condition-expression', 'true').perform(lc) with pytest.raises(SubstitutionFailure): AndSubstitution('true', 'not-condition-expression').perform(lc) def test_or_substitution(): lc = LaunchContext() assert OrSubstitution('true', 'true').perform(lc) == 'true' assert OrSubstitution('true', 'false').perform(lc) == 'true' assert OrSubstitution('false', 'true').perform(lc) == 'true' assert OrSubstitution('false', 'false').perform(lc) == 'false' assert OrSubstitution('true', '1').perform(lc) == 'true' assert OrSubstitution('true', '0').perform(lc) == 'true' assert OrSubstitution('false', '1').perform(lc) == 'true' assert OrSubstitution('false', '0').perform(lc) == 'false' assert OrSubstitution('1', 'true').perform(lc) == 'true' assert OrSubstitution('1', 'false').perform(lc) == 'true' assert OrSubstitution('0', 'true').perform(lc) == 'true' assert OrSubstitution('0', 'false').perform(lc) == 'false' assert OrSubstitution('1', '1').perform(lc) == 'true' assert OrSubstitution('1', '0').perform(lc) == 'true' assert OrSubstitution('0', '1').perform(lc) == 'true' assert OrSubstitution('0', '0').perform(lc) == 'false' with pytest.raises(SubstitutionFailure): OrSubstitution('not-condition-expression', 'true').perform(lc) with pytest.raises(SubstitutionFailure): OrSubstitution('true', 'not-condition-expression').perform(lc) def test_any_substitution(): lc = LaunchContext() assert AnySubstitution().perform(lc) == 'false' assert AnySubstitution('true').perform(lc) == 'true' assert AnySubstitution('false').perform(lc) == 'false' assert AnySubstitution('true', 'true').perform(lc) == 'true' assert AnySubstitution('true', 'false').perform(lc) == 'true' assert AnySubstitution('false', 'true').perform(lc) == 'true' assert AnySubstitution('false', 'false').perform(lc) == 'false' assert AnySubstitution('true', 'true', 'true').perform(lc) == 'true' assert AnySubstitution('true', 'true', 'false').perform(lc) == 'true' assert AnySubstitution('false', 'false', 'false').perform(lc) == 'false' assert AnySubstitution('1').perform(lc) == 'true' assert AnySubstitution('0').perform(lc) == 'false' assert AnySubstitution('1', 'true').perform(lc) == 'true' assert AnySubstitution('1', 'false').perform(lc) == 'true' assert AnySubstitution('0', 'true').perform(lc) == 'true' assert AnySubstitution('0', 'false').perform(lc) == 'false' assert AnySubstitution('1', 'true', 'true').perform(lc) == 'true' assert AnySubstitution('1', 'true', 'false').perform(lc) == 'true' assert AnySubstitution('true', 'true', '0').perform(lc) == 'true' assert AnySubstitution('0', 'false', 'false').perform(lc) == 'false' with pytest.raises(SubstitutionFailure): AnySubstitution('not-condition-expression', 'true').perform(lc) with pytest.raises(SubstitutionFailure): AnySubstitution('true', 'not-condition-expression').perform(lc) def test_all_substitution(): lc = LaunchContext() assert AllSubstitution().perform(lc) == 'true' assert AllSubstitution('true').perform(lc) == 'true' assert AllSubstitution('false').perform(lc) == 'false' assert AllSubstitution('true', 'true').perform(lc) == 'true' assert AllSubstitution('true', 'false').perform(lc) == 'false' assert AllSubstitution('false', 'true').perform(lc) == 'false' assert AllSubstitution('false', 'false').perform(lc) == 'false' assert AllSubstitution('true', 'true', 'true').perform(lc) == 'true' assert AllSubstitution('true', 'true', 'false').perform(lc) == 'false' assert AllSubstitution('false', 'false', 'false').perform(lc) == 'false' assert AllSubstitution('1').perform(lc) == 'true' assert AllSubstitution('0').perform(lc) == 'false' assert AllSubstitution('1', 'true').perform(lc) == 'true' assert AllSubstitution('1', 'false').perform(lc) == 'false' assert AllSubstitution('0', 'true').perform(lc) == 'false' assert AllSubstitution('0', 'false').perform(lc) == 'false' assert AllSubstitution('1', 'true', 'true').perform(lc) == 'true' assert AllSubstitution('1', 'true', 'false').perform(lc) == 'false' assert AllSubstitution('true', 'true', '0').perform(lc) == 'false' assert AllSubstitution('0', 'false', 'false').perform(lc) == 'false' with pytest.raises(SubstitutionFailure): AllSubstitution('not-condition-expression', 'true').perform(lc) with pytest.raises(SubstitutionFailure): AllSubstitution('true', 'not-condition-expression').perform(lc)
{ "content_hash": "5328e6981ee75d9677b76fb634b952ff", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 76, "avg_line_length": 47.71739130434783, "alnum_prop": 0.6675778283978739, "repo_name": "ros2/launch", "id": "7a2679b719fb64bfcc775fa4252eeda6f7004b43", "size": "7187", "binary": false, "copies": "1", "ref": "refs/heads/rolling", "path": "launch/test/launch/substitutions/test_boolean_substitution.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "857" }, { "name": "C++", "bytes": "1468" }, { "name": "CMake", "bytes": "8807" }, { "name": "Makefile", "bytes": "607" }, { "name": "Python", "bytes": "1063971" }, { "name": "Shell", "bytes": "85" } ] }
require_relative 'preflight_checks' class BookshelfPreflightValidator < PreflightValidator attr_reader :user_attrs, :node_attrs def initialize(node) super @user_attrs = PrivateChef['bookshelf'] @node_attrs = node['private_chef']['bookshelf'] end def run! verify_storage_type_unchanged end # 5 Cases # (1) First install, anything goes => OK # (2) An old storage type was not set and the new_storage_type is :filesystem => OK # (3) An old storage type was not set and the new_storage_type is :sql => NOT_OK # (4) An old storage type was set and is not equal to the new storage type => NOT_OK # (5) An old storage type was set and is equal to the new storage type => OK def verify_storage_type_unchanged if previous_run.nil? # case (1) true else previous_value = previous_run['bookshelf']['storage_type'] current_value = (user_attrs['storage_type'] || 'filesystem').to_s if previous_value.nil? && current_value == 'filesystem' # case (2) true elsif previous_value.nil? && current_value != 'filesystem' # case (3) fail_with <<~EOM Bookshelf's storage_type was previously the default of 'filesystem'; however the current configuration would result in a value of '#{current_value}'. At this time it is not possible to change the bookshelf storage_type post-installation. Please set bookshelf['storage_type'] = 'filesystem' in /etc/#{ChefUtils::Dist::Org::LEGACY_CONF_DIR}/#{ChefUtils::Dist::Server::SERVER}.rb or leave it unset. EOM elsif previous_value.to_s == current_value # case (5) true else # everything else is invalid, including case 4 above fail_with <<~EOM Bookshelf's storage_type was previously '#{previous_value}'; however the current configuration would result in a value of '#{current_value}'. At this time it is not possible to change the bookshelf storage_type post-installation. Please set bookshelf['storage_type'] = '#{previous_value}' in /etc/#{ChefUtils::Dist::Org::LEGACY_CONF_DIR}/#{ChefUtils::Dist::Server::SERVER}.rb EOM end end end end
{ "content_hash": "eb07db2fa84d78ab8d81b310f6106e06", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 115, "avg_line_length": 35.171875, "alnum_prop": 0.6463793869391382, "repo_name": "chef/chef-server", "id": "3a89ca128f8ad9aa77fd7855d2083cbef5ddd8e4", "size": "2833", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "omnibus/files/server-ctl-cookbooks/infra-server/libraries/preflight_bookshelf_validator.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "18719" }, { "name": "Erlang", "bytes": "2517983" }, { "name": "Go", "bytes": "99" }, { "name": "HTML", "bytes": "139644" }, { "name": "JavaScript", "bytes": "4396" }, { "name": "Lua", "bytes": "56683" }, { "name": "Makefile", "bytes": "34225" }, { "name": "PLpgSQL", "bytes": "186350" }, { "name": "R", "bytes": "6225" }, { "name": "RAML", "bytes": "2130" }, { "name": "Ruby", "bytes": "2374906" }, { "name": "SCSS", "bytes": "208826" }, { "name": "Shell", "bytes": "111662" } ] }
<?php require_once 'AbstractPipeStackConfig.php'; class DevPipeStackConfig extends AbstractPipeStackConfig { protected $clientId = 'YOUR DEV CLIENT ID GOES HERE'; protected $clientSecret = 'YOUR DEV CLIENT SECRET GOES HERE'; protected $accessToken = 'YOUR DEV ACCESS TOKEN GOES HERE'; protected $protocol = 'http://'; protected $hostname = 'apisandbox.pipestack.com'; protected $format = 'json'; protected $timeout = 20; }
{ "content_hash": "e3feae497d59c52a7ff235853d8c50a4", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 65, "avg_line_length": 21.904761904761905, "alnum_prop": 0.7043478260869566, "repo_name": "bva100/cms", "id": "75309a97e9c0460de0b9346523c98f58fb78e8be", "size": "460", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/pipestack-sdk-php-master/sdk/Config/DevPipeStackConfig.php", "mode": "33188", "license": "mit", "language": [ { "name": "ABAP", "bytes": "962" }, { "name": "ActionScript", "bytes": "1133" }, { "name": "Assembly", "bytes": "506" }, { "name": "AutoHotkey", "bytes": "720" }, { "name": "C", "bytes": "512" }, { "name": "C#", "bytes": "83" }, { "name": "C++", "bytes": "761" }, { "name": "CSS", "bytes": "519509" }, { "name": "Clojure", "bytes": "794" }, { "name": "CoffeeScript", "bytes": "403" }, { "name": "ColdFusion", "bytes": "86" }, { "name": "Common Lisp", "bytes": "632" }, { "name": "DOT", "bytes": "5910" }, { "name": "Dart", "bytes": "984" }, { "name": "Erlang", "bytes": "1977" }, { "name": "Go", "bytes": "641" }, { "name": "Groovy", "bytes": "1080" }, { "name": "Haskell", "bytes": "512" }, { "name": "Haxe", "bytes": "447" }, { "name": "Java", "bytes": "396" }, { "name": "JavaScript", "bytes": "19663942" }, { "name": "Julia", "bytes": "202" }, { "name": "LiveScript", "bytes": "5747" }, { "name": "Lua", "bytes": "981" }, { "name": "OCaml", "bytes": "539" }, { "name": "Objective-C", "bytes": "2672" }, { "name": "PHP", "bytes": "564675" }, { "name": "Pascal", "bytes": "1412" }, { "name": "Perl", "bytes": "3068" }, { "name": "PowerShell", "bytes": "418" }, { "name": "Python", "bytes": "478" }, { "name": "R", "bytes": "668" }, { "name": "Ruby", "bytes": "531" }, { "name": "Rust", "bytes": "495" }, { "name": "Scala", "bytes": "1541" }, { "name": "Scheme", "bytes": "559" }, { "name": "Shell", "bytes": "6378" }, { "name": "Tcl", "bytes": "899" }, { "name": "TypeScript", "bytes": "1607" }, { "name": "Visual Basic", "bytes": "916" }, { "name": "XQuery", "bytes": "114" } ] }
using System.Data.Entity; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace Scoala.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } }
{ "content_hash": "59f158e04dffbed570997084267a2b3e", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 175, "avg_line_length": 36.45454545454545, "alnum_prop": 0.7057356608478803, "repo_name": "claupcv/Internship", "id": "9b3989576558dcb0266c3d4a193050092d36f9d7", "size": "1205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "claupcv/2016/December/Scoala/Models/IdentityModels.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "97" }, { "name": "C#", "bytes": "407304" }, { "name": "CSS", "bytes": "1231" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "21071" }, { "name": "PLpgSQL", "bytes": "488" }, { "name": "PowerShell", "bytes": "101582" }, { "name": "Ruby", "bytes": "1030" } ] }
class Foo_Test: def test_foo(self): pass def test_bar(self): pass
{ "content_hash": "5003c785d37fe4bda07432d1c01c8ace", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 23, "avg_line_length": 13.714285714285714, "alnum_prop": 0.5, "repo_name": "cloudera/hue", "id": "5a629d3063eff9196a120c944ed326c5703c93d0", "size": "96", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "desktop/core/ext-py/nose-1.3.7/unit_tests/support/issue270/foo_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ABAP", "bytes": "962" }, { "name": "ActionScript", "bytes": "1133" }, { "name": "Ada", "bytes": "99" }, { "name": "Assembly", "bytes": "2347" }, { "name": "AutoHotkey", "bytes": "720" }, { "name": "BASIC", "bytes": "2884" }, { "name": "Batchfile", "bytes": "143575" }, { "name": "C", "bytes": "5129166" }, { "name": "C#", "bytes": "83" }, { "name": "C++", "bytes": "718011" }, { "name": "COBOL", "bytes": "4" }, { "name": "CSS", "bytes": "680715" }, { "name": "Cirru", "bytes": "520" }, { "name": "Clojure", "bytes": "794" }, { "name": "Closure Templates", "bytes": "1072" }, { "name": "CoffeeScript", "bytes": "403" }, { "name": "ColdFusion", "bytes": "86" }, { "name": "Common Lisp", "bytes": "632" }, { "name": "Cython", "bytes": "1016963" }, { "name": "D", "bytes": "324" }, { "name": "Dart", "bytes": "489" }, { "name": "Dockerfile", "bytes": "13576" }, { "name": "EJS", "bytes": "752" }, { "name": "Eiffel", "bytes": "375" }, { "name": "Elixir", "bytes": "692" }, { "name": "Elm", "bytes": "487" }, { "name": "Emacs Lisp", "bytes": "411907" }, { "name": "Erlang", "bytes": "487" }, { "name": "Forth", "bytes": "979" }, { "name": "FreeMarker", "bytes": "1017" }, { "name": "G-code", "bytes": "521" }, { "name": "GAP", "bytes": "29873" }, { "name": "GLSL", "bytes": "512" }, { "name": "Genshi", "bytes": "946" }, { "name": "Gherkin", "bytes": "699" }, { "name": "Go", "bytes": "641" }, { "name": "Groovy", "bytes": "1080" }, { "name": "HTML", "bytes": "28328425" }, { "name": "Haml", "bytes": "920" }, { "name": "Handlebars", "bytes": "173" }, { "name": "Haskell", "bytes": "512" }, { "name": "Haxe", "bytes": "447" }, { "name": "HiveQL", "bytes": "43" }, { "name": "Io", "bytes": "140" }, { "name": "Java", "bytes": "457398" }, { "name": "JavaScript", "bytes": "39181239" }, { "name": "Jinja", "bytes": "356" }, { "name": "Julia", "bytes": "210" }, { "name": "LSL", "bytes": "2080" }, { "name": "Lean", "bytes": "213" }, { "name": "Less", "bytes": "396102" }, { "name": "Lex", "bytes": "218764" }, { "name": "Liquid", "bytes": "1883" }, { "name": "LiveScript", "bytes": "5747" }, { "name": "Lua", "bytes": "78382" }, { "name": "M4", "bytes": "1751" }, { "name": "MATLAB", "bytes": "203" }, { "name": "Makefile", "bytes": "1025937" }, { "name": "Mako", "bytes": "3644004" }, { "name": "Mask", "bytes": "597" }, { "name": "Myghty", "bytes": "936" }, { "name": "Nix", "bytes": "2212" }, { "name": "OCaml", "bytes": "539" }, { "name": "Objective-C", "bytes": "2672" }, { "name": "OpenSCAD", "bytes": "333" }, { "name": "PHP", "bytes": "662" }, { "name": "PLSQL", "bytes": "29403" }, { "name": "PLpgSQL", "bytes": "6006" }, { "name": "Pascal", "bytes": "84273" }, { "name": "Perl", "bytes": "4327" }, { "name": "PigLatin", "bytes": "371" }, { "name": "PowerShell", "bytes": "6235" }, { "name": "Procfile", "bytes": "47" }, { "name": "Pug", "bytes": "584" }, { "name": "Python", "bytes": "92881549" }, { "name": "R", "bytes": "2445" }, { "name": "Roff", "bytes": "484108" }, { "name": "Ruby", "bytes": "1098" }, { "name": "Rust", "bytes": "495" }, { "name": "SCSS", "bytes": "78508" }, { "name": "Sass", "bytes": "770" }, { "name": "Scala", "bytes": "1541" }, { "name": "Scheme", "bytes": "559" }, { "name": "Shell", "bytes": "249165" }, { "name": "Smarty", "bytes": "130" }, { "name": "SourcePawn", "bytes": "948" }, { "name": "Stylus", "bytes": "682" }, { "name": "Tcl", "bytes": "899" }, { "name": "TeX", "bytes": "165743" }, { "name": "Thrift", "bytes": "341963" }, { "name": "Twig", "bytes": "761" }, { "name": "TypeScript", "bytes": "1241396" }, { "name": "VBScript", "bytes": "938" }, { "name": "VHDL", "bytes": "830" }, { "name": "Vala", "bytes": "485" }, { "name": "Verilog", "bytes": "274" }, { "name": "Vim Snippet", "bytes": "226931" }, { "name": "Vue", "bytes": "350385" }, { "name": "XQuery", "bytes": "114" }, { "name": "XSLT", "bytes": "522199" }, { "name": "Yacc", "bytes": "1070437" }, { "name": "jq", "bytes": "4" } ] }
import {expect} from 'chai'; import * as sinon from 'sinon'; import {PromiseResponseWrapper} from '../../../lib/promise-response/promise-response.wrapper'; import {Response} from '../../../lib/promise-response/response'; describe('PromiseResponseWrapper', () => { let middleware: (req: any, res: any, next: () => void) => void, handler: Sinon.SinonStub, log: any, req: any, res: any, next: any; function expectResponseNotToHaveBeenTouched(): void { expect(res.status).not.to.have.been.called; expect(res.end).not.to.have.been.called; expectNoContentToHaveBeenSent(); } function expectNoContentToHaveBeenSent(): void { expect(res.send).not.to.have.been.called; expect(res.json).not.to.have.been.called; } function waitForResponseEnd(): Promise<void> { if (res.end.calledOnce) { return Promise.resolve(); } return new Promise<void>((resolve) => { res.end = sinon.spy(() => { resolve(); }); }); } beforeEach(() => { log = { warn: sinon.stub(), error: sinon.stub() }; handler = sinon.stub(); req = { url: 'incoming' }; // Content is irrelevant, this is a placeholder res = {}; res.status = sinon.stub().returns(res); res.send = sinon.stub().returns(res); res.json = sinon.stub().returns(res); res.end = sinon.stub(); next = sinon.stub(); const factory = new PromiseResponseWrapper(); factory.setLogger(log); middleware = factory.wrap(handler); }); it('should call the handler with res, req, and next when the middleware is called', () => { // Code under test middleware(req, res, next); expect(handler).to.have.been.calledOnce; expect(handler).to.have.been.calledWithExactly(req, res, next); }); it('should not call next() if the handler returns void', () => { handler.returns(undefined); middleware(req, res, next); expect(next).not.to.have.been.called; expectResponseNotToHaveBeenTouched(); }); it('should not call next() or send a response if the handler returns a string value', () => { handler.returns('foobar'); middleware(req, res, next); expect(next).not.to.have.been.called; expectResponseNotToHaveBeenTouched(); }); it('should not call next() or send a response if the handler returns a non-promise object', () => { handler.returns({ error: 'foo' }); middleware(req, res, next); expect(next).not.to.have.been.called; expectResponseNotToHaveBeenTouched(); }); it('should send the response content as JSON when the handler returns a successful Response promise with an object', () => { const response = { content: 'foo' }; handler.returns(Response.resolve(response)); middleware(req, res, next); return waitForResponseEnd() .then(() => { expect(res.status).to.have.been.calledWithExactly(200); expect(res.json).to.have.been.calledWithExactly(response); }); }); it('should send the response content as a string when the handler returns a successful Response promise with a string', () => { const response = 'response message'; handler.returns(Response.resolve(response)); middleware(req, res, next); return waitForResponseEnd() .then(() => { expect(res.status).to.have.been.calledWithExactly(200); expect(res.send).to.have.been.calledWithExactly(response); }); }); it('should log a warning and return 500 if the response is a promise with a non-Response object', () => { const response = { content: 'hello world' }; handler.returns(Promise.resolve(response)); middleware(req, res, next); return waitForResponseEnd() .then(() => { expect(log.warn).to.have.been.called; expect(res.status).to.have.been.calledWithExactly(500); expectNoContentToHaveBeenSent(); }); }); it('should send the response content as JSON with the given error code when the handler returns a failed Response promise with an object', () => { const errorObject = { message: 'You are not logged in' }; handler.returns(Response.reject(errorObject, 401)); middleware(req, res, next); return waitForResponseEnd() .then(() => { expect(res.status).to.have.been.calledWithExactly(401); expect(res.json).to.have.been.calledWithExactly(errorObject); }); }); it('should send the response content as a string when the handler returns a failed Response promise with a string', () => { const response = 'response message'; handler.returns(Response.reject(response, 400)); middleware(req, res, next); return waitForResponseEnd() .then(() => { expect(res.status).to.have.been.calledWithExactly(400); expect(res.send).to.have.been.calledWithExactly(response); }); }); it('should log an error with the original URL and return 500 if the response is a failed promise with a non-Response error', () => { const error = new Error('Something went wrong'); handler.returns(Promise.reject(error)); const url = '/foo/bar'; req.originalUrl = url; middleware(req, res, next); return waitForResponseEnd() .then(() => { expect(log.error).to.have.been.calledOnce; expect(log.error.firstCall.args).to.contain(url); expect(log.error.firstCall.args).to.contain(error); expect(res.status).to.have.been.calledWithExactly(500); expectNoContentToHaveBeenSent(); }); }); it('should log an error with the original URL and return 500 if the handler itself throws an error', () => { const error = new Error('Something went wrong'); handler.throws(error); const url = '/foo/bar'; req.originalUrl = url; middleware(req, res, next); return waitForResponseEnd() .then(() => { expect(log.error).to.have.been.calledOnce; expect(log.error.firstCall.args).to.contain(url); expect(log.error.firstCall.args).to.contain(error); expect(res.status).to.have.been.calledWithExactly(500); expectNoContentToHaveBeenSent(); }); }); });
{ "content_hash": "a7543dfca216cc8fa60ca591ec609131", "timestamp": "", "source": "github", "line_count": 201, "max_line_length": 148, "avg_line_length": 30.751243781094526, "alnum_prop": 0.6432616081540203, "repo_name": "FOODit/express-router-decorators", "id": "73490e981eb2c38bf98c90174747932920c8a102", "size": "6181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/lib/promise-response/promise-response.wrapper.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "18435" }, { "name": "TypeScript", "bytes": "75378" } ] }
weibo-analysis ==============
{ "content_hash": "85bb022f362c93651102be512b1c5d85", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 14, "avg_line_length": 15, "alnum_prop": 0.43333333333333335, "repo_name": "longsail/weibo-analysis", "id": "b522bb1d88b843b513dc2ba9c1acbce6ca11ad82", "size": "30", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "7574" } ] }
id: 5a24c314108439a4d4036148 title: Connect Redux to the Messages App challengeType: 6 isRequired: false videoUrl: '' localeTitle: 将Redux连接到消息应用程序 --- ## Description <section id="description">现在您已了解如何使用<code>connect</code>将React连接到Redux,您可以将您学到的知识应用于处理消息的React组件。在上一课中,您连接到Redux的组件名为<code>Presentational</code> ,这不是任意的。该术语<i>通常</i>是指未直接连接到Redux的React组件。他们只负责UI的呈现,并根据他们收到的道具来执行此操作。相比之下,容器组件连接到Redux。这些通常负责将操作分派给商店,并且经常将商店状态作为道具传递给子组件。 </section> ## Instructions <section id="instructions">到目前为止,代码编辑器包含了您在本节中编写的所有代码。唯一的变化是React组件被重命名为<code>Presentational</code> 。创建一个名为<code>Container</code>的常量中保存的新组件,该常量使用<code>connect</code>将<code>Presentational</code>组件连接到Redux。然后,在<code>AppWrapper</code> ,渲染React Redux <code>Provider</code>组件。将Redux <code>store</code> <code>Provider</code>作为道具传递,并将<code>Container</code>作为子项呈现。设置完所有内容后,您将再次看到应用程序呈现给页面的消息。 </section> ## Tests <section id='tests'> ```yml tests: - text: <code>AppWrapper</code>应该呈现给页面。 testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').length === 1; })()); - text: <code>Presentational</code>组件应呈现<code>h2</code> , <code>input</code> , <code>button</code>和<code>ul</code>元素。 testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('Presentational').length === 1; })()); - text: <code>Presentational</code>组件应呈现<code>h2</code> , <code>input</code> , <code>button</code>和<code>ul</code>元素。 testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); return ( PresentationalComponent.find('div').length === 1 && PresentationalComponent.find('h2').length === 1 && PresentationalComponent.find('button').length === 1 && PresentationalComponent.find('ul').length === 1 ); })()); - text: <code>Presentational</code>组件应该从Redux商店接收<code>messages</code>作为道具。 testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); const props = PresentationalComponent.props(); return Array.isArray(props.messages); })()); - text: <code>Presentational</code>组件应该接收<code>submitMessage</code>操作创建者作为prop。 testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find('Presentational'); const props = PresentationalComponent.props(); return typeof props.submitNewMessage === 'function'; })()); ``` </section> ## Challenge Seed <section id='challengeSeed'> <div id='jsx-seed'> ```jsx // Redux: const ADD = 'ADD'; const addMessage = (message) => { return { type: ADD, message: message } }; const messageReducer = (state = [], action) => { switch (action.type) { case ADD: return [ ...state, action.message ]; default: return state; } }; const store = Redux.createStore(messageReducer); // React: class Presentational extends React.Component { constructor(props) { super(props); this.state = { input: ", messages: [] } this.handleChange = this.handleChange.bind(this); this.submitMessage = this.submitMessage.bind(this); } handleChange(event) { this.setState({ input: event.target.value }); } submitMessage() { const currentMessage = this.state.input; this.setState({ input: ", messages: this.state.messages.concat(currentMessage) }); } render() { return ( <div> <h2>Type in a new Message:</h2> <input value={this.state.input} onChange={this.handleChange}/><br/> <button onClick={this.submitMessage}>Submit</button> <ul> {this.state.messages.map( (message, idx) => { return ( <li key={idx}>{message}</li> ) }) } </ul> </div> ); } }; // React-Redux: const mapStateToProps = (state) => { return { messages: state } }; const mapDispatchToProps = (dispatch) => { return { submitNewMessage: (newMessage) => { dispatch(addMessage(newMessage)) } } }; const Provider = ReactRedux.Provider; const connect = ReactRedux.connect; // define the Container component here: class AppWrapper extends React.Component { constructor(props) { super(props); } render() { // complete the return statement: return (null); } }; ``` </div> ### After Test <div id='jsx-teardown'> ```js console.info('after the test'); ``` </div> </section> ## Solution <section id='solution'> ```js // solution required ``` </section>
{ "content_hash": "36533c62469d2052c2436d372e6dc73a", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 404, "avg_line_length": 30.1125, "alnum_prop": 0.6787048567870486, "repo_name": "jonathanihm/freeCodeCamp", "id": "a58f45d185bb666b6cf8232454c9a89944558c91", "size": "5508", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "curriculum/challenges/chinese/03-front-end-libraries/react-and-redux/connect-redux-to-the-messages-app.chinese.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "193850" }, { "name": "HTML", "bytes": "100244" }, { "name": "JavaScript", "bytes": "522335" } ] }
import map from 'lodash/map'; import { fetchNodeDataAndConvertExam } from 'kolibri.utils.exams'; import { ExamResource, ContentNodeResource } from 'kolibri.resources'; export function fetchQuizSummaryPageData(examId) { const payload = { // To display the title, status, etc. of the Quiz exam: {}, // To render the exercises in QuestionListPreview > ContentRenderer exerciseContentNodes: {}, }; return ExamResource.fetchModel({ id: examId }) .then(exam => { return fetchNodeDataAndConvertExam(exam); }) .then(exam => { payload.exam = exam; return ContentNodeResource.fetchCollection({ getParams: { ids: map(exam.question_sources, 'exercise_id'), }, }).then(contentNodes => { payload.exerciseContentNodes = contentNodes; return payload; }); }); } export function serverAssignmentPayload(listOfIDs, classId) { const assignedToClass = listOfIDs.length === 0 || listOfIDs[0] === classId; if (assignedToClass) { return [classId]; } return listOfIDs; } export function clientAssigmentState(listOfIDs, classId) { const assignedToClass = listOfIDs.length === 0 || listOfIDs[0] === classId; if (assignedToClass) { return []; } return listOfIDs; } export function deleteExam(examId) { return ExamResource.deleteModel({ id: examId }); }
{ "content_hash": "f0339874b5c4c010a1ebcbf980d96cbe", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 77, "avg_line_length": 29.04255319148936, "alnum_prop": 0.6732600732600733, "repo_name": "learningequality/kolibri", "id": "65b5dffa253b63b2008aa5fb44d48fab0a7e0b61", "size": "1365", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "kolibri/plugins/coach/assets/src/views/plan/QuizSummaryPage/api.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3095586" }, { "name": "Dockerfile", "bytes": "3559" }, { "name": "Gherkin", "bytes": "996801" }, { "name": "HTML", "bytes": "22573" }, { "name": "JavaScript", "bytes": "2233801" }, { "name": "Makefile", "bytes": "12972" }, { "name": "Python", "bytes": "3652744" }, { "name": "SCSS", "bytes": "8551" }, { "name": "Shell", "bytes": "3867" }, { "name": "Vue", "bytes": "2193917" } ] }
create vclass t1 ( c1 int Unique not null SHARED 9 ); drop t1;
{ "content_hash": "573aa13301ece94a9d10aa45a0089020", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 33, "avg_line_length": 13, "alnum_prop": 0.6923076923076923, "repo_name": "CUBRID/cubrid-testcases", "id": "e3ec2181d8527453cab7cb412c415ef097a6fe30", "size": "134", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "sql/_01_object/_03_virtual_class/_002_constrains/cases/1065.sql", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PLSQL", "bytes": "682246" }, { "name": "Roff", "bytes": "23262735" }, { "name": "TSQL", "bytes": "5619" }, { "name": "eC", "bytes": "710" } ] }
var Sql = require('../../Sql') , utils = require('../../utils') , Statement = require('../statements/Statement'); /** * Common interface for compiling query * @param {QueryBuilder} builder * * @constructor */ function Grammar (builder) { this.builder = builder; this.components = []; this.pCount = null; }; /** * @type {QueryBuilder} * @public */ Grammar.prototype.builder; /** * @type {Statement} * @protected */ Grammar.prototype.statement; /** * @type {Array} * @protected */ Grammar.prototype.components; /** * @type {Number} parameters count */ Grammar.prototype.pCount; /** * @param {Statement} query * @param {Object} params * * @return {Sql} * @public */ Grammar.prototype.compileStatement = function (query, params) { query.prepare(this.builder); this.statement = query; params = params || {}; this.pCount = null; utils.merge(params, query.criteria.params); var sql = this.compileComponents(query, params).join(' '); var options = query.options ? utils.clone(query.options) : {}; utils.merge(options, {params: params}); return new Sql(sql, options); }; /** * Compile the components necessary for a SQL query * @param {Statement} query * @param {Object} params * * @return {String[]} * @protected */ Grammar.prototype.compileComponents = function (query, params) { var self = this , method , sql = this.components.map(function (item) { if (query.criteria[item] === undefined) return null; method = 'compile' + item.charAt(0).toUpperCase() + item.slice(1); if (self[method] && utils.isFunction(self[method])) { return self[method](query.criteria[item], params); } }).filter(function (item) { return !!item; }); return sql.length > 1 ? sql : []; }; /** * Get class schema * * @return {Schema} * @protected */ Grammar.prototype.getSchema = function () { return this.statement.getSchema(); }; /** * @param {*} value * @param {Object} params * @param {Boolean} [one] * * @return {String|String[]} * @public */ Grammar.prototype.paramify = function (value, params, one) { var self = this , isArray = utils.isArray(value) , values = (isArray ? value : [value]).map(function (val) { return self.paramifyOne(val, params); }); return (one || !isArray) ? values[0] : values; }; /** * @param {*} value * @param {Object} params * * @return {String|null} * @protected */ Grammar.prototype.paramifyOne = function (value, params) { if (value instanceof Statement) { var sub = this.builder.compile(value, params); return sub.query ? '(' + sub.query + ')' : null; } if (this.pCount === null) { this.pCount = utils.count(params); } var pName = this.builder.paramPrefix + this.pCount; params[pName] = fixValue(value); this.pCount++; return ":" + pName; }; function fixValue (value) { var fixedV = utils.clone(value); if (utils.isArray(fixedV)) { return fixedV.map(function (item) { return fixValue(item); }); } else if (utils.isObject(fixedV)) { for (var i in fixedV) { if (!fixedV.hasOwnProperty(i)) continue; fixedV[i] = fixValue(fixedV[i]); } return fixedV; } else if (utils.isDate(fixedV)) { return utils.dateToString(fixedV); } return fixedV; }; /** * Convert value to SQL string * @param {*} value * @param {Object} params * * @return {String} * @protected */ Grammar.prototype.valueToString = function (value, params) { return this.builder.valueToString(value, params); }; /** * Cast types * @param {*} value * @param {String} [path] Path name * @param {String} [op] * * @return {*} Value string for SQL query * @protected */ Grammar.prototype.cast = function (value, path, op) { if (value instanceof Statement) return value; var schema = this.getSchema(); if (!schema) return value; // if no path specified we assume developer wants to cast full object if (!path) return schema.cast(value); var schematype = schema.path(path); if (!schematype) return value; return schematype.cast(value, path, op); }; module.exports = Grammar;
{ "content_hash": "1064bd6c5ad4fcb96f095c712db1440f", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 72, "avg_line_length": 21.15897435897436, "alnum_prop": 0.6335433834222006, "repo_name": "mav-im/orientorm", "id": "25379f143f5c8494b906672ab7cd4dd7cc2504b9", "size": "4126", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/query/grammars/Grammar.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "325794" } ] }
using namespace Eigen; using namespace std; void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs < 2 || nlhs < 2) { mexErrMsgIdAndTxt("Drake:jointLimitConstraintsmex:InvalidCall","Usage: [phi, J] = jointLimitConstraintsmex(mex_model_ptr, q) "); } RigidBodyManipulator *model= (RigidBodyManipulator*) getDrakeMexPointer(prhs[0]); if (mxGetNumberOfElements(prhs[1]) != model->num_positions) { mexErrMsgIdAndTxt("Drake:jointLimitConstraintsmex:InvalidPositionVectorLength", "q contains the wrong number of elements"); } Map<VectorXd> q(mxGetPr(prhs[1]),model->num_positions); size_t numJointConstraints = model->getNumJointLimitConstraints(); plhs[0] = mxCreateDoubleMatrix(numJointConstraints, 1, mxREAL); plhs[1] = mxCreateDoubleMatrix(numJointConstraints, model->num_positions, mxREAL); Map<VectorXd> phi(mxGetPr(plhs[0]), numJointConstraints); Map<MatrixXd> J(mxGetPr(plhs[1]), numJointConstraints, model->num_positions); model->jointLimitConstraints(q, phi, J); }
{ "content_hash": "70bf1b80772f7290451968711ccfd438", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 132, "avg_line_length": 37.392857142857146, "alnum_prop": 0.7411652340019103, "repo_name": "tkoolen/drake", "id": "52cbab0b268239eea73c5bd2604cf360b425d47a", "size": "1122", "binary": false, "copies": "1", "ref": "refs/heads/body-wrench-in-qp", "path": "systems/plants/jointLimitConstraintsmex.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "17234" }, { "name": "C++", "bytes": "1411594" }, { "name": "CMake", "bytes": "29515" }, { "name": "Java", "bytes": "29789" }, { "name": "M", "bytes": "13492" }, { "name": "Makefile", "bytes": "3867" }, { "name": "Matlab", "bytes": "3096265" }, { "name": "Objective-C", "bytes": "2333" }, { "name": "Perl", "bytes": "2675" }, { "name": "Python", "bytes": "22706" }, { "name": "Shell", "bytes": "2450" } ] }
package org.apache.apex.engine.plugin; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.apex.engine.api.plugin.DAGExecutionPlugin; import org.apache.apex.engine.api.plugin.DAGExecutionPluginContext; import org.apache.apex.engine.api.plugin.DAGExecutionPluginContext.Handler; import com.datatorrent.stram.api.StramEvent; import com.datatorrent.stram.api.StreamingContainerUmbilicalProtocol; import static org.apache.apex.engine.api.plugin.DAGExecutionPluginContext.COMMIT_EVENT; import static org.apache.apex.engine.api.plugin.DAGExecutionPluginContext.HEARTBEAT; import static org.apache.apex.engine.api.plugin.DAGExecutionPluginContext.STRAM_EVENT; public class DebugPlugin implements DAGExecutionPlugin { private int eventCount = 0; private int heartbeatCount = 0; private int commitCount = 0; CountDownLatch latch = new CountDownLatch(3); @Override public void setup(DAGExecutionPluginContext context) { context.register(STRAM_EVENT, new Handler<StramEvent>() { @Override public void handle(StramEvent stramEvent) { eventCount++; latch.countDown(); } }); context.register(HEARTBEAT, new Handler<StreamingContainerUmbilicalProtocol.ContainerHeartbeat>() { @Override public void handle(StreamingContainerUmbilicalProtocol.ContainerHeartbeat heartbeat) { heartbeatCount++; latch.countDown(); } }); context.register(COMMIT_EVENT, new Handler<Long>() { @Override public void handle(Long aLong) { commitCount++; latch.countDown(); } }); } @Override public void teardown() { } public int getEventCount() { return eventCount; } public int getHeartbeatCount() { return heartbeatCount; } public int getCommitCount() { return commitCount; } public void waitForEventDelivery(long timeout) throws InterruptedException { latch.await(timeout, TimeUnit.SECONDS); } }
{ "content_hash": "e268c10fbb5272f2dbeaae2f2ec49b8b", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 101, "avg_line_length": 24.285714285714285, "alnum_prop": 0.7235294117647059, "repo_name": "simplifi-it/otterx", "id": "5b8ca11bd865a069cec68ce198dd13ca2dbed11d", "size": "2848", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "engine/src/test/java/org/apache/apex/engine/plugin/DebugPlugin.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "843" }, { "name": "Java", "bytes": "3601702" }, { "name": "Shell", "bytes": "4439" }, { "name": "XSLT", "bytes": "1758" } ] }
require 'google/bigquery/property/array' module Google module Bigquery module Property # A class to handle serialization of Array items. class StringArray < Google::Bigquery::Property::Array def self.coerce ->(x) { ::Google::Bigquery::Property::StringArray.catalog_parse(x) } end def self.api_parse(value) value end def self.catalog_parse(value) value end def self.validate(value) return if value.nil? || value.is_a?(::String) unless value.is_a? ::Array raise "Expected string but found #{value.class} instead: #{value}" end value.each { |v| validate v } end end end end end
{ "content_hash": "529f4edcefdb4eac54d35900d72d1d33", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 78, "avg_line_length": 25.166666666666668, "alnum_prop": 0.5748344370860927, "repo_name": "GoogleCloudPlatform/chef-google-bigquery", "id": "48882be987f6481c4b6185eef05b3e9b7bc91698", "size": "1911", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libraries/google/bigquery/property/string_array.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "426973" } ] }
@interface AreasViewController () @property (nonatomic, strong) NSArray *areas; @end @implementation AreasViewController @synthesize floor; - (void)viewDidLoad { [super viewDidLoad]; self.title = [NSString stringWithFormat:@"Floor %@ - Areas", self.floor.label]; [self fetchAreas]; } - (void)fetchAreas { [[IFDataManager sharedManager] fetchAreasFromCacheForFloorId:self.floor.remote_id block:^(NSArray *areas) { NSLog(@"Fetch areas success"); self.areas = areas; if(self.refreshControl) { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"MMM d, h:mm a"]; NSString *lastUpdated = [NSString stringWithFormat:@"Last updated on %@", [formatter stringFromDate:[NSDate date]]]; self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated]; [self.refreshControl endRefreshing]; } [self.tableView reloadData]; }]; } #pragma mark - UITableViewDataSource - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return (NSInteger)self.areas.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell1"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; IFMArea *area = [self.areas objectAtIndex:(NSUInteger)indexPath.row]; cell.textLabel.text = area.name; if([area.contents allObjects].count >= 1){ IFMContent *content = [area.contents allObjects].firstObject; if(content && content.type == IFMContentTypeNone){ cell.accessoryType = UITableViewCellAccessoryNone; cell.userInteractionEnabled = NO; }else{ cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; cell.userInteractionEnabled = YES; } }else{ cell.accessoryType = UITableViewCellAccessoryNone; cell.userInteractionEnabled = NO; } return cell; } - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if([sender isKindOfClass:[UITableViewCell class]]) { NSIndexPath *indexPath = [self.tableView indexPathForCell:sender]; IFMArea *area = [self.areas objectAtIndex:(NSUInteger)indexPath.row]; if([segue.destinationViewController isKindOfClass:[ContentViewController class]]) { IFMContent *content = [[area.contents allObjects] firstObject]; NSURL *url = [NSURL URLWithString:[content getContentURL]]; [(ContentViewController *)segue.destinationViewController setUrl:url]; } }else if([segue.destinationViewController conformsToProtocol:@protocol(FloorplanChild)]){ [(id<FloorplanChild>)segue.destinationViewController setFloor:self.floor]; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
{ "content_hash": "6152d51e5d6ddf2cfe8dff16ea5625e3", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 111, "avg_line_length": 34.2967032967033, "alnum_prop": 0.6808715155398911, "repo_name": "Ifinity/ifinity-objc-example", "id": "a297c542a22c8b8562890225e890b7bef2c22a2c", "size": "3389", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "IfinitySdkSampleAppIos/AreasViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "43625" }, { "name": "Ruby", "bytes": "238" } ] }
End of preview.

No dataset card yet

Downloads last month
5