Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1751.

Solve : Input of certain character in VB-6 application?

Answer»

Sir,
I want to know that in VB-6 application
1- How can we restrict a user to input certain character (Alpha) ie only A to
Z in a text box in upper case. For example, as we restrict a user to enter
only numerics in a text box by passing a condition " if keyascii >=0 and
keyascii <=9"
2- How can we check that input is only alpha. For example to check that
whether input is numeric or not, we pass a condition of IsNumeric(). May
IsAplha() condition be USED in VB-6 or not?. If no, how can we check that
it is alpha or not other wise error message should appear .
Thanks in Advance.Quote from: lohani on July 08, 2010, 12:18:59 PM

1- How can we restrict a user to input certain character (Alpha) ie only A to
Z in a text box in upper case. For example, as we restrict a user to enter
only numerics in a text box by passing a condition " if keyascii >=0 and
keyascii <=9"
by changing keyascii to 0 in a control's "KeyPress" event, you "null" the input as if it never happened. Using the IsAlpha function I provide lower down:
Code: [Select]Private Sub Text1_KeyPress(KeyAscii as Integer)

KeyAscii = KeyAscii * Abs(IsAlpha(Chr$(KeyAscii)))

End Sub


IsAlpha will return either true or false- true is -1, the abs of which is 1 and that is multiplied by keyascii. Basically, if the return is false, keyascii is changed to 0, otherwise it remains the same.

2- How can we check that input is only alpha. For example to check that
whether input is numeric or not, we pass a condition of IsNumeric(). May
IsAplha() condition be used in VB-6 or not?. If no, how can we check that
it is alpha or not other wise error message should appear .
Thanks in Advance.
[/quote]
There is no IsAlpha Function in VB. But you can easily write your own:
Code: [Select]Public Function IsAlpha(ByVal InputString As String) As Boolean

Dim uppercaseasc As Integer, I As Long
For I = 1 To Len(InputString)
uppercaseasc = Asc(UCase$((Mid$(InputString, I, 1))))
If Not uppercaseasc >= 65 And uppercaseasc <= 90 Then
IsAlpha = False
Exit Function
End If



Next
IsAlpha = True
End Function

The above function returns true for alphanumeric characters- even space doesn't get through. make adjustments as necessary.This is my favorite WAY to see if a character is one of a set:

