text:
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
Apache OFBiz® Data Model Changes
=============
Apache OFBiz follows **The Universal Data Model** by **Len Silverston**, with a grain of salt.

The following file contains information about the data model changes in the Apache OFBiz.
The detailed description of migration scripts specified here can be found at [Revisions Requiring Data Migration - upgrade ofbiz](https://cwiki.apache.org/confluence/x/LoBr) page.

##Changes with OFBiz 17
Field types "id-ne", "id-long-ne" & "id-vlong-ne" has been removed. Use "id", "id-long" and "id-vlong" instead (detailed description at [OFBIZ-9351](https://issues.apache.org/jira/browse/OFBIZ-9351)).

###Entity Changes
No changes

###Field Changes

| Entity  | Field  | Action | IsPK | Revision |
|:------------- |:---------------:|:---------------:|:---------------:| -------------:|
| MarketingCampaignPrice | fromDate | Added | Yes | R1805961 |
| MarketingCampaignPrice | thruDate | Added | No | R1805961 |
| MarketingCampaignPromo | fromDate | Added | Yes | R1805961 |
| MarketingCampaignPromo | thruDate | Added | No | R1805961 |
| MarketingCampaignRole | fromDate | Added | Yes | R1805961 |
| MarketingCampaignRole | thruDate | Added | No | R1805961 |
| Product | manufacturerPartyId | Removed | No| R1804408 |
| SecurityGroupPermission | fromDate | Added | Yes | R1812383 |
| SecurityGroupPermission | thruDate | Added | No | R1812383 |

###Migration Scripts
1. Updated sql-type for date-time and time field in fieldtypemysql.xml file
R1793300 "Update msyql sql-type for datetime field-type to support Fractional Seconds in Time Values
Please upgrade mysql to at least 5.6.4 or higher.
After upgrade run 'generateMySqlFileWithAlterTableForTimestamps' service, groupName is required field for this service,
It will generate sql file with alter query statement for date-time and time field at location "${ofbiz.home}/runtime/tempfiles/<groupName>.sql"
You can use execute sql statement from any of the mysql batch command.

##Changes between OFBiz 9 to OFBiz 16

###Entity Changes
**Added 77 new entities**

1. JobRequisition
2. ProductAverageCostType
3. WorkEffortSurveyAppl
4. WorkEffortIcalData
5. WebSiteContactList
6. WebAnalyticsType
7. WebAnalyticsConfig
8. UserLoginSecurityQuestion
9. UomGroup
10. TrainingRequest
11. ThirdPartyLogin
12. TestFieldType
13. TestingSubtype
14. TestingStatus
15. TestingRemoveAll
16. TestingItem
17. TestingCrypto
18. SystemProperty
19. ShipmentGatewayUsps
20. ShipmentGatewayUps
21. ShipmentGatewayFedex
22. ShipmentGatewayDhl
23. ShipmentGatewayConfig
24. ShipmentGatewayConfigType
25. ReturnContactMech
26. QuoteNote
27. ProductPromoContent
28. ProductPromoContentType
29. ProductGroupOrder
30. ProductCostComponentCalc
31. CostComponentCalc
32. PayPalPaymentMethod
33. PaymentGroupType
34. PaymentGroup
35. PaymentGroupMember
36. PaymentGatewayConfig
37. PaymentGatewayConfigType
38. PaymentGatewayWorldPay
39. PaymentGatewaySecurePay
40. PaymentGatewaySagePay
41. PaymentGatewayOrbital
42. PaymentGatewayEway
43. PaymentGatewayCyberSource
44. PaymentGatewayAuthorizeNet
45. PaymentGatewayIDEAL
46. PaymentContentType
47. PaymentContent
48. OAuth2LinkedIn
49. OAuth2GitHub
50. JobManagerLock
51. JobInterviewType
52. JobInterview
53. JavaResource
54. InvoiceNote
55. InvoiceItemAssocType
56. InvoiceItemAssoc
57. InvoiceContentType
58. InvoiceContent
59. GlAccountCategoryType
60. GlAccountCategoryMember
61. GlAccountCategory
62. GitHubUser
63. FixedAssetTypeGlAccount
64. FacilityContent
65. ExcelImportHistory
66. EmplLeaveReasonType
67. EbayShippingMethod
68. EbayConfig
69. CountryAddressFormat
70. ContentSearchResult
71. ContentSearchConstraint
72. ContentKeyword
73. CheckAccount
74. AgreementFacilityAppl
75. AgreementContentType
76. AgreementContent

**Removed 8 entities**

1. DepreciationMethod
2. FixedAssetMaintMeter
3. OagisMessageErrorInfo
4. OagisMessageInfo
5. SalesOpportunityTrackingCode
6. SimpleSalesTaxLookup
7. TestBlob
8. WorkEffortAssignmentRate

###Field Changes
| Entity  | Field  | Action | IsPK | Revision |
|:------------- |:---------------:|:---------------:|:---------------:| -------------:|
| AcctgTransAttribute | attrDescription | Added | No| |
| AcctgTransEntry | inventoryItemId | Added | No| |
| AcctgTransTypeAttr | description | Added | No| |
| BenefitType | parentTypeId | Added | No| |
| BenefitType | hasTable | Added | No| |
| BudgetAttribute | attrDescription | Added | No| |
| BudgetItemAttribute | attrDescription | Added | No| |
| BudgetItemTypeAttr | description | Added | No| |
| BudgetStatus | changeByUserLoginId | Added | No| |
| BudgetTypeAttr | description | Added | No| |
| CommunicationEventRole | statusId | Added | No| |
| CommunicationEventType | contactMechTypeId | Added | No| |
| ContactListCommStatus | partyId | Added | No| |
| ContactListCommStatus | messageId | Added | No| |
| ContactListCommStatus | changeByUserLoginId | Added | No| |
| ContactMechAttribute | attrDescription | Added | No| |
| ContactMechTypeAttr | description | Added | No| |
| DeductionType | parentTypeId | Added | No| |
| DeductionType | hasTable | Added | No| |
| DocumentAttribute | attrDescription | Added | No| |
| DocumentTypeAttr | description | Added | No| |
| EmploymentApp | approverPartyId | Added | No| |
| EmploymentApp | jobRequisitionId | Added | No| |
| EmploymentAppSourceType | parentTypeId | Added | No| |
| EmploymentAppSourceType | hasTable | Added | No| |
| EmplPositionClassType | parentTypeId | Added | No| |
| EmplPositionClassType | hasTable | Added | No| |
| EmplPositionType | parentTypeId | Added | No| |
| EmplPositionType | hasTable | Added | No| |
| EmplPositionType | partyId | Removed | No| |
| EmplPositionType | roleTypeId | Removed | No| |
| FinAccountAttribute | attrDescription | Added | No| |
| FinAccountTransAttribute | attrDescription | Added | No| |
| FinAccountTrans | glReconciliationId | Added | No| |
| FinAccountTrans | statusId | Added | No| |
| FinAccountTransTypeAttr | description | Added | No| |
| FinAccountTypeAttr | description | Added | No| |
| FinAccountStatus | changeByUserLoginId | Added | No| |
| FixedAsset | acquireOrderId | Added | No| |
| FixedAsset | acquireOrderItemSeqId | Added | No| |
| FixedAssetAttribute | attrDescription | Added | No| |
| FixedAssetTypeAttr | description | Added | No| |
| GlAccount | externalId | Added | No| |
| GlAccount | openingBalance | Added | No| |
| GlReconciliation | createdDate | Added | No| |
| GlReconciliation | lastModifiedDate | Added | No| |
| GlReconciliation | statusId | Added | No| |
| GlReconciliation | openingBalance | Added | No| |
| InventoryItemAttribute | attrDescription | Added | No| |
| InventoryItemStatus | changeByUserLoginId | Added | No| |
| InventoryItemTypeAttr | description | Added | No| |
| InvoiceAttribute | attrDescription | Added | No| |
| InvoiceItemAttribute | attrDescription | Added | No| |
| InvoiceItemTypeAttr | description | Added | No| |
| InvoiceStatus | changeByUserLoginId | Added | No| |
| InvoiceTypeAttr | description | Added | No| |
| InvoiceTermAttribute | attrDescription | Added | No| |
| JobSandbox | currentRetryCount | Added | No| |
| JobSandbox | tempExprId | Added | No| |
| JobSandbox | currentRecurrenceCount | Added | No| |
| JobSandbox | maxRecurrenceCount | Added | No| |
| JobSandbox | jobResult | Added | No| |
| OrderAdjustment | amountAlreadyIncluded | Added | No| |
| OrderAdjustment | isManual | Added | No| |
| OrderAdjustment | oldPercentage | Added | No| |
| OrderAdjustment | oldAmountPerQuantity | Added | No| |
| OrderAdjustment | lastModifiedDate | Added | No| |
| OrderAdjustment | lastModifiedByUserLogin | Added | No| |
| OrderAdjustmentAttribute | attrDescription | Added | No| |
| OrderAdjustmentTypeAttr | description | Added | No| |
| OrderAttribute | attrDescription | Added | No| |
| OrderItem | supplierProductId | Added | No| |
| OrderItem | cancelBackOrderDate | Added | No| |
| OrderItem | changeByUserLoginId | Added | No| |
| OrderItemAttribute | attrDescription | Added | No| |
| OrderItemShipGroup | facilityId | Added | No| |
| OrderItemShipGroup | estimatedShipDate | Added | No| |
| OrderItemShipGroup | estimatedDeliveryDate | Added | No| |
| OrderItemShipGrpInvRes | priority | Added | No| |
| OrderItemShipGrpInvRes | oldPickStartDate | Added | No| |
| OrderItemTypeAttr | description | Added | No| |
| OrderTermAttribute | attrDescription | Added | No| |
| OrderPaymentPreference | track2 | Added | No| |
| OrderPaymentPreference | swipedFlag | Added | No| |
| OrderPaymentPreference | lastModifiedDate | Added | No| |
| OrderPaymentPreference | lastModifiedByUserLogin | Added | No| |
| OrderShipment | shipGroupSeqId | Added | No| |
| OrderTypeAttr | description | Added | No| |
| PartyAcctgPreference | orderSequenceEnumId | Removed | No| |
| PartyAcctgPreference | quoteSequenceEnumId | Removed | No| |
| PartyAcctgPreference | invoiceSequenceEnumId | Removed | No| |
| PartyAcctgPreference | oldOrderSequenceEnumId | Added | No| |
| PartyAcctgPreference | oldQuoteSequenceEnumId | Added | No| |
| PartyAcctgPreference | oldInvoiceSequenceEnumId | Added | No| |
| PartyAcctgPreference | orderSeqCustMethId | Added | No| |
| PartyQual | infoString | Removed | No| |
| PartyQual | institutionInternalId | Removed | No| |
| PartyQual | institutionPartyId | Removed | No| |
| PartyQual | partyQualId | Removed | No| |
| PartyRate | percentageUsed | Added | No| |
| PartyRate | rate | Removed | No| |
| PartyResume | contentId | Added | No| |
| PaymentAttribute | attrDescription | Added | No| |
| PaymentGatewayResponse | gatewayCvResult | Added | No| |
| PaymentMethod | finAccountId | Added | No| |
| PaymentTypeAttr | description | Added | No| |
| PerfRatingType | parentTypeId | Added | No| |
| PerfRatingType | hasTable | Added | No| |
| PerfReview | payHistoryRoleTypeIdTo | Removed | No| |
| PerfReview | payHistoryRoleTypeIdFrom | Removed | No| |
| PerfReview | payHistoryPartyIdTo | Removed | No| |
| PerfReview | payHistoryPartyIdFrom | Removed | No| |
| PerfReview | payHistoryFromDate | Removed | No| |
| PerfReviewItemType | parentTypeId | Added | No| |
| PerfReviewItemType | hasTable | Added | No| |
| PersonTraining | trainingRequestId | Added | No| |
| PersonTraining | workEffortId | Added | No| |
| PersonTraining | approverId | Added | No| |
| PersonTraining | approvalStatus | Added | No| |
| PersonTraining | reason | Added | No| |
| PostalAddress | houseNumber | Added | No| |
| PostalAddress | houseNumberExt | Added | No| |
| PostalAddress | cityGeoId | Added | No| |
| PostalAddress | municipalityGeoId | Added | No| |
| PostalAddress | geoPointId | Added | No| |
| PosTerminal | terminalName | Added | No| |
| PosTerminalInternTx | reasonEnumId | Added | No| |
| Product | releaseDate | Added | No| |
| Product | originalImageUrl | Added | No| |
| Product | inventoryItemTypeId | Added | No| |
| Product | shippingWeight | Added | No| |
| Product | productWeight | Added | No| |
| Product | diameterUomId | Added | No| |
| Product | productDiameter | Added | No| |
| Product | virtualVariantMethodEnum | Added | No| |
| Product | defaultShipmentBoxTypeId | Added | No| |
| Product | lotIdFilledIn | Added | No| |
| Product | orderDecimalQuantity | Added | No| |
| Product | weight | Removed | No| |
| Product | taxCategory | Removed | No| |
| Product | taxVatCode | Removed | No| |
| Product | taxDutyCode | Removed | No| |
| ProductAttribute | attrDescription | Added | No| |
| ProductAverageCost | productAverageCostTypeId | Added | No| |
| ProductAverageCost | facilityId | Added | No| |
| ProductContent | sequenceNum | Added | No| |
| ProductKeyword | keywordTypeId | Added | No| |
| ProductKeyword | statusId | Added | No| |
| ProductRole | sequenceNum | Added | No| |
| ProductStore | balanceResOnOrderCreation | Added | No| |
| ProductStore | defaultTimeZoneString | Added | No| |
| ProductStore | oldStyleSheet | Added | No| |
| ProductStore | oldHeaderLogo | Added | No| |
| ProductStore | oldHeaderRightBackground | Added | No| |
| ProductStore | oldHeaderMiddleBackground | Added | No| |
| ProductStore | styleSheet | Removed | No| |
| ProductStore | headerLogo | Removed | No| |
| ProductStore | headerRightBackground | Removed | No| |
| ProductStore | headerMiddleBackground | Removed | No| |
| ProductStorePaymentSetting | paymentCustomMethodId | Added | No| |
| ProductStorePaymentSetting | paymentGatewayConfigId | Added | No| |
| ProductStoreShipmentMeth | shipmentCustomMethodId | Added | No| |
| ProductStoreShipmentMeth | shipmentGatewayConfigId | Added | No| |
| ProductStoreShipmentMeth | allowancePercent | Added | No| |
| ProductStoreShipmentMeth | minimumPrice | Added | No| |
| ProductTypeAttribute | attrDescription | Added | No|
| QuoteAdjustment | lastModifiedDate | Added | No| |
| QuoteAdjustment | lastModifiedByUserLogin | Added | No| |
| QuoteAttribute | attrDescription | Added | No| |
| QuoteItem | leadTimeDays | Added | No| |
| QuoteRole | fromDate | Added | Yes| |
| QuoteRole | thruDate | Added | No| |
| QuoteTerm | termDays | Added | No| |
| QuoteTerm | textValue | Added | No| |
| QuoteTerm | description | Added | No| |
| QuoteTermAttribute | attrDescription | Added | No| |
| QuoteTypeAttr | description | Added | No| |
| RequirementAttribute | changeByUserLoginId | Added | No| |
| RequirementStatus | changeByUserLoginId | Added | No| |
| ResponsibilityType | parentTypeId | Added | No| |
| ResponsibilityType | hasTable | Added | No| |
| ReturnAdjustment | createdByUserLoginId | Added | No| |
| ReturnAdjustment | lastModifiedDate | Added | No| |
| ReturnAdjustment | lastModifiedByUserLogin | Added | No| |
| ReturnHeader | supplierRmaId | Added | No| |
| ReturnItemResponse | finAccountTransId | Added | No| |
| ReturnStatus | changeByUserLoginId | Added | No| |
| SalaryStep | fromDate | Added | Yes| |
| SalaryStep | thruDate | Added | No| |
| SalaryStep | createdByUserLoginId | Added | No| |
| SalaryStep | lastModifiedByUserLogin | Added | No| |
| SalesOpportunity | nextStepDate | Added | No| |
| ServiceSemaphore | lockedByInstanceId | Added | No| |
| ShoppingListItem | modifiedPrice | Added | No| |
| SkillType | parentTypeId | Added | No| |
| SkillType | hasTable | Added | No| |
| SupplierProduct | shippingPrice | Added | No| |
| SupplierProduct | supplierCommissionPerc | Removed | No| |
| TaxAuthorityRateProduct | isTaxInShippingPrice | Added | No| |
| TerminationType | parentTypeId | Added | No| |
| TerminationType | hasTable | Added | No| |
| TestingNodeMember | extendFromDate | Added | No| |
| TestingNodeMember | extendThruDate | Added | No| |
| TimeEntry | planHour | Added | No| |
| Timesheet | approvedByUserLoginId | Added | No| |
| TrainingClassType | parentTypeId | Added | No| |
| TrainingClassType | hasTable | Added | No| |
| UnemploymentClaim | thruDate | Added | No| |
| UserLogin | externalAuthId | Added | No| |
| UserLogin | userLdapDn | Added | No| |
| UserLogin | disabledBy | Added | No| |
| ValueLinkKey | createdByUserLogin | Added | No| |
| WebSite | visualThemeSetId | Added | No| |
| WebSite | hostedPathAlias | Added | No| |
| WebSite | isDefault | Added | No| |
| WebSite | displayMaintenancePage | Added | No| |
| WebSitePathAlias| fromDate | Added | Yes | R1738588 |
| WebSitePathAlias| thruDate | Added | No | R1738588 |
| WorkEffort | tempExprId | Added | No| |
| WorkEffort | sequenceNum | Added | No| |
| WorkEffortAttribute | attrDescription | Added | No| |
| WorkEffortAssocAttribute | attrDescription | Added | No| |
| WorkEffortAssocTypeAttr | description | Added | No| |
| WorkEffortContactMech | fromDate | Added | Yes| |
| WorkEffortContactMech | thruDate | Added | No| |
| WorkEffortFixedAssetAssign | availabilityStatusId | Added | No| |
| WorkEffortPartyAssignment | assignedByUserLoginId | Added | No| |
| WorkEffortPurposeType | parentTypeId | Added | No| |
| WorkEffortStatus | reason | Added | No| |
| WorkEffortTypeAttr | description | Added | No| |
| WorkOrderItemFulfillment | shipGroupSeqId | Added | No| |


text:
/**
 * A class for decoder objects that parse JSON strings and return
 * their translation into Java
 *
 * @author Graeme Boy, Vasilisa Bashlovkina
 * @created April 23, 2014
 *
 */
public class JSONDecoder
{
//+--------+----------------------------------------------------------
 // | Fields |
 // +--------+
  String jsonString;
  int i;
  JSONObject obj;

  // +--------------+----------------------------------------------------
  // | Constructors |
  // +--------------+
  public JSONDecoder(String stringIn)
  {
    this.i = 0;
    this.jsonString = stringIn;
  } // JSONDecoder ()

  /**
   * Parses the first object found in the jsonString
   *
   * @return the parsed object
   */
  public JSONObject jsonDecode()
  {
    return obj = parseObject();
  } // jsonDecode()

  /**
   * function nextChar, increments i before returning
   *
   * @return character at index i + 1 of jsonString
   * @post this.i is incremented
   */
  public char nextChar()
  {
    return this.jsonString.charAt(++this.i);
  } // nextChar

  /**
   * function curCharInc, returns the current character and then increments i by
   * one
   *
   * @return character at index i of jsonString
   * @post: increments i after returning the character at index i of jsonString
   */
  public char curCharInc()
  {
    return this.jsonString.charAt(this.i++);
  } // curCharInc ()

  /**
   * functoin currentChar
   *
   * @return the character at index i of jsonString
   */
  public char currentChar()
  {
    return this.jsonString.charAt(this.i);
  } // currentChar

  /**
   * function incChar, Increments i and returns the value
   *
   * @return the incremented value of i
   * @post this.i is incremented
   */
  public int incChar()
  {
    return ++this.i;
  } // incChar()

  /**
   * Parses the value in the key-pair of a JSON object. Values are preceeded by
   * colons.
   *
   * @return JSONVal
   * @pre value is either string, number, object, array, true, false, or null
   * @post the parse function for the type encountered is called
   */
  public JSONVal parseVal()
  {
    // Values are always preceeded by a colon.
    incChar(); // move past the colon.
    trim(); // remove whitespace after '"' or '['

    if (currentChar() == ':')
      {
        incChar(); // move past ':'
      }
    trim(); // remove whitespace after ':'

    char ch;
    ch = currentChar();
    /*
     * According to json.org, the acceptable types are: string, number, object,
     * array, true, false, and null
     */
    switch (ch)
      {
        case '0': // numbers, 0-9
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
        case '-': // for negative numbers
          return parseNumber();
        case '"': // string
          return parseString();
        case '[': // array
          return parseArray();
        case '{': // new object
          return parseObject();
          // True
        case 't': // has to be true
        case 'f': // has to be false
        case 'n': // has to be null
          return parseConstant();
      } // switch
    return null;
  }

  /**
   * parseObject Used to parse JSON objects
   *
   * @return JSONObject
   * @post all key and value pairs (seperated by commas) will be added
   */
  public JSONObject parseObject()
  {
    JSONObject object = new JSONObject();
    char ch;
    do
      {
        if (currentChar() == ',' || currentChar() == '{')
          {
            incChar(); // move past ',' or '{'
            trim();
          } // if
        else if (currentChar() == '}')
          {
            return null;
          } // else if
        if (currentChar() == '"')
          {
            object.addKey(parseKey());
          } // if
        trim(); // after '"'
        object.addVal(parseVal()); // this will recurse if objects are inside
        ch = currentChar(); // reset char to current
        if (ch != '}' && ch != ',')
          {
            incChar();
          } // if
        trim();
      } // do
    while (currentChar() == ',');

    return object;
  } // parseObject

  /**
   * While there is whitespace ahead, increment char
   *
   * @post this.i is incremented by the number of consecutive whitespaces,
   *       newlines, and then whitespaces again (as is common in formatted JSON)
   */
  public void trim()
  {
    trimSpace();
    trimLines();
    trimSpace();
  } // trim ()

  /**
   * Trims whitespace
   *
   * @post this.i is incremented by the number of consecutive whitespaces
   */
  public void trimSpace()
  {
    while (currentChar() == ' ')
      {
        incChar();
      } // while
  } // trim space

  public void trimLines()
  {
    while (currentChar() == '\n')
      {
        incChar();
      } // while
  }

  public JSONConstant parseConstant()
  {
    char ch = currentChar();
    while (currentChar() != '}' && nextChar() != ',')
      // scan past the constant value
      ; // no Operation
    return new JSONConstant(ch);
  } // parseSpecial

  /**
   *
   * @return a JSONString character containing
   */
  public JSONString parseString()
  {
    return new JSONString(parseStringInner());
  } // parseString ()

  /**
   * Parse the array
   *
   * @return JSONArray
   */
  public JSONArray parseArray()
  {
    JSONArray array = new JSONArray();
    while (currentChar() != ']')
      {
        array.add(parseVal());
        if (currentChar() == '"')
          {
            incChar();
          } // if
        trim();
        // End of objects can be skipped once their objects are parsed
        if (currentChar() == '}')
          {
            incChar();
          } // if
        trim();
      } // while
    return array;
  } // parseArray()

  // select name from schools where type = 'Liberal Arts'

  /*
   * { schools: [{ name: "grinnell", numStudents: 2500 }, { // carlton,
   * numStudents: 1500 }, ] }
   */

  // "0select 1name 2from 3schools 4where 5type 6= [7]2000"

  /**
   * "is" is for equality. (<, >) are for numbers.
   *
   * @param queryIn
   * @return
   * @throws Exception
   */

  public String
    query (String queryIn)
      throws Exception
  {
    String[] args = queryIn.split (" ");

    if (args[0].equalsIgnoreCase("select"))
      {

        int i = 7;

        String temp = "";
        String val;

        if (args[i].charAt (0) == '\'')
          {

            // The use is checking a string, which can have multiple words.
            // E.g. 'Liberal Arts'
            // Go through each subsequent word, and check to see whether that
            // word
            // has a "'" at the end. If it does, then we stop adding it to the
            // val variable.
            // Each time we do this, we must add the word, without the quotation
            // mark, to val.
            // If it's just one word, then take that word without the
            // quotations.
            if (args[i].charAt (args[i].length () - 1) == '\'')
              {
                val = args[i].substring (1, args[i].length () - 1);
              } // if
            else
              {
                // If it's two words, add the first word without the quotations,
                // and the add the others, until the last word, and take that
                // without quotation.
                val = args[i].substring (1, args[i].length ());

                while ((++i < args.length)
                       && (temp = args[i]).charAt (temp.length () - 1) != '\'')
                  {
                    // Concatenate the values, and add a space, because they are
                    // seperate words.
                    val += ' ' + temp;
                  } // while

                val += ' ' + temp.substring (0, temp.length () - 1);
              } // else
          } // if
        else
          {
            val = args[7];
          }

        JSONVal unknown;
        if (val.equals ("null") || val.equals ("true") || val.equals ("false"))
          unknown = new JSONConstant (val.charAt (0));
        else if (Character.isDigit (new Character (val.charAt (0)))
                 || val.charAt (0) == '-')
          unknown = new JSONNumber (val);
        else
          unknown = new JSONString (val);

        return ((JSONArray) this.obj.get (args[3])).selectFilter (args[1],
                                                                  args[6],
                                                                  args[5],
                                                                  unknown)
                                                   .toString ();
      } // if

    return "No results";
  } // query ()

  /**
   * function parseNumber
   *
   * @return a JSONNumber object that contains the value of the number
   */
  public JSONNumber parseNumber()
  {
    // As with string, go until reach a '"' and then get substring
    int startingIndex = this.i;
    char ch;
    boolean decimal = false;
    while ((ch = currentChar()) != ',' && currentChar() != '}')
      {
        if (ch == '.')
          {
            decimal = true; // contains a ., therefore is decimal
          } // if
        ch = nextChar();
      } // while
    return new JSONNumber(this.jsonString.substring(startingIndex, this.i),
                          decimal);
  } // parseNumber()

  /**
   * function parseStringInner
   *
   * @return the value within the string quotes
   * @post this.i is incremented by the number of characters within the string
   */
  public String parseStringInner()
  {
    String stringOut = "";
    int startingIndex = incChar(); // skip the first character

    while (nextChar() != '"')
      ; // No operation.
    stringOut = this.jsonString.substring(startingIndex, this.i);

    return stringOut;
  } // parseStringInner()

  /**
   * Function, parse key
   *
   * @return the key of the key-value pair
   */
  public String parseKey()
  {
    return parseStringInner(); // this is the key
  } // parseKey (String)
}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using BookStore.Domain.Contracts.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using BookStore.Domain.Model;
using Microsoft.AspNetCore.Mvc.Rendering;

// ReSharper disable Mvc.ViewNotResolved

namespace BookStore.Web.Controllers
{
    public class LivrosController : Controller
    {
        private readonly ILivroService _service;
        private readonly IGeneroService _generoService;
        private readonly IAutorService _autorService;

        public LivrosController(ILivroService service,
            IGeneroService generoService,
            IAutorService autorService)
        {
            _service = service;
            _generoService = generoService;
            _autorService = autorService;
        }

        // GET: Livros
        public async Task<IActionResult> Index(string search, int filterType)
        {
            return View(await Task.FromResult(_service.GetAll(search, filterType)));
        }

        // GET: Livros/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var livro = await Task.FromResult(_service.GetById(id.GetValueOrDefault()));
            if (livro == null)
            {
                return NotFound();
            }

            return View(livro);
        }

        // GET: Livros/Create
        public IActionResult Create()
        {
            ViewBag.Autores = _autorService.GetAll();
            ViewBag.Generos = _generoService.GetAll();

            return View();
        }

        // POST: Livros/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(
            [Bind("Nome,DataLancado,AutorId,GeneroId,NumeroPaginas,Corredor,Prateleira,Id")] LivroViewModel livro)
        {
            if (ModelState.IsValid)
            {
                await Task.Run(() => _service.Save(livro));
                return RedirectToAction("Index");
            }
            return View(livro);
        }

        // GET: Livros/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            ViewBag.Autores = _autorService.GetAll();
            ViewBag.Generos = _generoService.GetAll();

            var livro = await Task.FromResult(_service.GetById(id.GetValueOrDefault()));
            if (livro == null)
            {
                return NotFound();
            }
            return View(livro);
        }

        // POST: Livros/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id,
            [Bind("Nome,DataLancado,AutorId,GeneroId,NumeroPaginas,Corredor,Prateleira,Id")] LivroViewModel livro)
        {
            if (id != livro.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    await Task.Run(() => _service.Update(livro));
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!LivroExists(livro.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction("Index");
            }
            return View(livro);
        }

        // GET: Livros/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var livro = await Task.FromResult(_service.GetById(id.GetValueOrDefault()));
            if (livro == null)
            {
                return NotFound();
            }

            return View(livro);
        }

        // POST: Livros/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            await Task.Run(() => _service.Delete(id));
            return RedirectToAction("Index");
        }

        private bool LivroExists(int id)
        {
            return _service.GetById(id) != null;
        }
    }
}


