I am trying to loop the list through the function that i made. What I want to do with the loop is that the variable: "$huidige_folder" inside the function is filled with one location at a time that is in the list, loop and continue with the next location in the list
So first item in the list: "C:\Users\Nick\Desktop\Test1". It uses
this location in the function
Then C:\Users\Nick\Desktop\Test2". It uses this location in the
function
Then C:\Users\Nick\Desktop\Test3". It uses this location in the
function
But when i run the code it will only run the function for the first item in the list. That works and it does what i want.
But after that it stops and doenst run the funtion for the other 2 items in the list.
What am i doing wrong?
$path_dagelijkse_controle = "C:\Users\Nick\Desktop\Test1",
"C:\Users\Nick\Desktop\Test2",
"C:\Users\Nick\Desktop\Test3"
function Dagcontrole_folders_maken {($huidige_folder)
$Dagelijkse_controle = "Dagelijkse controle"
$datum_vandaag = $(Get-Date).toString('yyyy-MM-dd')
$jaar = $datum_vandaag.Substring(0,4)
$maand = $datum_vandaag.substring(5, 2)
$dag = (get-date).DayOfWeek
$path_jaar = Get-Item -Path "$huidige_folder\**" -Include *$jaar*
$path_maand = Get-Item -Path "$huidige_folder\$jaar\**" -Include *$maand*
$folder_maand = Get-Date -UFormat "%m - %B"
if ($path_jaar) {
Write-Output "Do Nothing"
}
Else {
md -Path "$huidige_folder\$jaar"
}
if ($path_maand) {
md -Path "$huidige_folder\$jaar\$folder_maand\Dagelijks\$datum_vandaag"
}
Else {
md -Path "$huidige_folder\$jaar\$folder_maand" # Makes the month folder
md -Path "$huidige_folder\$jaar\$folder_maand\Dagelijks\$datum_vandaag" # Makes a folder with current date inside the month folder
}
}
Foreach ($i in $path_dagelijkse_controle) {
Dagcontrole_folders_maken($i)
}
I would change the declaration of your function:
function Dagcontrole_folders_maken ([String]$huidige_folder) {
It means that $huidige_folder is declared as a String. But the main issue was the { character placed at the wrong place. It must be placed after the arguments.
I would also suggest you to parse all the elements within your function. You can write your ForEach into the function and give an array of strings as an argument. That way, your function would work with one or more elements.
function Dagcontrole_folders_maken ([String[]]$huidige_folder) {
ForEach($folder in $huidige_folder) {
...
Try removing the parentheses around $i.
Unlike most languages, Powershell does not require parentheses around the actual parameters on a function call. They may be doing harm.
Also, thanks to lieven Keersmaekers, the left brace in the definition should be after the parameter definiton, not before it.
Related
I'm trying to convert this recursive function to an iterative one using a stack:
void GetToTownRecursive(int x, Country &country, AList *accessiblesGroup, vector<eTownColor> &cities_colors)
{
cities_colors[x - 1] = eTownColor::BLACK;
accessiblesGroup->Insert(x);
List *connected_cities = country.GetConnectedCities(x);
if (!connected_cities->IsEmpty())
{
ListNode *curr_city = connected_cities->First();
while (curr_city != nullptr)
{
if (cities_colors[curr_city->GetTown() - 1] == eTownColor::WHITE)
{
GetToTownRecursive(curr_city->GetTown(), country, accessiblesGroup, cities_colors);
}
curr_city = curr_city->GetNextNode();
}
}
}
The function takes a town number as an input and returns a list of towns that are connected to that town (directly as well as indirectly).
I'm having difficulty converting it because of the while loop within and because the only action taken after the recursive call is the promotion of the list iterator - curr_city. What should I push into the stack in this case?
Would be glad for your help!
The action taken after the recursive call is the whole remainder of the while loop (all the remaining iterations). On the stack, you have to save any variables that could change during the recursive call, but will be needed after. In this case, that's just the value of curr_city.
If goto was still a thing, you could then replace the recursive call with:
save curr_city
set x = curr_city->GetTown()
goto start
Then at the end, you have to
check stack
If there's a saved curr_city, restore it and goto just after (3)
Because it's not acceptable to use gotos for this sort of thing (they make your code hard to understand), you have to break up your function into 3 top-level parts:
part 1: all the stuff before the first recursive call, ending with 1-3
part 2: a loop that does all the stuff between recursive calls, ending with 1-3 if it gets to another recursive call, or 4-5 if it doesn't.
part 3: anything that happens after the last recursive call, which is nothing in this case.
Typically there is then a lot of cleanup and simplification you can do after this rearrangement.
The basic idea would be something like the following.
void GetToTown(int x, Country &country, AList *accessiblesGroup,
vector<eTownColor> &cities_colors)
{
Stack<int> pendingX = new ...
pendingX.push(x);
while (!pendingX.isEmpty()) {
int localX = pendingX.Pop();
cities_colors[localX - 1] = eTownColor::BLACK;
accessiblesGroup->Insert(localX);
List *connected_cities = country.GetConnectedCities(localX);
if (!connected_cities->IsEmpty())
{
ListNode *curr_city = connected_cities->First();
while (curr_city != nullptr)
{
if (cities_colors[curr_city->GetTown() - 1] == nColor::WHITE)
{
pendingX.Push(curr_city->GetTown());
}
curr_city = curr_city->GetNextNode();
}
}
}
}
I have been banging my head on a problem related to lists. I am a beginner, so sorry if this is a bit unclear..
My goal is to be able to write numbers from keyboard inputs, that will be displayed in a UI element in Unity.
To do so i decided to use a list, because i was wanting to add control to the display, (for example, to add a "." every 3 digits so that they would be more easily readable, like "3.489.498").
So basically, i store new inputs in this list, then i display this list with a display.text every time there is a new digit as an input.
This works actually very well, but then i wanted to be able to delete the last typed element. So i added a backspace hotkey with a List.Remove().
And this is where the nightmare starts. The thing seems to work when i press "1" and deletes right after, but for some reasons it does not work with 2.
Error message is : "Argument out of range, parameter name: index."
I just can't wrap my head around this problem :(
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class BoxCreateNumber : MonoBehaviour {
public Text textDisplayNumber;
public List<int> numberList = new List<int>();
void Start () {
}
void Update () {
CollectingNumberInput ();
}
void CollectingNumberInput(){
if (Input.GetKeyDown(KeyCode.Keypad1)){
numberList.Add (1);
//numberList.Insert (numberList.Count,1);
DisplayNumber ();
} else if (Input.GetKeyDown(KeyCode.Keypad2)) {
numberList.Add (2);
//numberList.Insert (numberList.Count,2);
DisplayNumber ();
} else if (Input.GetKeyDown(KeyCode.Backspace)) {
numberList.Remove(numberList.Count);
DisplayNumber ();
}
}
void DisplayNumber(){
textDisplayNumber.text = "";
for (int i = 0; i <= numberList.Count; i++) {
textDisplayNumber.text += numberList [i];
}
}
}
You just need to read the documentation.
public bool Remove(
T item
)
Parameters
item - The object to remove from the List. The value can be null for reference types.
Instead of passing the function the object to remove, you pass the number of elements in the list. This means that if the list contains element "1" as its only element, then it will work, but only by accident.
Calling RemoveAt(numberList.Count - 1) will do what you want. RemoveAt takes the index of the element to remove, and the indices are 0-based, so the last one is Count-1.
Try this to remove the last element
numberList.RemoveAt(numberList.Count-1);
Giving as simple of a background context as I possibly can, which I don't think is necessary for what I'm trying to figure out at the moment, I'm trying to implement a graph representation via adjacency list, in my case being an unordered map that has a string key to a struct value that contains Vertex object pointers (the object that is identified by the key), and a vector of its dependencies. The goal is to output a critical path via a sort of DAG resolution algorithm.
So when I need to output a critical path, I'm trying to use a recursive solution I implemented. Basically it looks for a base case (if a job has no dependencies), return a print out of its id, start time and length. Otherwise, find the longest running (in terms of time length) job in its dependency list and call the function on that until you find a job with no dependencies. There can be more than one critical path, and I don't have to print out all of them.
MY QUESTION: I'm debugging this at the moment, and it has no problem printing out a job's properties when its a base case. If it has to recurse through though, the string always comes back as empty (""). Is the recursive call making my string go out of scope by the time it comes back to the caller? Here is the code structure for it. All of the functions below are public members of the same Graph class.
string recurseDeps(unordered_map<string, Dependencies>& umcopy, string key) {
if (umcopy[key].deps.empty()) {
string depPath = " ";
string idarg, starg, larg, deparg;
idarg = key;
starg = " " + to_string(umcopy[key].jobatKey->getStart());
larg = " " + to_string(umcopy[key].jobatKey->getStart() + umcopy[key].jobatKey->getLength());
umcopy.erase(key);
return depPath + idarg + starg + larg;
}
else {
string lengthiestDep = umcopy[key].deps[0];
for (auto i = begin(umcopy[key].deps); i != end(umcopy[key].deps); i++) {
if (umcopy[*i].jobatKey->getLength() >
umcopy[lengthiestDep].jobatKey->getLength()) {
lengthiestDep = *i;
}
}
recurseDeps(umcopy, lengthiestDep);
}
}
string criticalPath(unordered_map<string, Dependencies>& um, vector<Vertex*> aj) {
unordered_map<string, Dependencies> alCopy = um;
string path = aj[0]->getId();
for (auto i = begin(aj); i != end(aj); i++) {
if (um[(*i)->getId()].jobatKey->getLength() >
um[path].jobatKey->getLength()) {
path = (*i)->getId();
}
}
return recurseDeps(alCopy, path);
}
Later on down in the class members, a function called readStream() calls the functions like so:
cout << time << criticalPath(adjList, activeJobs) << endl;
You're not returning the value when you recurse. You're making the recursive call, but discarding the value and just falling off the end of the function. You need to do:
return recurseDeps(umcopy, lengthiestDep);
First of all, to answer your question, since you return by value the string is copied so no need to worry about variables going out of scope.
Secondly, and a much bigger problem, is that not all paths of your recursive function actually returns a value, which will lead to undefined behavior. If your compiler doesn't already warn you about this, you should enable more warnings.
I am looking for a grep, sed, or awk command that will recursively search through files for a function name and if a function name is matched then print the contents of that function.
int function_name(){
//Body
for(int i = 0; i < 3; ++i){
//this too
}
//with this
}
I want to be able use a terminal command that if I don't know what file function_name()is in I can search forfunction_name()` and it will print out
//Body
for(int i = 0; i < 3; ++i){
//this too
}
//with this
What I am using now that kind of works is grep -r -A 100 "function_name()" * but that always shows 100 lines after finding the function. The problem is that some functions are less than 100 and it shows stuff I don't need and some are larger than 100 lines which get cut off.
I am not too familiar with Regular Expressions but I would like it to print everything between the curly braces { Print This }, even if there are curly braces within the outer most curly braces.
As I said in comments, regular expressions available in the standard UNIX tools can't match braces. Things get even more ugly when you consider braces in strings, comments...
Here is a possible solution using indent matching. If you save this as findfunc.awk:
BEGIN {
printing = 0;
indent = "";
}
{
if (printing) {
if ($0 ~ ("^"indent"}$")) {
printing = 0;
} else {
print;
}
} else if ($0 ~ ("^[^(]*"name"\\(.*\\)\\s*{$")) {
indent = gensub(/^(\s*).*$/, "\\1", $0);
printing = 1;
}
}
you could invoke it like this:
awk -f findfunc.awk name=function_name source.c
Update:
Thanks Ben, I decided to copy the URL to another structure and modify that one with StructUpdate(). Here's the code if anyone's interested (specific to my application, but you can edit the lines with comments to get a useful function).
function rebuildURL(key, value)
{
var URLstring = "";
var VarCount = 0;
var tmpURL = duplicate(URL);
var VarSeparator = "";
structUpdate(tmpURL, arguments.key, arguments.value);
for (key in tmpURL)
{
if (tmpURL[key] neq "" and tmpURL[key] neq "10000" and tmpURL[key] neq "1") `<!--- remove the tmpURL[key] neq "10000" and "1"--->`
{
if (VarCount neq 0)
{
VarSeparator = "&";
}
else
{
VarSeparator = "";
}
URLstring = URLstring & VarSeparator & "#Lcase(key)#" & "=#Lcase(tmpURL[key])#";
VarCount = VarCount + 1;
}
}
structClear(tmpURL); `<!---not sure if this is necessary, but probably can't hurt unless you are processing thousands of links --->`
return(URLstring);
}
Thanks again!
Scott
Hey guys,
I'm writing a custom function to rework the URL for links in my pages, and I'm getting the following error:
Complex object types cannot be converted to simple values.
The expression has requested a variable or an intermediate expression result as a simple value, however, the result cannot be converted to a simple value. Simple values are strings, numbers, boolean values, and date/time values. Queries, arrays, and COM objects are examples of complex values.
The most likely cause of the error is that you are trying to use a complex value as a simple one. For example, you might be trying to use a query variable in a cfif tag.
The error occurred in C:\ColdFusion8\wwwroot\pascalnew\turbos.cfm: line 8
Called from C:\ColdFusion8\wwwroot\pascalnew\turbos.cfm: line 108
Called from C:\ColdFusion8\wwwroot\pascalnew\turbos.cfm: line 93
Called from C:\ColdFusion8\wwwroot\pascalnew\turbos.cfm: line 1
Called from C:\ColdFusion8\wwwroot\pascalnew\turbos.cfm: line 1
6 : URLvar = "#URL#";
7 : switch(param)
8 : {
9 : case 'mfr':
10 : {
Here's my function code:
<cfscript>
function SetURL(param, paramval)
{
URLvar = "#URL#";
switch(param)
{
case 'mfr':
{
IF (URLvar contains "mfr")
{
REReplaceNoCase(URLvar, "mfr=^[^\&]", "mfr=#paramval#", "All");
}
break;
}
}
return(URLvar);
}
</cfscript>
Here's what I was testing it with:
<cfset urlvar = SetUrl("mfr", "edwards")>
<cfdump var="#urlvar#">
How is "mfr" a complex variable??
Thanks,
Scott
When you use CFScript, some versions report the beginning of the block as the line with the error.
When you assign "#URL#" to URLVar, you are creating a pointer to the URL scope. then, you attempt to use the contains operator on it. Contains, however, only compares two simple values.
So, your attempt to reference a complex value as a scalar actually comes here:
IF (URLvar contains "mfr")
{
REReplaceNoCase(URLvar, "mfr=^[^\&]", "mfr=#paramval#", "All");
}
At a guess, you are trying to look at the URL itself, not the URL scope. You can assemble this from parts of the CGI scope, including SERVER_NAME, SCRIPT_NAME, AND QUERY_STRING (or you can look at the individual part you need).
Added: If you want to know if a variable is passed in the url, I think you are overthinking this. Let's say you have a param and a paramval to replace it with. You could do it like this:
function paramReplace(param, paramVal, scope)
{
if(structkeyexists(arguments.scope, arguments.param))
{
arguments.scope[arguments.param] = arguments.paramVal;
}
}
paramReplace("mfr", "fred", URL);
This simply uses structKeyExists to find out if that variable exists in the appropriate scope, then replaces the value if it does. If you need to rebuild your actual query string, you can do so later. This avoids scenarios where you get bad data if your query string contains something like "zone=mfr".
I've not tested this -- it's off the cuff -- so it may need tweaking, but it should get you started.