Skip to main content

Posts

Showing posts from January 14, 2012

Replacing special characters like dots in javascript

I have a search query from the user and I want to process it before applying to browser. since I'm using SEO with htaccess and the search url looks like this : /search/[user query] I should do something to prevent user from doing naughty things.. :) Like searching ../include/conf.php which will result in giving away my configuration file. I want to process the query like removing spaces, removing dots(which will cause problems), commas,etc. var q = document.getElementById('q').value; var q = q.replace(/ /gi,"+"); var q = q.replace(/../gi,""); document.location='search/'+q; the first replace works just fine but the second one messes with my query.. any solution to replacing this risky characters safely?

Animated sliding divs on click button jQuery

Im trying to write a simple script that slides the next 'slide' div in on a button click, I have 3 divs all inline, left alligned. theyre all set to a width, on 'next' button click id like the next slide to slide in, ive made the following fiddle only I cant seem to get it working... Can anybody see where im going wrong? http://jsfiddle.net/x2qk7/ Thanks

Need to add 45+ points to a google map

trying to add 45 different points to a map, but I just get OVER_QUERY_LIMIT returned, and no map. I am getting locations via a string search, then assigning the returned LatLng object to a new google Marker object String Search var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': x}, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { var result = results[0].geometry.location; return result; } else { alert("Geocode was not successful for the following reason: " + status); } });

jQuery function is not working as i planned, DIVs just disappear on click

I have a script here, and it works amazing, except for one small detail. It basically runs as click function that fades in and out certain DIVs on the click of a link. The problem is, however, that when you click ANYWHERE on the page, it removes the DIV and leaves an empty content area until you click one of the links. Obviously this is a problem. I can't use the exact code I'm using for NDA reasons, but here is same setup I am using with just some plain text in the divs. Just click the links to see the functionality, and then click anywhere else on the page (in the div, in the white space, whatever) and watch the div just disappear. I'm know that that is what the javascript is calling, but I don't know how to disable the click in the divs so this doesn't happen. Also, how to do that so it doesn't disable the link that are within that div. Any help is greatly appreciated. This website is a life saver. This is the original code I got off of this site

running Javascript from an external site in C# application

I'm think about building a Silverlight C# Windows phone application for buses in Israel, and I have a basic question(or is it?). The bus site which I want to get the data from uses Javascript. You need to type in the city you want to get to, and it returns the list of stations in that city. I'd like to somehow "get" this page, type the code in, and get the results - all in C#. I'm pretty much lost on where to start from. How do I "get" the site code? how do I run the Javascript action that returns the stations, from within C#? is that even possible?

can javascript-based charting component be integrated into Flex/AS3 web app?

I'm relatively new to flex, and I'm developing a web app that needs to plot relatively large data sets (e.g. 20,000 pts divided among 8 separate curves) in a line chart. Flex built-in chart components render too slowly. Two part question: Would javascript line chart render faster than Flex line chart? If so, is it possible to use a javascript-based charting solution instead of flex component, within the Flex application? Or, is this an impractical (or crazy) idea? Anyone doing this out there? How simple or complex is it? I'm hoping it's relatively easy to integrate a pre-developed solution like EST JS, HighCharts, etc. to simplify development.

Is there a way to automatically control orphaned words in an HTML document?

I was wondering if there's a way to automatically control orphaned words in an HTML file, possibly by using CSS and/or Javascript (or something else, if anyone has an alternative suggestion). By 'orphaned words', I mean singular words that appear on a new line at the end of a paragraph. For example: "This paragraph ends with an undesirable orphaned word." Instead, it would be preferable to have the paragraph break as follows: "This paragraph no longer ends with an undesirable orphaned word." While I know that I could manually correct this by placing an HTML non-breaking space (&nbsp) between the final two words, I'm wondering if there's a way to automate the process, since manual adjustments like this can quickly become tedious for large blocks of text across multiple files. Incidentally, the CSS2 properties "orphans:" (and "widows:") only apply to entire lines of text, and even then only for the printing of HTM

Trying to get value from textbox in column in table