Code: [Select]Function IsAlpha(chr As String)
If InStr(1, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", chr) <> 0 Then IsAlpha = True
End Function
All characters that should pass go in the second argument's literal string.

InStr is USEFUL Quote from: Fleexy on July 15, 2010, 12:25:07 PM
This is my favorite way to see if a character is one of a set:

Code: [Select]Function IsAlpha(chr As String)
If InStr(1, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", chr) <> 0 Then IsAlpha = True
End Function
First: completely trivial and MEANINGLESS nitpick: if you are going to specify the start argument as 1, just omit it entirely (1 is the default. (the OP requested VB6 so I assume that you are using it (the InStr Function should not be used in VB.NET), and if not, SHAME ON YOU for using the legacy functions in VB.NET! ).) Also, why not make the alphabetic string a constant? maybe even settle on the lower case or uppercase sequence only, and use LCase or UCase to change the case of the input before comparison?

IMO an IsAlpha() should mirror the functionality of the built in IsNumeric() Function- when you say IsNumeric("32") you get true, with your IsAlpha, IsAlpha("CB") returns False. Mine attempts to work with strings of any length, in a similar fashion to IsNumeric. Although to truly emulate it's function it should probably Trim() before the loop.


My version of a single-character IsAlpha function would be this:

Code: [Select]Public Function IsAlpha(char as String) as Boolean
Dim ucaseasc as Integer
ucaseasc=Asc(Ucase$(char))
IsAlpha = (ucaseasc >=65 and ucaseasc <= 90)
End Function



And, because I have discovered that C# is superior in nearly every way to my old love VB6, this is the C# version:

Code: [Select]private static bool IsAlpha(String alphastring)
{
return alphastring.ToUpper().All((w) => (w >= 65 && w <= 90));
}
Yep, a single line.
lambda expressions are awesome. The great thing is that in C#, and many other object oriented languages, a String is really just an array of Char objects, in this case, I am using the free extension methods provided on any IEnumerable<> Implementation. In this case, the "All()" extension method is acting on the IEnumerable that represents the string itself, then the lambda expression is executed for each character, where w is the iterating item. the All() function returns true if they all return true, and false otherwise. in this case, it's an extremely useful shorthand for what I would otherwise implement as a foreach, something like this:

Code: [Select]private static bool IsAlpha(String alphastring)
{
foreach(char w in alphastring.ToUpper())
{
if (!(w >= 65 && w <= 90)) return false;
}
return true;
}


Which is a version of the original VB6 solution I gave, but that doesn't suck. (I clearly rushed through my original VB6 implementation, as I should be calling UCase$() only a single time before the loop, rather then for every single character. Oh well.
1752.

Solve : Beginner who needs some help troubleshooting my c# code?

Answer»

I have been working on making a hangman game, and have run into an issue where the error counter only counts one incorrect letter. After that it will not count any other incorrect letters and stops at 1. It is supposed to count up to 7 INCCORECT letters, where a message telling you that you have lost should appear. (DU har tapt og klarte det ikke denne gangen.) I cannot figure out where my code is incorrect and what elements i need to change in oreder to fix this. Hoping to get some SUGGESTIONS and help with what I am doing wrong

Thanks in advance! -Jc

[attachment deleted by admin to conserve space]You are using the "Feil" variable to try to count the number of failures, correct?

But it will always be at most one, because it's declared a local variable and thus won't "survive" for subsequent clicks. You check ifi the guess is wrong,. then increment feil if it is, but feil will always be zero at that point, so the increment will only ever make it 1.

Move the DECLARATION so that it is a member variable- remove the int Feil=0 inside the button click and move it to above the click event as

Code: [Select]private int feil=0

Then it will count to 7... And beyond, but I suppose that will be your next problem to tackle Thanks, that gave me some more insight. But now that I have added that line above the click event for the button none of my labels, textboxes or image references in the code are recognized, for EXAMPLE ( The name txtGjett does not excist in the current context) and the button click event now shows a ( new protected member in sealed class).Add a semicolon.

1753.

Solve : hi all?

Answer»

I Want to know system design specification to meet REQUIREMENTS in the labs GIVEN below
1 PROGRAMMING lab
2 autocad lab
3 microsoft office lab
and justify suitability of design specifications for their above taskWe aren't here to do your HOMEWORK...

1754.

Solve : I need help to solve IMAP IDLE problem from gmail?

Answer»

Sorry for my bad enlish first.
Our programmer making IMAP IDLE program to send mail automatically to other e-mail but it KEEP connetion timming out so it made delay sending everyday.
He also doesn't know why it keep happening.
we think this is g-mail problem with imap fail reconnect.
This error is "about: socket error: EOF".
should i use another e-mail service to use this program?

here are errors what i want to show you.
I really wnat to FIX it and hope to get any anwer to solve this problem.
thanks.


2015-03-11 18:55:04,101 - Mailbot - ERROR - imap fail reconnect
Traceback (most recent call last):
File "/root/src/mailbot.py", line 89, in poll
text,res=self.imap.idle_done()
File "/usr/local/lib/python2.7/dist-packages/imapclient/imapclient.py", line 504, in idle_done
return self._consume_until_tagged_response(self._idle_tag, 'IDLE')
File "/usr/local/lib/python2.7/dist-packages/imapclient/imapclient.py", line 932, in _consume_until_tagged_response
line = self._imap._get_response()
File "/usr/lib/python2.7/imaplib.py", line 916, in _get_response
resp = self._get_line()
File "/usr/lib/python2.7/imaplib.py", line 1011, in _get_line
raise self.abort('socket error: EOF')
abort: socket error: EOF




===============




2015-03-11 18:58:15,560 - Mailbot - ERROR - imap fail reconnect
Traceback (most recent call last):
File "/root/src/mailbot.py", line 89, in poll
text,res=self.imap.idle_done()
File "/usr/local/lib/python2.7/dist-packages/imapclient/imapclient.py", line 504, in idle_done
return self._consume_until_tagged_response(self._idle_tag, 'IDLE')
File "/usr/local/lib/python2.7/dist-packages/imapclient/imapclient.py", line 932, in _consume_until_tagged_response
line = self._imap._get_response()
File "/usr/lib/python2.7/imaplib.py", line 916, in _get_response
resp = self._get_line()
File "/usr/lib/python2.7/imaplib.py", line 1011, in _get_line
raise self.abort('socket error: EOF')
abort: socket error: EOF

=====
00:00:23,825 - Mailbot - ERROR - [emailprotected] imap fail reconnect
Traceback (most recent call last):
File "/root/src/mailbot.py", line 89, in poll
text,res=self.imap.idle_done()
File "/usr/local/lib/python2.7/dist-packages/imapclient/imapclient.py", line 504, in idle_done
return self._consume_until_tagged_response(self._idle_tag, 'IDLE')
File "/usr/local/lib/python2.7/dist-packages/imapclient/imapclient.py", line 932, in _consume_until_tagged_response
line = self._imap._get_response()
File "/usr/lib/python2.7/imaplib.py", line 916, in _get_response
resp = self._get_line()
File "/usr/lib/python2.7/imaplib.py", line 1011, in _get_line
raise self.abort('socket error: EOF')
abort: socket error: EOFIt APPEARS he is using a scrip tin Python to send and receive e-mail.
Errors messages are not enough to identify the problem.
Please provide either the code or a descriptive OUTLINE of the program.


1755.

Solve : help with dictionaries in python?

Answer»

hi i'm trying to elarn programming, but as of today i've been stuck at 2 challenges, i am to write the who's your daddy program if you are familiar with it, i need a dictionary to hold father/son name pairs, and i need the user to be able to search the dictionary by kids names, and later on add the functionality of having grandfather/father pairs stored in a dictionary, and have it print the grandfather/father associated with the father/kid pair being printed.

my idea for how to make this program is i'd CREATE a dictionary (fathers as keys, sons as values) then have the user search the dictionary by values, if a corresponding key is found it will print both key and value, and then have it print the corresponding grandfather/father key/value the problem seems to be i can't get a straight answer anywhere on how the *censored* i search a dictionary by value.
i've been stuck on this problem close to 10 hours by now and i can't let it go, so help would really be appreciated Maybe this will help

http://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary
My thoughts on this is that every object given a unique identity and then concatenate a string with lineage association. Such as:

object 1 = 001
object 2 = 002
object 3 = 003

If object 2 ( 002 ) makes another object its object 4 ( 004 ), but object 4 was created from object 2 and so the lineage string in a database for example would be ( 004 002 ) If object 2 makes another object 5 ( 005 ), the database would have a lineage string of ( 005 002 ) if object 5 makes an object 6 then it would be a lineage string associated with object 6 of ( 006 005 002 ).

Not sure if this is a lineage problem that you have, where you want to maintain which objects are created from each other or some other problem. You have father/son and grandfather and the father as a key and son as a value, what does that make the grandfather then... so I am thinking instead of apples to oranges of father as a key and son as a value that concatenating a lineage string might work out best to append to the string its origin to maintain a lineage.

Thing is that you dont have anything here referring to a database and maybe you are going to be doing this possibly within python itself. This will require maintaining a flat database writing to files and populating arrays and string variables to populate the info, and the file that is written to to store the lineage information is going to grow quickly as each object spawns off a new object and the lineage appended to the lineage string data for the new object, so do you really need to have lineage back to the beginning, or maybe just 6 deep etc.

Here is an example of how it will grow in size where each object entry will consume more storage memory than the other

object 12 has a lineage string of ( 012 011 010 009 008 007 006 005 004 003 002 001 ) assuming the initial object only had 1 offspring object and then each generation maintained the same spawning of a single object. All 12 objects still exist but object 12 has lineage going back to object 1 and so the string of 12 back to 1.

object 12 spawns off a son and so that son is object 13 so it then has a string of ( 013 012 011 010 009 008 007 006 005 004 003 002 001 )

Where info in bold is the father and grandfather and great , great great, great great great and so on down the line back to the lowest object value of its lineage.

*This numbering only for example purposes the 000 to 999 RANGE of each object works for 1000 objects and so if you want greater than 1000 objects you could potentially have a lineage of ( 197387 167987 133290 121000 ....... a long string of lineage going back to the beginning of object 1 )The answer is: You don't.

Well, not really. You CAN search a dictionary for a key given a value- but it's going to be a sequential search- you'd have to look through every item and find the one with the correct value. You would also have to decide what to do when more than one key has the same value. Fact is, this is slow and very poor design, because you are basically misusing the Dictionary.

As a solution, We can discount adding the reverse association to the dictionary- eg, the son key returns the father key as well, because this would mean that a son could not be a father which would obviously be no good for your required scalability to include grandfathers.

The solution, IMO, would be to maintain two Dictionaries. One that indexes the sons by their father, and one that indexes fathers by their sons (the one you already have). when you add one in you add the appropriate values to each dictionary; when you define that Bob is the Son of George, for example, you add Bob with the Key George to your existing dictionary, but you also add George with the key Bob to the second dictionary; then you use the correct dictionary based on how you are searching.

Of course, this means that any father can only ever have one son, which is implied somewhat anyway since your original dictionary couldn't have more than one son indexed by the father anyway.

Realistically if the desire is to create a more full "Family Tree" than you would want to explore the CREATION of an Actual Tree Data structure.Quote from: BC_Programmer on February 20, 2017, 02:36:09 PM

The answer is: You don't.
You beat me to it. This isn't how a dictionary is meant to be used. A dictionary is like a mapping in mathematics. A dict is a mapping of the set of keys to the values, but not the other way around.

Amazing! Not one mention of learning how to properly write a sentence, paragraph, capitalize or use punctuation. Everybody must be in their happy place after a RESTFUL weekend.oh wow... this was waaaay more feedback then i was expecting in such short time

Quote
Maybe this will help

http://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary

i think i looked at that link earlier when searching around myself, but i didn't really understnad all of what was going on, there where functions i've never dealt with yet wich made it a bit too much for me to really grasp what they where doing.

DaveLembke, the challenge is to do it with a dictionary, but otherwise it sounds really smart and like something that's waaaaaaaay over the scale of my small python beginner challenge xD there is no file it's writing to it will just be a single file containing the program itself, i'm hardcoding the dictionary with some predefined values, and the user will be able to add/remove stuff but i won't be saving the changes or addittions anywhere, it's simply a code challenge to help me learn python

Quote
The answer is: You don't.

Well, not really. You CAN search a dictionary for a key given a value- but it's going to be a sequential search- you'd have to look through every item and find the one with the correct value. You would also have to decide what to do when more than one key has the same value. Fact is, this is slow and very poor design, because you are basically misusing the Dictionary.

As a solution, We can discount adding the reverse association to the dictionary- eg, the son key returns the father key as well, because this would mean that a son could not be a father which would obviously be no good for your required scalability to include grandfathers.

The solution, IMO, would be to maintain two Dictionaries. One that indexes the sons by their father, and one that indexes fathers by their sons (the one you already have). when you add one in you add the appropriate values to each dictionary; when you define that Bob is the Son of George, for example, you add Bob with the Key George to your existing dictionary, but you also add George with the key Bob to the second dictionary; then you use the correct dictionary based on how you are searching.

Of course, this means that any father can only ever have one son, which is implied somewhat anyway since your original dictionary couldn't have more than one son indexed by the father anyway.

Realistically if the desire is to create a more full "Family Tree" than you would want to explore the creation of an Actual Tree Data structure.

seems to be following the theme of tonight

while these answers have been rolling in i got some help from a friend on facebook, who's been going over this with me, and yes i understand that what i'm asking for help to do is breaking dictionaries and any real world applications xD

my friend also suggested doing 2 dictionaries, challenge with the grandfather part, says i have to do it inside one dictionary,

to give you a better idea i'll write out the entire challenge as it stands in the book i'm following

Write a Who's Your Daddy? program that lets the user enter the name of a male and produces the name of his father.
Allow the user to add, replace, and delete son-father pairs.

Improve the Who's Your Daddy? program by adding a choice that lets the user enter a name and get back a grandfather. Your program should still only use one dictionary of son-father pairs.
Make sure to include several generations in your dictionary so that a match can be found.

after talking to my friend i've been thinking about doing it as a dictionary where the son's name is gonna be the key, and the value will be a list containing his father and grandfather, it seems to be the way to go about making this work within the "rules" of the challengesI see. the issue is that your original assessment was backwards. There is no reason to have sons indexed by fathers, because according to the question, you do not need to retrieve the sons given a father, but the opposite way. So you can do this with only one dictionary, one which indexes fathers based on sons.

Given a Dictionary named "Paternity" with sons as the key, and fathers as the value, and a name "n":

Code: [Select]Father = Paternity[n]

would retrieve the father for the son named in variable n.

Now, At this point, you should be able to figure out how to get a grandfather as well; after all, a Grandfather is just a father's father, you have the father, and you have a way to get fathers based on sons, right? You just put those together.Quote
I see. the issue is that your original assessment was backwards. There is no reason to have sons indexed by fathers, because according to the question, you do not need to retrieve the sons given a father, but the opposite way. So you can do this with only one dictionary, one which indexes fathers based on sons.

Given a Dictionary named "Paternity" with sons as the key, and fathers as the value, and a name "n":

Code: [Select]

Father = Paternity[n]


would retrieve the father for the son named in variable n.

Now, At this point, you should be able to figure out how to get a grandfather as well; after all, a Grandfather is just a father's father, you have the father, and you have a way to get fathers based on sons, right? You just put those together.

ah i see, i understood it like i would need to do it the other way around yes

hmm YEAH i think so, i'm assuming add new pairs of fathers/sons (grandfathers/fathers) and add a condition to make it print both the father/son and the grandfather/father pairs at the same time

by the way thank you very much for all the input, i totally forgot to write it yesturday but it's really appreciated
1756.

Solve : Code - remove part of file name?

Answer»

Hi can someone create some code for me please to remove [www.lokotorrents.com] from the file name of a WHOLE bunch of files in the same directory in one command line please?

example:
C:\Documents and Settings\Administrator\My Documents\Downloads\filea[www.lokotorrents.com].nul
and
C:\Documents and Settings\Administrator\My Documents\Downloads\fileb[www.lokotorrents.com].nul

to remove [www.lokotorrents.com] from all the files in one GO thanks if you can help Why has it got to be in one line?
okay, it can be on multiple lines in which case can you create a batch file for it to run from? noticing a pattern here? I'm lazy!
I'm sure it could probably be done in one line anyways using a wild card. Basically I want to remove that part of the file name from 100's of files but not using lame-*censored* GUI windows which will take me hours. First person to give me the code wins a speed-boat.Quote

[www.lokotorrents.com]

Is this correct, that the unwanted section starts with a [ and ends with a ] ... ?

Yuuuup! you can do it?? awesome.... oh there isn't ACTUALLY a speed-boat by the way... SORRY.

[www.lokotorrents.com] <--- Remove all including '[' and ']' Code: [Select]
@echo off
setlocal enabledelayedexpansion
set deletestring=[www.lokotorrents.com]
echo Ready to start
echo.
pause
echo.
for /f "delims==" %%F in ('dir /b ^| find "%deletestring%"') do (
set oldfilename=%%F
set newfilename=!oldfilename:%deletestring%=!
echo Ren "!oldfilename!" "!newfilename!"
)
echo.
echo All done
pause


Copy the above into your editor e.g. Notepad. Save as a .bat or .cmd file in the folder where the files are. Run it. See the results. If you are happy with the way it offers to rename the files, remove 'echo' from the beginning of the line starting 'echo Ren' & save and run it for real.

Maybe backup the files first in case it all goes wrong?

Or change Ren to Copy?

Your choice.

I expect you can see where to edit so it will remove other strings...

Quote from: Shandy on January 13, 2009, 02:50:36 PM
I'm sure it could probably be done in one line anyways using a wild card.

I doubt it.
Awesome code
Didn't work though :/
Here is what I ran as a .bat inside the folder:

@echo off
setlocal enabledelayedexpansion
set deletestring=[www.lokotorrents.com]
echo Ready to start
echo.
pause
echo.
for /f "delims==" %%F in ('dir /b ^| find "%deletestring%"') do (
set oldfilename=%%F
set newfilename=!oldfilename:%deletestring%=!
Ren "!oldfilename!" "!newfilename!"
)
echo.
echo All done
pause

Thanks ANYWAY I'm still impressed Quote from: Shandy on January 15, 2009, 08:09:16 AM
Awesome code
Didn't work though :/

Well, it worked for me on a folder full of test files named like you said.
You don't actually say in what way it "didn't work" so I can't actually suggest what is wrong. Maybe the files are read only? Maybe you didn't describe what you wanted properly?

Code: [Select]S:\Test\Batch>dir *.nul
Volume in drive S is USBHD
Volume Serial Number is 2C51-AA7F

Directory of S:\Test\Batch

13/01/2009 22:25 0 Test-file02[www.lokotorrents.com].nul
13/01/2009 22:25 0 Test-file03[www.lokotorrents.com].nul
13/01/2009 22:25 0 Test-file04[www.lokotorrents.com].nul
13/01/2009 22:25 0 Test-file05[www.lokotorrents.com].nul
13/01/2009 22:25 0 Test-file06[www.lokotorrents.com].nul
13/01/2009 22:25 0 Test-file07[www.lokotorrents.com].nul
13/01/2009 22:25 0 Test-file08[www.lokotorrents.com].nul
13/01/2009 22:25 0 Test-file01[www.lokotorrents.com].nul
8 File(s) 0 bytes
0 Dir(s) 187,333,132,288 bytes free

S:\Test\Batch>test8.bat
S:\Test\Batch>dir *.nul
Volume in drive S is USBHD
Volume Serial Number is 2C51-AA7F

Directory of S:\Test\Batch

13/01/2009 22:25 0 Test-file02.nul
13/01/2009 22:25 0 Test-file03.nul
13/01/2009 22:25 0 Test-file04.nul
13/01/2009 22:25 0 Test-file05.nul
13/01/2009 22:25 0 Test-file06.nul
13/01/2009 22:25 0 Test-file07.nul
13/01/2009 22:25 0 Test-file08.nul
13/01/2009 22:25 0 Test-file01.nul
8 File(s) 0 bytes
0 Dir(s) 187,333,132,288 bytes free

S:\Test\Batch>



Test8.bat

Code: [Select]@echo off
setlocal enabledelayedexpansion
set deletestring=[www.lokotorrents.com]
for /f "delims==" %%F in ('dir /b ^| find "%deletestring%"') do (
set oldfilename=%%F
set newfilename=!oldfilename:%deletestring%=!
Ren "!oldfilename!" "!newfilename!"
)



Does this code only work on files with the extension .nul? By the looks of it, it works on all file types.
C:\Documents and Settings\Administrator\My Documents\Downloads\Hardcore Nation (2009) [WwW.LoKoTorre
nts.CoM]\Hardcore Nation 2009 .[WwW.LoKoTorrents.CoM](CD-1)>setlocal enabledelayedexpansion

C:\Documents and Settings\Administrator\My Documents\Downloads\Hardcore Nation (2009) [WwW.LoKoTorre
nts.CoM]\Hardcore Nation 2009 .[WwW.LoKoTorrents.CoM](CD-1)>set deletestring=[www.lokotorrents.com]


C:\Documents and Settings\Administrator\My Documents\Downloads\Hardcore Nation (2009) [WwW.LoKoTorre
nts.CoM]\Hardcore Nation 2009 .[WwW.LoKoTorrents.CoM](CD-1)>for /F "delims==" %F in ('dir /b | find
"[www.lokotorrents.com]"') do (
set oldfilename=%F
set newfilename=!oldfilename:[www.lokotorrents.com]=!
Ren "!oldfilename!" "!newfilename!"
)

C:\Documents and Settings\Administrator\My Documents\Downloads\Hardcore Nation (2009) [WwW.LoKoTorre
nts.CoM]\Hardcore Nation 2009 .[WwW.LoKoTorrents.CoM](CD-1)>pause
Press any key to continue . . .


That's what happened with the last code when i put @echo on at top and pause at the bottom. ^_^I have a feeling you just moved the goal posts, as we say in soccer countries.

Is this the string you wish to find and remove?

Quote
[WwW.LoKoTorrents.CoM]

Or is it this (as you originally stated)?

Quote
[www.lokotorrents.com]

because there is a difference. As you should be able to see. Which might explain why my code "didn't work".

And why, if I am right, you will need to change this line:

Code: [Select]for /f "delims==" %%F in ('dir /b ^| find "%deletestring%"') do (
to this:

Code: [Select]for /f "delims==" %%F in ('dir /b /l ^| find "%deletestring%"') do (
The /l switch for DIR forces the file listing to be all lower case.

And the answer to this question

Quote
Does this code only work on files with the extension .nul? By the looks of it, it works on all file types.

is: No, it doesn't only work on files with the extension .nul, and you are right, it works on all file types. If you wanted to restrict it to only certain file types, you could modify the FOR command line like this. Let's say you only want to rename .nul files...

for /f "delims==" %%F in ('dir /b /l *.nul ^| find "%deletestring%"') do (



It's [WwW.LoKoTorrents.CoM] as you said, but I'll try that other line and see what happens this is fun! lol
Thanks for the help It worked! Your a genius!
And it's called football not soccer I'm from England ^_^So is the /1 syntax to ignore letter case?? :S
1757.

Solve : C++ ASCII RogueLike?

Answer»

Hello! Once again, I come to you guys and gals with YET another problem. I have been creating an ASCII RogueLike with c++. Now it is nowhere close to ever be finished if I can't figure out this problem. For this game I would like it to be able to load maps from a text file and process it and then PRINT it to the screen. I don't know how though. I don't know if I should use a CHAR array or a vector with pop_back. What I do know is how to load the text file, with ifstream.

Thanks for any help!
Shiverbob
Curious as to what the "RogueLike" is... is this the game title?

Here is more info that might help: http://www.cplusplus.com/doc/tutorial/ntcs/

Is this going to be a turn based game where you make a selection and then press the enter key to submit your move etc or a game that does not require enter key to be pressed following a key input?

Will you need collision detection between objects on your map?

Is there a reason why you are having to read in from a text file the game map when you can more simply just have it hard coded in the initialization of the array etc?Quote from: DaveLembke on March 14, 2015, 09:33:34 PM

Curious as to what the "RogueLike" is... is this the game title?
http://en.wikipedia.org/wiki/Roguelike


Quote
Is this going to be a turn based game where you make a selection and then press the enter key to submit your move etc or a game that does not require enter key to be pressed following a key input?
The article above answers this.

Quote
Is there a reason why you are having to read in from a text file the game map when you can more simply just have it hard coded in the initialization of the array etc?
Yes, there would be a reason. And that reason is "competent design".Thanks for replying. As to ANSWER your question unanswered by BC_Programming.
There is no need for collision checking as far as walls and other things
The reason for that is so when I call the command _getch(); or getch(); It takes the first thing press, I put that into a variable called input. Then use a switch statement with a few cases and if nothing is done. nothing will be affected.
1758.

Solve : Help With A Batch File.?

Answer»

Hello,
I am new at creating batch files and am having a bit of trouble. what i am trying to do is build a batch that will basically copy the contents of 3 different files and paste them to a location on my network. i have come up with a CMD line code that will do the job but when i attempt to build this into a batch file it fails on my command. my code i am trying to use is as follows.

for /f %H in (hostnames.txt) do @robocopy /COPYALL /E "\\source" "\\%H\c$\DESTINATION"

i want this code to run 3 times copying 3 different files to 3 different locations from 3 different locations. any help would be appreciated. if you need more info feel free to ASK. In a batch script, you need 2 percent signs in FOR variables, but only one at the prompt. So change %H to %%H. Thanks for the help on that, one more question i added the extra % and that seemed to work BARING the attached image. basicaly CMD is showing that the destination is not found. when i run the command outside of the batch file it runs fine. any ideas?



[attachment deleted by admin to conserve space]Maybe run the batch as administrator?
Also check that the folders shown actually exist

location does exist as i am ABLE to push these files using just the solo command outside of the batch file. as for admin attempted while logged in as admin on system still no go just getting the error inside the image provided. my goal here is to basically push 3 folders/files to a group of pc's on a network streamlining the process so i dont need to move the files/folders manualy if that gives any insight to aid in this endeavor Looking at your screenshot I can see plain as day that you did not double BOTH of the percent symbols.Me too.

1759.

Solve : Javascript Loop doesn't exit?

Answer»

I've tried everything I can think of.
I'm building a sort of chat bot for IMVU, USING injected JavaScript on the IMVU mobile website. I have a loop to crawl the messages received, and search for certain key terms, like a message beginning with a slash (/) to indicate a command to the bot. When certain commands are used, I have a problem that the bot seems to get stuck in the loop, almost as if the index of the for loop is being modified inside the loop. The code is included below. If you need more, ask, and if you find something that might be causing the problem, please let me know. I'm at my wit's end.

Just for a note: jQuery is properly injected, all my variables are there, no errors in the debug console, and running under Chrome 41.0.2272.101m on Windows 7 x64.

Code: [Select]function verifyCommand() {
if (document.getElementsByClassName("message-list-item").length > last_cmd_count && !processing_commands) {
VAR new_length = $('.message-list .message-list-item').length;
console.log("Begin processing commands... ** SYSTEM LOCK **");
console.log(new_length);
for (i = last_cmd_count; i < (new_length); i++) {
processing_commands = true;
try {
var callinguser = $('.message-list .message-list-item .header .username .username-text')[i].innerText.replace("Guest_", "");
var messagetext = $('.message-list .message-list-item .message .message-text')[i].innerText
if (callinguser != "USERNAME REMOVED") {
if (messagetext.substr(0,1) == "/") {
if (strContains(callinguser,"IMVU User")){die();}
processCommand(messagetext.substr(1),callinguser);
} else {
if (messagetext.toLowerCase().indexOf('roomgreet') > -1 || messagetext.toLowerCase().indexOf('room greet') > -1){
if (detectFlirt()) {
sendMsgRaw('Please do not hit on me, ' + callinguser + '.');
if (!isAdmin(callinguser)) { logIdiot(callinguser); }
} else if (strContains(messagetext,'what is ')) { sendMsgRaw('Please use /solve or /advsolve for math.');
} else { if (callinguser != "USERNAME REMOVED") { ident(); } }
}
if (strContains(messagetext,'free') && strContains(messagetext,'credits') && strContains(messagetext,'http://')) {
sendMsgFrom("*** SCAM ALERT ***", callinguser);
}
}}
} catch(ex) { } finally {}
}
processing_commands = false;
last_cmd_count = new_length;
console.log("Finish processing commands... ** SYSTEM FREE **");
if (monitoring) { verifyUserMessageCount(); }
}
}I've added a topic on StackOverflow as well, will post back the answer if I should resolve it here.Try changing your function to use each() to loop through each element instead of the loop you have. Once an element has been processed, add a "processed" class to the element so we dont look at them again later. This should be more stable than forcing our logic to KEEP up with what ones have been processed already.

Here is a jsFiddle, throw in the html from your page that actually causes the problem and see if it still occurs

Code: [Select] function verifyCommand() {
//fixed some logic in here
if ($(".message-list-item").length > last_cmd_count && !processing_commands) {
processing_commands = true; // you should set this immediately
var new_length = $('.message-list-item').length;
console.log("Begin processing commands... ** SYSTEM LOCK **");
console.log('Last command count: '+ last_cmd_count +', New Length: '+new_length);
var newMessages = $('.message-list-item:not(.processed)'); // get all of the message elements that do not have the class "processed"
// loop through each of the message elements
newMessages.each(function(index, element){
console.log('Processing new element at index '+index );
try {
var callinguser = $(this).find('.username-text').text().replace("Guest_", "");
var messagetext = $(this).find('.message-text').text();
$(this).addClass('processed'); // add processed class to the element so we know not to process it again later
if (callinguser != "RoomGreet") {
if (messagetext.match(/^\//)) {
if (callinguser.match(/IMVU User/)) {
die();
}
processCommand(messagetext.substr(1), callinguser);
}
else {
if (detectFlirt(messagetext)) {
if (!isAdmin(callinguser)) {
sendMsgRaw('Please do not hit on me, ' + callinguser + '.');
logIdiot(callinguser);
}
}
else if (messagetext.match('what is ')) {
sendMsgRaw('Please use /solve or /advsolve for math.');
}
else {
if (callinguser != "Nezzle" && !isAdmin(callinguser)) {
ident();
}
}
if (strContains(messagetext,"imvu") && strContains(messagetext,"credits") && strContains(messagetext,"http://")) {
sendMsgFrom("*** SCAM ALERT ***", callinguser);
}
}
}
}
catch (ex) {
console.log('caught error');
}
finally {
}
});
last_cmd_count = new_length;
console.log("Finish processing commands... ** SYSTEM FREE **");
processing_commands = false;
if (monitoring) {
verifyUserMessageCount();
}
}
}

Source: StackOverflow: jquery - JavaScript Loop doesn't exit

1760.

Solve : Looking For a Java Tutor..?

Answer»

Like the SUBJECT says I've been trying to learn java by making a Minecraft mod (I've tried tutorials it ends up with me copying code and not learning anything.. and I've been playing Minecraft a while so why not learn like this? [or if there's a a better way I'm willing to try you war]) I'm just looking for someone that can maybe call me on Skype or Team VIEWER or some other form of helping me learn. It would be EXTREMELY helpful for me!There are Java user groups all over the world.
You can find them on Facebook or Twitter.
https://www.facebook.com/pdxjug
Portland, OR
http://www.meetup.com/sfjava/
San Francisco


What sort of programming experience do you have? If none, start off trying to learn something like Python on http://www.codecademy.com/ then move on to something like Java from there. Minecraft mods are far too complex to be used to learn to program, you need to focus on learning the BASIC concepts of any programming language and only move on to making advanced stuff once you have mastered these.

If you start by following tutorials on how to make big projects all you end up doing is copying insanely complicated blocks of code without understanding what they do, you need to get to grips with the basic concepts of programming before you start doing this.Java modding is a lot HARDER then you think. I recommend that you learn something easy first like batch or Python. The move up from there. Use resources AVAILABLE to you like YouTube and documentation for help, use books. Go to a library check out a book on it. Learn the idea of programming. What good and what bad. But ultimately it's up to you.new boston tutorials on youtube (coding along and messing around as you go) are pretty good.

1761.

Solve : Writing a bat file to replace a shortcut on a flash drive?

Answer»

Hello,

I have zero experience writing bat files, but was told on the hope chat to come here and ask as it was the way to do it.

I can make a shortcut on a flashdrive pointing to a local .exe file on the same drive. However, the shortcut breaks if the drive letter changes when it's plugged into a different machine.

Any help would be appreciated.

THanksYou say the exe is on the flashdrive? If so, you may only need to eliminate the drive letter from the line that invokes the exe.

Can you post the bat file?I don't have a bat and wouldn't have the faintest idea how to write one. A loooong way from my area of expertise!

I asked in the live chat how I could create a shortcut for an exe on a flashdrive where the drive letter can (and does) change when it's used on different PCs.

Someone said to USE a bat file. I couldn't write one.



ThanksHow is the exe file being started? Why can't the user just double click on the exe?

Perhaps this is what the Original Poster wants.

He has a .EXE file on a flash drive that he wants to run other PCs in his group. He would like a shortcut or batch file that would include the best set of parameters for the .EXE file. And shorten the name of the shortcut or batch.

The problem is that the drive letter changes when the drive is moved to another PC.
Poor example:
try.bat is:
F:\tryprogram.exe -a -b -c
So he puts try.bat on F:\ and he then takes it to another computer whee the drive letter for the flash drive i G: and the program fails to start.
Does this describe the problem?

If the exe is on the flashdrive then the invocation doesn't need to include the drive letter.

try.bat:
tryprogram.exe -a -b -c

This would work if try.bat and tryprogram.exe are both in the same folder on the flashdrive and the user invokes try.bat from that folder. If try.bat was in the root folder of the flashdrive and tryprogram.exe was in a folder called tryme, then try.bat would look like this:

\tryme\tryprogram.exe -a -b -c

The problem would come into play if try.bat is on the user's C: drive and was trying to invoke tryprogram on the flashdrive, in that case the drive letter would be required.
Thanks for all replies.

Salmon Trout - when I plug my USB in, I want to be able to run 6 programs from my USB. Each exe is SEVERAL folders deep - that's a lot of clicking.

I right clicked > send to > desktop (create shortcut).

That's fine until the drive letter changes.



Yes, that describes my problem Geek-9pm.


Strollin - so the code should be (for one of the programs)

\mikejava\109\IDE\eclipse\eclipse.exe -a -b -c

Thank you



Rather than send a shortcut to the desktop, one must create a shortcut or batch on the target drive.
The the user must navigate to the target drive and start the batch or shortcut.
Otherwise, this is, to my knowledge, no DOS thing that finds a drive letter for you.
If thee was, the pseudo code would be:
Code: [Select]For N=1 to 26
Type=FindDrive(n)
IF Type =="USB" set Gotdit = NThat is not real code.
It KINDA represent the idea if there was a FindDrive thing is DOS.

PowewrShell has something like that.
Code: [Select]GET-WMIOBJECT –query “SELECT * from win32_logicaldisk where DriveType = ‘3’” Also in C++ there is a thing. Somewhere.
Quote from: mike1980 on April 02, 2015, 06:40:17 PM

Thanks for all replies. ...

Strollin - so the code should be (for one of the programs)

\mikejava\109\IDE\eclipse\eclipse.exe -a -b -c

Thank you
Yes, pretty much. If you put the batch file in the root of the flashdrive then change to the flashdrive before inoking the batch file.A batch file knows its own drive letter, it is given by %~D0 which expands to a letter and colon thus D: E: F: or whatever. A batch file in the root of a removable drive could have a line pointing to an exe anywhere else on that drive for example "%~d0\path\to\program file\program.exe" (quotes needed if path has spaces, does no harm to always use therm). If you wanted this program to run when a flash drive is inserted you are getting into autorun territory and will run into security implications.That's a good tip Salmonthe drive letter is not necessary as long as the batch file and the exe are on the same drive but it certainly doesn't hurt to include it.
1762.

Solve : Visual Basic help!!?

Answer» OK i am receiving these errors in my code!!!!

Error1End of statement expected.C:\Users\scott\documents\visual studio 2013\Projects\WindowsApplication2\WindowsApplication2\Form1.vb911WindowsApplication2
Error2Statement is not valid in a namespace.C:\Users\scott\documents\visual studio 2013\Projects\WindowsApplication2\WindowsApplication2\Form1.vb171WindowsApplication2
Error3Statement is not valid in a namespace.C:\Users\scott\documents\visual studio 2013\Projects\WindowsApplication2\WindowsApplication2\Form1.vb661WindowsApplication2
Error4Statement is not valid in a namespace.C:\Users\scott\documents\visual studio 2013\Projects\WindowsApplication2\WindowsApplication2\Form1.vb2121WindowsApplication2
Error5Statement is not valid in a namespace.C:\Users\scott\documents\visual studio 2013\Projects\WindowsApplication2\WindowsApplication2\Form1.vb2511WindowsApplication2
Error6Statement is not valid in a namespace.C:\Users\scott\documents\visual studio 2013\Projects\WindowsApplication2\WindowsApplication2\Form1.vb3671WindowsApplication2
Error7Statement is not valid in a namespace.C:\Users\scott\documents\visual studio 2013\Projects\WindowsApplication2\WindowsApplication2\Form1.vb3771WindowsApplication2





here is my code can anyone please help me!!!!!




Sub [Dim] gNumRows As Long
Dim gDirection As String
Dim gBoxSize As Double
Dim gReversalBox As Integer
Dim gError As Integer
End Sub


Sub GetStock(BYVAL stockSymbol As String, ByVal StartDate As Date, ByVal EndDate As Date, ByVal dest As String, ByVal freq As String)

Dim noErrorFound As Integer
Dim DownloadURL As String
Dim StartMonth, StartDay, StartYear, EndMonth, EndDay, EndYear As String
StartMonth = Format(Month(StartDate) - 1, "00")
StartDay = Format(Day(StartDate), "00")
StartYear = Format(Year(StartDate), "00")
noErrorFound = 0

EndMonth = Format(Month(EndDate) - 1, "00")
EndDay = Format(Day(EndDate), "00")
EndYear = Format(Year(EndDate), "00")
DownloadURL = "URL;http://table.finance.yahoo.com/table.csv?s=" + stockSymbol + "&a=" + StartMonth + "&b=" + StartDay + "&c=" + StartYear + "&d=" + EndMonth + "&e=" + EndDay + "&f=" + EndYear + "&g=" + freq + "&ignore=.csv"

On Error GoTo ErrHandler
With ActiveSheet.QueryTables.Add(Connection:=DownloadURL, Destination:=Range(desti))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = "20"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.REFRESH BackgroundQuery:=False
End With
noErrorFound = 1

ErrHandler:
If noErrorFound = 0 Then
MsgBox("Stock " + stockSymbol + " cannot be found.")
gError = 1
End If

Resume Next
End Sub

Sub DownloadData()

Application.ScreenUpdating = False
Dim freqFlag As String
Dim numRows As Integer
Dim noErrorFoundInDownloadData As Integer
noErrorFoundInDownloadData = 0

On Error GoTo ErrHandlerDownloadData

freqFlag = "m"
If Worksheets("Input").Range("$E$10") = 1 Then
freqFlag = "d"
'plus 2 due to the intitial two rows
numRows = DateDiff("d", Worksheets("Input").Range("$E$8"), Worksheets("Input").Range("$E$9")) + 2
ElseIf Worksheets("Input").Range("$E$10") = 2 Then
freqFlag = "w"
numRows = DateDiff("w", Worksheets("Input").Range("$E$8"), Worksheets("Input").Range("$E$9")) + 2
ElseIf Worksheets("Input").Range("$E$10") = 3 Then
freqFlag = "m"
numRows = DateDiff("m", Worksheets("Input").Range("$E$8"), Worksheets("Input").Range("$E$9")) + 2
End If

If Worksheets("Input").Range("$E$12") = "" Then
noErrorFoundInDownloadData = -1
GoTo ErrHandlerDownloadData
End If


If IsNumeric(Worksheets("Input").Range("$E$12")) Then
gBoxSize = Worksheets("Input").Range("$E$12")
If gBoxSize >= 0.1 And gBoxSize <= 500 Then

Else
noErrorFoundInDownloadData = -1
GoTo ErrHandlerDownloadData
End If
Else
noErrorFoundInDownloadData = -1
GoTo ErrHandlerDownloadData
End If

If Worksheets("Input").Range("$E$13") = "" Then
noErrorFoundInDownloadData = -2
GoTo ErrHandlerDownloadData
End If

If IsNumeric(Worksheets("Input").Range("$E$13")) Then
gReversalBox = Worksheets("Input").Range("$E$13")
If gReversalBox >= 1 And gReversalBox <= 8 Then

Else
noErrorFoundInDownloadData = -2
GoTo ErrHandlerDownloadData
End If
Else
noErrorFoundInDownloadData = -2
GoTo ErrHandlerDownloadData
End If
gReversalBox = Floor(gReversalBox)

Worksheets("DownloadedData").Select()
Worksheets("DownloadedData").UsedRange.Clear()

'Stock 1
If Worksheets("Input").Range("$C$13") <> "NONE" Then
'Cells(1, 1) = Worksheets("Input").Range("$C$13")
'Cells(2, = "Returns"
Call GetStock(Worksheets("Input").Range("$E$11"), Worksheets("Input").Range("$E$8"), Worksheets("Input").Range("$E$9"), "$A$1", freqFlag)
ActiveWindow.SmallScroll Down:=-12
Columns("A:A").TextToColumns(Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
Array(7, 1)))
End If

Columns("A:Z").EntireColumn.AutoFit()


Dim vvx As Integer
vvx = Application.Version

If (vvx >= 12) Then
'Excel 2007
ActiveWorkbook.Worksheets("DownloadedData").Sort.SortFields.Clear()
ActiveWorkbook.Worksheets("DownloadedData").Sort.SortFields.Add(Key:=Range("A2:A6550") _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal)
With ActiveWorkbook.Worksheets("DownloadedData").Sort
.SetRange Range("A1:G65500")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply()
End With
Else
'Exel 2003
Columns("A:G").Select()
Selection.Sort(Key1:=Range("A2"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal)
End If

'If Worksheets("Input").Range("$E$11") = "Y" Then
' Call SwapCloseAndAdjustedClose
'End If
Worksheets("DownloadedData").Select()
Worksheets("DownloadedData").Range("H1").Select()

'Find number of rows
Dim i As Integer
Dim exitloop As Integer
exitloop = 0
i = numRows + 1
Do Until exitloop = 1
If Worksheets("DownloadedData").Cells(i, 1) = "" Then
i = i - 1
Else
gNumRows = i - 1
exitloop = 1
End If
Loop

noErrorFoundInDownloadData = 1
Application.ScreenUpdating = True
ErrHandlerDownloadData:
If noErrorFoundInDownloadData = 0 Then
MsgBox("Error in setting up Download Data.")
Application.ScreenUpdating = True
gError = 1
Exit Sub
ElseIf noErrorFoundInDownloadData = -1 Then
MsgBox("Box Size must be from 0.1 to 500.0.")
Application.ScreenUpdating = True
gError = 1
Exit Sub
ElseIf noErrorFoundInDownloadData = -2 Then
MsgBox("Number of Reversal Boxes must be a number from 1 to 8.")
Application.ScreenUpdating = True
gError = 1
Exit Sub
End If

End Sub

Sub SwapCloseAndAdjustedClose()

Application.ScreenUpdating = False

'Find the number of rows of stock data
M = 2
numRowsData = 0
Do While M < 65000
shtName = outputShtName
If Worksheets("DownloadedData").Cells(M, 1) = "" Then
numRowsData = M - 1 - 1 'Additional Blank Lines
M = 65000
End If
M = M + 1
Loop

Dim vvx As Integer
vvx = Application.Version

If (vvx >= 12) Then
'Excel 2007

Worksheets("DownloadedData").Range("DA1:DA" & numRowsData) = Worksheets("DownloadedData").Range("E1:E" & numRowsData).Value
Worksheets("DownloadedData").Range("E1:E" & numRowsData) = Worksheets("DownloadedData").Range("G1:G" & numRowsData).Value
Worksheets("DownloadedData").Range("G1:G" & numRowsData) = Worksheets("DownloadedData").Range("DA1:DA" & numRowsData).Value
Worksheets("DownloadedData").Range("DA1:DA" & numRowsData) = Worksheets("DownloadedData").Range("DB1:DB" & numRowsData).Value
Else
'Excel 2003

Worksheets("DownloadedData").Range("E1:E" & numRowsData).Copy Destination:=Worksheets("DownloadedData").Range("DA1")
Worksheets("DownloadedData").Range("G1:G" & numRowsData).Copy Destination:=Worksheets("DownloadedData").Range("E1")
Worksheets("DownloadedData").Range("DA1:DA" & numRowsData).Copy Destination:=Worksheets("DownloadedData").Range("G1")
Worksheets("DownloadedData").Range("DB1:DB" & numRowsData).Copy Destination:=Worksheets("DownloadedData").Range("DA1")
End If

Application.ScreenUpdating = True

End Sub

Sub DownloadDataAndChart()
gError = 0
Dim noErrorFoundInCharting As Integer
noErrorFoundInCharting = 0
On Error GoTo ErrHandlerCharting

Dim low As Double
Dim high As Double
Dim lowest As Double
Dim highest As Double
Dim X As Long
Dim y As Long
Dim numOutputRows As Long
Dim prevlowbox As Double
Dim prevhighbox As Double
Dim colCounter As Long

colCounter = 2
numOutputRows = 0
lowest = 0
highest = 0


Call DownloadData()
If (gError = 0) Then
Worksheets("Output").Select()
Worksheets("Output").UsedRange.Clear()

gDirection = "O"
For i = 2 To gNumRows
high = Worksheets("DownloadedData").Cells(i, 3)
low = Worksheets("DownloadedData").Cells(i, 4)
If i = 2 Then
lowest = low
highest = high
Else
If lowest > low Then
lowest = low
End If
If highest < high Then
highest = high
End If
End If
Next i
numOutputRows = Floor(((Floor(highest) + 1) * 2) / gBoxSize) + 1
For i = 1 To numOutputRows
Worksheets("Output").Cells(i, 1) = numOutputRows * gBoxSize - ((i - 1) * gBoxSize)
Worksheets("Output").Cells(i, 1).NumberFormat = "#,##0.000"

Next i
Worksheets("Output").Cells(numOutputRows + 1, 1) = 0
Worksheets("Output").Cells(numOutputRows + 1, 1).NumberFormat = "#,##0.000"

For i = 2 To gNumRows
high = Worksheets("DownloadedData").Cells(i, 3)
low = Worksheets("DownloadedData").Cells(i, 4)
Dim lowvalue As Double
Dim highvalue As Double
Dim lowbox As Double
Dim highbox As Double
lowvalue = Floor(low / gBoxSize) * gBoxSize + gBoxSize
highvalue = Floor(high / gBoxSize) * gBoxSize
lowbox = Floor(lowvalue / gBoxSize)
highbox = Floor(highvalue / gBoxSize)
If i = 2 Then
For j = lowbox To highbox
Worksheets("Output").Cells(numOutputRows + 1 - j, colCounter) = "O"
Next j
prevlowbox = lowbox
prevhighbox = highbox
Else
If gDirection = "O" Then
If lowbox < prevlowbox Then
For j = lowbox To prevlowbox
Worksheets("Output").Cells(numOutputRows + 1 - j, colCounter) = "O"
Next j
prevlowbox = lowbox
ElseIf ((highbox - prevlowbox) >= gReversalBox) Then
colCounter = colCounter + 1
If (colCounter > 12000) Then
noErrorFoundInCharting = 0
GoTo ErrHandlerCharting
End If
gDirection = "X"
For j = prevlowbox + 1 To highbox
Worksheets("Output").Cells(numOutputRows + 1 - j, colCounter) = "X"
Next j
prevhighbox = highbox
End If
Else
If highbox > prevhighbox Then
For j = prevhighbox To highbox
Worksheets("Output").Cells(numOutputRows + 1 - j, colCounter) = "X"
Next j
prevhighbox = highbox
ElseIf ((prevhighbox - lowbox) >= gReversalBox) Then
colCounter = colCounter + 1
If (colCounter > 12000) Then
noErrorFoundInCharting = 0
GoTo ErrHandlerCharting
End If
gDirection = "O"
For j = lowbox To prevhighbox - 1
Worksheets("Output").Cells(numOutputRows + 1 - j, colCounter) = "O"
Next j
prevlowbox = lowbox
End If
End If
End If
Next i

End If 'gError

noErrorFoundInCharting = 1
End Sub

Sub ErrHandlerCharting()
()

If noErrorFoundInCharting = 0 Then
MsgBox("Number of Columns to be plotted on the chart has exceeded 12000. Please reduce the amount of data for charting.")
gError = 1
Exit Sub
End If
End Sub

Function Floor(ByVal X As Double, Optional ByVal Factor As Double = 1) As Double
Floor = Int(X / Factor) * Factor
End Function
1763.

Solve : Need some help in JavaScript or CSS...Urgent Please?

Answer»

Any dynamic Programming language can be used Javascript or CSS. Javascript is Preferred

1) Take a string of unspecified length as input. The string is composed of three kinds of characters C,H and E. The string can be of any lenth

for eg) CCCHEECHHHC, CCCHEEEEEHHCCCHHEHHHEHCH,

The program should print the following output

a cylinder for H,
an arrow for E
and a STRAIGHT line for C

(An example has been given in the file below where input and output are both noted as pred)

2)Take a string of unspecified length as input. The string is composed of two kinds of characters, either e or -. The string can be of any lenth
for eg) ee--EEEE-------eeee--------e, -----e---e---,

The program should print the following output

a red circle(small size like an O of length 22 in MS word) for e
and a black circle(same specifications as above) for -

Please CHECK with the attachment... Any help WOULD be appreciated.. Need this in One day..

[attachment DELETED by admin to conserve space]We are not here to do your homework for you...

1764.

Solve : Loop in http post in vbscript / ASP?

Answer»

Good day..

How can I do request looping in request header ? Example..
I have whole day transaction stored in my database. My server will SEND all this value to another server to update payment status...
I WANT loop value for ID..
There is SYNTAX ERROR at ------- Function HTTPPost


below is my code

do while not abc.eof ' -------abc is value from my database

sUrl = "HTTPS:/qwer.com"

sRequest = "ID="&escape(a)&"&CODE="&escape(b)&"&NAME="&(strEncrypted)

HTTPPost sUrl, sRequest
Function HTTPPost(sUrl, sRequest)
Set oHTTP=Server.CreateObject("Msxml2.ServerXMLHTTP.6.0")
oHTTP.setOption 2, 13056
oHTTP.open "POST", sUrl,false
oHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
oHTTP.setRequestHeader "Content-Length", Len(sRequest)
oHTTP.send sRequest
HTTPPost = oHTTP.responseText
End Function
abc.movenext
loopMaybe I am ignorant, but I do not under stand why your have a Function defined inside a loop. But maybe things have changed since I did programming.Quote from: Geek-9pm on April 19, 2015, 10:56:28 PM

Maybe I am ignorant, but I do not under stand why your have a Function defined inside a loop. But maybe things have changed since I did programming.

You are correct. That is likely the syntax error. The Function definition will NEED to be moved outside of the loop.hehehe...sorry my mistake.....can someone show the right way todo this
Well, we are going to need more INFORMATION about what you are actually trying to do and what all the variables you are using actually represent.
1765.

Solve : Sharepath automation??

Answer»

is there any one that knows of a way to make a BATCH file that will automate the process of creating sharepaths via the computer management screen. i have a process where i work that requires me to drop a folder and Chrome Icon into the C:\ of a list of PC in our company and i have to create a sharepath to each of these and then forward the list of paths to the uppers. any one know if it is possible to create a batch file that can do this ? Could you please PROVIDE some examples of what you are trying to accomplish.

1766.

Solve : Help with a batch file to move based upon part of file name?

Answer»

Hi all, I'm a hack sql programmer / web designer of sorts. More of an Excel moderate/exp than a programmer. I'm familiar with batch files and how to use them, but very unfamiliar with how to program them.

I need a batch file to perform the following move:

From location:
C:\Materials\Transfer File

Filenames:
V00128594 11-001 MINERALS.pdf
V00128594 11-001 MICROS.pdf
V00128598 11-1000 MICROS.pdf
V00129476 11-001 MICROS.pdf
V00131451 33-4872 MICROS.pdf
V00131451 33-4872 MINERALS.pdf
V00131451 33-4872 SPECTROPHOTOMETRY.pdf

Results would look like this with Move To Filename Locations:
C:\Materials\11's\11-001

  • V00128594 11-001 MINERALS.pdf
  • V00128594 11-001 MICROS.pdf
  • V00129476 11-001 MICROS.pdf

C:\Materials\11's\11-1000
  • V00128598 11-1000 MICROS.pdf

C:\Materials\33's\33-4872
  • V00131451 33-4872 MICROS.pdf
  • V00131451 33-4872 MINERALS.pdf
  • V00131451 33-4872 SPECTROPHOTOMETRY.pdf


Our naming conventions are:
Filename
{LOT}" "{ITEM CLASS}"-"{ITEM NUMBER}" "{TEST RESULTS}.pdf

Locations
C:\Material\Transfer File - files are stored til ready to transfer
C:\Material\{ITEM CLASS}"'s"\{ITEM CLASS}"-"{ITEM NUMBER}\ - location where the files need to land, based upon filename

I've LOCATED several EXAMPLES in this forum that are very close, but I can't seem to figure out how to tell it the new location based upon the "33" before the dash, and adding an "'s" for the folder directory. Thanks in advance for any help.

Edit:
My files always end in .pdf and all of the folders will always be pre-existing.

With item numbers always the same you can add wildcard to ends of the filename such as *11-001*.* to your move instruction and this way anything conforming to any file name that contains 11-001 in it will go to the move destination. **Only tricky part would be if you had a part number of say 11-0018. It would grab this and move this to that location based on matching 11-001

If you only have a few part numbers it wouldnt take much time to make this happen, if you have many part numbers and need to have the xx-xxxx read in and dynamically make folders for the item numbers and then move those files to those specific folders then a batch guru would need to help here beyond that of myself because it goes above my skills in batch.

Example of a move with the wildecards at the ends would be:

Quote
MOVE "C:\Materials\Transfer File\*11-001*.*" C:\Materials\11's\11-001

This is only for the 11-001 for the others you would need a line for say 11-1000 and 33-4872 such as a batch with:
Quote
MOVE "C:\Materials\Transfer File\*11-001*.*" C:\Materials\11's\11-001
MOVE "C:\Materials\Transfer File\*11-1000*.*" C:\Materials\11's\11-1000
MOVE "C:\Materials\Transfer File\*33-4872*.*" C:\Materials\33's\33-4872

*Note: Untested but last time I did a similar process of placing a target index within 2 wildcards at either end it worked for me. The .* will grab all file types with the match. If you only want pdf's you can change it to

Code: [Select]MOVE "C:\Materials\Transfer File\*11-001*.pdf" C:\Materials\11's\11-001
MOVE "C:\Materials\Transfer File\*11-1000*.pdf" C:\Materials\11's\11-1000
MOVE "C:\Materials\Transfer File\*33-4872*.pdf" C:\Materials\33's\33-4872
If your dealing with a few hundred or thousand item numbers then maybe a batch guru can assist with making this a smaller batch that might be able to work from a text file with a list of part numbers and step down through the listing to handle all files that match the xx-xxxx item number range. If the item numbers are ever different than xx-xxxx for maximum digits then the largest part number should be shared so that they know to target - as the part number identifier and read in 2 characters prior to - and 4 characters after - or more than that to set the scope I am thinking. If I was going to make a complicated batch file I am thinking that is the direction i would go would be to read in part numbers from a text file list and then those that match xx-xxxx for *xx-xxxx*.pdf will be moved to appropriate folders.

Quote
I've located several examples in this forum that are very close, but I can't seem to figure out how to tell it the new location based upon the "33" before the dash, and adding an "'s" for the folder directory. Thanks in advance for any help.

If you already have a batch file that you got partially working you can share it here and we can assist with that too.

Thanks for the idea, but yes we'll probably have several hundred files to move per day, and we have over 4000 different items with inventory constantly growing. Trying to figure out an automated way to do this, where the lady that renames all the files can just double click something, like a batch file, and it will do all the TEDIOUS file transfers for her...we may just end up buying RoboBasket if we can't figure any other way. We just don't need a full feature software package to only perform one function. What is the range for the part numbers do all conform to xx-xxxx or would it need to look in a scope of xxx-xxxx or some other scope? The good thing is that in your files the ( - ) is the unique identifier so you can tell it to read in the first 2 characters before ( - ) and 4 characters after ( - ) I am thinking and go that route. If you had a text file with 1 item number per line and the batch can step through that list, it can then process I am hypothetically thinking all part numbers from the target location. The xx- (leading) part number can be used for pathing to group all 33- into 33's

This unfortunately exceeds my skills in batch though. So were gonna need another member here to assist with this one other then myself, but at least we are information gathering at this point and throwing out there some ideas on how this could be completed at this point so they have a head start on what you need by knowing the range that your part numbers will conform to such as they never exceed xx-xxxx or will some go beyond that for instead of 2 by 4 its 3 by 5 digits which are handled not as digits but characters so alpha would even work if you had a 11-103YAttaching a small .zip of the Materials folder, with SAMPLE files that anyone can feel free to work with, if it will help. This is our exact directory bones, and a sample of files in the Transfer folder that were just named today.

In response to Dave, all our items are format code xx-xxx or xx-xxxx. The first two numbers distinguish our item class (vitamin, mineral, protein, etc.), while the last 3 or 4 digits, after the dash represent that particular material.

Example
11-001 = Vitamin A
11-003 = Vitamin B12
33-149 = Liver Powder (33's being Proteins)
33-001 = Cranberry Juice Powder


[attachment deleted by admin to conserve space]Tested with your provided file.

Code: [Select]@echo off

REM Assign the working directory to a variable
set "from=C:\Materials\Transfer File"

REM Change the current directory and store the previous folder for use by the POPD command.
PUSHD "%from%"

REM Parse the output of the DIR command
REM File name is broken apart into tokens by the hyphen and space.
REM %%G will equal the first part of the file name up to the first space
REM %%H will equal the second part of the file name: space to hyphen
REM %%I will equal the third part of the file name: hyphen to space.
REM %%J will be the remainder of the file name.
FOR /F "tokens=1-3* delims=- " %%G IN ('dir /B /a-d *.pdf') DO (
IF NOT EXIST "..\%%H's\%%H-%%I" MD "..\%%H's\%%H-%%I"
MOVE "%%G %%H-%%I %%J" "..\%%H's\%%H-%%I\"
)
REM Change back to the previous directory.
popd
pause
1767.

Solve : Quick Question that came up Naturally.?

Answer» http://imgur.com/a/2usa4 Or if there is ONE and I don't know it can you please share!!Instead of ASKING people to click on a link, what is it you want to know?I clicked on link and tried to make sense of this yesterday. I see chat and with them and quantos and didnt understand what the question was although the bloody brick was an interesting visual, and so I just left without saying anything. Wants a 3rd party FB messenger app for some unspecified PORTABLE platform? Not very clear.

Yea sorry for not bieng very clear on my question. Im just trying to get some advice on what the best language would be to learn if i WANTED to make a 3rd party facebook and messenger application for android. And maybe just some general tips while trying to learn. Also if you guys know of any that i can use while learning to reference that would be awesome.For Android apps, you would need to learn Java as this is the language that all Android apps are built in. You can technically do them using web technologies such as Javascript, HTML and CSS and then use various systems such as PhoneGap to build an app around them but these never perform as well as one built natively in Java. That said, I'm not sure how open Facebook's platform is in terms of allowing developers enough access to build a full messenger alternative.Is this Android Studio a good IDE for them and others wanting to develop for android, or is there a better IDE?

https://developer.android.com/studio/index.htmlThere is not a shortage of Java tutorials,
- - nor are they hidden under rocks.
Just search for Java
http://www.itpro.co.uk/desktop-software/27961/is-the-sun-setting-on-java


Yeah, Android studio is probably the best option unless you already have a preferred Java development environment. Certainly saves a huge amount of hassle configuring something different to handle all the Android build stuff.Wonderful thanks a ton guys i definatly will look into that as soon as possible! Hope you guys have a wonderful week.
1768.

Solve : Any Python Experts Here????

Answer»

Currently doing GCSE computing where we have coursework which has to meet the deadline however HELP is required from experts that have greater knowledge using this.

Task 1 has been completed (designing mathematical quiz for students generating random multiplication questions) Task 2 has been completed (creating .TXT file for storing the data students got on the mathematical TEST) however Task 3 requires you to sort the data into alphabetical order, highest to LOWEST score and average score which has not been completed because help is needed.

The code which I have currently is...

results = input("Which class would you like to see: A, B or C? \n")
if results =="A":
print ("Mathematical test data for class A has been sorted in alphabetically order")
with open("ScoresClassA.txt", 'r') as r:
for LINE in sorted(r):
print(line, "\n", end='')

if results =="B":
print ("Mathematical test for class B has been sorted in alphabetically order")
with open("ScoresClassB.txt", 'r') as r:
for line in sorted(r):
print(line, "\n", end='')

But when I run the code it sorts the .txt in alphabetical order when I input one class but it gives below the alphabetical order for class B which I do not want because I requested for one class to be shown when it asked me to input the name ?

How would I do the highest score?
How would I do it by the average?

Thank you!
Well since you did not surround your code with code tags it is hard to tell whether or not you have your code indented properly. Too me it does not look like you have the code indented properly so the interpreter will always execute the second with statement and print the sorted B file.

But in my opinion, if you have three options to check you should use IF ELIF statements.when you open the data, add it to any array (as are, but then sort it manually (not with the sorted() function). How are you storing the data in the text file? You may need to do something like this:
Code: [Select]data = open("filename",'r')
data = data.readlines()
for line in data:
line = line.replace("\n","").split("delimiter")

# Sort algorithm here

Look up what kind of sorting algorithm is most efficient for your specific case and implement it there. Then you have a sorted list and you do so your print loop.

1769.

Solve : [Python] py2exe exe not responding?

Answer»

I assume from the lack of responces to other python questions, that there isn't anyone else that writes python code here, but I am having a PROBLEM with py2exe. The code runs fine in python interpreter, but when I 'compile' it via py2exe, it stops responding. Any ideas?

Code: [Select]from ctypes import windll, Structure, c_long, byref
import os
import win32gui
import win32api
import time
from PIL import Image,ImageDraw,ImageTk


key = ord('Z')
delay = 1
hashmap = {}
last20 = []
log_write='w'


# Declares deta type Point, which allows queryMousePossition to return two values
class POINT(Structure):
_fields_ = [("x", c_long), ("y", c_long)]

# Recalls cursor position and returns it as array values.
def queryMousePosition():
pt = POINT()
windll.user32.GetCursorPos(byref(pt))
return { "x": pt.x, "y": pt.y}
def queryKeyPress():
ky = win32api.GetAsyncKeyState(key)
return ky

ky = 0
print "PRESS '%s' to Start" %chr(key)
while ky == 0 or ky == 1:
pos = queryMousePosition()
ky = queryKeyPress()
print "\r \r(%s,%s)" % (pos["x"],pos["y"]), # for debug
print "\r "



i = delay
while i > 0:
print " \rStarting in %d SECONDS" % i,
time.sleep(1)
i-=1
print "\r "


ky = 0
log = open('log.txt',log_write)
print "Press '%s' to Halt" % chr(key)
while ky == 0 or ky == 1:
lastpoint=""
pos = queryMousePosition()
pos=str(pos["x"])+","+str(pos["y"])
ky = queryKeyPress()
last20.insert(0,pos)
while len(last20) > 20:
lastpoint = last20.pop()
print "\r \r("+pos+")", # for debug
amount = ""
if not(lastpoint == pos):
try:
amount = hashmap[pos]
log.write(pos+"\n")
except:
amount = 0
amount+=1
hashmap[pos] = amount
log.close()



print "Processing Data"
ch = 0
total=0
for x in hashmap:
if hashmap[x] > ch:
ch = hashmap[x]
total+=1
div = 255.000000/ch*2

img = Image.new("RGB",(win32api.GetSystemMetrics(0)/2, win32api.GetSystemMetrics(1)/2), 'white')
pen = ImageDraw.Draw(img)
lines = []
inc=0
for x in hashmap:
c = x.split(',')
h = str(hex(INT((div*(ch/hashmap[x]))))).replace("0x","")
if len(h) < 2:
h="0"+h
h = "#"+h+h+h
pen.point((int(c[0])/2,int(c[1])/2), fill=(h))
inc+=1
print x,str(hashmap[x]),"/",ch,h
#print "\r \r%d/%d" % (inc,total),
img.save("log.png")


ky = 0
print "Press '%s' to Exit" %chr(key)
while ky == 0 or ky == 1:
ky = queryKeyPress()
Are you using the 32 or 64 bit version of py2exe and on a 32 or 64 bit os? Friend of mine I sent a message on FB about this who dabbles with python and has made stand alone exe's using py2exe stated something about the 64 bit version being buggy and the 32-bit version being better. Also he said make sure you have the newest version in case there are any bug fixes for the issue your having.

Other than that he mentioned something about any legacy scripting techniques maybe not being supported under the py2exe and choking it up or missing dependencies for py2exe when it compiles, however a missing dependency should give an error message.

Hope this helps...

Thanks, I'll check on the version of py2exe that's installed. I've only just started using py2exe (as in this is the first test) and I'm using someone else's script to run it. The problem might also be in that.

Code: [Select]import sys
from distutils.core import setup
import py2exe

entry_point = sys.argv[1]
sys.argv.pop()
sys.argv.append('py2exe')
sys.argv.append('-q')

opts = {
'py2exe': {
'compressed': 1,
'optimize': 2,
'bundle_files': 1
}
}

setup(console=[entry_point], options=opts, zipfile=None)
where the script to be compiled is passed in as the first argument (Python setup.py script.py)


EDIT:
It was the setup.py file, I rewrote it and now it compiles. Thanks for the advice about the 64bit version.

1770.

Solve : REFERENCE Closed Workbooks on Mapped Drive?

Answer»

Our company MANAGES its projects in individual notebooks, and we use a master workbook to show program summaries. All files are stored on an internal, mapped drive.

I'm having some trouble pulling data from the project notebooks to the master workbook using this reference format:

=('\\AAA.BBB.CCC.net\wce\Maytag\Maytag-common\management tools\PROGRAM\[Prog_Fcst[File-M123456-ABC123 XYZ.xlsm]Program Hrs'!A1)

My END goal is to have the references AUTOMATICALLY update without opening the SOURCE files. Any suggestions?

Thank you!The \\server\path\to\file syntax may not work (never tried it TBH). You may WANT to try mapping the drive to give it a drive letter on your machine, then use this path in Excel.

1771.

Solve : [Python] Add frame to gif image?

Answer»

So I have code that takes 2,000,000+/- 1,000,000 coordinates and creates images of lines between them (consecutively). I want to make these images into a gif file for easy viewing. Unfortunately, there are too many of them to load into MEMORY at once, so I am trying to create a gif with the first 2, then add on each image at the end. I've looked into creating gif's with the images2gif library. I'm running into an issue where when I write the gif, instead of adding to it, it replaces what already exists (I believe).

Code: [Select]try:
from images2gif import writeGif
from PIL import Image,ImageDraw,ImageTk
import os,sys,time,win32api
except ImportError:
print "This script requires images2gif, PIL, os, sys, time and win32api libraries."
exit()

try:
step=int(sys.argv[1])
except IndexError:
step=10

duration = 0.01

def current_seconds_time():
return int(round(time.time()))

def wGif(fil):
GLOBAL gif
global diration
images = [gif,fil]
size = (150,150)
for im in images:
im.thumbnail(size, Image.ANTIALIAS)
writeGif("gif.gif", images, duration=duration, subRectangles=True)


def findRemTime(x):
change = current_seconds_time() - startTime
persecond = 1.0 * change / x
return persecond*(len(lines)-x)

def HRMN(x):
global mn, hr, sec
sec = findRemTime(x)
mn = sec / 60
sec = int(sec % 60)
hr = int(mn / 60)
mn = int(mn % 60)

img = Image.new("RGB",(win32api.GetSystemMetrics(0)/2, win32api.GetSystemMetrics(1)/2), 'white')
img2 = Image.new("RGB",(win32api.GetSystemMetrics(0)/2, win32api.GetSystemMetrics(1)/2), 'white')


pen = ImageDraw.Draw(img)
pen2 = ImageDraw.Draw(img2)
log = open("log.txt",'r')
lines = log.readlines()
startTime = current_seconds_time()

last = lines[0].replace("\n","").split(",")
line = lines[1].replace("\n","").split(",")
pen.line((int(last[0]),int(last[1]),int(line[0]),int(line[1])),fill=128)
last = lines[0].replace("\n","").split(",")
line = lines[1].replace("\n","").split(",")
pen2.line((int(last[0]),int(last[1]),int(line[0]),int(line[1])),fill=128)
img.save("1.jpg")
img2.save("2.jpg")
gif = Image.open("1.jpg")
wGif(Image.open("2.jpg"))

os.remove("1.jpg")
os.remove("2.jpg")


hr = '?'
mn = '?'
sec = '?'
skipped = 0
gif = Image.open("gif.gif")
last = lines[2].replace("\n","").split(",")
update = 0
for x in xrange(3,len(lines),step):
update+=1
if update > 75:
update=0
hrMn(x)
try:
if hr > 0:
print "\r \r",str(x)+"/"+str(len(lines))," "+str(hr)+"hr "+str(mn)+"min",
else:
print "\r \r",str(x)+"/"+str(len(lines))," "+str(mn)+"min "+str(sec)+"sec",
line = lines[x].replace("\n","").split(",")
pen.line((int(last[0]),int(last[1]),int(line[0]),int(line[1])),fill=128) #Going to change the color later
img.save("img.jpg")
img = Image.open("img.jpg")
wGif(img)
os.remove("img.jpg")
gif = Image.open("gif.gif")
#duration+=0.005
img = Image.new("RGB",(win32api.GetSystemMetrics(0)/2, win32api.GetSystemMetrics(1)/2), 'white')
pen = ImageDraw.Draw(img)
last = line
except IOError:
skipped += 1
print "\r \rIOError:"+str(x)+" skipped:"+str(skipped)

I've attached an example of log.txt (or part of one, it's actually 20MB total)

[attachment deleted by admin to conserve space]I can not help with the code... however -
What do you mean by
Quote

a gif file for easy viewing.
For easy viewing It has to fit on a standard monitor. How many pixels would a image of two million points take?
A screen shot of this monitor takes about 64,000 bytes in 256 colors.
So my question is: Why does it take so much memory to create a GIF file?

Im trying to make a gif where you can watch where your mouse went. The points i mentioned are the points read in through a different script. When i said easy viewing, i ment that you cant really look at either the log file or make 2,000,000 jpg FILES, it just isnt a good way of doing it.For a simple graphic, you want to use GIF, not JPG. But even GIF has a structure that might not seem obvious. Have you seen this?
Project: What's In A GIF - Bit by Byte[/url
Quote
A GIF file is made up of a bunch of different "blocks" of data. The following diagram shows all of the different types of blocks and where they belong in the file. The file starts at the left and works it's way right. At each branch you may go one way or the other. The large "middle" section can be repeated as many times as needed. (Technically, it may also be omitted completely but i can't imagine what good a GIF file with no image data would be.)
Python is often used to create animated GIF files. There is a library for a simple GIF.
http://svn.effbot.org/public/pil/Scripts/gifmaker.py
Sorry I am no help with the code.
Quote
I'm running into an issue where when I write the gif, instead of adding to it, it replaces what already exists (I believe).

The Images2Gif library takes a series of images to create a GIF out of. It does not do anything special if one of those frames is a GIF image- they are treated the same. a PIL.Image instance loaded with a GIF can be seeked and different frames read, but the Images2GIF library treats it like any other image, so it will end up creating a new GIF image that comprises of the first frame of the GIF, and whatever frame you are trying to add.

Arguably I'm not even sure if Images2Gif did this it would solve your problem. If it was smart enough to see a GIF and then seek out all the frames as images to add to the new GIF, all of those frames will be in memory.

I expect you would have to manage the file yourself- find the end terminator, then the last Graphics Control Extension block (for the last frame) and insert a encoded GIF Frame at that position, which is easier said than done, really.

1772.

Solve : Visual Basic 6?

Answer»

Hello... I am trying to write a visual basic 6 program that ACCESS an excel file over the network.
I have looked everywhere on the Internet but still unable to locate any sample code...
Please could someone offer some help!

Thanks in advanceAre you talking about ACCESSING a Comma Delimited CSV file with VB6 reading in info and writing back to a CSV file or are you looking to make a VB Script macro to use WITHIN Excel itself?

Have you EVER worked with VB before so that I/we can use terminology here and you'd be all set with it or should we describe everything in a greater detail in future posts to this thread?

Additionally is there a reason why your using VB6 which is almost 20 years old vs a newer VB IDE?

1773.

Solve : asking INPUT for string to PRINT string?

Answer»

digit = input("Give a Number")

print ("this is a %d") % digit

word = input("Give a String")

print ("this is a %s") % word
#print ("this is a %r") % word

# how do you ask for a number and then print it, i can print a number, but not a string
# how do you ask for a string and then print itWhat language is this. I ask because it looks like Python but half of it makes no SENSE as Python- and also because you decided to never mentioned what language it was.

What is % supposed to do?PYTHON

i used

%s

in the string to take a string from the VARIABLE which is listed at the end of the string with

% word

thinking that

the variable word would be PUT in place of

%s


and % d use for a digit

and %r use to force either a string or digitCode: [SELECT]print ('digit:%d' % (digit))

(comment powershell for display of output and the NOTEPAD++ to show what was typed to get there)





_______________________________________ _______________________________________ __________________________









I wasn't giving you a working solution. I was giving you the correct syntax. The code sample you provided wouldn't work so I presumed the problem was based on that.

Input will always give you a string, not a number. use either the int() or float() to coerce the result into a numeric type.



1774.

Solve : Retrieve multiple xml values to JS file?

Answer»

Hi all,

I am having few xml files with same attrributes having different input values. I have created a js file to take these INPUTS from single xml file.

Following is the js code :
VAR Nodes = new Array();
var RaidType;
function XMLReader()
{
var Doc, node, s;
// Create a COM object
Doc = Sys.OleObject("Msxml2.DOMDocument.6.0");
Doc.async = false;
var Filename = "test.xml";
// Load data from a file
Doc.load("C:\\test.xml");
// REPORT an error, if, for instance, the markup or file structure is invalid
// Obtain the node
node = Doc.documentElement;
// Process the node
ProcessNode(node);
}

function ProcessNode(ANode)
{
var i, ChildNodes;
// Process the node's value and insert it in variables
switch(ANode.nodeName)
{
case 'Node':
Nodes[a] = ANode.nodeTypedValue;
//Nodes = temp.split(" ");
Log.Message(Nodes[a]);
a = a + 1;
break;
case 'RaidType':
RaidType = ANode.nodeTypedValue;
Log.Message(RaidType);
break;
}
// Exclude helper nodes from processing
// Obtain the COLLECTION of child nodes
ChildNodes = ANode.childNodes;
// Processes each node of the collection
for(i = 0; i < ChildNodes.length; i++)
ProcessNode(ChildNodes.item(i));
}

I am Calling below two functions for execution :

XMLReader();
startUpgrade();


Query : As of now, i am able to RETRIEVE values from test.xml file (only) mentioned above in the code and execute. I need to similarly retrieve values from mutiple xml files ie. first time i need values from test.xml and process below functions:
XMLReader(); //values of test.xml
startUpgrade();

In the next iteration, i need values to be retrieved from abc.xml and process below functions:
XMLReader(); //values of abc.xml
startUpgrade();

In the next iteration, i need values to be retrieved from def.xml and process below functions:
XMLReader(); //values of def.xml
startUpgrade();

Can anyone help me on this as i am really confused on how to get going
Thanks in advance.. Issue resolved as i followed same procedure above to retrieve Xml files and paths and fed the inputs to above code by looping them.

1775.

Solve : MinGW uninstall completetion problem?

Answer»

Hello to anyone who can help.

I installed MinGW the codecompiler. I had some problems making the test pilot program ''Hello world'' RUN smoothly in CMD - never mind

When I finally had enough I decided to uninstall so I could re-install but it wouldn't let me with the message that it was still installed. Huh i thought??

So, I entered the command ''path'' into my cmd and found C/users / MinGW . OK, after that I went to environment variables and deleted minGW under that and when I checked CMD again it had successfully gone. So some success. HOWEVER, when I go to path I still see ''C:/bin etc


aaahhh but I don't know where it is and how to get rid of it or indeed any trace of MinGW so I can start again with EITHER the same code compiler or a DIFFERENT one to start using C language code.

If anyone has any suggestions they are most welcome - I am just a novice....

1776.

Solve : Not sure why my code is not working?

Answer»

So im trying to create a program pretty much that will open other programs upon exit or with a time delay. I get no build errors but everytime i RUN my program i get the ERROR Cannot start process because a file name has not been provided. but launches the first program anyways just not the other one upon exit. anyone see any issues with the code i provided. Thanks alot appreciate any help

Code: [Select]using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;

namespace ProcessExitSample
{
class testsandboxprogram
{
static void Main(string[] args)
{
Contract.Requires(args != null);
try
{
//why in the literal *censored* am i getting an error for no name!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!WHEN I DEFINED THE PATH
var firstProc = new Process();
Process.Start(@"PATH TO EXE I WANT TO LAUNCH");
firstProc.EnableRaisingEvents = true;

firstProc.Start();

firstProc.WaitForExit();

//so upon exit should run the second program here
Console.WriteLine("First process exited: " + firstProc.ExitCode);

var secondProc = new Process();
Process.Start(@"PATH TO PROGRAM I WANT TO LAUNCH");
secondProc.Start();

}
catch (Exception ex)
{
Console.WriteLine("Something went wrong sorry :(: " + ex.Message);
return;
}
}
}
}Process.Start() isn't going to give the firstProc instance any information about the file you specified as a parameter, as it creates a new Process and starts it and returns that Process as the return value.

You probably want something like this:

Code: [Select] ProcessStartInfo FirstProcInfo = new ProcessStartInfo(@"C:\Path\To\executable.exe");
var FirstProc = Process.Start(FirstProcInfo);
FirstProc.WaitForExit();
ProcessStartInfo SecondProcInfo = new ProcessStartInfo(@"C:\Path\To\second\executable.exe");
var SecondProc = Process.Start(SecondProcInfo);





Quote from: BC_Programmer on January 07, 2017, 02:51:49 PM

Process.Start() isn't going to give the firstProc instance any information about the file you specified as a parameter, as it creates a new Process and starts it and returns that Process as the return value.

You probably want something like this:

Code: [Select] ProcessStartInfo FirstProcInfo = new ProcessStartInfo(@"C:\Path\To\executable.exe");
var FirstProc = Process.Start(FirstProcInfo);
FirstProc.WaitForExit();
ProcessStartInfo SecondProcInfo = new ProcessStartInfo(@"C:\Path\To\second\executable.exe");
var SecondProc = Process.Start(SecondProcInfo);

thanks alot for the help im now using

Code: [Select]ProcessStartInfo FirstProcInfo = new ProcessStartInfo(@"C:\Program Files (x86)\Steam\steamapps\common\BattleBlock Theater\BattleBlockTheater.exe");

var FirstProc = Process.Start(FirstProcInfo);

firstProc.WaitForExit();


ProcessStartInfo SecondProcInfo = new ProcessStartInfo(@"C:\Program Files (x86)\Steam\steamapps\common\BattleBlock Theater\BattleBlockTheater.exe");


var SecondProc = Process.Start(SecondProcInfo);

}

catch (Exception ex)
{
Console.WriteLine("Something went wrong :) " + ex.Message);
return;
}
}
}
}



