Knight’s Tour – Python

Below is my recursive solution for the Knight’s Tour. The user can set the board size and the program will print the first legal knight’s tour it finds.

As there are potentially millions of correct solutions to the knight’s tour, only one solution is given.

def legal_moves(visited, position, sq):     """Calculate legal moves"""     legal_moves = [         (-2, -1),         (-2, 1),         (-1, -2),         (-1, 2),         (1, -2),         (1, 2),         (2, -1),         (2, 1),     ]      row = position // sq     col = position % sq      move_to = []     for dx, dy in legal_moves:         if 0 <= (row + dx) < sq and 0 <= (col + dy) < sq:             new_position = (position + (sq * dx)) + dy             if new_position not in visited and 0 <= new_position < (sq * sq):                 move_to.append(new_position)     return move_to   def make_move(move_to, visited, current, route, sq):     """Carry out the move"""     for move in move_to:         visited.add(current)         new_route = route + f"{current}-"         solution_found = next_move(visited, move, new_route, sq)         visited.remove(current)         if solution_found:             return True     return False   def next_move(visited, current, route, sq):     """Find the next valid moves and instruct "make_move" to carry them out"""     if len(visited) == (sq * sq) - 1:         route += f"{current}"         print(route)         return True     move_to = legal_moves(visited, current, sq)     solution_found = make_move(move_to, visited, current, route, sq)     if solution_found:         return True   def start_tour(sq):     """Calculate the knights tour for  grid sq*sq starting at all positions in range 0-sq"""     for starting in range(sq * sq):         visited = set()         route = ""         solution_found = next_move(visited, starting, route, sq)         if solution_found:             return     print("No knights tour could be calculated")   if __name__ == "__main__":     square_size = 8     start_tour(square_size)  

Batch retrieve formatted address along with geometry (lat/long) and output to csv

I have a csv file with 3 fields, two of which are of my interest, Merchant_Name and City.
My goal was to output multiple csv files each with 6 fields, Merchant_Name, City, name, formatted_address, latitude, longitude.

For example, if one entry of the csv is Starbucks, Chicago, I want the output csv to contain all the information in the 6 fields (as mentioned above) like so-
Starbucks, Chicago, Starbucks, "200 S Michigan Ave, Chicago, IL 60604, USA", 41.8164613, -87.8127855,
Starbucks, Chicago, Starbucks, "8 N Michigan Ave, Chicago, IL 60602, USA", 41.8164613, -87.8127855
and so on for the rest of the results.

For this, I used Text Search request of Google Maps Places API. Here is what I wrote.

import pandas as pd # import googlemaps import requests # import csv # import pprint as pp from time import sleep import random   def search_output(search):     if len(data['results']) == 0:         print('No results found for {}.'.format(search))      else:          # Create csv file         filename = search + '.csv'         f = open(filename, "w")          size_of_json = len(data['results'])          # Get next page token         # if size_of_json = 20:             # next_page = data['next_page_token']          for i in range(size_of_json):             name = data['results'][i]['name']             address = data['results'][i]['formatted_address']             latitude = data['results'][i]['geometry']['location']['lat']             longitude = data['results'][i]['geometry']['location']['lng']              f.write(name.replace(',', '') + ',' + address.replace(',', '') + ',' + str(latitude) + ',' + str(longitude) + '\n')          f.close()          print('File successfully saved for "{}".'.format(search))          sleep(random.randint(120, 150))   API_KEY = 'your_key_here'  PLACES_URL = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'   # Make dataframe df = pd.read_csv('merchant.csv', usecols=[0, 1])  # Construct search query search_query = df['Merchant_Name'].astype(str) + ' ' + df['City'] search_query = search_query.str.replace(' ', '+')  random.seed()  for search in search_query:     search_req = 'query={}&key={}'.format(search, API_KEY)     request = PLACES_URL + search_req      # Place request and store data in 'data'     result = requests.get(request)     data = result.json()      status = data['status']      if status == 'OK':         search_output(search)     elif status == 'ZERO_RESULTS':         print('Zero results for "{}". Moving on..'.format(search))         sleep(random.randint(120, 150))     elif status == 'OVER_QUERY_LIMIT':         print('Hit query limit! Try after a while. Could not complete "{}".'.format(search))         break     else:         print(status)         print('^ Status not okay, try again. Failed to complete "{}".'.format(search))         break 

I want to implement next page token but cannot think of a way which woudn’t make it all a mess. Another thing I wish to improve is my csv writing block. And dealing with redundancy.
I further plan to concatenate all the csv files into one(but still keeping the original separate files).

Please note that I’m new to programming, in fact this is actually one of my first programs to achieve something. So please elaborate a bit more when need be. Thanks!

Injecting Appsettings.json into nlong.config

My goal is to inject values from the appsettings.json into nlog.config for an ASP.NET Core application. I am using NLog.Web.AspNetCore 4.8.3, NLog 4.6.5, NLog.config 4.6.5, and Microsoft.Extensions.Logging.Abstractions 2.0.0.

