python arraylist distribution - arrays

def createlist(json, filename, arraygroup):
filehdl = open(filename, "wb")
for key, value in rulegroup.items():
filehdl.write('#' + value + "\n")
for list in json:
if list['arraygroup'] == value:
filehdl.write(list['name'] + " " + list['surname'] + "\n")
filehdl.close()
#depart1
testname testsurname
testname1 testsurname2
testname3 testsurname3
#depart2
#depart3
Json has 5 names, and 2 names should be places in #depart2, #depart3 base on their correct department.
Hi i have here a code that will create a file and separate the names in json file base on there group, but the 2nd forloop (with json) was not resetting its index, so after 1st loop of the forloop list was stuck.
tnx for answer.^^,

I already resolve the problem by inputing json obj to array.
jsonlist = []
for obj in json:
jsonlist.append(obj)
then change the 2nd loop with jsonlist
for list in jsonlist:
if list['arraygroup'] == value:
filehdl.write(list['name'] + " " + list['surname'] + "\n")

Related

'empty?' returns 'false' for an empty array within an empty array

My script returns an empty array in another empty array (or I guess it's not empty because there is another empty array within the other array).
I have an if condition that checks if the outer array is empty. It says it's not empty because it contains an empty array. I need help to get it return false. I believe the best method would be to check if the inner array is empty, but I'm not sure where the inner array is created.
Here's the code for the method that checks if the array is empty:
def directory_check(directory_list, save_to_file, today_date, output_file, output_extension, results_file_output)
if directory_list.empty? == false
# changes the working directory to the file output directory for the file
Dir.chdir(save_to_file)
# writes the array contents into a new file
file_name = output_file + "_" + today_date + output_extension
puts Time.now.to_s + " > " + "Saving contents to: " + results_file_output + file_name
puts ""
File.open(file_name, "a+") do |f|
directory_list.each { |element| f.puts(element) }
end
else
puts Time.now.to_s + " > " + "This directory does not contain any subdirectories that are older than 24 hours"
exit
end
end
The directory_list returns [[]], and empty? returns false.
I have another method that stores items into an array, but I cannot figure out why there is an array within an array:
def store_directories(directories, folder_to_exclude)
# updates search directory for each value for the directories hash
subdir_list = Array.new
directories.each do |element|
directory = "#{element}"
puts Time.now.to_s + " > " + "Updating search directory: " + directory
Dir.chdir(directory)
# outputs only subdirectories with a creation date of older than 24 hours, except for folders names 'Archive'
Dir.glob("*.*").map(&File.method(:realpath))
puts Time.now.to_s + " > " + "Gathering subdirectories..."
puts ""
# Stores the contents of the query into an array and appends to the list for each iteration of the array
subdir_list << Dir.glob("*").map(&File.method(:realpath)).reject {|files|
(not File.directory?(files) &&
(File.mtime(files) < (Time.now - (60*1440))) &&
(not files == directory + folder_to_exclude))
}
puts ""
puts "Adding new folders to the list..."
puts ""
puts "Excluding: " + directory + folder_to_exclude
puts ""
puts subdir_list
puts " "
end
return subdir_list
end
I'm passing an array of directories into the store_directories method.
The directory_list returns [[]], and empty? returns false.
it's working properly and it returns correct value, as your directory_list is not empty array, it contain empty array. You need to use Array#flatten
> [[]].flatten.empty?
#=> true

How to specify where to save string in file

How to save string to file to specify place ? I use path << 'string' to save, but it give it on end of file. In destination to xml(path) file have </databaseChangeLog>. I want to save to file before that word occurs.
There is java solution click, but it is static line. My file will be dynamic, I don't know with line it will be.
def add_to_version() {
def path = new File('C:/groovy/version-1.xml')
def branchId = "Promt"
def lineCount = 0
def count = path.eachLine { line ->
if(line.contains('<include file="' + branchId + '/' + branchId + '.xml" ')){
wordCount++
}else if(lineCount == 1 ){
println "package is there"
}
}
if(lineCount == 0){
path << '<include file="' + branchId + '/' + branchId + '.xml" ' + 'relativeToChangelogFile="true"/>'
}
}
code above do that :
and I want to get xml like that :
you can use xml parser like this:
def add_to_version(String branchId) {
def path = new File('C:/groovy/version-1.xml')
def xml = new XmlParser().parse(path)
xml.appendNode("include", [
file:"${branchId}/${branchId}.xml",
relativeToChangelogFile:"true"
])
groovy.xml.XmlUtil.serialize(xml, path.newOutputStream())
}
this variant will not keep the xml formatting and comments
however xml will be valid

How to save Array[String, Int] data into file

I am trying to save a Array[String, Int] data into file. However, every time, it reports:
object not serializable
I also tried to combine the two columns into a string, and want to write it line by line, but it still report such error. The code is:
val fw = new PrintWriter(new File("/path/data_stream.txt"))
myArray.foreach(x => fw.write((x._1.toString + " " + x._2.toString + "\n").toByte
import java.nio.file._
val data = Array(("one", 1), ("two", 2), ("three", 3))
data.foreach(d => Files.write(Paths.get("/path/data_stream.txt"), (d._1 + " " + d._2 + "\n").getBytes, StandardOpenOption.CREATE, StandardOpenOption.APPEND))

array of objects in genie

I have 2 classes: one with 2 properties and one with an array. I want to make an array of objects of the first class.
The example compiles, but gives a wrong answer. Why?
[indent=4]
class data
prop first_name : string = " "
prop last_name : string = " "
class Arr : Object
person : data
dataset : array of data[]
init
person = new data()
dataset = new array of data[3]
def date_input()
print "\n data input \n"
person.first_name = "Egon"
person.last_name = "Meier"
dataset[0] = person
print dataset[0].first_name + " " + dataset[0].last_name
person.first_name = "John"
person.last_name = "Schneider"
dataset[1] = person
print dataset[1].first_name + " " + dataset[1].last_name
person.first_name = "Erwin"
person.last_name = "Müller"
dataset[2] = person
print dataset[2].first_name + " " + dataset[2].last_name
def date_output()
print "\n data output \n"
for i : int = 0 to 2
print dataset[i].first_name + " " + dataset[i].last_name
init
Intl.setlocale()
var a = new Arr()
a.date_input()
a.date_output()
The fundamental problem is you are referring to the same person three times, but changing their name each time. In Genie there are both value types and reference types. Value types are simpler and automatically copied on assignment. For example:
[indent=4]
init
a:int = 2
b:int = a
b = 3
print( "a is still %i", a )
A reference type has the advantage that it can be easily copied, Genie simply keeps a count of the references made. So to copy a reference type the reference count is increased by one, but this means that changes to the underlying object will affect all variables that refer to it:
[indent=4]
init
a:ReferenceTypeExample = new ReferenceTypeExample()
a.field = 2
b:ReferenceTypeExample = a
b.field = 3
print( "a.field is not 2, but %i", a.field )
class ReferenceTypeExample
field:int = 0
In the working example below I have made Person a value object by using readonly properties:
[indent=4]
init
Intl.setlocale()
var group = new Group()
print "\n data input \n"
try
group.add_person( new Person( "Egon", "Meier" ))
group.add_person( new Person( "John", "Schneider" ))
group.add_person( new Person( "Erwin", "Müller" ))
except err:GroupError
print( err.message )
print( #"$group" )
class Person
prop readonly first_name:string = ""
prop readonly last_name:string = ""
construct( first:string, last:string )
_first_name = first
_last_name = last
exception GroupError
GROUP_FULL
class Group
_people_count:int = -1
_group:new array of Person
_max_size:int = 2
construct()
_group = new array of Person[ _max_size ]
def add_person( person:Person ) raises GroupError
_people_count ++
if _people_count > _max_size
_people_count = _max_size
raise new GroupError.GROUP_FULL(
"Group is full. Maximum is %i members",
_max_size + 1
)
_group[ _people_count ] = person
print( " " + _group[ _people_count ].first_name +
" " + _group[ _people_count ].last_name
)
def to_string():string
result:string = "\n data output \n\n"
if _people_count < 0
result += " empty group"
return result
for i:int = 0 to _people_count
result += " " + _group[i].first_name + \
" " + _group[i].last_name + "\n"
return result
Some details about the code:
By changing the properties to be readonly an error will be given when you compile the program if it tries to change a detail of Person. In your example, if you change the properties of data to be readonly then the Vala compiler will warn you are trying to re-write the current object
Person has its data values set in the constructor and then any attempt after that to change them is an error
For a simple property Genie generates an automatic backing field that starts with an underscore. For example in Person the property first_name has the backing field _first_name and it is that field that is set in the constructor
Instead of including the people's names in the method itself, a method called add_person() is used that takes a Person as a parameter. This separates the concrete data from the abstract class
Checks have been added to the add_person() method to make sure the array doesn't go beyond its limits. If more people are added to the group than are allowed then an exception is raised
The add_person() calls in the init block create the Person as part of the method call. This means a reference to a Person object is not kept in the init block

How to loop hashes within an array

I need to use a loop in my code so the user is prompted with "Name?" three times, and each answer is stored as a new hash within the data array. Each answer should also have a new random number generated for it, and an email.
I need puts data to output all three hashes and their contents. I've tried using 3.times do, but I'm having trouble:
data = Array.new()
puts "Name?, eg. Willow Rosenberg"
name = gets.chomp
number = rand(1000..9000) + 1
data = [
{
name: name,
number: number,
email: name.split(' ').last + number.to_s[1..3] + "#btvs.com"
}
]
puts data
data = []
3.times do
puts "Name?, eg. Willow Rosenberg"
name = gets.chomp
number = rand(1000..9000) + 1
hash = {
name: name,
number: number,
email: name.split(' ').last + number.to_s[1..3] + "#btvs.com"
}
data << hash
end
puts data

Resources