How to create Fields - indexing

I am trying to create a script to add Fields on MarkLogic Database with Admin API. I have created following functions to perform this task:
declare function local:createField($config as element(configuration), $server-config as element(http-server))
{
let $dbid := xdmp:database(fn:data($server-config/database))
let $addField :=
let $fieldspec := admin:database-field("VideoTitle1", fn:false())
return admin:save-configuration(admin:database-add-field($config, $dbid, $fieldspec))
return "SUCCESS"
};
declare function local:createFieldPath($config as element(configuration), $server-config as element(http-server))
{
let $dbid := xdmp:database(fn:data($server-config/database))
let $addPath :=
let $fieldpath := admin:database-field-path("/Video/BasicInfo/Title", 1.0)
return admin:save-configuration(admin:database-add-field-paths($config, $dbid, "VideoTitle1", $fieldpath))
return "SUCCESS"
};
declare function local:createFieldRangeIndex($config as element(configuration), $server-config as element(http-server))
{
let $dbid := xdmp:database(fn:data($server-config/database))
let $addRange :=
let $rangespec := admin:database-range-field-index("string","VideoTitle1", "http://marklogic.com/collation/",fn:false() )
return admin:save-configuration(admin:database-add-range-field-index($config, $dbid, $rangespec))
return "SUCCESS"
};
But I am getting error:
[1.0-ml] ADMIN-BADPATHFIELDTYPE: (err:FOER0000) Incorrect field:
the field VideoTitle1 already has include-root.
In /MarkLogic/admin.xqy on line 5255
In database-check-path-field(<configuration/>, xs:unsignedLong("12095791717198876597"), "VideoTitle1")
$config := <configuration/>
$database-id := xs:unsignedLong("12095791717198876597")
$field-name := "VideoTitle1"
$field := <field xmlns="http://marklogic.com/xdmp/database" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><field-name>VideoTitle1</field-name><include-root>false</include...</field>
$field-path := ()
I am running complete script through QC and my MarkLogic version is "7.0-1". I have created Element Range Index, Attribute Range Index successfully by the script. But for this I am getting error.
Error description says that field has include-root. But, I am keeping it false()
admin:database-field("VideoTitle1", fn:false())
Is I am using wrong function or missed something?
Please help.

If you're trying to set up an entire database you're usually better off using the packaging API and services: https://developer.marklogic.com/learn/packaging-tutorial gives a tour of the configuration manager web UI, and then there is a guide, an XQuery API, and a REST API.
That said let's try to debug. It's difficult to debug your error message because the variable names and line numbers in the error message don't match up with your sample code. For example the stack trace has $database-id but your code has $dbid. A test case needs to be reproducible.
However I notice that you aren't calling the right function to construct your field configuration. If you want to use paths, say so up front using https://docs.marklogic.com/admin:database-path-field — not admin:database-path. The error message could use some work: it should be something more like "Incorrect field: the field VideoTitle1 is not a path field".
If you really want to stick with the admin API for this, I recommend changing your code so that you only call admin:save-configuration once. That's more efficient, and more robust in the face of any need to restart. One way to arrange this would be for each of your function calls to take a $config as element(configuration) param and return a new element(configuration) with the changes. Another method is to have a module variable $CONFIG as element(configuration) and mutate it with xdmp:set. Take a look at https://stackoverflow.com/a/12252515/908390 for examples of both techniques.
Here's a working version of your code:
import module namespace admin="http://marklogic.com/xdmp/admin"
at "/MarkLogic/admin.xqy";
declare function local:createField(
$config as element(configuration),
$server-config as element(http-server))
as element(configuration)
{
let $dbid := xdmp:database(fn:data($server-config/database))
let $fieldspec :=
admin:database-path-field(
"VideoTitle1",
admin:database-field-path("/Video/BasicInfo/Title", 1.0))
return admin:database-add-field($config, $dbid, $fieldspec)
};
declare function local:createFieldRangeIndex(
$config as element(configuration),
$server-config as element(http-server))
as element(configuration)
{
let $dbid := xdmp:database(fn:data($server-config/database))
let $rangespec :=
admin:database-range-field-index(
"string",
"VideoTitle1",
"http://marklogic.com/collation/",
fn:false())
return
admin:database-add-range-field-index(
$config, $dbid, $rangespec)
};
let $cfg := admin:get-configuration()
let $fubar := <http-server><database>test</database></http-server>
let $_ := xdmp:set($cfg, local:createField($cfg, $fubar))
let $_ := xdmp:set($cfg, local:createFieldRangeIndex($cfg, $fubar))
return admin:save-configuration($cfg)