I dynamically created a table with three columns. <tr> <td>1</td> <td>SegName</td> <td><input type='text' /></td> </tr> I'm trying to write a function that goes through each row and grabs the value in that will be in the textbox. Javascript: $("#codeSegmentBody").children().eq(x).children().eq(2).val(); The code brings brings up undefined when I do val(), but if I do html it'll grab the html of the textbox. How can I get this to bring me the value?

Downloading file is corrupted - header

I have be trying to figure out what is wrong but every time i download the image and try to open it, it says that the file is corrupt. $h is the path which is pulled from the database, the $h displays the image on the page successfully but I dont get why it wont download. Any ideas ?? header("Pragma: public"); // required header("Cache-Control: private",false); // required for certain browsers header('Content-Length: '. filesize("../".$h)); header('Content-Type: application/octet-stream'); header('Content-Disposition: inline; filename="'.md5($h).$ext.'"'); header('Content-Transfer-Encoding:binary'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); readfile("../".$h);

Calling a Class function without using $this->function_name() &mdash; PHP --

So I have this class: class A{ public function do_a(){ return 'a_done';}; public function do_b(){ return 'b_done';}; } So I require the php file and create an instance of the class: require_once("A_class.php"); $System = new A(); require_once("user_calls.php"); //here I import the user file with the function calls. user_calls.php contents: echo 'this was the result of '.$System->do_a(); echo 'this was the result of '.$System->do_b(); So, that does work, but I don't want the user to have to use $System->do_a(); , but only do_a(); . Any solutions? EDIT: I also want to limit the functions the user could call in the user_calls.php file, to basic native php functions and those in class A.

Amazon EC2 Linux RH cannt connect from php script to RDS MYSQL

I have an amazon EC2 instance (redhat linux ) and a RDS (mysql 5.5 ). After stop /start EC2 instance. EC2's ip was changed and cannt connect RDS anymore. I can successfully connect RDS instance from command line. However, it is unable to connect from php script and give me this warning. PHP Warning: mysqli::mysqli(): (HY000/2003): Can't connect to MySQL server on 'applicantdb.xr3x2xcale.eu-west-1.rds' (13) It is working fine from my localhost and I can connect to localhost. It is really annoying and if somebody knows the solution. Please help me and I do really appreciate it.

Can we capture the same browser closing event without using &ldquo;onunload&rdquo;

Actually using the window.close , we can control whether browser is closed or not, but it works only for pop-ups created by the browser. So, are there any ways to listen to the closing event of the browser without using onunload ? Because we don't want things to be executed when back , refresh or forward actions occur. Please also reply if you know specifics regarding Firefox. Thanks in advance!

php, ajax authentication on external domain

Suppose I have domain-a.com (A) and domain-b.com (B) I'd like to be able to share php sessions between the two domains unifying logins in a way that once the user is logged to A is automatically logged into B and vice versa. Now, the problem I'm facing is that even if I managed to have the browser talk via ajax to an external domain via the Access-Control-Allow-Origin header it won't set cookies (please don't tell me "you can't set/get cookies for another domain, this is not the problem") here's the flow: A sends credentials to B if credentials are OK -B answers with the SESSID made in order to be consistent with the user credentials (so that it can be generated both ways ie: login from A or login from B), this will be used later to share the session created on B -At the same time I'd like that B could write cookies for its domain, but so far I wasn't able. What I need here is very simple, once that the credentials from A are

Apostrophe issue when inserting into MySQL

