Replace string does not work in python 3.2 - python-3.x

I have a template file: 'template.txt' like below:
class Core_Model_DbTable_{table_name} extends YouNet_Db_Table
{
const TYPE_PRINTED = 1;
const TYPE_DIGITAL = 2;
protected $_name = '{table_name}';
protected $_rowClass = 'Core_Model_{table_name:short}';
}
And I use Python 3.2 to read that file and try to replace:
{table_name} => Coupons
{table_name:short} => Coupon
and here my code:
in_file = open("template.txt","r")
text = in_file.read()
in_file.close()
txt = text.replace("{table_name}","Coupons")
txt = text.replace("{table_name:short}","Coupon")
But the output only shows the result:
c:\Python32\python.exe builder.py
<?php
class Core_Model_DbTable_{table_name} extends YouNet_Db_Table
{
const TYPE_PRINTED = 1;
const TYPE_DIGITAL = 2;
protected $_name = '{table_name}';
protected $_rowClass = 'Core_Model_Coupon';
}
Could you please tell me anything is wrong here?

You seem to have misspelled the name of your variable: "txt" vs "text".

Related

How to use NestJS-i18n with an Excel file instead of JSON file?

I'm trying to use NestJS-i18n for internationalization in my NestJS application. Currently, I have all my translation keys and values stored in a JSON file. However, I have a requirement to switch to an Excel file for managing translations.
I've been searching for a way to do this, but I haven't found any documentation or examples on how to use an Excel file with NestJS-i18n.
Does anyone have any ideas or suggestions on how I could achieve this? Any help would be greatly appreciated. Thank you.
you can convert your excel file to Json using xlsx package:
here enter code hereis an example of parser:
use sheet_to_json method for parsing xcell to json
Key
en
fr
greeting
Hello
Bonjour
welcome_message
Welcome to
Bienvenue à
import * as xlsx from 'xlsx';
export class ExcelParser {
constructor(private readonly options: ExcelParserOptions) {}
async parse(): Promise<Record<string, any>> {
const workbook = xlsx.readFile(this.options.path);
const worksheet = workbook.Sheets[this.options.sheetName];
const data : any[] = xlsx.utils.sheet_to_json(worksheet, {
header: 1,
raw: false,
});
const keys = data[0].slice(1);
const translations = {};
for (let i = 1; i < data.length; i++) {
const row = data[i];
const key = row[0];
translations[key] = {};
for (let j = 1; j < keys.length + 1; j++) {
const language = keys[j - 1];
const value = row[j];
translations[key][language] = value;
}
}
return translations;
}
}
export interface ExcelParserOptions {
path: string;
sheetName: string;
}

How can I export tables in Excel file using ASP.Net MVC?

