Create an HTLC contract
542090
def create(ctx, to, amount, symbol, secret, hash, account, expiration):
    
    ctx.blockchain.blocking = True
    tx = ctx.blockchain.htlc_create(
        Amount(amount, symbol),
        to,
        secret,
        hash_type=hash,
        expiration=expiration,
        account=account,
    )
    tx.pop("trx", None)
    print_tx(tx)
    results = tx.get("operation_results", {})
    if results:
        htlc_id = results[0][1]
        print("Your htlc_id is: {}".format(htlc_id))
1014036
def generate_contracts(input_dir, output_dir, host)
      WebMock.allow_net_connect!
      generator = Pacto::Generator.contract_generator
      puts "Generating contracts from partial contracts in #{input_dir} and recording to #{output_dir}\n\n"

      failed_contracts = []
      each_contract(input_dir) do |contract_file|
        begin
          contract = generator.generate_from_partial_contract(contract_file, host)
          output_file = File.expand_path(File.basename(contract_file), output_dir)
          output_file = File.open(output_file, 'wb')
          output_file.write contract
          output_file.flush
          output_file.close
        rescue InvalidContract => e
          failed_contracts << contract_file
          puts Pacto::UI.colorize(e.message, :red)
        end
      end

      if failed_contracts.empty?
        puts Pacto::UI.colorize('Successfully generated all contracts', :green)
      else
        fail Pacto::UI.colorize("The following contracts could not be generated: #{failed_contracts.join ','}", :red)
      end
    end
1108598
public void createDir(String key, int ttl, Boolean prevExist) throws EtcdClientException {
        Preconditions.checkNotNull(key);

        List<BasicNameValuePair> data = Lists.newArrayList();
        data.add(new BasicNameValuePair("dir", String.valueOf(true)));
        if (ttl > 0) {
            data.add(new BasicNameValuePair("ttl", String.valueOf(ttl)));
        }
        if (prevExist != null) {
            data.add(new BasicNameValuePair("prevExist", String.valueOf(prevExist)));
        }

        put(key, data, null, new int[]{200, 201});
    }
1031021
function buildBuilder(mqttClient, opts) {
   var connection;

   connection = tls.connect(opts);

   function handleTLSerrors(err) {
      mqttClient.emit('error', err);
      connection.end();
   }

   connection.on('secureConnect', function() {
      if (!connection.authorized) {
         connection.emit('error', new Error('TLS not authorized'));
      } else {
         connection.removeListener('error', handleTLSerrors);
      }
   });

   connection.on('error', handleTLSerrors);
   return connection;
}
1313936
def _make_txn(signer, setting_key, payload):
    
    serialized_payload = payload.SerializeToString()
    header = TransactionHeader(
        signer_public_key=signer.get_public_key().as_hex(),
        family_name='sawtooth_settings',
        family_version='1.0',
        inputs=_config_inputs(setting_key),
        outputs=_config_outputs(setting_key),
        dependencies=[],
        payload_sha512=hashlib.sha512(serialized_payload).hexdigest(),
        batcher_public_key=signer.get_public_key().as_hex()
    ).SerializeToString()

    return Transaction(
        header=header,
        header_signature=signer.sign(header),
        payload=serialized_payload)
387923
def create(**kwargs):
        
        secType = kwargs.get('secType', '')
        cls = {
            '': Contract,
            'STK': Stock,
            'OPT': Option,
            'FUT': Future,
            'CONTFUT': ContFuture,
            'CASH': Forex,
            'IND': Index,
            'CFD': CFD,
            'BOND': Bond,
            'CMDTY': Commodity,
            'FOP': FuturesOption,
            'FUND': MutualFund,
            'WAR': Warrant,
            'IOPT': Warrant,
            'BAG': Bag,
            'NEWS': Contract
        }.get(secType, Contract)
        if cls is not Contract:
            kwargs.pop('secType', '')
        return cls(**kwargs)
218157
def create(self, product_id, period, csr, software_id, organization_handle,
               approver_email=None, signature_hash_algorithm=None, domain_validation_methods=None,
               hostnames=None, technical_handle=None):
        """"""

        response = self.request(E.createSslCertRequest(
            E.productId(product_id),
            E.period(period),
            E.csr(csr),
            E.softwareId(software_id),
            E.organizationHandle(organization_handle),
            OE('approverEmail', approver_email),
            OE('signatureHashAlgorithm', signature_hash_algorithm),
            OE('domainValidationMethods', domain_validation_methods, transform=_domain_validation_methods),
            OE('hostNames', hostnames, transform=_simple_array),
            OE('technicalHandle', technical_handle),
        ))

        return int(response.data.id)