I have a script where I submit some fields that get entered into a MySQL database when I submit it now it goes through successfully but never gets inserted into the database if one of the fields has an apostrophe. What can I modify to get this to work? if ($_POST) { $name = trim($_POST['your_name']); $email = trim($_POST['your_email']); $answers = $_POST['answers']; $i = 0; foreach ($answers as $a) { if (trim($a)) $i++; } if ($name && $email && $i >= 40) { $array = array(); $q = mysql_query("select * from fields"); while($f = mysql_fetch_array($q)) $array[$f['label']] = $answers[$f['ID']]; $array = serialize($array); $time = time(); $ip = $_SERVER['REMOTE_ADDR']; $token = md5($time); $result = mysql_query("insert into data (submit_name, submit_email, submit_data, submit_confirm, submit_time, submit_ip, submit_token) values ('$name', 

Reusing PHP function to reduce code duplication

I am pulling in weather data from a Yahoo weather RSS feed for both London and New York. I'm trying to reduce code duplication by reusing a PHP file which contains functions for pulling in the weather data. Below is the function I am calling - get_current_weather_data() . This function goes off to various other functions such at the get_city() and get_temperature() functions. <?php function get_current_weather_data() { // Get XML data from source include_once 'index.php'; $feed = file_get_contents(if (isset($sourceFeed)) { echo $sourceFeed; }); // Check to ensure the feed exists if (!$feed) { die('Weather not found! Check feed URL'); } $xml = new SimpleXmlElement($feed); $weather = get_city($xml); $weather = get_temperature($xml); $weather = get_conditions($xml); $weather = get_icon($xml); return $weather; } In my index.php I set the URL for the RSS feed as the variable called $sourceFeed . <?php $tabTitle = ' | Home'; $pageIntroduction

Image upload takes previous temp file to upload in php

Here i have the problem with uploading image in php. The problem is that when first time i upload the image file it works fine. But when i am trying to upload the file second time without page refresh it takes first image name and upload it. Anybody can tell me what the problem and how can it resolve ? $name = $_FILES['ImageFile']['name']; $size = $_FILES['ImageFile']['size']; $tmp = $_FILES['ImageFile']['tmp_name']; $path = "public/www/uploads/"; $valid_formats = array("jpg", "png", "gif", "bmp"); $response = ''; if(strlen($name)) { list($txt, $ext) = explode(".", $name); if(in_array($ext,$valid_formats)) { if($size<(1024*1024)) { $actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext; if(move_uploaded_file($t

Getting the HTML source code of an .swf URI

I was wondering whether one could get the HTML source code from an .swf URI? For instance a web page such as: http://media.flixfacts.com/360view/acer_uk/002/acer_uk-002-en.swf When I use curl to scrape this page it brings back the swf source not the html source. Any ideas?

PHP is slower than it should be

Originally, I posted this on ServerFault ... but perhaps it is more of a PHP lingual question. I have a server with Dual Xeon Quad Core L5420 running at 2.5GHz. I've been optimizing my server, and have come to my final bottleneck: PHP. My very simple PHP script: ./test.php <?php print_r(posix_getpwuid(posix_getuid())); My not-so-scientific-because-they-don't-pay-attention-to-thread-locking-but-scientific-enough-to-give-me-a-reasonable-multithreaded-requests-per-second-result scripts: ./benchmark-php #!/bin/bash if [ -z $1 ]; then LIMIT=10 else LIMIT=$1 fi if [ -z $2 ]; then SCRIPT="index.php" else SCRIPT=$2 fi START=$(date +%s.%N) COUNT=0 while (( $COUNT < $LIMIT )) do php $SCRIPT > /dev/null COUNT=$(echo "$COUNT + 1" | bc) done END=$(date +%s.%N) DIFF=$(echo "$END - $START" | bc) REQS_PER_SEC=$(echo "scale=2; $COUNT / $DIFF" | bc) echo $REQS_PER_SEC ./really-benchmark-php #!/bin/bash if [ -z $1 ]; then

php file_get_contents return always FALSE on https://graph.facebook.com/oauth/access_token? request

Since some weeks the facebook connection to my application doesn't work. My dialog url is this one : $dialogUrl = "https://www.facebook.com/dialog/oauth?client_id=".$my_facebook_app_id."&redirect_uri=".urlencode($my_return_url)."&state=".$my_state."&scope=read_stream,offline_access,publish_stream"; Connection dialog accept my connection and return to $my_return_url with ?state=XXX&code=YYY When I call the file_get_contents() method on this url with $code corresponding to the code in query string : $tokenurl = "https://graph.facebook.com/oauth/access_token?client_id=".$my_facebook_app_id."&redirect_uri=".urlencode($my_return_url)."&client_secret=".$facebook_app_secret."&code=".$code; I have always a FALSE result ! A few month ago it was returning the access_token, but now it always return false on my website. Note than if I load the $tokenUrl in a navigator

replace function js to php

I am trying to change a js program to php. there is a replace function like $t = t.replace(/B/g, "b"); if i change this to php as $t = str_ireplace(/B/g, "b",$t); it shows error about "unexpecting '/' ". how to solve this.

Login Script working local but not on live environment

I seem to have a problem with a login script, it works on a local php dev box, but not on my live environment, i'm assuming i'm missing something can anyone advise further? <?php $user = $_POST["swtorun"]; $pass = $_POST["swtorpw"]; // Generate hash $enc_pwd = hash('sha256', $pass); // Connect to DataBase include('../../settings.php'); $conn = mysql_connect($host,$username,$password); $db = mysql_select_db($database, $conn); // mySql Query users $sql = "SELECT * FROM `users` WHERE username='$user' and password='$enc_pwd'"; $result = mysql_query($sql, $conn); $count = mysql_num_rows($result); // number of results (should be 1) if($count==1){ // initiate session session_start(); $_SESSION['logged'] = "1"; echo "you are now logged in, return to the <a href=\"../../index.php\">index</a>"; } else { echo "Wrong Username or Password"; } ?>

Cloud Apps vs Web Apps

I have 2 questions: First, what's the difference between a web application and a cloud application? Are there any differences at all? If I'm developing a web application (a site with many interactive features), can I call it a cloud application? Second, if there's a difference between a cloud and web application, what languages can cloud applications be developed in? Would a scripting language like PHP be useful for that? Thanks. UPDATE: I have watched the video in one of the answers, but I am still a little confused. Taking Google Docs as a example, all I see is a user interface that can be created with html and JS, along with a server script, and the data is stored in a database, which is basically the same thing a web application does. Or is it different? Thanks

Get geo location from RSS feed

I am working on RSS feed and I want to display it on google map, for that I need geo location (latitude and longitude). Is there any way to get geolocation from RSS feed. Please find below example link and it output the results as below: http://news.google.com/news?ned=us&topic=h&output=rss [0] => Array([ title] => With video: Marine urination outrage not stopping Afghan peace talk moves - Detroit Free Press [link] => http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNGJ6-pSyuoJH43Om0IZipU0bYSCZg&url=http://www.freep.com/article/20120113/NEWS07/120113024/With-video-Marine-urination-outrage-not-stopping-Afghan-peace-talk-moves [description] =>With video: Marine urination outrage not stopping Afghan peace talk moves [guid] => tag:news.google.com,2005:cluster=17593988265025 [pubDate] => Fri, 13 Jan 2012 16:14:32 GMT ) Thanks

PDO_OCI: could not find driver

Today my problem is connected with PDO, OCI8 and PDO_OCI. But from the beginning. I'm using Ubuntu 11.10 and PHP version: 5.3.8-1ubuntu3. I have installed Oracle 10g Express, configured it and it works fine. The next step I had to do was integration between Oracle and PDO. So I found this link: http://lacot.org/blog/2009/11/03/ubuntu-php5-oci8-and-pdo_oci-the-perfect-install.html and do it step by step (without instaling PDO, which was installed previously with pdo_mysql). When I tried to do it on Ubuntu 10.10 - it was working. Now, on 11.10 I get an error: 'Could not find driver' when I try to open my website application. I checked phpinfo() and in the row PDO there are: PDO support - enabled, PDO drivers - mysql. There is nothing about oci in this section, although few lines under it I have PDO Driver for OCI 8 and later - enabled. Hope somebody can help with this. Best regards, Mateo.

Why is the form not preventing submission?

I have a basic form that I am using as a dummy to test some JavaScript functionality. My goal is to click the submit button and have submission paused until a javascript function is executed, then submit the form after that. the code I currently have is below, but the submission of the form is not prevented, and the hidden field's value is never set. can someone explain why this is happening? NOTE I am aware of a jQuery method of performing the same functionality. I am specifically trying to solve this problem without using jQuery. If your only answer is "jQuery is better", please do not bother. <html> <head> <script type="text/javascript"> function test(){ document.getElementById("hidden").value="hidden"; var queryString = $('#decisionform').formSerialize(); alert(queryString); document.getElementById("form").submit(); } </script> </head> <body> <?php if ($_POST){ foreac

How to merge two arrays [closed]

Possible Duplicate: How to merge these two arrays? I've got two arrays array( '1' => 'string 1', '2' => 'string 2', '3' => 'string 3' ) array( 'a' => 'string a', 'b' => 'string b', 'c' => 'string c' ) What do I have to do to get this result: array( '1' => 'string 1', '2' => 'string 2', '3' => 'string 3', 'a' => 'string a', 'b' => 'string b', 'c' => 'string c' ) Will a simple $result = array_merge($array1, $array2) suffice or just glue them together with PHP $result = $array1 . $array2

Format MySQL Select into Associative Array in CakePHP

I like how CakePHP automatically loops through the results of MySQL queries and formats them in a nice map for you. Here's a sample query that I'm using: # Inside some model return $this->query(" SELECT Profile.id, SUM( IF( HOUR(Log.event_one) > 3, 1, 0 ) ) as EventOne FROM profiles Profile JOIN logs Log ON Log.id = Profile.log_id WHERE Profile.id = {$pUserId} "); CakePHP would return a map like the following as the result: array 0 array 'Profile' array 'id' => 23 '0' array 'EventOne' => 108 1 array 'Profile' array 'id' => 23 '0' array 'EventOne' => 42 2 ... What I'm trying to do is have the result be something like this: array 'Profile' array 'id' => 23 'Events' # ^ I want to be ab

Do I need to write a custom session class for CodeIgniter?

I cannot seem to get CI's session library to function the way I want it to. Essentially, I am storing 2 different categories of data within the sessions. The data within the 2 categories may contain the same value. Right now my attempt to add a key => value pair to the session is failing, as it is only allowing 1 key => value pair to be associated with the array. It overrides itself each time I do a post. $arr = array( 'favorite_products' => array(), 'viewed_products' => array() ); $arr["favorite_products"][] = $fav_id; $this->session->set_userdata($arr); This is what the array looks when I print_r it: Array ( [favorite_products] => Array ( [4f1066c2b7fff] => 1648406 ) [viewed_products] => Array ( )) Am I doing something wrong, or is this just the way CI's session library works?

Changed cookie domain, but old cookie is still used

EDITED, look at the end I got a Symfony 1.2 project, that was running on two domains (different app used on each domain) : www.mywebsite.com and abonnement.mywebsite.com I had two different cookie name/domain in each app. We decided to use the same cookie for both apps. So, i edited the config for both apps and set the cookie_domain to .mywebsite.com, and setted the cookie_name to mywebsite_cookie in boths apps. The problem is that when I visit abonnement.mywebsite.com, the old cookie is used. Manually deleting this cookie in my browser fixes the problem, but there are thousands of users on this website and I'm wondering if there's a solution to manually delete this cookie. I tried : if (isset($_COOKIE['abonnement_cookie'])) { ini_set('session.cookie_domain', 'abonnement.mywebsite.com); setcookie('abonnement_cookie', '', time() - 3600, '/'); $this->redirect('@internet_etape_1'); } But no success.

How to Bind SWFs to a Host?

I'm working on a major Flash project that is going to be the core content of a site. As most of you well know, almost any site can be entirely copied by copying the cached files and the hierarchy (files and folders structure), and it would run without problems on an Apache server with PHP enabled, if used. What I would like to know is: How to bind SWF files to run on a specific host? The SWFs will be encrypted, so outsiders won't have access to the methods used to stop the SWF from running on a different host, question is: what method to use? I think the solution could be hardcoding the host IP inside the SWF, so if the SWF is looking for 123.123.123.123, only a host with that IP would allow the SWF to run further. The issue is that AS3 alone can't discover the host IP or could it if it's trying to load a resource file? Anyway, that's why I need your help. EDIT: Ok, seems someone asked for something similar earlier: Can you secure your swf so it checks

Doctrine 1.2 / Zend

Im having trouble with doctrine generating the code for a query that has a umlaut in. $q = Doctrine_Query::create() ->select('DISTINCT p.project_name, fqha.form_question_has_answer_request, fqha.form_question_has_answer_form_id, fqha.form_question_has_answer_user_id, u.user_username, c.company_hall_no, c.company_type, c.company_company_name, c.company_country, c.company_stand_number, c.company_image_file_1, pchu.project_company_has_user_project_id, pchu.project_company_has_user_user_id') ->from('Klarents_Model_ProjectCompanyHasUser pchu') ->innerJoin('pchu.Klarents_Model_Company c') ->innerJoin('pchu.Klarents_Model_Project p') ->innerJoin('pchu.Klarents_Model_User u') ->innerJoin('pchu.Klarents_Model_Form f') ->leftJoin('pchu.Klarents_Model_FormQuestionHasAnswer fqha ON fqha.form_question_has_answer_form_id = ' . $this->zon

Strategy pattern in Symfony2

I'm trying to build simple service for rendering various types of pages. Basic concept is having something like: $somePageType = new PageType(...); $this->get('page.service')->render($somePagetype); ...which would be designed as Strategy pattern . Page types would implement interface with render method and page.service would call it. The problem is I'd like to use Doctrine in page type classes. What are my options here? I'd like to avoid creating service for each of these classes. Is that even possible? Is it possible to make them container aware without being services? Possibly, in the future, some page type might need something more than only Doctrine, so I need to keep in mind also that.

Unable to get Static declaration behaviour in PHP

class StaticTester { private static $id=0; function__construct() { self::$id+=1; } public static function checkIdFromStaticMethod() { echo "Current Id from Static method is ".self::$id; } } $st1=new StaticTester(); StaticTester::checkIdFromStaticMethod(); // this outputs 1. Okay ,I am not getting why the output is 1? After all Static means the value cannot be changed !

Problems With installation of MeioUpload with cakephp 2.0

thanks for reading this, i am working with cakephp 2.0 and making a form to upload some kind of files (rar and zip). I searched a lot and Finally got some plugin named "MeioUpload" and reading this install guide (https://github.com/jrbasso/MeioUpload/blob/master/README.markdown) I did the first two steps without problem, but the third one says "Download an archive from github and extract it in app/Plugin/MeioUpload" I do not know what it means. Which file should i download i do not know could you please help me? I am using windows with github. Here is my model, controller, and view from my project (spanish content) Model <?php class Proyecto extends AppModel { var $name = 'Proyecto'; var $belongsTo = array('Usuario'); var $actsAs = array( 'MeioUpload.MeioUpload' => array('filename') ); var $validate = array( 'name' => array( 'rule' => 'notEmpty'

SMTP or PHP mail on VPS ( Or Physical Severs) - A Social Networking site

I am developing a social networking site. It has functionality like user registration, people exchanging messages and sending email notifications for people's actions (and many more). Currently I use PHP's mail function to send mails and it is working fine. I already set up a VPS and hosted the application. My question may be a dumb question. Do Facebook and other social networking sites use SMTP servers to send the notifications or only just any kind of PHP mail function? I read somewhere that using PHP's mail , there is a chance of mail going to SPAM folder. They advised using a certified SMTP server. So, if I have to use an SMTP server: 1) Do I have to purchase a certified SMTP server separately? Or can this be hosted on same VPS whatever I have. If so, what server software will be good for this? 2) Are there settings I have to do in SMTP servers like send unlimited messages, because we don't know how many people exchange emails in a minute, and that

How to check an already existing record in Magento?

I am trying to perform an SQL query kind of thing where I need to check if my database table contains a particular record or not. If it does, do nothing else add the record which isn't present. My table sample contains fields like sample_id (auto-incremented), order_id, order_email_id, review_request, coupon_sent . It has got 4 records having order_ids (71, 74, 126, 165) To obtain $ids, I have this query, $to_date = date('Y-m-d H:i:s',strtotime('-3 days')); $orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('status', 'complete')->addFieldToFilter('updated_at',array('to' => $to_date ))->addAttributeToSelect('customer_email')->addAttributeToSelect('entity_id'); foreach($orders as $order) { $email = $order->getCustomerEmail(); $id = $order->getEntityId(); $sample = Mage::getModel('sample/sample')->getCollection()->addFieldToFilter('orde

JPA 2 + Criteria API - Defining a subquery

I try to convert a sql query to Criteria API without success so far. I can create two separate queries which return the values I need, but I don't know how to combine them in a single query. Here is the sql statement which works: select company.*, ticketcount.counter from company join (select company, COUNT(*) as counter from ticket where state<16 group by company) ticketcount on company.compid = ticketcount.company; This Criteria query returns the inner query results: CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<intCompany> qTicket = cb.createQuery(intCompany.class); Root<Ticket> from = qTicket.from(Ticket.class); Path groupBy = from.get("company"); Predicate state = cb.notEqual(from.<State>get("state"), getStateById(16)); qTicket.select(cb.construct( intCompany.class, cb.count(from),from.<Company>get("company"))) .where(state).groupBy(groupBy); em.createQuery

repaint() in Java

I write a Java code, but I have a trouble with GUI problem. When I add a component into JFrame object, then I call repaint() method in order to update the GUI but it doesn't work. But when I minimize or resize this frame, the GUI is updated. Here is my code: public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(460, 500); frame.setTitle("Circles generator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); String input = JOptionPane.showInputDialog("Enter n:"); int n = Integer.parseInt(input); CircleComponent component = new CircleComponent(n); frame.add(component); component.repaint(); }

Is possible to postpone trigger fire in Quartz?

I have two processes: Process 1 - implements runnable and can run forever. Process 2 - fires at fixed hour and minute of day (i've created a job that run with Quartz). To warn the process 1 that the other process is running I can use the TriggerListener , but how can I postpone the fire of the second process if the process 1 still doing something? For example: I need to fire the trigger at 2PM, but this need to be done after 2PM if the process 1 isnt idle. Here's some sample: ProcessForever.java import static org.quartz.CronScheduleBuilder.dailyAtHourAndMinute; import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; public class ProcessForever implements Runnable { private boolean processTwoRunning; private Scheduler scheduler; private Trigger trgProcessTwo; private String status; public static final STATUS_PROCESS = "PROCESS"; public static final STATUS_SLEEP = "SLEEP"; private

Drawing/warping a rectangular image into a quadrilateral image

I need to draw a BufferedImage within a given quadrilateral. I want to do that: I would like the cat to be deformed to be drawn within the quadrilateral. Graphics objects have different methods to draw images, but only to stretch them along the X and Y axis (See Graphics.drawImage methods). What I am dreaming of is a method Graphics.drawImage() where I specify the coordinates of the 4 quadrilateral points. Is there an easy way to do that?

Loading an animated image to a BufferedImage array

I'm trying to implement animated textures into an OpenGL game seamlessly. I made a generic ImageDecoder class to translate any BufferedImage into a ByteBuffer. It works perfectly for now, though it doesn't load animated images. I'm not trying to load an animated image as an ImageIcon. I need the BufferedImage to get an OpenGL-compliant ByteBuffer. How can I load every frames as a BufferedImage array in an animated image ? On a similar note, how can I get the animation rate / period ? Does Java handle APNG ?

How do I remove the root element of my Jetty webapp url?

I am running a Java webapp (let's call it mywebapp). Currently I access my page in this webapp by pointing locally to: http://localhost:9000/mywebapp/mystuff However, I need to access it using: http://localhost:9000/mystuff How can I do this? I've tried messing with some confs, but to no avail... This is my current root.xml: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://jetty.mortbay.org/configure.dtd"> <Configure class="org.mortbay.jetty.webapp.WebAppContext"> <Set name="contextPath">/root</Set> <Set name="war"> <SystemProperty name="app.webapps.path"/>/mywebapp.war </Set> </Configure> Also tried: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configu

Writing huge string data to file in java, optimization options

I have a chat like desktop java swing app, where i keep getting String type data. Eventually the String variable keeps growing larger and larger. 1) Is it wise idea to keep the large variable in memory and only when the logging is finished save this to disk. 2) If not, then should i continue saving everytime i get a new string (of length about 30-40). How should i go about optimizing such a desgin?

String.intern() vs manual string-to-identifier mapping?

I recall seeing a couple of string-intensive programs that do a lot of string comparison but relatively few string manipulation, and that have used a separate table to map strings to identifiers for equality efficiency and memory use, e.g.: public class Name { public static Map<String, Name> names = new SomeMap<String, Name>(); public static Name from(String s) { Name n = names.get(s); if (n == null) { n = new Name(s); names.put(s, n); } return n; } private final String str; public Name(String str) { this.str = str; } @Override public String toString() { return str; } // equals() and hashCode() are not overridden! } I'm pretty sure one of those program was javac from OpenJDK, so not some toy application. Of course the actual class was more complex (and also I think it implemented CharSequence), but you get the idea; the entire program was littered with Name in any location you would