text:
case node[:platform]
when "redhat","centos"
template "/etc/ssh/sshd_config" do
  source "centos_sshd_config.erb"
  mode 600
  owner "root"
  group "root"
end

service "sshd" do
  action :restart
end

when "ubuntu","debian"
template "/etc/ssh/sshd_config" do
  source "ubu_sshd_config.erb"
  mode 600
  owner "root"
  group "root"
end

service "ssh" do
  action :restart
end
end

# Add our group only if it doesn't already exist

execute "groupadd sftp-users" do
  not_if "grep sftp-users /etc/group"
end

# If user already exists, reset it
case node[:platform]
when "redhat","centos"
execute "usermod -s /bin/false -g sftp-users bobdole && echo 'bobsaget' | passwd --stdin bobdole && usermod -L bobdole" do
  only_if "id bobdole"
end

when "ubuntu","debian"
execute "usermod -s /bin/false -g sftp-users -p `mkpasswd bobsaget` bobdole && usermod -L bobdole" do
  only_if "id bobdole"
end
end

# Add user account if it doesn't exist

case node[:platform]
when "redhat","centos"
execute "useradd -s /bin/false -g sftp-users bobdole && echo 'bobsaget' | passwd --stdin bobdole && usermod -L bobdole" do
  not_if "id bobdole"