I wasn’t able to get this working. I was under the impression that $ {configsetting:name=ConnectionStrings.ApplicationDatabase} would be replaced with the ConnectionStrings.ApplicationDatabase value inside of my appsettings.json file but this does not work. The nlog.config variable value is unchanged and throws an error when I run my application because that is an invalid connection string.

My application should log to MongoDB error/event log collections.

Snippet of nlog.config

<!-- Using logDirectory variable to set path to src/logs folder in allfile and ownFile-web targets below -->   <variable name="logDirectory" value="$  {basedir}/../../../logs/$  {shortdate}/internal-nlog.log" />   <variable name="logDatabase" value="$  {configsetting:name=ConnectionStrings.ApplicationDatabase}"/>   <variable name="logDatabaseUser" value="$  {configsetting:name=DatabaseCredentials.User}"/>   <variable name="logDatabasePassword" value="$  {configsetting:name=DatabaseCredentials.Password}"/>-->   <variable name="logConnectionString" value="mongodb://$  {logDatabaseUser}:$  {logDatabasePassword}@$  {logDatabase}/myApplicationDB?authSource=admin"/>    <!-- Load the ASP.NET Core plugin -->   <extensions>     <add assembly="NLog.Web.AspNetCore" />     <add assembly="Log.Mongo" />   </extensions>    <!-- the targets to write to -->   <targets>     <!-- write logs to file -->     <target xsi:type="File" name="allfile" fileName="$  {logDirectory}"             layout="$  {longdate}|$  {event-properties:item=EventId.Id}|$  {logger}|$  {uppercase:$  {level}}|$  {message} $  {exception}" />      <!-- another file log, only own logs. Uses some ASP.NET core renderers -->     <target xsi:type="File" name="ownFile-web" fileName="$  {logDirectory}"             layout="$  {longdate}|$  {event-properties:item=EventId.Id}|$  {logger}|$  {uppercase:$  {level}}|  $  {message} $  {exception}|url: $  {aspnet-request-url}|action: $  {aspnet-mvc-action}" />      <target xsi:type="Mongo" name="error-mongo"             connectionString="$  {logConnectionString}"             collectionName="errorLogs">       <field name="date" layout="$  {date}" bsonType="DateTime" />       <field name="level" layout="$  {level}" />       <field name="message" layout="$  {message}" />       <field name="logger" layout="$  {logger}" />       <field name="exception" layout="$  {exception:format=tostring}" />       <field name="threadID" layout="$  {threadid}" bsonType="Int32" />       <field name="threadName" layout="$  {threadname}" />       <field name="processID" layout="$  {processid}" bsonType="Int32" />       <field name="processName" layout="$  {processname:fullName=true}" />       <field name="userName" layout="$  {windows-identity}" />     </target>  <target xsi:type="Mongo" name="event-mongo"          connectionString="$  {logConnectionString}"          collectionName="eventLogs">       <field name="date" layout="$  {date}" bsonType="DateTime" />       <field name="level" layout="$  {level}" />       <field name="event" layout="$  {event-properties:item=EventId.Id}" />       <field name="message" layout="$  {message}" />       <field name="logger" layout="$  {logger}" />     </target>   </targets> 

Snippet of appsetting.json

  "ConnectionStrings": {     "ApplicationDatabase": "App-db-server-1.com:27017,App-db-server-2.com:27017,App-db-server-3.com:27017/AccessManagement?ssl=true&replicaSet=myReplicaSet&authSource=admin"   },   "DatabaseCredentials": {     "User": "",     "Password": ""   } } 

Snippet of startup.cs

   // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)         {             if (env.IsDevelopment())                 app.UseDeveloperExceptionPage();              ConfigureNLog(app, loggerFactory);              /*These settings need to be changed*/             app.UseCors(                 options => options                     .AllowAnyOrigin()                     .AllowAnyMethod()                     .AllowAnyHeader()             );              app.UseAuthentication();             //Swagger Set Up             app.UseSwagger();             app.UseSwaggerUI(c =>             {                 c.SwaggerEndpoint("/swagger/v1/swagger.json", "Authentication API V1");             });             app.UseMvc();         }          private static void ConfigureNLog(IApplicationBuilder app, ILoggerFactory loggerFactory)         {              loggerFactory.AddNLog();             loggerFactory.ConfigureNLog("nlog.config");             app.AddNLogWeb();         } 

Clustering using k-medoids

This is the program function code for clustering using k-medoids

def kMedoids(D, k, tmax=100):     # determine dimensions of distance matrix D     m, n = D.shape     # randomly initialize an array of k medoid indices     M = np.sort(np.random.choice(n, k)     # create a copy of the array of medoid indices     Mnew = np.copy(M)     # initialize a dictionary to represent clusters     C = {}     for t in range(tmax):     # determine clusters, i.e. arrays of data indices         J = np.argmin(D[:,M], axis=1)         for kappa in range(k):             C[kappa] = np.where(J==kappa)[0]         # update cluster medoids         for kappa in range(k):             J = np.mean(D[np.ix_(C[kappa],C[kappa])],axis=1)             j = np.argmin(J)             Mnew[kappa] = C[kappa][j]             np.sort(Mnew)             # check for convergence             if np.array_equal(M, Mnew):                 break                 M = np.copy(Mnew)             else:                 # final update of cluster memberships                 J = np.argmin(D[:,M], axis=1)                 for kappa in range(k):                     C[kappa] = np.where(J==kappa)[0]                     # return results             return M, C 

and the I will call The function KMedoids with this program

D = pairwise_distances(arraydata,metric='euclidean')  # split into 2 clusters M, C = kMedoids(D, 2)  print('medoids:') for point_idx in M:     print(arraydata[point_idx] )  print('') # array for get label temp = [] indeks = [] print('clustering result:') for label in C:     for point_idx in C[label]:         print('label {0}: {1}'.format(label, arraydata[point_idx]))         temp.append(label)         indeks.append(point_idx) 

This is the result from this program

clustering result: label 0: [0.00000000e+00 0.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 0.00000000e+00 1.00000000e+00 1.00000000e+00 

Why my result of my program is slow for large data and almost have a result “Memory Error”? I hope someone can help me to review this code to improve its performance to get the result and process large amounts of data.

overly complicated list-culling function

I’m bothered by my answer to this SO question.

I’m pretty sure it’s more efficient than the sort-and-cull implementations, but I’m having trouble expressing that in a way that I trust.

Also, it’s rather convoluted by python standards.
Is there a way to express the same process more clearly, without pages of comments?

The problem statement:

Given a subject list of strings, make a list containing every element of the subject that isn’t a substring of a different element of the subject.

Current solution:

import itertools import operator import typing  Exploded = None Exploded = typing.Dict[str,typing.Union[Exploded,str]]  def explode(subject:typing.Iterable[str])->Exploded:     return {         head: prune_or_follow([tail for _, tail in heads_tails])         for (head, heads_tails)         in itertools.groupby(              ((s[0], s[1:]) for s in subject if s),               operator.itemgetter(0))         if head     }  def prune_or_follow(tails:typing.List[str])->typing.Union[Exploded,str]:     if 1 < len(tails):         return explode(tails)     else: #this is coming from groupby, so it can't be empty.         return tails[0]  def implode(e:Exploded)->typing.Generator[str, None, None]:     for (head, continued) in e.items():         if isinstance(continued, str):             yield head + continued         else:             for tail in implode(continued):                 yield head + tail  def cull(subject:typing.List[str])->typing.List[str]:     return list(implode(explode(subject)))  print(cull(['a','ab','ac','add'])) print(cull([ 'a boy ran' , 'green apples are worse' , 'a boy ran towards the mill' ,  ' this is another sentence ' , 'a boy ran towards the mill and fell'])) 

I know that it works for the two test cases.

Skipping over failed imports until they are needed (if ever)

We have a program with many dependencies. Because the user may not want to use all of them, the program should skip over failed imports and only raise an error if absolutely necessary. e.g. if the user tries to call that class.

I have implemented a way of doing this but I’m not sure it is as good as it could be, it certainly seems somewhat inelegant. I presume there are also some overlooked bugs.

The important file structure is:

Program:   - engines     - __init__.py     - base_engine.py     - ...     - psi4.py     - rdkit.py   - run.py 

The base_engine.py contains the base class Engines which all the other engines (PSI4 in psi4.py, RDKit in rdkit.py … ) inherit from, as well as a Default class.

If any class fails to import, Default is imported instead, but with the name of the class that failed to import (see the __init__.py file).

base_engine.py:

class Engines:     """     Engines base class containing core information that all other engines (PSI4, etc) will have.     """      def __init__(self, molecule):          self.molecule = molecule   class Default:     """     If there is an import error, this class replaces the class which failed to be imported.     Then, only if initialised, an import error will be raised notifying the user of a failed call.     """      def __init__(self, *args, **kwargs):         # self.name is set when the failed-to-import class is set to Default.         raise ImportError(             f'The class {self.name} you tried to call is not importable; '             f'this is likely due to it not being installed.') 

__init__.py:

try:     from .psi4 import PSI4 except ImportError:     from .base_engine import Default as PSI4     setattr(PSI4, 'name', 'PSI4')  try:     from .rdkit import RDKit except ImportError:     from .base_engine import Default as RDKit     setattr(RDKit, 'name', 'RDKit') 

psi4.py:

from Program.engines.base_engine import Engines  # Example import that would fail import abcdefg   class PSI4(Engines):     """     Writes and executes input files for psi4.     """      def __init__(self, molecule):          super().__init__(molecule)      def generate_input(self):          ... 

run.py:

from Program.engines import PSI4  PSI4('example_molecule').generate_input() 

So now when classes are imported at the top of the run.py file, there is no problem even if there’s an import error; if there’s a failed import with PSI4 because abcdefg cannot be imported, Default is simply imported as PSI4 and given the name PSI4 via the setattr().

Then, only if that Default class is called the ImportError is raised and the user can see that the issue was with PSI4.

This seems to work quite well, even when there are multiple failed imports. We can also add extended error messages for each different failed import. Is this the best way of doing something like this, though? It gets quite messy since we have so many files in our engines package.

Please let me know if some relevant code has been omitted and I can add it back. Thanks for any help.

Copy-Pasting (kind of) from Excel to an existing Word table

What I’m trying to do here is to open an excel file and then search and copy/store the data I need (i.e if there is a reference than I copy 2 columns). Afterwards, I paste or write that data into a word table (already exists in my template). Thus, here is my question: Is there a way to make run faster? It runs in about 21sec, and i would like to be faster cause I got plenty of macros to run and if each one runs about 20 sec than my users won’t be satisfied.

Here is the code:

Sub fournitureExcel(trigram As String, nbTable As Long, folderPath As String)      Dim filename As String, dataRange As String, dataC As New Collection     Dim refRow As Long, refColumn As Long, desigColumn As Long                     'la ligne de la trigramme recherche     Dim j As Long, c As Long      With ActiveDocument          .Application.ScreenUpdating = False          On Error Resume Next             Set xlApp = GetObject(, "Excel.Application")         If err Then             Set xlApp = CreateObject("Excel.Application")         End If         On Error GoTo 0          filename = "DE_Nom_art_" & trigram & ".xlsx"         Set xlBook = xlApp.workbooks.Open(folderPath & filename)         xlApp.Visible = False   'does not open the file, read only => faster to get the info          With xlBook.sheets(1)              ' searching for the Reference             Set rg = .Cells.Find(what:="Référence")             refRow = .Range(rg.Address).Row: refColumn = .Range(rg.Address).Column              Set desigAdrs = .Cells.Find(what:="Désignation")             'numero de colone Designation             desigColumn = .Range(desigAdrs.Address).Column: dataRange = "G" & (refRow + 2) & ":I" & 10000             'stock excel data into a collection             For Each cell In .Range(dataRange)                  If cell.Column = refColumn Then                     If Not IsEmpty(cell) Then ' checking if reference exists or not                         'designation & quantite                         dataC.Add .Cells(cell.Row, refColumn - 2).Value: dataC.Add .Cells(cell.Row, refColumn - 1).Value                     End If                 End If             Next cell             xlBook.Close SaveChanges:=False                           ' pour ne pas sauvegarder le document             Set src = Nothing             Set xlApp = Nothing             Set xlBook = Nothing         End With         'ajoute des lignes a la table fournitures i.e table nr3         .Tables(nbTable).Select         c = .Tables(nbTable).Range.Rows.Count         'c = .Tables(nbTable).Rows.Count         If c - (dataC.Count / 2) < 0 Then 'check if we need to add rows or not             With Selection                     .InsertRowsBelow -(c - (dataC.Count / 2))                     With .Shading                         .Texture = wdTextureNone                         .ForegroundPatternColor = wdColorAutomatic                         .BackgroundPatternColor = -603914241                     End With                     .Font.ColorIndex = wdBlack                     'ajout des bordures dans le tableau                     With .Borders                         .InsideLineStyle = wdLineStyleSingle                         .OutsideLineStyle = wdLineStyleSingle                         .InsideColorIndex = wdBlack                         .OutsideColorIndex = wdBlack                     End With             End With         Else             ' do nothing         End If         j = 3   'indice apartir du quel on va commencer a lire les donnees de la collection car on skip les 2 premiers         'fill the table         For i = 2 To dataC.Count / 2             With .Tables(nbTable).Rows(i)                 ' la  designation & la quantites                 With .Cells(1).Range                     .Text = dataC(j):                     .ParagraphFormat.Alignment = wdAlignParagraphLeft 'aligne text to the left                 End With                 .Cells(2).Range.Text = dataC(j + 1)                 With .Range                     .Font.ColorIndex = wdBlack   'text color :black                     .Font.Size = 9 '   Set String size = 9                 '   If the string begins with "Baie" then make it Bold                     If Left(dataC(j), Len("Baie")) = "Baie" Then                         .Bold = True                     Else                         .Bold = False                     End If                 End With                 j = j + 2             End With         Next i         'ActiveDocument.Tables(3).Rows.Last.Cells.Delete 'on efface la derniere ligne         .Application.ScreenUpdating = True     End With End Sub 

Is there any better approach on this rows to columns table?

enter image description here I pass a function into the variable ($ monthly_receivable) to get the value of each months to pass and get the result of a function.. but the process is dumb slow. This was the only January data but it can add a month range example January 2016 to December 2019.

When I try to remove that variable monthly_receivable it was smooth.

This is my code from server-side to view (client-side):

Controller

public function notes_receivable_summary($  start_date, $  end_date) { $  loans_list = $  this->db->query("SELECT                                  borr_name,                                     co_borrower,                                      released_date,                                      due_from,                                      due_to,                                      pn,                                      no_months,                                      loan_ref,                                      loan_id,                                      pn                                  FROM v_borrowers_nr dd                                 WHERE (df between '$  start_date' AND '$  end_date')                                 ORDER BY loan_ref")->result(); $  months     = $  this->db->query("SELECT dd FROM v_months_nr WHERE dd between '$  start_date' and '$  end_date'")->result();  $  data['monthly_receivable'] = function($  date, $  loan_ref, $  loan_id){         $  enc_url = explode('|', $  this->Main_model->encdec($  this->uri->segment(2), 'd'));         $  s_date  = $  enc_url[1];         $  e_date  = $  enc_url[2];         $  sd      = date('Y-m-d', strtotime('-1 months', strtotime($  s_date)));         $  ed      = $  e_date;    $  q             = $  this->db->query("SELECT * FROM f_monthly_rcvble('$  loan_ref', $  loan_id, '$  start_date', '$  end_date', '$  date')")->row();     return $  q; }; $  this->load->view('pages/ajax/reports/sample_nr', $  data); } 

View

<table id="displayTableNR" class="table displayTableNR js-sort-table">   <?php $  month = array(1=>'Jan', 2=>'Feb', 3=>'Mar', 4=>'Apr', 5=>'May', 6=>'Jun', 7=>'Jul', 8=>'Aug', 9=>'Sep', 10=>'Oct', 11=>'Nov', 12=>'Dec'); ?>   <?php $  total_as_of_h = 0; ?>   <?php $  range_date    = !empty($  months) ? date('M Y', strtotime($  months[0]->dd)) . ' - ' . date('M Y', strtotime($  months[count($  months) - 1]->dd)) : null; ?>   <thead>       <tr class="menu1">           <th class="table-head b-right" scope="col">Ref. No.</th>           <th class="table-head b-right js-sort-string fixed-side" scope="col">Name</th>           <th class="table-head b-right fixed-side" scope="col">Co-Borrower</th>           <th class="table-head b-right fixed-side" scope="col"><div class="wd-132px">Release Date</div></th>           <th class="table-head b-right js-sort-date fixed-side" scope="col">From</th>           <th class="table-head b-right js-sort-date fixed-side" scope="col">To</th>           <th class="table-head b-right fixed-side text-right" scope="col">PN</th>           <th class="table-head fixed-side" scope="col">Terms</th>            <?php $  count = 0; ?>           <?php foreach ($  months as $  row): ?>               <?php $  d = explode('-', $  row->dd); ?>               <th class="table-head text-center font-strong <?php echo $  count % 2 === 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>" colspan="10"><?php echo strtoupper($  month[(int) $  d[1]]) . ' ' . $  d[0]; ?></th>           <?php $  count++; ?>           <?php $  total_as_of_h++; ?>           <?php endforeach; ?>            <?php if ($  total_as_of_h === count($  months)): ?>               <th class="td-head text-center" colspan="3">COLLECTION ACTUAL/CLOSED OB/EFP</th>           <?php endif; ?>       </tr>       <tr class="menu2">           <th class="table-head b-right fixed-side"></th>           <th class="table-head b-right fixed-side"></th>           <th class="table-head b-right fixed-side"></th>           <th class="table-head b-right fixed-side"></th>           <th class="table-head b-right fixed-side"></th>           <th class="table-head b-right fixed-side"></th>           <th class="table-head b-right fixed-side"></th>           <th class="table-head fixed-side"></th>            <?php $  count = 0; ?>           <?php foreach ($  months as $  row): ?>               <th class="table-head font-strong <?php echo $  count % 2 === 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Current Target</div></th>               <th class="table-head font-strong amt_pd <?php echo $  count % 2 === 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Actual Collection</div></th>               <th class="table-head font-strong <?php echo $  count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">UA/SP</div></th>               <th class="table-head font-strong <?php echo $  count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Past Due Target UA/SP</div></th>               <th class="table-head font-strong <?php echo $  count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Actual Collection UA/SP</div></th>               <th class="table-head font-strong <?php echo $  count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Past Due Balance UA/SP</div></th>               <th class="table-head font-strong <?php echo $  count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Advanced Payment</div></th>               <th class="table-head font-strong <?php echo $  count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">OB Closed</div></th>               <th class="table-head font-strong <?php echo $  count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Early Full Payments</div></th>               <th class="table-head font-strong <?php echo $  count % 2 == 0 ? 'hexa-color-1' : 'hexa-color-2'; ?>"><div class="wd-132px text-center">Adjustments</div></th>           <?php $  count++; ?>           <?php endforeach; ?>            <?php if ($  total_as_of_h === count($  months)): ?>               <th class="table-head">TOTAL</th>               <th class="table-head"><div class="wd-118px text-center">(<?php echo $  range_date; ?>)</div></th>               <th class="table-head">NR BAL</th>           <?php endif; ?>       </tr>   </thead>   <tbody>    <?php $  totAmntToPay             = 0; ?>               <?php $  totCollection            = 0; ?>               <?php $  totBalance               = 0; ?>                <?php foreach($  loans_list as $  r): ?>   <?php $  name   = explode('|', $  r->borr_name); ?>   <tr class="">     <td class="td-border fixed-side"><?php echo $  r->loan_ref; ?></td>     <?php if (count($  name) < 3): ?>       <td class="td-border br-name-nr fixed-side"><div class="wd-210px"><?php echo strtoupper($  name[0]) . ', ' . strtoupper($  name[1]); ?></div></td>     <?php else: ?>       <td class="td-border br-name-nr fixed-side"><div class="wd-210px"><?php echo strtoupper($  name[0]) . ', ' . strtoupper($  name[1]) . ' ' . strtoupper($  name[2]); ?></div></td>     <?php endif; ?>     <td class="td-border fixed-side"><div class="wd-145px"><?php echo strtoupper($  r->co_borrower); ?></div></td>     <td class="td-border fixed-side"><?php echo date('Y-m-d', strtotime($  r->released_date)); ?></td>     <td class="td-border fixed-side"><?php echo date('Y-m-d', strtotime($  r->due_from)); ?></td>     <td class="td-border fixed-side"><?php echo date('Y-m-d', strtotime($  r->due_to)); ?></td>     <td class="td-border text-right fixed-side"><?php echo number_format($  r->pn, 2); ?></td>     <td class="td-border fixed-side"><?php echo number_format($  r->no_months, 0); ?></td>      <!-- TOTALS VARIABLE -->     <?php $  ct1                   = 0; ?>     <?php $  curr_or_prev_uasp     = 0; ?>     <?php $  tot_prev_uasp_balance = 0; ?>      <?php foreach($  months as $  row): ?>     <?php $  lref = $  r->loan_ref; ?>     <?php $  lid  = $  r->loan_id; ?>     <?php $  nr                     = $  monthly_receivable($  row->dd, $  lref, $  lid); ?>       <?php if (is_object($  nr)): ?>         <td class="td-border text-right"><?php echo number_format($  nr->amount_due, 2); ?></td>         <td class="td-border text-right"><?php echo number_format($  nr->actual_collection, 2); ?></td>           <?php if ($  ct1 == 0): ?>             <td class="td-border text-right"></td>           <?php else: ?>               <td class="td-border text-right"><?php echo number_format($  nr->col_ua_sp, 2); ?></td>           <?php endif; ?>         <td class="td-border text-right"><?php echo number_format($  nr->past_due_target_ua_sp, 2); //Past Due Target UA/SP ?></td>         <td class="td-border text-right"><a href="#" class="clrd-tooltip" data-toggle="tooltip" data-placement="right" title=""><?php echo number_format($  nr->past_due_collection_tot_ua_sp, 2); ?></a></td>         <td class="td-border text-right"><?php echo number_format($  nr->past_due_balance, 2); //Past Due Target Balance ?></td>         <td class="td-border text-right"><a href="#" class="clrd-tooltip" data-toggle="tooltip" data-placement="right" title=""><?php echo number_format($  nr->advanced_payment, 2); ?></a></td>         <td class="td-border text-right"><?php echo number_format($  nr->ob_closed, 2); ?></td>         <td class="td-border text-right"><?php echo number_format($  nr->early_full_payments, 2); ?></td>         <td class="td-border text-right"><?php echo number_format($  nr->adjustments, 2); ?></td>       <?php endif; ?>     <!-- TOTALS -->     <?php $  ct1++; ?>      <?php endforeach; ?>     <td class="td-border text-right total-to-pay"><?php echo number_format($  col_tot_pn, 2); ?></td>     <td class="td-border text-right total-coll"><?php echo number_format($  col_tot_col, 2); ?></td>     <td class="td-border text-right total-bal"><?php echo number_format($  col_tot_pn - $  col_tot_col, 2); ?></td>   </tr> </tbody> <tfoot>     <tr>         <th class="table-head b-right fixed-side">Ref. No.</th>         <th class="table-head b-right fixed-side">Name</th>         <th class="table-head b-right fixed-side">Co-Borrower</th>         <th class="table-head b-right fixed-side">Release Date</th>         <th class="table-head b-right fixed-side">From</th>         <th class="table-head b-right fixed-side">To</th>         <th class="table-head b-right text-right fixed-side"><?php echo number_format($  totPN, 2); ?></th>         <th class="table-head fixed-side">Terms</th>          <?php if ($  total_as_of_h === count($  months)): ?>             <td class="table-head text-right"><?php echo number_format($  totAmntToPay, 2); ?></td>             <td class="table-head text-right"><?php echo number_format($  totCollection, 2); ?></td>             <td class="table-head text-right"><?php echo number_format($  totBalance, 2); ?></td>         <?php endif; ?>     </tr>   </tfoot> </table>   

enter image description here

Robot game in C++

I have a very basic “game” where a robot is placed on a small 5×5 board, and commands are given to it. To start, the robot must be placed on the board, then you may command it to move, or rotate left and right. I have tried to use object oriented concepts, but it was not a requirement for my task. I think I have done an okay job, and I would love to know what I have done incorrectly.

Here are a few “requirements” given to me:

  1. The “place” command takes an x, y position, and a direction or NORTH, EAST, SOUTH, or WEST.
  2. No other commands may be run unless the robot has been placed
  3. Move will move the robot forward by 1, in the direction it is facing.
  4. LEFT and RIGHT will rotate the robot in their respective directions
  5. REPORT will print the current position, and facing direction of the robot
  6. Place is a valid command, even after it has already been placed
  7. Inputs that will cause the robot to fall off the board are to be rejected or ignored
  8. Invalid or “junk” input is to be ignored
  9. The robot will take commands as plaintext, the robot must take this text and run respective instructions given that they are valid

Example input/output:

PLACE 1,3,WEST MOVE REPORT Output: 0,3,WEST 

and here is my robot.cpp

#include "robot.h" #include "tabletop.h" #include "helpers.h"  namespace ToyRobot {     //used as an interface to supply instructions as text, robot will perform     bool Robot::command(std::string instruction)     {         std::istringstream iss(instruction);         std::vector<std::string> tokens{ std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{} };          if (this->commandList.count(tokens[0]) > 0) //is the first token, a valid command?         {             //command is valid             if (tokens[0] == "PLACE")             { //check if there are valid arguments                 if (tokens.size() < 2)                 {                     std::cout << "Error! Not enough arguments for 'PLACE'\n";                     return false;                 }                 else                 {                     try                     {                         uint8_t arg1 = std::stoi(split(tokens[1], ",")[0]);                         uint8_t arg2 = std::stoi(split(tokens[1], ",")[1]);                         std::string arg3 = split(tokens[1], ",")[2];                         this->place(arg1, arg2, arg3);                     }                     catch (...)                     {                         return false;                     }                      return true;                 }             }             else if (tokens[0] == "MOVE")             {                 this->move();             }             else if (tokens[0] == "LEFT" || tokens[0] == "RIGHT")             {                 this->rotate(tokens[0]);             }             else if (tokens[0] == "REPORT")             {                 this->printStatus();             }              return true;         }         else             return false;     }      //checks if a given position is valid (used only by other methods)     bool Robot::isValidPosition(uint8_t x, uint8_t y)     {         if (x < 0 || x > TABLETOP_MAX_X || y < 0 || y > TABLETOP_MAX_Y)             return false;         else             return true;     }      //places robot, ignores invalid positions     bool Robot::place(uint8_t x_place_pos, uint8_t y_place_pos, std::string facingDirection)     {         if (x_place_pos < 0 || x_place_pos > TABLETOP_MAX_X || y_place_pos < 0 || y_place_pos > TABLETOP_MAX_Y)             return false;          if (this->facingDirections.count(facingDirection) == 0) //check if given facing direction was valid             return false;          this->x_pos = x_place_pos;         this->y_pos = y_place_pos;          this->facingDirection = this->facingDirections[facingDirection];          this->placed = true;         return true;     }      //moves robot forward by one, ignored invalid movements     bool Robot::move()     {         if (this->placed)         {             uint8_t sim_x = this->x_pos;             uint8_t sim_y = this->y_pos;              //simulate movement             if (facingDirection == 0)                 sim_y += 1;             else if (facingDirection == 1)                 sim_x += 1;             else if (facingDirection == 2)                 sim_y -= 1;             else if (facingDirection == 3)                 sim_x -= 1;              if (isValidPosition(sim_x, sim_y))//if it was valid, set and return true             {                 this->x_pos = sim_x;                 this->y_pos = sim_y;                 return true;             }             else //invalid move (would be out of bounds)                 return false;         }         else //not placed             return false;     }      //rotates robot given a direction string     bool Robot::rotate(std::string direction)     {         if (this->placed)         {             uint8_t sim_direction = this->facingDirection;              if (direction == "LEFT")                 sim_direction = (sim_direction + 3) % 4; //rotate left             else if (direction == "RIGHT")                 sim_direction = (sim_direction + 1) % 4; //rotate right             else                 return false; //invalid input              this->facingDirection = sim_direction;             return true;         }         else //not placed             return false;     }      void Robot::printStatus()     {         if (this->placed)             std::cout << int(this->x_pos) << ',' << int(this->y_pos) << ',' << (this->reversedDirections[this->facingDirection]) << "\n";         else             std::cout << "Robot is not yet placed on the tabletop!\n";     } } 

robot.h

#pragma once  #include "stdafx.h"  namespace ToyRobot {     class Robot     {     private:         bool placed = false;         uint8_t x_pos = NULL;         uint8_t y_pos = NULL;         uint8_t facingDirection = NULL;          const std::unordered_set<std::string> commandList = { "PLACE","MOVE","LEFT","RIGHT","REPORT" };          std::unordered_map <std::string, int> facingDirections             = { {"NORTH", 0}, {"EAST", 1},                 {"SOUTH", 2}, {"WEST", 3} };          std::unordered_map <int, std::string> reversedDirections             = { {0, "NORTH"}, {1, "EAST"},                 {2, "SOUTH"}, {3, "WEST"} };          bool isValidPosition(uint8_t, uint8_t);     public:         Robot() //constructor         {         }          bool command(std::string);         bool place(uint8_t, uint8_t, std::string);         bool move();         bool rotate(std::string);         void printStatus();     }; } 

helpers.cpp

#include "stdafx.h" #include "helpers.h"  //python's "split" function, implemented in C++. returns a vector of split std::strings by a specified delimiter std::vector<std::string> split(const std::string& in, const std::string& delim) {     using std::string;     using std::vector;      string::size_type start = in.find_first_not_of(delim), end = 0;      vector<string> out;     while (start != in.npos)     {         end = in.find_first_of(delim, start);         if (end == in.npos)         {             out.push_back(in.substr(start));             break;         }         else         {             out.push_back(in.substr(start, end - start));         }         start = in.find_first_not_of(delim, end);     }     return out; } 

helpers.h

#pragma once  #include "stdafx.h"  std::vector<std::string> split(const std::string& in, const std::string& delim); 

tabletop.h (there is no tabletop.cpp, as there is no need for it)

#pragma once  #include "stdafx.h"  constexpr auto TABLETOP_MAX_X = 4; constexpr auto TABLETOP_MAX_Y = 4;  //0,0 is south west corner https://i.imgur.com/pm2XVHx.png //Tabletop is never used, but it is here if required class Tabletop { private:     const uint8_t x_len = TABLETOP_MAX_X;     const uint8_t y_len = TABLETOP_MAX_Y; public: }; 

and finally my stdafx.h

#pragma once  #include <iostream> #include <string> #include <unordered_map> #include <unordered_set> #include <sstream> #include <algorithm> #include <iterator> 

My robot header and implementation is in a namespace, as it is to be compiled into a library.

How is my project structure? Thanks

MySQL Stored Procedure How to Shorten the Statement

Just want to ask your help regarding creation of store procedure in MySQL database. This is my first time in creating the store procedure. Most likely, I used to creation views but this time, I need to implement a store procedure in the mysql database. I have here created a simple one but I think its redundant in statement. Is there anyone who can help me shortened the statement?. With this, it can help me to study more regarding stored procedure. Please see code for reference. Much appreciated with your help.

DELIMITER $  $    USE `doris_master_data`$  $    DROP PROCEDURE IF EXISTS `webserver_service_order`$  $    CREATE DEFINER=`root`@`localhost` PROCEDURE `webserver_service_order`( IN xselection BIGINT(8), IN xreceived_from_date BIGINT(8), IN xreceived_to_date BIGINT(8)) BEGIN  IF xselection=0 THEN  SELECT DISTINCT so.service_code, sl.service_name, xx.Total_Services FROM  service_order so INNER JOIN services_lists sl ON so.service_code=sl.service_code LEFT OUTER JOIN  (     SELECT     a.service_code,     COUNT(DISTINCT CONCAT(a.service_code,'-',a.service_order_code)) AS Total_Services     FROM     service_order a     WHERE     (a.service_order_date_received BETWEEN xreceived_from_date AND xreceived_to_date)     AND a.service_code_is_active=1     AND a.requirement_code_is_active=1     GROUP BY a.service_code ) AS xx ON so.service_code=xx.service_code WHERE (so.service_order_date_received BETWEEN xreceived_from_date AND xreceived_to_date) AND so.service_code_is_active=1 AND so.requirement_code_is_active=1;  ELSE SELECT DISTINCT so.service_code, sl.service_name, xx.Total_Services FROM  service_order so INNER JOIN services_lists sl ON so.service_code=sl.service_code LEFT OUTER JOIN  (     SELECT     a.service_code,     COUNT(DISTINCT CONCAT(a.service_code,'-',a.service_order_code)) AS Total_Services     FROM     service_order a     WHERE     (a.service_order_date_received BETWEEN xreceived_from_date AND xreceived_to_date)     AND a.service_code_is_active=1     AND a.requirement_code_is_active=1     GROUP BY a.service_code ) AS xx ON so.service_code=xx.service_code WHERE so.service_code=xselection AND (so.service_order_date_received BETWEEN xreceived_from_date AND xreceived_to_date) AND so.service_code_is_active=1 AND so.requirement_code_is_active=1;  END IF;   END$  $    DELIMITER ;