My View consists of multiple tables, and I am looking to Export multiple tables from View in Excel file. My current function only helps me to export 1 table.
Can any one help me to complete this code so that multiple tables can be exported?
Report VM
public class ReportVM
{
public string ScenName { get; set; }
public int Count { get; set; }
public string CreateTickYes { get; set; }
public int TickYes { get; set; }
public string RegionName { get; set; }
public int RegionCount { get; set; }
public string UserName { get; set; }
public int ChatCountUser { get; set; }
}
Action Method to export
public FileContentResult DownloadReport(DateTime start, DateTime end)
{
//var uName = User.Identity.Name;
var fileDownloadName = String.Format("Report.xlsx");
const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
// Pass your ef data to method
ExcelPackage package = GenerateExcelFile(db.Chats.Where(x => System.Data.Entity.DbFunctions.TruncateTime(x.ChatCreateDateTime) >= start && System.Data.Entity.DbFunctions.TruncateTime(x.ChatCreateDateTime) <= end)
.GroupBy(a => a.ScenarioList).Select(b => new ReportVM()
{
ScenName = b.Key,
Count = b.Count()
}).ToList());
var fsr = new FileContentResult(package.GetAsByteArray(), contentType);
fsr.FileDownloadName = fileDownloadName;
return fsr;
}
private static ExcelPackage GenerateExcelFile(IEnumerable<ReportVM> datasource)
{
ExcelPackage pck = new ExcelPackage();
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet 1");
// Sets Headers
ws.Cells[1, 1].Value = "Scenario";
ws.Cells[1, 2].Value = "No.Of Chats";
// Inserts Data
for (int i = 0; i < datasource.Count(); i++)
{
ws.Cells[i + 2, 1].Value = datasource.ElementAt(i).ScenName;
ws.Cells[i + 2, 2].Value = datasource.ElementAt(i).Count;
}
//Sheet2
// Format Header of Table
using (ExcelRange rng = ws.Cells["A1:B1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.Gold); //Set color to DarkGray
rng.Style.Font.Color.SetColor(Color.Black);
}
return pck;
}
So, now it export data for Table GroubBy = ScenarioList. I want to also include another column in groupBy = Username. So when Export data, Excel file should contain 2 Sheets. 1 for Table ScenarioList, and 2nd for Table Username.
Help is much appreciated. Thank you in advance.
You need create div/table under which put all tables and then by using below javascript function. Please call this javascript function on button click on same page which have all data. This is working for me which I already used in my project.
function DownloadToExcel() {
var htmls = $("#compareBodyContent")[0].innerHTML; // this main element under which
//all you data
var uri = 'data:application/vnd.ms-excel;base64,';
var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
var base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)))
};
var format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
})
};
var ctx = {
worksheet: 'Worksheet',
table: '<table>' + htmls + '</table>'
}
var compareLink = document.createElement("a");
compareLink.download = "Compare_Test.xls";
compareLink.href = uri + base64(format(template, ctx));
compareLink.click();
}
Hope this will help you. Let me know if you have any question on this.

fetch data from website using c#

input link for ex is "http://www.unionstationdc.com".I need to programmatically go here "http://www.unionstationdc.com/contact" & fetch contents of this page. I have written this code below but of no use.
doc = hw.Load(link);
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
bool hreflink = link.GetAttributeValue("p", true);
if (hreflink == true)
{
attr = link.Attributes;
att = attr.AttributesWithName("p");
for (int i = 0; i < attr.Count; i++)
{
name = attr[i].Name;
value = attr[i].Value;
string trim = value.Trim('/');
string uppercase = trim.ToUpper();
if (uppercase.Contains("CONTACT"))
{
string path = attr[i].XPath;
MessageBox.Show(path);
}
}
}
}
Please help me to finish .... Thanks in advance

interpret string as variable in C#

I have some public const strings in c# console application as shown below:
//Account one
public const string POP_USER1 = "abc#abcd.com";
public const string POP_PWD1 = "abc";
//Account two
public const string POP_USER2 = "xyz#abcd.com";
public const string POP_PWD2 = "xyz";
//Account three
public const string POP_USER3 = "pqr#abcd.com";
public const string POP_PWD3 = "pqr;
We are using c# MailMan to retrieve emails present in those accounts.
I simply wrote a for loop 3 times:
for (int i = 1; i <= 3; i++)
{
eEmails obj = new eEmails (i);
}
In the constructor of eEmails, I am writing the below logic:
public eEmails (int counter)
{
MailMan obj = new MailMan()
obj.PopUsername = "POP_USER" + counter;
obj.PopPassword = "POP_PWD" + counter;
}
The lines where I am assigning user name and passwords, I need to fetch the exact const variable (i.e., POP_USER1, POP_USER2, POP_USER3 etc.,)
However I am not able to get the variable dynamically.
I can simply write 3 if blocks in eEmails (int counter), but I didnt like that way.
can somebody advise a better way of handling this situation without using separate if blocks for each user??
Use a class instead of strings, then your code becomes more redable and maintainable and it'll also be less error-prone. Here is an example using a List<PopServerAccount> as container:
public class PopServerAccount
{
public string Username {get;set;}
public string Password {get;set;}
public override bool Equals(object obj)
{
PopServerAccount p2 = obj as PopServerAccount;
if (p2 == null) return false;
return Username == p2.Username;
}
public override int GetHashCode()
{
return Username.GetHashCode();
}
public override string ToString()
{
return Username;
}
}
now change the signature of your method:
public eEmails (PopServerAccount pop)
{
MailMan obj = new MailMan()
obj.PopUsername = pop.Username;
obj.PopPassword = pop.Password;
}
Sample data:
var myPopServers = new List<PopServerAccount>
{
new PopServerAccount{ Username = "abc#abcd.com", Password = "abc"},new PopServerAccount{ Username = "xyz#abcd.com", Password = "xyz"}
};
Use a loop and call your method:
foreach (PopServerAccount pop in myPopServers)
{
eEmails(pop);
}

