parsing,prolog,clpfd , Constraint not propagated upon instantiation of list members


Constraint not propagated upon instantiation of list members

Question:

Tag: parsing,prolog,clpfd

I am building a parser and generator for dates and times. In an ordinary programming language these would be written separately. In Prolog+CLP(FD) I can write 1 predicate that does both :-)

In my use case it often makes sense to parse a number of digits and convert the to an integer, or to generate a number of digits based on a given integer.

My problem is that clpfd:run_propagator/2 is not called when individual digits are instantiated, despite my declarations using clpfd:init_propagator/2. Is there a way to do this or am I making a mistake in my definition of clpfd_digits/2?

Code implemented in SWI-Prolog:

:- use_module(library(apply)).
:- use_module(library(clpfd)).

:- multifile(clpfd:run_propagator/2).

day(D) --> {clpfd_digits(D, [D1,D2])}, digit(D1), digit(D2).

digit(D) --> [C], {code_type(C, digit(D))}.

clpfd_digits(N, Ds):-
  clpfd:make_propagator(clpfd_digits(N, Ds), Prop),
  clpfd:init_propagator(N, Prop),
  clpfd:init_propagator(Ds, Prop),
  forall(
    member(D, Ds),
    clpfd:init_propagator(D, Prop)
  ),
  clpfd:trigger_once(Prop).

clpfd:run_propagator(clpfd_digits(N, Ds), MState):-
  (   maplist(is_digit0, Ds)
  ->  clpfd:kill(MState),
      digits_to_nonneg(Ds, N)
  ;   integer(N)
  ->  clpfd:kill(MState),
      nonneg_to_digits(N, Ds)
  ;   true
  ).

digits_to_nonneg([], 0):- !.
digits_to_nonneg(Ds, N):-
  maplist(char_weight, Chars, Ds),
  number_chars(N, Chars).

char_weight(Char, D):-
  char_type(Char, digit(D)).

nonneg_to_digits(0, []):- !.
nonneg_to_digits(N, Ds):-
  atom_chars(N, Chars),
  maplist(char_weight, Chars, Ds).

is_digit0(D):- integer(D), between(0, 9, D).

Example of use:

?- string_codes("12", Cs), phrase(day(D), Cs).
Cs = [49, 50],
clpfd_digits(D, [1, 2]).

As you can see the constraint is not calculated to derive at the value of D.


Answer:

+1 for using CLP(FD) constraints for this task!

forall/2 and constraints do not mix very well, since backtracking revokes posted constraints.

Your example works as expected with:

flip_init(Prop, D) :- clpfd:init_propagator(D, Prop).

and using maplist(flip_init(Prop), Ds) instead of forall/2.

The next problem is then that digits_to_nonneg([1,2], N) simply fails, but this is unrelated to the actual constraint triggering, which happens as expected. (By the way: Using constraints, you may be able to simplify the code so that you can use a single predicate in both directions.)

Also, you can use in/2 instead of between/3: D in 0..9. This is often useful if you want to use it as a constraint instead of just a test.


Related:


XML file parsing - Get data from a child of a child


python,xml,parsing,python-3.x
I know how to get data from a child tag but I would like to get data from a child tag of a child tag of the "root" tag. We can use this database for example : <DB> <Entry> <Name></Name> <DisplayName>Assembly.iam</DisplayName> <Scalar> <Name>d0</Name> <DisplayName>d0 (value = 0 mm)</DisplayName> <Value>0</Value> </Scalar>...

Parsing XML in PHP with SimpleXML


php,xml,parsing
I am trying to parse the below XML , i have tryed loads of different solutions, i have provided an example of what i have tryed. I have read the SimpleXML documents and i still cant get this right. In the Example below all im trying to do is Echo...

Golang - using/iterating through JSON parsed map


json,parsing,go
With PHP and Javascript (and Node) parsing JSON is a very trivial operation. From the looks of it Go is rather more complicated. Consider the example below package main import ("encoding/json";"fmt") type fileData struct{ tn string size int } type jMapA map[string] string type jMapB map[string] fileData func parseMapA(){ var...

JSON parse will not execute with JavaScript


javascript,json,list,parsing
This is my current code, any help would be greatly appreciated. I need to call my listApp.json file and parse it. I want to display my list which currently has one link. I'm new to this. <script type = "text/javascript"> // If the .js files are linked correctly, we should...

prolog rules as arguments


prolog,artificial-intelligence,expert-system
I'm building an expert system shell based on Luger & Stubblefield's ExShell. In their system, they define rules in the following way: rule((Goal :- (Premise)), CF_Rule). Ignore the CF_Rule. An example of this syntax is: rule((fix(Advice) :- (bad_component(X),fix(X, Advice))), 100). I want to add an OR in certain rules, but...

Need to parse live json file using Socket io


json,node.js,parsing,socket.io
First a Heads Up! I am very new to the world of node.js and socket.io I have a json file which contains following data for example:- { "football": { "id": 1, "home": "Liverpool", "away": "Chelsea", "score": "1-0", "last scorer":"Gerrard" } } This file is updated live on few seconds basis....

How do I load data from a txt file into variables in my C program?


c,arrays,parsing,file-io,struct
I have a program that has a struct of channels: struct channel { char title[40]; float gain; float offset; }; int main (int argc, char **argv) { struct channel channels[8]; } And a text file called configurationSettings.txt that holds the information needed to fill up 8 channels: Title1 20 30...

Android - Saving Objects to List of Object


android,parsing
I am learning how to retrieve data stored in Parse.I am able to retrieve data from parse and bind it to simple ListView. Now I am trying to mock a simple chat app. I have two column in my parse class to store senders name and Chat message. I have...

Getting error in JSON parsing with array in iOS


ios,json,parsing,nsjsonserialization
I am newly to iPhone, basically in my application I am parsing below JSON model and need to save it in my custom Entity class. JSON model : { "Products": [ { "Pcs": [ { "product_id": 2, "product_name": "MyProduct", "category": { "Clamshells": [ { "product_category_id": 11, "product_category_name": "MyProductCategory", "Sub_category": [...

ANSI escape characters in gprolog


prolog,escaping,iso-prolog
Trying to print bold and underlined text in prolog but can't write them write('\033[1mbold\033[0m') Makes this (expected) error: syntax error: \ expected in \constant\ sequence What's the correct way to do it with gprolog ? Maybe with format ?...

jquery get elements by class name


html,arrays,parsing,getelementsbyclassname
I'm using Jquery to get a list of elements having a class "x". html: <p class="x">Some content</p> <p class="x">Some content#2</p> If we use Jquery to get both these html elements and do something with it- we use something like: $(".x").text("changed text"); This will change the text of both the paragraphs....

PHP - Parse Facebook Post JSON


php,json,parsing,facebook-graph-api
I am really struggling with parsing JSON data from Facebook's Graph API. I am using file_get_contents and json_decode to decode the object $json = file_get_contents($facebook_url); $obj = json_decode($json, true); Here is some sample JSON: { "data": [ { "place": { "id": "134972803193847", "name": "University of Southern California", "location": { "city":...

PROLOG: Summing up the series procedure


prolog
I have been trying to work on this problem that I found in a book, but am not able to make sense of it in my head. The problem asks me to use series(N, Total) for this procedure; 1 + 1/2 + 1/3 + 1/4 + ... + 1/(N-1). Any...

Validate double number in current culture


c#,parsing,double,cultureinfo,currentculture
There is a way to validate a double number in the current culture? I have tried this: var number ="10,10"; double value = double.Parse(number, NumberStyles.Float, CultureInfo.CurrentCulture); If I try this with "es-ES" (where decimal separator is ",") then the parsing works perfect, I got an double 10.10, but if I...

printing invalid input from string in Java


java,string,parsing
I am trying to print the invalid number, number which is not of type int or double but not getting desired output, please help me pointing out my mistake and another thing is it is possible to to find out invalid number using some other way? public class Test {...

make all elements in list equal with minimal cost


list,optimization,prolog
I am trying to create a prolog program that allows to convert a list into a list with the same length consisting of only 1 element from the original list. This element must be chosen in such a way that a minimal number of elements from the original list needs...

Find element by class name


python,parsing,selenium,selenium-webdriver,css-selectors
I'm trying to find one tag using we.find_element_by_css_selector('p.p1.transfer strong.ng-binding').text The problem is that there is sometimes a 'strong' tag before the tag I'm searching for which is very similar but it's class is: class="ng-binding ng-hide" instead of class="ng-binding". But when I try to find it it finds the first tag....

How to instantiate lexical.Scanner in a JavaTokenParsers class?


scala,parsing,lexical-scanner
I am writing a parser which inherits from JavaTokenParsers in that I have a function as follow: import scala.util.parsing.combinator.lexical._ import scala.util.parsing._ import scala.util.parsing.combinator.RegexParsers; import scala.util.parsing.combinator.syntactical.StdTokenParsers import scala.util.parsing.combinator.token.StdTokens import scala.util.parsing.combinator.lexical.StdLexical import scala.util.parsing.combinator.lexical.Scanners import scala.util.parsing.combinator.lexical.Lexical import...

prolog misunderstanding. Split list into two list with even and odd positions. where is my mistake?


list,split,prolog
I'm trying to split a list into two other list. List Even with the elemnts in even possition and a List Odd with the others. I've been looking over iinternet a solution, but all seem to me like chinese, i can not understand the process. So this is what i've...

Prolog rules and query


prolog
I need some help to find the rules and/or query for knowledgebase in Prolog with information about Costumers in a supermarket. For example I have: Customer(Name,Age,Sex,Wage). customer(John,30,M,2000). customer(Mary,35,F,2500). customer(Mark,40,M,2500). invoice(Number, CostumerName, Product, Price). invoice(001, John, Potatoes, 20). invoice(002, John, Tomatoes, 10). invoice(003, Mary, Soap, 50). invoice(004, Mark, Potatoes, 20). invoice(005,...

String parsing with batch scripting


windows,string,parsing,batch-file,xml-parsing
I have a file called pictures.xml and it contains some pictures information like: <ResourcePicture Name="a.jpg"> <GeneratedPicture Name="b.jpg"/> <GeneratedPicture Name="c.jpg"/> </ResourcePicture> <ResourcePicture Name="z1.jpg"> <GeneratedPicture Name="z2.jpg"/> <GeneratedPicture Name="z3.jpg"/> <GeneratedPicture Name="z4.jpg"/> </ResourcePicture> What I want do do is to get each line in for loop and print the names of the pictures. Sample...

How to parse output of external command in Julia?


parsing,julia-lang
Let us say that I have an external command called "Busca01.x" which returns three integers separated by tabs, like this: [email protected]: Busca01.x 192 891 9029 So, I can call this from julia and store the result as a string using either readall or readchomp. I need the data as an...

Syntax Error, Operator Expected


sql-server,prolog
I am trying to query the MS SQL Server database using Prolog. Prolog Code lemmas:- odbc_query('my_db', 'SELECT * ,case when ActualCost<EstimatedCost then 'true' else 'false' end as Value from Work_Order ' ). It gives an error that operator is expected after 'true' . Note: The Query works in SQL-Server but...

How to add a print command to DCG syntax


prolog,dcg
I want to add a print command to my DCG syntax, here is what I have: program( (R0 --> R) ) --> [begin],instructs(( R0 --> R )),[end]. instructs( ( R0 --> R ) ) --> instr(( R0 --> R )). instructs( ( R0 --> R ) ) --> instr(( R0...

pandas parse dates from csv


parsing,datetime,pandas
I am trying to read a csv file which includes dates. The csv looks like this: h1,h2,h3,h4,h5 A,B,C,D,E,20150420 A,B,C,D,E,20150420 A,B,C,D,E,20150420 For reading the csv I use this code: df = pd.read_csv(filen, index_col=None, header=0, parse_dates=[5], date_parser=lambda t:parse(t)) The parse function looks like this: def parse(t): string_ = str(t) try: return datetime.date(int(string_[:4]),...

How can I call a function random inside other function in prolog?


prolog,prolog-assert
I'm trying to call the random function inside another function. For example I want to do this assert(fact(random()). But it does not work. How can I insert a random number this way? Thanks.

Custom Converter for Retrofit


android,json,parsing,gson,retrofit
I am trying to use a custom converter for Retrofit RestAdapter.Builder builder = new RestAdapter.Builder() .setEndpoint(BuildConfig.BASE_SERVER_ENDPOINT) .setClient(new OkClient(client)).setConverter(new CitationResponseConverter()) .setLogLevel(RestAdapter.LogLevel.FULL); below is my custom converter public class CitationResponseConverter implements Converter { @Override public Object fromBody(TypedInput typedInput, Type type) throws ConversionException { try { InputStream in = typedInput.in(); // convert the...

Extracting strings from HTML with Python wont work with regex or BeautifulSoup


python,regex,parsing,beautifulsoup,python-requests
Im using Python 2.7, BeautifulSoup4, regex, and requests on windows 7. I've scraped some code from a website and I am having problems parsing and extracting the bits I want and storing them in a dictionary. What I'm after is text that is presented as follows in the code: @CAD_DTA\">I...

How do we get text from a file (word-by-word) into a 2D array in PHP?


php,arrays,parsing,file-handling
I have a text file with some stuff that I would like to put into a 2D array. That text file comprises of sentences of equal length. How do I put each word into an array? Example of text file is - This is stackoverflow I am user This file...

Parse JSON on PHP and extract the particular value(s)


php,mysql,json,parsing,logic
Objective: To parse following json string and get mentioned values separately, later those separated values are going to be inserted to mysql database. I have checked my json string on JsonLint user_name, selected_date, selected_project, tasks , 4.1.task_name, 4.2 work_hours { "user_name": "USER", "selected_date": "2015-06-08", "selected_project": "Project1", "tasks": [ { "task_name":...

Parse.Cloud.httpRequest not returning response


parsing,parse.com,cloud-code
I am trying to make a Parse.Cloud.httpRequest call, the job executes successfully but i am not getting any response. If i run the request on a RestClient it executes fine but for some reason it's not working in Parse Cloud Code. What am i doing wrong? Parse.Cloud.job("Loader", function(request, status) {...

Create XSD based on root element


java,xml,parsing,xsd
I have a XSD as shown below , i need to extract all the root Elements in the XSD and create a separate XSD for each root element pragmatically in java, is there some framework of java library that can aid me in achieving this. <?xml version='1.0' encoding='windows-1252'?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"...

save parsed JSON as obj


javascript,jquery,json,parsing
first question ever, I'm trying to parse a JSON file stored within the same file directory on my webhost as my html file that runs the javascript to parse it, I've added a console.log to debug and confrim that the file is being caught by the 'get' to ensure that...

How to get xml attribute and values using JAXB


xml,parsing,jaxb
I am new in Jaxb i have one xml file which contain many attribute so i want the attribute with value My XMl <message_mapping> <message Rtype="DIAGNOSTIC" direction="2" name="Diagnostic" mode=""> <field tag="USERNAME" source="I" tranData="username" required="false" dataType="string" defaultValue="" /> <field tag="PASSWORD" source="I" tranData="password" required="true" dataType="string" defaultValue="" /> <field tag="LOCALDATETIME" source="E" tranData="trxDateTime" required="true"...

Prolog: Summing elements of two lists representing an integer(restrictions inside not regular sum!!)


list,prolog
I was solving a problem: A list is representing an integer say 12345 by L=[12,34,5] each element should be from 0 to 99.The exercise is to write a function (sum) that sums two lists and gives the equivalent list of their sum which is representing the sum of two integers....

Reading JSON file from dropbox iOS


ios,json,parsing,dropbox
I have a scenario where app reads file from server (dropbox) and checks version. If new version is available then download the app. I'm trying to read file from link but getting null after JSON parsing. NSError *error; NSString *strFileContent = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"https://www.dropbox.com/s/22mm417fxdqdn8c/FileStructure.txt?dl=0"] encoding:NSUTF8StringEncoding error:&error]; if(!error) { //Handle error...

Exception Value: list indices must be integers, not str


python,json,parsing
I'm trying to work on a JSON file that I get from an API. But when I try to access it's info once I converted it with json.loads(). I get the following error: Exception Value: list indices must be integers, not str the python code : response = requests.get(url, params=params)...

DateTime.Parse ignoring my IFormatProvider?


c#,.net,parsing,datetime
It looks to me like .NET is ignoring the TwoDigitYearMax property of the CultureInfo (IFormatProvider) I pass for parsing? Specifically, I cannot explain why the last line of this says 1930, and not 2030. Can anyone reproduce or explain it? Windows 7, .NET 4.0, en-US system settings. using System; using...

How to set up XPath query for HTML parsing?


python,xml,parsing,xpath,lxml
Here is some HTML code from http://chem.sis.nlm.nih.gov/chemidplus/rn/75-07-0 in Google Chrome that I want to parse the website for some project. <div id="names"> <h2>Names and Synonyms</h2> <div class="ds"><button class="toggle1Col"title="Toggle display between 1 column of wider results and multiple columns.">&#8596;</button> <h3 id="yui_3_18_1_3_1434394159641_407">Name of Substance</h3> <ul> <li id="ds2"> `` <div>Acetaldehyde</div> </li> </ul>...

How to get a sub parameter of JSON


c#,json,parsing
Sorry for the ambiguous title but I don't know how to explain better. Anyway, I made a code for parse a Json in c#, this structure: { "_links": { "self": { "href": "http://api.football-data.org/alpha/soccerseasons/354" }, "teams": { "href": "http://api.football-data.org/alpha/soccerseasons/teams" }, "fixtures": { "href": "http://api.football-data.org/alpha/soccerseasons/fixtures" }, "leagueTable": { "href": "http://api.football-data.org/alpha/soccerseasons/leagueTable" } },...

Avoid recursion in predicate


prolog
I have the following question for the following predicate, how can i drop the recursive call f(T,S1) from both predicates. Flow model: (i,o) f([],0). f([H|T],S):- f(T,S1), S1 > 2,!, S is S1 + H. f([_|T],S):- f(T,S1), S is S1 + 1. This is a trick question, and I am not...

Solving constraints with string concatenations in Prolog


prolog,swi-prolog
Here, I tried to solve some simple string constraints in Prolog. While this problem seems to be straightforward, the main predicate still does not print the value of FinalString, which should be "hello world". Is it possible for Prolog to solve constraints that contain string concatenations, like this one? :-...

Get operator operands


list,prolog,operators
I have list: List = [a=3, b=2, c=0]. For example, first element a=3, how can I get value Left = a, Right = 3. Left side is atom and right side is number....

How to define a Regex in StandardTokenParsers to identify path?


regex,scala,parsing,lexical-analysis
I am writing a parser in which I want to parse arithmetic expressions like: /hdfs://xxx.xx.xx.x:xxxx/path1/file1.jpg+1 I want to parse it change the infix to postfix and do the calculation. I used helps from a part of code in another discussion as well. class InfixToPostfix extends StandardTokenParsers { import lexical._ def...

get element by id and get element by Value xpath in php


php,xml,parsing,domxpath,xpathquery
XML file <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ew-language id="en"> <global> <phrase id="actiondeleted" value="Deleted"> <child_phrase_1 id="1234" value="numbers"> <child id="test_id" value="test_value"/> <child id="test_id" value="test_value_2"/> </child_phrase_1> </phrase> </global> </ew-language> how to get element by ID and by value so the element is unique.I tried these $parent = ($xpath->query("//*[@id='$previous_tag_id']")&&...

Node.js - Browserify: Error on parsing tar file


javascript,node.js,parsing,tar,browserify
I'm trying to download a tar file (non-compressed) over HTTP and piping it's response to the tar-stream parser for further processing. This works perfect when executed on the terminal without any errors. For the same thing to be utilized on browser, a bundle.js file is generated using browserify and is...

parsing JSON files in python to get specific values


python,json,parsing,data
I'm trying to simply grab information from a json file using python. I've seen many threads that briefly cover this, however there are some questions that I have that I have not seen answered on here. Let's say I have the following json file: { "href" : "http://www.google.com", "Hosts" :...

Unwanted logical variable in Prolog output


prolog
I have to do a Prolog homework for College and I'm mostly done, but i keep getting a _G variable in the output. We need to compare a List - L - to a regular term - K -, and, if the item in the list is bigger than the...

How to translate parts of source program to library calls without writing a full parser?


c,parsing,translation
To give an example: Say I have a very simple library that allows C code to be called from another language L. In order to use your C code from L you need to change certain constructs in your C code such as changing function types to void, replacing function...

Parse text from a .txt file using csv module


python,python-2.7,parsing,csv
I have an email that comes in everyday and the format of the email is always the same except some of the data is different. I wrote a VBA Macro that exports the email to a text file. Now that it is a text file I want to parse the...