Not sure if it matters or not but im trying to open the same exe after it exits from the first one so opens up exe if you exit that exe it opens the same one up again. Not sure if that matters but im getting the method or operation is not implemented the first exe opens up correctly. the second one doesnt open up apon closing it thoThat code wouldn't even compile. You defined the v ariable as FirstProc but then used it as firstProc.

anyway, Steam changes everything. When you launch a steam-managed game by itself it will launch steam telling it to launch itself and exit, so WaitForExit() will return immediately.

I don't get "method or Operation is Not Implemented".Quote from: BC_Programmer on January 07, 2017, 03:40:11 PM
That code wouldn't even compile. You defined the v ariable as FirstProc but then used it as firstProc.

anyway, Steam changes everything. When you launch a steam-managed game by itself it will launch steam telling it to launch itself and exit, so WaitForExit() will return immediately.

I don't get "method or Operation is Not Implemented".




changed up my code a bit now compiles without any errors

Code: [Select]using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;

namespace ProcessExitSample
{
class testsandboxprogram
{
static void Main(string[] args)
{

try
{
//why in the literal *censored*
ProcessStartInfo FirstProcInfo = new ProcessStartInfo(@"C:\Program Files (x86)\Steam\steamapps\common\BattleBlock Theater\BattleBlockTheater.exe");
var FirstProc = Process.Start(FirstProcInfo);




Console.WriteLine("First process Started: ");

System.Threading.Thread.Sleep(4000);
Task.Delay(2000);

// should run the second program here

ProcessStartInfo SecondProcInfo = new ProcessStartInfo(@"C:\Program Files (x86)\Steam\steamapps\common\BattleBlock Theater\BattleBlockTheater.exe");
var SecondProc = Process.Start(SecondProcInfo);
}
catch (Exception ex)
{
Console.WriteLine("Something went wrong :) " + ex.Message);
return;

}
}
}
}