Not a direct answer, but why reinvent a wheel that other have already invented. There are several solutions that can help deploy database settings and more. One of them is Roxy:
https://github.com/marklogic/roxy
Roxy provides a full framework for managing a MarkLogic project. You can find docs and tutorials on the wiki of the github project.
Another, less intrusive solution could be to configure your databases once, and then use the built-in Configuration Manager (http://host:8002/nav/) to export your database settings, and use the export to import the settings elsewhere.
HTH!

Related

create a charge with Stripe and Delphi

I am trying to create a charge in Stripe following API documentation but without success :
jsnObj := TJSONObject.Create;
jsnObj.AddPair('amount', TJSONNumber.Create('111'));
jsnObj.AddPair('currency', 'eur');
jsnObj.AddPair('customer', 'cus_JL30ptApR3U2gL');
jsnObj.AddPair('description', 'My First Test');
ss := TStringStream.Create(jsnObj.ToString);
rs := TStringStream.Create;
IdHTTP1.Request.BasicAuthentication := True;
IdHTTP1.Request.Username := ApiKey ; // test private key
IdHTTP1.Post('https://api.stripe.com/v1/charges', ss, rs);
StatusBar1.SimpleText := IdHTTP1.ResponseText;
the result is always error :
{
"error": {
"code": "parameter_missing",
"doc_url": "https://stripe.com/docs/error-codes/parameter-missing",
"message": "Must provide source or customer.",
"type": "invalid_request_error"
}
}
Http returns 400 bad request.
All data is correct but the source parameter is missing as Stripe documentation states that it is optional so I include customer parameter instead and it should work.
Other calls to the Stripe API are successful with the same code (connect, retrieve objects etc.)
Thanks for any tips..

Write datas from Stripe API in a CSV file in golang

I am trying to retrieve Stripe datas and parse them into a CSV file.
Here is my code:
package main
import (
"github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/invoice"
"fmt"
"os"
"encoding/csv"
)
func main() {
stripe.Key = "" // I can't share the API key
params := &stripe.InvoiceListParams{}
params.Filters.AddFilter("limit", "", "3")
params.Filters.AddFilter("status", "", "paid")
i := invoice.List(params)
// Create a CSV file
csvdatafile, err := os.Create("./mycsvfile.csv")
if err != nil {
fmt.Println(err)
}
defer csvdatafile.Close()
// Write Unmarshaled json data to CSV file
w := csv.NewWriter(csvdatafile)
//Column title
var header []string
header = append(header, "ID")
w.Write(header)
for i.Next() {
in := i.Invoice()
fmt.Printf(in.ID) // It is working
w.Write(in) // It is not working
}
w.Flush()
fmt.Println("Appending succed")
}
When I am running my program with go run *.go I obtain the following error:
./main.go:35:10: cannot use in (type *stripe.Invoice) as type []string in argument to w.Write
I think I am not far from the solution.
I just need to understand how to write correctly in the CSV file thank's to w.Write() command.
According to the doc, the Write function is:
func (w *Writer) Write(record []string) error
That is, it is expecting you to pass a slice of strings representing a line of CSV data with each string being a slice. So, if you have only one field, you have to pass a string slice of 1:
w.Write([]string{in.ID})

Fiddler: Programmatically add word to Query string

Please be kind, I'm new to Fiddler
My purpose:I want to use Fiddler as a Google search filter
Summary:
I'm tired of manually adding "dog" every time I use Google.I do not want the "dog" appearing in my search results.
For example:
//www.google.com/search?q=cat+-dog
//www.google.com/search?q=baseball+-dog
CODE:
dog replaced with -torrent-watch-download
// ==UserScript==
// #name Tamper with Google Results
// #namespace http://superuser.com/users/145045/krowe
// #version 0.1
// #description This just modifies google results to exclude certain things.
// #match http://*.google.com
// #match https://*.google.com
// #copyright 2014+, KRowe
// ==/UserScript==
function GM_main () {
window.onload = function () {
var targ = window.location;
if(targ && targ.href && targ.href.match('https?:\/\/www.google.com/.+#q=.+') && targ.href.search("/+-torrent/+-watch/+-download")==-1) {
targ.href = targ.href +"+-torrent+-watch+-download";
}
};
}
//-- This is a standard-ish utility function:
function addJS_Node(text, s_URL, funcToRun, runOnLoad) {
var D=document, scriptNode = D.createElement('script');
if(runOnLoad) scriptNode.addEventListener("load", runOnLoad, false);
scriptNode.type = "text/javascript";
if(text) scriptNode.textContent = text;
if(s_URL) scriptNode.src = s_URL;
if(funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName('head')[0] || D.body || D.documentElement;
targ.appendChild(scriptNode);
}
addJS_Node (null, null, GM_main);
At first I was going to go with Tampermonkey userscripts,Because I did not know about Fiddler
==================================================================================
Now,lets focus on Fiddler
Before Request:
I want Fiddler to add text at the end of Google Query string.
Someone suggested me to use
static function OnBeforeRequest(oSession: Session) {
if (oSession.uriContains("targetString")) {
var sText = "Enter a string to append to a URL";
oSession.fullUrl = oSession.fullUrl + sText;
}
}
Before Response:
This is where my problem lies
I totally love the HTML response,Now I just want to scrape/hide the word in the search box without changing the search results.How can it be done? Any Ideas?
http://i.stack.imgur.com/4mUSt.jpg
Can you guys please take the above information and fix the problem for me
Thank you
Basing on goal definition above, I believe you can achieve better results with your own free Google custom search engine service. In particular, because you have control over GCSE fine-tuning results, returned by regular Google search.
Links:
https://www.google.com/cse/all
https://developers.google.com/custom-search/docs/structured_search

How to search for a string inside a class in Squeak smalltalk ? How about inside a package?

I searched, and searched.
I went to IRC
Hope the question is not silly. If it was, the right string to search at google would still be much appreciated
Answering such questions with the refactoring engine is quite easy. The following code finds all occurrences of / in the system:
allCodeWithSlash := RBBrowserEnvironment new matches: '/'
From there you can further scope the search, e.g. to inside a class:
allCodeWithSlashInClass := allCodeWithSlash forClasses: (Array with: DosFileDirectory)
Or inside a package:
allCodeWithSlashInPackage := allCodeWithSlash forPackageNames: (Array with: 'Files')
If you have an UI loaded, you can open a browser on any of these search results:
allCodeWithSlashInPackage open
If you use OmniBrowser, you can also build and navigate these scopes without typing any code through the Refactoring scope menu.
Here's an example that shows you all methods in DosFileDirectory containing the string '\'.
aString := '\\'.
class := DosFileDirectory.
methodsContainingString := class methodDictionary values select: [:method |
method hasLiteralSuchThat: [:lit |
(lit isString and: [lit isSymbol not]) and:
[lit = aString]]].
messageList := methodsContainingString collect: [ :e | MethodReference new setStandardClass: class methodSymbol: e selector ].
SystemNavigation new
browseMessageList: messageList
name: 'methods containing string'.
To search a whole package, wrap the search part in:
package := PackageOrganizer default packageNamed: packageName ifAbsent: [ self error: 'package doesn't exist' ].
package classesAndMetaClasses do: [ :class | ... ]

How to redefine FrontEndEventActions?

Good day,
This question comes from the question on aborting evaluation of the full sequence of inputs.
I think it is probably possible to achieve the desired behavior by redefining FrontEndEventActions for two events: "EvaluateCells" (or pressing Shift+Enter) and for pressing Alt+.. It should be something like:
SetOptions[$FrontEndSession,
FrontEndEventActions -> {"EvaluateCells" :> Last$PreRead,
{{"Alt", "."} :> AbortAllNextInputs}}]
or
SetOptions[$FrontEndSession,
FrontEndEventActions -> {{{"ShiftKey", "ReturnKeyDown"} :> Last$PreRead}
{{"Alt", "."} :> AbortAllNextInputs}}]
Where AbortAllNextInputs and Last$PreRead are defined as follows:
AbortAllNextInputs := AbortProtect[
$new$PreRead = True;
last$PreRead = ToString[Definition[$PreRead], InputForm];
ClearAll[$PreRead];
$PreRead := # &] /; ! TrueQ[$new$PreRead]
Last$PreRead :=
$PreRead := AbortProtect[
$new$PreRead = False;
ClearAll[$PreRead];
If[last$PreRead === "Null", #,
ToExpression[last$PreRead]; $PreRead##]
] &
But I can not get FrontEndEventActions working. Can anyone help me?
I believe you need to modify KeyEventTranslations.tr as referenced here and here.