jeudi 30 avril 2015

Write Java Code to execute SQL Group By

We would typically write Oracle SQL to find max salary of every employee in each department if we had a table with EmpID, DeptID, Salary:

select EmpID,DeptID, rank over(partition by DeptID order by Salary) rnk
from Table
where rnk=1;


select EmpID
from Table1
where Salary =(Select max(Salary) from Table2 group by DeptID
               and Table2.DeptId = Table1.DeptId )

If the above table was a file instead, then how can we write custom Java code to implement the same behavior?

Index.php cannot access private files

I developed a php MVC framework from scratch and my index.php cannot access some files when I change the permissions. I use fillezilla and the only file permissions I can set are read, write and execute checkboxes for each group (owner, group and public). If I uncheck all the public ones then I get an error, but if I leave the public->execute box checked, index.php finds the files. I don't have public/private folder setting so is this setting ok or what should I do??

A java file processing assignment

I have to write a program that reads a file and basically categorize it in 3 separate categories. I am new to this and I do not know where to began. Any help with be appreciated. This is the question:

Write a program to process a file containing information about your music collection. Each song in your song library will have a name, artist, and length in seconds. Read this data into three arrays, two for strings (for title and artist) and one for integers (for length). Then perform the following processing.

Output the songs in a table
Determine and output the total length of all songs
Determine and output the longest song
Determine and output the shortest song
Output the song titles in alphabetical order  

I already have the file created and its formatted like:


212:Float On:Modest Mouse

259:Cherub Rock:Smashing Pumpkins

512:Won't Get Fooled Again:The Who

417:Teen Age Riot:Sonic Youth


These are the required methods we must use:

Arrays: sort

String: split

Integer: parseInt

Python read from file and show max and min total population

I'm working on this python code where I have to open up this file and read it so that it finds out the total population with the max and min from the years 1900 - 1990(Each state is on its own line, but the data are grouped so that only three decades of data are on each line complicating the task of extracting the data)I"m stuck I'd appreciate any help .. here is an example of how the finished code should look like

Enter census year 1900 to 1990: 1970
Min: (302853, 'Alaska')
Max: (19971069, 'Calfornia')

import sys

data = 0
##def total_population(pop_list):
##      check_year = int (input ("Enter a census year 1900 to 1990 (must end with 0) : "))
##      data = open ("urpop0090.txt","r")
##      temp_list = []
##      print ("check_year: ", (check_year))
##      #variables
##      max_pop = 0
##      min_pop = 1
##      tp = 0
##      temp_list = []
##      data = open ("urpop0090.txt","r")

def STATES(check_year):
      data = open("urpop0090.txt","r")
      check_year.remove("UNITED STATES")

def search(myFile, x, y):
    data = open("urpop0090.txt","r")

def check_year(year):
    if year >= 1900 and year <= 1990:
          if year % 10 == 0:
#X axis horizontally on x axis
        if year == 1990 or year == 1980 or year == 1970: #1st page
            x= 0
        elif year == 1960 or year == 1950 or year == 1940:#2nd page
            x = 52
        elif year == 1930 or year == 1920 or year == 1910:#3rd page
            x = 154
        elif year == 1900:
            x = 206
#Y axis going vertically by spaces
        if year == 1990 or year == 1960 or year == 1930 or year == 1900:#1st page
            y= 1
        elif year == 1980 or year == 1950 or year == 1920:#2nd page
            y = 7
        elif year == 1970 or year == 1940 or year == 1910:#3rd page
            y = 12
        #elif year == 1900:
              #y = 241

        return (x,y)

#population= total_population(data)
#Taking r's
data = open ("urpop0090.txt","r")
year = int (input ("Enter a census year 1900 to 1990 (must end with 0) : "))
x,y = check_year(year)

print("x:", x, "y:", y)

temp_list = []
#Second column on x axis
for new_line in data :
    if new_line[0:5]=="     " and new_line[6]!=" ":
#Removing r letters
    r_removed = new_line.replace(" r ", "   ")
    comma_removed = r_removed.replace(",","")
    split_line = comma_removed.split()

#Converting column to an int
        split_line[1] = int(split_line[1])
    except ValueError:
            split_line[2] = int(split_line[2])
            split_line[0] = split_line[0]+" "+split_line[1]

        except ValueError:

##               for max in data:
##                     print data
##                     max = 0
##                     for i in range(1,len(words)):
##                           if len(words[i] > len(words[max]:
##                                                 max = i
        if line_num>= x and line_num<= x+ 50:

#developing a column of data (adding +1 until 50)
        if line_num == 50:


year = 1990
coordinates = check_year(year)

# print(temp_list)

upload multiple files , enctype=“multipart/form-data”

I want to upload multiple files to the controller but its taking only one.

I am using multipart for file transfer. How to get the multiple files to the controller side. I am not able to access bytes and filename. Its throwing errors,

@RequestMapping(value = "/home/step38/uploadReport", method = RequestMethod.POST)
public ModelAndView uploadReport(                 
         @RequestParam(value = "fileName") List<MultipartFile> files,
         @RequestParam(value = "pLogId") String pLogId,
          HttpServletRequest request, HttpSession session) 
    int applicationNameId = 0;
   String fileName;
    String typeOption = "Raw Particle Data";
    for(MultipartFile file:files)      
     fileName = file.getOriginalFilename();

    logger.debug("step3.1 upload particle count -- Start");

    ModelAndView modelAndView = createModelAndView(ToogleStep.step38);
    setCurrentStep(session, modelAndView, ToogleStep.step38);
    String view = "redirect:/home/step38";

        User user = (User) session.getAttribute(Constants.USER_DB);
        Project current_project = (Project) session.getAttribute(Constants.PROJECT);
        Credential credential = (Credential) session.getAttribute(Constants.AUTH_USER);            
        boolean checkOK = true;        

        if (current_project != null && SystemUtils.projectEditable(current_project, credential)) 
            long projectId = current_project.getId();

               byte[] bytes = file.getBytes();      
                HashMap<String,String> options= new HashMap<String,String>();
               //added pLogId in the options(this will contain demoToogleFileInfoId)           
                String toogleFileId = reportService.uploadReport(user, projectId, fileName, typeOption, bytes, applicationNameId, options);


How do I make a photo upload form for users?

So i want people to go on my website, upload a picture and then the website saves it and waits to be published and it continues to the website where I want them (the user) to choose two other pictures already on the webiste. Once they check a box on both the two pictures, it will then submit it to their social media, their picture that they first tried to upload will NOW be published on the website. How should I go about this. I only know HTML and Java.Hardly anything at all. -------I am really trying to make the upload form that only allows pictures the size of your thumb and save it in the background. The window should hide and then they should be able to find two pictures, check them, post them, and tada! their upload has been published. but HELP ME WITH THE UPLOAD FORM THAT I MENTIONED. tHANK YOU!!!

how to use parameterized junit when input is from several files?

I used to use Parameterized junit.

I have two files with a long list in each of them.



I loaded the two big lists into memory and compared each line in a different test.

Unfortunately the list grew too big and I had a memory problem to parse to parse it to json before saving to file.

That's why I split each long list to smaller files. say




how can I still use the parameterized junit infra and syntax to compare each corresponding list items, when each list is distributed to few files?