the only thing now is session 1 terminates once session 2 launches decided ill just work with launching TWO at the same time.
1777.

Solve : .bat file to delete certain files?

Answer»

Hi all - just wondering if someone has some coding i could use for a batch file in windows


I have a back up folder and files automatically backup with a date and time at the end. Over time this becomes a long list. Can someone share some coding for a batch file that once there is more than 2 of a specific file name [taking into account the file name will have successive dates and times] and then delete them leaving only the 2 latest files of each of the different files in that folder. Only needs to work when i run the batch.

e.g. keep The 2 latest
Apple 2017-01-01 21.30.xls
Apple 2017-01-01 21.59.xls
Apple 2017-01-02 21.10.xls
Apple 2017-01-03 21.150.xls

and keep the 2 latest
Water 2017-01-01 21.30.mdb
Water 2017-01-01 21.59.mdb
Water 2017-01-02 21.10.mdb
Water 2017-01-03 21.15.mdb

and so on....


Many thanks in anticipation


Ian

I have this coding - but it deletes all but the last 4 files in total - so it's not quite there yet:
pushd "C:\Users\ian.woodland\Documents\irw Bin" && ( for /f "skip=4 eol=: delims=" %%F in ('dir /b /o-d /tw /a-d') do del "%%F")I myself have taken the easy route with this myself. I shuffle backup files down a path to eventual deletion. Example Being Folder 1, Folder 2, and Folder 3.

Folder 1 is populated with the latest backup
Folder 2 is populated with backup that is up to 2 days old
Folder 3 is the waste bin where all files that end up here get deleted

example being:
Code: [Select]echo off
cls
@echo. Shuffling Backups and Deleting the 3rd day
@echo.
ERASE c:\backups\folder3\*.* /q
xcopy c:\backups\folder2\*.* c:\backups\folder3\*.*
erase c:\backups\folder2\*.* /q
xcopy c:\backups\folder1\*.* c:\backups\folder2\*.*
erase c:\backups\folder1\*.* /q
@echo.
@echo. Backup Shuffle Complete
pause
You will want to run this shuffle batch prior to your actual backup of latest data to folder1. This way all data is shuffled down making folder1 empty waiting the latest data after each run of this. *Note: Use of xcopy and wildcards is because I use this myself for multiple file types.

If you dont want it to shuffle as a wildcard anything contained within, you can shuffle just the mdb and xls files.

Warning: It is assumed when RUNNING this batch that no other important data is at the backup location such as Folder1 as for if the application or program is located in the same location as the backups such as with my example at Folder 1, it will rip the data from its home location and pass it down stream to Folder 2. This one line here is very dangerous if for example your program or application resided at the same location as your backups. If this is the case then the backup location needs to be changed to protect from moving the program from where it should remain. erase c:\backups\folder1\*.* /q

Code: [Select]echo off
cls
@echo. Shuffling Backups and Deleting the 3rd day
@echo.
erase c:\backups\folder3\*.* /q
xcopy c:\backups\folder2\*.mdb c:\backups\folder3\*.mdb
xcopy c:\backups\folder2\*.xls c:\backups\folder3\*.xls
erase c:\backups\folder2\*.* /q
xcopy c:\backups\folder1\*.mdb c:\backups\folder2\*.mdb
xcopy c:\backups\folder1\*.xls c:\backups\folder2\*.xls
erase c:\backups\folder1\*.* /q
@echo.
@echo. Backup Shuffle Complete
pause
*Last Important Note... You actually have 3 days of backup before the batch is run again. The waste cleanup of Folder 3 doesnt happen until the next run of this batch. So after you have run this and data is moved down from folder 2 to 3 ... 1 to 2 and then you run your backup for that day into the was empty Folder 1. You now have Folder 1, 2, and 3 with backup files. Until this batch is run in which Folder 3 is wiped clean and only 2 days move from folder to folder.

Reason why I did not use the MOVE command and decided to use XCOPY is because if this process was disrupted say a blackout. The MOVE command is less graceful to disruption whereas I have been told that XCOPY is graceful to interruption because its making a copy of the data to another destination vs moving the data bit for bit which if interrupted spells disaster. Maybe one of the batch gurus here can confirm that rumor. If using the MOVE command alone, this could be shortened as for the only erase would need to happen at Folder 3 and the MOVE command would move data between Folders 2 to 3 and 1 to 2.
hi Dave - thanks so much for taking the time to reply. Since i posted EARLIER, i decided that there was an easier way. I split into folders my backups and then have several batch files that delete all but 2 of the latest files from each folder. All the batch files run from just one single batch file that i'll get windows to run.

Much appreciate your suggestion and i'll keep it if my way doesn't work out

All the best

IanHello Ian,

Great to hear you got it to work. As per you stated using multiple batch files. Just wanted to mention that most of the time batches can be combined that is that you can merge batched instructions so that say you have 4 batches combined into 1, whatever needs to run first is at the top of the batch file, then the next batch to run you can copy paste that info from that batch file below the other batch files instructions, and do the same for adding contents from all other batches into that first back file. Order of Operation/Execution is what is most important. Batches are like a linear CHECKLIST of go down the line and do this and do that with ability to jump around with goto statements usually used only for when specific instructions are met or to start the batch over from scratch in an endless loop until CTRL+C or exiting the WINDOW and FOR loop instructions with parsing and other tasks.

But there are other times as well when you want functions/instructions to not run all the time as part of following other processes and for that keeping them separate makes sense.

1778.

Solve : rand() ... How many random numbers before cycle repeats?

Answer»

I was looking online and cant find anything out there other than this one link below. Maybe my search is using wrong search words. I am curious with the standard rand() algorithm for a Windows based computer ( Stating Windows because I heard that Linux generates rand() differently ) how many numbers can be generated before the cycle repeats, basically the limitations of the algorithm. I expected this to be well documented and nothing to be found yet.

http://justbasic.conforums.com/index.cgi?board=tutorial&action=display&num=1170007376

What I found was this one hit that was the closest match but no cigar.

The random generators algorithm should repeat, but how many iterations can it run before it ends up back where it started in which the next numbers generated become predictable because it made a full circle?

At the link above someone else was already where I am now and they seemed to give up at 2 Billion generated Numbers with no repeating found.

Quote

1) JB have at least 2 000 000 000 un-repeating random numbers;
2) I do not know if they repeat anythere soon after 2 000 000 000 (remember, that 256^4 = 4 294 967 296)
3) probably JB not supposed to run for several days in a row non-stop. (Well, It might be a coincidence. I just not in mood to start this program for another 3 days).

Had a laugh at this part:

Quote
(Well, It might be a coincidence. I just not in mood to start this program for another 3 days)

Last year I ran a program looking for the weakest key for my program. A key used that when info put into it, the output would be clear text. I gave up after 1 Billion searches for this worst key ever and it took almost a week on a 8-core AMD FX-8350 at 4Ghz with each core processing 125 Million searches for the worst key since my C++ programs are single-threaded to make the most use of my processing power. This program was very fast and very small and just took an string, shuffled it, and tested the output result to see if it matched the initial string. The string length was 85 characters and that has since grown to 89 characters which means it will take even longer to find that worst key ever. I have since implemented in my code a key strength tester that looks for duplicates between the character placement of the initial string and the output to look for characters that after shuffled end up back in their original location as for this shuffle with too many back in their original position would mean that some information would be clear text, and the more characters that didnt change placement in the shuffle, the easier it is to crack the secret message etc.

If I was to brute force search for the end of the algorithm, I was thinking that storing the first 10 very large numbers generated and then have a counter that counts how many iterations the random generator ran to display in the end, and test each next group of 10 randomly generated numbers to the initial group of 10 might be the way to find that point when it makes a full circle, however its also possible that the algorithm that is like the tracks of a roller coaster has as exactly curved section of track that is of 10 numbers, but the 11th onwards dont match up, in which then I have to expand my search to say a group of 20 as a exact match and then test the 21st value and see if that matches the next.

Multiple computers could be used if you used a manually injected seed to place each of the systems into their own crunching quadrant of numbers to work with similar to how I took my 8-core processor and broke it up into 125 Million iterations each core for the 1 Billion keys tested, I could have each core of each system set to start at a different skipped ahead position from the other so that each core is working as a team with all cores of all computers involved to hunt for that initial group of 10 very large numbers and then stops showing that it found a match to the 10. Once that match detected it shows the value of iterations and I know the seed value. Then removing the seed value from the iterations the exact number of iterations should be able to be calculated. And then the limit position in which the random generator made a full circle is then known.

But instead of brute forcing to find this number at the cost of an elevated electric bill, its always best to see if someone else out there knows this magic number before the algorithm repeats. Additionally, there may be different algorithms with a different number before full circle. I am, working with a Windows 7 64-bit computer and C++

The point behind wanting to know where the algorithm makes a full circle is to then understand how many keys are available before keys of a different value give the same result as key #1 such as Key #1 and Key # 298,371,000,000,000 might be the same because of the full circle of the algorithm. And only the first billion I know are unique in green. with the unknown in red. *Also with 89 characters in a string shuffle, I think its 89 to the power of 89 which is a huge number of different shuffles. The first billion were tested under an earlier version of my program that only used 85 characters for 85 to power of 85.

Sometimes I think so far outside of the box that I forget about K.I.S.S so if there is a better way to hunt for these if they need to be hunted if undocumented to find that full circle of the algorithm please share a better method. If the algorithm formula was known it might also be a means of knowing its limit in which it makes full circle. Additionally it might be a long long time before it repeats if its a really well constructed algorithm in which it might be completely pointless to hunt for it since it could take a very very long time to repeat with all the processing power that can be thrown at it. Example being the best server out there taking 514 years before it makes full circle.

I really liked this part of the thread i read from the link:
Quote
"If we had a infinite amount of monkeys randomly pressing keys on an infinite amount of typewriters then eventually one of them will type out the entire Old Testament, correct to the last full stop."
the psuedorandom number generator will repeat individual numbers but the whole cycle never repeats, except in the same sense that Pi's digits repeat- that is since it can be drawn out to infinity then the statistically improbable become a certainty. If you generate 2 billion random numbers, the chance of the first billion being the same sequence as the second billion is infinitesimal. However if you instead generate an infinite sequence of random numbers, the chance that there is a sequence of one billion values followed directly by the exact same sequence of a billion values is a statistical certainty.

