Finding the number of times a name is in a string - function

string = "Hamza flew his kite today. But Hamza forgot to play basketball"
def count_name():
count = 0
for sub_str in string:
if sub_str == "Hamza":
count += 1
return count
print(count_name())
My goal here was to find the number of times the name "Hamza", appears in the string.
But it keeps returning 0, instead of 2.
I tried setting the variable count = 0, so it can count how many times the name "Hamza" appears in the string.

The countName function takes a string as an argument and returns the number of times "Hamza" appears in it. Here is one way to count the number of times "Hamza" appears in a given string:
function countName(str) {
let count = 0;
let index = str.indexOf("Hamza");
while (index != -1) {
count++;
index = str.indexOf("Hamza", index + 1);
}
return count;
}
let string = "Hamza flew his kite today. But Hamza forgot to play basketball";
let count = countName(string);
console.log(count); // Output: 2

when you do for sub_str in string: you are looking at one letter a time (not one word at a time). You are checking...
'H'=='Hamza' which returns False
'a'=='Hamza' which returns False
'm'=='Hamza' which returns False...
that is why your count will never increase.
Luckily for you python has built in methods to make your life easy.
Try string.count('Hamza')

Related

Compare time in gorm: time.Time or string

We are using gorm v1.9.11and mysql.
// before is string like "2019-01-15T06:31:14Z"
if len(before) > 0 {
// TODO: Determine time format
beforeDate, e := time.Parse(time.RFC3339, before)
if e != nil {
...
}
// TODO: Pass in string?
statement = statement.Where("created_at < ?", beforeDate)
}
I have two questions:
1, any problems in the above piece of codes? I found it took about 5 minutes to finish the query given before. If no before, it tooks 14 seconds.
2, it is OK to pass string like "2019-01-15T06:31:14Z" as argument in statement.Where("created_at < ?", beforeString)?
Thanks
UPDATE
We have an index on created_at, the query plan shows that it will filter 8millions rows based on created_At. I guess this is the reason.
Now, trying to avoid this index to be used.

Fetch records with query Args in Go