end

when "ubuntu","debian"
execute "useradd -s /bin/false -g sftp-users -m -p `mkpasswd bobsaget` bobdole && usermod -L bobdole" do
  not_if "id bobdole"
end
end

# Reset home folder permissions cause we're evil

directory "/home/bobdole" do
  owner "bobdole"
  group "sftp-users"
  mode 0700
end


text:
title: Blog 5- Neatening up the code.
layout: post
author: thomas.hitchman
permalink: /blog-5--neatening-up-the-code./
source-id: 1mJwXZFNnbRmfw5GXka63OjlCAdm4m6AgbTyQ-K5mrPk
published: true
---

    Title:
    Finishing up and neatening up.
    Date:
    10/10/18

    Starting point:
    We had a shift cipher code and were trying to fix it.

    Target for this lesson?
    We had to finish up our code, and neaten it up in a format that looked professional.

    Did I reach my target?
(add details to "Lesson Review")
    Yes I did, and I had only just finished it by the end of the lesson.

    Lesson Review

    How did I learn? What strategies were effective?

     I just mainly learnt by looking at the board- this was was much more important than last lesson because there were certain layouts and things like how to hide tabs for code and such. However, due to doing not much in the lesson beforehand because of the start of an illness, I was helped by a fellow student in between lessons so I could catch up and get it to work.

    What limited my learning? Which habits do I need to work on?

    One part of my code did not work when I moved it over to a separate tab, when the rest of this did. It meant I had to spend a while trying to figure out how to make it more neat. I eventually had to move the main part over to a different slide and hide all the coding on the first one.

    What will I change for next time? How will I improve my learning?

    Next time I will try yo get my code even neater, maybe by laying it out in a larger space instead of in the top left corner, so it looks nicer. This would make some things clearer, but it still leaves lots of unused space, like it does now/