But computationally generating such sequences where that phenomena could be observed would probably take even all the fastest supercomputers many thousands of years to discover (and that's an optimistic estimate).Thanks for your input on this BC...

Plus I was also feeling it would be a crazy amount of processing power to discover with a very long time to make that discovery.

Quote
But computationally generating such sequences where that phenomena could be observed would probably take even all the fastest supercomputers many thousands of years to discover (and that's an optimistic estimate).

I guess I will just go with the fact that the first billion keys are safe from spitting out the input as the output in clear text. Additionally I have a key strength test in the program that allows you to set the strength for key to be used where all characters need to change position from their origin within the array - or - you can allow some to remain their initial character so that if trying to crack a message it is unknown if a character is truly substituted or is truly itself. Such as out of 89 characters only 2 could be not swapped for example if the value of 2 is given to the strength test function vs all swapped from their location.As far as your specific shuffling test, The default shuffle will swap every element with another randomly chosen element in the sequence. It is literally impossible for "RANDOM" to be shuffled into "RANDOM" regardless; the R, for example, will be randomly swapped with one of the other letters, and cannot swap with itself so will always be moved, as will all the other letters. The only way the same letter can appear in the same location in the input and output is if it appears more than once and is swapped with one of that letters other appearances.What is the goal?
Do you want real random numbers?
The use a real random number generator.
http://arstechnica.com/security/2013/12/we-cannot-trust-intel-and-vias-chip-based-crypto-freebsd-developers-say/
This is about hardware that has been in Intel chips.

Also:
http://stackoverflow.com/questions/7901829/making-use-of-sandy-bridges-hardware-true-random-number-generator
Quote
Be aware that rdrand is actually a 128-bit pseudo-random number generator with hardware-generated entropy. (The upcoming Broadwell architecture will provide an rdseed instruction to access the true random number generator.) The details of the difference and its implications can be found under the "Long Answer" heading at http://software.intel.com/en-us/blogs/2012/11/17/the-difference-between-rdrand-and-rdseed.
First link is about how Intel and VIA hardware Crypto random number generation cannot be trusted.

Second link is about how to utilize the Intel RDRAND instruction.

Dave is using an AMD CPU.
Quote from: BC_Programmer on December 31, 2016, 04:51:56 PM
...
Second link is about how to utilize the Intel RDRAND instruction.
Dave is using an AMD CPU.
AMD did it.
http://support.amd.com/TechDocs/24594.pdf
see page 34
Quote
Support for the RDRAND instruction is optional. On processors that support the instruction, CPUID Fn0000_0001_ECX[RDRAND] = 1
It is only implemented in their latest line of CPUs (Excavator Core, Athlon X4 Desktop CPU and 8000 series APU). It is not an instruction available for use on the 8350FX.



Thank you BC for providing some usefull information.
I founds this:
http://crypto.stackexchange.com/questions/29894/amds-implementation-of-rdrand-instruction
So, exactly how the hardware does it is either a mystery or they do not think we need to know. Does this mean programmersare goingto avoid ysing it? So the software methodwill continue to be tghe standard?As I understand it the main difference is that the distribution is cryptographically secure, so it is preferable for generating random numbers as part of a encryption algorithm. But outside of that pseudorandom is good enough. As an example a lot of games use random numbers to control certain AI decisions or game events or what-have-you, but there is no need for the number generator to have a cryptographically secure distribution.

Even in Dave's specific case I don't think a cryptographically secure distribution would serve to improve a random cipher. (Could be wrong about that)Quote
Even in Dave's specific case I don't think a cryptographically secure distribution would serve to improve a random cipher. (Could be wrong about that)

One problem I could see using a random generator that is from one specific class of processors is that if the data was masked under a shuffle and substitution under one processor and then brought to a different processor that didnt have this instruction set function, the keys to unlock that info back to its original form, the inverse as the best choice of words for the original random function would likely not give the same outcome and so the information would still look scrambled. I havent tested my program among different CPUs yet because it was my understanding that the rand that I am using in C++ is one that is tied to the OS that is in use with the pseudorandom. I suppose I could go down the path to use a CPUs instruction set for a better nonpseudo random but the info I have to mask out from eyes of anyone accidentally finding access to my information isnt that critical. The existing means that i have now with a key that has to specifically be the one and only key and I have available keys that far exceed 1 billion of them, and I have seen how much processing power is needed to test for 1 billion keys, solving for 1 billion would take even far more processing power.

The next revision of my code is going to be to remove the static string by which the program starts with for substitution so that it injects the string from a file This way the starting string before the shuffle is unknown vs a static known. Quote
As far as your specific shuffling test, The default shuffle will swap every element with another randomly chosen element in the sequence. It is literally impossible for "RANDOM" to be shuffled into "RANDOM" regardless; the R, for example, will be randomly swapped with one of the other letters, and cannot swap with itself so will always be moved, as will all the other letters. The only way the same letter can appear in the same location in the input and output is if it appears more than once and is swapped with one of that letters other appearances.

The C++ Shuffle Function I am using I have detected where characters shuffled end up back in their starting position. This is why i had to implement a key strength routine to my code to give choice of strong or weaker keys. Having a choice of strong or weaker keys allows for all keys to be considered unknown to whether a string or weaker key was used when shuffling the information. I ran a smaller test program that wrote to file keys that were strongest and there are quite a few keys that are weaker with 2 characters or more remaining in their starting position such as

ABCDEF shuffled to FEDCBA is every character is no longer in its original position in the string, so the array that has these characters for substitution if the message to be scrambled up is BAD FACE it would be EFC AFDB

But in a weaker shuffle where a weaker long long int key is used to seed the random shuffle if ABCDEF was shuffled as ABCDFE now the message to scramble is seen in the output saved to file as BAD EACF and BAD is plain as day and it could then be assumed that BAD are 3 letters that werent shuffled out of their original placement within the starting string. So the ( A ) in EACF is very probable the A of the next word.

Here is more on the Random_Shuffle function: http://www.cplusplus.com/reference/algorithm/random_shuffle/

Quote
Randomly rearrange elements in range
Rearranges the elements in the range [first,last) randomly.

The function swaps the value of each element with that of some other randomly picked element. When provided, the function gen determines which element is picked in every case. Otherwise, the function uses some unspecified source of randomness.


This function states that it carries out this action as a for each character
:
Quote
The function swaps the value of each element with that of some other randomly picked element

Initially I thought just as you stated that RANDOM would be a scramble where every character was placed different from its original position, but I think the issue is in the fact that if there are 15 characters, it is doing a for each character shuffle stepping say left to right.

So you can have this happen below:

ABCDEFGHIJKLMNO = Starting string

Random_Shuffle then swaps first character or element A with C

CBADEFGHIJKLMNO

Random_Shuffle then swaps next character B with O

COADEFAHIJKLMNB

Random_Shuffle then swaps next character A with C ( *Here is how A and C get back to their original place within the string )

AOCDEFAHIJKLMNB

It will perform this for 15 iterations for 15 characters and the worst case scenario would be that the shuffle placed everything back into its original order of

ABCDEFGHIJKLMNO

However its more probable that a few characters are in their original location and this makes for an long long int value that is used as a key value for the seed of the random_shuffle to be a weaker key since this seed value shuffles the string in a way that some characters are not moved out of their original place within the string.

When I first read up on this random_shuffle function having never used it until this program as for in the past I have made my own shuffler function vs using a built in function, I read this as the fact that every character would be shuffled so that none would ever end up back in their original placement, but then i got thinking about it and realized that its probably not testing in any way to avoid a character from going back to its original place within the string. So I needed to test for this. To me it was important for it to be able to make for weaker keys, otherwise if only strong keys (strong seeds) were used, then you could throw out a very large list of keys as not in use for scrambling data. So for the fact that it can shuffle in a way that characters can make their way back to their original position and choice to use a strong or weaker key and no one knowing if you used a stronger or weaker key, you then wouldnt be excluding a whole bunch of keys from use.

I dont have the source code on me to list here the test program, I have it at home and i can share it here so you can see how its placing characters back into their original location. I have a LOOP that you tell it how many times to run say for 10,000 times and it steps through each seed value and performs a string compare between the original static string and that of the output on a character for character ( element for element ) basis between the original and the shuffled. It then has flags that when X-many matches are found to display that iteration of the 10,000 to display what seed values match to that WEAK key with say 4 characters that end up back in their original location after the random_shuffle has completed.

The random_shuffle initially I thought was playing 52 pickup in which throw a deck of cards into the air and pick the cards back up and there is the chance that you could pick them up and have 2 through ACE in the 4 suits perfect as the day you first opened the pack of cards, but from testing with it it seems like its doing a 1 for 1 for as many characters are in that string so its running left to right with substituting a 1 for 1 until end of the string which would use less memory at the cost of clock cycles. But with as fast as computers are today extra clock cycles for a program like this is just about unnoticeable. Its too bad there is no way to pause the random_shuffle function through its execution in which you can step the clock cycle for the program and see the inner workings of it to see if its 52 card pick up or a 1 for 1 which I think its a 1 for 1 left to right possibly. The seed to the generator in a 52 pickup would be the trajectory of the cards and where they landed and to which order they are picked up in a very bent analogy that sounds godlike quantum magic knowing exactly as something would fall and land based on all parameters of the environment in which that one seed value alone is the fate of all cards in the 52 pickup as to how they will reenter the deck form in known order based on the seed alone and rules that dont change so outcome is always the same based on that one single long long int.


Quote
Size of long long types is 8 bytes
Signed long long min: -9,223,372,036,854,775,808 max: 9,223,372,036,854,775,807
Unsigned long long min: 0 max: 18,446,744,073,709,551,615

Note that int and long are the same size and if you want a 64 bit integer then you need to use long long (or unsigned long long).

Quite a number of keys to pick from with the Long Long Int seed. And I have only played around with the first Billion of them and that took a FX-8350 8-Core 4Ghz almost a week to complete testing full tilt 125 Million keys per core with 8 copies of my program running testing keys on a Windows 7 64-bit based system with 8GB RAM. The computer became a good loud fan noisy space heater for that week since I dont have liquid cooling, just the stock aluminum block heatsink and it levels out at 63C with CPU fan on maximum RPMs.

I see, I assumed it would use the well-established fisher-yates/Knuth shuffle, which works as I described and would result in the output never having a letter in the same position in the output as the input. But it looks like most implementations are arguably awful and merely swap each element with a randomly chosen element from the entire sequence, and it can even choose to swap with itself.

The idea that a shuffle algorithm could return output that is the same as it's input and call it "shuffled" is poor design IMO.

if you want to avoid the possibility completely, you could use your own fisher-yates/Knuth shuffle. Basic algorithm is to go through each element and swap it with any element before that element chosen at random. Just do a manual run through: (using random.org)

{1, 2, 3, 4, 5}

1. for the first element there are no elements before it
for the second, we have only one choice, so we have:

{2, 1, 3, 4 ,5}

The third index CHOOSES between the first and second element. It chooses the second element:

{2, 3, 1, 4, 5}

Fourth index chooses between the first three; It chooses the second.

{2, 4, 1, 3, 5}

Final index swaps between one of the first four. It chooses the third.

{2, 4, 5, 3, 1}

Which is our final result.

Heres an implementation using rand(), (mind you the randint() function exhibits low-bias due to the modulus unless the number of elements is evenly divisible by the maximum int value)

Code: [Select]int randint(int min, int max)
{
return rand() % (max - min + 1) + min;
}
void yates_shuffle(vector<int>& v)
{
int n = v.size();
for (int a = n - 1; a >= 0; a--)
{

int j = randint(a, n-1);
int tmp = v[a];
v[a] = v[j];
v[j] = tmp;
}
}





One interesting note regarding random numbers, however, is that rand() and srand() are actually strongly discouraged, in preference to some new way of doing it which presumably uses classes rather than being global state.Quote
The idea that a shuffle algorithm could return output that is the same as it's input and call it "shuffled" is poor design IMO.

I too thought the same, however if you need all combinations of A thru Z you wouldnt want to exclude A thru Z I suppose from the output. A better example would be the shell game with 3 shells and which one has the marble under it. Your starting position is say the shell furthest left. You wouldnt want people having a 50/50 chance that it has to be the middle or the right, you would want it to remain at 33% that all 3 locations for the marble to be located are in play. However a shuffle back to original form does seem kind of silly for so many other purposes where you dont want to have the output the same as the input. Catastrophic for a video game with a mortar range that is random. Range = 0 .... EPIC SHUFFLE FAIL

And that was why i went on the hunt for that magic number in the vast pool of Long Long Int looking for that magical worst seed value possible in which the output is the same as the input after a shuffle, and its not within the first Billion. I instead adapted a key strength test to the program so it will only allow use of a key thats strength matches what you allow. If allowance is 0 then all characters have to be in different placement for a complete shuffle an if you set it to 2 then 2 characters can be in their original spot as the allowance, but greater than 2 it rejects the key and says try another because the key you used is too weak. I should have just went this route to begin with vs running a 8-core computer for a week in search for that magical shuffle back to its original state of what was 85 characters and now expended to 89 characters. At some point it will be 90 characters with space considered as a character, but havent added that yet. Currently I use underscores or other characters in the message as word breaks such as [ Hello_World-It's~January_First ] to avoid [ HelloWorldIt'sJanuaryFirst ] so with 90 character support with the ASCII for space added I would have the ability eventually to have [ Hello World It's January First ] However spaces in crypt are a weakness because it would stand out like a sore thumb with a single string substitution where every character substituted for another you can figure out vowels pretty quickly and then pick away at it and crack it pretty fast. So my use of [ _-~ ] as word break spacers makes the word length a little more difficult to see vs such as if space was substituted for * you would see something like [ [emailprotected]*K0(sm*$9:*PqzVx(+*#u(^X ] where the * frequency sound be used as a space identifier and using a character of choice as a space holder would make something like this instead [ [emailprotected]?K0(sml$9:8PqzVx(+A#u(^X ] where word length is suddenly harder to find to dig at VOWEL probability.

The latest program that uses the flipflop uses 2 different shuffles and picks from them alternating so that something like AAAABBBBCCCCDDDD end up showing up as DxDx8v8vQwQw$c$c, additionally with two different shuffles to pull from you also have probability for characters to be used to substitute for two different characters where say L could be a D or a 7 depending on if its in the string at an even or odd interval withing the string so that [ HELLO ] could be an outcome of [ 4&D7P ] and now that D7 is unknown that its a double LL. This way if you look at the end result and see WW you cant say ohhhh that is a double letter or number and rule out the WW's in the text file as being high probability as being specific alpha characters in words or 00 thru 99.

Its been a lot of fun building up on this project and tinkering on it as I have time. I am learning from my mistakes and adding features reusing test code in the main program for example to exclude weak keys as an option based on what you want for key (shuffle strength).

Currently working on the inverse to this next version to convert the DxDx8v8vQwQw$c$c back to AAAABBBBCCCCDDDD which requires 2 Long Long Int keys to be entered and correct to get back to the initial input. And looking for why it gets stuck in an endless loop where it should run for as many iterations as is the length of the input so if you type in ABCD it should process 4 loops and end. Just like the flipflop problem I had with the other program its probably right in front of me and I will work at finding it. I have a condition where if a character is not recognized it will state that fact. If it hits this, then it means that a character wasnt satisfied and an unsupported character was used. I started looking at my arrays first to make sure I didnt make the mistake of arrays starting at 1 instead of that they start at 0 for first element in which you could essentially call to an array outside of the scope of the string in which you then are injecting whatever is in the memory at say array element 4 instead of 3 for the letter D and 4 is returned as garbage input that is not a supported ASCII character. Currently I have debugger lines added in there that I enable and disable through //commenting out to see that its flipping between 01010101 so I know thats correct but the fact that its doing whats seen below in an infinite loop vs ending after say 4 iterations for ABCD is strange and its a flaw in the code that I will find. Sometimes walking away from code and coming back to it it will all of a sudden stand out like a sore thumb.

unsupported character
0
unsupported character
1
unsupported character
0
unsupported character
1



Here is an example in how the shuffle can give out a weak shuffle. I ran looking for 9 characters that were shuffled back to their original position and found the seed/key value of 379120 to shuffle 9 characters back to their original starting position.

Ran the Poor Key Finder to get the key of 379120
Code: [Select]Poor Key Finder - Search for 9 or more matches
Searching through Key Values of 1 thru 1000000

WARNING - Program Running Please Wait...

Greater or Equal to = 9 ===== 379120
100% Complete
Completed = 1000000


Press any key to continue . . .
Code: [Select]#include <iostream>
#include <string>


int delay;
long long int counter1=0; // Add LL beyond 9 digits
long long int endcount=0; // while loop end counter
//long long int match=0;
//long long int nomatch=0;
long long int seed1=0;
int match2=0;
int ST=0;
int flag=0;
int progress=0; //Fixed float issue with 25% exact never found, removed float and placed int.
int step1=0;
int step2=0;
int step3=0;


int main ()
{
system("color b0");
std::cout<<"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n";
std::cout<<" Poor Key Finder Version 1.0\n";
std::cout<<" Build 01/30/2016\n";
std::cout<<"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n";
std::cout<<" Enter Starting Key Value\n";
std::cin>>counter1;
std::cout<<" Enter Ending Key Value\n";
std::cin>>endcount;
std::cout<<" Enter Duplicate Character Counter Value\n";
std::cin>>flag;
system("cls");

std::string str="[emailprotected]#$%^&*()_-+=?<>:\\/~.,;";
std::string str2="[emailprotected]#$%^&*()_-+=?<>:\\/~.,;";
system("@echo. Started on %date% at %time%>>LogKey.txt");
system("color f0");
std::cout<<"Poor Key Finder - Search for "<<flag<<" or more matches \n";
std::cout<<"Searching through Key Values of "<<counter1<<" thru "<<endcount<<"\n\n";
std::cout<<" WARNING - Program Running Please Wait...\n\n";
while(counter1<=endcount){
seed1=counter1;
srand(seed1);
random_shuffle(str.begin(), str.end()); // Shuffle the string
ST=0;
match2=0;

progress=((100*counter1)/endcount);


if(progress==25){
step1++;
if(step1==1){
std::cout<<"25% Complete\n";
}
else{}
}
else if(progress==50){
step2++;
if(step2==1){
std::cout<<"50% Complete\n";
}
else{}
}
else if(progress==75){
step3++;
if(step3==1){
std::cout<<"75% Complete\n";
}
else {}
}
else if(endcount==counter1){
std::cout<<"100% Complete\n";
}
else{
}
while(ST<=85){
if(str[ST]==str2[ST]){
match2++;
}
else{
}
ST++;
}
if(match2>=flag){
std::cout<<"Greater or Equal to = "<<flag<<" ===== "<<seed1<<"\n";
}
else{
}
counter1++;
}
std::cout<<"Completed = "<<endcount<<"\n\n\n";
system("@echo. Ended on %date% at %time%>>LogKey.txt");
system("pause");
//std::cin>>delay;
return 0;
}
Use the weak key in the old version of the crypto to get the crypt string key to copy paste that to word to line up that with the starting string in the screenshot below. Red is Bad below with characters that either never left their position or were shuffled back to their original position. My latest program uses the test of the poor key finder to allow you to know before use if a key is string enough or not.
Code: [Select] Crypt Version 1.05

XXXXXXXXXXXXXXXXXXXXX
Enter Integer Seed:
XXXXXXXXXXXXXXXXXXXXX

379120


Crypt String Key =

wLxDK8Ucfaj4nsVTINSM9oW!,pt_y:-;AYG%u/73m#q>z*^v$C.g1~H<X6&e\)[emailprotected]?i(bQ=dZhJrB
5+20RE


Enter Info to Crypt in correct case
Close Window to Exit
Pic attached shows the results with 9 characters that are shuffled back to their original position with a single random_shuffle.

So the Worst Key Ever to use with this is out there, the long long int value that shuffles everything back to its original position to where everything is clear text, however with the key strength test before key use, thats not a problem because the program wont allow you to use that worst key ever or anything not matching the key strength.



[attachment deleted by admin to conserve space]
1779.

Solve : VBScript GUI framework?

Answer»

I have been programming in VB6 and vbscript for a few years and have been annoyed that vbscript doesn't allow you to create any kind of interface aside from msgbox and inputbox. So I made it. I made it a while ago and discovered that it is very useful when you want to make GUIs without opening a VB6 project and creating a whole exe. I initially intended it to be used just by me, but then I got bored and decided to make it into an official project with documentation and everything. I also added a few other classes that do "AutoIt" like stuff. The actual file that creates the GUI is an ActiveX exe (28KB) that I created in VB6.

To test it:

Download the zip.
Run the install.bat (just copies to system32 and registers the exe)
Look at and run the sample vbscripts (sample1 might not work because of a path issue)
Use wshshelp in the help folder to read all of the functions that this has

Here is a quick sample of how this works encase you don't want to download:

Code: [Select]Dim f
Set f = CreateObject("WSHSHELL.GUI")

f.OpenWindow
f.SetWindowTitle "This is a sample window"
f.SetWindowLocation 10, 50
f.SetWindowSize 320, 200
f.LinearGradient 1, 0, 0, 255, 0, 0, 0

f.NewButton 1, "Push This!", 1, 1

While Not f.XIsPushed
Wscript.Sleep 100
If f.IsPushed("btn", 1) Then
f.FMsgBox "You pressed the button."
End If
Wend

f.CloseWindow
Set f = Nothing

[recovering DISK space - old attachment deleted by admin]What was wrong with using GTK with VBScript Language bindings?

(http://www.gtk-server.org/embedded.vbs.txt)

I mean no offense, but I can tell your rather new to most of this- I gather this purely from your apparent fascination with gradients. One of my first Subroutines was for painting a gradient in a variety of styles, and the first ActiveX Control I created was as well.


I've experimented with similar ideas (generalized GUI framework for scripting) but I didn't want to use it for VBScript, I wanted to use it with BCScript. Unfortunately I refuse to settle for a simple premise such as adding public methods that simply add new items to a control array. Controls.Add() would have worked perfectly, but unfortunately I could not find a way to properly sink events. I already had/have a rudimentary method (I could simply hook the event to a Evaluator function, in either my older VB6 version or my newer C# revisit) the issue (at least with VB6) was that I wanted a generalized method- I didn't want a event handler set that only worked for forms or certain controls, I wanted a way to actually sink events completely generically, much as VBControlExtender allows for ActiveX Controls (but I wanted this for control and object types). I managed to get a almost working version by manually implemented COM interfaces like IConnectionPoint2, but the whole thing was pretty much a rube goldberg device standing on a house of cards, something that comes with the territory when you start dealing with low level COM interfaces and literally EDIT the memory of Object Vtables to get around the fact that some COM interfaces have methods that are VB6 keywords. I learned this first with IEnumVariant, I had my BCFile library working so that I could use For Each and iterate through all the files in a folder, and the custom implementation would retrieve each ITEM one by one, rather then the makeshift method usually implemented, which is to just defer to a collection CLASS (that is, grab all files at once and RETURN the collection's IEnumVariant Implementation) The thing worked perfectly in the IDE, but crashed when compiled. And with all the various memory copies and modified object vtables, not to mention window subclassing debugging was anything but easy. I managed to trace it to a single instruction but was never able to determine the true cause.

Thankfully, with C#, this might be a little easier to implement, if I decide to allow it to be used as a sort of scripting language. Events are far easier to handle in a more generic fashion, especially thanks to reflection. (although the typelib information library was and is a powerful tool in VB6, when you don't have to language constructs to take advantage of the information, the information is useless).


Other notes:

Is your F: drive in some way special?
@linux711, heard of HTA? Quote

What was wrong with using GTK with VBScript Language bindings?

I didn't know something like that existed and could be implemented through vbscript.

Quote
I mean no offense, but I can tell your rather new to most of this- I gather this purely from your apparent fascination with gradients. One of my first Subroutines was for painting a gradient in a variety of styles, and the first ActiveX Control I created was as well.

The gradients are just use to make the gray background more interesting. That wasn't the main focus. I know gradients are kind of dull, I will probably add some kind of themes later.

Quote
I've experimented with similar ideas (generalized GUI framework for scripting) but I didn't want to use it for VBScript, I wanted to use it with BCScript.

If I made my own programming language, then I probably would have used it with that except I would have used C to make it faster.

Quote
Other notes:

Is your F: drive in some way special?

The F: drive is were VB6 is installed as well as all my program files. Why do you ask?Quote
@linux711, heard of HTA?

Yes, but I don't like using HTML to build a GUI. I am not much of a web programmer. I find this easier than HTML (not saying that HTML is hard Quote from: Linux711 on July 21, 2010, 01:55:27 AM
The F: drive is were VB6 is installed as well as all my program files. Why do you ask?

I ran sysinternals' "strings" utility on it, and one of the strings was

Code: [Select]F:\ProgramFiles\VB6\VB98\VB6.OLB

also whats with the "behzad.khazama" as the description in the manifest, as well as the url to "http://www.khazama.com/" And what is "Dosaidsoft"?

I'd remove those, or at least change them. I know I still have a few executables on my drive floating around with "School District 68" as their author.

Quote from: Linux711 on July 21, 2010, 01:55:27 AM
I would have used C to make it faster.

C doesn't make anything faster. it certainly makes most development a lot slower and tedious.Quote
also whats with the "behzad.khazama" as the description in the manifest, as well as the url to "http://www.khazama.com/" And what is "Dosaidsoft"?

The "behzad.khazama" manifest is what I used to apply the XP themes to my program. I got it from a forum and forgot to remove the guy's name DosaidSoft is just what I call my one-man software company.

Quote
I'd remove those, or at least change them. I know I still have a few executables on my drive floating around with "School District 68" as their author.

I'll remove the "behzad.khazama" and the web site, but isn't the "F:\ProgramFiles\VB6\VB98\VB6.OLB" required or something?Where do i download this frameworkQuote from: elishakkk on May 14, 2015, 09:25:02 AM
Where do i download this framework
Not here; deleted years ago; it was a home made thing; not available any more.
1780.

Solve : Small Basic. Nor for everyone - But great for youngsters.?

Answer»

In My Opinion , SMALL Basic. is Nor for everyone - But great for youngsters.

From time to time somebody asks 'what is best way for a young person to understand programming?' Often the response is to tell the person to study C or C++ pr Pascal or Python or Ruby or XYZ. This will bury the newcomer in documentation! Many don't want to read. That have to see it.

A very useful set of tools came for Microsoft in the form of Visual Basic. True, diving into Microsoft Visual Studio is a big task. But there is Small Basic. It is a nice entry into Microsoft Basic.

With Small Basic you get a super simple syntax that can be enlarged to show modern ideas in programming. Some nice arcade games are available in Small Basic. You can just copy and paste the examples and have working game.

References:
http://smallbasic.com/
Quote

Collision Physics
Demonstrates object collisions using real world physics properties. Tweak properties like elasticity, gravity, etc. to see the effects.

https://www.educatornetwork.com/Resources/Tools/Details/88dc49c7-6692-4ed9-8168-36f189941793
Quote
Help your students start writing their first programs quickly and easily. With only 15 keywords and an inviting development environment, Small Basic is structured to help them succeed. Students who wish to advance their software development skills can also take advantage of Small Basic's online guides and e-books to help them move ahead.

http://social.technet.microsoft.com/wiki/contents/articles/16059.small-basic-getting-started-guide.aspx

http://smallbasic.com/smallbasic.com/wiki/Search.aspx?Query=Einf%C3%BChrung+in+den+turtle-Befeh

Or just Google 'small basic' and find lots of stuff.
Small Basic is interesting but I see very little uptake in it. For very young kids, Scratch is fantastic for them to use and sets them up for a proper language like Python. With Small Basic the kids need to learn syntax for a full program language (where the syntax isn't that simple to begin with). Scratch on the other hand teaches the basic concepts of control flow and programming without worrying about learning syntax of a programming language. Once kids have mastered this they can then move onto learning an actual program to build useful stuff.I think beginning to program in BASIC is really a double edged sword. It may be relatively easy for someone to begin programming in BASIC, however, it's very different from most modern day languages. Almost all modern day languages have a syntax derived from C and are also object orientated. I think learning to program in C# as a first language is probably better in the long run even though it may be a little hard to start off. I taught myself to program in BASIC very young (around 13) and consequently stuck with the basic-like languages (Visual Basic) longer than I should have.

However, I would agree that learning BASIC as a first language is better than plain C or C++. C++ introduces unnecessary complexities that may frustrate a beginner enough to make them not want to bother programming at all. And it's not just the language itself; it's the weird tweaks and configurations that have to be done just to get a program to compile.The first language a person uses doesn't matter. SmallBASIC is as good as any, and because of it's context you'll never have beginners going on stackoverflow and being told "you should use WPF with MVC so you can keep to the DRY principle and also be sure to properly singleton your factory classes" or other nonsense garbage uttered by the type of people who, if they were to be a bridge engineer rather than a software engineer, would be obsessed with how to build the bridge while IGNORING the experience of actually crossing it. Many universities teach programming using languages like Haskell and Scheme, which have no stong presence outside academia. They do this on purpose. Then you have the classes that teach Java... ick.

Also, languages with a C-style syntax seem to be considered more "professional" but all we end up with by people learning languages like C# and Java is a bunch of punctuation fetishists obsessed with Three-Letter Acronyms.


SmallBASIC, Scratch(as camerongray mentioned) and Processing are some of the languages that I hear as being "beginner friendly", particularly for beginners still in grade school, as a sort of replacement for logowriter.Quote
Also, languages with a C-style syntax seem to be considered more "professional" but all we end up with by people learning languages like C# and Java is a bunch of punctuation fetishists obsessed with Three-Letter Acronyms.

Yes, I agree. I would have preferred that a language with a python/lua type syntax or some type of refined BASIC be adopted "professionally", but because C style languages are the most POPULAR, I think they are the best to learn.So that begs the question, what was Microsoft's intention with this version of Basic?Quote
because C style languages are the most popular, I think they are the best to learn.
Popular languages are hardly the best to learn by virtue of being popular, since popular languages often ignore powerful idioms. You aren't going to learn about OOP properly if you are taught Java or C#, you'll be taught Java's or C#'s 'special' kind of OOP; you aren't going to learn about things like Monads or metaprogramming, or the use of Option types, Object Expressions or Mixins.

Quote from: Squashman on February 27, 2015, 04:19:00 PM
So that begs the question, what was Microsoft's intention with this version of Basic?


Quote
Small Basic is intended for beginners that want to learn programming. In our internal trials we've had success with kids between the ages of 10 and 16. However, it's not limited to just kids; even adults that had an inclination to programming have found Small Basic very helpful in taking that first step.
Hey! Question. What is the best language to learn right now? I was told by a fellow programmer that Python was the one to learn right now. He said "It is the voice of the internet". But I'm skeptical because other languages seem just as good. I'm a beginner programmer just trying to make my way around. Thanks! Quote from: ThonkEggs on May 14, 2015, 08:55:22 AM
Hey! Question. What is the best.... that Python was the one to learn right now..... I'm a beginner programmer just trying to make my way around. Thanks!
In the IT and software development industry, Python is often used to model a possible solution to a problem. Later, the finished product might be done with something that gives higher performance.
On some instances, a bit of Python is needed to tie modules together. The Python code is then embedded into the product.
But his thread is about Small Basic. Learning Python as a first language will be a steep curve for the average person. IIMHO, the learning cure for Small Basic is much easier. Which is the point of this thread.
Professional programmers wind up using and/or learning four or more programming languages. But you have to start somewhere. Quote from: ThonkEggs on May 14, 2015, 08:55:22 AM
Hey! Question. What is the best language to learn right now? I was told by a fellow programmer that Python was the one to learn right now. He said "It is the voice of the internet". But I'm skeptical because other languages seem just as good. I'm a beginner programmer just trying to make my way around. Thanks!
You would be best to create your own thread for this but Python is a very good start. Sites like http://www.codecademy.com/ are great for learning it. The good thing with Python is that it is easy to get started in but is genuinely useful and can be used to build real world things, it's not just some sort of basic learning language.

When learning to program you will learn the basic concepts of all imperative programming languages which means that actually picking up a new language for a specific task is relatively easy.

The key thing is to just take care and think about the code you are writing and what everything does rather than simply copying code from tutorials.

Quote from: Geek-9pm on May 14, 2015, 02:57:11 PM
In the IT and software development industry, Python is often used to model a possible solution to a problem. Later, the finished product might be done with something that gives higher performance.
Python is also used for tonnes of large scale applications, it is not just a toy for modelling things. Performance with stuff like CPython is very good and is perfectly sufficient for the majority of applications.

Quote from: Geek-9pm on May 14, 2015, 02:57:11 PM
Learning Python as a first language will be a steep curve for the average person. IIMHO, the learning cure for Small Basic is much easier. Which is the point of this thread.
Python has one of the shortest learning curves of any programming language. The problem with learning Small Basic is that apart from learning it is virtually useless - Nothing in the real world is built with it. The only thing it has going for it is the easy graphics stuff but BEYOND that there is almost no reason that I can see for learning it over the likes of Python.Camerongray,
I stand corrected. Python really is a better choice for many.
Somebody ought to start a new thread on Python.

As BC noted, there has been too much emphasis on what language you start with. You can be sloppy or neat in almost any programming language. Just be neat and logical and you will make progress.
Reference:
http://www.hongkiat.com/blog/programming-myth/

Back to topic, a number of users may feel better about a thing supported by Microsoft. After Small Basic, a newcomer could more up to Visual Basic. It has been used to develop some important p[programs. While yes, they can move up to Visual Basic, that is still not really seen as a great language and while it is used in industry, it is certainly not that nice to work with or used for building new stuff outside of small hacked up applications nowadays. As far as being backed my Microsoft, this is hardly a reason to go for it, Python is hardly going to suddenly disappear and runs on anything. Small Basic is designed for Windows only and to a certain extent Visual Basic is as well (You can run VB stuff on other OSs using things like Mono but Microsoft's supported version is WIndows only at the MOMENT).SmallBASIC is sort of like a modern-day Logo. Logo was an excellent tool for learning programming concepts early on.

Though, at the same time, Logo was based on Common LISP.It somewhat is yeah, although if you want something purely for learning at that very early stage, I'd recommend something like Scratch, that way young kids aren't liable to make basic syntax/typing errors and can focus on the logic itself. Beyond the graphics stuff (which Scratch also has and could be implemented in Python with some libraries that could make it similar to Small Basic), I see very little benefit to Small Basic over Python.Quote
I see very little benefit to Small Basic over Python.

The Small BASIC "IDE" is far better integrated than IDLE, or any other Python IDE; I'd say only PyCharm really approaches it's level of accessibility. One of the reasons I think Logo is a good teaching language- bear in mind I refer to say, second grade or third-grade students - is that Logo is accessible and it provides a symbolic metaphor to understand the concepts in the form of the turtle.

SmallBASIC, nor Python have the symbolism, but SmallBASIC, I think, is more accessible to that level of learning.

Another 'starting language' that I've heard good things about is "Processing".

I don't think the cross-platform argument would ever apply in this scenario. A Learning language is not going to ever benefit widely from being cross-platform except to the vendor to distribute to more systems. A first or second grader using the system will be using it at school and the language being able to be used on, say, their Mom's macbook isn't going to really matter because that will never take place in that scenario. (of course, if a computer lab is already stocked with Macs, then clearly SmallBASIC is never an option to begin with).


Quote
While yes, they can move up to Visual Basic, that is still not really seen as a great language and while it is used in industry, it is certainly not that nice to work with or used for building new stuff outside of small hacked up applications nowadays.

Sounds more like an opinion than a statement of fact, though I would agree with the general sentiment when it comes to Visual Basic 6. But I think you would find it difficult to argue beyond opinion that VB.NET is "not that nice to work with or used for building new stuff outside of small hacked-up applications" I'm not even sure I could demonstrably argue against that being applied to any programming language. Any programming language A person is not familiar with will feel clumsy. Ruby feels clumsy to me, but that doesn't mean Ruby is clumsy- it means I don't know Ruby.

I don't think the First language a person learns really matters in terms of that language having an "obvious upgrade". The Fact that you can move to Visual Basic .NET from SmallBASIC could almost be argued as a negative simply because it promotes a monoculture.

The importance of a "first language" at that age is IMO accessibility. Make it as straightforward as possible. The fact that a kid learning via Logo in Grade 2 didn't have an obvious "upgrade path" doesn't matter. What is important is the concepts and the seed being planted. How that applies to SmallBASIC and Python, well, I don't know. I think both can be used reasonably in that environment, but Python would require some up-front work by educators to make it more accessible. Not a difficult task by any means. But I think Python would still take more effort than simply using Processing or SmallBASIC. (I know literally nothing about scratch so can't comment on that). You said it yourself-

Quote
The key thing is to just take care and think about the code you are writing and what everything does rather than simply copying code from tutorials.
It doesn't matter what language is being used.


Now, rolling back here a bit- I should reiterate that I am talking about "First language" in terms of say a primary school. If we're talking about a "First language" to use in an introductory college or high school course, then I would definitely say Python, Processing, even Scheme or Java or C# would be better choices than SmallBASIC. Historically the time when Primary schoolkids learned with Logo was the same time that introductory college courses used Pascal, so obviously the choice of software still needs to vary depending on the specific age group. I don't think SmallBASIC is a bad choice for very early programming to expose kids to basic (no pun intended) programming skills, but it would be a terrible choice for learning about data structures or OO concepts.

I think the point of such early programming is to firmly establish that computers are not magic boxes. They do not take special talent to program or control and telling them what to do is practically part of their function.
1781.

Solve : comparing dates?

Answer»

Hi, I get:

Fatal error: Can't use function return value in WRITE context in C:\xampp\htdocs\

from following code: I just want to determine "dayslate".
//---------

$dayslate = CURDATE() = DATE(DUEDATE);

// $dayslate = DATE(NOW()) - DATE(duedate);
//---------
// QUERY ON TABLENAME TABLE
$query = "SELECT dayslate,
--------------------------------What are you actually trying to do here? You have:
Code: [Select]$dayslate = CURDATE() = DATE(duedate);
Are you sure you aren't MEANING to SUBTRACT DATE(duedate) from CURDATE() rather than trying to set CURDATE() equal to DATE(duedate) which is what is causing the error. Your code should probably be:
Code: [Select]$dayslate = CURDATE() - DATE(duedate);

1782.

Solve : Java heart rate calculator?

Answer»

I'm writing a simple program to calculate someone's target heart rate, which is said to be between 50-85% of their max heart rate. Their max heart rate is defined as 220 minus their age.

Code: [Select] // based on age, return maximum HR
public int getMaxHeartRate()
{
int maxHeartRate = 220 - getUserAge();
return maxHeartRate;
}

// return target heart rate
public String getTargetHeartRate()
{
int targetHeartRateMin = (50/100) * getMaxHeartRate();
int targetHeartRateMax = (85/100) * getMaxHeartRate();
String targetHeartRate = " between " + targetHeartRateMin + " and " + targetHeartRateMax + " BPM.";
return targetHeartRate;
}

The getUserAge() method just takes a user inputted year and subtracts it from a Calendar.YEAR object, which works fine.

I'm calling the method with
Code: [Select] System.out.printf( "Your target heart rate range is: %s", getTargetHeartRate() );

I'm not sure where I'm going wrong, but I've a feeling it's a problem with DATA types between strings and ints. The output I get is "between 0 and 0 BPM", which obviously isn't correct.

Any help appreciated as usual. Quote from: kpac on October 13, 2011, 09:52:50 AM

but I've a feeling it's a problem with data types between strings and ints.

You're close; it's actually because of the way you are doing the MATH:

Code: [Select]int targetHeartRateMin = (50/100) * getMaxHeartRate();
int targetHeartRateMax = (85/100) * getMaxHeartRate();

in this expression, the (50/100) and (85/100) values consist of int's. What this means is that the division will have a result that is an int; the problem is that since 50/100 is 0.5, the int result is 0; same with 85/100 (it rounds down as well). so you end up multiplying it by ZERO. The solution is to force that calculation to be a float:
Code: [Select]int targetHeartRateMin = (int)((50f/100f) * getMaxHeartRate());
int targetHeartRateMax = (int)((85f/100f) * getMaxHeartRate());


Basically, the f makes the literals floats, so their result will also be a float, and a float multiplied by a int will be a float as well, and that get's cast to an int... I made that sound way more complicated than it is.

Another note, is that you might want to store the Result of getMaxHeartRate() beforehand, particularly if it asks for user input; if so you would need to enter the age twice.
Ah right, okay. I thought it would do the calculation first and then convert the result to an int.

Thanks anyway, works great.

Quote
Another note, is that you might want to store the Result of getMaxHeartRate() beforehand, particularly if it asks for user input; if so you would need to enter the age twice.
Yep, I am doing that actually. I'm using Scanner to get input and a setUserAge() method to save it to a variable.Who can help me To have much higher efficiency during exercises fitness / aerobic heart tries preferably 20 to 30 minutes maximum heartbeat which a person's heart can the afford. The written program for the calculation of the maximum heartbeat if given the entrance age, weight in kilograms and the number of heartbeat per minute (BEATS per minute). FORMULA MHR = 223 - age. Feil MHR formula = 211 415 - 0.5 * age * weight + 4.5. THR = (MHR-RHR) + RHR * 1.25. I need te write this in jgrasp. thanks!
1783.

Solve : Mis-use of Char or Proper??

Answer»

Picked back up on my one project to work on it further and after months of not looking at my code, I read through it again and realized that I might be mis-using code in which it works, but is not correct usage. I looked on google to try to find information on how it works to support whether its correct or not or if I am actually using a buffer batch like exploit in my code and this is the closest match to what I have: http://stackoverflow.com/questions/21675628/why-am-i-able-to-put-more-than-one-character-into-a-variable-of-type-char

Without listing the entire huge program I am just going to discuss the key areas. I initialize a Char at ch1 and have an input that is rested inside a while loop. This input into ch1 will take quite a few characters without a specified string length set. This is sort of sloppy when string length is unknown, but it works. When the user inputs data at the input such as Hello_World and then presses the enter key, it handles each character of the string input individually to end of the string. But the code is not told to handle the input as a string, instead the code appears to handle Hello_World as almost a batched character input where it will run the while loop for the number of characters entered. So the input is almost batching the characters as ( H, e, l, l, o, _, W, o, r, l, d ) then runs each character at a time as a single input stepping to the next then it ends when no more characters to process as an input.

Looking online as to how and why this works, I found this comment:

Quote

You type the whole string, the first GETCHAR() get first character, the remaining string stay at input stream, and your later getchar() inside while loop read them(one by one) and print out(one by one) until there are no char left(EOF), that's what happen. – moeCake Feb 10 '14 at 11:22

Trying to dig further into if this is proper use or not I find nothing. Additionally I was trying to figure out how a string could be held at a char input which is intended for just one single character to be stored at. Where does it store or buffer or batch this string for picking away at it 1 character at a time to end of the input character length.Standard Input and Standard Output are default streams attached to most processes. They operate like any other streams and this includes the presence of a buffer.

getchar() reads the next character in the standard input stream. SO when the code reaches the getchar() function, it blocks waiting for the next character.

However text is only added to the standard input buffer from the keyboard when you type enter. so when you type a line- say your Hello World example- and press enter, you are putting "Hello World" into the buffer. So getchar() reads the first character, "H", then drops into the loop, where it prints "H", reads the next character, "E", prints it, reads the next character, "L" ... etc.

Coincidentally, I had a run-in with a standard buffer issue myself, in something of a different way.

We have a Java program which our C# software invokes for reports. Recently, we added a capability to batch reports; that is, a single invocation of the Java program would be able to effectively run the same report for different sets of parameters (this avoided Java startup time and a bunch of other overhead connecting to the database and such).

What we found (or... well, actually our customers found it...) was that in using the new feature to try to mass reprint a large number of them at the same time, it would get stuck at about 300 or so. Even stranger, if the C# program that launched it was closed, suddenly the Java program started churning out report files again! It was quite a curious problem.

As it happens, these standard stream buffers- the same one that get's filled when you type a line of input into that getchar() loop- have a maximum size and that was the problem. The C# program redirects the standard input and output streams because it needs to send in database login info through stdin. Now, normally, it will have a background thread making sure the standard output is "drained" so it doesn't fill up, however a logic issue that dated back to 2014 was preventing that thread from ever being started (Woops!). We only saw an issue crop up recently because it wasn't until we added that batched feature that the standard output buffer was filled up- when the buffer gets filled, then the Java program blocks on the System.out.println() waiting for the standard output stream to be read to free space in the buffer, which never happens. Closing the original program fixes the issue as it stops the redirection, and if the buffer is never filled then the java program finishes it's task and exits without issue and all those standard streams get closed.Thanks for the info... also do you know what the maximum size is for the buffer. Is it the same as the default clipboard buffer or its own buffer?

I had a oddity happening within my loop with my latest code and not ready to tap out yet and ask for help on it as for maybe looking at my code with fresh eyes tonight it will jump out at me, but I have a counter that counts to 1 from 0 and resets to 0 when counter =1 after it completed the iteration instruction for a 0,1,0,1,0,1,0,1... flipflop and this way it uses two different arrays alternating. Current code starts at 0 and gets stuck at 1, so its 0,1,1,1,1,1,1,1,1,1 and looking at the code it should with the IF STATEMENT when counter=1 set it back to 0 to run the next iteration as 0 and use the other array. When the code looked correct and the outcome of how it runs was messing up I started digging for a cause and when i saw my string passed to char through the buffer, I got curious if this was breaking it and maybe I was misusing char with unknown string length and getting abnormal execution within it as a result of this.Quote from: DaveLembke on December 23, 2016, 11:40:43 AM
Thanks for the info... also do you know what the maximum size is for the buffer. Is it the same as the default clipboard buffer or its own buffer?

According to this the default size is 4K. Would be consistent with what I was seeing.
Cool thanks for your help with this. 4k is pretty decent size. Better than the 512 character LIMIT that I thought I might have had. So it can store 1024 to 4096 characters before overflow. http://stackoverflow.com/questions/4100324/how-many-characters-can-be-stored-in-4kb

Now to tackle the bug in my code with that counter that should be as clear as day and is acting up. Quote from: DaveLembke on December 23, 2016, 07:33:22 PM
Now to tackle the bug in my code with that counter that should be as clear as day and is acting up.

If you like, you can plop it here I could take a look and see if I spot anything off. Fixed my counter issue...and its a strange fix.

So in my code if you have

IF (flipflop==1){
flipflop=0;
}


It doesnt work.

BUT if you use this it works

IF (flipflop==1){
flipflop=-1;
}


Now its no longer doing the 01111111111111 and is now proper with 010101010101010101....

Here is a copy/paste from my program. The ABCDEFGHI = shows the crypt substitute for those characters per crypt. there are 2 crypts used so you see this twice below but different characters substituting in the 2nd group.

Quote
Crypt #1 String Key =

X=rGg"kZ:,@wf<msx3#tUL/*pnRNCc9-Q6SK!Y~?1_EP7h>TIF$4HJl(0jo%O;2Aedaivu5Vz&M)B.y8
bWD]'^q+\[

ABCDEFGHI = X=rGg"kZ:


Crypt #2 String Key =

o1zDMj";m(ER%h!7_eC=NT*P^Ygt4pn+v53#L'O$u~J6dKlwF-Q2IWyiq\9>k&8V]/?,rHSx:U)[emailprotected]
[BG.f<cbZ0

ABCDEFGHI = o1zDMj";m


Enter Info to Crypt in correct case
To Exit Inner Program enter ( ` )


AAAABBBBCCCCDDDDEEEEFFFFGGGGHHHHIIII
XoXo=1=1rzrzGDGDgMgM"j"jk"k"Z;Z;:m:m

The alternating character substitution shows it working as I wanted it to for 2 crypts. Not sure why it will work with -1 and not with 0, but i was like ok... this makes no sense at all, but what if I remove 1 with -1 from flipflop instead of setting it back to 0.

At least now I can move forward with making it more complex.


flipflop=-1;
This has been documented elsewhere.
Both Intel and Microsoft say you mist use -1 as a signed 16 bit integer to get all ones up and alive.
1111 1111b
This is more often an issue in verily low level code. Like assemble.
I can not find this in a Google,but I know it it is what Intel requires at the machine code level.
true = -1
false = 0
In x86 code you have a non zero and zero test. Using all ones for true allows bit testing for program control.

See also two's complement arithmetic.




I don't even really understand the problem. was flipflop not 1? Did you not initialize it to a known value beforehand?

Why not initialize it to 1 or 0 and use:

Code: [Select]flipflop = !flipflop;
It will flipflop from 1 to 0. !1 is 0. !0 is 1.

Initialized initially as 0

Then first time through the loop it is 0 ( This part works correct )

Then next iteration of loop it has flipflop++; which increments +1 ( This part works correct )

After its done processing for that loop in which the value is 1, the value is switched back to 0 with

IF(flipflop==1){
flipflop=0;
}

And this part doesnt work and for such one of the most basic of instructions I hit this problem months ago and it was frustrating in how this should switch flipflop to 0 if flipflip is 1, but it wasnt doing that.

Now here is where it gets really weird... I didnt change the placement of where the flipflop is reset in the program. And I tried using modulus even as a means to have even where mod = 0 and odd having mod = 1 and that didnt work. I said what if I set the value to -1 and compiled and ran it and all of a sudden it was working.

Here below is the latest program that is built upon my first. I ran into problems with the conversion from what i had initially to ASCII calls, so I stuck with the long list of IF statements to test the input character and then assign it a value reference to a shuffled crypt as a 1 for 1 replacement.

In this newest code there are 2 crypts and it alternates between use of crypt key 1 and crypt key 2. With this the character A substituted with say X would only be X at say every odd array element in which there is an A to substitute for in the input string that is to be jumbled and cryptic. My first program was just a 1 for 1 replacement and so it was pretty easy to break and see the message knowing that every character that is the same represents the same character substitution. With the newer more complex program that uses 2 crypt keys to generate the cryptic output A and X wont represent the same character so

AVAILABLE in my first program was X5X:#X8k!

AVAILABLE in my second program is X5X:#$8k!

The colored letters/characters representing where A is in each output. A to be X A has to land at a odd interval, whereever A lands at an even interval it is no longer X but instead it is $ since $ is from the second crypt key and same array element placeholder as the first. So if A was 1 then Array 1 element 1 is X and Array 2 element 1 is $

Also very cool on sharing the Quote
flipflop = !flipflop;
method. Ive never seen this trick done before. Question i have with its use is if its only good for 010101 pattern or if you can use a value specification with its use to get say 012301230123 etc? For years I have used the Increment and IF reset method.

Here is the entire program below. The part that might be confusing is the key strength part. If you use a value such as 9 it will use a weak key. 9 states that 9 characters can be the same between the original character from the string and the crypt output. Some shuffles have characters that stay in their original place within the array. I added this test for shuffle strength I think after I shared my first program last year, so this might be new to anyone who remembers the first program. I wrote a smaller program that used this key strength object as a means to try to discover the worst keys in which I told it to run for 1 billion keys from 1 to 1 billion shuffles of the array and look for characters that remained in their original element location within the array. I found a few that had 14 characters that remained in their original location, but didnt find the worst shuffle possible in which it is possible to use a value as a key and the shuffle places every character back into their original position in which there is none of the input cryptic, it all would go in as Hello_World and it would be written to file was Hello_World. I was very curious if there was the worst shuffle of all within the first billion keys and if so, how many times it hit that worst of all shuffle in which nothing ever got shuffled. I then realized after running my AMD FX-8350 4Ghz 8-core computer for almost a week that the best means to avoid use of a horrible key would be instead to just have it test the key right then and there as its input by user. So the electric wasted through this process was heating my home last winter for a week, and at least i know that the first billion keys dont have the worst shuffle of all in which the input becomes the same as the output. Additionally my program is single-threaded and I had it processing in 8 programs running with 125 million keys each in ranges from 1 to 125 million, 125 million and 1 to 250 million and 1, and so on in 8 groups each using a core of the 8-core CPU to process it all that much sooner vs 1 core of 8 pegged and it taking 8 times longer to get to 1 billion because all processing power not utilized.

After you put in 2 keys and it shows the 2 keys scrambled on the screen that it is going to use, you then type in whatever you want, however it does not support spaces and so underscores can be used as space holders. You then press the enter key when everything to scramble is typed and you will see it display characters from left to right, this can happen fast with a fast computer or slow if your on an Intel Atom or Pentium 4 computer. When you see this scrambled output to exit the program you press the [ ` ] key which is the key that the tilde key is but the other character that skips my mind as to its name. And press enter after pressing the [ ` ] key. This will then write the last character of the scramble to the data file that saves the message etc. You also will have 3 other files created. A counter file that is used to keep track of what was the last value to have them listed in the files and be able to know that data at line 5 goes with the 2 key files that are also line 5. So reassembly of the data requires you to have Key 1 and Key 2 from line 5 which goes with the data at line 5 in the data file. *Note: The program to unscramble/decrypt it is not contained within the main program. They are intended to be isolated as well as the keys and the data also isolated so that they can be physically separated and brought back together like pieces of a puzzle to get the messages back out from if you have the decrypt program, correct keys to put in and the data that needs to be unscrambled.

Reasoning behind this program is to take my very important data and put it on a thumb drive that I can store elsewhere and if my home burned to the ground I wouldnt lose this data. I use unique complex passwords with just about everything from banking to even online games that I dont want to get hacked etc. This data isnt safe on a cloud. I like having physical control of my data. I was for a while leaving a small notebook in my car with this data, but it was far too risky having something so easily read by another. I then put it on a thumb drive in my car with this data in a hidden location but the one day i realized I would be really scrambling to change passwords if this ever got lost ( fell out of car etc ) as well as if someone got their hands on a thumb drive say when getting an oil change and they are cleaning and they find it and pocket it the first thing they would want to do is see what is on it. I could have bank accounts cleaned out etc. So this is why I am working on making my own tool for my data to keep it safe. I plan on adding a SALT program later to this that also adds extra characters so that makes the data even that much more difficult to crack not knowing the message length, character substitution not always the same, and what is real from what is noise in the data.

The IDE I am using btw is Bloodshed Dev C++ 4.9.9.2 in which I have been aware that this IDE could have bugs that I might face some day and maybe just maybe the way that this IDE is compiling my program the reset to 0 doesnt work unless you use -1.

Code: [Select]#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <string>
#include <fstream>

using namespace std;


int main ()
{
long long int seed1=0;
long long int seed2=0;
int code1=0;
int run=1;
int again=1;
int test=1;
int writeenable=0;
int counter=0;
int intcheck=0;
int intcheck2=0;
char ch1;
char ch2;
int ST,ST2,match2,match3,flag;
int flipflop=0;

while(again==1){
system("color 8e"); // Black text with Yellow background

while(intcheck==0){
cout<<" XXXXXXXXXXXXXXXXXXXXXXXXXX \n\n";
cout<<" X Crypt Version 2.00C X\n\n";
cout<<" X Build 002 - 12/26/2016 X\n\n";
cout<<" XXXXXXXXXXXXXXXXXXXXXXXXXX\n\n\n";
cout<<" Enter Integer Seed 1: \n"; // Asks user to input integer seed
cout<<"\n\n";
cin >> seed1; // Input user seed1
cout<<"\n"<<" Enter Integer Seed 2: \n"; // Asks user to input integer seed
cout<<"\n\n";
cin >> seed2; // Input user seed2
cout<<"\n\n\n";
cout<<"Enter Key Strength Value\n\n";
cout<<"Note: 0 = complete scramble and 3 = 3 matching pairs in crypt\n\n";
cin>>flag;

// Seed 1 Test
// --------------------------------------------------------------------------
string str3="[emailprotected]#$%^&*()_-+=?<>:\\/~.,;[]\"\'";
string str4="[emailprotected]#$%^&*()_-+=?<>:\\/~.,;[]\"\'";

srand(seed1); // Allows user custom seeded starting algorithm position for random

random_shuffle(str4.begin(), str4.end()); // Shuffle the string

// -------------------------------------------------------------------------

ST=0;
match2=-1;


while(ST<=89){
if(str3[ST]==str4[ST]){
//cout<<str[ST]<<"\n";
match2++;
}
else{
}
ST++;
}

if(match2>=flag){
match2++;
intcheck=0;
system("cls");
system("color 4F");
cout<<" Warning: Crypt Key #1 Weak with [ "<<match2<<" ] matching characters \n";
cout<<" Please enter a different key\n\n\n";

}
else{
system("cls");
cout<<"Key #1 Approved\n\n\n";
intcheck=1;
}

// ----------------------------------------------------------------------


// } closed loop on 110 and prior, remains open on 200 and after

// Seed 2 Test
// --------------------------------------------------------------------------
string str5="[emailprotected]#$%^&*()_-+=?<>:\\/~.,;[]\"\'";
string str6="[emailprotected]#$%^&*()_-+=?<>:\\/~.,;[]\"\'";

srand(seed2); // Allows user custom seeded starting algorithm position for random

random_shuffle(str6.begin(), str6.end()); // Shuffle the string

// -------------------------------------------------------------------------

ST2=0;
match3=-1;


while(ST2<=89){
if(str5[ST2]==str6[ST2]){
//cout<<str[ST2]<<"\n";
match3++;
}
else{
}
ST2++;
}

if(match3>=flag){
match3++;
intcheck2=0;
system("cls");
system("color 4F");
cout<<" Warning: Crypt Key #2 Weak with [ "<<match3<<" ] matching characters \n";
cout<<" Please enter a different key\n\n\n";

}
else{
system("cls");
cout<<"Key #2 Approved\n\n\n";
intcheck2=1;
}

// ----------------------------------------------------------------------


}


system("color 8f"); // Black text with Yellow background



// Read in from text file the value for foldercounter variable
ifstream myfile("counter200.txt", ifstream::in);
while(myfile >> counter);

counter=counter+1;

//write value to pick up with next time program is run here
std::ofstream write ("counter200.txt", std::ofstream::out);
write << counter;
write.close();

//write value to pick up with next time program is run here
std::ofstream write2 ("Crypt200Key1.txt", std::ofstream::out | ios::app);
write2 <<"\n"<<counter<<" "<<seed1;
write2.close();

//write value to pick up with next time program is run here
std::ofstream write5 ("Crypt200Key2.txt", std::ofstream::out | ios::app);
write5 <<"\n"<<counter<<" "<<seed2;
write5.close();

//write value to pick up with next time program is run here
std::ofstream write3 ("Crypt200Data.txt", std::ofstream::out | ios::app);
write3 <<"\n"<<counter<<" ";
write3.close();

//Initialize Valid Characters for String Shuffle Output
//Note Bug corrected with blank space for \ by use of escape character proceeding
string str="[emailprotected]#$%^&*()_-+=?<>:\\/~.,;[]\"\'";
srand(seed1); // Allows user custom seeded starting algorithm position for random
random_shuffle(str.begin(), str.end()); // Shuffle the string
cout<<"\n\n"<<"Crypt #1 String Key =\n\n";
cout << str << "\n\n\n"; // Output the shuffle sequence

//Pass String Output into an array to pair up pointer value with associated character
string tmp = str; //Pass str output to string tmp
char tab2[128]; // Memory Allocation for array population
strncpy(tab2, tmp.c_str(), sizeof(tab2)); //string copy tmp into tab2 array
tab2[sizeof(tab2) - 1] = 0;

//HERE #2
//Initialize Valid Characters for String Shuffle Output
//Note Bug corrected with blank space for \ by use of escape character proceeding
string str7="[emailprotected]#$%^&*()_-+=?<>:\\/~.,;[]\"\'";
srand(seed2); // Allows user custom seeded starting algorithm position for random
random_shuffle(str7.begin(), str7.end()); // Shuffle the string
cout<<"\n\n"<<"Crypt #2 String Key =\n\n";
cout << str7 << "\n\n\n"; // Output the shuffle sequence

//Pass String Output into an array to pair up pointer value with associated character
string tmp2 = str7; //Pass str output to string tmp
char tab20[128]; // Memory Allocation for array population
strncpy(tab20, tmp2.c_str(), sizeof(tab20)); //string copy tmp into tab2 array
tab20[sizeof(tab20) - 1] = 0;


cout<<"Enter Info to Crypt in correct case\n";
cout<<"To Exit Inner Program enter ( ` ) \n\n\n";

while(run==1){

cin>>ch1;
//supress write to file until 1 loop run ( bug fix for double character write )
if(writeenable==1){

if(flipflop==0){
//write value to pick up with next time program is run here
//string tab2;
std::ofstream write4 ("Crypt200Data.txt", std::ofstream::out | ios::app);
write4 << tab2[code1];
write4.close();
}

if(flipflop==1){

//string tab20;
std::ofstream write4 ("Crypt200Data.txt", std::ofstream::out | ios::app);
write4 << tab20[code1];
write4.close();

} // While FF1
} //write enable
else{
//do nothing and continue
}
writeenable=1; //enable write to file

if (ch1=='A'){
code1=0;
}
else if (ch1=='B'){
code1=1;
}
else if (ch1=='C'){
code1=2;
}
else if (ch1=='D'){
code1=3;
}
else if (ch1=='E'){
code1=4;
}
else if (ch1=='F'){
code1=5;
}
else if (ch1=='G'){
code1=6;
}
else if (ch1=='H'){
code1=7;
}
else if (ch1=='I'){
code1=8;
}
else if (ch1=='J'){
code1=9;
}
else if (ch1=='K'){
code1=10;
}
else if (ch1=='L'){
code1=11;
}
else if (ch1=='M'){
code1=12;
}
else if (ch1=='N'){
code1=13;
}
else if (ch1=='O'){
code1=14;
}
else if (ch1=='P'){
code1=15;
}
else if (ch1=='Q'){
code1=16;
}
else if (ch1=='R'){
code1=17;
}
else if (ch1=='S'){
code1=18;
}
else if (ch1=='T'){
code1=19;
}
else if (ch1=='U'){
code1=20;
}
else if (ch1=='V'){
code1=21;
}
else if (ch1=='W'){
code1=22;
}
else if (ch1=='X'){
code1=23;
}
else if (ch1=='Y'){
code1=24;
}
else if (ch1=='Z'){
code1=25;
}
else if (ch1=='a'){
code1=26;
}
else if (ch1=='b'){
code1=27;
}
else if (ch1=='c'){
code1=28;
}
else if (ch1=='d'){
code1=29;
}
else if (ch1=='e'){
code1=30;
}
else if (ch1=='f'){
code1=31;
}
else if (ch1=='g'){
code1=32;
}
else if (ch1=='h'){
code1=33;
}
else if (ch1=='i'){
code1=34;
}
else if (ch1=='j'){
code1=35;
}
else if (ch1=='k'){
code1=36;
}
else if (ch1=='l'){
code1=37;
}
else if (ch1=='m'){
code1=38;
}
else if (ch1=='n'){
code1=39;
}
else if (ch1=='o'){
code1=40;
}
else if (ch1=='p'){
code1=41;
}
else if (ch1=='q'){
code1=42;
}
else if (ch1=='r'){
code1=43;
}
else if (ch1=='s'){
code1=44;
}
else if (ch1=='t'){
code1=45;
}
else if (ch1=='u'){
code1=46;
}
else if (ch1=='v'){
code1=47;
}
else if (ch1=='w'){
code1=48;
}
else if (ch1=='x'){
code1=49;
}
else if (ch1=='y'){
code1=50;
}
else if (ch1=='z'){
code1=51;
}
else if (ch1=='1'){
code1=52;
}
else if (ch1=='2'){
code1=53;
}
else if (ch1=='3'){
code1=54;
}
else if (ch1=='4'){
code1=55;
}
else if (ch1=='5'){
code1=56;
}
else if (ch1=='6'){
code1=57;
}
else if (ch1=='7'){
code1=58;
}
else if (ch1=='8'){
code1=59;
}
else if (ch1=='9'){
code1=60;
}
else if (ch1=='0'){
code1=61;
}
else if (ch1=='!'){
code1=62;
}
else if (ch1=='@'){
code1=63;
}
else if (ch1=='#'){
code1=64;
}
else if (ch1=='$'){
code1=65;
}
else if (ch1=='%'){
code1=66;
}
else if (ch1=='^'){
code1=67;
}
else if (ch1=='&'){
code1=68;
}
else if (ch1=='*'){
code1=69;
}
else if (ch1=='('){
code1=70;
}
else if (ch1==')'){
code1=71;
}
else if (ch1=='_'){
code1=72;
}
else if (ch1=='-'){
code1=73;
}
else if (ch1=='+'){
code1=74;
}
else if (ch1=='='){
code1=75;
}
else if (ch1=='?'){
code1=76;
}
else if (ch1=='<'){
code1=77;
}
else if (ch1=='>'){
code1=78;
}
else if (ch1==':'){
code1=79;
}
else if (ch1=='\\'){ // Escape Character \ needed to allow \ check
code1=80;
}
else if (ch1=='/'){
code1=81;
}
else if (ch1=='~'){
code1=82;
}
else if (ch1=='.'){
code1=83;
}
else if (ch1==','){
code1=84;
}
else if (ch1==';'){
code1=85;
}
else if (ch1=='['){ // added 86 thru 89 in version 1.10
code1=86;
}
else if (ch1==']'){
code1=87;
}
else if (ch1=='\"'){
code1=88;
}
else if (ch1=='\''){
code1=89;
}
else if (ch1=='\`'){ //Escape Character \ before ` to exit
run=0; //Run = False at 0 and leaves while loop
}
else {
cout<<"Invalid Input = No Match\n\n";
system("color CF"); // White text with Red background
}
system("color 8b"); // Black text with Green background
// Display output
//string tab2; //why? `tab2' undeclared (first use this function)

//Key #1 crypt
if(flipflop==0){

cout<<tab2[code1];

}
//Key #2 crypt
if(flipflop==1){

cout<<tab20[code1];

}
if(flipflop==1){
flipflop=-1; //Flipflop -1 because setting back to 0 is broken
}
flipflop++; //starts at 0 and alternates 010101010101 for 2 keysets
}// end inner while loop

test=1;
while(test==1){
system("CLS");
cout<<"Enter ( Y ) to continue - or - ( N ) to end program\n\n\n";
cin>>ch2;
if (ch2=='N'||ch2=='n'){
// line return to file ( formatting purposes )
std::ofstream write4 ("Crypt200Data.txt", std::ofstream::out | ios::app);
write4<<"\n";
write4.close();

again=0;
test=0;
}
else if (ch2=='Y'||ch2=='y'){
// line return to file ( formatting purposes )
std::ofstream write4 ("Crypt200Data.txt", std::ofstream::out | ios::app);
write4<<"\n";
write4.close();

intcheck=0;
again=1;
test=0;
run=1;
writeenable=0; //reset write enable to start of 0
system("CLS");
}
else {
cout<<"Invalid Input, please choose Y or N \n\n";
test=1;
}
}


} // end outter while loop
system("CLS");
system("PAUSE");
//return EXIT_SUCCESS;
return(0);
}



Quote
if(flipflop==1){
flipflop=-1; //Flipflop -1 because setting back to 0 is broken
}
flipflop++; //starts at 0 and alternates 010101010101 for 2 keysets


Mystery solved when more awake to look at own code ... Looking back at my code it looks like there is no good place for flipflop++ to increment and not affect the 0 to flip it to 1 and so the -1 fix I did, its changing the -1 to 0 and then counting to 1 in which it then is flagged to go back to -1 and then immediately set to 0 from the flipflop++ which +1 to -1 to make 0.

So thats why it was 011111111 when resetting to 0 because immediately it was incrementing the 0 to 1. Cant believe how stupid the fix was and I didnt catch that increment was hitting the 0 right away.

So its doing:
-1
0 // immediate from flipflop++ following -1
1
-1
0 // immediate from flipflop++ following -1
1
-1
0 // immediate from flipflop++ following -1
1
1784.

Solve : Crouton on Chrome OS?

Answer»

I'm trying to install Linux Ubuntu on my Chromebook, but I've ran into a couple problems.
When I enter Code: [Select]SUDO enter-chroot startxfce4 into my shell(I'm using crosh's chronos shell), it runs, but immediately shows an error, then another when I click past that one.

I installed Crouton from http://www.howtogeek.com/162120/how-to-install-ubuntu-linux-on-your-chromebook-with-crouton/, and followed the directions there, too. I did Code: [Select]sudo sh ~/Downloads/crouton -e -t xfce, then made a PASSWORD and encryption passphrase when prompted.

First error:
Code: [Select]Unable to contact settings server
//bin/dbus-launch terminated abnormally with the following error: EOF in dbus-launch reading ADDRESS from bus-daemon.
Second error:
Code: [Select]Unable to load a failsafe session
Unable to determine failsafe session name. Possible causes: xfconfd isn't running(D-bus setup problem);
environment VARIABLE $XDG_CONFIG_DIRS is set incorrectly(must include "/etc"), or xfce4 session is
installed incorrectly.
I've also added SCREENSHOTS of the command in crosh.

[attachment deleted by admin to conserve space]

1785.

Solve : .bat file to change multiple windows user's passwords?

Answer»

I have a .bat file that can change the password of one windows user account, however for the purpose i need it to be able to change the password of multiple or all user accounts. Here is the current .bat text so please tell me how to change it or write a new one.

@echo off

cls
set /p CP=Would you like to change the password of ANY user account on your pc? (Y/N):
IF '%CP%' == 'Y' GOTO CP
IF '%CP%' == 'y' GOTO CP
IF '%CP%' == 'N' GOTO DCP
IF '%CP%' == 'n' GOTO DCP

:CP
cls
set /p UN=What User Account Do you want to change the password for? (Type a user Name. For a list of users type UL.):
IF '%UN%' == 'UL' Goto NETUSER

cls
set /p AYS=Are You Sure you Want to Change the password of the account %UN%. (Y/N)
IF '%AYS%' == 'Y' goto CPY
IF '%AYS%' == 'y' goto CPY
IF '%AYS%' == 'N' Goto DCP
IF '%AYS%' == 'n' Goto DCP

:CPY
cls
Net User %UN% *
pause
exit

:DCP
cls
Echo The password will not be changed.
pause
exit

:NETUSER
Net User
pause
Goto :CPWhat you are doing would seem to be a violation of basic rules about privacy and security. If you are the real administrator of the system, you should already know this. So unless you can explain why you need to do this, it is doubtful any professionals would help you.I am in a club at school called cyberpatriots. In the club we are given virtual images that are messed up and need to be fixed. Every single time we need to do things like change the passwords and turn on the firewall. I want a batch file to do all the simple stuff quickly, so we can have more time to work on the more complicated problems with the image.I feel it necessary to "defend" what is being done here in a way. It is being replied to as if it defies security, or is some sort of exploit. It is not. NET USER * allows a password to be changed. It doesn't just allow you to change any password willy-nilly- one must have appropriate privileges. On a school network, for example, the user doing so will require domain administrator privileges. Given the context they have provided, it makes sense that they would have these privileges within the virtual images.

By the time this command is of any use for defeating security, that security is already defeated- as Raymond Chen would say, "You're already on the other side of the airtight hatchway".

All that said- I have no idea what the OP is asking for. If you want to deal with multiple accounts, just run the batch file multiple times. (perhaps in a SECOND batch file)Quote

I am in a club at school called cyberpatriots. In the club we are given virtual images that are messed up and need to be fixed

Anyone know if Microsoft has an exception for edu's to be able to copy and distribute images to students to operate under the same LICENSE key by which the image was created/activated?

Back in 2004 when I was in college we were strictly told to NOT violate Microsoft EULA by running any systems under the same license key as for the college didnt want the "Microsoft Police" there as the PROFESSOR stated. We also worked with virtual images of systems that the teacher would mess up, but they would be messed up by the teacher accessing your virtual PC 2004 image at your work station and then you had to go in and fix it. Sometimes it was a CD that was passed around the room that the teacher stated for everyone to run a program in the virtual environment that he made and burned to CD which would flip registry key entry VALUES that you wouldnt know what was changed until boot or until you went to perform some operation within the system etc. And you had to go in and fix the problems. Other times he didnt mess with anything, but wanted you to mess with it and then show him that you did it etc.Quote from: BC_Programmer on May 24, 2015, 05:00:43 PM
I feel it necessary to "defend" what is being done here in a way. It is being replied to as if it defies security, or is some sort of exploit. It is not. NET USER <username> * allows a password to be changed. It doesn't just allow you to change any password willy-nilly- one must have appropriate privileges. On a school network, for example, the user doing so will require domain administrator privileges. Given the context they have provided, it makes sense that they would have these privileges within the virtual images.

By the time this command is of any use for defeating security, that security is already defeated- as Raymond Chen would say, "You're already on the other side of the airtight hatchway".

All that said- I have no idea what the OP is asking for. If you want to deal with multiple accounts, just run the batch file multiple times. (perhaps in a second batch file)



The thing is i need the passwords changed as fast a possible. To run the batch file multiple times wouldn't be much faster than just going in and changing it the normal way. On the image we are given there are usually 5+ user accounts and each account needs the password to be changed to "Cyberpatriots!" or something like that. To be able to run the batch file once and change all the account passwords, to a specified password, is the thing i want. We are given admin privileges on the images we work on.It deems the BAT file you gave is harder Utahn it needs to be.
Here is what MS says about NET USER.

https://support.microsoft.com/en-us/kb/251394

Or, at the command line type:

Code: [Select]net help user
.. .and see all the options.
Quote from: FluffyWhale on May 25, 2015, 08:34:22 AM
The thing is i need the passwords changed as fast a possible. To run the batch file multiple times wouldn't be much faster than just going in and changing it the normal way. On the image we are given there are usually 5+ user accounts and each account needs the password to be changed to "Cyberpatriots!" or something like that. To be able to run the batch file once and change all the account passwords, to a specified password, is the thing i want. We are given admin privileges on the images we work on.
Instead of using set /p tp accept input, you can likely pipe keyboard input directly into the command eg.

Code: [Select]Net user BC_Programming * < newpassword

1786.

Solve : How do I create a pulse triggered by changes in a variable in FPGA??

Answer»

I need a MINIMUM 1 clock cycle pulse on a REGISTER whenever any of a few variables (other registers) change.
The following code is in VERILOG:
Code: [SELECT]reg pulse;
reg [2:0] count = 0; //Count to ensure that a FULL clock cycle has passed
always @ (var1, var2, var3)
pulse = 1;

always @ (posedge clk) begin
if (pulse == 1)
count = count + 1;
if (count > 1) begin
pulse = 0;
count = 0;
end
end That above results in the second Always block being ignored during synthesis optimizations.
Anyone know of a way to achieve a pulse?

1787.

Solve : How to open dbf file ??

Answer»

I am trying to load DBF files into SQL server within CLR (actually if just running the select statement outside, say within the SQLQuery window, i got the same result), but with the following ERROR:

Msg 7314, Level 16, State 1, Line 1
The OLE DB provider "VFPOLEDB" for linked server "MYDBF" does not contain the table "T8866064". The table either does not exist or the current user does not have permissions on that table.


I created the linked server in this way

EXEC sp_addlinkedserver
@server = 'MYDBF',
@provider = 'VFPOLEDB',
@srvproduct = 'My Data',
@datasrc = 'c:\data'

i did not create the login since my SQL instance is running under a superaccount with all privilege.

What frustrates me is that i can read most of the dbf files, but just a few of them is not readable.

Can anyone give me some hints on it?

by the way, i am using vfp9.0

thanksThe message of

Quote

The table either does not exist or the current user does not have permissions on that table.

States that either its permissions related or the table doesnt exist that the data is to be passed to. I'd look to see if the table exists first. A tool like SQLyog Community Edition is EASIEST to look at the database. If the table exists at the database that is the target, then I'd look into privileges, either creating an account or using the superaccount and specifying in the instruction the username and password to authenticate with.A linked server is basically just a pointer that lets the code within your database INTERACT with external data sources as if they were also within your database/instance. There are some examples here for creating linked servers to DBF Viewer Tool:
http://www.dbf.viewertool.com/
So for example if you had a linked server to a FoxPro database CALLED MyFoxProDB you could run a query within SQL Server like this:
UPDATE t
SET t.foo = x.bar
FROM dbo.LocalTable AS t
INNER JOIN MyFoxProDB...TableName AS x
ON t.key = x.key;
You could also consider using OPENROWSET as described in this question:
http://www.filerepairforum.com/forum/databases/databases-aa/dbase-iv-clipper-foxpro/964-how-to-restore-a-corrupted-file
You can safely ignore the software linked in the above post.
1788.

Solve : How do I install a program for a specific user,only!!?

Answer»

We have a VPS with more then 8 admins , users etc..
So my QUESTION is: How do I install a program for a specific user,only! and without appearing the shortcuts on ALL users desktops and without appearing in start Menu neither! I can remove the progr. icon from my start menu but i can't delete from All users menu

-Many programs don't have the option to install a progr. only for the current user

p.s
i work with windows 7 and server2008 only!

thank you
The answer is found on the Microsoft web site. But the way it is done might not be what you would like. The problem is that you have too many administrators.
Maybe yeou will have to SOMEHOW put most of the users into some group.
Fore Windows 8:
http://answers.microsoft.com/en-us/windows/forum/windows_8-security/how-do-i-install-an-app-visible-on-one-user/5bc629d1-c62a-47fd-b9c9-d74688442f52
Motr general method:
http://windowssecrets.com/forums/showthread.php/139248-How-do-I-install-an-application-for-just-one-user

You may need to re-think the way you manage users. When many people share the same computer, you don't want them all to have the same level of authority. Consider Group Policy.
See this:
https://technet.microsoft.com/en-us/library/hh147307(v=ws.10).aspx
Group Policy for Beginners
Quote

This white paper is an introduction to Group Policy. It first provides an overview of what you can do with Group Policy, and then it describes essential concepts that you must know. For example, what is a Group Policy object (GPO)? What does inheritance mean? With the fundamentals out of the way, this white paper provides step-by-step instructions, with plenty of screenshots, for the most common Group Policy tasks.
Even if you can not use Group Policy in your workplace, the concepts are important. Not everybody can be a chief. You may have to de-mote all users who should not use the special program.

IMO, you and your group need to consider having a group policy, at least as a concept.
Hope that helps. I've seen it done a few different ways. Some installers ask if its for everyone or just the user that is installing it which makes it EASY. If the installer has that option then you elevate their privileges as an admin of the system making them admin temporarily and install the software just for them as the installer has the option for, then after installed you drop their privileges back to user so they cant install anything else etc. Then that program on that system is set up just for them.

Method for systems where there is no option to deselect for everyone would REQUIRE pruning the desktop shortcut and path from the users who dont need that software as for its PART of their profile. Sometimes its as easy as altering the all users profile specification and then adding the shortcut for just that one user who needs it.

Group policy is the better means.
1789.

Solve : SQL Server 2000: Corrupt Stored Procedure (or syscomments table)?

Answer»

Under SQL Server 2000, I'm having a problem using (or viewing) a stored procedure. When trying to view the SP using the Enterprise Manager I'm getting this error message:

Error 0:[SQL-DMO]Object 'dbo.SP_ProcName' was not scripted. It is possible that the information in system table 'syscomments' about the object was corrupt or missing?

I can delete the SP using this interface without issue (by right-clicking on it and selecting 'Delete'). I can, using the Query ANALYZER, recreate it using a CREATE PROCEDURE script. When I try to use or view this script after recreating it, however, I get the same error message.
Have you tried google yet for info on this error?

Lots of hits, and this ONE might have a solution?

https://communities.vmware.com/message/2514397For more answers and solution TAKE a look at https://social.technet.microsoft.com/Forums/en-US/cc4cfcf8-93ad-4d8e-98db-9f241543da89/my-database-mdf-file-got-corrupted?forum=ssdsgetstarted

1790.

Solve : Java at 20: How it changed programming forever?

Answer»

Not a question, but an invitation for comments.
Twenty year sago the world saw the start of Java, which is now used everywhere.
Article from Info-world:
[ur=]http://www.infoworld.com/article/2923773/java/java-at-20-how-java-changed-programming-forever.html]How it changed programming forever[/url]
Quote

Java changed all that. While platform-dependent, manually allocated, procedural C code will continue to be with us for the next 20 years at least, Java proved this was a choice, not a requirement. For the first time, we began writing real production code in a cross-platform, garbage-collected, object-oriented language; and we liked it ... millions of us. Languages that have come after Java, most notably C#, have had to clear the new higher bar for developer productivity that Java established

What do you think about Java?
If you are a SOFTWARE engineer and you’re working on Java platform, then Java is definitely not dead. I think, near about 60% - 70% of job offers involve Java programming. Java is widespread in the enterprise as well as open source frameworks and platforms.Correct link is:
Java at 20:How it changed programming forever

Other variations of interpretive code followed. A large body of applications now are in some kind of byte-code like Java. But Java is a name held by Sun/Oracle. So the mutations can not be Java. Some think that in five years Oracle will loose its control.
Reference:
http://alternativeto.net/software/java/
There is a rebellion to overthrow the Java kingdom.

I have books on Java and Java Script which are 2 different but similar languages. Back when I was in college during the Dot-Com Bubble years 1997 thru 2000 it was important to learn and apply it as fast as your learned it. Friends of mine were making money left and RIGHT with freelance web design for everything from somewhat simple HTML with some neat Java Scripts to full projects with Java server side for businesses.

My BIGGEST problem during these years was that I wasnt focused enough to just deal with one thing as for I wanted to learn it all and so instead of spending the time my friends did with Java and Java Script projects, I was jumping all over the place with projects in C, C++, Visual Basic, Perl, HTML, Java, and Java Script and many many hours wasted but enjoyed playing video games. So I became familiar with these, but sort of a master of none by not being focused enough on one specific language.

In my area there has been a decline in Java positions in the employment ads and an ever growing listing for Ajax with Ruby and PHP. Its been a rare site to see Java anymore. Not to say that its dead, but the demand seems to be with Ruby and PHP in my area with Ajax Framework.Quote from: DaveLembke on June 22, 2015, 12:29:40 PM
I have books on Java and Java Script which are 2 different but similar languages.
aside from both languages having semicolons and braces, they are completely different languages. Visual Basic has more in common with Java than Javascript does. Java is an Object Oriented language where everything is part of a class; Javascript is not Object Oriented, instead it's OO capabilities are mimicked via prototyping.

The similarities between Java and Javascript pretty much end at the name. They are about as similar as a car is to carpet or a hamster is to ham.



Personally I think Java is one of the least usable of the more POPULAR languages in use today. I never say to myself "Oh right, I'm using Java" In a good way- it's always when I try something that doesn't exist in Java.

Or like I always think when I run the Java Installer where it says "Over one billion devices run Java"- "Oh don't be so melodramatic, we don't live in a world that is that awful"The similarities between Java and Javascript pretty much end at the name. They are about as similar as a car is to carpet or a hamster is to ham.Quote from: tiarulehe on July 06, 2015, 08:30:44 PM
The similarities between Java and Javascript pretty much end at the name. They are about as similar as a car is to carpet or a hamster is to ham.
...QUOTE OF THE MONTH CANDIDATE!
1791.

Solve : VPS: how to run as system a .exe tool as long as the server is UP?

Answer»

So i have a Tool.EXE i run it through a script ''Script.bat''.Now all i WANT is to run it day and night ''as SYSTEM'',as long as the SERVER is UP!! even if the other 4 administrators restarts or log off my session,how to do that?can someone help me? I strugle doing this for more than 6 months with poor results,i tried NSSM.exe but it only works when the vps is restarted,and not when i'm logged off.

thank you!!!!! You might need to wrap this program around a service name. Services can run in ways that BATCHES cant.

https://www.coretechnologies.com/products/AlwaysUp/Apps/RunBatchFileAsAService.htmlworking fine but how can i stop this??? i receive same message for windows 7 and server 2008Quote from: DaveLembke on November 28, 2016, 06:02:06 AM

You might need to wrap this program around a service name. Services can run in ways that batches cant.

https://www.coretechnologies.com/products/AlwaysUp/Apps/RunBatchFileAsAService.html

working fine but how can i stop this??? i receive same message for windows 7 and server 2008


when i press View the message i can see my tool runningInteresting typo in the window "form" vs "from"

More info here on hiding it... https://blogs.msdn.microsoft.com/patricka/2011/03/14/troubleshooting-interactive-services-detection/Quote from: DaveLembke on November 29, 2016, 11:46:42 AM
Interesting typo in the window "form" vs "from"

More info here on hiding it... https://blogs.msdn.microsoft.com/patricka/2011/03/14/troubleshooting-interactive-services-detection/

I USE a .bat script for a .exe tool
and yes i receive this:



When i check this i see nothing,is empty:


what about this? https://www.youtube.com/watch?v=5QrvC0gzmRw
1792.

Solve : front page display issue?

Answer»

my front page LOOKS great when IM in customizer but when i GO to my site and look at my front page it dont look right please help meHave you tried it through different browsers to see if it looks good under ONE but incorrect under another? Do you have a screenshot or more info on the not looking right part so we can see what the issue EXACTLY is vs guessing?

1793.

Solve : Java Banking Application Help Required?

Answer»

Hi, could someone please help me with my java code here is what i have so far but I'm getting compiling errors. It is an application to create a bank customer, set their initial deposit. It also needs to be able to withdraw only if funds permit. It also needs to be able to CALCULATE bank fees after the first initial transaction which is free. As well as do balance enquires I thought maybe storing customerName, balance, openingDate, accountNumber inside a VARIABLE but i have no idea how to do that yet. I'm new to java and programming in general maybe someone could help me out please? The main error I'm getting is "non-static variable this cannot be referenced from a static context" on lines 121-122-249-250

Code: [Select]/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package section3banking;


import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class S3Banking {

public static void main(String[] args) throws IOException {

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
int numberOfCustomers = 0;
Bank bank = new Bank();
String acc = null;
Customer[] c = bank.getCustomer();
while (true) {
System.out.println("****************************");
System.out.println("* Franks Bank *");
System.out.println("****************************");
System.out.println("* *");
System.err.println("* Please Enter Your Choice *");
System.out.println("* 1) Add Customer *");
System.out.println("* 2) Deposit Money *");
System.out.println("* 3) Withdraw Money *");
System.out.println("* 4) Check Balance *");
System.out.println("* 5) Calculate Interest *");
System.out.println("* 6) Exit *");
System.out.println("* *");
System.out.println("****************************");
int choice = Integer.parseInt(bufferedReader.readLine());
switch (choice) {
case 1:
System.err.println("\tEnter New Customers Name");
String name = bufferedReader.readLine();
System.err.println("\tEnter Opening Deposit Balance");
double bal = Double.parseDouble(bufferedReader.readLine());
System.out.println("\n");
Account account = new Account(bal, acc);
Customer customer = new Customer(name, account);
c[numberOfCustomers] = customer;

numberOfCustomers++;
System.out.println("<----------------------------------------->");
System.err.println(". Customer Account Created Successfully .");
System.out.println("...........................................");
System.out.println(". Opening Date : ");
if (numberOfCustomers == 0) {
System.err.println("Account Number Not Found");
System.out.println("\n");
} else {
boolean found = false;
for (int i = 0; i < numberOfCustomers; i++) {
Account temp = c[i].getAccount();
String accTemp = temp.getAccountNumber();
if (accTemp.equals(acc)) {
System.err.println("Enter Deposit Amount");
double money = Double.parseDouble(bufferedReader.readLine());
temp.deposit(money);
found = true;
break;
}
}
if (found == false) {
System.out.println("Account Number Not Found");
System.out.println("\n");
}
}
break;
case 3:
System.err.println("Enter Account Number");
acc = bufferedReader.readLine();
if (numberOfCustomers == 0) {
System.err.println("Account Number Not Found");
System.out.println("\n");
} else {
boolean found = false;
for (int i = 0; i < numberOfCustomers; i++) {
Account temp = c[i].getAccount();
String accTemp = temp.getAccountNumber();
if (accTemp.equals(acc)) {
System.err.println("Enter Amount To Withdraw");
double money = Double.parseDouble(bufferedReader.readLine());
temp.withdraw(money);
found = true;
}
}
if (found == false) {
System.out.println("Account Number Not Found");
System.out.println("\n");
}
}
break;
case 4:
System.err.println("Enter Account Number");
acc = bufferedReader.readLine();
if (numberOfCustomers == 0) {
System.err.println("Account Number Not Found");
System.out.println("\n");
} else {
boolean found = false;
for (int i = 0; i < numberOfCustomers; i++) {
Account temp = c[i].getAccount();
String accTemp = temp.getAccountNumber();
if (accTemp.equals(acc)) {
System.out.println("Balance is " + temp.getBalance());
found = true;
}
}
if (found == false) {
System.err.println("Account Number Not Found");
System.out.println("\n");
}
}
break;
case 5:
break;
case 6:
System.exit(0);
break;
default:
break;
}
}

}class Bank {

private double interestRateSavings = 2.5;
private double interestRateNegative = 12.75;
private double interestRatePositive = 0.5;
private double transactionFees = 1.00;
private Customer[] customers = new Customer[99999];

public void calculateInterest(Customer customer) {
Account a = customer.getAccount();
double bal = a.getBalance();
double interestAmount = bal * interestRatePositive / 100;
double totalBalance = bal + interestAmount;

}
String setDateTime() {
Date date = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
RETURN sdf.format(date);
}

public double getInterestRate() {
return interestRatePositive;
}

public double getTransactionFees() {
return transactionFees;
}

public Customer[] getCustomer() {
return customers;
}

}

class Account {

private double balance = 0.00;
private final String accountNumber;
private boolean firstTime = true;

public static Account(String acc) {
accountNumber = acc;
}

public Account(double bal, String acc) {
if (bal >= 0.00) {
balance = bal;
} else {
balance = 0.00;
}
accountNumber = acc;
}

public void deposit(double howMuch) {
if (howMuch > 0.00) {
balance = balance + howMuch;
System.out.println("\n");
System.out.println("New Balance:");
System.err.println(balance);
System.out.println("\n");
} else {
System.out.println("\n");
System.err.println("Incorrect Amount Entered");
System.out.println("\n");
}
}

public void withdraw(double howMuch) {
if (howMuch > 0.00) {
if (firstTime == true) {
double tempBalance = balance;
tempBalance = tempBalance - howMuch;
if (tempBalance >= 2.00) {
balance = balance - howMuch;
System.out.println("You Successfully Withdrawed " + howMuch);
System.err.println("Your New Current Balance is " + balance);
System.out.println("\n");
} else {
System.err.println("Insufficient Funds to withdraw " + howMuch);
System.out.println("\n");
}
firstTime = false;
} else {
Bank bank = new Bank();
double tempBalance = balance;
tempBalance = tempBalance - howMuch - bank.getTransactionFees();
if (tempBalance > 2.00) {
balance = balance - bank.getTransactionFees() - howMuch;
System.err.println("Withdraw " + howMuch + " from account " + accountNumber + "");
System.out.println("The transaction fee " + bank.getTransactionFees());
System.out.println("New Balance : " + tempBalance);
} else {
System.err.println("Insufficient Funds to withdraw" + howMuch);
System.out.println("\n");
}
}
} else {
System.err.println("Incorrect Amount Entered");
System.out.println("\n");
}
}

public double getBalance() {
return balance;
}

public String getAccountNumber() {
return accountNumber;
}
}

class Customer {

String date;
String name;
private final Account account;

Customer(String n, Account a) {
name = n;
account = a;
}

public void display() {
System.out.println("Name: " + name + ",Account Number: " + account.getAccountNumber());
}

public String getName() {
return name;
}

public Account getAccount() {
return account;
}

public String getOpeningDate() {
return date;
}

}
}
So you work for a bank, they need to you create a simple routine what's normally already usually created by a 3rd party company, and you don't know the language that the programming is in?

I have a friend who works for a bank and at least banks within the USA don't allow any information LIKE this to be shared outside of the bank. Additionally, they use a extremely secure system that was created by a 3rd party company outside of the bank that is liable for flaws in their programming, so its very well tested and penetration tested.

I would almost hope that this was homework and not an actual bank that needed to ACCOMPLISH this code goal to get this working. I do however like the 2.5% interest for savings private double interestRateSavings = 2.5; which is very generous compared to the less than 1% that I get on my savings.



Sounds like homework to me....Bank, Account, and Customer are nested classes of S3Banking. This means that in order to create instances of them you need an instance of S3Banking.

You can either split Bank, Account, and Customer into their own separate source files, or you can make the nested classes static. (You've also declared the Account constructor as "static" which isn't a valid modifier)

1794.

Solve : Code in excel?

Answer»

How do I create an interactive form using SPREADSHEET software that requests the person to enter a username, IDENTIFICATION number and job TITLE? Thanks in advance!I would do this using EXCEL VBA.

http://www.excel-easy.com/vba/examples/inputbox-function.htmlThanks you. I will try this.

1795.

Solve : FPGA odd behavior?

Answer»

I am programming a filter for a FPGA.
The input is 14 BITS, with registers arranged as [13:0], at a sample rate of 125 million samples per second.

I have coded the I/O to be this, where X[n] is input and y[n] is output:
aK,L[n] = x[n] − x[n − K] − x[n − L] + x[n − K − L]
b[n] = b[n − 1] + aK,L[n], n ≥ 0
c[n] = b[n] + MaK,L[n]
y[n] = y[n − 1] + c[n], n ≥ 0

There are 2 recursions needed, one at b[n] = b[n-1] + .... and one at y[n] = y[n-1] + ...
The first recursion at b[n] works properly, with expected outputs. The second recursion, however, exhibits some odd behavior. There are random spikes in the outputs for about 20 nanoseconds then return to expected values. The width of the input is 14 bits and all operations are done on 64 bit registers, oscillations are at a frequency of 100000hz, no overflow should be happening. Even if you're not sure how to fix this, any suggestions on what's causing this or possible solutions for this would be greatly appreciated (I honestly have no idea what could possibly be happening). Thanks in advance!
(Note: I should add that dividing c[n] by 1024 solves the issue, although I have no idea why. It does create new problems though, because of rounding errors, y[n] will approach to infinity if I divide c[n] by 1024. I am fine with dividing c[n] by 1024 if I can fix y[n] approaching infinity, as y[n] will simply be a trigger for the computer to capture x[n]).

- The code for this will be released as open-source once a working version is developed. For now, I'd prefer to not release any major section of the code just yet. If you need a specific MODULE to know what's causing this problem, then let me know and I'll post code for it if reasonable. c[n] is correct, y[n] is incorrect after recursion. Every operation in the equation (coefficients, +, -, *, /, ect...) represents a module.

Additional information:
Compiler - Vivado 2016.02 on MBP r13' 2015
OS - computer:ubuntu 16.04 FPGASystem:debian Custom OS
Input - Advanced Digital Cable.
Quote

The second recursion, however, exhibits some odd behavior. There are random spikes in the outputs for about 20 nanoseconds then return to expected values

Question I have is do these 20 ns spikes affect the outcome of the end result or is it just odd behavior while it runs, but otherwise the end result is fine?

Reason why I ask is because I ran into some oddities in how a multiple core CPU handled some code before, where I expected all active threads to end at just about the same time, however they didnt. I had a multithreaded execution that when that part of the process was done, another process then grabbed this data and further refined it. What i ended up having to do is put in a delay so that all threads were done processing before running with the next step as the quick fix to my problem. Digging deeper as to why the threads were ending the task sooner than others, it came down to the fact that the OS itself while running was using slices of the multiple core system and this caused the execution of those threads to slow as for it wasnt given the constant green light to keep crunching the numbers, it got red lights the wait at as the OS was running other duties and until that was done and green light given to continue for that thread it added lag to that thread, which in the end caused them to end in unpredictable order. I played some with core affinity to set the OS to run only on a single core of a multiple core system and this helped some, but it really came down to that why isolate the OS to a single core of the quadcore, just add a time delay for whichever thread ends the soonest, and then with a time delay window large enough but not too long of a delay, all threads are done and then its able to then start the next part of the process with all threads at the finish line for the first part of the crunching before the end result is then used for the next step of the process.

Im thinking your running into this delay ( 20 ns spike ) which may even act harmonic at times in addition to random in relation to how the OS is using the CPU and how your program is. One thing to try would be to set core affinity for set the OS to a single core and then other available cores used just for your processing and see if this changes this 20 ns spike issue.

This is a situation where the code is likely sound and solid, but, the way the CPU is juggling the OS and your program is giving you this oddity. Here is more INFO on Core Affinity for Ubuntu: http://www.hecticgeek.com/2012/03/assign-process-cpu-ubuntu-linux/

Setting Dedicated Cores with core affinity for your program might clean this up is my thoughts to this.

Also through this process, does this system have plenty of RAM, or is RAM use 100% to where data is paging to HDD and then playing catch up to slip it back into the execution.Sorry I think you misunderstand. The computer creating the FPGA is running ubuntu. There are error checks while synthesizing code, it's highly unlikely that the compiled code is wrong repetedly. (I compiled 7 slightly different versions attempting to fix the problem without doing c[n]/1024).
The computer actually running the FPGA is running debian (redpitaya OS). The CPU is set to directly upload input and output to ethernet, it does nothing else. Calculations are done by hardware logic. The number of cores it's using shouldn't affect its ability to correctly display numbers.
As for the FPGA, it's purely sequantial and alternating clock so no race conditions exist. If a logic series happens to take more than an 0.5 clock cycles, I'd be extremely surpised. I can test this by adding a delay between every module, but I doubt if it will change things. The problem occurs at the second accumulator module, which is identical to the first accumulator module. The reason why I say this is odd is because the first one works and the second one doesn't, despite them being literally the exact same.

I am trying something right now that will hopefully fix it. Currently the circuit is in one line that goes like this:
[13:0]
[63:0] x 7
[13:0]

I will try rewiring in this fashion:
[13:0] [63:0] x 2
[63:0] x 6 [13:0]

No idea if it will work at the moment.
The RAM usage as you suggested may also be a cause of this. I will disable some unneccesary modules and see if it fixes things. The ram is PARTITIONED, I don't have the equipment to monitor the section dedicated to the fpga.Okay, I just tested the rewiring and it takes care of the spikes. But, of course, a new problem happens (why am I not surprised....).
Lets cover problem first:
Output is off by about 2048, easy fix with offset settings.

Now, 2 more problems that I have no idea how to fix:
1. Oscillations of ±80 to the original waveform, as if a sinusoidal wave is added on to the output waveform. This problem also occurred in simulator, so it may be an actual logic problem, let's not worry about that for now.
2. Incorrect shaping of output waveform (suggests synthesized logic isn't an exact match of equation mentioned in first post).

The simulated logic from the code matches the equations, I'll assume it's synthesis errors or hardware delays causing the incorrect shaping. Now rewiring circuit again, separating all modules this time. Hopefully this may be a usable version after synthesis. If not then I will empty out room (possibly get rid of the digital input filtering and decimation modules) for registers between each module. If anyone knows a better way to do this then please let me know. Thanks.Quote
1. Oscillations of ±80 to the original waveform, as if a sinusoidal wave is added on to the output waveform. This problem also occurred in simulator, so it may be an actual logic problem, let's not worry about that for now.
Quote
2. Incorrect shaping of output waveform (suggests synthesized logic isn't an exact match of equation mentioned in first post).

The help your looking for is slightly outside the scope of what most are able to assist with here. Your dabbling in an area that I am not a specialist with with the FPGA and your electronics. I have worked with DAC & DSP's but the wave forms were used for linear positioning with transducers etc. Automation and Microcomputer Electronics is where I have dabbled with in a past career and left that in 2001 after 6 years with Rockwell Automation. Electronics has come quite a ways since 2001. Sorry to say that I'm probably not going to be of much more help on this.

Regarding #1, if its a fixed sinusoidal frequency that your getting that you want to eliminate, I would think that cancellation would be just a matter of a synchronous phase lock to it to remove it as synchronous noise removal. However if you can find the cause of this vs a phase lock cleanup that would be better than adding band aids. Problem with a synchronous phase lock cleanup is that while it would clean it up to remove this, you have a probability that for very small time intervals you could be cutting out the signal you want where the sine wave intersects your signal, and this could make for more problems.

Regarding #2 ... thinking #1's noise is causing the shaping issues.

Do you have a schematic available to take a look at of what electronics your using?
1796.

Solve : Macro in Microsoft Word (code)?

Answer»

Does anyone know how to construct a macro that runs an Automatic spell check on a document when opening and closing it? Would be nice to have a macro button for it as well.

Would also like to know how to construct a macro that counts the number of words in a document too.

Yes I am aware Word has these features built in, but I'm a student working on a project and really in need of this information. Thanks in advance!
The forum can not help a student SHIP homework.
Exceptions are made for absolute Dummies. If you confess to being an absolute dummy, we MIGHT be able to help.

Here is a tutorial you should have read at least once:
How to Make a Macro in Word 2013 - For Dummies!
You will find 6 screen shots of how a simple macro is made in Word. To go to the next screenshot, CLICK on the .

That will give you a start.


I am an absolute dummy on this specific topic and will ask nothing further based on my student side of life, just need some guidance not the answer, if that is possible? Okay, seeing the guidance POST, thanks

1797.

Solve : Problem Importing FoxPro File...?

Answer»

I'm using MS Access 97 and I'm TRYING to import a FoxPro "dbf" FILE. When I try to import, I get the message "Cannot access the FoxPro 3.0 BOUND DBF file ...(filename)". Now, I thought the file was a FoxPro 3.0 file, but the extension is dbf, not dbc and the file only shows up when I choose files of type "FoxPro (*dbf)" format and not "FoxPro 3.0 (*dbc)". Does that MAKE any sense?

THANKS.

1798.

Solve : int main() vs int main(void)?

Answer»

Got into a discussion at work with another C++ hobbyist and they looked at a program I wrote and asked why not use

int main(void) instead of int main()

I personally have always used just int main() for the most part because its by habit and how I was taught in college.

Looking here there is a discussion on it:
http://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c

Quote

Standard C++

The C++11 standard (ISO/IEC 14882:2011) says:

3.6.1 Main function [basic.start.main]

¶1 A program shall contain a global function called main, which is the designated start of the program. [...]

¶2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation defined. All implementations shall allow both of the following definitions of main:

int main() { /* ... */ }

and

int main(int argc, char* argv[]) { /* ... */ }

In the latter FORM argc shall be the number of arguments passed to the program from the environment in which the program is run. If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as POINTERS to the initial characters of null-terminated multibyte strings (NTMBSs) (17.5.2.1.4.2) and argv[0] shall be the pointer to the initial character of a NTMBS that represents the name used to invoke the program or "". The value of argc shall be non-negative. The value of argv[argc] shall be 0. [ Note: It is recommended that any further (optional) parameters be added after argv. —end note ]

¶3 The function main shall not be used within a program. [...]

¶5 A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the ARGUMENT. If control reaches the end of main without encountering a return statement, the effect is that of executing

return 0;


And the int main(void) seems to be dated back to earlier C++ standards



Quote
The accepted answer appears to be targetted for C++, so I thought I'd add an answer that pertains to C, and this differs in a few ways.

ISO/IEC 9899:1989 (C90):

main should be declared as either:

int main(void)
int main(int argc, char **argv)

Or equivalent. For example, int main(int argc, char *argv[]) is equivalent to the second one. Further, the int return type can be omitted as it is a default.

If an implementation permits it, main can be declared in other ways, but this makes the program implementation defined, and no longer strictly conforming.

The standard defines 3 values for RETURNING that are strictly conforming (that is, does not RELY on implementation defined behaviour): 0 and EXIT_SUCCESS for a successful termination, and EXIT_FAILURE for an unsuccessful termination. Any other values are non-standard and implementation defined. main must have an explicit return statement at the end to avoid undefined behaviour.

Finally, there is nothing wrong from a standards point of view with calling main() from a program.

ISO/IEC 9899:1999 (C99):

For C99, everything is the same as above except:

The int return type may not be omitted.
You may omit the return statement from main. If you do, and main finished, there is an implicit return 0.


So does it really not matter int main() or int main(void), its just 2 ways of accomplishing the same thing, since after all the programs both will run fine with whatever style is used?

I was taught this way without the use of int main(void) between 2000-2004 back in college.










Quite a big discussion here

http://stackoverflow.com/questions/12225171/difference-between-int-main-and-int-mainvoid
As the linked StackOverflow question/answers indicate, the difference would only really affect C.

As noted therein in one of the answers, In C, when declaring a function prototype, an empty argument list basically meant that you could pass any parameters to that function. In order to make a function and have it take no arguments at all, you would have to specify "void". C++ of course being a superset of C allows you to do this but an empty parameter list means the same thing.

Personally, any C++ main() routine I write (I don't write C/C++ very often, though) get's the full int main(int argc, char** argv) definition. (Should be noted that char** argv is identical to char* argv[] as a parameter type, though I'm not sure how I got into that habit)Quote
Personally, any C++ main() routine I write (I don't write C/C++ very often, though) get's the full int main(int argc, char** argv) definition. (Should be noted that char** argv is identical to char* argv[] as a parameter type, though I'm not sure how I got into that habit)

Being explicit with the parameter types I guess might be better practice vs leaving it undefined (). There are times when you have to be explicit or else you end up with strange problems or compiler warnings or errors. When compiling it was my understanding that the compiler whether int main() or int main(void) basicially interpreted it the same such as when using cout and printf(). However I have read that printf() seems to run faster than cout calls so if the compiler accepted both as equal when compiling there wouldnt be a speed advantage between one and the other when they are executed, so the statement that a software engineer told me years back may be completely false with how the compiler compiles the source from what we can read as source code into machine language.

Thanks for the inputs on this subject
1799.

Solve : VFP9 Double click on DBF .dbf gives message ".fxp is not an?

Answer»

In Windows Explorer, when I double click on a dbf file (of FORM .dbf), INSTEAD of opening the file in VFP, I get a message ".fxp is not an object file".

e.g. clicking on T_DCLNT.DBF, gives message "t_dclnt.fxp is not an object file".

OS is Windows 7 Home Premium 64 bit.

Am unsure what to do as Windows 7 no longer has the Edit File Type tab to edit ACTIONS associated with a particular extension or file type.
You don't have the Edit File tab but you do have Open with... Right click on the DBF file in Windows Explorer and choose Open with... Then choose your Visual FoxPro and check the "ALWAYS use the selected program to open this type of file" box.

1800.

Solve : mysqli update?

Answer»

Hi, the code below creates the result I want (don't know how to post a localhost screenshot). My issue is that I don't know how to link that code, (code 1) to (code 2) which updates the "lastused" file, the current date.
-------------------------------------------------------
(code 1)
Code: [Select]<!DOCTYPE html><html>
<title>email menu</title>
<head></head>
<BODY><center>
<FORM name=lastused method="post" action="">

<?php
error_reporting(E_ALL^E_NOTICE);
//error_reporting(0);
echo"<center>";echodate('m/d/y');echo"</center>";
$id="''";
$con=mysqli_connect("localhost","root","cookie","homedb");

//==============checkconnection

if(mysqli_errno($con))
{echo"Can'tConnecttomySQL:".mysqli_connect_error();}
else
{echo"</br>";}

//==========Thiscreatesthedropdownboxusingrecordsinthetable

echo"<selectname='target'>";
echo'<optionvalue="">'.'---selectemailaccount---'.'</option>';
$query=mysqli_query($con,"SELECTtargetFROMemailtbl");
$query_display=mysqli_query($con,"SELECT*FROMemailtbl");
while($row=mysqli_fetch_array($query))

{echo"<optionclass=highlightvalue='".$row['target']."'>".$rowtarget']
.'</option>';}

echo'</select>';
?>
<input type="submit" name="submit" value="Submit"/>
</form></body></html>Code: [Select] <?php
error_reporting(E_ALL^E_NOTICE);
//error_reporting(0);
$con=mysqli_connect("localhost","root","cookie","homedb");
if(mysqli_errno($con))
{echo"Can'tConnecttomySQL:".mysqli_connect_error();}
if(isset($_POST['target']))
{
$id=$_POST['id'];
$lastused=$_POST['lastused'];
$name=$_POST['target'];
$fetch="SELECTtarget,username,password,emailused,lastused,purpose,savedFROMemailtblWHEREtarget='".$name."'";
$result=mysqli_query($con,$fetch);
if(!$result)
{echo"Error:".(mysqli_error($con));}

//===============================thisdisplaysthetable

echo'<tableborder="1">'.'<tr>'.'<tdbgcolor="#FFD47F"align="center">'.'emailmenu'.'</td>'.'</tr>';
echo'<tr>'.'<td>'.'<tableborder="1">'.'<tr>'.'<tdbgcolor="#ccffff">'.'target'.'</td>'.'<tdbgcolor="#ccffff">'.'username'.'</td>'.'<tdbgcolor="#ccffff">'.'password'.'</td>'.'<tdbgcolor="#ccffff">'.'emailused'.'</td>'.'<tdbgcolor="#FFD47F">'.'lastused'.'</td>'.'<tdbgcolor="#ccffff">'.'purpose'.'</td>'.'<tdbgcolor="#ccffff">'.'saved'.'</td>'.'</tr>';
//while($data=mysqli_fetch_row($fetch))
while($data=mysqli_fetch_row($result))
{echo("<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td><td>$data[4]</td><td>$data[5]</td><td>$data[6]</td></tr>");}
echo'</table>'.'</td>'.'</tr>'.'</table>';
}
?>
</body></html>-----------------------------------------------------------
(code 2)
Code: [Select]<?php
error_reporting(E_ALL^E_NOTICE);
$servername="localhost";$username="root";$password="cookie";
$dbname="homedb";
//Createconnection
$conn=mysqli_connect($servername,$username,$password,$dbname);
//Checkconnection
if(!$conn)
{die("Connectionfailed:".mysqli_connect_error());}

$name=$_POST['target'];
$SQL="UPDATEemailtblSETvisits=visits+1,lastused=NOW()WHERE

target='".$name."'";
if(mysqli_query($conn,$sql))
{echo"Recordupdatedsuccessfully";}
else
{echo"Errorupdatingrecord:".mysqli_error($conn);}
?>-----------------------------------------------------------








First things first, I suggest that rather than jumping straight in and building this you go and learn how to properly perform database QUERIES in PHP. At the moment you are putting user input directly into queries which leaves you wide open to SQL Injection Attacks. You need to read up on how to properly escape inputs coming from the user before putting them into a query or use something like PDO to work with prepared statements.camerongray has a point here. You should not be developing code that leaves user input unfiltered. However, I realize we all start somewhere, just that I would advise you to keep your testing code on a local server, or on a server with a .htaccess entry to restrict access to only your IP address. This is how I started, throwing myself into development and learning what I needed to as the need arose.

Moving on:

Correct me if I am wrong, but it looks like you are trying to essentially timestamp when the records were accessed and increment the "views" each time the script is called.

There are two ways you could do this.

SINCE you have the "$name = $_POST['target']" therefore requiring a POST request, you could look into a JQuery call in JavaScript to run the code2.php page when code1.php also loads.

You could also use an include or require or require_once and include the code2.php file that way, and find a way of naming the "$name" variable before the include (As variables from your code1.php are run in your includes) and then get rid of the $_POST variable.

Still, the code is vulnerable to SQL Injection attacks and I would keep this on a private server.

I claim not to be an expert so if anyone else has some better SOLUTION let us know. Thanks for the response. My past was in data proc., now, with memory probs, it's my pastime, localhost only.
Having written hundreds of docs using mysql I'm attempting to learn mysqli. I intend going to prepared statements, if only for the learning exp.
The following code is my current stab at it.

My object is just to update
fields in a database table. The 3 records in the table are shown in the
subsequent report. All the fields DO have a value and the recur values are 'Y', payrec 'P' and periodic '1 or 6' but nothing GETS updated.
No errors indicated.
Any help?

Code: [Select] <?php
echo"<center>";echodate('m/d/y');echo"</center>";
$id="''";
$periodic='';
$duedate='';
$con=mysqli_connect("localhost","user","passwd","mydb");
//==============checkconnectiont
if(mysqli_errno($con))
{echo"Can'tConnecttomySQL:".mysqli_connect_error();}
else
{echo"connectedtodatabase</br>";}

//-----------------------------------------
$fetch="SELECT
acctno,recur,pd,payrec,bname,duedate,datepaid,purpose,amtdue
FROMtestbl
WHERErecur='Y'ANDpayrec='P'";
$result=mysqli_query($con,$fetch);
if(!$result)
{echo"Error:".(mysqli_error($con));}
else
{echo"databasetableselected</br>";}

//----------------------------------------

//outputdataofeachrow
while($data=mysqli_fetch_row($result))
{

//----------------------------------------
if($periodic==1)
{$duedate=date('Y-m-d',strtotime('+4week'))."\n";}
if($periodic==6)
{$duedate=date('Y-m-d',strtotime('+25week'))."\n";}
$pd='P';$dayslate=0;

//-------------------------------------------------
$sql="UPDATEtestblSET
duedate=$duedate,
pd=$pd,
dayslate=$dayslate,
datepaid=NOW()
WHERErecur='Y'ANDpayrec='P'";

//------------------------------------------------
}
header("refresh:3;url='http://localhost/invoice/autolist.php'");
?>I have checked the validity of the table and in
all 3 records "recur" ='Y', "payrec" ='p', values are in "duedate",
"datepaid" (type is DATE) and "periodic". I'm looping thru the data; var_dump() displays NULL NULL NULL, It seems that my DATEDIFF is flawed.
I've spent considerable time viewing forums, manuals, code types. How about some advice?

Code: [Select]<?php
error_reporting(E_ALL^E_NOTICE);
//error_reporting(0);
$servername="localhost";$username="root";
$password="cookie";$dbname="test";

//Createconnection
$conn=newmysqli($servername,$username,$password,$dbname);
//Checkconnection
if($conn->connect_error)
{die("Connectionfailed:".$conn->connect_error);}
//==================================================
$sql="SELECTrecur,periodic,pd,payrec,duedate,datepaid,
[b]DATEDIFF(CURDATE(),duedate)ASdayslate[/b]
FROMtestblWHERErecur='Y'&&payrec='P'";
$result=$conn->query($sql);
if($result->num_rows>0)
{
//outputdataofeachrow
while($row=$result->fetch_assoc())//****3records*****
{
//***************************************************
var_dump($dayslate);//NULLNULLNULL
//***************************************************
if($dayslate>0)
{
if($dayslate>120)
{$pastdue="PASTDUE";}

if($periodic==1)
{$duedate=date('Y-m-d',strtotime('+4week'))."\n";}
if($periodic==6)
{$duedate=date('Y-m-d',strtotime('+25week'))."\n";}
$pd='P';$daylate=0;
//==================================================
$sql="UPDATEtestblSET
pd='$pd',
duedate='$duedate',
$datepaid='NOW()',
dayslate='$dayslate'
WHEREdayslate=0";
if($conn->query($sql)===TRUE)
{echo"Recordupdatedsuccessfully";}
else
{echo"Errorupdatingrecord:".$conn->error;}

$conn->close();
}
}
}
//header("refresh:3;url='http://localhost/invoice/autolist.php'");
?>