I have tried:

    public void compareNewResponseToBaselineReturnsNoLargeDifferences() throws IOException {

        E2EResultShort baseLineList = routingResponseShortRepository.getBaseLine(chunkId);
        E2EResultShort freshRunList = routingResponseShortRepository.getLatestResponse(chunkId);

??? how do I iterate over differet `i` for each test ??

        List<String> testFailureMessages = alternativeShortTotalChecker.checkAllAlternativesShort(baseLine.get(i), freshRun.get(i));
        assertThat("testFailureMessages should be empty", String.join("", testFailureMessages), equalTo(""));
        assertThat("error messages should be null", freshRoutingResponse.regression_error, is(nullValue()));

How do I use strtok to take in words separated by white space into a char array in C?

I have opened a file as such:

#define MAX 1000000000
char buffer[MAX];

FILE *file = fopen("sample1.txt", "r");
char c;

if(file == NULL) {
    perror("File open error");
    return -1;

Now what I want to do is that use 'strtok' and take in seperate words from the file into the char array buffer.

how to read diffrent file formats from asset folder in android

i am working on a project using arcgis sdk for android.and i need to include diffrent file formats like .tpk .loc and a folder.there is method called RouteTask.createLocalRouteTask in my code which takes the path of a folder which holds around 6 diffrent files in it. RouteTask.createLocalRouteTask(Environment.getExternalStorageDirectory().getPath() + "/Download/Routing/gashu.geodatabase", "Navigator_ND"); Navigator_ND is a folder which needs to hold 6 diffrent files in it. i know ho to read and use simple formats like .txt from my asset folder but i dont how to read directories and use them in my code as i mentioned above.can any one help me

Python different operations on the same resources

I'm trying to analyze a large python file with different tasks on it. I've already read and preprocessed the file and it's now in memory. The thing is, the tasks I have, they pretty much have to go through the whole list of the records. It's something similar like:

resourceList = [..] #list of records from the file (say, 2GB)
def taskA():
    for i in resourceList:

def taskB():
    for i in resourceList:

If I do taskA() then taskB() it's going through the 2GB file twice and it's really slow. Is that a way that taskA and taskB can do their job simultaneously at the same time so that I don't have to go through the task twice?

I read about something which involved python threads and Queue, is that the only (and right) way to do it? If so, what if the "resourceList" is a generator instead of a list?


C# How To create GUI program

I was wondering if someone can give me an idea on how to start this? I need a step by step guide if possible?

using a GUI interface, Create a scrubbing program that has 2 methods (ScrubData, ReplaceData)

that takes in a file - allow the user to upload the file. Do a try catch to make sure they don't load the wrong file - I will ask you to load a random file to make sure you program does not load it.









generate random numbers for col 1 (ssn).

Extra credit store in array the random number and reuse

random number for multiple ssn's that match...any place where NICK FAVAZZA ssn is defined should be the same for the random number used throughout.

In col 3, generate random letters for the number of characters for the last name

in col 4, put replace numbers to 'X' for all but the last 4.

in col 5, check to see if the amount is greater than 100. create a new column at the end that says yes or no if the amount is greater than 100

and then recreate the file.

Real Data file “data.txt”

Scrubbed Data file “data_scrubbed.txt”

Please make sure to following correct naming conventions and put in comments that would help someone who knows nothing about the program to follow along. Also, since this is a GUI (Graphical User Interface), make it look appealing. Make sure to place the two methods I showed you in class as two separate methods (GetRandomLetter, GetRandomNumber).

Get last X files created from a directory (PHP)

Im using this code to get the most recent file created:


    $files = glob($siteRoot.'/dir/*/*.php');
    $files = array_combine($files, array_map('filectime', $files));
    echo key($files); 


How can I enhance this to get the last 3 files created, or what ever number I need? Any help would be appreciated. Thanks!

Error 502 Wistia video upload

I am trying to upload a video via Wistia's api and I am getting a 502.

public function send_video($file) {

    $data["file"]           = $file;
    $data["project_id"]     = "123";
    $data["api_password"]   = "123";

    return self::get_json_response($data);

public function get_json_response($data) {

    $headers["Content-Type"] = "multipart/form-data";

    $http_transport_util = new HTTP_TRANSPORT_UTIL();
    $has_success = $http_transport_util->post("",$data,$headers,"username","password");

    $http_response = $http_transport_util->get_http_response();

//Just prints the out the response which can be seen below p($http_response);

    $code = $http_transport_util->get_http_response()->get_code();


HTTP_RESPONSE Object ( [_code] => 502 [_header] => HTTP_HEADER Object ( [iterationStyle] => lowerCase [fields:protected] => Array ( [Content-Type] => multipart/form-data,text/html [Cache-Control] => no-cache [X-Served] => bakery-breadroute-naan )

        [camelCase:protected] => 
        [lowerCase:protected] => 

[_request_header] => HTTP_HEADER Object
        [iterationStyle] => lowerCase
        [fields:protected] => Array
                [0] => POST / HTTP/1.1
                [1] => Authorization: Basic 123
                [2] => Host:
                [3] => Accept: */*
                [4] => Content-Type:multipart/form-data
                [5] => Content-Length: 202
                [6] => 
                [7] => file=D%253A%252FProjects%252Fwhitefire%252Fdata%252Ftemp%252F54483cfd0b5403d8dba98e7bcbeeec02%252Fclipcanvas_14348_offline.mp4&project_id=3131231&api_password=1234

        [camelCase:protected] => 
        [lowerCase:protected] => 

[_cookies] => Array

[_body] => <html><body><h1>502 Bad Gateway</h1>

The server returned an invalid or incomplete response.

[_http_version] => 
[_path] => 
[_uri] => 


Cannot locate files created in C++ using Codeblocks

On building and running the code snippet below, I receive no errors, but at the same time, no file gets created. In fact, specifically no file of whatsoever extension is created (I have thoroughly checked My Computer, for the file)

Please explain. note: Necessary header files had been included.

Python finding file path

if os.path.exists('D:\Python\New folder\'+f):
    open(f+c, 'w')

The f is a character that changes in a loop. How do i add it to the rest of the 'D:\Python\New folder\' ? What i've done above makes the whole line highlighted as a comment.

Why does FileOutputStream corrupt my properties file?

I have encountered a weird problem while coding a class to read/write settings. I'm using a properties file. In a prepare()-method, I want to load the in-/output streams to the file. When I only load the input stream everything works fine, but once I try to load the output stream as well, something breaks. Whatever I try to read through a properties object, it gives back null. Even if I then get rid off the output stream again, and start the program only with the input stream, it still gives back null. If I then create a new properties file (copy/paste the content), it works again (without output stream).

My guess is, the output stream corrupts the file in some way (even though I have no clue how). I can still open the file in a text editor.

Here's the code:

File configFile = new File(SettingsProvider.class.getResource("/res/").toURI());
streamIn = new FileInputStream(configFile);
streamOut = new FileOutputStream(configFile);
props = new Properties();

A generic error occurred in GDI+ (screenshot SaveAsFile, ExternalException)

Hello I tried looking through questions that may have my answer but none of them did.

I am doing web automation testing and trying to take a screenshot of when an error occurs and save it to a file in another folder.

My program has a 30 second timeout when searching for elements on the page. If after 30 seconds no element is found, it takes a SS, reloads the page, and tries again.

The first screenshot works fine. But on the second run through, it tries to save another screenshot to the folder and I get this incredibly vague error that is seemingly caused by a hundred different things, so I'm not quite sure what the problem is.

Here's my code:

public void takeScreenShot()
        string ssPath = _persistencePath += "\\Errors";

        string currTime = DateTime.Now.ToString(@"");

        Screenshot ss = ((ITakesScreenshot)_driver).GetScreenshot();

            ss.SaveAsFile(ssPath + "\\ERROR-" + currTime + ".png", System.Drawing.Imaging.ImageFormat.Png);
            ssCount = 0;
        catch (System.Runtime.InteropServices.ExternalException)

            //error occurs here
            ss.SaveAsFile(ssPath + "\\ERROR-" + currTime + "(" + ssCount + ")" + ".png", System.Drawing.Imaging.ImageFormat.Png);

I initially thought the issue was that it was trying to save a file of the same name, because if the error happens during the same minute then the file name is the same. So that's why I added that catch block, in an attempt to change the name if it occurs in the same minute. But that didn't fix it.

Again I tried searching all over and couldn't find an answer. Any help is greatly appreciated.

If I have three different text file how do I read them then sort them by average?

Hi I am currently writing a code where you ask maths questions. I have saved the students score along with their name in different folders for 3 different classes. Then I have three different files for each test they have done. I want a code that checks if their name is in each file. Then when it checks if the name is in each file I would like to read all three scores from the persons results. Then sort the three scores by average and print it but for each person who has done the test three times.

Here is my code so far that asks the questions and then saves the names and scores to a file etc. :

import random

Name =input("What is your name?")
Class =input("What class are you in? (1/2/3)")
TimesDone = input("How many times have you done the test before(1-3)")

Score = 1
Questions = 1

while Questions < 10:
    Randomnumber1 = (random.randint(1,10))
    Randomnumber2 = (random.randint(1,10))

Operators = ['+','-','*']
Operators1 = random.choice(Operators)

print(Randomnumber1, Operators1, Randomnumber2)

if Operators1 == '+':
    answer = (Randomnumber1 + Randomnumber2)
elif Operators1 == '-':
    answer = (Randomnumber1 - Randomnumber2)
elif Operators1 == '*':
    answer = (Randomnumber1 - Randomnumber2)

UserGuess = int(input("What is the answer to the question?"))

if UserGuess == answer:
    print("Well done",Name,"you got the correct answer!")
    Questions = Questions+1
    Score = Score+1
    print("Wrong answer",Name,"the correct answer is",answer,".")
    Questions = Questions+1

if Questions == 10:
    print("You answered all 10 questions and your final score",Score,".")

if Class == '1':
    if TimesDone == '1':
        myfile = open('namesforclass1test1.txt','a')
        names = (Name)

        myfile = open('scoresforclass1test1.txt','a')
        scores = (Score)
    elif TimesDone == '2':
        myfile = open('namesforclass1test2.txt','a')
        names = (Name)

        myfile = open('scoresforclass1test2.txt','a')
        scores = (Score)
    elif TimesDone == '3':
        myfile = open('namesforclass1test3.txt','a')
        names = (Name)

        myfile = open('scoresforclass1test3.txt','a')
        scores = (Score)
elif Class == '2':
    if TimesDone == '1':
        myfile = open('namesforclass2test1.txt','a')
        names = (Name)

        myfile = open('scoresforclass2test1.txt','a')
        scores = (Score)
    elif TimesDone == '2':
        myfile = open('namesforclass2test2.txt','a')
        names = (Name)

        myfile = open('scoresforclass2test2.txt','a')
        scores = (Score)
    elif TimesDone == '3':
        myfile = open('namesforclass2test3.txt','a')
        names = (Name)

        myfile = open('scoresforclass2test3.txt','a')
        scores = (Score)
elif Class == '3':
    if TimesDone == '1':
        myfile = open('namesforclass3test1.txt','a')
        names = (Name)

        myfile = open('scoresforclass3test1.txt','a')
        scores = (Score)

    elif TimesDone == '2':
        myfile = open('namesforclass3test2.txt','a')
        names = (Name)

        myfile = open('scoresforclass3test2.txt','a')
        scores = (Score)
    elif TimesDone == '3':
        myfile = open('namesforclass3test3.txt','a')
        names = (Name)

        myfile = open('scoresforclass3test3.txt','a')
        scores = (Score)

Thanks, I would be very grateful if anyone could help me as I have tried many different ways and they didn't work. Sorry that the indents are off a bit but I couldn't manage to fix it

File access with C++ on WindowsPhone 8.1 Silverlight

My project use to be a WP8.1 WRT project -> C++ + Xmal,

Now I convert it into a WP8.1 Silverlight project - C# + Xmal + C++DLL.

Because I must use Silverlight and C++(openssl) at the same time.

This is how I access the file in the WP8.1 WRT project

For file in assets:

wchar_t pw_filedir[MAX_PATH];

wcscpy_s( pw_filedir, MAX_PATH, Windows::ApplicationModel::Package::Current->InstalledLocation->Path->Data() );
wcscat_s( pw_filedir, MAX_PATH, L"\\Assets\\FileName" );
// Then I can do file access with C style

For file in Isolate storage

wchar_t pw_filedir[MAX_PATH];
wcscpy_s( pw_filedir, MAX_PATH, Windows::Storage::ApplicationData::Current->LocalFolder->Path->Data() );
wcscat_s( pw_filedir, MAX_PATH, L"\\FileName" );
// Then I can do file access with C style

Now both of them no longer works on WP8.1 Silverlight.

Did any of you try to access file on WindowsPhone silverlight?

Here I mean:

Project - WP8.1 SL (C#)
Dll - WP8.1 SL native Dll (C++)

So I need to do a C++ file access in a native DLL in a WP8.1 SL C# project..

I'll appreciate a lot for the answers!

file reading difference on ruby and mac os due to different encoding

I have a file test.conf on mac . I downloaded it from web location as application/octet. When I check fro mime type using commandline I get

     file -Ib ~/test.conf 
     text/plain; charset=us-ascii

But in ruby irb, i see it as utf-8 irb(main):039:0> f ="test.conf") => # irb(main):040:0> f.external_encoding => # irb(main):041:0> contents = irb(main):042:0> contents.encoding => #

So when I try to open the file for reading one line at a time using File.foreach in Ruby , I get 52 lines, whereas

    cat ~/test.conf | wc -l

So my dilemma here is how to make sure ruby sees the same number of lines as cat command?


How to read files containing different formats/extensions?

I am very new to c++ and I wanted to write a program that would read and extract data from files with/of different format (example: .dat). I just want to read and extract the data from it. Some people say something about file headers, structures and bodies, what are they actually ?

How to display file data in an android app?

I am trying to do an android project.In that ,I have created a file named fie.txt..So i want the data(integers) stored in that file.I don't know how to retrieve and display that using android studio.Please help me...

Program will not let me store only the last three scores of the user

if class_number == 0:
    #This will create and open a new text file under the name
    #of the class_tag variable.
    file = open("Class 0" + ".txt", "a")
    #This will write down the user's name and their score
    file.write(str(name) + " scored " + str(score))
    #This will create a new line for each user
    #This will close the file.

import collections

def new3ElementDeque():
   return collections.deque([], 3)

nameTop3 = collections.defaultdict(new3ElementDeque)

with open("Class 0.txt") as f:
    for line in f:
        user, score = line.split(':')

I tried to get the program to only save the last three scores of the user rather than all the scores into a text file.

It looks like this now:

student scored 3
student scored 8
student scored 0
student scored 4
student scored 10
student scored 3
student scored 0
student scored 4

I want it to be like this:

student scored 3
student scored 0
student scored 4

However, the IDLE shell states:

    name, score = line.split(':')
ValueError: need more than 1 value to unpack

How would I get the program to store the last three scores of the user and save it to text file?

The name input is:

name = input("What is your name? ")

Render image with jinja2 and ndb BlobProperty

What is the simplest way to upload image and render it on another page using jinja2 and ndb. My includes:

class Student(ndb.Model):
    name = ndb.StringProperty()
    avatar = ndb.BlobProperty()

JINJA_ENVIRONMENT = jinja2.Environment(

My form in html file is:

<form method='post' action='/Student' enctype ='multipart/form-data'>
First Name <input type='text' name='firstName'/> </br>
Avatar <input type ='file' name ='avatar' /><br>
<input type='submit' value='Save'>

My post method for the form is:

def post(self):
    firstName = self.request.get('firstName')   
    student = Student()
    student.firstName = firstName
    avatar = self.request.get('avatar')
    avatar = images.resize(avatar, 32, 32)
    student.avatar = avatar 

My get method to get the information of the student is:

def get(self):            
    template = JINJA_ENVIRONMENT.get_template('student.html')
    students = Student.query().fetch()

    template_values = {'students': students}

In my html file I use:

{% for student in students %}
    {{ student.firstName }} - {{ student.avatar }} <br/>
{% endfor %}

There is no problem when I submit the form but I when I go to the html file which display the inf, it shows the error in the terminal: UnicodeDecodeError: 'ascii' codec can't decode byte 0x89 in position 0: ordinal not in range(128)

Please help!!

Python - not write to file

I am making a save option for a text-based survival and I cannot get the save to work right. This is the error I get:

IOError: File not open for reading

f = open('saves.txt','w')
file =
file = file.split("\n")
savefile = []
for line in file:
    temp = line.split("-")
    if name == temp[0]:
        savefile.append("%s-%s-%s-%s-%s-%s-%s-%s-%s-%s-%s-%s-%s" % (name,story,stats,place,health,accuracy,level,exp,cash,inventory,loadingSpeed,electricity,pistolUpgrade))
savefile = '\n'.join(savefile)
f.write(savefile) # python will convert \n to os.linesep
f.close() # you can omit in most cases as the destructor will call if

Bulk Insert CSV File Using Format File

I am trying to insert a CSV file into a SQL database using Bulk Insert and a Format File but I am having some trouble. I have been using the following tutorial.

When I run the script I get this error I think it has something to do with the format of the Format File.

Msg 4863, Level 16, State 1, Line 3
Bulk load data conversion error (truncation) for row 2, column 3 (Ref).
Msg 7399, Level 16, State 1, Line 3
The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error.
Msg 7330, Level 16, State 2, Line 3
Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)".

Table Format

[Id]       INT           NULL,
[Name]     NVARCHAR (50) NULL,
[Townland] NVARCHAR (100) NULL,
[Ref]      INT           NULL,
[Lat]      FLOAT (53)    NULL,
[Lng]      FLOAT (53)    NULL


use HOM
bulk insert HouseInfo
from 'c:\HOM\Houses_of_Mayo_02_02_2015.txt'
firstrow = 2,
fieldterminator = ',',
FORMATFILE = 'c:\HOM\Format_File.fmt'
select *
from HouseInfo

Format File

1   SQLINT      0   50  ","    2    Id          ""  
2   SQLNCHAR    0   50  ","    3    Name        ""
3   SQLNCHAR    0   100 ","    4    Townland    ""
4   SQLINT      0   50  ","    5    Ref         ""
5   SQLFLT8     0   53  ","    6    Lat         ""
6   SQLFLT8     0   53  "\n"   7    Lng         ""

CSV File

A1,Aasleagh Lodge,Srahatloe,1,53.613873,-9.668301
A2,Aasleagh Rectory,Srahatloe,2,53.612478,-9.668033
A3,Abbey Lodge,Carrowkeel (ED Croaghpatrick),3,53.785667,-9.638768
A4,Abbeytown House,Abbeytown,4,54.107701,-9.318194

Filename cannot be empty in

A few weeks ago I had this code to upload a file to my database , but now does not work

the input:

 <input type="file" name="archivo" accept=".doc, .pfd, .docx"/>

the .php to upload the file (the connection to the database is made)

 $archivo = $_FILES["archivo"]["tmp_name"]; 
 $tamanio = $_FILES["archivo"]["size"];
 $tama    = $_FILES["archivo"]["size"];
 $tipo    = $_FILES["archivo"]["type"];
 $nombre  = $_FILES["archivo"]["name"];
 $titulo  = $_POST["titulo"];

 if ( $archivo != "none" )
    $fp = fopen($archivo, "rb");
    $contenido = fread($fp, $tamanio);
    $contenido = addslashes($contenido);

    $qry = "INSERT INTO archivos VALUES 

    mysql_query($qry) or die('Consulta fallida: ' . mysql_error());

    if(mysql_affected_rows($link) > 0)
       print "Se ha guardado el archivo en la base de datos.";
       print "NO se ha podido guardar el archivo en la base de datos.";
    print "No se ha podido subir el archivo al servidor";

How to create a file and to give it name at the same time

I am having a problem with this C code. I am creating a file and I want to give it a name at the same time. But something is not working - it won´t create this file with the chosen name. The rest of the code works fine btw.

FILE *InputRef;                                            

char outputFilename[];                   // Creates a char
printf("Enter the name of your file");   // It asks for a name
outputFilename=getchar();   // And here I want to enter the file name

InputRef = fopen(outputFilename, "w"); // 

Boostrap bug? trying to reach 15 characters

This code works without bootstrap, but with bootstrap it displays the file input tag. Help

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="">

<!-- Latest compiled and minified JavaScript -->
<script src=""></script>
<input type="file" class="nodisplay">
<div class="nodisplay">lol</div>

Is 1MB = 1000000 bytes OR 1048576 considering file size

I have to place a 1MB size check on my files to be uploaded . Now in code (using c#) i have to mention the size in bytes . Should i check the size of upload file with the value MaxSizeInBytes = 1048576 OR MaxSizeInBytes = 1000000 .

split txt file line by line and create from each line a txt file

I need a batch script which splits a file with 4 lines and creates from those 4 lines 4 txt files.

Looks like this: test.txt

line 1
line 2
line 3
line 4

--> every line should be outputted in an other txt file.

Thanks guys, Anita

Download binary file over http with rails and support multiple threads?

I would like to download a binary file over HTTP and found a good question with several references and examples here

How do I download a binary file over HTTP?

The question is how to make this multi threaded? Im using PUMA as webserver so assuming it is already multi threaded but how to make this sure?

The method that would write the binary would accept 1 argument ("filename") and would store it that way. The method would be called from outside http://myapp/record_file/myfilename So multiple requests to this method could be made at the same time.

How would one handle performance issues in this case? Any tips suggestions advice on how to best approach this?

Simple Encryption and Decryption of a String using a Password in Java

I have the following problem: I have an application that needs some passwords for git and a db etc. I want to write all the passwords into a file, so the user doesn't have to enter all the passwords after starting the application. The user enters only a masterpassword and then all the other passwords can be decrypted and encrypted ( if he enters a new password ) with his masterpassword. The code should look like this:

String masterPassword = getMasterpassword()
String encryptedPassword = getPasswordFromFile("git")
String clearPassword = decryptPassword(encryptedPassword, masterPassword)
String masterPassword = getMasterpassword()
String clearPassword = getClearPassword("Please enter the password")
writeToFile("git",encryptPassword(clearPassword, masterPassword)

I don't need a incredibly secure encryption. It's important, that the encryption is not done randomly, because i have to decrypt the password after the restart of the application.

Btw. I'm using Scala. But an it doesn't matter if the explanation is for Java or Scala.

I realy hope you can help me! Thanks!

Read content of Registry.pol

I'm trying to read content of the following file C:\Windows\System32\GroupPolicy\User\Registry.pol in C# application.

Here is the snippet of code:

string content = File.ReadAllText(@"C:\Windows\System32\GroupPolicy\User\Registry.pol");

Despite this folder, this file exists and I run program from Administrator I always get exception of the following type System.IO.DirectoryNotFoundException.

Could you please suggest solution to read the content? Thanks

mercredi 29 avril 2015

Trying to display console art by using array with biggest value

My program is supposed to take user input of names and numerical values and then display it with console art (asterisks) It saves it all to a text file and can be reused.

We have to find the index of the biggest array element and then base our console art around that. For instance, if someone has 8000 sales, then they will have (at most possible) 50 asterisks in order to not flood the window. Then we have to evaluate the other array elements by using division (smaller element/bigger element and times that by 50)

We have a function that can find the index of the array with the biggest element so that's done. But we're having logic problems with the output of the display.

int main()

double sales[100];
string names[100];
string fileName = "";
string choice = "";
int indexOfLargest = 0;

cout << "Welcome to the sales Record Program!" << endl;

    if (choice == "1")
        indexOfLargest = findLargest(sales, fileName);
        enterInfo(fileName, names, sales);
    else if (choice == "2")
        indexOfLargest = findLargest(sales, fileName);
        displayInfo(fileName, indexOfLargest);
}while (choice != "x");
cout << "Goodbye!" << endl;

Now my code that finds the index number:

int findLargest(double sales[], string fileName) 

int sz = 0;
string names;
int indexOfLargest = 0;
ifstream fin(fileName.c_str());
if (fin)
    cout << "file opened" << endl;
    while (isalnum(fin.peek()))
        getline(fin, names);
        fin >> sales[sz];
        fin.ignore(5, '\n');
    cout << "The size is " << sz << endl;
    //size = 4
    if (sz == 0) return -1;  // no data means no highest index
    for (int i = 0; i < sz; i++)
        if (sales[i] > sales[indexOfLargest])
            indexOfLargest = i;
    cout << "Index: " << indexOfLargest;

return indexOfLargest;

And now the function that I am currently having problems with:

void displayInfo(string fileName, int indexOfLargest)

string names;
double sales = 0;
double bigSales = 0;
int counter = 0;
ifstream fin(fileName.c_str());
if (fin)
    cout << "file opened" << endl;
    while (isalnum(fin.peek()))
        getline(fin, names);
        fin >> sales;
        fin.ignore(5, '\n');

        if (counter == indexOfLargest)
            cout << setw(10) << left << names << setw(10) << left;
            for (int i = 1; i < 50; i++)
                cout << "first" << endl;
                cout << "*";
                sales = bigSales;
            cout << setw(10) << left << names << setw(10) << left;
            for (int i = 0; i < ((sales/bigSales) * 50); i++)
                cout << "second" << endl;
                cout << "*";


Other notes: We are using parallel arrays, text files, and whatever else I'll remember after I post this.

We know the problems with my logic on the last function but we don't know where to go. Say the first element in the array isn't the biggest one, then it will loops through the "else" forever because bigSales hasn't been changed from 0, so it will be an error * 50. I'm not sure if we should sort it (really not sure how to do it either) so we're looking for an alternative. (Yes, we know the last code is messy)

While loop runs once?

The split function does not work. for the last print statement, it gives me an arrayoutofbound error. Any help?

 while (inFile.hasNext())
               String clean = inFile.nextLine();
               String[] nm = clean.split(",");
               for (int i = 0; i < nm.length; i++)
                    System.out.println("at index "+ i +" string is "+nm[i]);
               System.out.print("at index"+2+"Strin"+nm[3]);

text file :


How to check line in file (php)

I'm new to php and wanted to make a simple php script to check a form of my html site.

To answer the questions: I have a file, that's the Name of the User and I want to check if the password that is in there (line 1) is the same as the one in the "password" field on my site. And when it's like this it should open a site.

Maybe a check if the file exists would be nice :D

This is my php-file, it's named "check.php":


    $f = fopen($_POST["name"], "r");

    $theData = fgets($f);

    if ($_POST["pw"] == $theData) {
        $ch = curl_init("");


This is my html-file:

<form action="check.php" method='post'>
    <b>Name: </b><input name="name" type="text" value="Name"> <br>
    <b>Password: </b><input name="pw" type="text" value="Passwort"> <br>
    <input type="submit" value="Check">
    <input type="reset" value="Reset">

I hope one can help me ^^ I've tried a lot of things now, nothing really worked.

Super basic C++ Error

I have this code...

#include <stdio.h>
#include <wiringPi.h>

#include <fstream>
#include <iostream>

int main ()

  wiringPiSetup ();

  char instructions[100];

  ifstream b_file ( "instructions.txt" );
  b_file>> instructions;
  cout<< instructions <<"\n";


As far as I understand it, this should compile to a program that outputs the contents of "instructions.txt" in the console...however, it won't even compile with g++ in Ubunutu...what's wrong?

Error messages tell:

"if_stream" wasn't declared in this scope
"b_ file" wasn't declared in this scope
"cout" wasn't declared in this scope.

How can I set file creation times in ZFS?

I've just got a NAS running ZFS and I'd like to preserve creation times when transferring files into it. Both linux/ext4 (where the data is now) and zfs store creation time or birth time. In the case of zfs it's even reported by the stat command. But I haven't been able to figure out how I can set the creation time of a file so it mirrors the creation time in the original file system. Unlike an ext4->ext4 transfer where I can feed debugfs a script to set the file creation times.

Is there a tool similar to debugfs for ZFS?

PS. To explain better:

  • I have a USB drive attached to a Ubuntu 14.04 laptop. It holds a file system where I care about the creation date (birth date) of the individual files. I consult these creation timestamps often using a script based on debugfs, which reports it as crtime.

  • I want to move the data to a NAS box running ZFS, but the methods I know (such as scp -p -r, rsync, tar/untar) preserve the modification time but not the creation time.

  • If I were moving to another ext4 file system I would say debugfs -w, to read a script with lines of the form

    set_inode_field filename crtime <value>

prepared with the help of find and stat. I've tested this and it works just fine. But my target filesystem is not ext4 but ZFS

  • When I try debugfson the target machine running ZFS, I can't figure out what argument (device name) debugfs will understand. For instance the output of zfs list gives the name of the newly created file system as tank/levy2. But when I say debugfs tank/levy2 I get "tank/levy2: No such file or directory while opening filesystem".

  • Another debug tool that lets you alter timestamps by editing an inode directly is fsdb; it too runs on the NAS box, but again I can't seem to get it to recognize a ZFS file system: fsdb -d tank/levy2 gives

    fsdb: cannot set up file system `tank/levy2'

  • I'm told by the folks who sold me the NAS box that debugfs and fsdb are not meant for ZFS filesystems, but they haven't been able to come up with an equivalent. So, after much googling and trying out things I finally decided to post a question here today, hoping someone might have the answer. The question of how to replicate a dataset so the timestamps are identical seems quite natural from an archival point of view.

What is the appropriate regular expression for this pattern?

I have a text file that contains a course catalog of all CS courses. The actual course itself is pretty simple to find because it is in the beginning of the line and begins with the course. The prerequisite is a bit trickier for me though. I can find the line that has the prerequisites but the prereq courses can be one or multiple and separated by commas and "and". There is also sometimes a line after the prereq sentence that contains other course names but not the prereq itself. Here is a sample of what the prereq file looks like:

CS 4213. Computing for Bioinformatics. (3-0) 3 Credit Hours.
Prerequisite: CS 1173 or another programming course. Emphasizes computing tasks common in bioinformatics: variables, flow control, input/output, strings, pattern matching, arrays, hash tables, functions, access to databases, and parsing data from queries for common bioinformatics tasks. SQL, XML, and BioPerl. May not be applied to the 24 hours of required electives for computer science majors, but may be included for a computer science minor.
CS 4313. Automata, Computability, and Formal Languages. (3-0) 3 Credit Hours.
Prerequisites: CS 3341 and CS 3343. Discussion of abstract machines (finite state automata, pushdown automata, and Turing machines), formal grammars (regular, context-free, and type 0), and the relationship among them.
CS 4353. Unix and Network Security. (3-0) 3 Credit Hours.
Prerequisite: CS 3433. A technical survey of the fundamentals of computer and information security. Issues include cryptography, authentication, attack techniques at both the OS and network level, defense techniques, intrusion detection, scan techniques and detection, forensics, denial of service techniques and defenses, libpcap, libdnet and libnet programming.
CS 4363. Cryptography. (3-0) 3 Credit Hours.
Prerequisites: CS 3341, CS 3343, and CS 3433. A course in pure and applied cryptography, with emphasis on theory. Topics may include conventional and public-key cryptosystems, signatures, pseudo-random sequences, hash functions, key management, and threshold schemes.
CS 4383. Computer Graphics. (3-0) 3 Credit Hours.
Prerequisites: CS 2121, CS 2123, CS 3341, and CS 3343. An introduction to two- and three-dimensional generative computer graphics. Display devices, data structures, mathematical transformations, and algorithms used in picture generation, manipulation, and display.
CS 4393. User Interfaces. (3-0) 3 Credit Hours.
Prerequisite: CS 3443. Study of advanced user interface issues. User interface design, human factors, usability, GUI programming models, and the psychological aspects of human-computer interaction.
CS 4413. Web Technologies. (3-0) 3 Credit Hours.
Prerequisites: CS 3421 and CS 3423. Fundamentals of Web and component technology: markup languages, layout design, client and server side programming, database and Web integration.
CS 4593. Topics in Computer Science. (3-0) 3 Credit Hours.
Prerequisite: Consent of instructor. Advanced topics in an area of computer science. May be repeated for credit when topics vary.
CS 4633. Simulation. (3-0) 3 Credit Hours.
Prerequisites: CS 3341 and CS 3343. Design, execution, and analysis of simulation models, discrete event simulation techniques, input and output analysis, random numbers, and simulation tools and languages.
CS 4713. Compiler Construction. (3-0) 3 Credit Hours.
Prerequisites: CS 3341, CS 3343, CS 3841, and CS 3843. An introduction to implementation of translators. Topics include formal grammars, scanners, parsing techniques, syntax-directed translation, symbol table management, code generation, and code optimization. (Formerly titled “Compiler Writing.”).

This is what I have right now:

Pattern p = Pattern.compile("^(CS [0-9][0-9][0-9][0-9]).*");
        Pattern p2 = Pattern.compile("^Prereq.* ([A-Z]* [0-9][0-9][0-9][0-9]).*");
        while ((line = br.readLine()) != null) {
            Matcher m = p.matcher(line);
            if (m.find()) {
            Matcher m2 = p2.matcher(line); 
            if (m2.find()){

                System.out.println("Prereq: "", Occurrences: "+m2.groupCount());

And so far this gets all the courses and the first prerequisite or none if there are no prereqs for the course.

New file creation

Ok so my professor threw a curve at us, something we didn't learn before. He said it would be hard but i don't know where to start.

here is the question:

Write a program that creates a new text file called "wikipediaEntries.txt" that contains the full Wikipedia URL for Representatives that have a non-blank value in the "wikipedia_id" field. The new file should contain the name of the representatives followed by a dash and then the representative's Wikipedia page.

Also her is the link to the .txt file (sorry i don't know how to put it another way):

How do i do this?

Django 1.8 static files doesnt work

Im using the 1.8 version of Django and my CSS, JS or images are not working, i really dont know why, my project folder is like


My settings:

    DEBUG = True


# Application definition



ROOT_URLCONF = 'jetint.urls'

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['jetint/templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [

WSGI_APPLICATION = 'jetint.wsgi.application'

# Database

    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'bd',
        'USER': 'bd',
        'PASSWORD': 'xxxx',
        'HOST': '',
        'PORT': '',
        'ATOMIC_REQUESTS': True

TEMPLATE_DIRS = (BASE_DIR, 'jetint/templates')

# Internationalization



USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)

STATIC_URL = '/static/'
    os.path.join(BASE_DIR, '/static/'),


and my base.html

<!DOCTYPE html>
<html lang="en">
<title> - {% block title-section%}{% endblock %}</title>
<meta charset="utf-8">
<meta name = "format-detection" content = "telephone=no" />
{# <link rel="icon" href="{{ STATIC_URL }}images/favicon.ico"> #}
{# <link rel="shortcut icon" href="{{ STATIC_URL }}images/favicon.ico" /> #}
{% load staticfiles %}
<link rel="stylesheet" href="{{ STATIC_URL }}css/camera.css">
<link rel="stylesheet" href="{{ STATIC_URL }}css/stuck.css">
<link rel="stylesheet" href="{{ STATIC_URL }}css/style.css">

but nothing works, css, js files, or images. please help?

How to run different compilers when read the different file in C++?

In C++ code, how to run different compilers when read a different file, like this example:

Getting the right compiler and getting it to run

• If there are .cpp and/or .hpp, .h files --to run C++ compiler

• If there are only .c and .h files --to run C compiler

• If there are .java files -- to run java compiler

Compare two text files in Perl

I have several strings in two .txt file. Both of them contain some similar strings but are not arranged on the same line number.

For example, file1.txt Carmen Edison Molly Jason Damon Gerard

file2.txt Edison Jason

I want to save the similar strings that found in both text files (in this case: Edison Jason) to an array.

Reading a file in Javascript in Node

I'm simply trying to read a text file in Node. I'm not in the DOM.

I can write to a file with this package but I'm having trouble reading from it .

I know i neead the following:

var fs = require('fs');

var readStream = fs.createReadStream('my_file.txt');

But the readStream is a complex object. I just want the variable as a string. Any ideas?

Copying multiple files into same directory while changing filename

I need to copy a series of files that look like

into the same director, but change the foo to moo.

But I'm not sure how I can copy and rename multiple files in one command. Something along the lines of

cp 'foo.*' . | ren foo.* moo.*

Except that doesn't make syntatic sense.

HG Delete Server side package files etc

I didnt add .ignore to my folder and uploaded 600 files to the Kiln/Mercurial server. I have read the boards and cant find a way to delete those files and start over.
can anyone help.

Load and update a locally JSON file by input text

I'm working on a project with a little CMS system where data gets loaded from a extern JSON file.

This data loads in perfectly, but then I'm trying to update the JSON with HTML input fields (like changing a title and stuff)

A little preview of the JSON File:

"paths": [{
    "path": [{

This is the code that I have for the loading in:

$string = "file.json";
$jsonString = file_get_contents($string);
$data = json_decode($jsonString, true);
$paths = $data["paths"];

And then there are some input fields like this:

<input type="text" name="title" value="Update the title" />

So I just want to update some textfields and overwrite the JSON titles for example. Hope someone can help me.

PS: I know that SQL maybe was a better solution, but I received this from the client.

Problems With files

I am looking for a program that will search a file for all names from a state(NY,PA,etc) and by their county number (1,2,3.etc). this needs to be user inputted also def main(): legislatorsTxtFile= open("legislators-all.txt","r") stateName= input("enter a state abv.") districtNum= input("enter district Number") R1= legislatorsTxtFile.readline() # while loop #

R2= R1.split(",")
if stateName in legislatorsTxtFile:


this is all i have so far im a bit lost atm.

Python - How to make sure that a line being read from a file contain only a given string and nothing else

In order to make sure I start and stop reading a text file exactly where I want to, I am providing 'start1'<->'end1', 'start2'<->'end2' as tags in between the text file and providing that to my python script. In my script I read it as:

start_end = ['start1','end1']
line_num = []
        with open(file_path) as fp1:
            for num, line in enumerate(fp1, 1):
                for i in start_end:
                    if i in line:
        print '\nLine number: ', line_num
        fp2 = open(file_path)
        for k, line2 in enumerate(fp2): 
            for x in range(line_num[0], line_num[1] - 1):
                if k == x:

This works well until I reach start10 <-> end10 and further. Eg. it checks if I have "start2" in the line and also reads the text that has "start21" and similarly for end tag as well. so providing "start1, end1" as input also reads "start10, end10". If I replace the line:

if i in line:


if i == line:

it throws an error.

How can I make sure that the script reads the line that contains ONLY "start1" and not "start10"?

SWI-Prolog file Input/Output

I am having trouble with file input/output in SWI-Prolog.

The basic idea is I need to ask the user to input a file that contains three fields (ID, Name, Grade). I need to input that text into a list. Here is my input implementation:

load_file :-
   write('Enter name of file to load: '), read(File),

All of the information they provide in their text file should go into my "Roster" list. The add_student function I have implemented works well, do I need to parse that file and call my add_student function to add each list of information to my Roster list?

As for Output, I'm having slightly better luck. The only problem is the resulting text file I get has erroneous results. Here is my store_file implementation:

store_file :-
    write('Enter name of file to save as: '), read(File),

I was under the impression that write(Roster) would write out the entire List of lists (Roster) without me needing to iterate through every list of information (ID, Name, Grade). Any help would be much appreciated, thank you!

Disable Cache/Buffer on Specific File (Linux)

I am currently working in a Yocto Linux build and am trying to interface with a hardware block on an FPGA. This block is imitating an SD card with a FAT16 file system on it; containing a single file (cam.raw). This file represents the shared memory space between the FPGA and the linux system. As such, I want to be able to write data from the linux system to this memory and get back any changes the FPGA might make (Currently, the FPGA simply takes part of the data from the memory space and adds 6 to the LSB of a 32-bit word, like I write 0x40302010 and should get back 0x40302016 if I read back the data). However, due to some caching somewhere, while I can write the data to the FPGA, I cannot immediately get back the result.

I am currently doing something like this (using python because its easy):

% mount /dev/mmcblk1 /memstick
% python
>> import mmap
>> import os
>> f ="/memstick/cam.raw", os.O_RDWR | os.O_DIRECT)
>> m = mmap.mmap(f, 0)
>> for i in xrange(1024):
...  m[i] = chr(i % 256)
>> m.flush() # Make sure data goes from linux to FPGA
>> hex(ord(m[0])) # Should be 0x6

I can confirm with dd that the data is changed (though I frequently run into buffering issues with that too) and using the tools for the FPGA (SignalTap/ChipScope) that I am indeed getting correct answer (ie, the first 32-bit word in this case is 0x03020106). However, someone, whether its python or linux or both are buffering the file and not reading from the "SD card" (FPGA) again and storing the file data in memory. I need to shut this completely off so all reads result in reads from the FPGA; but Im not sure where the buffering is taking place or how to do that.

Any insight would be appreciated! (Note, I can use mmap.flush() to take any data I write from python to dump it to the FPGA, but I need like a reverse flush or something to have it reread the file data into the mmap!)


As suggested in the comments, the mmap approach might not be the best one to implement what I need. However, I have now tried both in python and C, but using basic I/O functions ( in python, read/write in C) using the O_DIRECT flag. For most of these operations, I end up getting errno 22. Still looking into this....

Getting garbage values when accessing values in array read from binary file

void RecordFile::load(ifstream& file){
    size_t n = 0;<char*>(&weeks), sizeof(weeks));<char*>(&n), sizeof(int));
    char buffer[256];<char*>(&buffer), n);
    buffer[n] = '\0';
    studentName = buffer;

        delete quiz;
    quiz = new double[weeks];
        delete assignment;

    assignment = new double[weeks];<char*>(quiz), sizeof(quiz));<char*>(assignment), sizeof(assignment));

    cout << "Failed to load file" << endl;


void RecordFile::store(ofstream& file){
    size_t n = studentName.length();
    file.write(reinterpret_cast<char*>(&weeks), sizeof(weeks));
    file.write(reinterpret_cast<char*>(&n), sizeof(n) );
    file.write(, n);

    file.write(reinterpret_cast<char*>(quiz), sizeof(quiz));
    file.write(reinterpret_cast<char*>(assignment), sizeof(assignment));

    cout << "Failed to load file" << endl;


The code reads everything but the quiz and assignment arrays perfectly. Which is a surprise to me because this is the first time I've ever tried i/o with binary files. But anyways, I'm pretty certain the values I get when I Try to output the values in the array are garbage values (6.somethinge+66).

EDIT: I'm able to access the variable by storing and reading the arrays using a for loop, which is fine, but I'd like to know if there's a way to read the entire array at one time. I'm pretty sure this has little to no impact on file size, but just for the sake of simplifying my code (and learning more) I'd like to know a better alternative.

Using Resource Files in a Release Build - Files don't seem to be recognized

I built a piece of software that ultimately parses text files and writes HTML documents with the information contained in said text files. The program works as expected in debug mode, but the release build doesn't seem to be able to read the files correctly.

The program contains a configuration file of sorts, and one of the values within it is a Boolean value that tells the system whether or not the user needs to set these config options. If they do not need to configure the system, the menu to do so is not presented; however, every time I run the release executable, it goes into that menu, and the config file is emptied (This I attribute to the fact that he is trying to write the new configuration settings to the file, but the point is that he shouldn't be getting here because the file held the value telling him to skip this process).

I've found that the system will read the file in fine, but only if you refresh the current explorer window before running the executable, and even then, this only works once. After that, the issue resurfaces.

I wondered initially if it was an issue with the location of the resource files to the executable and where they were placed during debugging, but I don't think that's the case since the release build is capable of loading the correct values at least once. I'm kind of at a loss for which direction to go in, I feel like it's a path or other build setting that is wrong, but I am not familiar with configuring those settings in visual studio 2013.

I am using std::ifstream and std::ofstream to read and write files, and assert that it's good() before proceeding in the code. All streams are closed at the end. I have posted code related to the part of the system dealing with the reading/writing of the config file below.


 Initialization_Package Initialize(){
    //Declare Lexical Variables
    Initialization_Package toReturn;
    ofstream out;"Control_SetupProfile.txt");

    cout << "Initializing. . ." << endl;
    cout << "We need some information..." << endl;

    cout << "How many rooms does your conference center have?" << endl;
    cout << "-->3 (System currently only supports 3 rooms)" << endl;
    toReturn.numOfRooms = 3;

    cout << "How many pairs of speakers do you stock? (Remember to exclude a few for"
        << "\nbackups): " << endl;
    cout << "-->";
    cin >> toReturn.speakersAvailable;

    cout << "How many white boards do you stock? (Remember to exclude a few for backups):"
        << endl;
    cout << "-->";
    cin >> toReturn.whiteBoardAvailable;

    cout << "How many microphones do you stock? (Remember to exclude a few for backups):"
        << endl;
    cout << "-->";
    cin >> toReturn.micsAvailable;

    cout << "How many projectors do you stock? (Remember to exclude a few for backups):" << endl;
    cout << "-->";
    cin >> toReturn.projectorAvailable;

    cout << "How many people fit into the smallest room?" << endl;
    cout << "-->";
    cin >> toReturn.seatsInRoosevelt;

    cout << "How many people fit into the medium sized room?" << endl;
    cout << "-->";
    cin >> toReturn.seatsInLincoln;

    cout << "How many people fit into the largest room?" << endl;
    cout << "-->";
    cin >> toReturn.seatsInWashington;

    cout << "Finishing..." << endl;
    if (out.is_open()){
        //Write the data
        out << toReturn.numOfRooms << endl;
        out << toReturn.speakersAvailable << endl;
        out << toReturn.whiteBoardAvailable << endl;
        out << toReturn.micsAvailable << endl;
        out << toReturn.projectorAvailable << endl;
        out << toReturn.seatsInRoosevelt << endl;
        out << toReturn.seatsInLincoln << endl;
        out << toReturn.seatsInWashington << endl;
        out << "true" << endl;
        //Append the MISC details of the database
        out << "#END FORMATTED DATA" << endl;
        out << "* | ===================================================================================== | *" << endl;
        out << "* | Database: Record                                                                      | *" << endl;
        out << "* | DBA :                                                               | *" << endl;
        out << "* | Infrastructure Last Updated: 4/5/15                                                   | *" << endl;
        out << "* | Table: Control_SetupProfile                                                           | *" << endl;
        out << "* | ===================================================================================== | *" << endl;
        out << "int" << endl;
        out << "int" << endl;
        out << "int" << endl;
        out << "int" << endl;
        out << "int" << endl;
        out << "int" << endl;
        out << "int" << endl;
        out << "int" << endl;
        out << "bool" << endl;
        out << "\n*********************************************************************************************" << endl;
        out << "#Reset values(Requires initial setup again):" << endl;
        out << "0" << endl;
        out << "0" << endl;
        out << "0" << endl;
        out << "0" << endl;
        out << "0" << endl;
        out << "0" << endl;
        out << "0" << endl;
        out << "0" << endl;
        out << "0" << endl;
        out << "0";

        cout << "Fatal error writing to database! - (Local Profile)\n";

    return toReturn;


void loadControl(bool& init, Initialization_Package& prev){
    //Declare Lexical Variables
    ifstream in;"Control_SetupProfile.txt");

    if (in.is_open()){
        //Scan in the data
        in >> prev.numOfRooms;
        in >> prev.speakersAvailable;
        in >> prev.whiteBoardAvailable;
        in >> prev.micsAvailable;
        in >> prev.projectorAvailable;
        in >> prev.seatsInRoosevelt;
        in >> prev.seatsInLincoln;
        in >> prev.seatsInWashington;
        in >> init;

        cout << "Fatal error connecting to database! - (Local Profile)\n";

The debug executable is located in C:\Users\Jake\documents\visual studio 2013\Projects\UCCS\Debug\UCCS.exe and it is reading and writing from/to C:\Users\Jake\Documents\Visual Studio 2013\Projects\UCCS\UCCS (Probably because they are resource files) and I tried placing the build release in the same folder as the debug release, but he is still just creating (and I'm assuming reading) the files in the local (current) directory. Can any one hint at what might be happening?

Edit: I've never had this issue before; however, this is the first time I've ever added the files to Visual Studio, I typically just run the debug executable manually after building it with VS keeping the files in the debug directory.

how to use parameterized junit when input is from several files?

I used to use Parameterized junit.

I have two files with a long list in each of them.



I loaded the two big lists into memory and compared each line in a different test.

Unfortunately the list grew too big and I had a memory problem to parse to parse it to json before saving to file.

That's why I split each long list to smaller files. say




how can I still use the parameterized junit infra and syntax to compare each corresponding list items, when each list is distributed to few files?

I have tried:

    public void compareNewResponseToBaselineReturnsNoLargeDifferences() throws IOException {

        E2EResultShort baseLineList = routingResponseShortRepository.getBaseLine(chunkId);
        E2EResultShort freshRunList = routingResponseShortRepository.getLatestResponse(chunkId);

??? how do I iterate over differet `i` for each test ??

        List<String> testFailureMessages = alternativeShortTotalChecker.checkAllAlternativesShort(baseLine.get(i), freshRun.get(i));
        assertThat("testFailureMessages should be empty", String.join("", testFailureMessages), equalTo(""));
        assertThat("error messages should be null", freshRoutingResponse.regression_error, is(nullValue()));

Python capture command send to unix, capture output and write to file

Rookie looking for help on the code urgently

import subprocess 
cmd = 'ifconfig -a'

p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)

while True:
    out =
    if out == '' and p.poll() != None:
    if out != '':
        file = open('outputFile.txt', 'w+')

How to create a new file in libgdx?

I am trying to create a new file into my game ( for saving purporses ) using Libgdx. I have no idea how to do this and all tutorials seem to write / read but not create the files.

try {

        //File file = new File("LnRSave.txt");
        FileHandle file = Gdx.files.local("LnRSave.txt");
        // if file doesnt exists, then create it
        if (!file.exists()) {


        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);


    } catch (IOException e) {

Would tail block appending to file in linux kernel?

We have two processes:

  1. Append to the log file
  2. Tail the log file and send it to the centralised monitor

My concern is if the process 2 would block process 1 during reading the file? Is there any lock contention in kernel/disk driver here?

Finding Duplicates in Array and printing them only Once

I am trying to loop through my array and find all the numbers that are repeating more than once:

E.G: if there is 1 1 2 3 4

It should print saying "1 repeats more than once"

Here is my code and so far what I have tried, however it prints all duplicates and keep going, if there is 4 4 4 4 3 6 5 6 9, it will print all the 4's but i dont want that:

class average {

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

    int numOfLines = 0;
    int sum = 0, mean = 0, median = 0, lq = 0, uq = 0;
    int[] buffer;

    File myFile = new File("num.txt");
    Scanner Scan = new Scanner(myFile);

    while(Scan.hasNextLine()) {
    Scan = new Scanner(myFile);

    System.out.println("Number Of Lines: " + numOfLines);

    buffer = new int[numOfLines];

    for(int i=0; i<numOfLines; i++) {
        buffer[i] = Scan.nextInt();
    Scan = new Scanner(myFile);

    for(int i=0; i<buffer.length; i++) {
        sum = sum+i;
        mean = sum/numOfLines;
    System.out.println("Sum: " + sum);
    System.out.println("Mean: " + mean);

    for(int i=0; i<buffer.length; i++) {
        for(int k=i+1; k<buffer.length; k++) {
            if(buffer[k] == buffer[i]) {

How to read a large file of Strings in chunks, each time from different offset, in Java?

I have a large file that consists of several lines, where each line is actually one word of English. The complete file does not fit in memory. As such, I want to process it chunk by chunk. So, I need to implement something like this:

  1. Method1 : Read one chunk, call Method 2.
  2. Method2: Do some processing on the strings in that chunk and go back Step 1.

I have two questions.

1. How can one implement Method1? I know very well how to implement Method2.

I know how to use BufferedReader to read a large file line-by-line. e.g.,

BufferedReader br = new BufferedReader(new FileReader(file)) {
    String line;
    while ((line = br.readLine()) != null) {
       // process the line.

But I would like to read more lines instead of one line, and process all of them in Method2. Then, when I am back to Method1, I want to load several lines once again...

2. My assumption is that it is more efficient (performance wise), to process a chunk of lines rather than process each line. Is this assumption correct?

runtime Error in c++ VS

I have a code for saving file and it works in code blocks but in VS it gives me a run time error. Here is my code:

using namespace std;
int main()
    struct st
        int a;
        int b;
    st temp;
    FILE *f;f=fopen("c:\\data1.dat","w");

    while (1)
        cout << "enter a and b";
        cin >> temp.a;
        cin >> temp.b;
        fwrite(&temp, sizeof(st), 1, f);
        if (temp.a == 0)break;
    f = fopen("c:\\data1.dat", "r");
    st temp2;
    while (fread(&temp2, sizeof(st), 1, f))
        cout << temp2.a << endl;
        cout << temp2.b << endl;

Does anybody know what is the problem? Thanks

remove parentheses from output in spark

I'm using saveAsTextFile(path) in order to save output as text file in later to import the result to DB. The output looks something like this: (value1,value2) how can I remove the parentheses??

Registering a File System in Apache Drill

I'm trying to register a file system in Apache drill but it doesn't work.

I tried these steps:

  1. Navigate to http://localhost:8047, and select the Storage tab.
  2. In the New Storage Plugin window, enter a unique name and then click Create.
  3. In the Configuration window, provide the following configuration information for the type of file system that you are configuring as a data source.a.

I entered:

{  "type": "file",  
      "enabled": true,  
      "connection": "file:///",  
      "workspaces": {    
       "root": {      
        "location": "/root/data/json",      
        "writable": false,      
        "storageformat": null    
       "formats" : {      
          "json" : {         
            "type" : "json"      

  1. update.

every time when I press the button my code is deleted, Result: null

There is a instance created but without content.

Any ideas?

Thanks! Siar

NoneType Buffer interface error in windows 8

I am making a text editor, so you can imagine that there is a lot of manipulating text files. When I double click on the .py file to run it in python.exe in windows, it throws an error of 'NoneType does not support the Buffer interface'

Here is the code:

from tkinter import *
from tkinter.filedialog import *
from tkinter.messagebox import *
import os



def newfile():

    def create_file(entry):
        global current
        global root
        nonlocal create_in
        nonlocal name_it
        current = open(entry.get(),'w')
        root.title(create_in+'/'' - Aspus')

    if create_in!='':
        global root
        name_it.title("Name the File?")
        prompt=Label(name_it, text="Enter name for new file:")
        entry.insert(0, "Untitled.txt")
        create=Button(name_it, text="Create", command = lambda: create_file(entry))
        create.grid(row=1, column=3)

def openfile(master):
    global current
    global backup
    file=open(opening, 'r')
    file=open(opening, 'w')
    master.title(' - Aspus')
    return insert

def savefile(entry):
    global current
    if current!=None:
        current.write(entry.get('1.0', END))

    elif current==None:
        current.write(entry.get('1.0', END))

def ask_save():
    global root
    global current
    global main
    if current!=None:
        save_exit=askyesnocancel("Save Before Exit?", "Do you want to save before exiting?")
        if save_exit==True:
            current=open(a, 'w')
        elif save_exit==False:
            current=open(a, 'w')
    elif current==None:
        if main.get('0.1', END).strip()!='':
            save_exit=askyesnocancel("Save Before Exit?", "Do you want to save before exiting?")
            if save_exit==True:
            elif save_exit==False:

def setpgwidth():

    def adjust(entry):
        global main
            showerror("Invalid width", "You entered an invalid width. Expected an integer.")
            entry.delete(0, END)
            main.pack(expand=Y, fill=Y, side=LEFT)

    width.title("Set Page Width")
    prompt=Label(width, text="Enter new page width:")
    prompt.grid(row=0, column=0, columnspan=2)
    new.grid(row=1, column=0)
    submit=Button(width, text="Submit", command=lambda: adjust(new))
    submit.grid(row=1, column=1)

root.title("Aspus Text Editor")

#create main text widget
main=Text(root, wrap=WORD)
main.pack(expand=True, fill=BOTH, side=LEFT)

#create scrollbar
scroll.pack(side=RIGHT, fill=Y)

#configure scrollbar

#Creating menus
menu.add_command(label="New File", command=newfile)
menu.add_command(label="Open File", command=lambda: main.insert(END, openfile(root)))
menu.add_command(label="Save File", command=lambda: savefile(main))
menu.add_cascade(label="Format", menu=formatmenu)
formatmenu.add_command(label="Set Page Width", command=setpgwidth)
menu.add_command(label="Quit", command=ask_save)
root.protocol("WM_DELETE_WINDOW", ask_save)


Does anyone know why this is happening and how to avoid it?

System.IO.IOException: The process cannot access the file '.txt' because it is being used by another process

I am using the next code to log errors of an web application.

using (StreamWriter myStream = new StreamWriter(sLogFilePath, true))
myStream.WriteLine(string.Format("{0, -45}{1, -25}{2, -10 {3}", guid, DateTime.Now, StringEnum.GetStringValue(enumMsg), sText));      


Sometimes, the following exception 'System.IO.IOException: The process cannot access the file '.txt' because it is being used by another process.' is thrown.

I think this is caused by multiple instances of the web app at the same time. Can you help me fix this problem, please ?

EDIT: I have to add that for every method I log like this:

Date - Method X started.

Date - Exception.Message (table not found or other errors)

Date - Method X stopped.

and when this Error appears, it's logged only this:

Date - System.IO.IOException: The process cannot access the file '.txt' because it is being used by another process.

Python: send file to a server without third-party libraries?

I have a Python client behind a NAT and a python server with a public IP address. My job is to send a pcap file (the size of a few MB) from the client to a server, as well as a dictionary with some data.

Is there any easy way of doing this without resorting to third-party libraries (e.g. twisted, tornado)? If not, what's the easiest alternative?

I thought I could send the pcap file through http so that it would be easier to read it on the server side, and perhaps I could do the same with the dictionary by first pickling it. Would it be a good solution?

(I have complete control on the server, where I can install whatever)

Read from file line by line and parse to vector a lot of ints in c++

I have seen a lot of similar posts regarding very similar cases but my case is a bit different. I'm a newbie to c++, so any help would be appreciated.

I have a large file full of lines full of integers. Each number is separated by blank spaces. I need diferent lines to stay seperate, i don't want to read all the file on one go. I want to read line by line and parse each line in to a vector of integers. The code I've got is this:

int main () {
  string line;
  ifstream myfile; ("numbers.txt");
  vector<int> vec1;
  int const2=0;
  int a;
  while ( getline (myfile,line) ){ // I understand that this reads line 
                                   // by line and stores the string to "line"
    while (line >> a){  // this part is the one i can't get right, i 
                        // want to push_back every int from
                        // the string to vec1 but doesn't work
      // More stuff
    // more stuff
  return 0;

Magento: remove tags from the header logo image - "Need file path"

What I'm attempting to do is to remove some <p> tags that wrap the header logo image which does not contain any text because I think they should not be there.

But this is throwing the following error when testing via the W3-validator.

Line 261, Column 216: Element p not allowed as child of element a in this context. (Suppressing further errors from this subtree.)

What file should I look in to locate line 261

I'm stuck. I've searched for hours and can't find the file-path to the file that contains the string I need to edit. I currently don't have access to link hints function so that out of the question.

Any suggestions would be highly appreciated.

Thanks a million Fish

Update: Code from header.phtml file regarding logo..

Here is some code regarding the logo from the header.phtml    <div class="header-wrapper <?php echo $hdr_style?>">
        <?php if ( $config['design']['below_logo'] ) : ?>
        <div class="row clearfix">
            <div class="grid_12">
                <?php if ($this->getIsHomePage()):?>
                <h1 class="logo"><strong><?php echo $this->getLogoAlt() ?></strong><a href="<?php echo $this->getUrl('') ?>" title="<?php echo $this->getLogoAlt() ?>" class="logo"><?php echo $this->getChildHtml('theme_logo', false) ?></a></h1>
                <?php else:?>
                <a href="<?php echo $this->getUrl('') ?>" title="<?php echo $this->getLogoAlt() ?>" class="logo"><strong><?php echo $this->getLogoAlt() ?></strong><?php echo $this->getChildHtml('theme_logo', false) ?></a>
                <?php endif?>

How can I save data from a html form in a file? [duplicate]

This question already has an answer here:

I did the simple form.In that i am trying modifying the $_post output.


    $lhs = array();
    $rhs = array();

    foreach($_POST as $key => $value) {
        echo $key . "=" . $value;
        echo "<br>";
        $lhs[] = $key; //first array for left hand side 
        $rhs[] = $value; //second array for right hand side



<form name="form1" method="post" action="">
    Name: <input type="text" name="name"><br>
    Phone No: <input type="text" name="phone" /><br/>
    Course:<input type="text" name="course" /> <br />
    <input type="submit" name="Submit" value="Sign Up">

So the output of this could be:

Submit=Sign Up

now you can observe see that I am getting the output of the button also:

Submit=Sign Up

Which I don't require in the output. And I require the output something like this:


This output I want to store in a text file.

I am not able to modify the output either I am not able to store this output in a text file.

How can I get rid of the submit button output and save the data into a file?

Any Help or advice is appreciated and Thanks in advance.

copying data from another workbook

i am trying to replace the current data in my file with the data in any another selected file which have same attributes. i want to replace the data from A1:Q in the current file from any other selected file. I tried writing the code but its showing errors .

Sub newdata()

Set appxl = CreateObject("Excel.application")
Dim myfile As Window
Dim currentSheet As Worksheet
Dim lastRow As Double
Dim sourceFileName As String

'Open Source File.xlsx
With appxl

    vFile = Application.GetOpenFilename(Title:="Select File To Be Opened")
    If vFile = False Then Exit Sub  'if the user didn't select a file, exit sub
   ' Set myfile = Workbooks.Open(vFile)

    .Visible = False
End With

'Get first sheet data
Set myfile = appxl.Windows(vFile)
Set currentSheet = myfile.Sheets(1)

'Past the table in my current Excel file
lastRow = currentSheet.Range("A1").End(xlDown).Row
Sheets("Data retrieval").Range("A1:E" & lastRow) = currentSheet.Range("A1:Q" & lastRow).Value

'Close Source File.xlsx

End Sub

Creating a file with dynamic name in cobol

We want to create a file with a date embedded in it which is derived from another file. Consider a file A contains processing date '04/18/2015'. Now we want to create a file with name 'XXXX.YYYY.04182015'.

Can it be accomplished using COBOL and JCL?

java token recognition program

i am new in java world and i am trying to read data from file then recognize each char token according to a specific grammer then recognize each word token here is my non-complete code but i can't even read chars from text file and recognize the chars tokens i hope to find some help

package compilers_project;
import java.util.*;
import java.util.regex.*;
import java.util.function.*;
public class compiler {
public static Scanner scan;
public  static int lines_num=0;
public static void main(String args[]){
    element elements[][]= new element[lines_num][150];
    elements = read_file("E:\\source.txt");
    for (int i=0;i<lines_num;i++){


public static void open_file(String path){
        scan = new Scanner (new File(path));
    catch(Exception ex){
        System.out.print("couldn't find "+ ex.getMessage());    


static int count_lines(String path){
    int count = 0;
    while (scan.hasNextLine()) {
    return count;
public static token get_token(element e){
    return token.letter;    
    else if(Arrays.asList(digits).contains(e.value)){
        return token.digit; 
    else if(Arrays.asList(symbols).contains(e.value)){  
        return token.special_symbol;
        return token.undefined;

public static token get_token(word w){
    return token.letter;    
    else if(Arrays.asList(digits).contains(w.value)){
        return token.digit; 
    else if(Arrays.asList(symbols).contains(w.value)){  
        return token.special_symbol;
        return token.undefined;

public static element[][] read_file(String path){
    int lines_num = count_lines(path);
    element array[][]= new element[lines_num][150];
    int count=0,i;
    String line;
    while (scan.hasNext()){
        line =scan.nextLine();
        for(i = 0 ; i< line.length();i++){
            array[count][i].tokn = get_token(array[count][i]);
    }   //now we have array of array in which each element(single digit) have value and token

return array;

public static boolean is_special_symbol(String s){
    if(s=="or"|| s== "not"|| s=="and"|| s=="<=" ||s==">=" ||s=="==" || s=="!=" || s=="<*" || s=="*>"){  
    return true;    
    return false;

public static word[][] get_words(element e[][])
    int c=0,i=0;
    word words[][]=new word[lines_num][100];
    words[0][0]=new word();
        int current_word=0;
            while(e[i][c].value!=' ' && e[i][c].value!='\n' ){              
            if(e[i][c].value !='\n' && e[i][c].tokn !=token.special_symbol && e[i][c].value !=' ' ){
        words[i][current_word].tok= find_word_tokn(words[i][current_word]);
        words[i][current_word]=new word();

return words;
public static token find_word_tokn(word w){
    return get_token(w);    
else if( is_id(w)){
    return token.ID;
else if(is_str(w)){
    return token.STR;
else if(is_int(w)){
    return token.INT_NUM;
else if(is_float(w)){
    return token.FLOAT_NUM;
    return token.undefined;


public static boolean is_str(word w){
    for (int i=0;i< w.elements_tok.length;i++){
        if(w.elements_tok[i] ==token.digit || w.elements_tok[i] == token.digit || w.value.charAt(i)=='_' ){
        //go on 
        return false;   
    return true;

public static boolean is_id(word w){
    if(w.elements_tok[0]==token.letter && is_str(w)){
        return true;

        return false;

public static boolean is_float(word w){
    int count=0;
    for (int i=0;i< w.elements_tok.length;i++){
        if(w.elements_tok[i] ==token.digit|| w.value.charAt(i)=='.' ){
        //go on 
        else if(i==0 && (w.value.charAt(0)=='+'|| w.value.charAt(0)=='-' ))
            //go on
        return false;   
    if(count <2){
    return true;
    return false;

public static boolean is_int(word w){
    for (int i=0;i< w.elements_tok.length;i++){
        if(w.elements_tok[i] ==token.digit){
        //go on 
        else if(i==0 && (w.value.charAt(0)=='+'|| w.value.charAt(0)=='-' ))
            //go on
        return false;   
    return true;


Diff two files in shell script

Assume we have two files named file1 and file2.



Here file2 has the same keys of file1 and different values.Apart from some extra key-value pair of its own.

Compare two files keys, replace file2 value with file1 value based on key match. Retain the new entries in file2.

So, my final output should be :


Thanks In Advance.

Check for file and process it, existence of file launch script - perl

Is there any way how in perl handle file event processing. I mean check if the file exist and then process data from it (xml). With perl i can check (-e, if, ...) if file itself exists. But how to handle when file will be created to launch script. Is there anything like this ?

Merging Video Files with PHP

I have two mp4 files and i want to merge them.

$media1 = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/dir/media1.mp4');
$media2 = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/dir/media2.mp4');

file_put_contents($_SERVER['DOCUMENT_ROOT'].'/dir/combined.mp4', $media1.$media2);

media1.mp4 : 1 Megabyte, 10 second

media2.mp4 : 2 Megabyte, 20 second

combined.mp4 : 3 Megabyte but 10 second (There is only media1.mp4)

How can i merge these two files?