Search Results

Search found 3214 results on 129 pages for 'city simulation'.

Page 16/129 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • Game Resource Generation

    - by Darthg8r
    I am currently building a game that has a "City" entity. These cities generate and consume resources such as food variably over a period of time. I need to be able query the server often to find exactly how much food the city at any given point. These queries can take place multiple times per minute. There could also be 400,000 cities to track at a given time. How would you handle tracking these resources? Would you do it in real time, keeping an instance of the city in memory on the server, with some sort of a snapshot in time of the resources, then computing the growth/consumption from that snapshot time for subsequent queries? Would you work exclusively with a database, using a similar "snapshoting" scheme? Maybe a mixture of the 2, caching recently queried cities in memory for a period of time? There is also a lot of other data that each city needs to track. A player can queue units to build in a barrack. The armies available in the city will need to be updated as units complete. I'm interested in everyone's input on where/when/how you'd manage the real time data.

    Read the article

  • Algorithm allowing a good waypoint path following?

    - by Thierry Savard Saucier
    I'm more looking into how should I implement this, either a tutorial or even the name of the concept I'm missing. I'm pretty sure some basic pathfinding algorithm could help me here, but I dont know which one ... I have a worldmap, with different cities on it. The player can choose a city from a menu, or click on an available cities on the world map, and the toon should walk over there. But I want him to follow a predefine path. Lets say our hero is on the city 1. He clicks on city 4. I want him to follow the path to city 2 and from there to city 4. I was handling this easily with arrow movement (left right top bottom) since its a single check. Now I'm not sure how I should do this. Should I loop threw each possible path and check which one leads me to D the fastest ... and if I do how do I avoid running in circle forever with cities 1-5-2 ?

    Read the article

  • Designing rules to fight smallpox in Civ-style TBS games

    - by Williham Totland
    TL;DR: How do you design a ruleset for a Civ-style TBS game that prevents city smallpox from being a profitable or viable strategy? Long version: Civ-style games are pretty great. Bringing a civilization from cradle to grave is a great endeavor, and practicing diplomacy with hard-line human players is fun and challenging. In theory. In practice, however, many of these games has, especially in multiplayer, exactly one viable strategy: City smallpox, a.k.a. infinite city spread, a.k.a. covering all available space with 1-citizen cities, packed as tight as they will go. I suppose this could count as emergent gameplay, but still; it could hardly be considered to be in the spirit of the class of game. The Civilization series, of course, is stuck in their more or less fixed rule sets, established with Civilization. Yes, there have been major changes in some respects, but the rules pertaining to city building and maintenance have stayed pretty similar. So the question, then: If you build a ruleset for a TBS from the ground up; what rules should be in place to prevent Infinite City Sprawl from being a viable strategy? Or should ICS be a viable strategy?

    Read the article

  • nginx rewrite rule for using domain host to redirect to specific internal directory

    - by user85836
    I'm new to Nginx rewrites and looking for help in getting a working and minimal rewrite code. We would like to use urls like 'somecity.domain.com' on campaign materials and have the result go to city-specific content within the 'www' site. So, here are use cases, if the customer enters: www.domain.com (stays) www.domain.com domain.com (goes to) www.domain.com www.domain.com/someuri (stays the same) somecity.domain.com (no uri, goes to) www.domain.com/somecity/prelaunch somecity.domain.com/landing (goes to) www.domain.com/somecity/prelaunch somecity.domain.com/anyotheruri (goes to) www.domain.com/anyotheruri Here's what I've come up with so far, and it partially works. What I can't understand is how to check if there is no path/uri after the host, and I'm guessing there is probably a way better way to do this. if ($host ~* ^(.*?)\.domain\.com) { set $city $1;} if ($city ~* www) { break; } if ($city !~* www) { rewrite ^/landing http://www.domain.com/$city/prelaunch/$args permanent; rewrite (.*) http://www.domain.com$uri$args permanent; }

    Read the article

  • Microsoft Excel IF/THEN statement for Words

    - by user1667462
    Right now I have an excel spreadsheet. In Cells A1 and down I have cities listed. In Cells B1 and down I have some generic information with the word CITY in it. What I want to know if there is a formula to replace the word CITY that is in the contents of Cell B1 with the contents in Cell A1. For instance... Cell A1 has "Daytona Beach, FL" Cell B1 has "Compare mortgage & refinance rates from different mortgage lenders and brokers in CITY. Find the home refinance rate you were looking for in CITY." I need a formula that replaces "CITY" in B1 with "Dayton Beach, FL" in A1. Is this possible? Thank you for your help!

    Read the article

  • Software architecture for two similar classes which require different input parameters for the same method

    - by I Like to Code
    I am writing code to simulate a supply chain. The supply chain can be simulated in either an intermediate stocking or a cross-docking configuration. So, I wrote two simulator objects IstockSimulator and XdockSimulator. Since the two objects share certain behaviors (e.g. making shipments, demand arriving), I wrote an abstract simulator object AbstractSimulator which is a parent class of the two simulator objects. The abstract simulator object has a method runSimulation() which takes an input parameter of class SimulationParameters. Up till now, the simulation parameters only contains fields that are common to both simulator objects, such as randomSeed, simulationStartPeriod and simulationEndPeriod. However, I now want to include fields that are specific to the type of simulation that is being run, i.e. an IstockSimulationParameters class for an intermediate stocking simulation, and a XdockSimulationParameters class for a cross-docking simulation. My current idea is take the method runSimulation() out of the AbstractSimulator class, but to put a runSimulation(IstockSimulationParameters) method in the IstockSimulator class, and a runSimulation(XdockSimulationParameters) method in the IstockSimulator class. I am worried however, that this approach will lead to code duplication. What should I do?

    Read the article

  • Error while installing an application

    - by Bong.Da.City
    So i have installed synaptic package manager.. via it, i have checked once libopencv-highgui-dev and applied complete removal.. after that i installed it... now everytime i try to install an application e.g Format Junkie sudo add-apt-repository ppa:format-junkie-team/release && sudo apt-get update && sudo apt-get install formatjunkie in the command install format junkie it gives me that error everytime: sudo apt-get install formatjunkie Reading package lists... Done Building dependency tree Reading state information... Done Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: libopencv-features2d-dev : Depends: libopencv-highgui-dev (= 2.3.1-11ubuntu2) but it is not going to be installed E: Error, pkgProblemResolver::Resolve generated breaks, this may be caused by held packages. What should i do? And 2nd what did i did wrong so it won't happen another time? output of lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 12.10 Release: 12.10 Codename: quantal

    Read the article

  • how to enrich my programming background? [on hold]

    - by city
    I am not sure whether I post my question in right place. I am a master student in computer science and I will graduate next year.Recently, I failed in an interview. Because (at least I think) the interviewer did not think my background strong enough although I finished 5 courses projects and currently working on other 2 projects in graduate school. It seems that nowadays, recruiters like these candidates who finish some projects out of school/work. So I wanna enrich my background. So, I hope you guys recommend some java/C++ projects to me, which I can finish in two or three months. And it would be better if concurrency programming or other fancy skills are needed.

    Read the article

  • Help With Database Layout

    - by three3
    Hello everyone, I am working on a site similar to Craigslist where users can make postings and sell items in different cities. One difference between my site and Craigslist will be you will be able to search by zip code instead of having all of the cities listed on the page. I already have the ZIP Code database that has all of the city, state, latitude, longitude, and zip code info for each city. Okay, so to dive into what I need done and what I need help with: 1.) Although I have the ZIP Code database, it is not setup perfectly for my use. (I downloaded it off of the internet for free from http://zips.sourceforge.net/) 2.) I need help setting up my database structure (Ex: How many different tables should I use and how should I link them) I will be using PHP and MySQL. These our my thoughts so far on how the database can be setup: (I am not sure if this will work though.) Scenario: Someone goes to the homepage and it will tell them, "Please enter your ZIP Code.". If they enter "17241" for example, this ZIP Code is for a city named Newville located in Pennsylvania. The query would look like this with the current database setup: SELECT city FROM zip_codes WHERE zip = 17241; The result of the query would be "Newville". The problem I see here now is when they want to post something in the Newville section of the site, I will have to have an entire table setup just for the Newville city postings. There are over 42,000 cities which means I would have to have over 42,000 tables (one for each city) so that would be insane to have to do it that way. One way I was thinking of doing it was to add a column to the ZIP Code database called "city_id" which would be a unique number assigned to each city. So for example, the city Newville would have a city_id of 83. So now if someone comes and post a listing in the city Newville I would only need one other table. That one other table would be setup like this: CREATE TABLE postings ( posting_id INT NOT NULL AUTO_INCREMENT, for_sale LONGTEXT NULL, for_sale_date DATETIME NULL, for_sale_city_id INT NULL, jobs LONGTEXT NULL, jobs_date DATETIME NULL, jobs_city_id INT NULL, PRIMARY KEY(posting_id) ); (The for_sale and job_ column names are categories of the types of postings users will be able to list under. There will be many more categories than just those two but this is just for example.) So now when when someone comes to the website and they are looking for something to buy and not sell, they can enter their ZIP Code, 17241, for example, and this is the query that will run: SELECT city, city_id FROM zip_codes WHERE zip = 17241; //Result: Newville 83 (Please note that I will be using PHP to store the ZIP Code the user enters in SESSIONS and Cookies to remember them throughout the site) Now it will tell them, "Please choose your category.". If they choose the category "Items For Sale" then this is the query to run and sort the results: SELECT posting_id, for_sale, for_sale_date FROM postings WHERE for_sale_city_id = $_SESSION['zip_code']; Will this work? So now my question to everyone is will this work? I am pretty sure it will but I do not want to set this thing up and realize I overlooked something and have to start from all over from scratch. Any opinions and ideas are welcomed and I will listen to anyone who has some thoughts. I really appreciate the help in advance :D

    Read the article

  • Flex list control itemrenderer issue

    - by Jerry
    Hi Guys I am working on a small photo Gallery. I create a xml file and try to link it to my List control with itemrenderer. However, when I tried to save the file, I got access of undefined property data. Here is my code...and thanks a lot! <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"> <fx:Declarations> <fx:Model id="pictureXML" source="data/pictures.xml"/> <s:ArrayList id="pictureArray" source="{pictureXML.picture}"/> </fx:Declarations> <s:List id="pictureGrid" dataProvider="{pictureArray}" horizontalCenter="0" top="20"> <s:itemRenderer> <fx:Component> <s:HGroup> <mx:Image source="images/big/{data.source}" /> <s:Label text="{data.caption}"/> </s:HGroup> </fx:Component> </s:itemRenderer> </s:List> </s:Application> My xml <?xml version="1.0"?> <album> <picture> <source>city1.jpg </source> <caption>City View 1</caption> </picture> <picture> <source>city2.jpg </source> <caption>City View 2</caption> </picture> <picture> <source>city3.jpg </source> <caption>City View 3</caption> </picture> <picture> <source>city4.jpg </source> <caption>City View 4</caption> </picture> <picture> <source>city5.jpg </source> <caption>City View 5</caption> </picture> <picture> <source>city6.jpg </source> <caption>City View 6</caption> </picture> <picture> <source>city7.jpg </source> <caption>City View 7</caption> </picture> <picture> <source>city8.jpg </source> <caption>City View 8</caption> </picture> <picture> <source>city9.jpg </source> <caption>City View 9</caption> </picture> <picture> <source>city10.jpg </source> <caption>City View 10</caption> </picture> </album> I appreciate any helps!!!

    Read the article

  • Getting Segmentation Fault in C++, but why?

    - by Carlos
    I am getting segmentation fault in this code but i cant figure out why. I know a segmentation fault happens when a pointer is NULL, or when it points to a random memory address. #include <iostream> #include <fstream> #include <cmath> using namespace std; //**************************** CLASS ******************************* class Database { struct data{ string city; float latitude, longitude; data *link; }*p; public: Database(); void display(); void add(string cityName, float lat, float lon); private: string cityName; float lat, lon; }; //************************** CLASS METHODS ************************** Database::Database() { p = NULL; } void Database::add(string cityName, float lat, float lon){ data *q, *t; if(p == NULL){ p = new data; p -> city = cityName; p -> latitude = lat; p -> longitude = lon; p -> link = NULL; } else{ q = p; while(q -> link != NULL){ q = q -> link; } t = new data; t -> city = cityName; t -> latitude = lat; t -> longitude = lon; q -> link = t; } } void Database::display() { data *q; cout<<endl; for( q = p ; q != NULL ; q = q->link ) cout << endl << q -> city; } //***************************** MAIN ******************************* //*** INITIALIZATION *** Database D; void loadDatabase(); //****** VARIABLES ***** //******* PROGRAM ****** int main() { loadDatabase(); D.display(); } void loadDatabase() { int i = 0; string cityName; float lat, lon; fstream city; city.open("city.txt", ios::in); fstream latitude; latitude.open("lat.txt", ios::in); fstream longitude; longitude.open("lon.txt", ios::in); while(!city.eof()){ //************************************ city >> cityName; //* * latitude >> lat; //Here is where i think is the problem longitude >> lon; //* * D.add(cityName, lat, lon); //************************************ } city.close(); latitude.close(); longitude.close(); } This is the error am actually getting in console

    Read the article

  • "Expected initializer before '<' token" in header file

    - by Sarah
    I'm pretty new to programming and am generally confused by header files and includes. I would like help with an immediate compile problem and would appreciate general suggestions about cleaner, safer, slicker ways to write my code. I'm currently repackaging a lot of code that used to be in main() into a Simulation class. I'm getting a compile error with the header file for this class. I'm compiling with gcc version 4.2.1. // Simulation.h #ifndef SIMULATION_H #define SIMULATION_H #include <cstdlib> #include <iostream> #include <cmath> #include <string> #include <fstream> #include <set> #include <boost/multi_index_container.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/mem_fun.hpp> #include <boost/multi_index/composite_key.hpp> #include <boost/shared_ptr.hpp> #include <boost/tuple/tuple_comparison.hpp> #include <boost/tuple/tuple_io.hpp> #include "Parameters.h" #include "Host.h" #include "rng.h" #include "Event.h" #include "Rdraws.h" typedef multi_index_container< // line 33 - first error boost::shared_ptr< Host >, indexed_by< hashed_unique< const_mem_fun<Host,int,&Host::getID> >, // 0 - ID index ordered_non_unique< tag<age>,const_mem_fun<Host,int,&Host::getAgeInY> >, // 1 - Age index hashed_non_unique< tag<household>,const_mem_fun<Host,int,&Host::getHousehold> >, // 2 - Household index ordered_non_unique< // 3 - Eligible by age & household tag<aeh>, composite_key< Host, const_mem_fun<Host,int,&Host::getAgeInY>, const_mem_fun<Host,bool,&Host::isEligible>, const_mem_fun<Host,int,&Host::getHousehold> > >, ordered_non_unique< // 4 - Eligible by household (all single adults) tag<eh>, composite_key< Host, const_mem_fun<Host,bool,&Host::isEligible>, const_mem_fun<Host,int,&Host::getHousehold> > >, ordered_non_unique< // 5 - Household & age tag<ah>, composite_key< Host, const_mem_fun<Host,int,&Host::getHousehold>, const_mem_fun<Host,int,&Host::getAgeInY> > > > // end indexed_by > HostContainer; typedef std::set<int> HHSet; class Simulation { public: Simulation( int sid ); ~Simulation(); // MEMBER FUNCTION PROTOTYPES void runDemSim( void ); void runEpidSim( void ); void ageHost( int id ); int calcPartnerAge( int a ); void executeEvent( Event & te ); void killHost( int id ); void pairHost( int id ); void partner2Hosts( int id1, int id2 ); void fledgeHost( int id ); void birthHost( int id ); void calcSI( void ); double beta_ij_h( int ai, int aj, int s ); double beta_ij_nh( int ai, int aj, int s ); private: // SIMULATION OBJECTS double t; double outputStrobe; int idCtr; int hholdCtr; int simID; RNG rgen; HostContainer allHosts; // shared_ptr to Hosts - line 102 - second error HHSet allHouseholds; int numInfecteds[ INIT_NUM_AGE_CATS ][ INIT_NUM_STYPES ]; EventPQ currentEvents; // STREAM MANAGEMENT void writeOutput(); void initOutput(); void closeOutput(); std::ofstream ageDistStream; std::ofstream ageDistTStream; std::ofstream hhDistStream; std::ofstream hhDistTStream; std::string ageDistFile; std::string ageDistTFile; std::string hhDistFile; std::string hhDistTFile; }; #endif I'm hoping the other files aren't so relevant to this problem. When I compile with g++ -g -o -c a.out -I /Applications/boost_1_42_0/ Host.cpp Simulation.cpp rng.cpp main.cpp Rdraws.cpp I get Simulation.h:33: error: expected initializer before '<' token Simulation.h:102: error: 'HostContainer' does not name a type and then a bunch of other errors related to not recognizing the HostContainer. It seems like I have all the right Boost #includes for the HostContainer to be understood. What else could be going wrong? I would appreciate immediate suggestions, troubleshooting tips, and other advice about my code. My plan is to create a "HostContainer.h" file that includes the typedef and structs that define its tags, similar to what I'm doing in "Event.h" for the EventPQ container. I'm assuming this is legal and good form.

    Read the article

  • Select XML nodes as rows

    - by Bjørn
    I am selecting from a table that has an XML column using T-SQL. I would like to select a certain type of node and have a row created for each one. For instance, suppose I am selecting from a people table. This table has an XML column for addresses. The XML is formated similar to the following: <address> <street>Street 1</street> <city>City 1</city> <state>State 1</state> <zipcode>Zip Code 1</zipcode> </address> <address> <street>Street 2</street> <city>City 2</city> <state>State 2</state> <zipcode>Zip Code 2</zipcode> </address> How can I get results like this: Name         City         State Joe Baker   Seattle      WA Joe Baker   Tacoma     WA Fred Jones  Vancouver BC

    Read the article

  • .NET MVC custom routing with empty parameters

    - by user135498
    Hi All, I have a .net mvc with the following routes: routes.Add(new Route( "Lookups/{searchtype}/{inputtype}/{firstname}/{middlename}/{lastname}/{city}/{state}/{address}", new RouteValueDictionary( new { controller = "Lookups", action = "Search", firstname = (string)null, middlename = (string)null, lastname = (string)null, city = (string)null, state = (string)null, address = (string)null, SearchType = SearchType.PeopleSearch, InputType = InputType.Name }), new MvcRouteHandler()) ); routes.Add(new Route( "Lookups/{searchtype}/{inputtype}", new RouteValueDictionary( new { controller = "Lookups", action = "Search", firstname = "", middlename = "", lastname = "", city = "", state = "", address = "" }), new MvcRouteHandler()) ); routes.Add(new Route( "Lookups/{searchtype}/{inputtype}", new RouteValueDictionary( new { controller = "Lookups", action = "Search", firstname = "", middlename = "", lastname = "", city = "", state = "", address = "", SearchType = SearchType.PeopleSearch, InputType = InputType.Name }), new MvcRouteHandler()) ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Account", action = "LogOn", id = "" } // Parameter defaults ); The following request works fine: http://localhost:2608/Lookups/PeopleSearch/Name/john/w/smith/seattle/wa/123 main This request does not work: http://localhost:2608/Lookups/PeopleSearch/Name/john//smith//wa/ Not all requests will have all paramters and I would like empty parameters to be passed to the method as empty string or null. Where am I going wrong? The method: public ActionResult Search(string firstname, string middlename, string lastname, string city, string state, string address, SearchType searchtype, InputType inputtype) { SearchRequest r = new SearchRequest { Firstname = firstname, Middlename = middlename, Lastname = lastname, City = city, State = state, Address = address, SearchType = searchtype, InputType = inputtype }; return View(r); }

    Read the article

  • rails semi-complex STI with ancestry data model planning the routes and controllers

    - by ere
    I'm trying to figure out the best way to manage my controller(s) and models for a particular use case. I'm building a review system where a User may build a review of several distinct types with a Polymorphic Reviewable. Country (has_many reviews & cities) Subdivision/State (optional, sometimes it doesnt exist, also reviewable, has_many cities) City (has places & review) Burrow (optional, also reviewable ex: Brooklyn) Neighborhood (optional & reviewable, ex: williamsburg) Place (belongs to city) I'm also wondering about adding more complexity. I also want to include subdivisions occasionally... ie for the US, I might add Texas or for Germany, Baveria and have it be reviewable as well but not every country has regions and even those that do might never be reviewed. So it's not at all strict. I would like it to as simple and flexible as possible. It'd kinda be nice if the user could just land on one form and select either a city or a country, and then drill down using data from say Foursquare to find a particular place in a city and make a review. I'm really not sure which route I should take? For example, what happens if I have a Country, and a City... and then I decide to add a Burrow? Could I give places tags (ie Williamsburg, Brooklyn) belong_to NY City and the tags belong to NY? Tags are more flexible and optionally explain what areas they might be in, the tags belong to a city, but also have places and be reviewable? So I'm looking for suggestions for anyone who's done something related. Using Rails 3.2, and mongoid.

    Read the article

  • SQL Server 2008 - Keyword search using table Join

    - by Aaron Wagner
    Ok, I created a Stored Procedure that, among other things, is searching 5 columns for a particular keyword. To accomplish this, I have the keywords parameter being split out by a function and returned as a table. Then I do a Left Join on that table, using a LIKE constraint. So, I had this working beautifully, and then all of the sudden it stops working. Now it is returning every row, instead of just the rows it needs. The other caveat, is that if the keyword parameter is empty, it should ignore it. Given what's below, is there A) a glaring mistake, or B) a more efficient way to approach this? Here is what I have currently: ALTER PROCEDURE [dbo].[usp_getOppsPaged] @startRowIndex int, @maximumRows int, @city varchar(100) = NULL, @state char(2) = NULL, @zip varchar(10) = NULL, @classification varchar(15) = NULL, @startDateMin date = NULL, @startDateMax date = NULL, @endDateMin date = NULL, @endDateMax date = NULL, @keywords varchar(400) = NULL AS BEGIN SET NOCOUNT ON; ;WITH Results_CTE AS ( SELECT opportunities.*, organizations.*, departments.dept_name, departments.dept_address, departments.dept_building_name, departments.dept_suite_num, departments.dept_city, departments.dept_state, departments.dept_zip, departments.dept_international_address, departments.dept_phone, departments.dept_website, departments.dept_gen_list, ROW_NUMBER() OVER (ORDER BY opp_id) AS RowNum FROM opportunities JOIN departments ON opportunities.dept_id = departments.dept_id JOIN organizations ON departments.org_id=organizations.org_id LEFT JOIN Split(',',@keywords) AS kw ON (title LIKE '%'+kw.s+'%' OR [description] LIKE '%'+kw.s+'%' OR tasks LIKE '%'+kw.s+'%' OR requirements LIKE '%'+kw.s+'%' OR comments LIKE '%'+kw.s+'%') WHERE ( (@city IS NOT NULL AND (city LIKE '%'+@city+'%' OR dept_city LIKE '%'+@city+'%' OR org_city LIKE '%'+@city+'%')) OR (@state IS NOT NULL AND ([state] = @state OR dept_state = @state OR org_state = @state)) OR (@zip IS NOT NULL AND (zip = @zip OR dept_zip = @zip OR org_zip = @zip)) OR (@classification IS NOT NULL AND (classification LIKE '%'+@classification+'%')) OR ((@startDateMin IS NOT NULL AND @startDateMax IS NOT NULL) AND ([start_date] BETWEEN @startDateMin AND @startDateMax)) OR ((@endDateMin IS NOT NULL AND @endDateMax IS NOT NULL) AND ([end_date] BETWEEN @endDateMin AND @endDateMax)) OR ( (@city IS NULL AND @state IS NULL AND @zip IS NULL AND @classification IS NULL AND @startDateMin IS NULL AND @startDateMax IS NULL AND @endDateMin IS NULL AND @endDateMin IS NULL) ) ) ) SELECT * FROM Results_CTE WHERE RowNum >= @startRowIndex AND RowNum < @startRowIndex + @maximumRows; END

    Read the article

  • SQL: Order randomly when inserting objects to a table

    - by Ekaterina
    I have an UDF that selects top 6 objects from a table (with a union - code below) and inserts it into another table. (btw SQL 2005) So I paste the UDF below and what the code does is: selects objects for a specific city and add a level to those (from table Europe) union that selection with a selection from the same table for objects that are from the same country and add a level to those From the union, selection is made to get top 6 objects, order by level, so the objects from the same city will be first, and if there aren't any available, then objects from the same country will be returned from the selection. And my problem is, that I want to make a random selection to get random objects from table Europe, but because I insert the result of my selection into a table, I can't use order by newid() or rand() function because they are time-dependent, so I get the following errors: Invalid use of side-effecting or time-dependent operator in 'newid' within a function. Invalid use of side-effecting or time-dependent operator in 'rand' within a function. UDF: ALTER FUNCTION [dbo].[Objects] (@id uniqueidentifier) RETURNS @objects TABLE ( ObjectId uniqueidentifier NOT NULL, InternalId uniqueidentifier NOT NULL ) AS BEGIN declare @city varchar(50) declare @country int select @city = city, @country = country from Europe where internalId = @id insert @objects select @id, internalId from ( select distinct top 6 [level], internalId from ( select top 6 1 as [level], internalId from Europe N4 where N4.city = @city and N4.internalId != @id union select top 6 2 as [level], internalId from Europe N5 where N5.countryId = @country and N5.internalId != @id ) as selection_1 order by [level] ) as selection_2 return END If you have fresh ideas, please share them with me. (Just please, don't suggest to order by newid() or to add a column rand() with seed DateTime (by ms or sthg), because that won't work.)

    Read the article

  • Optimize a MySQL count each duplicate Query

    - by Onema
    I have the following query That gets the city name, city id, the region name, and a count of duplicate names for that record: SELECT Country_CA.City AS currentCity, Country_CA.CityID, globe_region.region_name, ( SELECT count(Country_CA.City) FROM Country_CA WHERE City LIKE currentCity ) as counter FROM Country_CA LEFT JOIN globe_region ON globe_region.region_id = Country_CA.RegionID AND globe_region.country_code = Country_CA.CountryCode ORDER BY City This example is for Canada, and the cities will be displayed on a dropdown list. There are a few towns in Canada, and in other countries, that have the same names. Therefore I want to know if there is more than one town with the same name region name will be appended to the town name. Region names are found in the globe_region table. Country_CA and globe_region look similar to this (I have changed a few things for visualization purposes) CREATE TABLE IF NOT EXISTS `Country_CA` ( `City` varchar(75) NOT NULL DEFAULT '', `RegionID` varchar(10) NOT NULL DEFAULT '', `CountryCode` varchar(10) NOT NULL DEFAULT '', `CityID` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`City`,`RegionID`), KEY `CityID` (`CityID`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; AND CREATE TABLE IF NOT EXISTS `globe_region` ( `country_code` char(2) COLLATE utf8_unicode_ci NOT NULL, `region_code` char(2) COLLATE utf8_unicode_ci NOT NULL, `region_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`country_code`,`region_code`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; The query on the top does exactly what I want it to do, but It takes way too long to generate a list for 5000 records. I would like to know if there is a way to optimize the sub-query in order to obtain the same results faster. the results should look like this City CityID region_name counter sheraton 2349269 British Columbia 1 sherbrooke 2349270 Quebec 2 sherbrooke 2349271 Nova Scotia 2 shere 2349273 British Columbia 1 sherridon 2349274 Manitoba 1

    Read the article

  • Calculating a total cost in Python

    - by Sérgio Lourenço
    I'm trying to create a trip planner in python, but after I defined all the functions I'm not able to call and calculate them in the last function tripCost(). In tripCost, I want to put the days and travel destination (city) and the program runs the functions and gives me the exact result of all the 3 functions previously defined. Code: def hotelCost(): days = raw_input ("How many nights will you stay at the hotel?") total = 140 * int(days) print "The total cost is",total,"dollars" def planeRideCost(): city = raw_input ("Wich city will you travel to\n") if city == 'Charlotte': return "The cost is 183$" elif city == 'Tampa': return "The cost is 220$" elif city == 'Pittsburgh': return "The cost is 222$" elif city == 'Los Angeles': return "The cost is 475$" else: return "That's not a valid destination" def rentalCarCost(): rental_days = raw_input ("How many days will you rent the car\n") discount_3 = 40 * int(rental_days) * 0.2 discount_7 = 40 * int(rental_days) * 0.5 total_rent3 = 40 * int(rental_days) - discount_3 total_rent7 = 40 * int(rental_days) - discount_7 cost_day = 40 * int(rental_days) if int(rental_days) >= 3: print "The total cost is", total_rent3, "dollars" elif int(rental_days) >= 7: print "The total cost is", total_rent7, "dollars" else: print "The total cost is", cost_day, "dollars" def tripCost(): travel_city = raw_input ("What's our destination\n") days_travel = raw_input ("\nHow many days will you stay\n") total_trip_cost = hotelCost(int(day_travel)) + planeRideCost (str(travel_city)) + rentalCost (int(days_travel)) return "The total cost with the trip is", total_trip_cost tripCost()

    Read the article

  • How can get unique values from data table using dql?

    - by piemesons
    I am having a table in which there is a column in which various values are stored.i want to retrieve unique values from that table using dql. Doctrine_Query::create() ->select('rec.school') ->from('Records rec') ->where("rec.city='$city' ") ->execute(); Now i want only unique values. Can anybody tell me how to do that... Edit Table Structure: CREATE TABLE IF NOT EXISTS `records` ( `id` int(11) NOT NULL AUTO_INCREMENT, `state` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `city` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `school` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16334 ; This is the Query I am using: Doctrine_Query::create() ->select('DISTINCT rec.city') ->from('Records rec') ->where("rec.state = '$state'") // ->getSql(); ->execute(); Generting Sql for this gives me: SELECT DISTINCT r.id AS r__id, r.city AS r__city FROM records r WHERE r.state = 'AR' Now check the sql generated:::: DISTINCT is on 'id' column where as i want Distinct on city column. Anybody know how to fix this. EDIT2 Id is unique cause its an auto incremental value.Ya i have some real duplicates in city column like: Delhi and Delhi. Right.. Now when i am trying to fetch data from it, I am getting Delhi two times. How can i make query like this: select DISTINCT rec.city where state="xyz"; Cause this will give me the proper output. EDIT3: Anybody who can tell me how to figure out this query..???

    Read the article

  • Is good practice to optimize FPS even when it's above the lower limit to give illusion of movement?

    - by rraallvv
    I started over 50 FPS on the iPhone, but now I'm bellow 30 PFS, I've seen most iPhone games clamped to either 60 or 30 FPS, even when 24 or less would give the illusion of movement. I've concidered my limit to be a little bit over 15 FPS, in fact my physics simulation is updated at that rate (15.84 steps/s) as that is the lowest that still give fluid movement, a bit lower gives jerky motion. Is there a practical reason why to clamp FPS way above the lower limit? Update: The following image could help to clarify I can independently set the physic simulation step, frame rate, and simulation interval update. My concern is why should I clamp any of those to values greater than the minimum? For instance to conserve battery life I could just to choose the lower limits, but it seems that 60 or 30 FPS are the most used values.

    Read the article

  • Optimization of time-varying parameters

    - by brama
    I need to find an optimal set of "n" parameter values that minimize an objective function (a 2-hr simulation of a system). I have looked at genetic algorithm and simulated annealing methods, but was wondering if there are any better algorithms and guidance on their merits and limitations. With the above optimization methods I can find the optimal parameter values that hold true for the entire simulation duration. Incase, I want to find the optimal "time varying" parameter values (parameter values change with time during the 2-hr simulation), are there any methods/ideas other than making each time varying parameter value a variable to optimize? Any thoughts?

    Read the article

  • Rails "NoMethodError" with sub-resources

    - by Tchock
    Hi. I'm a newbie Rails developer who is getting the following error when trying to access the 'new' action on my CityController: undefined method `cities_path' for #<#<Class:0x104608c18>:0x104606f08> Extracted source (around line #2): 1: <h1>New City</h1> 2: <%= form_for(@city) do |f| %> 3: <%= f.error_messages %> 4: 5: <div class="field"> As some background, I have a State model with many Cities. I'm getting this error after clicking on the following link coming from a State show page: <p>Add a city: <%= link_to "Add city", new_state_city_path(@state) %></p> When I run 'rake:routes' it says this is a legit route... For more background, here is the CityController 'new' action: def new @city = City.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @city } end end Here is the (complete) form in the view: <%= form_for(@city) do |f| %> <%= f.error_messages %> <div class="field"> <%= f.label :name %><br /> <%= f.text_field :name %> </div> <div class="actions"> <%= f.submit %> </div> <% end %> This initially made me think that it's a resources/routes issue since it came back with a mention of 'cities_path' (in fact, that's what another person posting to Stack Overflow had wrong (http://stackoverflow.com/questions/845315/rails-error-nomethoderror-my-first-ruby-app). However, that doesn't seem to be the case from what I can see. Here are how my resources look in my routes file: resources :states do resources :cities end I can get it working when they are not sub-resources, but I really need to keep them as sub-resources for my future plans with the app. Any help would be very much appreciated, since I've been racking my brains on this for more hours than I would care to admit... Thanks! (Not sure this matters at all, but I'm running the very latest version of Rails 3 beta2).

    Read the article

  • Django database caching

    - by hekevintran
    The object user has a foreign key relationship to address. Is there a difference between samples 1 and 2? Does sample 1 run the query multiple times? Or is the address object cached? # Sample 1 country = user.address.country city = user.address.city state = user.address.state # Sample 2 address = user.address country = address.country city = address.city state = address.state

    Read the article

  • To HTMLENCODE or not to HTMLENCODE user input on web form (asp.net vb)

    - by Phil
    I have many params making up an insert form for example: x.Parameters.AddWithValue("@city", City.Text) I had a failed xss attack on the site this morning, so I am trying to beef up security measures anyway.... Should I be adding my input params like this? x.Parameters.AddWithValue("@city", HttpUtility.HtmlEncode(City.Text)) Is there anything else I should consider to avoid attacks? Thanks

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >