Search Results

Search found 49435 results on 1978 pages for 'query string'.

Page 14/1978 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • How to replace characters in a java String?

    - by ManBugra
    I like to replace a certain set of characters of a string with a corresponding replacement character in an efficent way. For example: String sourceCharacters = "šdccŠÐCCžŽ"; String targetCharacters = "sdccSDCCzZ"; String result = replaceChars("Gracišce", sourceCharacters , targetCharacters ); Assert.equals(result,"Gracisce") == true; Is there are more efficient way than to use the replaceAll method of the String class? My first idea was: final String s = "Gracišce"; String sourceCharacters = "šdccŠÐCCžŽ"; String targetCharacters = "sdccSDCCzZ"; // preparation final char[] sourceString = s.toCharArray(); final char result[] = new char[sourceString.length]; final char[] targetCharactersArray = targetCharacters.toCharArray(); // main work for(int i=0,l=sourceString.length;i<l;++i) { final int pos = sourceCharacters.indexOf(sourceString[i]); result[i] = pos!=-1 ? targetCharactersArray[pos] : sourceString[i]; } // result String resultString = new String(result); Any ideas? Btw, the UTF-8 characters are causing the trouble, with US_ASCII it works fine.

    Read the article

  • String operations

    - by NEO
    I am trying to find the most repeated word in a string. My code is as follows: public class Word { private String toWord; private int Count; public Word(int count, String word){ toWord = word; Count = count; } public static void main(String args[]){ String str="my name is neo and my other name is also neo because I am neo"; String []str1=str.split(" "); Word w1=new Word(0,str1[0]); LinkedList<Word> list = new LinkedList<Word>(); list.add(w1); ListIterator itr = list.listIterator(); for(int i=1;i<str1.length;i++){ while(itr.hasNext()){ if(str1[i].equalsTO(????)); else list.add(new Word(0,str1[i])); } How do I compare the string from string array str1 to the string stored in the linked list and then how do i increase the respective count. I will then print the string with the highest count, I dont know how to do that either.

    Read the article

  • MS Query returns data inside itself but does not export it to Excel

    - by kappa
    Hi, I'm having a strange problem with Excel and MS Query: I'm using MS Query to run a T-SQL query against a Microsoft SQL Server 2000 and return the results to Excel. To do this, I open Excel, go to Data - Import external data - New database query, select my data source, paste the SQL script in MS Query and click File - Return data to Microsoft Office Excel, leaving all the query options to their defaults. This works fine for many other Excel files, but this time although MS Query shows the correct data when I paste the SQL script, after returning to Excel all I get is the query name in the upper left cell, with no data returned. I fear the cause could be the SQL script, as it contains some advanced functions like union all, UDFs and variables. Here's the script: declare @date smalldatetime set @date = dateadd(day, datediff(day, 0, getdate()), 0) select [date], sum([hours]) as [hours] from ( select [date], [hours] from [server].[dbo].[udf] (84, '2010-01-01', @date) union all select [date], [hours] from [server].[dbo].[udf] (89, '2010-01-01', @date) union all select [date], [hours] from [server].[dbo].[udf] (93, '2010-01-01', @date) ) as [a] group by [date] order by [date] asc I can't get rid of the UDF as inside them are done advanced groupings involving cursors and temporary tables, nor I can remove the variable as the UDF won't accept dateadd(day, datediff(day, 0, getdate()), 0) as parameter. Any ideas? Thanks in advance, Andrea.

    Read the article

  • String from Httpresponse not passing full value.

    - by Shekhar_Pro
    HI i am in desperate need for help here, I am making a web request and getting a json string with Response.ContentLenth=2246 but when i parse it in a string it gives only few 100 characters, i traked it down that it is only getting values less than 964. strings length is still 2246 but remaining values are just (\0) null characters. Its also giving an error Unterminated string passed in. (2246): at following line FacebookFeed feed = sr.Deserialize<FacebookFeed>(data); It works fine if the response stream contains characters less than 964 chars. Following is the extract from the full code error encountered in last line. System.Web.Script.Serialization.JavaScriptSerializer sr = new System.Web.Script.Serialization.JavaScriptSerializer(); System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(@"https://graph.facebook.com/100000570310973_181080451920964"); req.Method = "GET"; System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse(); byte[] resp = new byte[(int)res.ContentLength]; res.GetResponseStream().Read(resp, 0, (int)res.ContentLength); string data = Encoding.UTF8.GetString(resp); FacebookFeed feed = sr.Deserialize<FacebookFeed>(data); error given is Unterminated string passed in. (2246): {"id":"100000570310973_1810804519209........ (with rest of data in the string data including null chars) following is the shape of classes used in my code: public class FacebookFeed { public string id { get; set; } public NameIdPair from { get; set; } public NameIdPair to { get; set; } public string message { get; set; } public Uri link{get;set;} public string name{get; set;} public string caption { get; set; } public Uri icon { get; set; } public NameLinkPair[] actions { get; set; } public string type { get; set; } public NameIdPair application { get; set; } //Mentioned in Graph API as attribution public DateTime created_time { get; set; } public DateTime updated_time { get; set; } public FacebookPostLikes likes { get; set; } } public class NameIdPair { public string name { get; set; } public string id { get; set; } } public class NameLinkPair { public string name { get; set; } public Uri link{get; set;} } public class FacebookPostLikes { public NameIdPair[] data { get; set; } public int count { get; set; } }

    Read the article

  • Write Parcelable for ArrayList<String []> in android?

    - by sugan.s
    I just created model with String array and array list of string array.Like this public class LookUpModel implements Parcelable { private String [] lookup_header; private ArrayList<String []> loookup_values; public void writeToParcel(Parcel dest, int flags) { dest.writeStringArray(getLookup_header()); }; } I have implemented parcelbale then write for String [] but how to do for the ArrayList<String []> and that values need to pass to another activity.Thanks in advance.

    Read the article

  • How to remove characters from a string?

    - by masato-san
    Hi, Below is interview question so you cannot relay on the functions that predefined in libraries. Also my answer below set the element to null but there is another ways to solve the problem. Given string $string = "This is a pen", remove "is" so that return value is "Th a pen" (including whitespece). I've tried (shown below) but returned value is not correct. Thanks in advance! function remove_delimiter_from_string(&$string, $del) { for($i=0; $i<strlen($string); $i++) { for($j=0; $j<strlen($del); $j++) { if($string[$i] == $del[$j]) { $string[$i] = $string[$i+$j]; //this grabs delimiter :( } } } echo $string . "\n"; }

    Read the article

  • How to Convert Boolean to String

    - by tag
    I have a boolean variable which I want to convert to a string $res = true; I need it the converted value to also be in the format "true" "false" not "0" "1" $converted_res = "true"; $converted_res = "false"; I've tried: $converted_res = string($res); $converted_res = String($res); but it tells me string and String are not recognized functions. How do I convert this boolean to a string in the format "true" or "false" in php?

    Read the article

  • How to get N random string from a {a1|a2|a3} format string?

    - by Pentium10
    Take this string as input: string s="planets {Sun|Mercury|Venus|Earth|Mars|Jupiter|Saturn|Uranus|Neptune}" How would I choose randomly N from the set, then join them with comma. The set is defined between {} and options are separated with | pipe. The order is maintained. Some output could be: string output1="planets Sun, Venus"; string output2="planets Neptune"; string output3="planets Earth, Saturn, Uranus, Neptune"; string output4="planets Uranus, Saturn";// bad example, order is not correct Java 1.5

    Read the article

  • Matching String.

    - by Harikrishna
    I have a string String mainString="///BUY/SELL///ORDERTIME///RT///QTY///BROKERAGE///NETRATE///AMOUNTRS///RATE///SCNM///"; Now I have another strings String str1= "RT"; which should be matched only with RT which is substring of string mainString but not with ORDERTIME which is also substring of string mainString. String str2= "RATE" ; And RATE(str2) should be matched with RATE which is substring of string mainString but not with NETRATE which is also substring of string mainString. How can we do that ?

    Read the article

  • how to use same string in two java files

    - by Palike
    Sorry for my bad English and for maybe stupid question but I'm new in Java. I need use same string in 2 java files for example: In first java file I've got code for sending emails, I've got string set to default email: public String mail = new String ("[email protected]"); and I use this string in code for send email: email.addTo(mail); In second java file something like set up where can user set new email address I want to have same string, connected with string in first java file. When user put new email String mail will be change to new email address and in email.addTo(mail); will be use this new address How can I do this?

    Read the article

  • Is there a word or description for this type of query?

    - by Nick
    We have the requirement to find a result in a collection of records based on a prioritised set of search criteria against a relational db (I'm talking indexed field matching here rather than text search). The way we are thinking about designing the query is to begin with a highly refined and specific set of criteria. If there are no results for this initial query we want to progressively reduce the criteria one by one in order of reducing priority, querying each time such a less specific set of criteria until we find a result we can accept. Alternatively, we have considered starting with a smaller set of criteria and increasing until we have reduced number of results down to the last set. What I would like to know is if an existing term to describe this type of query exists? So that we can look to model our own on existing patterns and use best practice.

    Read the article

  • XML Serializing a class with a Dictionary<string, List<string>> object

    - by Matt
    Is it possible to implement IXmlSerializable and in my XML file capture an object of type Dictionary ? I have the following public class coolio : IXmlSerializable { private int a; private bool b; private string c; private Dictionary<string, List<string>> coco; public coolio(int _a, bool _b, string _c, Dictionary<string, List<string>> _coco) { a=_a; b=_b; c=_c; coco=_coco; } public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void WriteXml(XmlWriter writer) { const string myType = "coolio"; writer.WriteStartElement(myType); writer.WriteAttributeString("a", a.ToString()); writer.WriteAttributeString("b", b.ToString()); writer.WriteAttributeString("c", c); // How do I add a subelement for Dictionary<string, List<string>> coco? writer.WriteEndElement(); } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() != XmlNodeType.Element || reader.LocalName != "coolio") return; a= int.Parse(reader["a"]); b = bool.Parse(reader["b"]); c= reader["c"]; // How do I read subelement into Dictionary<string, List<string>> coco? } } But I am stumped as to how I could add the Dictionary (XML seriliazed to my XML file)

    Read the article

  • Avoiding resource (localizable string) duplication with String.Format

    - by Hrvoje Prgeša
    I'm working on a application (.NET, but not relevant) where there is large potential for resource/string duplication - most of these strings are simple like: Volume: 33 Volume: 33 (dB) Volume 33 dB Volume (dB) Command - Volume: 33 (dB) where X, Y and unit are the same. Should I define a new resource for each of the string or is it preferable to use String.Format to simplify some of these, eg.: String.Format("{0}: {1}", Resource.Volume, 33) String.Format("{0}: {1} {2}", Resource.Volume, 33, Resource.dB) Resource.Volume String.Format("{0} ({1})", 33, Resource.dB) String.Format("{0} ({1})", Resource.Volume, Resource.dB) String.Format("Command - {0}: {1} {2}", Resource.Volume, 33, Resource.dB) I would also define string formats like "{0}: {1}" in the resources so there would be a possibility of reordering words... I would not use this approach selectivly and not throughout the whole application.. And how about: String.Format("{0}: {1}", Volume, Resource.Muted_Volume) // = Volume: Muted Resource.Muted_Volume String.Format("{0}: {1} (by user {2})", Volume, Resource.Muted_Volume, "xy") // = Volume: Muted (by user xy) The advantage is cutting the number of resource by the factor of 4-5. Are there any hidden dangers of using this approach? Could someone give me an example (language) where this would not work correctly?

    Read the article

  • Optimizing a lot of Scanner.findWithinHorizon(pattern, 0) calls

    - by darvids0n
    I'm building a process which extracts data from 6 csv-style files and two poorly laid out .txt reports and builds output CSVs, and I'm fully aware that there's going to be some overhead searching through all that whitespace thousands of times, but I never anticipated converting about about 50,000 records would take 12 hours. Excerpt of my manual matching code (I know it's horrible that I use lists of tokens like that, but it was the best thing I could think of): public static String lookup(List<String> tokensBefore, List<String> tokensAfter) { String result = null; while(_match(tokensBefore)) { // block until all input is read if(id.hasNext()) { result = id.next(); // capture the next token that matches if(_matchImmediate(tokensAfter)) // try to match tokensAfter to this result return result; } else return null; // end of file; no match } return null; // no matches } private static boolean _match(List<String> tokens) { return _match(tokens, true); } private static boolean _match(List<String> tokens, boolean block) { if(tokens != null && !tokens.isEmpty()) { if(id.findWithinHorizon(tokens.get(0), 0) == null) return false; for(int i = 1; i <= tokens.size(); i++) { if (i == tokens.size()) { // matches all tokens return true; } else if(id.hasNext() && !id.next().matches(tokens.get(i))) { break; // break to blocking behaviour } } } else { return true; // empty list always matches } if(block) return _match(tokens); // loop until we find something or nothing else return false; // return after just one attempted match } private static boolean _matchImmediate(List<String> tokens) { if(tokens != null) { for(int i = 0; i <= tokens.size(); i++) { if (i == tokens.size()) { // matches all tokens return true; } else if(!id.hasNext() || !id.next().matches(tokens.get(i))) { return false; // doesn't match, or end of file } } return false; // we have some serious problems if this ever gets called } else { return true; // empty list always matches } } Basically wondering how I would work in an efficient string search (Boyer-Moore or similar). My Scanner id is scanning a java.util.String, figured buffering it to memory would reduce I/O since the search here is being performed thousands of times on a relatively small file. The performance increase compared to scanning a BufferedReader(FileReader(File)) was probably less than 1%, the process still looks to be taking a LONG time. I've also traced execution and the slowness of my overall conversion process is definitely between the first and last like of the lookup method. In fact, so much so that I ran a shortcut process to count the number of occurrences of various identifiers in the .csv-style files (I use 2 lookup methods, this is just one of them) and the process completed indexing approx 4 different identifiers for 50,000 records in less than a minute. Compared to 12 hours, that's instant. Some notes (updated): I don't necessarily need the pattern-matching behaviour, I only get the first field of a line of text so I need to match line breaks or use Scanner.nextLine(). All ID numbers I need start at position 0 of a line and run through til the first block of whitespace, after which is the name of the corresponding object. I would ideally want to return a String, not an int locating the line number or start position of the result, but if it's faster then it will still work just fine. If an int is being returned, however, then I would now have to seek to that line again just to get the ID; storing the ID of every line that is searched sounds like a way around that. Anything to help me out, even if it saves 1ms per search, will help, so all input is appreciated. Thankyou! Usage scenario 1: I have a list of objects in file A, who in the old-style system have an id number which is not in file A. It is, however, POSSIBLY in another csv-style file (file B) or possibly still in a .txt report (file C) which each also contain a bunch of other information which is not useful here, and so file B needs to be searched through for the object's full name (1 token since it would reside within the second column of any given line), and then the first column should be the ID number. If that doesn't work, we then have to split the search token by whitespace into separate tokens before doing a search of file C for those tokens as well. Generalised code: String field; for (/* each record in file A */) { /* construct the rest of this object from file A info */ // now to find the ID, if we can List<String> objectName = new ArrayList<String>(1); objectName.add(Pattern.quote(thisObject.fullName)); field = lookup(objectSearchToken, objectName); // search file B if(field == null) // not found in file B { lookupReset(false); // initialise scanner to check file C objectName.clear(); // not using the full name String[] tokens = thisObject.fullName.split(id.delimiter().pattern()); for(String s : tokens) objectName.add(Pattern.quote(s)); field = lookup(objectSearchToken, objectName); // search file C lookupReset(true); // back to file B } else { /* found it, file B specific processing here */ } if(field != null) // found it in B or C thisObject.ID = field; } The objectName tokens are all uppercase words with possible hyphens or apostrophes in them, separated by spaces. Much like a person's name. As per a comment, I will pre-compile the regex for my objectSearchToken, which is just [\r\n]+. What's ending up happening in file C is, every single line is being checked, even the 95% of lines which don't contain an ID number and object name at the start. Would it be quicker to use ^[\r\n]+.*(objectname) instead of two separate regexes? It may reduce the number of _match executions. The more general case of that would be, concatenate all tokensBefore with all tokensAfter, and put a .* in the middle. It would need to be matching backwards through the file though, otherwise it would match the correct line but with a huge .* block in the middle with lots of lines. The above situation could be resolved if I could get java.util.Scanner to return the token previous to the current one after a call to findWithinHorizon. I have another usage scenario. Will put it up asap.

    Read the article

  • SQL SERVER – SQL in Sixty Seconds – 5 Videos from Joes 2 Pros Series – SQL Exam Prep Series 70-433

    - by pinaldave
    Joes 2 Pros SQL Server Learning series is indeed fun. Joes 2 Pros series is written for beginners and who wants to build expertise for SQL Server programming and development from fundamental. In the beginning of the series author Rick Morelan is not shy to explain the simplest concept of how to open SQL Server Management Studio. Honestly the book starts with that much basic but as it progresses further Rick discussing about various advanced concepts from query tuning to Core Architecture. This five part series is written with keeping SQL Server Exam 70-433. Instead of just focusing on what will be there in exam, this series is focusing on learning the important concepts thoroughly. This book no way take short cut to explain any concepts and at times, will go beyond the topic at length. The best part is that all the books has many companion videos explaining the concepts and videos. Every Wednesday I like to post a video which explains something in quick few seconds. Today we will go over five videos which I posted in my earlier posts related to Joes 2 Pros series. Introduction to XML Data Type Methods – SQL in Sixty Seconds #015 The XML data type was first introduced with SQL Server 2005. This data type continues with SQL Server 2008 where expanded XML features are available, most notably is the power of the XQuery language to analyze and query the values contained in your XML instance. There are five XML data type methods available in SQL Server 2008: query() – Used to extract XML fragments from an XML data type. value() – Used to extract a single value from an XML document. exist() – Used to determine if a specified node exists. Returns 1 if yes and 0 if no. modify() – Updates XML data in an XML data type. node() – Shreds XML data into multiple rows (not covered in this blog post). [Detailed Blog Post] | [Quiz with Answer] Introduction to SQL Error Actions – SQL in Sixty Seconds #014 Most people believe that when SQL Server encounters an error severity level 11 or higher the remaining SQL statements will not get executed. In addition, people also believe that if any error severity level of 11 or higher is hit inside an explicit transaction, then the whole statement will fail as a unit. While both of these beliefs are true 99% of the time, they are not true in all cases. It is these outlying cases that frequently cause unexpected results in your SQL code. To understand how to achieve consistent results you need to know the four ways SQL Error Actions can react to error severity levels 11-16: Statement Termination – The statement with the procedure fails but the code keeps on running to the next statement. Transactions are not affected. Scope Abortion – The current procedure, function or batch is aborted and the next calling scope keeps running. That is, if Stored Procedure A calls B and C, and B fails, then nothing in B runs but A continues to call C. @@Error is set but the procedure does not have a return value. Batch Termination – The entire client call is terminated. XACT_ABORT – (ON = The entire client call is terminated.) or (OFF = SQL Server will choose how to handle all errors.) [Detailed Blog Post] | [Quiz with Answer] Introduction to Basics of a Query Hint – SQL in Sixty Seconds #013 Query hints specify that the indicated hints should be used throughout the query. Query hints affect all operators in the statement and are implemented using the OPTION clause. Cautionary Note: Because the SQL Server Query Optimizer typically selects the best execution plan for a query, it is highly recommended that hints be used as a last resort for experienced developers and database administrators to achieve the desired results. [Detailed Blog Post] | [Quiz with Answer] Introduction to Hierarchical Query – SQL in Sixty Seconds #012 A CTE can be thought of as a temporary result set and are similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. A CTE is generally considered to be more readable than a derived table and does not require the extra effort of declaring a Temp Table while providing the same benefits to the user. However; a CTE is more powerful than a derived table as it can also be self-referencing, or even referenced multiple times in the same query. A recursive CTE requires four elements in order to work properly: Anchor query (runs once and the results ‘seed’ the Recursive query) Recursive query (runs multiple times and is the criteria for the remaining results) UNION ALL statement to bind the Anchor and Recursive queries together. INNER JOIN statement to bind the Recursive query to the results of the CTE. [Detailed Blog Post] | [Quiz with Answer] Introduction to SQL Server Security – SQL in Sixty Seconds #011 Let’s get some basic definitions down first. Take the workplace example where “Tom” needs “Read” access to the “Financial Folder”. What are the Securable, Principal, and Permissions from that last sentence? A Securable is a resource that someone might want to access (like the Financial Folder). A Principal is anything that might want to gain access to the securable (like Tom). A Permission is the level of access a principal has to a securable (like Read). [Detailed Blog Post] | [Quiz with Answer] Please leave a comment explain which one was your favorite video as that will help me understand what works and what needs improvement. Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology, Video

    Read the article

  • Using Query Classes With NHibernate

    - by Liam McLennan
    Even when using an ORM, such as NHibernate, the developer still has to decide how to perform queries. The simplest strategy is to get access to an ISession and directly perform a query whenever you need data. The problem is that doing so spreads query logic throughout the entire application – a clear violation of the Single Responsibility Principle. A more advanced strategy is to use Eric Evan’s Repository pattern, thus isolating all query logic within the repository classes. I prefer to use Query Classes. Every query needed by the application is represented by a query class, aka a specification. To perform a query I: Instantiate a new instance of the required query class, providing any data that it needs Pass the instantiated query class to an extension method on NHibernate’s ISession type. To query my database for all people over the age of sixteen looks like this: [Test] public void QueryBySpecification() { var canDriveSpecification = new PeopleOverAgeSpecification(16); var allPeopleOfDrivingAge = session.QueryBySpecification(canDriveSpecification); } To be able to query for people over a certain age I had to create a suitable query class: public class PeopleOverAgeSpecification : Specification<Person> { private readonly int age; public PeopleOverAgeSpecification(int age) { this.age = age; } public override IQueryable<Person> Reduce(IQueryable<Person> collection) { return collection.Where(person => person.Age > age); } public override IQueryable<Person> Sort(IQueryable<Person> collection) { return collection.OrderBy(person => person.Name); } } Finally, the extension method to add QueryBySpecification to ISession: public static class SessionExtensions { public static IEnumerable<T> QueryBySpecification<T>(this ISession session, Specification<T> specification) { return specification.Fetch( specification.Sort( specification.Reduce(session.Query<T>()) ) ); } } The inspiration for this style of data access came from Ayende’s post Do You Need a Framework?. I am sick of working through multiple layers of abstraction that don’t do anything. Have you ever seen code that required a service layer to call a method on a repository, that delegated to a common repository base class that wrapped and ORMs unit of work? I can achieve the same thing with NHibernate’s ISession and a single extension method. If you’re interested you can get the full Query Classes example source from Github.

    Read the article

  • bind would not work unless allow-query is "any"

    - by adrianTNT
    I have this in /etc/named.conf, I commented the default values and set my own under it. My domain would not load in browser unless I set allow-query to "any", is this OK, what should I edit? If is localhost or 127.0.0.1; 10.0.1.0/24; domain would not load. I tried the 127.. thing because it mentioned it here: http://wiki.mandriva.com/en/Testing:Bind Bind version is 9.7.0-P2-RedHat-9.7.0-5.P2.el6_0.1 OS is CentOS 6.0. options { // listen-on port 53 { 127.0.0.1; }; listen-on port 53 { any; }; //listen-on-v6 port 53 { ::1; }; listen-on-v6 port 53 { any; }; directory "/var/named"; dump-file "/var/named/data/cache_dump.db"; statistics-file "/var/named/data/named_stats.txt"; memstatistics-file "/var/named/data/named_mem_stats.txt"; //allow-query { localhost; }; allow-query { any; }; recursion yes; dnssec-enable yes; dnssec-validation yes; dnssec-lookaside auto; /* Path to ISC DLV key */ bindkeys-file "/etc/named.iscdlv.key"; };

    Read the article

  • MySQL query cache and PHP variables

    - by Saif Bechan
    I have seen the following statement made about the query cache: // query cache does NOT work $r = mysql_query("SELECT username FROM user WHERE signup_date >= CURDATE()"); // query cache works! $today = date("Y-m-d"); $r = mysql_query("SELECT username FROM user WHERE signup_date >= '$today'"); So the query cache only works on the second query. I was wondering if the query cache will also work on this: define('__TODAY',date("Y-m-d")); $r = mysql_query("SELECT username FROM user WHERE signup_date >= '".__TODAY."'");

    Read the article

  • ADO.NET Commands and SQL query plans

    - by ingredient_15939
    I've been reading up on query plans and how to minimise duplicate plans being created by SQL Server for the same basic query. For example, if I understand correctly, sending both these query strings will result in 2 different query plans: "SELECT FirstName FROM Members WHERE LastName = 'Lee'" "SELECT FirstName FROM Members WHERE LastName = 'MacGhilleseatheanaich'" Using a stored procedure avoids this, as the query plan is the same, and "LastName" is passed as a variable, eg: CREATE PROCEDURE sp_myStoredProcedure @LastName varchar(100) AS SELECT FirstName FROM Members WHERE LastName = @LastName Go Now, my question is whether the same applies to the Command object (eg. SQLClient.SQLCommand in ADO.NET). The reason I ask is that string parameters don't have a defined max length, as in the code above. Take the following code: MyCmd.CommandText = "SELECT FirstName FROM Members WHERE LastName = @LastName" MyCmd.Parameters.AddWithValue("@LastName", "Lee") Then later: MyCmd.Parameters.Clear() MyCmd.Parameters.AddWithValue("@LastName", "MacGhilleseatheanaich") Since @LastName hasn't been declared to SQL Server as having a defined maximum length, will SQL Server create a new query plan for every different value when I execute the command this way?

    Read the article

  • rewritten mysql query returning unexpected results, trying to figure out why

    - by dq
    I created a messy query in a hurry a while ago to get a list of product codes. I am now trying to clean up my tables and my code. I recently tried to rewrite the query in order for it to be easier to use and understand. The original query works great, but it requires multiple search strings in order to do one search because it uses UNIONS, and it has a few other issues. My newly modified query is easier to understand, and only requires one search string, but is returning different results. Basically the new query is leaving records out, and I would like to understand why, and how to fix it. Here are the two queries (search strings are all null): Original Query: $query = 'SELECT product_code FROM bus_warehouse_lots WHERE status=\'2\''.$search_string_1 .' UNION SELECT product_code FROM bus_po WHERE status=\'0\''.$search_string_2 .' UNION SELECT bus_warehouse_entries.new_product_code AS product_code FROM (bus_warehouse_entries LEFT JOIN bus_warehouse_transfers ON bus_warehouse_entries.picking_ticket_num=bus_warehouse_transfers.pt_number) LEFT JOIN bus_warehouse_lots ON bus_warehouse_entries.ebooks_lot_id=bus_warehouse_lots.id WHERE bus_warehouse_entries.type=\'6\' AND bus_warehouse_transfers.status=\'0\''.$search_string_3 .' UNION SELECT bus_contracts.main_product AS product_code FROM bus_contracts LEFT JOIN bus_warehouse_lots ON bus_contracts.main_product=bus_warehouse_lots.product_code WHERE bus_contracts.status=\'0\''.$search_string_4 .' UNION SELECT prod_id AS product_code FROM bus_products WHERE last_usage > \''.date('Y-m-d', strtotime('-12 months')).'\''.$search_string_5 .' ORDER BY product_code'; New Query: $query = 'SELECT bus_products.prod_id FROM bus_products' .' LEFT JOIN (bus_warehouse_lots, bus_po, bus_warehouse_entries, bus_contracts) ON (' .'bus_products.prod_id = bus_warehouse_lots.product_code' .' AND bus_products.prod_id = bus_po.product_code' .' AND bus_products.prod_id = bus_warehouse_entries.new_product_code' .' AND bus_products.prod_id = bus_contracts.main_product)' .' LEFT JOIN bus_warehouse_transfers ON' .' bus_warehouse_entries.picking_ticket_num = bus_warehouse_transfers.pt_number' .' WHERE (bus_products.last_usage > \''.date('Y-m-d', strtotime('-12 months')).'\'' .' OR bus_warehouse_lots.status = \'2\'' .' OR bus_po.status = \'0\'' .' OR (bus_warehouse_entries.type = \'6\' AND bus_warehouse_transfers.status = \'0\')' .' OR bus_contracts.status = \'0\')' .$search_string_6 .' GROUP BY bus_products.prod_id' .' ORDER BY bus_products.prod_id';

    Read the article

  • SQL query duration is longer for smaller dataset?

    - by entens
    I received reports that a my report generating application was not working. After my initial investigation, I found that the SQL transaction was timing out. I'm mystified as to why the query for a smaller selection of items would take so much longer to return results. Quick query (averages 4 seconds to return): SELECT * FROM Payroll WHERE LINEDATE >= '04-17-2010'AND LINEDATE <= '04-24-2010' ORDER BY 'EMPLYEE_NUM' ASC, 'OP_CODE' ASC, 'LINEDATE' ASC Long query (averages 1 minute 20 seconds to return): SELECT * FROM Payroll WHERE LINEDATE >= '04-18-2010'AND LINEDATE <= '04-24-2010' ORDER BY 'EMPLYEE_NUM' ASC, 'OP_CODE' ASC, 'LINEDATE' ASC I could simply increase the timeout on the SqlCommand, but it doesn't change the fact the query is taking longer than it should. Why would requesting a subset of the items take longer than the query that returns more data? How can I optimize this query?

    Read the article

  • AdvancedFormatProvider: Making string.format do more

    - by plblum
    When I have an integer that I want to format within the String.Format() and ToString(format) methods, I’m always forgetting the format symbol to use with it. That’s probably because its not very intuitive. Use {0:N0} if you want it with group (thousands) separators. text = String.Format("{0:N0}", 1000); // returns "1,000"   int value1 = 1000; text = value1.ToString("N0"); Use {0:D} or {0:G} if you want it without group separators. text = String.Format("{0:D}", 1000); // returns "1000"   int value2 = 1000; text2 = value2.ToString("D"); The {0:D} is especially confusing because Microsoft gives the token the name “Decimal”. I thought it reasonable to have a new format symbol for String.Format, "I" for integer, and the ability to tell it whether it shows the group separators. Along the same lines, why not expand the format symbols for currency ({0:C}) and percent ({0:P}) to let you omit the currency or percent symbol, omit the group separator, and even to drop the decimal part when the value is equal to the whole number? My solution is an open source project called AdvancedFormatProvider, a group of classes that provide the new format symbols, continue to support the rest of the native symbols and makes it easy to plug in additional format symbols. Please visit https://github.com/plblum/AdvancedFormatProvider to learn about it in detail and explore how its implemented. The rest of this post will explore some of the concepts it takes to expand String.Format() and ToString(format). AdvancedFormatProvider benefits: Supports {0:I} token for integers. It offers the {0:I-,} option to omit the group separator. Supports {0:C} token with several options. {0:C-$} omits the currency symbol. {0:C-,} omits group separators, and {0:C-0} hides the decimal part when the value would show “.00”. For example, 1000.0 becomes “$1000” while 1000.12 becomes “$1000.12”. Supports {0:P} token with several options. {0:P-%} omits the percent symbol. {0:P-,} omits group separators, and {0:P-0} hides the decimal part when the value would show “.00”. For example, 1 becomes “100 %” while 1.1223 becomes “112.23 %”. Provides a plug in framework that lets you create new formatters to handle specific format symbols. You register them globally so you can just pass the AdvancedFormatProvider object into String.Format and ToString(format) without having to figure out which plug ins to add. text = String.Format(AdvancedFormatProvider.Current, "{0:I}", 1000); // returns "1,000" text2 = String.Format(AdvancedFormatProvider.Current, "{0:I-,}", 1000); // returns "1000" text3 = String.Format(AdvancedFormatProvider.Current, "{0:C-$-,}", 1000.0); // returns "1000.00" The IFormatProvider parameter Microsoft has made String.Format() and ToString(format) format expandable. They each take an additional parameter that takes an object that implements System.IFormatProvider. This interface has a single member, the GetFormat() method, which returns an object that knows how to convert the format symbol and value into the desired string. There are already a number of web-based resources to teach you about IFormatProvider and the companion interface ICustomFormatter. I’ll defer to them if you want to dig more into the topic. The only thing I want to point out is what I think are implementation considerations. Why GetFormat() always tests for ICustomFormatter When you see examples of implementing IFormatProviders, the GetFormat() method always tests the parameter against the ICustomFormatter type. Why is that? public object GetFormat(Type formatType) { if (formatType == typeof(ICustomFormatter)) return this; else return null; } The value of formatType is already predetermined by the .net framework. String.Format() uses the StringBuilder.AppendFormat() method to parse the string, extracting the tokens and calling GetFormat() with the ICustomFormatter type. (The .net framework also calls GetFormat() with the types of System.Globalization.NumberFormatInfo and System.Globalization.DateTimeFormatInfo but these are exclusive to how the System.Globalization.CultureInfo class handles its implementation of IFormatProvider.) Your code replaces instead of expands I would have expected the caller to pass in the format string to GetFormat() to allow your code to determine if it handles the request. My vision would be to return null when the format string is not supported. The caller would iterate through IFormatProviders until it finds one that handles the format string. Unfortunatley that is not the case. The reason you write GetFormat() as above is because the caller is expecting an object that handles all formatting cases. You are effectively supposed to write enough code in your formatter to handle your new cases and call .net functions (like String.Format() and ToString(format)) to handle the original cases. Its not hard to support the native functions from within your ICustomFormatter.Format function. Just test the format string to see if it applies to you. If not, call String.Format() with a token using the format passed in. public string Format(string format, object arg, IFormatProvider formatProvider) { if (format.StartsWith("I")) { // handle "I" formatter } else return String.Format(formatProvider, "{0:" + format + "}", arg); } Formatters are only used by explicit request Each time you write a custom formatter (implementer of ICustomFormatter), it is not used unless you explicitly passed an IFormatProvider object that supports your formatter into String.Format() or ToString(). This has several disadvantages: Suppose you have several ICustomFormatters. In order to have all available to String.Format() and ToString(format), you have to merge their code and create an IFormatProvider to return an instance of your new class. You have to remember to utilize the IFormatProvider parameter. Its easy to overlook, especially when you have existing code that calls String.Format() without using it. Some APIs may call String.Format() themselves. If those APIs do not offer an IFormatProvider parameter, your ICustomFormatter will not be available to them. The AdvancedFormatProvider solves the first two of these problems by providing a plug-in architecture.

    Read the article

  • Too many Bind query (cache) denied, DNS attack?

    - by Jake
    Once Bind crashed and I did: tail -f /var/log/messages I see a massive number of logs every second. Is this a DNS attack? or is there something wrong? Sometimes I see a domain in logs like this: dOmAin.com (upper and lower). As you see there is only one single domain in the logs with different IPs Oct 10 02:21:26 mail named[20831]: client 74.125.189.18#38921: query (cache) 'ns1.domain2.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 192.221.144.171#38833: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 74.125.189.17#42428: query (cache) 'ns2.domain2.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 192.221.146.27#37899: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 193.203.82.66#39263: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 8.0.16.170#59723: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 80.169.197.66#32903: query (cache) 'dOmAin.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 134.58.60.1#47558: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 192.221.146.34#47387: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 8.0.16.8#59392: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 74.125.189.19#64395: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 217.72.163.3#42190: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 83.146.21.252#22020: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 192.221.146.116#57342: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 193.203.82.66#52020: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 8.0.16.72#64317: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 80.169.197.66#31989: query (cache) 'dOmAin.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 74.125.189.18#47436: query (cache) 'ns2.domain2.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 74.125.189.16#44005: query (cache) 'ns1.domain2.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 85.132.31.10#50379: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 94.241.128.3#60106: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 85.132.31.10#59118: query (cache) 'domain.com/A/IN' denied Oct 10 02:21:26 mail named[20831]: client 212.95.135.78#27811: query (cache) 'domain.com/A/IN' denied /etc/resolv.conf ; generated by /sbin/dhclient-script nameserver 4.2.2.4 nameserver 8.8.4.4 Bind config: // generated by named-bootconf.pl options { directory "/var/named"; /* * If there is a firewall between you and nameservers you want * to talk to, you might need to uncomment the query-source * directive below. Previous versions of BIND always asked * questions using port 53, but BIND 8.1 uses an unprivileged * port by default. */ // query-source address * port 53; allow-transfer { none; }; allow-recursion { localnets; }; //listen-on-v6 { any; }; notify no; }; // // a caching only nameserver config // controls { inet 127.0.0.1 allow { localhost; } keys { rndckey; }; }; zone "." IN { type hint; file "named.ca"; }; zone "localhost" IN { type master; file "localhost.zone"; allow-update { none; }; }; zone "0.0.127.in-addr.arpa" IN { type master; file "named.local"; allow-update { none; }; };

    Read the article

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