text:
package com.jetbrains.python;

import com.intellij.codeInsight.TargetElementUtil;
import com.intellij.codeInsight.documentation.DocumentationManager;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowType;
import com.intellij.openapi.wm.WindowManager;

import java.awt.*;

public class PyDocumentationManager extends DocumentationManager {

  public PyDocumentationManager(Project project, ActionManager manager, TargetElementUtil targetElementUtil) {
    super(project, manager, targetElementUtil);
  }

  @Override
  protected void setToolwindowDefaultState() {
    final Rectangle rectangle = WindowManager.getInstance().getIdeFrame(myProject).suggestChildFrameBounds();
    myToolWindow.setDefaultState(ToolWindowAnchor.RIGHT, ToolWindowType.DOCKED, new Rectangle(rectangle.width/4, rectangle.height));
    myToolWindow.setType(ToolWindowType.DOCKED, null);
    myToolWindow.setAutoHide(false);
  }
}


text:
using Newtonsoft.Json;
namespace LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects

{

    /// <summary>
    ///	Response containing Definition for Complete Video data
    /// </summary>
    public class Video
    {
		/// <summary>
		///	Date of Creation of Profile
		/// </summary>
		[JsonProperty(PropertyName = "CreatedDate")]
        public  string CreatedDate {get;set;}

		/// <summary>
		///	detailed information
		/// </summary>
		[JsonProperty(PropertyName = "Description")]
        public  string Description {get;set;}

		/// <summary>
		///	Video direct link
		/// </summary>
		[JsonProperty(PropertyName = "DirectLink")]
        public  string DirectLink {get;set;}

		/// <summary>
		///	Video duration
		/// </summary>
		[JsonProperty(PropertyName = "Duration")]
        public  string Duration {get;set;}

		/// <summary>
		///	Embed html of video
		/// </summary>
		[JsonProperty(PropertyName = "EmbedHtml")]
        public  string EmbedHtml {get;set;}

		/// <summary>
		///	Video id
		/// </summary>
		[JsonProperty(PropertyName = "ID")]
        public  string ID {get;set;}

		/// <summary>
		///	image URL should be absolute and has HTTPS domain
		/// </summary>
		[JsonProperty(PropertyName = "Image")]
        public  string Image {get;set;}

		/// <summary>
		///	Video name
		/// </summary>
		[JsonProperty(PropertyName = "Name")]
        public  string Name {get;set;}

		/// <summary>
		///	Video owner id
		/// </summary>
		[JsonProperty(PropertyName = "OwnerId")]
        public  string OwnerId {get;set;}

		/// <summary>
		///	Video owner name
		/// </summary>
		[JsonProperty(PropertyName = "OwnerName")]
        public  string OwnerName {get;set;}

		/// <summary>
		///	Source of video
		/// </summary>
		[JsonProperty(PropertyName = "Source")]
        public  string Source {get;set;}

		/// <summary>
		///	Updated date
		/// </summary>
		[JsonProperty(PropertyName = "UpdatedDate")]
        public  string UpdatedDate {get;set;}

    }
}


text:
#include <common/Database.h>
#include <factory/Language.h>
#include <psql/Language.h>

namespace DbObjects
{

namespace Factory
{

/*!
 * \param[in] ipName - Name of a language that is going to be constructed
 *
 * \return Pointer to database language object
 */
DbObjects::Common::DbLanguage*
Language::createLanguage(const QString &ipName)
{
    using namespace DbObjects::Common;

    DbLanguage *lang = 0;

    switch (Database::instance()->sqlDriver()) {
        case Database::PostgreSQL:
                lang = createPsqlLanguage(ipName);
                break;
        case Database::MySQL:
        case Database::Oracle:
        case Database::SQLite:
        case Database::Unknown:
        default:
                break;
    }

    // if language creation failed or the information cannot be read from database
//    if (!lang || !lang->loadData()) {
//        delete lang;
//        lang = 0;
//    }

    return lang;
}

/*!
 * \param[in] ipName - Name of a language that is going to be constructed
 *
 * \return Pointer to PostgreSQL language object
 */
Psql::Language*
Language::createPsqlLanguage(const QString &ipName)
{
    return new(std::nothrow) Psql::Language(ipName);
}

} // namespace Factory

} // namespace DbObjects


text:
;------------------------------------------------------------------------------
;
; MemoryFence() for AArch64
;
; Copyright (c) 2013, ARM Ltd. All rights reserved.
;
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution.  The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php.
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
;------------------------------------------------------------------------------

    EXPORT MemoryFence

    AREA MemoryBarriers, CODE, READONLY

;/**
;  Used to serialize load and store operations.
;
;  All loads and stores that proceed calls to this function are guaranteed to be
;  globally visible when this function returns.
;
;**/
;VOID
;EFIAPI
;MemoryFence (
;  VOID
;  );
;
MemoryFence FUNCTION
    dmb
    bx      lr
    ENDFUNC

    END


text: Paytheartist::Application.config.session_store :cookie_store, key: '_paytheartist_session'


text:
@class FlatDatePicker;

@protocol FlatDatePickerDelegate<NSObject>
@optional
- (void)flatDatePicker:(FlatDatePicker*)datePicker dateDidChange:(NSDate*)date;
- (void)flatDatePicker:(FlatDatePicker*)datePicker didCancel:(UIButton*)sender;
- (void)flatDatePicker:(FlatDatePicker*)datePicker didValid:(UIButton*)sender date:(NSDate*)date;
@end

typedef NS_ENUM(NSInteger, FlatDatePickerMode) {
    FlatDatePickerModeTime,           // Displays hour, minute, and optionally AM/PM designation depending on the locale setting (e.g. 6 | 53 | PM)
    FlatDatePickerModeDate,           // Displays month, day, and year depending on the locale setting (e.g. November | 15 | 2007)
    FlatDatePickerModeDateAndTime    // Displays date, hour, minute, and optionally AM/PM designation depending on the locale setting (e.g. Wed Nov 15 |
};

@interface FlatDatePicker : UIControl <UIScrollViewDelegate> {

    // Parent View :
    UIView *_parentView;

    // Header :
    UILabel *_labelTitle;
    UIButton *_buttonClose;
    UIButton *_buttonValid;

    // ScrollView :
    UIScrollView *_scollViewDays;
    UIScrollView *_scollViewMonths;
    UIScrollView *_scollViewYears;

    // Lines :
    UIView *_lineDaysTop;
    UIView *_lineDaysBottom;
    UIView *_lineMonthsTop;
    UIView *_lineMonthsBottom;
    UIView *_lineYearsTop;
    UIView *_lineYearsBottom;

    // Title :
    NSString *_title;

    // Days, Months, Years :
    NSMutableArray *_days;
    NSMutableArray *_months;
    NSMutableArray *_years;

    // Labels :
    NSMutableArray *_labelsDays;
    NSMutableArray *_labelsMonths;
    NSMutableArray *_labelsYears;

    // Date selected :
    int _selectedDay;
    int _selectedMonth;
    int _selectedYear;

    // First init flag :
    BOOL _isInitialized;
}

@property (nonatomic, strong) NSObject<FlatDatePickerDelegate> *delegate;

@property(nonatomic) FlatDatePickerMode datePickerMode;           // default is UIDatePickerModeDateAndTime