I Need help for fetch records from table using Go.
My Problem is that i'm writing MySQL query and add another where clause i.e HPhone number, Here HPhone number inserted in data base with format like 999-999-9999.And i passed this HPhone Number in format like 9999999999. which is not matching with correct data base field value. And i used SUBSTRING for add hyphen between numbers but it does not get records but when i passed like 999-999-9999 without SUBSTRING it return records.
Here i demonstrate how i used this.
strQry = `SELECT * from table WHERE Depot = ?`
if HPhone != "" {
strQry += ` AND HPhone = ?`
}
queryArgs := []interface{}{RouteAvailability.Depot}
if HPhone != "" {
queryArgs = append(queryArgs, "SUBSTRING("+HPhone+",1,3)"+"-"+"SUBSTRING("+HPhone+",4,3)"+"-"+"SUBSTRING("+HPhone+",7,4)")
}
Help would be appreciated.
Thanks in advance.
Instead of SUBSTRING you can use REPLACE like so:
queryArgs := []interface{}{RouteAvailability.Depot}
if HPhone != "" {
strQry += ` AND REPLACE(HPhone, '-', '') = ?`
queryArgs = append(queryArgs, HPhone)
}
If possible I would suggest you normalize your data, i.e. decide on a canonical format for a particular data type and everytime your program receives some input that contains that data type you format it into its canonical form, that way you can avoid having to deal with SUBSTRING, or REPLACE, or multiple inconsistent formats etc.
This won't work as you are using prepared statements, and the argument you are building when HPhone is not empty will be used in escaped form - so when executing the query, it won't compare the HPhone values with the computed result of some substring, but with a string containing SUBSTRING(9999...

Python 2.7.5, using a loop within a function and calling the function

I can't seem to get user input for a number of times to display. For example, if the input is
Jeff 6
The output should be
Jeff
Jeff
Jeff
Jeff
Jeff
Jeff
I'm new to functions in Python, but here is my code thus far:
def getName():
name = raw_input("please enter name")
return name
def getRepval():
irepnum = float(raw_input("please enter number to show name entered"))
return irepnum
def inamed(name, irepnum):
count = 1 #the loop to show the name entered by the user
while irepnum != count:
print name
count += 1 #do I need to use return??
def main(): #having the main func like this gives me an infinite loop
irepnum = 0
iname = getName() #I think my problem is somewhere here.
irepnum = getRepval()
inamed(irepnum,name)
main()
You need to call inamed(iname, irepnum), not inamed(irepnum, name), as you are doing now.
Other than the obvious mistake of name not being defined (the actual variable is called iname), the wrong order causes irepnum in the function to be set to a string the user entered as name. Since count, no matter how large, never compares equal to the passed string, the code loops infinitely.
Several tips:
Learn to use the for loop and xrange. The idiom you want is for count in xrange(irepnum):. (Using it would have prevented this bug.)
Give more distinctive names to your identifiers. Currently you have an inamed function and an iname variable. Confusing.
Don't use floats where an int would suffice. Misusing floats is asking for trouble.

Format number Rdlc report

i need to show numbers 1 2 3 in Arabic letters
i write in text box expression this statement
=FormatNumber(Fields!Size.Value,1,-2,-2,-2)
but i don't know it's parameter and which parameter can show numbers in Arabic format
MANY THANKS
set report language to your local language (ar-EG)
in the textbox properties set NumeralVariant to 3
references
similar problem
NumeralVariant
limitations
1- will not work for strings containing numbers
2- will not work for dates
work around limitation with bad performance i guess
you can replace any english number with arabic number using Replace method in any string that may contain numbers
your expression will be some thing like this
=Replace(Replace(Replace(Fields!FieldName.Value,"0","۰"),"1","۱"),"2","۲")
complete expression to 9
You can write function in code and use that
enter image description here
Public Shared Function farsi(input As String) As String
Dim result As String = input
result = result.Replace("1", "۱")
result = result.Replace("2", "۲")
result = result.Replace("3", "۳")
result = result.Replace("4", "۴")
result = result.Replace("5", "۵")
result = result.Replace("6", "۶")
result = result.Replace("7", "۷")
result = result.Replace("8", "۸")
result = result.Replace("9", "۹")
result = result.Replace("0", "۰")
Return result
End Function
Usage:
=Code.farsi(1111.555)
Public Shared Function Arabic(input As String) As String
Dim result As String = input
result = result.Replace("1", "۱")
result = result.Replace("2", "۲")
result = result.Replace("3", "۳")
result = result.Replace("4", "٤")
result = result.Replace("5", "۵")
result = result.Replace("6", "٦")
result = result.Replace("7", "۷")
result = result.Replace("8", "۸")
result = result.Replace("9", "۹")
result = result.Replace("0", "۰")
Return result
End Function
Use it for arabic Numbers
=Code.Arabic(Fields!OrderID.Value)
=Code.Arabic(FieldName)

Use of custom expression in LINQ leads to a query for each use

I have the following problem: In our database we record helpdesk tickets and we book hours under tickets. Between those is a visit report. So it is: ticket => visitreport => hours.
Hours have a certain 'kind' which is not determined by a type indicator in the hour record, but compiled by checking various properties of an hour. For example, an hour which has a customer but is not a service hour is always an invoice hour.
Last thing I want is that the definitions of those 'kinds' roam everywhere in the code. They must be at one place. Second, I want to be able to calculate totals of hours from various collections of hours. For example, a flattened collection of tickets with a certain date and a certain customer. Or all registrations which are marked as 'solution'.
I have decided to use a 'layered' database access approach. The same functions may provide data for screen representation but also for a report in .pdf . So the first step gathers all relevant data. That can be used for .pdf creation, but also for screen representation. In that case, it must be paged and ordered in a second step. That way I don't need separate queries which basically use the same data.
The amount of data may be large, like the creation of year totals. So the data from the first step should be queryable, not enumerable. To ensure I stay queryable even when I add the summation of hours in the results, I made the following function:
public static decimal TreeHours(this IEnumerable<Uren> h, FactHourType ht)
{
IQueryable<Uren> hours = h.AsQueryable();
ParameterExpression pe = Expression.Parameter(typeof(Uren), "Uren");
Expression left = Expression.Property(pe, typeof(Uren).GetProperty("IsOsab"));
Expression right = Expression.Constant(true, typeof(Boolean));
Expression isOsab = Expression.Equal(Expression.Convert(left, typeof(Boolean)), Expression.Convert(right, typeof(Boolean)));
left = Expression.Property(pe, typeof(Uren).GetProperty("IsKlant"));
right = Expression.Constant(true, typeof(Boolean));
Expression isCustomer = Expression.Equal(Expression.Convert(left, typeof(Boolean)), Expression.Convert(right, typeof(Boolean)));
Expression notOsab;
Expression notCustomer;
Expression final;
switch (ht)
{
case FactHourType.Invoice:
notOsab = Expression.Not(isOsab);
final = Expression.And(notOsab, isCustomer);
break;
case FactHourType.NotInvoice:
notOsab = Expression.Not(isOsab);
notCustomer = Expression.Not(isCustomer);
final = Expression.And(notOsab, notCustomer);
break;
case FactHourType.OSAB:
final = Expression.And(isOsab, isCustomer);
break;
case FactHourType.OsabInvoice:
final = Expression.Equal(isCustomer, Expression.Constant(true, typeof(Boolean)));
break;
case FactHourType.Total:
final = Expression.Constant(true, typeof(Boolean));
break;
default:
throw new Exception("");
}
MethodCallExpression whereCallExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { hours.ElementType },
hours.Expression,
Expression.Lambda<Func<Uren, bool>>(final, new ParameterExpression[] { pe })
);
IQueryable<Uren> result = hours.Provider.CreateQuery<Uren>(whereCallExpression);
return result.Sum(u => u.Uren1);
}
The idea behind this function is that it should remain queryable so that I don't switch a shipload of data to enumerable.
I managed to stay queryable until the end. In step 1 I gather the raw data. In step 2 I order the data and subsequently I page it. In step 3 the data is converted to JSon and sent to the client. It totals hours by ticket.
The problem is: I get one query for the hours for each ticket. That's hundreds of queries! That's too much...
I tried the following approach:
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Ticket>(t => t.Bezoekrapport);
options.LoadWith<Bezoekrapport>(b => b.Urens);
dc.LoadOptions = options;
Bezoekrapport is simply Dutch for 'visitreport'. When I look at the query which retrieves the tickets, I see it joins the Bezoekrapport/visitreport but not the hours which are attached to it.
A second approach I have used is manually joining the hours in LINQ, but that does not work as well.
I must do something wrong. What is the best approach here?
The following code snippets are how I retrieve the data. Upon calling toList() on strHours in the last step, I get a hailstorm of queries. I've been trying for two days to work around it but it just doesn't work... Something must be wrong in my approach or in the function TreeHours.
Step 1:
IQueryable<RelationHoursTicketItem> HoursByTicket =
from Ticket t in allTickets
let RemarkSolved = t.TicketOpmerkings.SingleOrDefault(tr => tr.IsOplossing)
let hours = t.Bezoekrapport.Urens.
Where(h =>
(dateFrom == null || h.Datum >= dateFrom)
&& (dateTo == null || h.Datum <= dateTo)
&& h.Uren1 > 0)
select new RelationHoursTicketItem
{
Date = t.DatumCreatie,
DateSolved = RemarkSolved == null ? (DateTime?)null : RemarkSolved.Datum,
Ticket = t,
Relatie = t.Relatie,
HoursOsab = hours.TreeHours(FactHourType.OSAB),
HoursInvoice = hours.TreeHours(FactHourType.Invoice),
HoursNonInvoice = hours.TreeHours(FactHourType.NotInvoice),
HoursOsabInvoice = hours.TreeHours(FactHourType.OsabInvoice),
TicketNr = t.Id,
TicketName = t.Titel,
TicketCategorie = t.TicketCategorie,
TicketPriority = t.TicketPrioriteit,
TicketRemark = RemarkSolved
};
Step 2
sort = sort ?? "TicketNr";
IQueryable<RelationHoursTicketItem> hoursByTicket = GetRelationHours(relation, dateFrom, dateTo, withBranches);
IOrderedQueryable<RelationHoursTicketItem> orderedResults;
if (dir == "ASC")
{
orderedResults = hoursByTicket.OrderBy(sort);
}
else
{
orderedResults = hoursByTicket.OrderByDescending(sort);
}
IEnumerable<RelationHoursTicketItem> pagedResults = orderedResults.Skip(start ?? 0).Take(limit ?? 25);
records = hoursByTicket.Count();
return pagedResults;
Step 3:
IEnumerable<RelationHoursTicketItem> hours = _hourReportService.GetRelationReportHours(relation, dateFrom, dateTo, metFilialen, start, limit, dir, sort, out records);
var strHours = hours.Select(h => new
{
h.TicketNr,
h.TicketName,
RelationName = h.Relatie.Naam,
h.Date,
TicketPriority = h.TicketPriority.Naam,
h.DateSolved,
TicketCategorie = h.TicketCategorie == null ? "" : h.TicketCategorie.Naam,
TicketRemark = h.TicketRemark == null ? "" : h.TicketRemark.Opmerking,
h.HoursOsab,
h.HoursInvoice,
h.HoursNonInvoice,
h.HoursOsabInvoice
});
I don't think your TreeHours extension method can be converted to SQL by LINQ in one go. So are evaluated on execution of each constructor of the row, causing a 4 calls to the database in this case per row.
I would simplfy your LINQ query to return you the raw data from SQL, using a simple JOIN to get all tickets and there hours. I would then group and filter the Hours by type in memory. Otherwise, if you really need to perform your operations in SQL then look at the CompiledQuery.Compile method. This should be able to handle not making a query per row. I'm not sure you'd get the switch in there but you may be able to convert it using the ?: operator.