233646
private static OkHttpClient.Builder enableTls12(OkHttpClient.Builder client) {
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                    TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:"
                        + Arrays.toString(trustManagers));
            }
            X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
            client.sslSocketFactory(new TLSSocketFactory(), trustManager);
            ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                    .tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1)
                    .build();
            List<ConnectionSpec> specs = new ArrayList<>();
            specs.add(cs);
            specs.add(ConnectionSpec.COMPATIBLE_TLS);
            specs.add(ConnectionSpec.CLEARTEXT);
            client.connectionSpecs(specs);
        } catch (Exception exc) {
            Log.e(TAG, "Error while setting TLS", exc);
        }
        return client;
    }
287137
public ReleaseCompleteMessage createRLC() {

        ReleaseCompleteMessage msg = new ReleaseCompleteMessageImpl(_RLC_HOLDER.mandatoryCodes,
                _RLC_HOLDER.mandatoryVariableCodes, _RLC_HOLDER.optionalCodes, _RLC_HOLDER.mandatoryCodeToIndex,
                _RLC_HOLDER.mandatoryVariableCodeToIndex, _RLC_HOLDER.optionalCodeToIndex);

        return msg;
    }
131568
def createComboContract(self, symbol, legs, currency="USD", exchange=None):
        
        exchange = legs[0].m_exchange if exchange is None else exchange
        contract_tuple = (symbol, "BAG", exchange, currency, "", 0.0, "")
        contract = self.createContract(contract_tuple, comboLegs=legs)
        return contract
29057
def create_exchange(self):
        
        mq_channel = self._connect_mq()
        mq_channel.exchange_declare(exchange=self.code_name,
                                    exchange_type='fanout',
                                    durable=True)
605435
def create_fct_file(self):
        '''
        
        '''
        fct_str = ''
        fct_str += self.fct_rec(self.db.target_table)
        return fct_str
925904
def _make_req(self, method, url, methname, headers=None):
        """"""

        # Build up headers
        hset = hdrs.HeaderDict()

        # Walk through our global headers
        for hdr, value in self._headers.items():
            # If it's a callable, call it
            if callable(value):
                value = value(methname)
            else:
                # OK, just stringify it
                value = str(value)

            # If it's meaningful, attach it
            if value:
                hset[hdr] = value

        # Were headers passed in?
        if headers is not None:
            # Update from specified headers
            hset.update(headers)

        # Hook method to instantiate requests
        self._debug("Creating request %s.%s(%r, %r, headers=%r)",
                    self._req_class.__module__, self._req_class.__name__,
                    method, url, hset)
        return self._req_class(method, url, self._client, self._procstack,
                               headers=hset, debug=self._debug)
353577
def reqMktDepth(self, tickerId, contract, numRows, mktDepthOptions):
        """"""
        return _swigibpy.EClientSocketBase_reqMktDepth(self, tickerId, contract, numRows, mktDepthOptions)
298668
def CreateSignatureContract(publicKey):
        
        script = Contract.CreateSignatureRedeemScript(publicKey)
        params = b'\x00'
        encoded = publicKey.encode_point(True)
        pubkey_hash = Crypto.ToScriptHash(encoded, unhex=True)

        return Contract(script, params, pubkey_hash)
1034226
def createComboLeg(self, contract, action, ratio=1, exchange=None):
        
        leg = ComboLeg()

        loops = 0
        conId = 0
        while conId == 0 and loops < 100:
            conId = self.getConId(contract)
            loops += 1
            time.sleep(0.05)

        leg.m_conId = conId
        leg.m_ratio = abs(ratio)
        leg.m_action = action
        leg.m_exchange = contract.m_exchange if exchange is None else exchange
        leg.m_openClose = 0
        leg.m_shortSaleSlot = 0
        leg.m_designatedLocation = ""

        return leg
215261
function command (
  {
    privateKeys,
    creatorAccountId,
    quorum,
    commandService,
    timeoutLimit
  } = DEFAULT_OPTIONS,
  tx
) {
  let txToSend = txHelper.addMeta(tx, {
    creatorAccountId,
    quorum
  })

  txToSend = signWithArrayOfKeys(txToSend, privateKeys)

  let txClient = commandService

  return sendTransactions([txToSend], txClient, timeoutLimit)
}