@property(nonatomic,retain) NSLocale      *locale;                // default is [NSLocale currentLocale]. setting nil returns to default
@property(nonatomic,copy)   NSCalendar    *calendar;              // default is [NSCalendar currentCalendar]. setting nil returns to default
@property(nonatomic,retain) NSTimeZone    *timeZone;              // default is nil. use current time zone or time zone from calendar

@property(nonatomic,retain) NSDate        *minimumDate;           // specify min/max date range. default is nil. When min > max, the values are ignored. Ignored in countdown timer mode
@property(nonatomic,retain) NSDate        *maximumDate;           // default is nil

- (id)initWithParentView:(UIView*)parentView;

#pragma mark - Show and Dismiss

- (void)show;
- (void)dismiss;

#pragma mark - Title DatePicker

- (void)setTitle:(NSString *)title;
- (NSString*)title;

#pragma mark - Date

- (void)setDate:(NSDate *)date animated:(BOOL)animated;
- (NSDate*)getDate;

@end


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.storage.model;

/**
 * An access-control entry.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Storage JSON API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class ObjectAccessControl extends com.google.api.client.json.GenericJson {

  /**
   * The name of the bucket.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String bucket;

  /**
   * The domain associated with the entity, if any.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String domain;

  /**
   * The email address associated with the entity, if any.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String email;

  /**
   * The entity holding the permission, in one of the following forms: - user-userId  - user-email
   * - group-groupId  - group-email  - domain-domain  - project-team-projectId  - allUsers  -
   * allAuthenticatedUsers Examples:  - The user liz@example.com would be user-liz@example.com.  -
   * The group example@googlegroups.com would be group-example@googlegroups.com.  - To refer to all
   * members of the Google Apps for Business domain example.com, the entity would be domain-
   * example.com.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String entity;

  /**
   * The ID for the entity, if any.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String entityId;

  /**
   * HTTP 1.1 Entity tag for the access-control entry.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String etag;

  /**
   * The content generation of the object, if applied to an object.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.lang.Long generation;

  /**
   * The ID of the access-control entry.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String id;

  /**
   * The kind of item this is. For object access control entries, this is always
   * storage#objectAccessControl.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String kind;

  /**
   * The name of the object, if applied to an object.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key("object")
  private java.lang.String object__;

  /**
   * The project team associated with the entity, if any.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private ProjectTeam projectTeam;

  /**
   * The access permission for the entity.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String role;

  /**
   * The link to this access-control entry.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String selfLink;

  /**
   * The name of the bucket.
   * @return value or {@code null} for none
   */
  public java.lang.String getBucket() {
    return bucket;
  }

  /**
   * The name of the bucket.
   * @param bucket bucket or {@code null} for none
   */
  public ObjectAccessControl setBucket(java.lang.String bucket) {
    this.bucket = bucket;
    return this;
  }

  /**
   * The domain associated with the entity, if any.
   * @return value or {@code null} for none
   */
  public java.lang.String getDomain() {
    return domain;
  }

  /**
   * The domain associated with the entity, if any.
   * @param domain domain or {@code null} for none
   */
  public ObjectAccessControl setDomain(java.lang.String domain) {
    this.domain = domain;
    return this;
  }

  /**
   * The email address associated with the entity, if any.
   * @return value or {@code null} for none
   */
  public java.lang.String getEmail() {
    return email;
  }

  /**
   * The email address associated with the entity, if any.
   * @param email email or {@code null} for none
   */
  public ObjectAccessControl setEmail(java.lang.String email) {
    this.email = email;
    return this;
  }

  /**
   * The entity holding the permission, in one of the following forms: - user-userId  - user-email
   * - group-groupId  - group-email  - domain-domain  - project-team-projectId  - allUsers  -
   * allAuthenticatedUsers Examples:  - The user liz@example.com would be user-liz@example.com.  -
   * The group example@googlegroups.com would be group-example@googlegroups.com.  - To refer to all
   * members of the Google Apps for Business domain example.com, the entity would be domain-
   * example.com.
   * @return value or {@code null} for none
   */
  public java.lang.String getEntity() {
    return entity;
  }

  /**
   * The entity holding the permission, in one of the following forms: - user-userId  - user-email
   * - group-groupId  - group-email  - domain-domain  - project-team-projectId  - allUsers  -
   * allAuthenticatedUsers Examples:  - The user liz@example.com would be user-liz@example.com.  -
   * The group example@googlegroups.com would be group-example@googlegroups.com.  - To refer to all
   * members of the Google Apps for Business domain example.com, the entity would be domain-
   * example.com.
   * @param entity entity or {@code null} for none
   */
  public ObjectAccessControl setEntity(java.lang.String entity) {
    this.entity = entity;
    return this;
  }

  /**
   * The ID for the entity, if any.
   * @return value or {@code null} for none
   */
  public java.lang.String getEntityId() {
    return entityId;
  }

  /**
   * The ID for the entity, if any.
   * @param entityId entityId or {@code null} for none
   */
  public ObjectAccessControl setEntityId(java.lang.String entityId) {
    this.entityId = entityId;
    return this;
  }

  /**
   * HTTP 1.1 Entity tag for the access-control entry.
   * @return value or {@code null} for none
   */
  public java.lang.String getEtag() {
    return etag;
  }

  /**
   * HTTP 1.1 Entity tag for the access-control entry.
   * @param etag etag or {@code null} for none
   */
  public ObjectAccessControl setEtag(java.lang.String etag) {
    this.etag = etag;
    return this;
  }

  /**
   * The content generation of the object, if applied to an object.
   * @return value or {@code null} for none
   */
  public java.lang.Long getGeneration() {
    return generation;
  }

  /**
   * The content generation of the object, if applied to an object.
   * @param generation generation or {@code null} for none
   */
  public ObjectAccessControl setGeneration(java.lang.Long generation) {
    this.generation = generation;
    return this;
  }

  /**
   * The ID of the access-control entry.
   * @return value or {@code null} for none
   */
  public java.lang.String getId() {
    return id;
  }

  /**
   * The ID of the access-control entry.
   * @param id id or {@code null} for none
   */
  public ObjectAccessControl setId(java.lang.String id) {
    this.id = id;
    return this;
  }

  /**
   * The kind of item this is. For object access control entries, this is always
   * storage#objectAccessControl.
   * @return value or {@code null} for none
   */
  public java.lang.String getKind() {
    return kind;
  }

  /**
   * The kind of item this is. For object access control entries, this is always
   * storage#objectAccessControl.
   * @param kind kind or {@code null} for none
   */
  public ObjectAccessControl setKind(java.lang.String kind) {
    this.kind = kind;
    return this;
  }

  /**
   * The name of the object, if applied to an object.
   * @return value or {@code null} for none
   */
  public java.lang.String getObject() {
    return object__;
  }

  /**
   * The name of the object, if applied to an object.
   * @param object__ object__ or {@code null} for none
   */
  public ObjectAccessControl setObject(java.lang.String object__) {
    this.object__ = object__;
    return this;
  }

  /**
   * The project team associated with the entity, if any.
   * @return value or {@code null} for none
   */
  public ProjectTeam getProjectTeam() {
    return projectTeam;
  }

  /**
   * The project team associated with the entity, if any.
   * @param projectTeam projectTeam or {@code null} for none
   */
  public ObjectAccessControl setProjectTeam(ProjectTeam projectTeam) {
    this.projectTeam = projectTeam;
    return this;
  }

  /**
   * The access permission for the entity.
   * @return value or {@code null} for none
   */
  public java.lang.String getRole() {
    return role;
  }

  /**
   * The access permission for the entity.
   * @param role role or {@code null} for none
   */
  public ObjectAccessControl setRole(java.lang.String role) {
    this.role = role;
    return this;
  }

  /**
   * The link to this access-control entry.
   * @return value or {@code null} for none
   */
  public java.lang.String getSelfLink() {
    return selfLink;
  }

  /**
   * The link to this access-control entry.
   * @param selfLink selfLink or {@code null} for none
   */
  public ObjectAccessControl setSelfLink(java.lang.String selfLink) {
    this.selfLink = selfLink;
    return this;
  }

  @Override
  public ObjectAccessControl set(String fieldName, Object value) {
    return (ObjectAccessControl) super.set(fieldName, value);
  }

  @Override
  public ObjectAccessControl clone() {
    return (ObjectAccessControl) super.clone();
  }

  /**
   * The project team associated with the entity, if any.
   */
  public static final class ProjectTeam extends com.google.api.client.json.GenericJson {

    /**
     * The project number.
     * The value may be {@code null}.
     */
    @com.google.api.client.util.Key
    private java.lang.String projectNumber;

    /**
     * The team.
     * The value may be {@code null}.
     */
    @com.google.api.client.util.Key
    private java.lang.String team;

    /**
     * The project number.
     * @return value or {@code null} for none
     */
    public java.lang.String getProjectNumber() {
      return projectNumber;
    }

    /**
     * The project number.
     * @param projectNumber projectNumber or {@code null} for none
     */
    public ProjectTeam setProjectNumber(java.lang.String projectNumber) {
      this.projectNumber = projectNumber;
      return this;
    }

    /**
     * The team.
     * @return value or {@code null} for none
     */
    public java.lang.String getTeam() {
      return team;
    }

    /**
     * The team.
     * @param team team or {@code null} for none
     */
    public ProjectTeam setTeam(java.lang.String team) {
      this.team = team;
      return this;
    }

    @Override
    public ProjectTeam set(String fieldName, Object value) {
      return (ProjectTeam) super.set(fieldName, value);
    }

    @Override
    public ProjectTeam clone() {
      return (ProjectTeam) super.clone();
    }

  }

}


