w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
get a list of comma separated values in python and use that list to perform a command as many times as necessary with each value
You can use a for loop to loop over a dict object and create multiple pages. Here is a little snippet to get you started. import gdata.sites.client client = gdata.sites.client.SitesClient( source=SOURCE_APP_NAME, site=site_name, domain=site_domain) pages = {"page_1":'<b>Your html content</b>', "page_2":'<b>Your other html content</b>'} for title, content in pages.items(): feed = client.GetContentFeed() parent = None if selection is not None: parent = feed.entry[selection - 1] client.CreatePage('webpage', page_title, content, parent=parent) as for feeding your script from an external source I would recommend something like a csv file ##if you have a csv file called pages.csv with the following lines ##page_1,<b>

Categories : Python

Return comma separated list of names from comma separate list of IDs
Do 2 separate queries, one of the Personnel tables and one of Techniques. Process the Techniques query result into an associative array, where the index is the ID, and the value is the Name. When outputting the Personnel.Technique_ID field, process the comma separated value as a list. Loop through each item in the list, and output the value of the Techniques associative array.

Categories : Sql Server

PHP MYSQL - Search comma separated list with a comma separated list
Have a read of these: Many-to-many data model Junction table Implementing this, as opposed to comma-separated values, should probably save you and your coworkers a lot of headache and simplify your queries, effectively eliminating the need of complex queries. It should be faster, too.

Categories : PHP

Convert string in list objects to comma separated
Override the toString() method in the Employee class public String toString() { return name; } Then, print the list: String listToString = empList.toString(); System.out.println(listToString.substring(1, listToString.length() - 1)); This is not that sophisticated way to print it, but I doesn't involve the usage of third-party libraries. If you'd like to use third party libraries, here are several way you can print the list. // Using Guava String guavaVersion = Joiner.on(", ").join(items); // Using Commons / Lang String commonsLangVersion = StringUtils.join(items, ", ");

Categories : Java

How can I parse this list of comma separated values
for perm in listOfPermissions: user, perms = perm.split(',', 1) for p in perms: print "%s, %s" %(user, p) To write this to a file: with open('path/to/file', 'w') as outfile: for perm in listOfPermissions: user, perms = perm.split(',', 1) for p in perms: outfile.write("%s, %s " %(user, p))

Categories : Python

Why does Python operator.itemgetter work given a comma separated list of numbers as indices, but not when the same list is packaged in a variable?
This isn't about itemgetter, but about function calling syntax. These are different things: operator.itemgetter(1, 3, 5) operator.itemgetter((1, 3, 5)) The first one gets you item #1, item #3, and item #5. The second one gets you item #(1, 3, 5). (Which may make sense for a dictionary, but not for a list.) The second one is what you get when you use itemgetter(columns). So, how do you get the first? operator.itemgetter(*columns) That's it. See Unpacking Argument Lists in the tutorial for more information.

Categories : Python

How to display a comma or semicolon separated list of values
Just use <ui:repeat>. You can use varStatus to reference an iteration status instance which has among others a boolean last property which is helpful in omitting the comma from the last item. <ui:repeat value="#{listOfStrings}" var="string" varStatus="loop"> #{string}#{not loop.last ? ', ' : ''} </ui:repeat>

Categories : JSF

How can I convert values from one column into a quoted, comma-separated list?
Try This declare @formattdstring varchar(100) set @formattdstring='' select @formattdstring=@formattdstring+'"'+ Code +'",' from Table1 select '['+@formattdstring+']' as formattedstring Cheers!!!

Categories : Sql Server

Regex to match comma separated list with no comma on the end
Try using this pattern: ^([0-9]+,)*[0-9]+$ You can test it here.

Categories : C#

Comma separated list in twig
Don't know about shortest but this could be clear. Try the following to add comma after all lines in the loop except the last one: {% for role in user.roles %} {{ role.name }} {% if not loop.last %},{% endif %} {% endfor %}

Categories : PHP

Sort comma separated list Alphabetically PHP
Try this: $xyz="Europe, France, Italy, Spain, UK, US,Nordic, West Europe, Belgium, Luxembourg, Netherlands, Sweden,US,Asia, Europe, Israel, North America, India,North America, , China, Hong Kong,West North Central, West South Central,UK,East South Central,Middle Atlantic, Greater China, Malaysia, Singapore, Taiwan, Middle Atlantic, Global, Australasia, Central and East Europe"; $arr = explode(',', $xyz); asort($arr); print_r($arr);

Categories : PHP

Comma separated list from array with "and" before last element
Remove the last element from the list, implode what's left with commas and then concatenate "and last_element": $last = array_pop($number_list); $output = implode(', ', $number_list); if ($output) { $output =. ', and '; } $output .= $last; If you prefer, you can also write the above more tersely as $last = array_pop($number_list); $output = $number_list ? implode(', ', $number_list).', and '.$last : $last; Update: I have to admit I initially misread the question and thought that it was about replacing the last comma with "and", not adding an "and" before the final item. I have since edited the answer to target the latter scenario. Note that the code can be easily adapted to do either by selecting " and " or ", and " for the "glue" string respectively.

Categories : PHP

Store enum as comma separated list
What's wrong with part.MyProperty = Enum.GetNames(typeof(Choices)); ? To get a comma separated list, use String.Join: string csvEnums = string.Join(",", Enum.GetNames(typeof(Choices)));

Categories : Asp Net Mvc

jsrender iterate over list separated by comma
http://msdn.microsoft.com/en-us/magazine/hh975379.aspx On the section "converters" you will find a suitable way to do it

Categories : Misc

Find manager in a comma-separated list
In a WHERE clasue a = operator looks for an exact match. You can use a LIKE with wildcards for a partial match. where Manager LIKE '%Jim%'

Categories : SQL

Find primary key from one table in comma separated list
Using this function Create FUNCTION F_SplitAsIntTable ( @txt varchar(max) ) RETURNS @tab TABLE ( ID int ) AS BEGIN declare @i int declare @s varchar(20) Set @i = CHARINDEX(',',@txt) While @i>1 begin set @s = LEFT(@txt,@i-1) insert into @tab (id) values (@s) Set @txt=RIGHT(@txt,Len(@txt)-@i) Set @i = CHARINDEX(',',@txt) end insert into @tab (id) values (@txt) RETURN END You can query like this declare @a Table (id int,Name varchar(10),Kind Varchar(100)) insert into @a values (1,'test','1,2,3,4'),(2,'test2','1,2,3,5'),(3,'test3','3,5') Select a.ID,Name from @a a cross apply F_SplitAsIntTable(a.Kind) b where b.ID=2

Categories : Sql Server

Split comma-separated list and prepend character to each value
Use the + operator and join: for(var i = 0; i < str_array.length; i++) { str_array[i] = 'a' + str_array[i]; } var out_str = str_array.join(' '); Replace 'a' with whatever character you wish to prepend.

Categories : Javascript

Intersection operation on a list of comma separated string
I don't know about "less memory utilization", but my first shot at this would be something along these lines (untested, coded in browser, no Visual Studio handy yadda yadda): Dictionary<int,int> occurences = new Dictionary<int,int>(); int numberOfLists = YourCollectionOfOuterLists.Count; foreach (string list in YourCollectionOfOuterLists) { foreach (string value in list.Split(',')) { occurences[value] = ((occurences[value] as int) ?? 0) + 1; } } List<int> output = new List<int>(); foreach (int key in occurences.Keys) { if (occurences[key] == numberOfLists) { output.Add(key); } } return String.Join(output.Select(x => x.ToString()), ","); It might very well be possible to write the code more tersely, but anything that accomplis

Categories : C#

Mysql: Look for specific letter in comma separated list
Use FIND_IN_SET for matching comma-separated values: select * from TableName where FIND_IN_SET("c", column)

Categories : Mysql

Getting unique values from a list of objects with a List as a property
If I understand, you want a list of all of the unique certifications among all of the employees. This would be a job for SelectMany: var uniqueCerts = empList.SelectMany(e => e.Certifications).Distinct().ToList();

Categories : C#

How do i pass a comma separated list of numbers to my MYSQL as a string
You need to enclose $scores_csv variable between quotes. Try this: $sql="INSERT INTO $db_name.$tbl_name (`game_id` ,`user_id` ,`scores`) VALUES (NULL , $session_id, '$scores_csv')";

Categories : PHP

Convert List To Comma Separated MySQL Insert Statements
String.Join(",", models.Select(m => String.Format("({0},{1},{2})", m.ModelId, m.Name, m.Enabled))); That will give you string with False and True as Enabled values. If you want Enabled and Disabled instead, then use: m.Enabled ? "Enabled" : "Disabled" when formatting model string. Full sample (with NBuilder used to create sample models): IEnumerable<Model> models = Builder<Model>.CreateListOfSize(3).Build(); Func<Model, string> formatModel = m => String.Format("({0},{1},{2})", m.ModelId, m.Name, m.Enabled); string result = String.Join(",", models.Select(formatModel)); Output: (1,Name1,False),(2,Name2,True),(3,Name3,False)

Categories : C#

xslt to create comma-separated list from node attributes
If you can switch to XSLT 2, it becomes trivial. Replace <xsl:value-of select="Product/@skn"/> with <xsl:value-of select="Product/@skn" separator=","/>

Categories : Xslt

Emacs: convert items on separate lines to a comma-separated list
M-q would replace linebreaks with spaces (in reasonably short lists of short words) but won't add quotes and commas. Or, maybe M-^ many times, until you have them all on the same line. Other than that - nothing built in comes to mind. Obviously, a keyboard macro is a good candidate for this. But a faster way, that doesn't create many undo steps would be something along these lines: (defun lines-to-cslist (start end &optional arg) (interactive "r P") (let ((insertion (mapconcat (lambda (x) (format ""%s"" x)) (split-string (buffer-substring start end)) ", "))) (delete-region start end) (insert insertion) (when arg (forward-char (length insertion)))))

Categories : Emacs

