Blogs

A to Z Docker example

Init, Build and Run Work based on: Overview of the get started guide Clone an get-started app: git clone https://github.com/docker/getting-started-app.git Create a Dockerfile for the above application: docker init ? Do you want to overwrite them? Yes ? What application platform does your project use? Node ? What version of Node do you want to use? 14.15.0 ? Which package manager do you want to use? yarn ? What command do you want to use to start the app?
    December 19, 2023

    Git - Rename pushed branches

    Git - Rename pushed branches where remote is usually: origin Rename the local branch to the new name git branch -m <old_name> <new_name> Delete the old branch on remote - where is, for example, origin git push <remote> --delete <old_name> Prevent git from using the old name when pushing in the next step. git branch --unset-upstream <new_name> Push the new branch to remote git push <remote> <new_name> Reset the upstream branch for the new_name local branch git push <remote> -u <new_name>
      February 10, 2023

      A to Z Kafka Streams (Example 1)

      Running a Kafka Streams application Install Kafka: curl https://archive.apache.org/dist/kafka/2.8.0/kafka_2.12-2.8.0.tgz -o kafka_2.12-2.8.0.tgz Got a 404? check the current urls at: https://kafka.apache.org/downloads Make sure to pick a binary download Extract: tar xzf kafka_2.12-2.8.0.tgz Go to Kafka folder: cd kafka_2.12-2.8.0 Start zookeeper: bin/zookeeper-server-start.sh -daemon config/zookeeper.properties Zookeeper defaults to port 2181 Start kafka: bin/kafka-server-start.sh -daemon config/server.properties Kafka defaults to port 9092 Create the input topic(input-topic): bin/kafka-topics.sh --create --topic input-topic --partitions 1 --replication-factor 1 --bootstrap-server localhost:9092 Create the output topic(output-topic):
        September 27, 2022

        A to Z Kafka Streams (Example 2)

        Running a Kafka Streams application Download Kafka: curl https://dlcdn.apache.org/kafka/3.6.1/kafka_2.13-3.6.1.tgz -o kafka_2.13-3.6.1.tgz Extract: tar -xzf kafka_2.13-3.6.1.tgz Go to Kafka folder: cd kafka_2.13-3.6.1.tgz Start zookeeper: bin/zookeeper-server-start.sh config/zookeeper.properties Note: Zookeeper defaults to port 2181 Start kafka: bin/kafka-server-start.sh config/server.properties Note: Kafka defaults to port 9092 Create the input topic(input-topic): bin/kafka-topics.sh --create \ --bootstrap-server localhost:9092 \ --replication-factor 1 \ --partitions 1 \ --topic streams-plaintext-input Create the output topic(output-topic): bin/kafka-topics.sh --create \ --bootstrap-server localhost:9092 \ --replication-factor 1 \ --partitions 1 \ --topic streams-wordcount-output \ --config cleanup.
          September 27, 2022

          A to Z python example

          Create an virtual environment (a virtual environment a command-line tool which creates an isolated Python enviroment) $ python3 -m venv env Activate your environment $ source env/bin/activate Installing packages $ python3 -m pip install package_name Write your script contents into test.py print("hello") Run your python app $ python3 test.py
            September 27, 2022

            Mixing Elastic 'bool' and 'range' queries

            To mix ‘bool’ and ‘range’ queries in an Elastic query, add the range query to the array of queries: GET documents/_search { "query": { "bool": { "must": [ { "terms": { "entityId": [ "-832106300000216000" ], "boost": 1 } },{ "range" : { "pubyear" : { "gte" : 2020 } } } ] } } }
              February 28, 2022

              Leetcode 121 "Best Time to Buy and Sell Stock"

              Title (121. Best Time to Buy and Sell Stock)[https://leetcode.com/problems/best-time-to-buy-and-sell-stock/] Result Runtime: 6 ms, faster than 29.03% of Java online submissions for Best Time to Buy and Sell Stock. Memory Usage: 83.9 MB, less than 35.75% of Java online submissions for Best Time to Buy and Sell Stock. class Solution { public int maxProfit(int[] prices) { int max = 0; int buy = -1; int sell = -1; for(int i=0; i<prices.length; i++) { // if we never bought we buy if(buy == -1 // if the price today is lower then when we buy, its not worth // going futher based based on the previous buy price // buy here and continue.
                January 1, 2022

                Leetcode 205. Isomorphic Strings

                205. Isomorphic Strings Result Runtime: 7 ms, faster than 90.80% of Java online submissions for Isomorphic Strings. Memory Usage: 42.5 MB, less than 82.34% of Java online submissions for Isomorphic Strings. class Solution { public boolean isIsomorphic(String s, String t) { Map<Character, Character> fromTo = new HashMap<>(); // we make sure that there are not several translations into the same charachter Map<Character, Character> toFrom = new HashMap<>(); for(int i=0; i<s.length(); i++) { if(fromTo.
                  January 1, 2022

                  Leetcode 235 "Lowest Common Ancestor of a Binary Search Tree"

                  Title 235. Lowest Common Ancestor of a Binary Search Tree Result Runtime: 20 ms, faster than 22.41% of Java online submissions for Lowest Common Ancestor of a Binary Search Tree. Memory Usage: 50.1 MB, less than 25.70% of Java online submissions for Lowest Common Ancestor of a Binary Search Tree. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { TreeNode head = root; while(true) { if(head == null) break; if(head.
                    January 1, 2022

                    Leetcode 409 "Longest palimdrome"

                    Title 409. Longest Palindrome Result Runtime: 35 ms, faster than 5.55% of Java online submissions for Longest Palindrome. Memory Usage: 42.2 MB, less than 64.86% of Java online submissions for Longest Palindrome. class Solution { public int longestPalindrome(String s) { int result = 0; int maxOdd = 0; Map<Character, Integer> map = new HashMap<>(); for(int i=0; i<s.length(); i++) { if(map.containsKey(s.charAt(i))) { int val = map.get(s.charAt(i)); val = val + 1; map.
                      January 1, 2022

                      Leetcode 70 "Climbing stairs"

                      Title 70. Climbing stairs Result Runtime: 1 ms, faster than 10.33% of Java online submissions for Climbing Stairs. Memory Usage: 40.6 MB, less than 62.22% of Java online submissions for Climbing Stairs. class Solution { Map<Integer, Integer> map = new HashMap<>(); public int climbStairs(int n) { return climbStairsAux(n, 0, 0); } public int climbStairsAux(int n, int from, int step) { if(map.containsKey(from+step)) return map.get(from+step); if(from + step > n) return 0; if(from + step == n) return 1; int result = 0; result = result + climbStairsAux(n, from + step, 1); result = result + climbStairsAux(n, from + step, 2); map.
                        January 1, 2022

                        Leetcode 704. Binary search

                        704. Binary search) Result Runtime: 1 ms, faster than 16.02% of Java online submissions for Binary Search. Memory Usage: 52.8 MB, less than 82.35% of Java online submissions for Binary Search. class Solution { public int search(int[] nums, int target) { return searchAux(nums, target, 0, nums.length-1); } public int searchAux(int[] nums, int target, int right, int left) { int middle = right + (left - right)/2; if(right > left || left >= nums.
                          January 1, 2022

                          Leetcode 724. Find Pivot Index

                          724. Find Pivot Index Result Runtime: 1 ms, faster than 100.00% of Java online submissions for Find Pivot Index. Memory Usage: 42.2 MB, less than 99.85% of Java online submissions for Find Pivot Index. class Solution { public int pivotIndex(int[] nums) { int[] leftRight = new int[nums.length]; int[] rightLeft = new int[nums.length]; for(int i=nums.length-1; i>-1; i--) { if(i==nums.length-1) { rightLeft[i] = nums[i]; continue; } rightLeft[i] = nums[i] + rightLeft[i+1]; } for(int i=0; i<nums.
                            January 1, 2022

                            Leetcode 746 "Min Cost Climbing stairs"

                            Title 746. Min Cost Climbing Stairs Result Runtime: 7 ms, faster than 7.42% of Java online submissions for Min Cost Climbing Stairs. Memory Usage: 45.9 MB, less than 5.68% of Java online submissions for Min Cost Climbing Stairs. class Solution { Map<Integer, Integer> map = new HashMap<>(); public int minCostClimbingStairs(int[] cost) { return Math.min(minCostClimbingStairs(cost, 0), minCostClimbingStairs(cost, 1)); } public int minCostClimbingStairs(int[] cost, int stair) { if(map.containsKey(stair)) return map.get(stair); if(stair >= cost.
                              January 1, 2022

                              Leetcode 300 "Longuest Increasing Subsequence"

                              Title (300. Subsequence)[https://leetcode.com/problems/longest-increasing-subsequence/] Result Runtime: 196 ms, faster than 5.02% of Java online submissions for Longest Increasing Subsequence. Memory Usage: 41.9 MB, less than 6.22% of Java online submissions for Longest Increasing Subsequence. class Solution { int total = Integer.MIN_VALUE; int thisTotal = Integer.MIN_VALUE; Integer[] cache; public int lengthOfLIS(int[] nums) { cache = new Integer[nums.length+1]; return lengthOfLISAux(0, nums, Integer.MIN_VALUE); } public int lengthOfLISAux(int index, int[] nums, int currMax) { if(index >= nums.
                                November 23, 2021

                                Leetcode 322 "Coin change"

                                Title (322. Coin change)[https://leetcode.com/problems/coin-change/] Result Runtime: 85 ms, faster than 11.40% of Java online submissions for Coin Change. Memory Usage: 42.2 MB, less than 15.17% of Java online submissions for Coin Change. class Solution { Integer[][] cache; public int coinChange(int[] coins, int amount) { cache = new Integer[amount+1][coins.length]; int total = coinChangeAux(coins, amount, coins.length-1); if(total == Integer.MAX_VALUE) return -1; else return total; } public int coinChangeAux(int[] coins, int amount, int i) { if(i < 0) return Integer.
                                  November 23, 2021

                                  My notes on coding interviews

                                  Technics and tips Consider searches within hashmaps Consider storing number of ocurrences with hashmaps When using recursion consider keeping track of visited paths with an array When using recursion consider keeping track of previous scores with an hashmap Fast checks for elements of type X via stack (e.g. is there any parking place for buses?) Fast lookup if element X via hashmaps (e.g. where is the vehicle with this license place?
                                    April 10, 2021

                                    My notes on systems design interviews

                                    My notes on systems design interviews System design resources Load-balancing Round robin IP Hash Caching CDN Pull Push - Pushes data to CDN but can push data that no user ever requires Types Distributed Local (per jvm, per …) Database schema design Indexes Replication Slave-master replications NoSQL vs. Relational Sharding Vertical - User table, Tweets table, Logs table each in different machines Horizontal NoSQL Types Key-value Wide column Document based Graph based API design Data transport mecahnism Json vs.
                                      April 10, 2021

                                      Leetcode 11. Container With Most Water

                                      11. Container With Most Water Result Runtime: 1411 ms, faster than 5.00% of Java online submissions for Container With Most Water. Memory Usage: 62.6 MB, less than 33.47% of Java online submissions for Container With Most Water. class Solution { int max = 0; public int maxArea(int[] height) { for(int i=0; i<height.length; i++) { if(height[i] * (height.length-i) > max) { maxAreaAux(height, i, i); } } return max; } public void maxAreaAux(int[] height, int start, int end) { if(end >= height.
                                        January 3, 2020

                                        Leetcode 1480. Running Sum of 1d Array

                                        1480. Running Sum of 1d Array) Result Runtime: 1411 ms, faster than 5.00% of Java online submissions for Container With Most Water. Memory Usage: 62.6 MB, less than 33.47% of Java online submissions for Container With Most Water. class Solution { public int[] runningSum(int[] nums) { int[] result = new int[nums.length]; for(int i=0; i<nums.length; i++) { if(i==0) { result[i] = nums[i]; continue; } result[i] = result[i-1] + nums[i]; } return result; } }
                                          January 3, 2020

                                          Leetcode 334. Increasing Triplet Subsequence

                                          334. Increasing Triplet Subsequence The general idea is to keep track of a minimum and middle value. If a maximum appears we have a solution. The secrete, is to understand that we while keeping a minimum its index can, and should, change even for an index higher than the middle. The idea is that if a minimun is lower than the previous minimun the solution keeps holding, with either “minimun indexes” but by doing so we open the door for a new solution.
                                            January 3, 2020

                                            Leetcode 647 "Palindromic Substrings"

                                            647. Palindromic Substrings Result Runtime: 1 ms, faster than 100.00% of Java online submissions for Palindromic Substrings. Memory Usage: 34.2 MB, less than 100.00% of Java online submissions for Palindromic Substrings. class Solution { public int countSubstrings(String s) { if (s.length() == 0) { return 0; } if (s.length() == 1) { return 1; } int count=0; for(int i = 0; i<s.length(); i++) { count = count + getPalindroms(s, i, i); count = count + getPalindroms(s, i, i+1); } return count; } private int getPalindroms(String s, int from, int to) { int count=0; while(from>=0 && to<s.
                                              January 3, 2020

                                              Leetcode 79 "Word Search"

                                              79. Word Search Result Runtime: 78 ms, faster than 38.82% of Java online submissions for Word Search. Memory Usage: 37.1 MB, less than 58.28% of Java online submissions for Word Search. class Solution { public boolean exist(char[][] board, String word) { for(int i=0; i<board.length; i++) { for(int j=0; j<board[0].length; j++) { if(board[i][j] == word.charAt(0)) { boolean value = existRec(board, word, j, i, new int[board.length][board[0].length], 0); if(value) return true; } } } return false; } public boolean existRec(char[][] board, String word, int x, int y, int[][] visited, int index) { if(index >= word.
                                                January 3, 2020

                                                Leetcode 91 "Decode ways"

                                                91. Decode ways Result Runtime: 2 ms, faster than 43.76% of Java online submissions for Decode Ways. Memory Usage: 38.7 MB, less than 41.87% of Java online submissions for Decode Ways. class Solution { Map<String, Integer> cache = new HashMap<>(); int total = 0; public int numDecodings(String s) { return numDecodingsAux(s); } public int numDecodingsAux(String s) { if(s.length() == 0) { return 1; } if(cache.containsKey(s)) return cache.get(s); int a1 = 0; int a2 = 0; if(s.
                                                  January 3, 2020

                                                  Comment on exported method should be of the form

                                                  Problem comment on exported method should be of the form " …” Solution The type func (p MyType) Get2() int { return p.i } should have a comment in the form: // Get2 blablabla func (p MyType) Get2() int { return p.i }\]\]>
                                                    February 23, 2018

                                                    Exported type should have comment or be unexported

                                                    Problem exported type should have comment or be unexported Solution The type type MyType struct{ i int }\]\]> should have a comment in the form: // MyType blablabla type MyType struct{ i int }\]\]>
                                                      February 23, 2018

                                                      heroku[router]: at=error code=H10 desc="App crashed"

                                                      While trying to deploy a Spring application: Problem: heroku[router]: at=error code=H10 desc="App crashed” (…) Solution: Create a `Procfile` under the project root with the contents: web: java -Dserver.port=$PORT $JAVA_OPTS -cp target/classes:target/dependency/* The problem is that the application is not binding with the Heroku provided port.
                                                        December 28, 2017

                                                        com.sksamuel.elastic4s.TcpClient$ - No cluster.name was specified in the settings for the client.

                                                        Problem: com.sksamuel.elastic4s.TcpClient$ - No cluster.name was specified in the settings for the client.” Solution: Add the cluster name as a parameter on the connection URI: Go to http://<elasticsearch_host>:9200 Retrieve the cluster_name value and add it as a parameter to the connection URI: elasticsearch://<elasticsearch_host>:9300?cluster.name=<cluster_name_value
                                                          October 16, 2017

                                                          Angular - apollo-client/core/types.d.ts (17,45): ',' expected

                                                          Problem: Starting problems while using the apollo graphQL client: $ npm install apollo-client apollo-angular graphql-tag –save (…) _ $ npm start _ (…) _ERROR in /(…)/node_modules/apollo-client/core/types.d.ts (17,45): ‘,’ expected. ERROR in /(…)/node_modules/apollo-client/core/types.d.ts (17,47): ‘>’ expected. ERROR in /(…)/node_modules/apollo-client/core/types.d.ts (19,2): ‘;’ expected. ERROR in /(…)/node_modules/apollo-client/core/types.d.ts (19,4): Expression expected. ERROR in /(…)/node_modules/apollo-client/core/types.d.ts (20,10): Expression expected. ERROR in /(…)/node_modules/apollo-client/core/types.d.ts (20,5): Cannot find name ‘data’. ERROR in /(…)/node_modules/apollo-client/core/types.d.ts (20,12): Cannot find name ‘T’. ERROR in /(…)/node_modules/apollo-client/data/mutationResults.
                                                            July 19, 2017

                                                            Angular - UNMET PEER DEPENDENCY apollo-client@1.9.0-0

                                                            Problem: Adding apollo GraphQL client to a Angular 4 application: $ npm install apollo-client apollo-angular graphql-tag –save UNMET PEER DEPENDENCY apollo-client@1.9.0-0 Solution: Update npm version $ npm install -g npm
                                                              July 18, 2017

                                                              XSL - Transformer configuration exception error checking type expression funcall replace

                                                              Problem: javax.xml.transform.TransformerConfigurationException: Error checking type of the expression ‘funcall(replace, Solution: Make sure to be using an updated xsl transalation engine like, for instance, saxon 9. Maven dependency: net.sf.saxonSaxon-HE9.8.0-3 Usage example: public ProductPool process(FeedProduct feedProduct) throws Exception { File stylesheet = new File("src/main/resources/XMLToCSVStyle.xsl"); File xmlSource = new File(feedFileName); File csvTarget = new File(feedFileName.replace(".xml", ".csv")); TransformerFactory tFactory = TransformerFactory.newInstance(); // TransformerFactoryImpl tFactoryImpl = (TransformerFactoryImpl) tFactory; // net.sf.saxon.Configuration saxonConfig = tFactoryImpl.getConfiguration(); try { Transformer transformer = tFactory.
                                                                July 14, 2017

                                                                Terraform, AWS - aws Instance Profile already exists error

                                                                Problem “aws Instance Profile already exists error” $ terraform --version Terraform v0.9.8 Solution This is a know issue with terraform, see: https://github.com/hashicorp/terraform/issues/3749 , read: brikis98 commented on 4 Nov 2015 Update: it turns out that instance profiles don’t show up in the AWS console. Well, they do, but only attached to a role. If you delete the role, but not the policy, then there is no longer a way to see the policy in the console.
                                                                  June 29, 2017

                                                                  cannot locate the core snap: No such file or directory

                                                                  Problem cannot locate the core snap: No such file or directory Solution $ snap list Check for packages with “Notes” as broken $ snap remove <broken_package> $ sudo snap install <broken_package> Note: <broken_package> equals to “core” in this particular case.
                                                                    June 28, 2017

                                                                    Scala - cannot resolve symbol "toList"

                                                                    Problem “cannot resolve symbol toList” Solution import scala.collection.JavaConversions
                                                                      June 14, 2017

                                                                      Play Framework - @helper custom @input text field

                                                                      Target <![CDATA[ <div class="form-group”> <label class="text-left col-lg-5 col-sm-6 control-label”>Emailadres contactpersoon</label> <div class="col-lg-7 col-sm-6”> <input maxlength="50” placeholder="Emailadres” tabindex="4” class="form-control” id="Emailadres” name="Emailadres” type="text”> </div> </div> ]]> SyntaxHighlighter.highlight(); Solution Render the input text without the labels part of the play framework defaults by creating a file customfield.scala.html under app/view/helper: <![CDATA[ @(elements: helper.FieldElements) @elements.input <span class="errors”>@elements.errors.mkString(", “)</span> <span class="help”>@elements.infos.mkString(", “)</span ]]> SyntaxHighlighter.highlight(); Create a custom input text consctructor by adding a new file under app/view/helper:
                                                                        May 8, 2017

                                                                        Mongo - Custom pessimistic locking mechanism

                                                                        Problem: Having one thread updating a document at a time. Solution: Lock manager: <![CDATA[ /** * MongoDB document locking manager * (custom solution) */ @Component public class MongoLockManager { private WriteConcern WRITE_CONCERN = WriteConcern.MAJORITY; private int TIMEOUT = 2; private TimeUnit TIMEOUT_TIME_UNIT = TimeUnit.SECONDS; @Autowired private MongoClient mongoClient; @Value(“${spring.application.name}") private String applicationName; private static final Logger logger = LoggerFactory.getLogger(MongoLockManager.class); /** * Inserts a document id in the product full details locking management collection * @param document the document containing the id to getLock */ public void insert(Document document) { Lock lock = new Lock(document.
                                                                          April 13, 2017

                                                                          Logstash - logstash.runner, An unexpected error occurred! does not exist, and I failed trying to create it

                                                                          Problem: [FATAL][logstash.runner ] An unexpected error occurred! {:error=>#<ArgumentError: Path “” does not exist, and I failed trying to create it Solution: chmod -R 755 or, chmod -R 755 /..
                                                                            March 20, 2017

                                                                            spring @async causing BeanCurrentlyInCreationException

                                                                            Problem: Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name ‘’: Bean with name ‘’ has been injected into other beans [] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using ‘getBeanNamesOfType’ with the ‘allowEagerInit’ flag turned off, for example.
                                                                              March 16, 2017

                                                                              Linux - Grep, escape back slash characters

                                                                              Problem: Execute ‘grep’ in order to match with: \“123456789\” Solution: grep ‘\\\“123456789\\\"’
                                                                                February 15, 2017

                                                                                Hibernate - Exception "node to traverse cannot be null"

                                                                                Problem: Hibernate exception “java.lang.IllegalArgumentException: node to traverse cannot be null” Query query = session.createQuery(“delete " + “(…) " + “where map_material.id > map_material_1.id " + " and map_material.map_key = map_material_1.map_key " + “(…) " Solution: Make sure to use hibernate “createSQLQuery” method Query query = session.createSQLQuery(“delete " + “(…) " + “where map_material.id > map_material_1.id " + “and map_material.map_key = map_material_1.map_key " + “(…) "
                                                                                  September 21, 2016

                                                                                  Java - Transform string list into list

                                                                                  Problem: Transform a list of strings into a single string. One solution is to iterate over the list and append its contents. Remember that StringBuilder’s append is much faster than Strings concatenation. Solution: A better solution is relying on Java StringJoiner <![CDATA[ String.join(", “, list); ]]> SyntaxHighlighter.highlight(); , or with Java 8 <![CDATA[ String joinedFirstNames = list.stream() .map(String::toString) .collect(Collectors.joining(", “)); ]]> SyntaxHighlighter.highlight();
                                                                                    September 12, 2016

                                                                                    Jongo Mongo - Unwind with match example

                                                                                    Example of an unwind query in Jongo MongoDB query <![CDATA[ db.getCollection(‘<collection_name>’) .aggregate([{$unwind : “$offers.offers”},{$match:{“offers.offers.seller.sellerId”:“999”}}]) ]]> SyntaxHighlighter.highlight(); Jongo query <![CDATA[ db.getCollection(‘<collection_name’) .aggregate([{$unwind : “$offers.offers”},{$match:{“offers.offers.seller.sellerId”:“999”}}]) Aggregate.ResultsIterator<class_name> products = <class_name>.<method_name>() .aggregate("{$unwind: ‘$offers.offers’}") .and("{$match:{offers.offers.seller.sellerId: #}}", String.valueOf(retailer.getId())) .as(<class_name> .class); ]]> SyntaxHighlighter.highlight();
                                                                                      September 7, 2016

                                                                                      Java - Measuring process times

                                                                                      Solution: <![CDATA[ (…) Instant startTime; Instant endTime; (…) startTime = Instant.now(); (…) // do your processing here (…) endTime = Instant.now(); // <some_class>.<some_static_method> JobLog.incrTime(Duration.between(startTime, endTime).toMillis()); (…) try { difference = JobLog.getTime(); long diffSeconds = difference / 1000 % 60; long diffMinutes = difference / (60 * 1000) % 60; long diffHours = difference / (60 * 60 * 1000) % 24; long diffDays = difference / (24 * 60 * 60 * 1000); System.
                                                                                        August 18, 2016

                                                                                        Mongo - Sum values inside documents

                                                                                        Schema: <![CDATA[ { (…) “offers” : { “offerCount” : 1, (…) } ]]> SyntaxHighlighter.highlight(); Solution: <![CDATA[ db.getCollection(‘<collection_name>’) .aggregate( {$group:{_id:"", totalAmount: { $sum: “$offers.offerCount” }, count: { $sum: 1 }}} ) ]]> SyntaxHighlighter.highlight(); Note: schema based on https://schema.org/AggregateOffer
                                                                                          August 17, 2016

                                                                                          Spring, Hibernate - org.springframework.retry.RetryException: Non-skippable exception in recoverer while processing; nested exception is org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session

                                                                                          Problem: org.springframework.retry.RetryException: Non-skippable exception in recoverer while processing; nested exception is org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session Solution 1: http://stackoverflow.com/questions/3609653/hibernate-error-org-hibernate-nonuniqueobjectexception-a-different-object-with Solution 2: This was the one that worked for me. Make sure to create a new object instead of reusing and old one and setting new values into it: records.setJob(feedJob); records.setProcessedRecords(seenFeedProducts.size()); feedJobRecordsDAO.save(records); vs. records = new FeedJobRecords(); records.setJob(feedJob); records.setProcessedRecords(seenFeedProducts.size()); feedJobRecordsDAO.save(records);
                                                                                            July 25, 2016

                                                                                            Mongo - Update element inside array

                                                                                            Problem: Update seller.id, from 1 to 4, inside the offers array: { “_id” : ObjectId(“578c7e3c92022220f068d8dd”), (…) “offers” : { (…) “offers” : [ { “productId” : “20001534”, (…) “seller” : { “_id” : “1”, “name” : “Mediamarkt” }, } ] } } Solution: db.getCollection(<target_collection_name>).update({“offers.offers.seller._id”:“1”},{$set:{“offers.offers.$.seller._id”:“4”}}, false, true) The third parameters tells mongo not to create new documents when no math es are found. The fourth parameters tells mongo to updated all matching documents
                                                                                              July 18, 2016

                                                                                              Spring data Mongo - Search inside array

                                                                                              Query query = new Query(Criteria.where("[FIELD]").in([VALUE_TO_SEARCH]));
                                                                                                June 30, 2016

                                                                                                Java 8 - Avoid null pointer exception on object calls

                                                                                                Optional.ofNullable().orElse(new ())).toString(); for example: <![CDATA[ Optional.ofNullable(message).orElse(new String()).replace("\t”, " “); ]]> SyntaxHighlighter.highlight();
                                                                                                  June 24, 2016

                                                                                                  Java 8 - Avoid null pointer exception while calling a null list, set or array of objects

                                                                                                  StringBuilder sb = new StringBuilder(); ofNullable(category).orElse(new LinkedList<>()).forEach(a->sb.append(a.toString()));
                                                                                                    June 24, 2016

                                                                                                    Spring data mongodb - remove element from array

                                                                                                    Remove an element from inside an array. Solution: Update update = new Update(); AdditionalProperty additionalProperty = new AdditionalProperty(); additionalProperty.setType("remove additional properties with this type"); update.pull("additionalProperty", additionalProperty); mongoClient.updateFirst(query, update, <collection\_name>);
                                                                                                      June 23, 2016

                                                                                                      Spring - Asynchronous longpooling rest controller via "callable"

                                                                                                      Implementation of an controller with asyncronous processing. This is a good solution for whenever a long pooling is needed. @RequestMapping(method = RequestMethod.PUT, path="xxx/yyy/{yyy}") public Callable<string> processProductImage2(HttpServletRequest request , @PathVariable("yyy") Integer yyy) { (...) Callable<string> callable = () -&gt; { (...) // long process (...) return "ok"; }; // return results to the caller return callable; } Notes: Though the controller seams to return imidiatelly the caller connection will still remain opened untl the results are returned.
                                                                                                        June 14, 2016

                                                                                                        Mongo - exception aggregation result exceeds maximum document size 16MB

                                                                                                        Problem: exception: aggregation result exceeds maximum document size (16MB) Solution: Configure the aggregation options and set it to return the results as a cursor:<![CDATA[ public BasicDBList aggregateWithCursor(Aggregation aggregation, Object source, Object target) { aggregation = aggregation.withOptions(Aggregation.newAggregationOptions().cursor(new BasicDBObject()).allowDiskUse(true).build()); AggregationResults<? extends Object> aggregationResults = mongoAccess.getMongoTemplate().aggregate(aggregation, source.getClass(), target.getClass()); BasicDBObject cursor = ((BasicDBObject) aggregationResults.getRawResults().get(“cursor”)); return (BasicDBList) cursor.get(“firstBatch”); } ]]> SyntaxHighlighter.highlight();
                                                                                                          May 31, 2016

                                                                                                          Java - Reflection dynamic toString() method

                                                                                                          <![CDATA[ @Override public String toString() { StringBuilder sb = new StringBuilder(); String value; sb.append(super.getClass().getName()); sb.append(": “); sb.append(super.toString()); sb.append(getClass().getName()); sb.append(": “); for (java.lang.reflect.Field f : Width.class.getDeclaredFields()) { try { value = f.get(this).toString(); sb.append(f.getName()); sb.append(“=”); sb.append(value); sb.append(", “); } catch (Exception e) { } } return sb.toString(); } ]]> SyntaxHighlighter.highlight();
                                                                                                            May 4, 2016

                                                                                                            Mongo - Update nested array element

                                                                                                            Problem: Update a nested element inside an array, lets say, the product “availability”. Example structure Solution:  The “non-trivial” part of this solution is the need for the “$” operator: <![CDATA[ (…) Query query = new Query(Criteria.where(“offers.offers.seller.name”).is(offer.getSeller().getName()) .and(“offers.offers.productId”).is(offer.getProductId())); update.set(“offers.offers.$.availability”, offer.getAvailability()); (…) ]]> SyntaxHighlighter.highlight();
                                                                                                              April 13, 2016

                                                                                                              Mongo - errno:111 Connection refused

                                                                                                              Problem: Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refuse Solution: $ sudo rm /var/lib/mongodb/mongod.lock $ mongod –repair $ sudo service mongodb start
                                                                                                                April 4, 2016

                                                                                                                Hibernate - javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: could not get a field value by reflection getter

                                                                                                                Problem: javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: could not get a field value by reflection getter <![CDATA[ public BigDecimal getMinPrice(Product product){ logger.debug(“Entering getMinPrice. productId="+product.getId()); Session session = this.sessionFactory.openSession(); Criteria criteria = session.createCriteria(ShopProductPriceHistory.class); criteria.add(Restrictions.eq(“product”, product.getId())); criteria.setProjection(Projections.min(“price”)); return (BigDecimal) criteria.uniqueResult(); } ]]> Solution: Check that the criteria is being done properly via join (Hibernate “Alias”). <![CDATA[ public BigDecimal getMaxPrice(Product product){ logger.debug(“Entering getMaxPrice. productId="+product.getId()); Session session = this.sessionFactory.openSession(); Criteria criteria = session.createCriteria(ShopProductPriceHistory.class); criteria.createAlias(“product”, “product”).add(Restrictions.eq(“product.id”, product.getId())); criteria.setProjection(Projections.max(“price”)); return (BigDecimal) criteria.
                                                                                                                  March 31, 2016

                                                                                                                  Spring batc, H2 - DataAccessResourceFailureException Could not obtain last_insert_id() Invalid parameter count for "LAST_INSERT_ID", expected count: "0"; SQL statement

                                                                                                                  Problem: Environment: Spring Batch Test database: H2 org.springframework.dao.DataAccessResourceFailureException: Could not obtain last\_insert\_id(); nested exception is org.h2.jdbc.JdbcSQLException: Invalid parameter count for "LAST\_INSERT\_ID", expected count: "0"; SQL statement: update BATCH_JOB_SEQ set ID = last_insert_id(ID + 1) <bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="transactionManager" ref="transactionManager" /> <property name="databaseType" value="mysql" /> </bean> Solution: <bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="transactionManager" ref="transactionManager" /> <property name="databaseType" value="h2" /> </bean> , besides, i also had to add two sequences to my spring batch scripts:
                                                                                                                    March 24, 2016

                                                                                                                    Java - JSTL, números aleatorios entre valores

                                                                                                                    Solución: Añadir la etiqueta a la página JSP: <jsp:useBean id="random” class="java.util.Random” scope="application”/> , y la siguiente etiqueta para generar un número aleatorio: ${random.nextInt(N)} , por ejemplo: Generar un número aleatorio entre 1 y 4, con el fin de mostrar un fondo diferente en cada actualización de la página:
                                                                                                                      March 24, 2016

                                                                                                                      Java - getResourceAsStream returning null

                                                                                                                      Problem: ProcessTest.class.getResourceAsStream(“H2/ddl/spring_batch/schema-drop.sql”); Solution: Check that the folder (““H2/ddl/spring_batch”) is part of the project classpath in eclipse: Right click on project Click “Build Path” Click “Configure Build Path…” Select “Java Build Path” Edit “Source” accordingly
                                                                                                                        March 23, 2016

                                                                                                                        Java, Mongo - Start mongo connecting to replica set

                                                                                                                        <![CDATA[ (…) import com.mongodb.MongoClient; (…) MongoClient mongo = new MongoClient(Arrays.asList( new ServerAddress(“<hostname_1>”, <host_port_1>), new ServerAddress(“<hostname_2>”, <host_port_2>), new ServerAddress(“<hostname_3>”, <host_port_3>))); // you may need to use: // Integer.parseInt(“<host_port">) ]]> SyntaxHighlighter.highlight();
                                                                                                                          March 18, 2016

                                                                                                                          Mongo - Start mongo connecting to replica set

                                                                                                                          $ mongo –host <replica_set_name>/<hostname_1>:<host_port_1>,host2[:porthost1],host3[:porthost3] <database_name> <replica_set_name>: Probably defaults to “rs0” Find the pairs :using the mongo command rs.status()
                                                                                                                            March 18, 2016

                                                                                                                            Mongo - error "not master and slaveOk=false"

                                                                                                                            Problem: listDatabases failed:{ “ok” : 0, “errmsg” : “not master and slaveOk=false”, “code” : 13435 } at src/mongo/shell/mongo.js:47 Solution: Make sure you have the replication set: rs.initiate();
                                                                                                                              March 17, 2016

                                                                                                                              Java, Mongo - BasicBSONList can only work with numeric keys not:

                                                                                                                              Problem <![CDATA[ DBObject offers = (DBObject) ((DBObject)mongoClient.find(query, fields).next().get(“offers”)).get(“offers”); assertEquals(“efgh”, ((DBObject)offers.get(“url”)); ]]> BasicBSONList can only work with numeric keys, not: [url] Solution: Looking at the Intelij debug output the solution became obvious: offers = {BasicDBList@5718} size = 1 0 = {BasicDBObject@7368} size = 12 0 = {LinkedHashMap$Entry@7371} “@type” -> “Offer” 1 = {LinkedHashMap$Entry@7372} “availability” -> 2 = {LinkedHashMap$Entry@7373} “name” -> “xxx” 3 = {LinkedHashMap$Entry@7374} “description” -> “yyy” 4 = {LinkedHashMap$Entry@7375} “itemCondition” ->
                                                                                                                                March 10, 2016

                                                                                                                                Play, EBean - SQLException Column Index out range 0 < 1

                                                                                                                                Problem: Caused by: java.sql.SQLException: Column Index out of range, 0 < 1. Solution: Ebean “translates” the result columns names to “productEanId”, “productId” and “ean”. The solution is to give as alias the exact same names of the property to which the columns are going to be assigned: <![CDATA[ (…) String sql = “select icecat_product_ean.product_ean_id productEANId, " + “icecat_product_ean.product_id productId, " + “icecat_product_ean.ean ean " + “from icecat_product_ean “; (…) ]]>
                                                                                                                                  March 2, 2016

                                                                                                                                  Java, Mongo - Update array element

                                                                                                                                  (based on http://schema.org/Product schema) <![CDATA[ private void update(String path, Object newValue, Integer productId, Integer retailerId) throws Exception { BasicDBObject query = new BasicDBObject(“productID”, String.valueOf(productId)) .append(“offers.offers.offerID”, String.valueOf(offerId))); BasicDBObject update = new BasicDBObject(“$set”, new BasicDBObject().append(“offers.offers.$.name”, newValue)); mongoDatasource.getMongoDatasource().update(query, update, false, true); } ]]> SyntaxHighlighter.highlight();
                                                                                                                                    February 26, 2016

                                                                                                                                    Mongo - Select max field (aggregate, $project, $macth)

                                                                                                                                    (based on http://schema.org/Product schema) <![CDATA[ db.user.aggregate([ { $match: {productID:“1”} }, { $project: {_id: “$productID”, highPrice: { $max: “$offers.highPrice”}} } ]) ]]> SyntaxHighlighter.highlight();
                                                                                                                                      February 26, 2016

                                                                                                                                      Play Framework - Get current controller path programmatically

                                                                                                                                      Problem: Get the current path from the inside the controller method Solution: <![CDATA[ play.mvc.Http.Context.Implicit.request().path() ]]> SyntaxHighlighter.highlight();
                                                                                                                                        February 19, 2016

                                                                                                                                        Java MongoDB - Commands

                                                                                                                                        Queries only the “productID” and “@type” fields from all the collection documents: BasicDBObject fields = new BasicDBObject(); query.put(“productID”, 1); query.put("@type”, 2); BasicDBObject allQuery = new BasicDBObject(); DBCursor cursor = mongoDatasource.getMongoDatasource().find(allQuery, fields); while(cursor.hasNext()) { DBObject document = cursor.next(); System.out.println(document); } Result: { “_id” : { “$oid” : “56c6c9e0612eb61e88166894”} , “@type” : “Product” , “productID” : “1”} Adding a new node to an exisitng array BasicDBObject query = new BasicDBObject().append(“productID”, String.valueOf(productId)); DBObject listItem = new BasicDBObject(“offers.
                                                                                                                                          February 19, 2016

                                                                                                                                          My mongoDB commands

                                                                                                                                          Lists all mongo databases show dbs Switches to a database use <database_name> Lists all database collections show collections Deletes all collection content db.<collection_name>.remove({}) Selects documents having offers with sub-type SingleOffer db.<collection_name>.find({“offers.@type”:“SingleOffer”}}) Displays all collection content db.user.find() Select with AND db.user.find({“offers.offers.offerID”:“1”, “productID”:“1”}) Single field update  The follwing command updates the type of the nested under offer { “_id” : “1”, “offer” : { “@type” : “foo”, (...) }
                                                                                                                                            February 19, 2016

                                                                                                                                            Avro - Defining nested types

                                                                                                                                            Message: {"source": "<source>", "action": "<action>", "identifier": "<identifier>", "data": { "productId": "<productid>", "keywords": "<keywords>" }, "start": <timestamp>} Avro serialization schema: {"namespace": "event.serialization.model.<package\_name>", "type": "record", "name": "<outer\_class\_name>", "fields": \[ {"name": "source", "type": \["string", "null"\]}, {"name": "action", "type": \["string", "null"\]}, {"name": "identifier", "type": \["string", "null"\]}, {"name": "data", "type": { "type": "record", "name": "<inner\_class\_name>", "fields": \[ {"name": "productId", "type": \["string", "null"\]}, {"name": "keywords", "type": \["string", "null"\]} \]}}, {"name": "start", "type": \["string", "null"\]} \]}
                                                                                                                                              February 18, 2016

                                                                                                                                              Play - Synchronous server calls with Jersey

                                                                                                                                              Synchronous server calls with Jersey Edit your build.sbt: <![CDATA[ libraryDependencies ++= Seq( (…) “com.sun.jersey” % “jersey-client” % “1.19”, “com.sun.jersey” % “jersey-core” % “1.19” (…) ) ]]> Edit your Java client class: <![CDATA[ Client client = Client.create(); client.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter(login, password)); WebResource webResource = client.resource(baseURL) .queryParam(“param1”, “param_value”) .queryParam(“param2”, “param_value”) .queryParam(“param3”, “param_value”); String response = webResource.header(“Content-Type”, “application/xml”).get(String.class); ]]> SyntaxHighlighter.highlight();
                                                                                                                                                February 16, 2016

                                                                                                                                                Spring - Asynchronous rest call to a server

                                                                                                                                                Implement a TaskService class responsible for running the asynchronous processing: private class TaskService { public TaskService) { // (...) } public String execute() throws InterruptedException { String url = (...); RestTemplate restTemplate = new RestTemplate(); return restTemplate.getForObject(url, <RETURNED_CLASS_NAME>.class); } } Implement the calling code for the above TaskService: private void callICECAT() throws IOException { TaskService taskService = new TaskService(); Callable<string> callable = taskService::execute; try { callable.call(); } catch (Exception e) { (.
                                                                                                                                                  February 10, 2016

                                                                                                                                                  Eclipse - Missing Maven Dependencies

                                                                                                                                                  Problem: Missing project “Maven Dependencies” event after trying to add them through the project “Build path”. Solution: Right click over the project settings “Maven” “Update Project…”
                                                                                                                                                    February 2, 2016

                                                                                                                                                    Java - javax naming NameNotFoundException DefaultDS not found

                                                                                                                                                    Problem: play javax.naming.NameNotFoundException: DefaultDS not found Solution: Make sure you include an jndiName to you database configuration, for example:  “db” : { “default” : { “driver” : com.mysql.jdbc.Driver }}, “db” : { “default” : { “url” : “jdbc:mysql://xxx.xxx.xxx.xxx:xxxx/<database_name>” }}, “db” : { “default” : { “username” : }}, “db” : { “default” : { “password” : }}. **_ “db” : { “default” : { “jndiName” : DefaultDS }},_**
                                                                                                                                                      February 1, 2016

                                                                                                                                                      Play - No Persistence provider for EntityManager named defaultPersistenceUnit

                                                                                                                                                      Problem: play No Persistence provider for EntityManager named defaultPersistenceUnit Solution: Make sure your file persistence.xml is inside a conf/META-INF subfolder (<project_root>/conf/META-INF/persistence/xml)
                                                                                                                                                        February 1, 2016

                                                                                                                                                        Play - Junit runtimeException no started application

                                                                                                                                                        Problem:  “RuntimeException: There is no started application” <![CDATA[ @Test public void test1() { (…) assertEquals(…); ]]> Solution: <![CDATA[ (…) import static play.test.Helpers.fakeApplication; import static play.test.Helpers.running; (…) @Test public void test1() { running(fakeApplication(), new Runnable() { public void run() { subscriber.set(“key_1”, “value_1”); subscriber.set(“key_2”, “value_2”); subscriber.set(“key_3”, “value_3”); assertEquals(subscriber.get(“key_1”),“value_1”); ]]> SyntaxHighlighter.highlight();
                                                                                                                                                          January 19, 2016

                                                                                                                                                          MySQL: Error 1071 Specified key was too long max key length is 1000 bytes

                                                                                                                                                          Problem: _(…) KEY `value` (`value`(250)) _ ) ENGINE=MyISAM; Error Code: 1071. Specified key was too long; max key length is 1000 bytes Solution: KEY `value` (`value`(250)) -- ) ENGINE=MyISAM; ) ENGINE=InnoDB DEFAULT CHARSET=utf8; alternatively: set global innodb_large_prefix = ON;
                                                                                                                                                            January 6, 2016

                                                                                                                                                            EGit Eclipse refresh branch list

                                                                                                                                                            Problem: Can’t see all existing branches while in the repository view. Solution: Select the git repository > right click > Pull > Ok
                                                                                                                                                              December 22, 2015

                                                                                                                                                              Hibernate - Update with Inner Join

                                                                                                                                                              Problem: Perform an hibernate update based on the results from a inner join. Solution: String hqlUpdate = “update Product p “ + “set p.flowStatus = :toFlowStatus “ + “where p.id in “ + “(select fp.id “ + “from OrderProduct as op “ + “inner join op.product as p “ + “where op.flowStatus = :orderProductFlowStatus” + “)"; sessionFactory.getCurrentSession().createQuery(hqlUpdate) .setString( “toFlowStatus”, toFlowStatus.getKey().toString()) _.setString( “_orderProductFlowStatus", feedProductDeltaFlowStatus.getKey().toString()) .executeUpdate();
                                                                                                                                                                December 10, 2015

                                                                                                                                                                Groovy, Soap UI - Mock service parameter testing script example

                                                                                                                                                                _import java.net.* // Match based on query parameter def queryString = mockRequest.getRequest()getQueryString(); def paramMap = queryString.split('&').collectEntries { param -> param.split(‘=’).collect { URLDecoder.decode(it) } } //def paramCount = paramMap.size() if( queryString == null) { log.info “400 bad request - no parameters”; return “400 bad request - no parameters”; } else if( queryString.contains(” “)) { log.info “400 bad request - queryString not correctly encoded”; return “400 bad request - queryString not correctly encoded”;
                                                                                                                                                                  December 7, 2015

                                                                                                                                                                  Play - play.libs.ws.WSClient [error] cannot find symbol

                                                                                                                                                                  Problem: [error] (…): package play.libs.ws does not exist [error] play.libs.ws.WSClient [error] (…): cannot find symbol [error] symbol: class WSClient [error] location: class controllers.(…) [error] WSClient [error] (compile:compileIncremental) javac returned nonzero exit code Solution: Add javaWs to build.sbt file: libraryDependencies ++= Seq( javaWs ) and refresh the project: sbt clean compile run or, activator clean compile run
                                                                                                                                                                    December 4, 2015

                                                                                                                                                                    Play - IllegalStateException: path.home is not configured

                                                                                                                                                                    Problem: IllegalStateException: path.home is not configured Solution:  Passing an activator initialization parameter (-Des.path.home): ./activator -DenvTarget=local -Des.path.home=/Project/Path/etc -jvm-debug 9010 clean compile run
                                                                                                                                                                      December 2, 2015

                                                                                                                                                                      Play - The import views.html.index cannot be resolved

                                                                                                                                                                      Problem: The import views.html.index cannot be resolved Solution:  Add target/scala-2.11/routes/main _target/scala-2.11/twirl/main _ to your project build path. For some reason the option bellow wasn’t enough: EclipseKeys.createSrc := EclipseCreateSrc.ValueSet(EclipseCreateSrc.ManagedClasses, EclipseCreateSrc.ManagedResources)
                                                                                                                                                                        November 30, 2015

                                                                                                                                                                        Hibernate - Avoid delete of all entity structure (cascade delete up)

                                                                                                                                                                        Problem: When issuing an delete action Hibernate cascades up and deletes all the entity structure. _ for(ShopProductSpec shopProductSpec: shopProductSpecs) { shopProductSpecDAO.delete(shopProductSpec); }_ _ …_ _ Hibernate: delete from shop_product_brand where shop_product_id=? Hibernate: delete from shop_product_brand where shop_product_id=? Hibernate: delete from shop_product_uid where id=? Hibernate: delete from shop_product_image where id=? Hibernate: delete from shop_product_image where id=? Hibernate: delete from shop_product_image where id=? Hibernate: delete from shop_product_image where id=? Hibernate: delete from shop_product_image where id=?
                                                                                                                                                                          November 12, 2015

                                                                                                                                                                          Hibernate - Criteria Inner Join

                                                                                                                                                                          Build an Inner Join in Hibernate: Solution: @Entity @Table(name = “shop_product_uid”) public class ShopProductUid { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = “shop_product_id”) private ShopProduct shopProduct; @Column(name = “shop_product_uid”) private String shopProductUid; @ManyToOne @JoinColumn(name = “shop_product_uid_type_id”) private ShopProductUidType shopProductUidType; Criteria criteria = session.createCriteria(ShopProductUid.class) criteria.createAlias(“shopProductUidType”, “shopProductUidType”) // inner join by default .add(Restrictions.eq(“shopProductUidType.typeId”, parameterTypeId));
                                                                                                                                                                            November 12, 2015

                                                                                                                                                                            Spring, Java - @ResponseBody(JSON) request returning Internal Server Error 500

                                                                                                                                                                            Problem: Requests to return an JSON object returns Internal Server Error 500 Solution: Controller: @RequestMapping(method = RequestMethod.GET, value = "/get") public @ResponseBody Question getQuestionsAjax() { (...) return (...); } mvc-dispatcher-servlet.java: mvc:annotation-driven/ <bean id="jacksonMessageConverter” class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter”/> Pom.xml <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.0</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.0</version> </dependency> @RequestMapping(method = RequestMethod.GET, value = "/get") public @ResponseBody Question getQuestionsAjax() { (...) return (...); }
                                                                                                                                                                              September 8, 2015

                                                                                                                                                                              Play - Caused by: java.lang.RuntimeException: There is no started application

                                                                                                                                                                              Problem: Caused by: java.lang.RuntimeException: There is no started application Solution: Tests under under Playframework need to be run inside fakeApplication() source: https://www.playframework.com/documentation/2.0/JavaTest <![CDATA[ import static org.fest.assertions.Assertions.assertThat; import static play.test.Helpers.fakeApplication; import static org.fest.assertions.Assertions.assertThat; import static play.test.Helpers.fakeApplication; import static play.test.Helpers.running; import org.junit.Test; import play.data.validation.ValidationError; public class AllTests { @Test public void validateBirthdate() { running(fakeApplication(), new Runnable() { public void run() { User user = new User(); Listerrors = new ArrayList(); user.ValidateDate(“dd/mm/yyyy”, “32/01/2015”, errors); // must fail user.
                                                                                                                                                                                July 31, 2015

                                                                                                                                                                                PersistenceException: ERROR executing DML bindLog[] error[Column 'XXX' specified twice]

                                                                                                                                                                                Problem: javax.persistence.PersistenceException: ERROR executing DML bindLog[] error[Column ‘graphId’ specified twice] (…) @Required public String city; @Required public String birthdate; @Required public String username; @Required public String password; public Long role_id; @ManyToOne @JoinColumn(name = “role_id”) public Role role; **Solution: ** Tell Hibernatee not to process the join column a “second time”: @ManyToOne @JoinColumn(name = “role_id”, insertable = false, updatable = false) public Role role;
                                                                                                                                                                                  July 30, 2015

                                                                                                                                                                                  Play - com.mysql.jdbc.Driver driver not found

                                                                                                                                                                                  Problem: Configuration error Driver not found: [com.mysql.jdbc.Driver] In /Users/guybrushtreepwood/git/Play/assessment-joel/conf/application.conf:33 # You can declare as many datasources as you want. # By convention, the default datasource is named `default` db.default.driver=com.mysql.jdbc.Driver db.default.url="jdbc:mysql://localhost:3306/play_assessment_db” db.default.user=play_user db.default.password="Pl@y” db.default.logStatements=true Solution: Add libraryDependencies += “mysql” % “mysql-connector-java” % “5.1.21” to build.sb located in the root of your project Run “sh activator clean” (MACOS) Run “sh activator dependencies (MACOS)
                                                                                                                                                                                    July 25, 2015

                                                                                                                                                                                    Wordpress, Hostmonster - 403 permission denied wp-admin install.php

                                                                                                                                                                                    Problem: 403 Permission Denied You do not have permission for this request /wp-admin/install.php Solution 1: Are you using an FTP application to manage your new Wordpress files? If so, try to use CPanel instead. Solution 2: Backup your .htaccess (rename it to .htaccess.old  Replace its contents with the default configuration: Options +FollowSymLinks # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index.php$ - [L] RewriteCond %{REQUEST_FILENAME} !
                                                                                                                                                                                      July 24, 2015

                                                                                                                                                                                      Heroku - Java HTTP 500 connection refused

                                                                                                                                                                                      Problem: HTTP ERROR 500 Problem accessing /header.jsp. Reason: Connection refused Caused by:java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect Solution: Check that there are no calls hardcoded connections to localhost (JSP imports, etc)
                                                                                                                                                                                        July 13, 2015

                                                                                                                                                                                        Java, Spring, Javascript: errorThrown SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

                                                                                                                                                                                        Problema: errorThrown SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data Solucion: JSON esta esperando por lo menos un array vacio, un objecto tipo String (return new String()) no es suficiente. @RequestMapping("/xxx”) public @ResponseBody String[] xxx(HttpServletRequest request, @RequestParam(“xxxx”) String xxx) { (…) return new String[]{""}; } }
                                                                                                                                                                                          March 4, 2015

                                                                                                                                                                                          JAVA - Problem accessing the absolute URL; java.net.ConnectException: Connection refused

                                                                                                                                                                                          **Problem:**org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspException: Problem accessing the absolute URL “http://localhost:8089/xxxx/xxxx.jsp”. java.net.ConnectException: Connection refused Solution: Fix the http port number on the application server. On this particular case it should be 8089.
                                                                                                                                                                                            February 7, 2015

                                                                                                                                                                                            Spring - Bean property 'propertyXXX' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?

                                                                                                                                                                                            Problem: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'beanXXX' defined in class path resource \[pathXXX/filenameXXX\]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'propertyXXX' of bean class \[packageXXX.classXXX\]: Bean property 'propertyXXX' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter? Solution Add the setter and getter methods for the invalid property.
                                                                                                                                                                                              October 30, 2014

                                                                                                                                                                                              Codility PermCheck test 100% score

                                                                                                                                                                                              Solution to Codility PermCheck Problem at: [https://codility.com/c/intro/demoJH2RM2-UZ8](https://codility.com/c/intro/demoJH2RM2-UZ8) class Solution { public static void main(String[] args) { int A[] = {4, 1, 3, 2}; //int A[] = {4, 4, 3, 2}; //int A[] = {4, 3, 2}; //int A[] = {}; //int A[] = {1000000000, 3, 2}; //int A[] = {1000000000, 1000000001, 1000000002}; //int A[] = new int[100000]; System.out.println(solution(A)); } public static int solution(int[] A) { int result = 0; int size = A.
                                                                                                                                                                                                September 17, 2014

                                                                                                                                                                                                JAVA - Codility FrogRiverOne test 100% score

                                                                                                                                                                                                class Solution { public int solution(int X, int[] A) { // write your code in Java SE 8 int numberOfPositions = 0; int result = -1; int[] array = new int[X]; int index = 0;  // Initialize array for (int i : array) { array[index] = -1; index++; }  index = 0; for (int i : A) { try { if (array[i - 1] == -1) { array[i - 1] = index;
                                                                                                                                                                                                  September 15, 2014

                                                                                                                                                                                                  Codility "Equilibrium"

                                                                                                                                                                                                  class Solution { public int solution(int[] B) { // write your code in Java SE 8 long[] rightToLeft = new long[A.length]; long[] leftToRight = new long[A.length]; long[] A = new long[B.length]; int result = -1; // Convert int array to long array int j = 0; for (int value : B) { A[j++] = (long)value; } for(int i=0; i<rightToLeft.length; i++){ if(i==0){ rightToLeft[i] = A[i]; } else { rightToLeft[i] = A[i] + rightToLeft[i-1]; } } for(int i=leftToRight.
                                                                                                                                                                                                    September 15, 2014

                                                                                                                                                                                                    APEX - Error saving column settings with ORA-01403: no data found Error

                                                                                                                                                                                                    Problem: While working with the report source and column names somehow it became “corrupted”, it was impossible to change the name of one of the columns though possible to update the source and the rest of column names: While saving the report APEX was showing the bellow error: _ Error saving column settings with ORA-01403: no data found Error_ Solution: Try to force APEX to refresh the column names by selection:
                                                                                                                                                                                                      September 12, 2014

                                                                                                                                                                                                      Hostmonster - 403 Permission denied (htaccess)

                                                                                                                                                                                                      Are you getting the error “403 Permission denied” when trying to access your website from a single location? Try the following: Go to Google and search for “what is my ip” Get the ip returned by your search query Access your cpanel and go to your home or “public_html” folder Backup the .htaccess file to ,htaccess_old Open .htaccess Search for any entry related to your ip (search for a few numbers only if the full ip is not found)
                                                                                                                                                                                                        September 8, 2014

                                                                                                                                                                                                        APEX - Dynamic actions "in list" condition not working

                                                                                                                                                                                                        Problem: While setting an APEX dynamic action with the condition “in list” the system is ignoring the last element. _ MANAGER,ADMIN_ Solution: Though the user manual states that the elements in the list must be comma separated it omits the fact that it must also end with comma. _ MANAGER,ADMIN**,**_
                                                                                                                                                                                                          September 5, 2014

                                                                                                                                                                                                          JAVA - Introduce Line break in request

                                                                                                                                                                                                          In the example bellow the recipe description had something like: _ 100ml milk\r\n10g sugar_ which in html corresponded to the following textarea contents: _ 100ml milk_ _ 10g sugar_  @RequestMapping("/submitRecipe”) public String submitRecipe2(Model model, @ModelAttribute Recipe recipe, HttpServletRequest request) { model.addAttribute(“recipe”, recipe.getDescription().replace("\r\n”, “%0A”)); return “result2”; }
                                                                                                                                                                                                            September 3, 2014

                                                                                                                                                                                                            ORACLE - SQL estructura jerarquica padre hijo

                                                                                                                                                                                                            El proximo SQL devuelve la informacion jerárquicade los registros en una table basando en el código del padre. Este script es muy útil para determinar la estructura de jerarquía: _SELECT _ _ ID, _ _ ORGANIZACION, _ _ ID_PADRE, _ _** LEVEL, – PALABRA RESERVADA**_ _** SYS_CONNECT_BY_PATH(ORGANIZACION, ‘/') – USADO PARA LA CONSTRUCCIÓN DEL PATH/MIGA-DE-PAN (PUEDE SER REMOVIDO)**_ _FROM_ _ ORG_UNITS_ _where _ _ ACTIVE = 0_ _**START WITH ID = XXX – CÓDIGO DEL PADRE, RAÍZ DE LA ESTRUCTURA**_
                                                                                                                                                                                                              August 29, 2014

                                                                                                                                                                                                              Java - JSTL, random number between values

                                                                                                                                                                                                              Add the bellow tag to your jsp page: <jsp:useBean id="random” class="java.util.Random” scope="application”/> , and the followin tag to generate your random number: ${random.nextInt(N)} Particular case: Generate a random number, between 1 and 4, in order to display a different background at each page refresh:
                                                                                                                                                                                                                August 28, 2014

                                                                                                                                                                                                                Java - SpringMVC NetworkError 406 Not Acceptable while using JSON

                                                                                                                                                                                                                Problem: “NetworkError 406 Not Acceptable” when calling a servlet using jQuery and expecting a JSON result. <![CDATA[ function getRecipeNutritionalInformation(recipe) { $.getJSON(“http://xxx/getRecipeNutritionalInformation?recipe=” + recipe, function(data){ res=jQuery.stringify(data); $.each(data, function(index) { alert(index); }); }) .success(function() { alert(“success”);}) .error(function(XMLHttpRequest, textStatus, errorThrown) { alert(“textStatus “+textStatus); alert(“errorThrown “+errorThrown);}) .complete(function() { alert(“complete”);}) ; } @RequestMapping(method=RequestMethod.GET, value=”/getRecipeNutritionalInformation”) public @ResponseBody NutritionalFacts getRecipeNutritionalInformation(@RequestParam(“recipe”) String input) { (…) } ]]> Solution: The JSON converting Maven dependencies (or plain libraries) might be missing on the project classpath:
                                                                                                                                                                                                                  August 27, 2014

                                                                                                                                                                                                                  Java - Project properties Cannot nest inside library

                                                                                                                                                                                                                  Problem: Cannot nest ‘xxx/test/java’ inside library ‘xxx/src’ Solution: Check the project properties libraries configuration, in my case the problem was in the “Web App Libraries” configuration. Once removed the problem was solved.
                                                                                                                                                                                                                    August 26, 2014

                                                                                                                                                                                                                    APEX - Set item value from different page via Javascript

                                                                                                                                                                                                                    In order to set a item value in another page without submitting the page create a Javscript call in the source page: javascript:opener.document.getElementById(“DESTINY_PAGE_ITEM_NAME”).value = VALUE_TO_SET; For example, you may have an interactive report showing a set of values, on click, this row values should populate a form in a different page: Interactive Report: Interactive Report configuration: Source page header section source:
                                                                                                                                                                                                                      July 3, 2014

                                                                                                                                                                                                                      APEX - Javascript submit page with confirmation box

                                                                                                                                                                                                                      Problem: Submit APEX page via JavaScript with confirmation box. *Solution: Set the link action as “Redirect to URL” and set the URL as: javascript:apex.confirm(‘’,‘’);
                                                                                                                                                                                                                        May 21, 2014

                                                                                                                                                                                                                        APEX - Not passing session values

                                                                                                                                                                                                                        Problem: APEX is not passing values from one page to other: Solution: Set Item “Save Session State” value to “Yes”
                                                                                                                                                                                                                          May 1, 2014

                                                                                                                                                                                                                          Cocos 2d - You don’t have permission to save the file “api-docs”

                                                                                                                                                                                                                          Problem: With both the installer and package downloaded from github i was getting: >» Installing Cocos2D-v3.0.0 files >» Installing Cocos2D-v3.0.0 templates >» Building/Installing Cocos2D-v3.0.0 documentation, this may take a minute…. appledoc version: 2.2 (build 963) Generation step 1/5 failed: GBHTMLOutputGenerator failed copying template files to output, aborting! You don’t have permission to save the file “api-docs”. You don’t have permission. >» Cocos2D-v3.0.0 installation complete! Solution: It seams that the user which you are using to install Cocos 2d has to belong to the sudoers file.
                                                                                                                                                                                                                            April 16, 2014

                                                                                                                                                                                                                            APEX - javascript apex submit pasando parametros variables

                                                                                                                                                                                                                            Problema: Submit de una pagina en APEX con javascript pasando a la vez variables/valores en el request. Solución: Usar el carácter de escape " en substitución de " : javascript:apex.submit({request:"SAVE",set:{"P400_REPORT_ID":2}}); Passing as argument an APEX variable: javascript:apex.submit( {request:"SAVE" ,set{"P400_REPORT_ID":"&P400_MPP_REPORT_ALL_Y_ID."}});
                                                                                                                                                                                                                              April 15, 2014

                                                                                                                                                                                                                              ORACLE - SQL inserir cambio de linea en campo texto (varchar2, bloc, clob, etc.)

                                                                                                                                                                                                                              Problema: Inserir un cambio de linea(enter) en un campo de texto, varchar2, clob, blob etc. Solución: Concatenar chr(13) || chr(10): _ p_log clob;_ _ p_log := p_log || ‘blah blah’ || chr(13) || chr(10);_
                                                                                                                                                                                                                                April 1, 2014

                                                                                                                                                                                                                                Apex - Submit current page via Javascript

                                                                                                                                                                                                                                In order to submit the current page via JavaScript edit the element that will trigger the event and configure the target as a URL with the following link: javascript:apex.submit();
                                                                                                                                                                                                                                  March 27, 2014

                                                                                                                                                                                                                                  Maven - springframework.web.context.ContextLoaderListener org.lang.ClassNotFoundException

                                                                                                                                                                                                                                  Problema: java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener Solución: Ir a las propriedades del proyecto (botón derecho del ratón sobre el nombre del proyecto) Seleccionar “Deployment Assembly”. “Add.. Seleccinar “Java Build Path Entries” “Next” Seleccinar “Maven Dependencies”  “Finish”
                                                                                                                                                                                                                                    March 27, 2014

                                                                                                                                                                                                                                    Maven - Update Index Repository

                                                                                                                                                                                                                                    Problema: Por veces Maven deja de lograr encontrar nuevas dependencias. Una de las soluciones es actualizar los repositorios/indices locales de Maven Solución: Window -> Show View -> Maven Repositories
                                                                                                                                                                                                                                      March 27, 2014

                                                                                                                                                                                                                                      HTTP Status 500 absolute cannot resolved web.xml jar deployed application

                                                                                                                                                                                                                                      Problem: HTTP Status 500 - The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application Solution: Add the following Maven dependency: <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> Or alternatively dowload and deploy the jstl jar file.
                                                                                                                                                                                                                                        March 25, 2014

                                                                                                                                                                                                                                        ORACLE - ORA-12008: error in materialized view refresh path ORA-01476: divisor is equal to zero

                                                                                                                                                                                                                                        **Problem: ** begin dbms_mview.refresh(‘MY_VIEW’,‘C’); end; ORA-12008: error in materialized view refresh path ORA-01476: divisor is equal to zero create or replace MY_VIEW(F_FIELD_1, (…), F_CREATED_BY, F_CREATED_ON, F_UPDATED_BY, F_UPDATED_ON) as select (…) CREATED_DATE, to_date(CREATED_BY, ‘DD/MM/YYYY’), UPDATEDD_DATE, to_date(UPDATED_BY, ‘DD/MM/YYYY’),  from (…) ; Caused by: to_date(CREATED_BY, ‘DD/MM/YYYY’), to_date(UPDATED_BY, ‘DD/MM/YYYY’),
                                                                                                                                                                                                                                          January 27, 2014

                                                                                                                                                                                                                                          Tomcat - Como iniciar y cerrar Apache Tomcat en un sistema MacOS

                                                                                                                                                                                                                                          Para iniciar el Apache Tomcat en un sistema MacOS deberá abrir una consola y ir a la carpeta donde se desplegó el Tomcat, por ejemplo: cd /Users/XXX/Other Applications/apache-tomcat-6.0.37 en seguida entrar en la carpeta “bin” donde se encuentran los scripts para iniciar y cerrar el Tomcat cd bin Finalmente iniciar el tomcar via: sh startup.sh , la respuesta podrá ser algo como: xxx-MacBook-Air:bin xxx$ sh startup.sh Using CATALINA_BASE: /Users/xxx/Other Applications/apache-tomcat-6.0.37
                                                                                                                                                                                                                                            January 2, 2014

                                                                                                                                                                                                                                            Oracle - SQL - Retornar registros entre incio del ano passado y el proximo

                                                                                                                                                                                                                                            Solución: select * from where between to_date(‘0101’ || to_char(trunc(sysdate, ‘YEAR’)-1, ‘YYYY’), ‘DDMMYYYY’) AND to_date(‘3112’ || to_char(trunc(sysdate, ‘YEAR’)+1, ‘YYYY’), ‘DDMMYYYY’)
                                                                                                                                                                                                                                              December 3, 2013

                                                                                                                                                                                                                                              ORACLE - PL/SQLsubstituir texto (String Replace)

                                                                                                                                                                                                                                              Para substituir texto em PL/SQL es necesario usar la funcion REPLACE Atención: REPLACE devuelve la string con la substituicion echa, por lo tanto el resultado de su llamada debera ser guardado en una variable: … text_aux varchar2(1024); text clob; … text := text || replace(text_aux, ' xmlns=’ || chr(34) || ‘http://www.aaa.com’ || chr(34), ‘'); … (En este caso chr(34) es el carácter de escape para: “)
                                                                                                                                                                                                                                                November 13, 2013

                                                                                                                                                                                                                                                java rmi server ExportException internal error ObjID already use

                                                                                                                                                                                                                                                Problem: Sep 21, 2013 9:12:09 AM suncertify.main.URLyBirdMain main INFO: Executing in server mode. Sep 21, 2013 9:12:09 AM suncertify.server.RMIFactoryServerImpl INFO: rmi://127.0.0.1:1099/URLyBirdRMIServer java.rmi.server.ExportException: internal error: ObjID already in use at sun.rmi.transport.ObjectTable.putTarget(ObjectTable.java:169) at sun.rmi.transport.Transport.exportObject(Transport.java:74) at sun.rmi.transport.tcp.TCPTransport.exportObject(TCPTransport.java:229) at sun.rmi.transport.tcp.TCPEndpoint.exportObject(TCPEndpoint.java:393) at sun.rmi.transport.LiveRef.exportObject(LiveRef.java:129) at sun.rmi.server.UnicastServerRef.exportObject(UnicastServerRef.java:188) at sun.rmi.registry.RegistryImpl.setup(RegistryImpl.java:100) at sun.rmi.registry.RegistryImpl.(RegistryImpl.java:86) at java.rmi.registry.LocateRegistry.createRegistry(LocateRegistry.java:186) at suncertify.server.RMIFactoryServerImpl.(RMIFactoryServerImpl.java:38) at suncertify.server.RMIFactoryServerImpl.(RMIFactoryServerImpl.java:43) at suncertify.main.ServerModeMain.(ServerModeMain.java:54) at suncertify.main.URLyBirdMain.main(URLyBirdMain.java:41) and the class: public class RMIFactoryServerImpl extends UnicastRemoteObject implements RMIFactoryServer {  private static final long serialVersionUID = 2364209308189771862L;
                                                                                                                                                                                                                                                  September 21, 2013

                                                                                                                                                                                                                                                  Java - RMI - Caused by: java.lang.IllegalArgumentException: illegal remote method encountered

                                                                                                                                                                                                                                                  Problem: Caused by: java.lang.IllegalArgumentException: illegal remote method encountered: public abstract java.util.List suncertify.server.Server.getAccomodation() Used Interface: public interface Server extends java.rmi.Remote, Serializable { List getAccomodation(); List getAccomodation(String criteria); List getAccomodation(int recNo); List bookAccomodation(int recNo); } Solution: Java RMI and Remote interface make mandatory for all methods to throw RemoteException public interface Server extends java.rmi.Remote, Serializable { List getAccomodation() throws RemoteException; List getAccomodation(String criteria) throws RemoteException; List getAccomodation(int recNo) throws RemoteException; List bookAccomodation(int recNo) throws RemoteException;
                                                                                                                                                                                                                                                    September 16, 2013

                                                                                                                                                                                                                                                    Oracle - Ler/Insert ficheros XML

                                                                                                                                                                                                                                                    Teniendo un fichero XML: Una tabla: CREATE TABLE XML_TEST (id number, title varchar2(200), description varchar2(200)); Para ler el fichero en la consola: SELECT * FROM XMLTABLE('/Row’ PASSING XMLTYPE(BFILENAME(‘’, ‘’), NLS_CHARSET_ID(‘CHAR_CS’)) COLUMNS ID NUMBER PATH ‘F_ID’, TITLE VARCHAR2(200) PATH ‘F_TITLE’, DESCRIPTION VARCHAR2(200) PATH ‘F_DESCRIPTION’ ); Otra alternativa es hacer el insert de un fichero XML en una tabla: INSERT INTO xml_test (ID, TITLE, DESCRIPTION) SELECT * FROM XMLTABLE('/Row’ PASSING XMLTYPE(BFILENAME(‘’, ‘’),
                                                                                                                                                                                                                                                      August 29, 2013

                                                                                                                                                                                                                                                      Oracle - ORA-00955 name is already used by an existing object 00955

                                                                                                                                                                                                                                                      Problem: ORA-00955: name is already used by an existing object 00955. 00000 - “name is already used by an existing object” Solution: Verificar que tipo de object esta a utilizar el nombre: _ select * from all_objects where object_name = ‘XXX’;_ Si el object existing no es necesario se puede realizar el drop: _ drop “tipo_de_objecto” “nombre_del_object”;_
                                                                                                                                                                                                                                                        June 26, 2013

                                                                                                                                                                                                                                                        Spring - Repeated column in mapping for collection:

                                                                                                                                                                                                                                                        Problem: Caused by: org.hibernate.MappingException: Repeated column in mapping for collection: xxx.xxx.xxx.xxx: ID Cause by: <list name\="value" table\="QUESTION\_VALUE" cascade\="save-update, delete" fetch\="join" lazy\="true"\> <key column\="ID"/> **<index column\="ID"\></index\>** <one-to-many class\="com.mkyong.common.model.QuestionValue"/> </list\> Solution: User a field other than “ID”, in my case i created a “ORDER” and filled its value explicity.
                                                                                                                                                                                                                                                          May 18, 2013

                                                                                                                                                                                                                                                          ORACLE - Cambiar próxima fecha de ejecución de un job

                                                                                                                                                                                                                                                          Listar los Oracle jobs existentes: select * from dba_jobs; Obtener la próxima fecha de ejecución: select to_char( next_date, ‘YYYYMMDD:HH24MI’) from dba_jobs where job = 181; Testar la próxima fecha de ejecución: select to_char( trunc(SYSDATE) + ((16*60)+50)/1440 , ‘YYYYMMDD:HH24MI’) from dual; Aplicar los cambios: exec DBMS_JOB.next_date ( <JOB_ID>, trunc(SYSDATE) + ((16*60)+50)/1440); Commit a los cambios: Commit;
                                                                                                                                                                                                                                                            May 11, 2013

                                                                                                                                                                                                                                                            APEX - Item ID (XXX) is not an item defined on the current page

                                                                                                                                                                                                                                                            Thanks for posting such simple solution to this. Anonymous - Nov 1, 2013Thanks for posting such simple solution to this. This absolutely saved me some headache. Many thanks! Thank you so much! I referred to this solution twice -because I’m so dumb and I don’t learn from my mistakes- and I just have to thank you!! Thanks a lot! Awesome!!! Saved my day!! Awesome!!! Saved my day!! Thank you so muach.
                                                                                                                                                                                                                                                              April 16, 2013

                                                                                                                                                                                                                                                              APEX - Item ID (XXX) is not an item defined on the current page

                                                                                                                                                                                                                                                              **Environment: ** APEX4.2 application migrated from 3. Problem: Error message: “Item ID (XXX) is not an item defined on the current page” Solution: Determine what is the object with ID XXX; select * from apex_application_page_items where item_id = XXX; Go to the conflicting item and change from “Display as” “Text Field” to “Text Area” Save After performing this solution i could even return and change it back to “Display as” Text Field.
                                                                                                                                                                                                                                                                April 16, 2013

                                                                                                                                                                                                                                                                Oracle - Importar datos desde otra dase datos (impdb)

                                                                                                                                                                                                                                                                El siguiente script transfiere datos del esquema AAA de una base de datos usando el database link BBB. Porque deseamos guardar las trazas de la operación en el fichero de nombre CCC tendremos que informar Oracle que debe hacerlo en el directory object DDD: impdp system/system_user_password schemas=AAA directory=DDD network_link=BBB logfile=CCC remap_schema=AAA:AAA remap_tablespace=AAA:AAA Nota: 1- El script arriba parte del principio que el tablespace tiene el mismo nombre que el esquema
                                                                                                                                                                                                                                                                  April 10, 2013

                                                                                                                                                                                                                                                                  Oracle - Importing data from another database (impdb)

                                                                                                                                                                                                                                                                  The following script transferes the schema AAA from a database using the database link BBB. Because we want to store the log of this operation in file CCC we have to inform oracle to save it int the directory object DDD: impdp system/system_user_password schemas=AAA directory=DDD network_link=BBB logfile=CCC_ remap_schema=AAA:AAA remap_tablespace=AAA:AAA_ Nota: 1- The above script takes into consideration that the tablespace has the same name as the schema 2- In order to import the data, instead of only the databale elements (tables, views, etc) droping the schema might also be necesary.
                                                                                                                                                                                                                                                                    April 10, 2013

                                                                                                                                                                                                                                                                    Oracle - Concatenate several columns in one cell separeted by newline

                                                                                                                                                                                                                                                                    In order to concatenate the values of the same column across several records do: _ select replace( wm_concat(<FIELD_NAME>), ‘,', chr(13)) from <TABLE_NAME>; _ Examples: Add all distinct values in the same cell separated by “:”  select distict(wm_concat(<FIELD_NAME>), ‘,', ‘:') from <TABLE_NAME>; Add all values in the same cell separated by a new line “chr(13)” _ replace(wm_concat(<FIELD_NAME>), ‘,', chr(13))_
                                                                                                                                                                                                                                                                      April 8, 2013

                                                                                                                                                                                                                                                                      ORACLE - Concatenar varias lineas en una celda

                                                                                                                                                                                                                                                                      Seguidamente un ejemplo de como juntar en una misma celda el contenido de varios registros. Ejemplo de una table estudiantes con varios periodos StudentId FromDate ToDate 28 01-Oct-08 31-Dec-07 28 01-Jan-09 31-Mar-09 34 01-Feb-11 30-Jun-11 35 01-Feb-11 30-Jun-11 36 01-Nov-10 31-Dec-10 36 01-Mar-11 31-May-11 Si queremos ensenar todos los periodos de cada uno de los estudiantes en una misma celda: -- Juntar las varias celdas de las varias lineas en una misma celda
                                                                                                                                                                                                                                                                        April 5, 2013

                                                                                                                                                                                                                                                                        Oracle - Converter varchar2 para Clob

                                                                                                                                                                                                                                                                        De modo a convertir una columna tipo varchar2 para clob es necesario: paso 1 - adicionar una nueva columna con del tipo clob: alter table add( clob); paso 2 - copiar los datos de la columna tipo varchar2 para la nueva tipo clob: update <___tabla> set <___nombre_nueva_columna_> = ;_ paso 3 - finalmente, renombrar el nombre de la nueva columna para el nombre de original: alter table <_____tabla> rename column_ _to_ _;
                                                                                                                                                                                                                                                                          April 2, 2013

                                                                                                                                                                                                                                                                          Oracle - Convert varchar2 to Clob datatype

                                                                                                                                                                                                                                                                          In order to convert a column datatype from varchar2 to clob do: step 1 - add a column with clob datatype: _alter table add( clob); _ step 2 - copy data from the source column to the new one: _update set = ; _ step 3 - rename the new column created in the step 1 in order to complete the process: alter table__rename column to ; alter table__rename column to ;
                                                                                                                                                                                                                                                                            April 2, 2013

                                                                                                                                                                                                                                                                            Jackson - BeanSerializer.serialize and ContainerSerializers$CollectionSerializer.serialize error

                                                                                                                                                                                                                                                                            In a Spring + Hibernate + Jackson project while calling: http://localhost:8080/SpringMVC/getAllBookmark (…) @RequestMapping(value=”/getAllBookmark”, method = RequestMethod.GET) public @ResponseBody List getAllBookmarkJSON() { List list = this.bookmarkDAO.getAllBookmark(); return list; } (…) , was getting the following error: at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:122) at org.codehaus.jackson.map.ser.ContainerSerializers$CollectionSerializer.serialize(ContainerSerializers.java:151) at org.codehaus.jackson.map.ser.ContainerSerializers$CollectionSerializer.serialize(ContainerSerializers.java:117) at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:218) The problem was related to a cyclic reference (click here for more information) in a relation type “many-to-one” between Bookmark and Image: (…) public class Bookmark implements Serializable {
                                                                                                                                                                                                                                                                              March 21, 2013

                                                                                                                                                                                                                                                                              Oracle - Conceder permisos de acceso a una table

                                                                                                                                                                                                                                                                              Script para conceder permisos de acceso a una tabla/view a un User/Schema: grant select on to ; Con opcion “grantable” grant select on to ; with grant option;
                                                                                                                                                                                                                                                                                March 4, 2013

                                                                                                                                                                                                                                                                                Hibernate - HibernateException: createQuery is not valid without active transaction

                                                                                                                                                                                                                                                                                I have this problem.by use your solution.. i clear… Unknown - Jul 5, 2015I have this problem.by use your solution.. i clear the error. Thnaks :) glad i could help i have the same problem.but I have auto-generated dao classes so i can’t add the line " Transaction tx = getCurrentSession().beginTransaction();” manually. then how can i solve this pb? Are you using Spring? Maybe using the @Transactional annotation at method level could be a solution.
                                                                                                                                                                                                                                                                                  March 3, 2013

                                                                                                                                                                                                                                                                                  Hibernate - HibernateException: createQuery is not valid without active transaction

                                                                                                                                                                                                                                                                                  Problem: SEVERE: Servlet.service() for servlet mvc-dispatcher threw exception org.hibernate.HibernateException: createQuery is not valid without active transaction at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:338) at com.sun.proxy.$Proxy20.createQuery(Unknown Source) at com.mkyong.common.dao.MessageDAO.getAllMessages(MessageDAO.java:39) at com.mkyong.common.controller.MessageController.printMessageList(MessageController.java:39) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778) at javax.servlet.http.HttpServlet.service(HttpServlet.java:617) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
                                                                                                                                                                                                                                                                                    March 3, 2013

                                                                                                                                                                                                                                                                                    Oracle - duplicate fields in RECORD,TABLE or argument list are not permitted

                                                                                                                                                                                                                                                                                    Thank you. that post is very useful. Ahmet DEMIR - Mar 2, 2017Thank you. that post is very useful.
                                                                                                                                                                                                                                                                                      February 25, 2013

                                                                                                                                                                                                                                                                                      Oracle - duplicate fields in RECORD,TABLE or argument list are not permitted

                                                                                                                                                                                                                                                                                      Problem: Error: PLS-00323: subprogram or cursor ‘UPD_COSTELEMENTX’ is declared in a package specification and must be defined in the package body Error: PLS-00410: duplicate fields in RECORD,TABLE or argument list are not permitted _Error: PL/SQL: Item ignored _ procedure UPD_COSTELEMENT (p_commit in number, p_out_msg out varchar2) is (…) l_logfile_name varchar2(250); **p_out_msg varchar2(4000); ** lf utl_file.file_type; begin dbms_output.enable(null); _(…) _ Cause: Double initialization of the variable p_out_msg.
                                                                                                                                                                                                                                                                                        February 25, 2013

                                                                                                                                                                                                                                                                                        Oracle - ORA-29282: invalid file ID, ORA-06512: at "SYS.UTL_FILE"

                                                                                                                                                                                                                                                                                        Problem: Connecting to the database APPS_MANPOWER_PLUS_APPS. ORA-29282: invalid file ID ORA-06512: at “SYS.UTL_FILE”, line 878 ORA-06512: at “APPS_MANPOWER_PLUS.PKG_UPD_BULK”, line 421 ORA-06512: at line 6 -——————————————————————————- Process exited. , generated by: (…) _ _ begin dbms_output.enable(null); dbms_output.put_line(RPAD('-',80,'-')); utl_file.put_line(lf, RPAD('-',80,'-')); l_logfile_name := ‘UPD_XXX’ || ‘_’ || to_char(sysdate, ‘YYYYMMDDHH24MISS’) || ‘.log’;___ **lf := utl_file.fopen(‘OPERATION_LOGS’, l_logfile_name, ‘W’);**__ dbms_output.put_line(‘BEGIN: PKG_UPD_BULK.UPD____XXX_'); utl_file.put_line(lf, ‘BEGIN: PKG_UPD_BULK.UPD____XXX_');_ _(…) _ Cause: Write in the file before first open it. The correct code should be:
                                                                                                                                                                                                                                                                                          February 25, 2013

                                                                                                                                                                                                                                                                                          Oracle - Send mail with UTL_SMTP

                                                                                                                                                                                                                                                                                          Procedure PL/SQL to send a email using UTL_SMTP package: Declare l_mail_conn UTL_SMTP.connection; BEGIN l_mail_conn := UTL_SMTP.open_connection('', 25); UTL_SMTP.helo(l_mail_conn, ‘'); UTL_SMTP.mail(l_mail_conn, ‘'); UTL_SMTP.rcpt(l_mail_conn, ' UTL_SMTP.data(l_mail_conn, '’ || UTL_TCP.crlf || UTL_TCP.crlf); UTL_SMTP.quit(l_mail_conn); END;
                                                                                                                                                                                                                                                                                            February 18, 2013

                                                                                                                                                                                                                                                                                            Spring - BeanCreationException or CGLIB2 when using @Transactional(readOnly = true)

                                                                                                                                                                                                                                                                                            Problem: If the instruction @Transactional(readOnly = true) is causing the bellow error(s): org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xxx' defined in class path resource \[xxx/xxx.xml\]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces. Caused by: org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces.
                                                                                                                                                                                                                                                                                              February 18, 2013

                                                                                                                                                                                                                                                                                              APEX - Interactive report submission, set up UDP_MAIL ACLs

                                                                                                                                                                                                                                                                                              This post describes how to set up APEX to send emails in order to allow users to subscribe to interactive report: Configure APEX with the SMTP server, port and user credentials: Verify the existing ACLs: select * from dba_network_acl_privileges; Add the APEX user, APEX_040000 in my case, to the ACL list of allowed users to send email, or in a more general form, use UDP_MAIL: _begin dbms_network_acl_admin.add_privilege ( acl => ‘netacl.
                                                                                                                                                                                                                                                                                                February 15, 2013

                                                                                                                                                                                                                                                                                                Oracle - Function/Procedure call with output to console

                                                                                                                                                                                                                                                                                                Take the following Oracle function as example: sql>create or replace function “func_get_project_id” (p_project_code varchar2) return varchar2 is param_value varchar2(255); begin select project.id into param_value from project, costelement where project.costelementid = costelement.id and code = p_project_code; return param_value; exception when others then return sqlerrm; end func_get_project_id; 1- The first option is to call the function using a select: sql>select func_get_project_id(‘e/0900-04’) from dual; 2- The second option is to set the activate the server output:
                                                                                                                                                                                                                                                                                                  February 15, 2013

                                                                                                                                                                                                                                                                                                  Oracle - String empezando por (Starts With)

                                                                                                                                                                                                                                                                                                  El script/procedimiento abajo testa si una dada Organización es padre de una segunda pasada como argumento: declare dummy varchar2(500); f_unit varchar2(50); f_parent_unit varchar2(50); begin f_unit := ‘AA-ABC’; f_parent_unit := ‘AA-AB’; begin select * into dummy from dual where f_unit like f_parent_unit || ‘%’ and f_unit != f_parent_unit; dbms_output.put_line(‘DATA FOUND’); exception when others then dbms_output.put_line(‘NO DATA FOUND’); end; end; / En una forma aun mas general solo necesitéis: begin select * into dummy
                                                                                                                                                                                                                                                                                                    February 15, 2013

                                                                                                                                                                                                                                                                                                    Oracle - Field Starts With

                                                                                                                                                                                                                                                                                                    The following script/procedure tests if a given Organization is the father of a second: declare dummy varchar2(500); f_unit varchar2(50); f_parent_unit varchar2(50); begin f_unit := ‘AA-ABC’; f_parent_unit := ‘AA-AB’; begin select * into dummy from dual where f_unit like f_parent_unit || ‘%’ and f_unit != f_parent_unit; dbms_output.put_line(‘DATA FOUND’); exception when others then dbms_output.put_line(‘NO DATA FOUND’); end; end; / In a more general form you will only need_:_ begin select * into dummy
                                                                                                                                                                                                                                                                                                      February 15, 2013

                                                                                                                                                                                                                                                                                                      Oracle - Generate a Random number in Oracle between a interval

                                                                                                                                                                                                                                                                                                      You can easily generate a random number by: select dbms_random.normal from dual; Unfortunately, Oracle does not provide a solution if you require a random number between a interval of values. To do it you might wand to do: create or replace function RANDOM_NUMBER(lower IN int,higher IN int) return number is begin return trunc(abs(( GREATEST(lower, higher) - LEAST(lower, higher) + 1 ) * abs(dbms_random.value)) + LEAST(lower, higher)); end; My own solution involved a last steep:
                                                                                                                                                                                                                                                                                                        February 14, 2013

                                                                                                                                                                                                                                                                                                        Oracle - Renaming Table Columns in a Oracle External Table

                                                                                                                                                                                                                                                                                                        Unfortunately it is not possible to rename a Oracle external table, the solution is to drop the column and create it from scratch: alter table drop column alter table add
                                                                                                                                                                                                                                                                                                          March 20, 2012

                                                                                                                                                                                                                                                                                                          Oracle - Change next Job execution date

                                                                                                                                                                                                                                                                                                          List of existing jobs: select * from dba_jobs; Get the actual Oracle Job next execution date: select to_char( next_date, ‘YYYYMMDD:HH24MI’) from dba_jobs where job = 181; Test the next execution time: select to_char( trunc(SYSDATE) + ((16*60)+50)/1440 , ‘YYYYMMDD:HH24MI’) from dual; Execute the job update: exec DBMS_JOB.next_date ( <JOB_ID>, trunc(SYSDATE) + ((16*60)+50)/1440); Commit the changes: Commit;
                                                                                                                                                                                                                                                                                                            November 23, 2011

                                                                                                                                                                                                                                                                                                            Oracle - UTL_FILE.fopen ORA-29280 invalid directory path

                                                                                                                                                                                                                                                                                                            This helped me out, thank you! Regards, Paul. Anonymous - Nov 5, 2011This helped me out, thank you! Regards, Paul.
                                                                                                                                                                                                                                                                                                              May 3, 2011

                                                                                                                                                                                                                                                                                                              Oracle - UTL_FILE.fopen ORA-29280 invalid directory path

                                                                                                                                                                                                                                                                                                              Too user UTL_FILE.fopen first create a directory in ORACLE _ CREATE OR REPLACE DIRECTORY AS ‘/xxx/yyy/zzz’;_ Grant the permissions to it GRANT WRITE ON DIRECTORY TO APPS_NPI; Use the UTL_FILE.fopen in your PL/SQL block … _l_blob_len := DBMS_LOB.getlength (p_data); l_out_file := UTL_FILE.fopen ('', file_name, ‘wb’, 32767); WHILE l_pos < l_blob_len LOOP DBMS_LOB.READ (p_data, l_amount, l_pos, l_buffer); IF l_buffer IS NOT NULL THEN UTL_FILE.put_raw (l_out_file, l_buffer, TRUE); END IF; l_pos := l_pos + l_amount; END LOOP; UTL_FILE.
                                                                                                                                                                                                                                                                                                                May 3, 2011

                                                                                                                                                                                                                                                                                                                MS Access obtener fecha de hoy

                                                                                                                                                                                                                                                                                                                select Now() as Fecha_de_Hoy;
                                                                                                                                                                                                                                                                                                                  March 29, 2011

                                                                                                                                                                                                                                                                                                                  MS Access get today date

                                                                                                                                                                                                                                                                                                                  select Now() as Today_Date;
                                                                                                                                                                                                                                                                                                                    March 29, 2011

                                                                                                                                                                                                                                                                                                                    How to get the Computer Host Name

                                                                                                                                                                                                                                                                                                                    Today i had to do some configuration and had to instruct a user on how to send me his host-name: 1 - Click on Windows “Start” menu 2 - Right click on “My Computer” 3 - Click on “Properties” 4 - Click on the tab “Computer Name” 5 - The host-name is the text in the “Full computer name” label.
                                                                                                                                                                                                                                                                                                                      February 14, 2011

                                                                                                                                                                                                                                                                                                                      Ubuntu - Reduce the heat generated by yout laptop/netbook

                                                                                                                                                                                                                                                                                                                      Searching for ways to reduce the heat generated by my laptop i found a nice applet that helps to reduce the heat and save battery life. Depending on the CPU/Processor you have it may have a capability to set its own the cock speed according to the processor load. Mime for instance, a AMD X2, has 1600Mhz and 800Mhz, for surf at internet 800 Mhz is more then enough and extents bouth battery life and reduces the temperature of your computer.
                                                                                                                                                                                                                                                                                                                        January 24, 2011

                                                                                                                                                                                                                                                                                                                        Ubuntu - Save laptop/netbook battery life

                                                                                                                                                                                                                                                                                                                        Searching for ways to reduce the heat generated by my laptop i found a nice applet that helps to reduce the heat and save battery life. Depending on the CPU/Processor you have it may have a capability to set its own the cock speed according to the processor load. Mime for instance, a AMD X2, has 1600Mhz and 800Mhz, for surf at internet 800 Mhz is more then enough and extents bouth battery life and reduces the heat.
                                                                                                                                                                                                                                                                                                                          January 24, 2011

                                                                                                                                                                                                                                                                                                                          Improve blogger visual appearance

                                                                                                                                                                                                                                                                                                                          The best way to improve blogger visual appearance is by changing its template. To do so visit one on many web sites with free templates and download one of your liking. After you select and download your new template go to the “Desgn” folder and select “Edit HTML” On the same page as before select “Download Full Template”, this way you will have a backup of your old design if anything goes wrong.
                                                                                                                                                                                                                                                                                                                            January 21, 2011

                                                                                                                                                                                                                                                                                                                            Ubuntu - Install KDE, the alternative to Gnome

                                                                                                                                                                                                                                                                                                                            There are two major Desktop environments managers, Gnome and Kde, let’s not start argue about which one is the best, try and install both and judge for yourself. My ubuntu version came with Gnome for default, to install the Kde go to System Administration Synaptic Package Manager Search for “Kubuntu desktop” And choose “Apply” To start using KDE, log out and in the login screen choose as Display Manager te Kde, instead of Gnome.
                                                                                                                                                                                                                                                                                                                              January 16, 2011

                                                                                                                                                                                                                                                                                                                              mySql - Get N Top rows

                                                                                                                                                                                                                                                                                                                              In mySql to return the first N rows execute the following: select * from <table_name> limit N; Besides, mySql as a very useful feature, the “offset” in conjunction with “limit” may let define any interval that you desire, for instance to return rows 10 to 20: select * from <table_name> limit 10 offset 10;
                                                                                                                                                                                                                                                                                                                                January 2, 2011

                                                                                                                                                                                                                                                                                                                                mySql - Recuperar el ultimo ID insertado

                                                                                                                                                                                                                                                                                                                                Dado el escenario en el que han las tablas: Clientes y Clientes_Direcciones Para recuperar el identificador del último cliente insertado en la tabla Clientes que pueden hacer: select LAST_INSERT_ID() Mirando a la consulta vera que la misma no hace referencia a la tabla. Así que esta solución sólo funcionará si desea recuperar el identificador de la última fila insertada en todas la base de datos, así deberá tener en cuenta posibles problemas de concurrencia.
                                                                                                                                                                                                                                                                                                                                  January 1, 2011

                                                                                                                                                                                                                                                                                                                                  mySql - Get Last Inserted ID

                                                                                                                                                                                                                                                                                                                                  Given the scenario where you have the tables: Clients and Clients_Addresses In order to retrieve the id of the last client inserted in Clients you may do: select LAST_INSERT_ID() This will then retrieve the last inserted id, but looking at the query you will notices that you don’t have the table. So this solution will only work if you want to retrieve the id of the last inserted row in all your database, so be aware of concurrency problems.
                                                                                                                                                                                                                                                                                                                                    January 1, 2011

                                                                                                                                                                                                                                                                                                                                    JSP - Como importar clases

                                                                                                                                                                                                                                                                                                                                    Para importar una clase en una pagina JSP: <%@ page import="java.util.List;” %> hola , para importar mas que una clase usando una sintaxis corta: <%@ page import="java.util.List,java.util.ArrayList;” %> hola o usando una sintaxis mas sencilla de leer: <%@ page import="java.util.List” %> <%@ page import="java.util.ArrayList” %> hola
                                                                                                                                                                                                                                                                                                                                      December 30, 2010

                                                                                                                                                                                                                                                                                                                                      How to import classes in JSPs

                                                                                                                                                                                                                                                                                                                                      To import one class to your jsp file : <%@ page import="java.util.List;” %> hello To import more than one using a short sintaxe: <%@ page import="java.util.List,java.util.ArrayList;” %> hello To import more than one using in a more readable way: <%@ page import="java.util.List” %> <%@ page import="java.util.ArrayList” %> hello
                                                                                                                                                                                                                                                                                                                                        December 30, 2010

                                                                                                                                                                                                                                                                                                                                        SCJP - Books, Mocks and Links

                                                                                                                                                                                                                                                                                                                                        A few months ago i decided that my resume need something “more”, something to put me a bit forward against other CV’s. Personally a think, that if you Do want to study and make a course, better to get a certification on the final. As for books I’ve read SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055), this is a very good book and it comes with a browsable helping section with a theoretical resume and question/answering of every book section, you may download a free copy of this SCJP book.
                                                                                                                                                                                                                                                                                                                                          December 12, 2010

                                                                                                                                                                                                                                                                                                                                          Setting JDBC to use mySQL

                                                                                                                                                                                                                                                                                                                                          To use mySql in your java projects in eclipse first go to http://dev.mysql.com/downloads/connector/j/ and download the connector, for example: mysql-connector-java-5.1.13-bin.jar Finally copy it to your lib folder, for example: path-to-your-workspace/your-workspace-name/WebContent/WEB-INF/lib Go to the eclipse, right button on the project name and select “Refresh”. Pay atention, to use the new imported jar you have to add one of the following imports to your classes: import com.mysql.jdbc.Driver; import com.
                                                                                                                                                                                                                                                                                                                                            December 5, 2010

                                                                                                                                                                                                                                                                                                                                            MySQL Error Nr. 2002 Can't connect

                                                                                                                                                                                                                                                                                                                                            Hi, After installing, or at least was what it thought i did, mySql and configure mySql Admin i received the following error message : MySQL Error Nr. 2002 Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2) The solution was simple, the fact was that i only installed mySql client and so just went to synaptic and installed the mySql Server package.
                                                                                                                                                                                                                                                                                                                                              December 3, 2010

                                                                                                                                                                                                                                                                                                                                              Ebay Finding Api - Deploy WSDL

                                                                                                                                                                                                                                                                                                                                              This weekend i decided to do a little application to interact with Ebay. In its source it will use the Ebay Findig Api. My solution is based in Java(V1.6) though Ebay lets you use PHP, JSON etc. Besides Java i’m using. Ubunto Karmic 9.10 Eclipse Helios Tomcat 5.5 Apache To interact with Ebay one has to their WSDL and with it generate the classes. First, open a shell and execute :
                                                                                                                                                                                                                                                                                                                                                November 21, 2010

                                                                                                                                                                                                                                                                                                                                                Ubuntu - All permissions in Nautilus

                                                                                                                                                                                                                                                                                                                                                Sometimes while using Ubuntu as a user normal user (which is the way you should normally work in Linux, and leave root account for special purposes) you may want to save to a directory where you don’t have permission. To use/login nautilus as super user (root): Open a console or shell Write “sudo nautilis” Enter Super user password
                                                                                                                                                                                                                                                                                                                                                  November 21, 2010

                                                                                                                                                                                                                                                                                                                                                  Ubuntu - Missing NetWork Manager icon

                                                                                                                                                                                                                                                                                                                                                  By accident y removed the Network Manager icon from them panel bar of my Ubuntu. What was actually missing was the nm-applet icon, to recover it do the following: Right click on the panel bar Select “Add to panel…”  Network Manager icon missing - Right click in panel  Select “Notification area” Network Manager icon missing - Select “Notification area”
                                                                                                                                                                                                                                                                                                                                                    November 20, 2010

                                                                                                                                                                                                                                                                                                                                                    Oracle - Caracteres de Escape

                                                                                                                                                                                                                                                                                                                                                    Para ejecutar una instrucción con caracteres especiales es necesario usar caracteres de escape. La siguiente una instrucción de Update hará el replace de “&” por "” update set = replace( , CHR(38), ‘'); La siguiente una instrucción de Insert de “TESTE ' TESTE’: _insert into _ ( f_description) values( ‘TESTE’ || CHR(39) || ‘TESTE’); Un metodo mas comodo, que no necesita definicion de los caracteres de escape, es: set define off;
                                                                                                                                                                                                                                                                                                                                                      November 12, 2010

                                                                                                                                                                                                                                                                                                                                                      FTP Bajar más que un fichero a la vez

                                                                                                                                                                                                                                                                                                                                                      Para bajar mas que un fichero a la vez través una conexión por FTP es necesario logear en el servidor y luego usar el mando “mget” con los parámetros adecuados. Por ejemplo: (para todos los ficheros html) mget *.htm (para todos los ficheros con la palabra “product”) mget product*.* Saludos.
                                                                                                                                                                                                                                                                                                                                                        September 16, 2010

                                                                                                                                                                                                                                                                                                                                                        FTP Download more than one file at time

                                                                                                                                                                                                                                                                                                                                                        Hi, yes it is obvious but still i post it :) For download more than one file at a time with a FTP connection first log on, go to the directory in question and use (for all html files) mget *.htm (for all productXXX.htm files) mget product*.htm Bye.
                                                                                                                                                                                                                                                                                                                                                          September 16, 2010

                                                                                                                                                                                                                                                                                                                                                          Oracle - Creaccion de indices

                                                                                                                                                                                                                                                                                                                                                          La creación de un indice en una tabla es la solución para aumentar el tiempo de respuesta a una consulta, desde cuando se haga sobre el campo indexado. Para crearlo necesitamos : CREATE INDEX <nombre_indice> on <nombre_de_la_tabla>(<nombre_del_campo>);
                                                                                                                                                                                                                                                                                                                                                            September 2, 2010

                                                                                                                                                                                                                                                                                                                                                            Oracle - Index creation

                                                                                                                                                                                                                                                                                                                                                            Create indexes on a table to optimize data queries, always when the query is made using the indexed field CREATE INDEX <index_name> on <table_name>(<table_field_name>);
                                                                                                                                                                                                                                                                                                                                                              September 2, 2010

                                                                                                                                                                                                                                                                                                                                                              Oracle - Alter Table, adicionar clave primaria

                                                                                                                                                                                                                                                                                                                                                              La llave primaria de una tabla es una regla que especifica que el valor del campo de la tabla identifica de modo único su linea en la tabla, es decir, el valor sirve como llave para el acceso a una linea en la tabla. Como consecuencia estos valores no se puede repetir ni ser nulos en estos campos. Es posible especificar mas de un campo como llave primaria Abajo, se indica un script para definir una llave primaria en una tabla ya existente.
                                                                                                                                                                                                                                                                                                                                                                September 2, 2010

                                                                                                                                                                                                                                                                                                                                                                Oracle - Alter Table, add primary key constraint

                                                                                                                                                                                                                                                                                                                                                                The primary key its a constraint that specifies that the value of the field fully identifies the row in the table, that is, the value is the “key” to he table. And so this constraint will not permit duplicate or null values int that field. Its possible to specify more than one field as primary key. Next, there’s a script for defining a primary key in a already existing table.
                                                                                                                                                                                                                                                                                                                                                                  September 2, 2010

                                                                                                                                                                                                                                                                                                                                                                  Oracle - Alter Table, cambiar nombre de una columna

                                                                                                                                                                                                                                                                                                                                                                  Buen dato Unknown - Feb 6, 2014Buen dato Buen dato Gracias!
                                                                                                                                                                                                                                                                                                                                                                    September 2, 2010

                                                                                                                                                                                                                                                                                                                                                                    Oracle - Alter Table, cambiar nombre de una columna

                                                                                                                                                                                                                                                                                                                                                                    Script Oracle “Alter Table” para cambiar el nombre de una columna: alter table <nombre_de_la_tabla> rename column <nombre_antiguo_del_campo> to<nuevo_nombre_del_campo>;
                                                                                                                                                                                                                                                                                                                                                                      September 2, 2010

                                                                                                                                                                                                                                                                                                                                                                      Oracle - Alter Table, change column name

                                                                                                                                                                                                                                                                                                                                                                      The following script changes the name of an already existing field in a table alter table rename column to
                                                                                                                                                                                                                                                                                                                                                                        September 2, 2010

                                                                                                                                                                                                                                                                                                                                                                        Ubuntu - No application bars

                                                                                                                                                                                                                                                                                                                                                                        After performing a system cleanup with the “janitor"and installing a theme manager “Art manager” the application simply disappear (the one with the minimise restore and maximise buttons). The solution for it was installing/reinstalling some packages from synaptic : search using “Windows manager” select: metacity - A lightweight GTK2 based Window Manager libmetacity0 - library of lightweight GTK2 based Window Manager metacity-common - Shared files of lightweight GTK2 based Window Manager
                                                                                                                                                                                                                                                                                                                                                                          August 22, 2010

                                                                                                                                                                                                                                                                                                                                                                          Apache & Tomcat 404, 503 custom error page

                                                                                                                                                                                                                                                                                                                                                                          Configure Tomcat and Apache to show custom 404 and 503 error pages. This should cover the cases when the either the page and/or application is not available. Configure Apache httpd.conf configuration file in order to show a custom 404 and/or 503 error page: # to handle 404 page not found ErrorDocument 404 /404.htm # to handle 503 application not available ErrorDocument 503 /503.htm Note(s): The file 404 error page name can be anything you want and its path is relative to the applications DocumentRoot Handling the 404 error by apache can be redundant, if the application is running then the 404 is catch and handled first by tomcat Configure Tomcat web.
                                                                                                                                                                                                                                                                                                                                                                            August 17, 2010

                                                                                                                                                                                                                                                                                                                                                                            Forcing Visits to use SSL

                                                                                                                                                                                                                                                                                                                                                                            Intro Doesn’t matter whether it’s a CakePHP app for a client, your own personal CMS, or any other web based application. If your passing around passwords or other sensitive info you should really implement SSL. SSL provides 2 main perks to your visitors. First it encrypts all communication that flies across the web. This prevents curious or devious billies from getting your secrets. Secondly it ensures to the user that your server is in fact who it claims, and not a nasty ‘man in the middle” attack.
                                                                                                                                                                                                                                                                                                                                                                              January 1, 2009

                                                                                                                                                                                                                                                                                                                                                                              Pipeline steps Data extraction from sources; databases, RESTAPIS, S3, datalakes, etc Data ingestion Processing Data enrichment Data cleaning Data transformation Data anonymization Sink; data store Pipeline design steps Determine the business value What are our objectives for this data pipeline? What use cases will the data pipeline serve (reporting, analytics, machine learning)? Choose the data sources What are all the potential sources of data?
                                                                                                                                                                                                                                                                                                                                                                                January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                Fix 404 - page not found routing errors in netlify Angular apps

                                                                                                                                                                                                                                                                                                                                                                                Problem 404 - page not found routing errors in netlify Angular apps Solution In Angular 6 add a _redirects file under src folder add the following contents: /* /index.html 200 Open angular.json and append the assets section with "src/_redirects", for example: "projects": { "ng-universal-demo": { "root": "", "projectType": "application", "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/browser", "index": "src/index.html", "main": "src/main.ts", "tsConfig": "src/tsconfig.app.json", "polyfills": "src/polyfills.
                                                                                                                                                                                                                                                                                                                                                                                  January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                  Leetcode 1239 "Maximum Length of a Concatenated String with Unique Characters"

                                                                                                                                                                                                                                                                                                                                                                                  1239. Maximum Length of a Concatenated String with Unique Characters Result Runtime: 39 ms, faster than 23.63% of Java online submissions for Maximum Length of a Concatenated String with Unique Characters. Memory Usage: 38.9 MB, less than 38.68% of Java online submissions for Maximum Length of a Concatenated String with Unique Characters. class Solution { public int maxLength(List<String> arr) { return maxLengthRec(arr, 0, ""); } public int maxLengthRec(List<String> arr, int index, String word) { if(index > arr.
                                                                                                                                                                                                                                                                                                                                                                                    January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                    Leetcode 1306 "Jump Game III"

                                                                                                                                                                                                                                                                                                                                                                                    1306. Jump Game III Result Runtime: 2 ms, faster than 79.51% of Java online submissions for Jump Game III. Memory Usage: 52.2 MB, less than 24.27% of Java online submissions for Jump Game III. class Solution { int[] visit; public boolean canReach(int[] arr, int start) { visit = new int[arr.length]; return canReachRec(arr, start, visit); } public boolean canReachRec(int[] arr, int start, int[] visit) { if(start < 0) return false; if(start >= arr.
                                                                                                                                                                                                                                                                                                                                                                                      January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                      Leetcode 152. Maximum Product Subarray

                                                                                                                                                                                                                                                                                                                                                                                      152. Maximum Product Subarray Result Runtime: 233 ms, faster than 5.89% of Java online submissions for Maximum Product Subarray. Memory Usage: 42 MB, less than 29.04% of Java online submissions for Maximum Product Subarray. class Solution { public int maxProduct(int[] nums) { int total = Integer.MIN_VALUE; int l = 0; int r = l; while(l < nums.length) { int thisTotal = 1; while(r < nums.length) { thisTotal = thisTotal * nums[r]; if(thisTotal > total) { total = thisTotal; } r = r + 1; } l = l + 1; r = l; } return total; } }
                                                                                                                                                                                                                                                                                                                                                                                        January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                        Leetcode 1701 "Avarage Waiting Time"

                                                                                                                                                                                                                                                                                                                                                                                        1701. Average Waiting Time Result Runtime: 3 ms, faster than 52.34% of Java online submissions for Average Waiting Time. Memory Usage: 90.1 MB, less than 32.94% of Java online submissions for Average Waiting Time. class Solution { public double averageWaitingTime(int[][] customers) { int finishedAtTime = 1; double total = 0; for(int i=0; i<customers.length; i++) { finishedAtTime = Math.max(finishedAtTime, customers[i][0]) + customers[i][1]; total = total + (finishedAtTime - customers[i][0]); } return total/customers.
                                                                                                                                                                                                                                                                                                                                                                                          January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                          Leetcode 21. Merge Two Sorted Lists"

                                                                                                                                                                                                                                                                                                                                                                                          21. Merge Two Sorted Lists Runtime: 1 ms, faster than 81.82% of Java online submissions for Merge Two Sorted Lists. Memory Usage: 43 MB, less than 55.19% of Java online submissions for Merge Two Sorted Lists. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.
                                                                                                                                                                                                                                                                                                                                                                                            January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                            Leetcode 242 "Valid Anagram"

                                                                                                                                                                                                                                                                                                                                                                                            242 Valid Anagram Runtime: 5 ms, faster than 49.66% of Java online submissions for Valid Anagram. Memory Usage: 39.5 MB, less than 57.91% of Java online submissions for Valid Anagram. class Solution { public boolean isAnagram(String s, String t) { int[] arr1 = new int[27]; int[] arr2 = new int[27]; if(s.length() != t.length()) return false; System.out.println((int)s.charAt(0)); for(int i=0; i<s.length(); i++) { arr1[(int)s.charAt(i) -97] = arr1[(int)s.charAt(i) -97] + 1; } for(int i=0; i<t.
                                                                                                                                                                                                                                                                                                                                                                                              January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                              Leetcode 246 "Strobogrammatic Number"

                                                                                                                                                                                                                                                                                                                                                                                              246. Strobogrammatic Number Result Runtime: 0 ms, faster than 100.00% of Java online submissions for Strobogrammatic Number. Memory Usage: 36.5 MB, less than 95.52% of Java online submissions for Strobogrammatic Number. class Solution { public boolean isStrobogrammatic(String num) { int left = 0; int right = num.length() - 1; while(left <= right) { if(num.charAt(left) == '0' && num.charAt(right) == '0') { left++; right--; continue; } if(num.charAt(left) == '1' && num.charAt(right) == '1') { left++; right--; continue; } if(num.
                                                                                                                                                                                                                                                                                                                                                                                                January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                                Leetcode 347 "Top K Frequent elements"

                                                                                                                                                                                                                                                                                                                                                                                                347. Top K Frequent elements Result Runtime: 10 ms, faster than 69.45% of Java online submissions for Top K Frequent Elements. Memory Usage: 41.8 MB, less than 46.78% of Java online submissions for Top K Frequent Elements. class Solution { public int[] topKFrequent(int[] nums, int k) { int ans[]= new int[k]; // (a,b)-> (b[1] - a[1]) is the ordering we want to apply on the queue // the ordering is applyed over the second cell of the array which corresponds to the key frequency PriorityQueue<int[]> queue = new PriorityQueue<>((a,b)-> (b[1] - a[1])); Map<Integer, Integer> map = new HashMap<>(); for(int i=0; i<nums.
                                                                                                                                                                                                                                                                                                                                                                                                  January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                                  Leetcode 392. Is Subsequence"

                                                                                                                                                                                                                                                                                                                                                                                                  1239. Maximum Length of a Concatenated String with Unique Characters Result Runtime: 6 ms, faster than 21.93% of Java online submissions for Is Subsequence. Memory Usage: 41.8 MB, less than 63.47% of Java online submissions for Is Subsequence. class Solution { public boolean isSubsequence(String s, String t) { if(s.length() == 0) return true; int index = 0; for(int i=0; i<t.length(); i++) { if(s.charAt(index) == t.charAt(i)) { index++; } if(index == s.
                                                                                                                                                                                                                                                                                                                                                                                                    January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                                    Leetcode 416 "Partition equal subset sum"

                                                                                                                                                                                                                                                                                                                                                                                                    416. Partition Equal Subset Sum Result Runtime: 51 ms, faster than 39.36% of Java online submissions for Partition Equal Subset Sum. Memory Usage: 115.6 MB, less than 5.01% of Java online submissions for Partition Equal Subset Sum. class Solution { Boolean[][] arr; public boolean canPartition(int[] nums) { int total = 0; for(int i=0; i<nums.length; i++) { total = total + nums[i]; } if(total % 2 == 1) return false; arr = new Boolean[total+1][nums.
                                                                                                                                                                                                                                                                                                                                                                                                      January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                                      Leetcode 419 "Battleships in a Board"

                                                                                                                                                                                                                                                                                                                                                                                                      419. Battleships in a Board Result Runtime: 1 ms, faster than 38.31% of Java online submissions for Battleships in a Board. Memory Usage: 38.6 MB, less than 42.02% of Java online submissions for Battleships in a Board. class Solution { public int countBattleships(char[][] board) { int count = 0; int[][] visited = new int[board.length][board[0].length]; for(int i=0; i<board.length; i++) { for(int j=0; j<board[0].length; j++) { if(board[i][j] == 'X') { count = count + (countBattleshipsRec(board, j, i, visited) > 0 ?
                                                                                                                                                                                                                                                                                                                                                                                                        January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                                        Leetcode 45 "Jump Game II"

                                                                                                                                                                                                                                                                                                                                                                                                        45. Jump Game II Result Runtime: 0 ms, faster than 100.00% of Java online submissions for Jump Game II. Memory Usage: 36.2 MB, less than 88.57% of Java online submissions for Jump Game II. class Solution { int[] arr; public int jump(int[] nums) { arr = new int[nums.length]; if(nums.length == 0) return 0; if(nums.length == 1) return 0; return jumpRec(nums, 0); } public int jumpRec(int[] nums, int index) { // arr can have either: // the minimun number of jumps // the initialized value // or an out out range value // NOTE: by using 1001 (check the problem description), instead of Integer.
                                                                                                                                                                                                                                                                                                                                                                                                          January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                                          Leetcode 46 "Permutations"

                                                                                                                                                                                                                                                                                                                                                                                                          46. Permutataions Result Runtime: 1 ms, faster than 92.78% of Java online submissions for Permutations. Memory Usage: 39.1 MB, less than 71.12% of Java online submissions for Permutations. class Solution { List<List<Integer>> solution = new ArrayList<>(); public List<List<Integer>> permute(int[] nums) { List<Integer> thisRun = new ArrayList<>(); permuteRec(nums, 0, thisRun, new int[nums.length]); return solution; } public void permuteRec(int[] nums, int index, List<Integer> run, int[] visited) { if(index >= nums.length) { solution.add(run); return; } for(int i=0; i<nums.
                                                                                                                                                                                                                                                                                                                                                                                                            January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                                            Leetcode 5 "Longest Palindromic Substring"

                                                                                                                                                                                                                                                                                                                                                                                                            5. Longest Palindromic Substring Result LTE class Solution { int[][] arr; String result = ""; public String longestPalindrome(String s) { arr = new int[s.length()+1][s.length()+1]; for(int i=0; i<s.length(); i++) { longestPalindromeAux(s, i, i+1); } return result; } public int longestPalindromeAux(String s, int from, int to) { if(to > s.length()) { return -1; } if(from < 0) { return -1; } if(arr[from][to] != 0) { return arr[from][to]; } String thisString = s.substring(from, to); if(!
                                                                                                                                                                                                                                                                                                                                                                                                              January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                                              Leetcode 739 "Daily Temperatures"

                                                                                                                                                                                                                                                                                                                                                                                                              739. Daily Temperatures Result Runtime: 1001 ms, faster than 7.45% of Java online submissions for Daily Temperatures. Memory Usage: 47.1 MB, less than 66.06% of Java online submissions for Daily Temperatures. class Solution { public int[] dailyTemperatures(int[] temperatures) { for(int i=0; i<temperatures.length; i++) { int count = 0; boolean flag = false; for(int j=i; j<temperatures.length; j++) { if(temperatures[j] <= temperatures[i]) { count = count + 1; } else { flag = true; break; } } temperatures[i] = flag ?
                                                                                                                                                                                                                                                                                                                                                                                                                January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                                                Leetcode 797 "All Paths From Source to Target"

                                                                                                                                                                                                                                                                                                                                                                                                                797. All Paths From Source to Target Result Runtime: 5 ms, faster than 17.57% of Java online submissions for All Paths From Source to Target. Memory Usage: 40.9 MB, less than 26.23% of Java online submissions for All Paths From Source to Target. class Solution { public List<List<Integer>> allPathsSourceTarget(int[][] graph) { List<List<Integer>> solution = new ArrayList<>(); int[][] arr = new int[graph.length+1][graph.length+1]; for(int i=0; i<graph.length; i++) { for(int j=0; j<graph[i].length; j++) { arr[i][graph[i][j]] = 1; } } Stack<List<Integer>> stack = new Stack<>(); List<Integer> list = new ArrayList<>(); list.
                                                                                                                                                                                                                                                                                                                                                                                                                  January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                                                  Reflected XSS All clients - security issue

                                                                                                                                                                                                                                                                                                                                                                                                                  Problem: Reflected XSS All Clients Solution Quick fix in java: value = StringEscapeUtils.escapeHtml(value); For a more in-deep solution i recommend checking: https://github.com/mehditahmasebi/spring/tree/master/spring-xss-filter
                                                                                                                                                                                                                                                                                                                                                                                                                    January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                                                    Spark optimization technics

                                                                                                                                                                                                                                                                                                                                                                                                                    Use broadcast joins whenever possible When joining a large with a small table broadcast the contents of the smaller table to the individual executors for local processing resut = large.join(broadcast(small)) Tweak correct value via spark.sql.autoBroadcastJoinThreshold variable, which defaults to 10mb. Be mindful of serialization methods Be mindful of the memory size of your encoded objects impact in your join and shuffle operations: Java serializers are very object centric, lots of GC operations occuring with these.
                                                                                                                                                                                                                                                                                                                                                                                                                      January 1, 0001

                                                                                                                                                                                                                                                                                                                                                                                                                      Subscribe Firehose to SNS with Terraform

                                                                                                                                                                                                                                                                                                                                                                                                                      Further reading: Terraform documentation Cloud formation example In sns/main.tf set the Firehose SNS subscription resource "aws_sns_topic_subscription" "report_target" { topic_arn = aws_sns_topic.subscription_calamiteit_events.arn endpoint = var.aws_firehose_delivery_stream.arn protocol = "firehose" subscription_role_arn = aws_iam_role.iam_for_sns_firehose.arn } Now the tricky part is setting subscription_role_arn. This role needs both rights to assume role under SNS and a policy that allows it to write into Firehose. In sns/main.tf create an iam role as mentioned above: resource "aws_iam_role" "iam_for_sns_firehose" { name = "iam_role_${aws_sns_topic.
                                                                                                                                                                                                                                                                                                                                                                                                                        January 1, 0001