text:
from core.services import dashboard_service
from cli_tools.soundwave.tables import timeseries

CLOUD_PATH = 'gs://chrome-health-tvdata/datasets/weblayer_study.csv'

SYSTEM_HEALTH = [
    {
        'test_suite': 'system_health.memory_mobile',
        'measurement': ('memory:chrome:all_processes:reported_by_os:'
                        'private_footprint_size_avg'),
    }
]

STARTUP_BY_BROWSER = {
    'cct': {
        'test_suite': 'startup.mobile',
        'measurement': 'first_contentful_paint_time',
        'test_case': 'cct_coldish_bbc'
    },
    'weblayer': {
        'test_suite': 'startup.mobile',
        'measurement': 'first_contentful_paint_time',
        'test_case': 'intent_coldish_bbc'
    },
}

def IterSystemHealthBots():
  yield 'ChromiumPerf:android-pixel2-perf'
  yield 'ChromiumPerf:android-pixel2_weblayer-perf'

def GetBrowserFromBot(bot):
  return 'weblayer' if 'weblayer' in bot else 'cct'

def GetHealthCheckStories():
  description = dashboard_service.Describe('system_health.common_mobile')
  return description['caseTags']['health_check']

def IterTestPaths():
  test_cases = GetHealthCheckStories()
  for bot in IterSystemHealthBots():
    browser = GetBrowserFromBot(bot)

    # Startup.
    yield timeseries.Key.FromDict(STARTUP_BY_BROWSER[browser], bot=bot)

    for series in SYSTEM_HEALTH:
      measurement = series['measurement']
      for test_case in test_cases:
        print timeseries.Key.FromDict(
            series, bot=bot, measurement=measurement, test_case=test_case)
        yield timeseries.Key.FromDict(
            series, bot=bot, measurement=measurement, test_case=test_case)


text:
package org.apache.geode.internal.cache;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.distributed.internal.ClusterDistributionManager;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.internal.cache.TXCommitMessage.RegionCommit;
import org.apache.geode.test.junit.categories.UnitTest;

@Category(UnitTest.class)
public class RegionCommitTest {

  private ClusterDistributionManager dm;
  private String path;
  private LocalRegion region;
  private TXCommitMessage txCommitMessage;

  @Before
  public void setUp() {
    path = "path";

    InternalCache cache = mock(InternalCache.class);

    dm = mock(ClusterDistributionManager.class);
    region = mock(LocalRegion.class);
    txCommitMessage = mock(TXCommitMessage.class);

    when(dm.getCache()).thenReturn(cache);
    when(cache.getRegionByPath(path)).thenReturn(region);
    when(dm.getSystem()).thenReturn(mock(InternalDistributedSystem.class));
  }

  @Test
  public void getsRegionFromCacheFromDM() {
    RegionCommit regionCommit = new RegionCommit(txCommitMessage);
    assertThat(regionCommit.getRegionByPath(dm, path)).isEqualTo(region);
  }
}


text:
namespace miso {
//------------------------------------------------------------------------------

class client_interface
{
public:
    virtual bool send_raw(const void* data, std::uint16_t size) = 0;
    virtual std::uint16_t recv_raw(void* data, std::uint16_t size) = 0;
};

//------------------------------------------------------------------------------
}


text:
package org.apache.camel.component.quartz;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Trigger;

/**
 * This test the  CronTrigger as a timer endpoint in a route.
 */
public class QuartzCronRouteTest extends BaseQuartzTest {

    @Test
    public void testQuartzCronRoute() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMinimumMessageCount(3);

        assertMockEndpointsSatisfied();

        Trigger trigger = mock.getReceivedExchanges().get(0).getIn().getHeader("trigger", Trigger.class);
        Assert.assertThat(trigger instanceof CronTrigger, CoreMatchers.is(true));

        JobDetail detail = mock.getReceivedExchanges().get(0).getIn().getHeader("jobDetail", JobDetail.class);
        Assert.assertThat(detail.getJobClass().equals(CamelJob.class), CoreMatchers.is(true));

        Assert.assertThat(detail.getJobDataMap().get(QuartzConstants.QUARTZ_TRIGGER_TYPE).equals("cron"), CoreMatchers.is(true));
        Assert.assertThat(detail.getJobDataMap().get(QuartzConstants.QUARTZ_TRIGGER_CRON_EXPRESSION).equals("0/1 * * * * ?"), CoreMatchers.is(true));
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() {
                // triggers every 1th second at precise 00,01,02,03..59
                from("quartz://myGroup/myTimerName?cron=0/1 * * * * ?").to("mock:result");
            }
        };
    }
}


text:
SCRIPTPATH=`dirname "${BASH_SOURCE[0]}"`;

# import config vars
source ${SCRIPTPATH}/../config.sh;

# list customizations to install
customs=(
  "system-settings"
  "user-settings"
)

# execute selected customizations
for custom in ${customs[@]}; do
  source `dirname "${BASH_SOURCE[0]}"`/${custom}.sh;
done