How to Export DataTable into Excel

I have list of objects and i converted those into data table now i am unable to export those into excel
Below is the sample code
class Program
{
static void Main(string[] args)
{
Student s1 = new Student("Student-A",100);
Student s2 = new Student("Student-B", 90);
Student s3 = new Student("Student-C", 80);
List<Student> studentList = new List<Student>() { s1,s2,s3};
ListToDataTable converter = new ListToDataTable();
DataTable dt = converter.ToDataTable(studentList);
Console.WriteLine();
}
}
Below is the student class which has two properties
class Student
{
public string Name { get; set; }
public int? Score { get; set; }
public Student(string name,int? score)
{
this.Name = name;
this.Score = score;
}
}
Below is the class used for converting list of objects to data table
public class ListToDataTable
{
public DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
}
Try to create a simple CSV file from your DataTable.
You can use the following DataTable extension, after you have converted your list to a DataTable.
public static string ToCSV(this DataTable table)
{
var result = new StringBuilder();
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(table.Columns[i].ColumnName);
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(row[i].ToString());
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
}
return result.ToString();
}
Example of usage :
// replace with your data table here
DataTable dt = new DataTable();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(dt.ToCSV());
MemoryStream stream = new MemoryStream(bytes);
StreamReader reader = new StreamReader(stream);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", "filename"));
Response.ContentType = "application/text";
Response.ContentEncoding = Encoding.Unicode;
Response.Output.Write(reader.ReadToEnd());
Response.Flush();
Response.End();
Since you have this tagged as interop, I went that route (no need to create a csv file, just export directly to excel).
This solution is not the prettiest, but it works. I've also changed it some as you can export your studentList directly to excel (no need to convert it to a dataTable first).
First thing, in your solution, you need to add a reference to "Microsoft.Office.Interop.Excel". To do this, right click on "References" in Solution Explorer, then "Add Reference", then click on the ".NET" tab, then scroll down to find it.
Once that is done, update your code as follows:
using System;
using System.Collections.Generic;
using Excel = Microsoft.Office.Interop.Excel;
static void Main()
{
var s1 = new Student("Student-A", 100);
var s2 = new Student("Student-B", 90);
var s3 = new Student("Student-C", 80);
var studentList = new List<Student> { s1, s2, s3 };
// Create an excel sheet
var xlApp = new Excel.Application { Visible = true }; // Create instance of Excel and make it visible.
xlApp.Workbooks.Add(Excel.XlSheetType.xlWorksheet); // Create a workbook (WB)
var xlWS = (Excel.Worksheet)xlApp.ActiveSheet; // Reference the active worksheet (WS)
xlWS.Name = "Exported Student"; // Name the worksheet
// Add Header fields to Excel [row, column]
var r = 1;
xlWS.Cells[r, 1] = "Name";
xlWS.Cells[r, 2] = "Score";
// Copy data from StudentList to Excel
foreach (Student student in studentList)
{
r++;
xlWS.Cells[r, 1] = student.Name;
xlWS.Cells[r, 2] = student.Score;
}
}
This will automatically export your studentList to an excel sheet. There wasn't a need for the ListToDataTable class.

Resources