Find and replace comma-separated strings to Cassandra list format in VIM
Try this :%s/v(".*)@<=s*([^,"]+)s*(.*")@=/'2'/g :%s/"/"[ :%s/"[@!/]" Or all at once :%s/v(".*)@<=s*([^,"]+)s*(.*")@=/'2'/ge | %s/"/"[/e | %s/"[@!/]" This works on the example. This will not work if there more than one pair of quotes on the line. Explanation :%s/v(".*)@<=s*([^,"]+)s*(.*")@=/'2'/g This looks for a string that has a quote before and after it with lookaheads and lookbehinds. Then we capture everything that isn't a comma or a quote and replace it with the captured part in single quotes. This throws out any leading or trailing spaces. :%s/"/"[ This should be self explanatory if you have used :s before :%s/"[@!/]" This uses a negative lookahead to find the first quote that isn't followed by a left bracket and replaces it with a right bracket and a quote.

Categories : Regex

Setting up a CoreData regular expression predicate for a comma-separated list
This is solved with this code: NSString *format = @"(maps MATCHES %@) OR (maps == '')"; NSString *pattern = [NSString stringWithFormat:@".*(\b%@\b).*", _map.mapID]; NSPredicate *predicate = [NSPredicate predicateWithFormat:format, pattern]; I was assuming the format of the predicate was the same as formatting a string, which is not. I was enlightened by this other answer: http://stackoverflow.com/a/12672462/189292

Categories : Objective C

Parse comma-separated string to make IN List of strings in the Where clause
Try this one - DDL: CREATE TABLE dbo.Table1 ( [EmpId] INT , [FirstName] VARCHAR(7) , [LastName] VARCHAR(10) , [domain] VARCHAR(6) , [Vertical] VARCHAR(10) , [Account] VARCHAR(50) , [City] VARCHAR(50) ) INSERT INTO dbo.Table1 ([EmpId], [FirstName], [LastName], [Vertical], [Account], [domain], [City]) VALUES (345, 'Priya', 'Palanisamy', 'DotNet', 'LS', 'Abbott', 'Chennai'), (346, 'Kavitha', 'Amirtharaj', 'DotNet', 'CG', 'Diageo', 'Chennai'), (647, 'Kala', 'Haribabu', 'DotNet', 'DotNet', 'IMS', 'Chennai') Query: DECLARE @Account VARCHAR(200) SELECT @Account = 'CG,LS' SELECT * FROM Table1 WHERE [Vertical] = 'DotNet' AND (ISNULL(@Account, '') = '' OR Account IN ( SELECT t.c.value('.', 'VARCHAR(20)') FROM ( SELECT x = CAST('

Categories : SQL

Unmarshall xml list of objects to java list without class list
You could use JAXB with StAX to do the following: import java.util.*; import javax.xml.bind.*; import javax.xml.stream.*; import javax.xml.transform.stream.StreamSource; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(User.class); XMLInputFactory xif = XMLInputFactory.newFactory(); StreamSource xml = new StreamSource("src/forum17047306/input.xml"); XMLStreamReader xsr = xif.createXMLStreamReader(xml); List<User> users = new ArrayList<User>(); Unmarshaller unmarshaller = jc.createUnmarshaller(); while(xsr.getEventType() != XMLStreamReader.END_DOCUMENT) { if(xsr.isStartElement() && "User".equals(xsr.getLocalName())) {

Categories : Java

Getting a list of values from a list of dict in python: Without using list comprehension
You could use map() here. map() applies the lambda to every item of testList and returns it as a list. >>> testList = [{'id': 1L, 'name': u'Library'}, {'id': 2L, 'name': u'Arts'}, {'id': 3L, 'name': u'Sports'}] >>> map(lambda x: x['name'], testList) [u'Library', u'Arts', u'Sports']

Categories : Python

Error converting an object list to tag list with dynamic UI in shiny
I would guess one problem is that the plot_output_list should not be indexed by strings, but instead by number, i.e. plot_output_list[[symbol]] <- ... should be plot_output_list[[i]] <- ...; i <- i + 1 If that doesn't work, try running traceback() right after you hit the error so we can see where the error comes from.

Categories : R

How to write regex to verify a comma delimited list of values
Try this: ^[-ws]+(?:,[-ws]*)*$ Using ^ and $ ensures that we validate the entire value, and don't just find a match somewhere within. The first character class, [-ws]+ allows one or more alphanumeric, whitespace, or dash characters. The dash should go first in the class brackets. The second group allows zero or more repetitions with separating commas. It is wrapped in non-capturing parentheses, a small performance optimization: (?: … )* Notes: This expression allows empty entries, such as A,B,,D. If you don't want to allow this, change the second-to-last * to a +. The w shorthand allows underscores. To prevent this, replace them with A-Za-z0-9.

Categories : Regex

Converting JSON returned from ASMX service to list of C# objects
Thanks to Brian Rogers and Tanim Salem (see comments above) I did change the web service so that it not double serialized. I can now simplify the code to something like this: private static JArray ConvertToJsonArray(string json) { var jsonObject = JObject.Parse(json); return (JArray)jsonObject["d"]; } And then convert it to my list of objects using: private static IList<ThirdPartyClaim> ConvertJsonArrayToListOfClaims(JArray jsonArray) { return JsonConvert.DeserializeObject<List<ThirdPartyClaim>>(jsonArray.ToString()); } Any other comments or improvements would be appreciated.

Categories : C#

Converting an integer list into a string list
You can use List Comprehension: >>> my_list = [1, 2, 3, 4] >>> [str(v) for v in my_list] ['1', '2', '3', '4'] or map(): >>> str_list = map(str, my_list) >>> str_list ['1', '2', '3', '4'] In Python 3, you would need to use - list(map(str, my_list)) For 2nd part, you can use join(): >>> ''.join(str_list) '1234' And please don't name your list list. It shadows the built-in list.

Categories : Python

converting a list with strings into a list with floats
You can convert string to float using float() function import csv with open ('data.txt', 'r') as f: col_one = [float(row[0]) for index, row in enumerate(csv.reader(f, delimiter= ' ')) if index != 0]

Categories : Python

How to convert list of group-by objects into html unordered list in Java?
public String convertToHTML(ArrayList<CountData> stuffs){ StringBuilder sb = new StringBuilder() sb.append(“<ul> ”); for(CountData cd : stuffs){ sb.append(“<li>”+cd.getCountry()+” (“+cd.getCount()+”) ”); sb.append(“ <ul>); sb.append(“ <li>”+cd.getState()+” (“+cd.getCount()+”) ”); sb.append(“ <ul>); sb.append(“ <li>”+cd.getCity()+” (“+cd.getCount()+”) ”); sb.append(“ <ul>); sb.append(“ <li>”+cd.getMfc()+” (“+cd.getCount()+”)</li> ”); sb.append(“ </ul>); sb.append(“ </li>); sb.append(“ </ul>); sb.append(“ </li>); sb.app

Categories : Java

How to sort list of locale objects in list interface using comparator in java
You are using an unmodifiable list. If you put the elements in a modifiable list it can be sorted. Otherwise you could your own sorting algorithm that put the elements in a new list. This approach could be faster. Try this instead: List<Locale> localeList = new ArrayList<Locale>(list); Collections.sort(localeList, comparator);

Categories : Java

Using linq group by to get from a list of objects with a DateTime property to a list with an interval StartDate, EndDate
You can use GroupBy in combination with SelectMany and Aggregate for this: var setups = bookedRooms.GroupBy(x => Tuple.Create(x.TimePeriodId, x.VenueId)) .SelectMany(x => x.Aggregate( new List<EventSetup>(), AccumulateRooms)) .OrderBy(x => x.StartDate) .ToList(); List<EventSetup> AccumulateRooms(List<EventSetup> existingSetups, BookedRoom currentRoom) { var setup = existingSetups.LastOrDefault(); if(setup == null || setup.EndDate.AddDays(1) != currentRoom.Day.Date) { setup = new EventSetup { VenueId = currentRoom.VenueId, TimePeriodId = currentRoom.TimePeriodId, StartDate = currentR

Categories : C#

Append different object into list but the list result in same objects repeating
Whenever you call neighbor_list.append(neighbor) you just add a reference to neighbor, rather than a new list. This means that every list in neighbor_list is just the current value of neighbor. To fix this, you should make a copy of the list like this: neighbor_list.append(copy.copy(neighbor) Documentation for copy

Categories : Python

Can List.Distinct() apply to the list type of List>?
That's because List<T> has no Equals and GetHashCode implemented, so standard reference comparison is being performed. And it returns false, because you have two separated lists. You can write your own IEqualityComparer<List<string>> implementation and provide it as Distinct method parameter. Within the comparer you can use Enumerable.SequenceEqual) method to check if lists has the same content.

Categories : C#

Deserializing List of objects yields empty list
Ok, I've reimplemented your solution in C#, and what makes the difference is the fact that you didn't provide the namespace for TaskRequests in MobileRequest class. To summarize: 1) You mix attributes for DataContractSerializer and XmlSerializer which makes this code hard to manage, I've used only XmlSerializer related attributes. 2) The XML you've provided cannot be the result of serializing the classes you've presented. It contains "MyNameSpace" on TaskReqests field, whereas in your code there are no namespaces for XmlSerializer (only for DataContractSerializer which is not relevant here). 3) The minimal fix of your code to make XML you've given deserialize correctly (see edit below) is: [Serializable] public class MobileRequest { [XmlArray(Namespace="MyNameSpace")] //note the n

Categories : Xml



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.