text:
"""
Copyright 2015-2018 Jacob M. Graving <jgraving@gmail.com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import numpy as np
import imgstore

__all__ = ['StoreFrameReader', 'StoreReader']

class StoreFrameReader:

    def __init__(self, path):
        self.store = imgstore.new_for_filename(path)
        self.metadata = self.store.get_frame_metadata()
        self.metaindex = np.array(self.metadata['frame_number'])
        self.shape = self.store.image_shape

    def __len__(self):
        return self.metaindex.shape[0]

    def get_data(self, indexes):
        indexes = self.metaindex[indexes]

        frames = []
        frames_idx = []
        timestamps = []
        for idx in indexes:
            if idx is self.store.frame_number + 1:
                frame, (frame_idx, timestamp) = self.store.get_next_framenumber(exact_only=False)
            else:
                frame, (frame_idx, timestamp) = self.store.get_image(idx, exact_only=False)
            frames.append(frame)
            frames_idx.append(frame_idx)
            timestamps.append(timestamp)
        frames = np.stack(frames)
        if frames.ndim == 3:
            frames = frames[..., np.newaxis]
        frames_idx = np.array(frames_idx)
        timestamps = np.array(timestamps)

        return frames, frames_idx, timestamps

    def _check_index(self, key):
        if isinstance(key, slice):
            start = key.start
            stop = key.stop
            if start is None:
                start = 0
            if stop is None or stop >= len(self):
                stop = len(self)
            if stop <= len(self):
                idx = range(start, stop)
            else:
                raise IndexError
        elif isinstance(key, (int, np.integer)):
            if key < len(self):
                idx = [key]
            else:
                raise IndexError
        elif isinstance(key, np.ndarray):
            if np.max(key) < len(self):
                idx = key.tolist()
            else:
                raise IndexError
        elif isinstance(key, list):
            if max(key) < len(self):
                idx = key
            else:
                raise IndexError
        else:
            raise IndexError
        return idx

    def __getitem__(self, key):
        indexes = self._check_index(key)
        return self.get_data(indexes)

class StoreReader:

    def __init__(self, path, batch_size):
        self.path = path
        self.store = StoreFrameReader(path)
        self.shape = self.store.shape
        self.batch_size = batch_size
        self.idx = 0

    def __len__(self):
        return int(np.ceil(self.n_frames / float(self.batch_size)))

    @property
    def n_frames(self):
        return len(self.store)

    def get_batch(self, index=None):
        if index:
            if isinstance(index, (int, np.integer)):
                if index < 0:
                    index += len(self)
                if index < len(self):
                    idx0 = index * self.batch_size
                    idx1 = idx0 + self.batch_size
                    self.idx = index
                else:
                    raise IndexError('index out of range')
            else:
                raise NotImplementedError
        else:
            if self.idx >= len(self) - 1:
                self.idx = 0
            if self.idx < len(self) - 1:
                idx0 = self.idx * self.batch_size
                idx1 = idx0 + self.batch_size
                self.idx += 1
            else:
                raise StopIteration

        return self.store[idx0:idx1]

    def __getitem__(self, index):
        return self.get_batch(index)


text:
'use strict'
var fs = require('fs');
var readLine = require('readline');

/**
 * A utility that  reads the full list of customers and output the names and user ids of matching customers (within given meters), sorted by User ID (ascending).
 *
 * @class GCDCalculator
 * @constructor
 */
function GCDCalculator() {};

/**
 * My method description.  Like other pieces of your comment blocks,
 * this can span multiple lines.
 *
 * @method getDistanceFromJson
 * @param {String} path to the json file
 * @param {Array} array of integers with latitude and longitude in degrees
 * @param {Integer} distance to match in metres
 * @param {Function} callback function on the compliation of the computation, which returns an array with matched results
 */
GCDCalculator.prototype.getDistanceFromJson = function getDistanceFromJson(jsonPath, cord, m, callback) {
  var result = [];
  //check function arguments
  if (jsonPath == null || cord == null || m == null || isNaN(m) || callback == null) {
    throw new Error("Wrong argument passing");
  }
  //create an interface with a stream reader
  var lineReader = readLine.createInterface({
    input: fs.createReadStream(jsonPath).on('error', function(error) {
      //return error if file doesn't exist
      callback(error, null);
    })
  });

  //read json file line by line
  lineReader.on('line', function(line) {
    var el = JSON.parse(line);
    //calculate the distance for the parsed line
    var dist = _getDistance([el["latitude"], el["longitude"]], cord);
    //collect results if within the passed meters threshold
    if (dist < m) {
      result = _insert({
        user_id: el["user_id"],
        name: el["name"]
      }, result)
    }
  }).on('close', function() {
    //return results in the callback
    callback(null, result);
  });
};

/**
 * Private method _getDistance to calculate the distance between two coordinates
 *
 * @method _getDistance
 * @private
 * @param {Array} first cordinate array of integers with latitude and longitude in degrees
 * @param {Array} second cordinate array of integers with latitude and longitude in degrees
 * @return {Integer} great-circle distance in metres
 */
var _getDistance = function(cord1, cord2) {
  // Converts numeric degrees to radians
  var toRadians = function(num) {
    return num * Math.PI / 180;
  }
  var lat1 = cord1[0],
    lat2 = cord2[0],
    lon1 = cord1[1],
    lon2 = cord2[1],
    φ1 = toRadians(lat1),
    φ2 = toRadians(lat2),
    Δλ = toRadians(lon2 - lon1),
    R = 6371000; // gives d in metres

  var d = Math.acos(Math.sin(φ1) * Math.sin(φ2) + Math.cos(φ1) * Math.cos(φ2) * Math.cos(Δλ)) * R;
  return d;
}

/**
 * Private method to insert integer in order (Quicksort) in the array.
 * note: faster the standard sort because applied on buffered read on line
 *
 * @method _insert
 * @private
 * @param {Integer} element to insert into the array
 * @param {Array} array to update
 * @return {Array} updated array
 */
function _insert(element, array) {
  array.splice(_locationOf(element, array, _userIdCompare) + 1, 0, element);
  return array;
}

/**
 * Private function object _userIdCompare to compare two records in customer json file
 *
 * @method _userIdCompare
 * @private
 * @param {Array} first cordinate array of integers with latitude and longitude in degrees
 * @param {Array} second cordinate array of integers with latitude and longitude in degrees
 * @return {Integer} great-circle distance in metres
 */
var _userIdCompare = function(a, b) {
  if (a.user_id < b.user_id) return -1;
  if (a.user_id > b.user_id) return 1;
  return 0;
};

/**
 * Private method to find location of element into array (Quicksort)
 *
 * @method _locationOf
 * @private
 * @param {Integer} element to locate
 * @param {Array} array to compute the location
 * @param {Function} comparer function in array
 * @param {Integer} starting index to search
 * @param {Integer} ending index to search
 * @return {Integer} location to insert the element in array
 */
function _locationOf(element, array, comparer, start, end) {
  if (array.length === 0) {
    return -1;
  }
  start = start || 0;
  end = end || array.length;
  var pivot = (start + end) >> 1;
  var c = comparer(element, array[pivot]);
  if (end - start <= 1) return c == -1 ? pivot - 1 : pivot;

  switch (c) {
    case -1:
      return _locationOf(element, array, comparer, start, pivot);
    case 0:
      return pivot;
    case 1:
      return _locationOf(element, array, comparer, pivot, end);
  };
};

module.exports = GCDCalculator;


text:
import {Component, OnInit} from "@angular/core";
import {Router, ActivatedRoute, Params} from "@angular/router";
import {User} from "../../models/user.model.app";
import {IdeaService} from "../../services/idea.service";

@Component({
    selector: "idea-responses",
    templateUrl: "./idea-responses.component.html",
    styles: [ require("./idea-responses.component.css").toString() ]
})
export class IdeaResponsesComponent implements OnInit {

    private title: string = "";

    private likes: User[] = [];
    private likesMessage: string = "Loading...";
    private comments: User[] = [];
    private commentsMessage: string = "Loading...";

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private ideaService: IdeaService) {

    }

    ngOnInit(): void {
        this.route.params.forEach((params: Params) => {
            let ideaId = params["id"];

            this.ideaService.getTitle(ideaId)
                .subscribe((json: any) => {
                    this.title = json.fail || json.title;
                });

            this.ideaService.getLikes(ideaId)
                .subscribe((json: any) => {
                    if (json.fail) {
                        this.likesMessage = json.fail;
                    } else {
                        this.pushLikes(json);
                        if (this.likes.length === 0) {
                            this.likesMessage = "There are no likes for this idea.";
                        } else {
                            this.likesMessage = "";
                        }
                    }
                });

            this.ideaService.getComments(ideaId)
                .subscribe((json: any) => {
                    if (json.fail) {
                        this.commentsMessage = json.fail;
                    } else {
                        this.pushComments(json);
                        if (this.comments.length === 0) {
                            this.commentsMessage = "There are no comments for this idea.";
                        } else {
                            this.commentsMessage = "";
                        }
                    }
                });
        });
    }

    private pushLikes(json: any): void {
        json.list.map((item: any) => {
            this.likes.push(new User(item.id, "", "user",
                item.name, "", item.profilePic,
                new Date(0), new Date(0), new Date(item.timestamp)));
        });
    }

    private pushComments(json: any): void {
        json.list.map((item: any) => {
            let user: User = new User(item.author.id, "", "user",
                item.author.name, "", item.author.profilePic,
                new Date(0), new Date(0), new Date(item.comment.timestamp));
            (user as any).comment = item.comment.text;
            this.comments.push(user);
        });
    }

}


text:
using UnityEngine;
using System.Collections;

public abstract class Switch : MonoBehaviour {

    public SwitchEvent parent;

}