Search Results

Search found 373 results on 15 pages for 'salary'.

Page 4/15 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Query a recordset

    - by Dion
    I'm trying to work out how to move the $sql_pay_det query outside of the $sql_pay loop (so in effect query on $rs_pay_det rather than creating a new $rs_pay_det for each iteration of the loop) At the moment my code looks like: //Get payroll transactions $sql_pay = 'SELECT Field1, DescriptionandURLlink, Field5, Amount, Field4, PeriodName FROM tblgltransactionspayroll WHERE CostCentreCode = "'.$cc.'" AND SubjectiveCode = "'.$subj.'" AND PeriodNo = "'.$month.'"'; $rs_pay = mysql_query($sql_pay); $row_pay = mysql_fetch_assoc($rs_pay); while($row_pay = mysql_fetch_array($rs_pay)) { $employee_name = $row_pay['Field1']; $assign_no = $row_pay['DescriptionandURLlink']; $pay_period = $row_pay['Field5']; $mth_name = $row_pay['PeriodName']; $amount = $row_pay['Amount']; $total_amount = $total_amount + $amount; $amount = my_number_format($amount, 2, ".", ","); $sql_pay_det = 'SELECT ElementDesc, Amount, WTEWorked, WTEPaid, WTEContract, Payscale FROM tblpayrolldetail WHERE CostCentreCode = "'.$cc.'" AND SubjectiveCode = "'.$subj.'" AND AccountingPeriod = "'.$mth_name.'" AND EmployeeRef = "'.$assign_no.'"'; $rs_pay_det = mysql_query($sql_pay_det); $row_pay_det = mysql_fetch_assoc($rs_pay_det); while($row_pay_det = mysql_fetch_array($rs_pay_det)) { $element_det = $row_pay_det['ElementDesc']; $amount_det = $row_pay_det['Amount']; $wte_worked = $row_pay_det['WTEWorked']; $wte_paid = $row_pay_det['WTEPaid']; $wte_cont = $row_pay_det['WTEContract']; $payscale = $row_pay_det['Payscale']; //Get band/point and annual salary where element is basic pay if ($element_det =="3959#Basic Pay"){ $sql_payscale = 'SELECT txtPayscaleName, Salary FROM tblpayscalemapping WHERE txtPayscale = "'.$payscale.'"'; $rs_payscale = mysql_query($sql_payscale); $row_payscale = mysql_fetch_assoc($rs_payscale); $grade = $row_payscale['txtPayscaleName']; $salary = "£" . my_number_format($row_payscale['Salary'], 0, ".", ","); } } } I've tried doing this: //Get payroll transactions $sql_pay = 'SELECT Field1, DescriptionandURLlink, Field5, Amount, Field4, PeriodName FROM tblgltransactionspayroll WHERE CostCentreCode = "'.$cc.'" AND SubjectiveCode = "'.$subj.'" AND PeriodNo = "'.$month.'"'; $rs_pay = mysql_query($sql_pay); $row_pay = mysql_fetch_assoc($rs_pay); //Get payroll detail recordset $sql_pay_det = 'SELECT ElementDesc, Amount, WTEWorked, WTEPaid, WTEContract, Payscale, EmployeeRef FROM tblpayrolldetail WHERE CostCentreCode = "'.$cc.'" AND SubjectiveCode = "'.$subj.'" AND AccountingPeriod = "'.$mth_name.'"'; $rs_pay_det = mysql_query($sql_pay_det); while($row_pay = mysql_fetch_array($rs_pay)) { $employee_name = $row_pay['Field1']; $assign_no = $row_pay['DescriptionandURLlink']; $pay_period = $row_pay['Field5']; $mth_name = $row_pay['PeriodName']; $amount = $row_pay['Amount']; $total_amount = $total_amount + $amount; $amount = my_number_format($amount, 2, ".", ","); //Query $rs_pay_det $sql_pay_det2 = 'SELECT ElementDesc, Amount, WTEWorked, WTEPaid, WTEContract, Payscale FROM "'.$rs_pay_det.'" WHERE EmployeeRef = "'.$assign_no.'"'; $rs_pay_det2 = mysql_query($sql_pay_det2); $row_pay_det2 = mysql_fetch_assoc($rs_pay_det2); while($row_pay_det = mysql_fetch_array($rs_pay_det)) { $element_det = $row_pay_det['ElementDesc']; $amount_det = $row_pay_det['Amount']; $wte_worked = $row_pay_det['WTEWorked']; $wte_paid = $row_pay_det['WTEPaid']; $wte_cont = $row_pay_det['WTEContract']; $payscale = $row_pay_det['Payscale']; //Get band/point and annual salary where element is basic pay if ($element_det =="3959#Basic Pay"){ $sql_payscale = 'SELECT txtPayscaleName, Salary FROM tblpayscalemapping WHERE txtPayscale = "'.$payscale.'"'; $rs_payscale = mysql_query($sql_payscale); $row_payscale = mysql_fetch_assoc($rs_payscale); $grade = $row_payscale['txtPayscaleName']; $salary = "£" . my_number_format($row_payscale['Salary'], 0, ".", ","); } } } But I get an error on $row_pay_det2 saying that "mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource"

    Read the article

  • Android From Local DB (DAO) to Server sync (JSON) - Design issue

    - by Taiko
    I sync data between my local DB and a Server. I'm looking for the cleanest way to modelise all of this. I have a com.something.db package That contains a Data Helper and couple of DAO classes that represents objects stored in the db (I didn't write that part) com.something.db --public DataHelper --public Employee @DatabaseField e.g. "name" will be an actual column name in the DB -name @DatabaseField -salary etc... (all in all 50 fields) I have a com.something.sync package That contains all the implementation detail on how to send data to the server. It boils down to a ConnectionManager that is fed by different classes that implements a 'Request' interface com.something.sync --public interface ConnectionManager --package ConnectionManagerImpl --public interface Request --package LoginRequest --package GetEmployeesRequest My issue is, at some point in the sync process, I have to JSONise and de-JSONise my data (E.g. the Employee class). But I really don't feel like having the same Employee class be responsible for both his JSONisation and his actual representation inside the local database. It really doesn't feel right, because I carefully decoupled the rest, I am only stuck on this JSON thing. What should I do ? Should I write 3 Employee classes ? EmployeeDB @DatabaseField e.g. "name" will be an actual column name in the DB -name @DatabaseField -salary -etc... 50 fields EmployeeInterface -getName -getSalary -etc... 50 fields EmployeeJSON -JSON_KEY_NAME = "name" The JSON key happens to be the same as the table name, but it isn't requirement -name -JSON_KEY_SALARY = "salary" -salary -etc... 50 fields It feels like a lot of duplicates. Is there a common pattern I can use there ?

    Read the article

  • Merge Records in Session bean by using ADF Drag/Drop

    - by shantala.sankeshwar
    This article describes how to merge multiple selected records in Session Bean using ADF drag & drop feature. Below described is simple use case that shows how exactly this can be achieved. Here we will have table & user input field.Table shows  EMP records & user input field accepts Salary.When we drag & drop multiple records on user input field,the selected records get updated with the new Salary provided. Steps: Let us suppose that we have created Java EE Web Application with Entities from Emp table.Then create EJB Session Bean & generate Data control for the same. Write a simple code in sessionEJBBean & expose this method to local interface :  public void updateEmprecords(List empList, Object sal) {       Emp emp = null;       for (int i = 0; i < empList.size(); i++)       {        emp = em.find(Emp.class, empList.get(i));         emp.setSal((BigDecimal)sal);       }      em.merge(emp);   } Now let us create updateEmpRecords.jspx page in viewController project & Drop empFindAll object as ADF Table Define custom SelectionListener method for the table :   public void selectionListener(SelectionEvent selectionEvent)     {     // This method gets the Empno of the selected record & stores in the list object      UIXTable table = (UIXTable)selectionEvent.getComponent();      FacesCtrlHierNodeBinding fcr      =(FacesCtrlHierNodeBinding)table.getSelectedRowData();      Number empNo = (Number)fcr.getAttribute("empno") ;      this.getSelectedRowsList().add(empNo);     }Set table's selectedRowKeys to #{bindings.empFindAll.collectionModel.selectedRow}"Drop inputText on the same jspx page that accepts Salary .Now we would like to drag records from the above table & drop that on the inputtext field.This feature can be achieved by inserting dragSource operation inside the table & dropTraget operation inside the inputText:<af:dragSource discriminant="tab"/> //Insert this inside the table<af:inputText label="Enter Salary" id="it13" autoSubmit="true"       binding="# {test.deptValue}">       <af:dropTarget dropListener="#{test.handleTableDrop}">       <af:dataFlavor        flavorClass="org.apache.myfaces.trinidad.model.RowKeySet"    discriminant="tab"/>       </af:dropTarget>       <af:convertNumber/> </af:inputText> In the above code when the user drags & drops multiple records on inputText,the dropListener method gets called.Goto the respective page definition file & create updateEmprecords method action& execute action dropListener method code:        public DnDAction handleTableDrop(DropEvent dropEvent)        {          //Below code gets the updateEmprecords method,passes parameters & executes method            DataFlavor<RowKeySet> df = DataFlavor.getDataFlavor(RowKeySet.class);            RowKeySet droppedKeySet = dropEvent.getTransferable().getData(df);            if (droppedKeySet != null && droppedKeySet.size() > 0)           {                  DCBindingContainer bindings =                  (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();                  OperationBinding updateEmp;                  updateEmp= bindings.getOperationBinding("updateEmprecords");                  updateEmp.getParamsMap().put("sal",                  this.getDeptValue().getAttributes().get("value"));                            updateEmp.getParamsMap().put("empList", this.getSelectedRowsList());                  updateEmp.execute(); //Below code performs execute operation to refresh the updated records                 OperationBinding executeBinding;                 executeBinding= bindings.getOperationBinding("Execute");                 executeBinding.execute(); AdfFacesContext.getCurrentInstance().addPartialTarget(dropEvent.getDragComponent());                this.getSelectedRowsList().clear();          }                 return DnDAction.NONE;        }Run updateEmpRecords.jspx page & enter any Salary say '5000'.Select multiple records in table & drop these selected records on the inputText Salary. Note that all the selected records salary value gets updated to 5000.Technorati Tags: ADF Drag and drop,EJB Session bean,ADF table,inputText,DropEvent  

    Read the article

  • What is the point of the prototype method?

    - by Mild Fuzz
    I am reading through Javascript: The Good Parts, and struggled to get my head around the section on prototypes. After a little google, I came to the conclusion that it is to add properties to objects after the objects declaration. Using this script gleamed from w3schools, I noticed that removing the line adding the prototype property had no effect. So what is the point? //Prototyping function employee(name,jobtitle,born) { this.name=name; this.jobtitle=jobtitle; this.born=born; } var fred=new employee("Fred Flintstone","Caveman",1970); employee.prototype.salary=null; // <--- try removing this line fred.salary=20000; document.write(fred.salary);

    Read the article

  • A potential new hire may make more money you do..what should I do [migrated]

    - by Ali
    I have a very solid experience in Software Development and Project management. I just learned that the company I work for has posted a new position with half the experience of mine and even lesser set of skills than I have. However, the new position pays the same salary as my current salary while at the same time they declined to pay the asking salary when I was joining the company. How should I counter this? I know there are many projects in the pipeline where my involvement is crucial for the projects to be successful but I don't want to come across threating. Any advise would be helpful..!

    Read the article

  • How to handle compensation issue

    - by Ali
    I consider myself an expert Software Developer. Recently, I noticed my current company posted a new job through a recruting firm requiring half experience than I have and even lesser set of skills. However, they are offering the same salary as my current salary. When I joined my current company a year ago, they declined to pay my asking salary. My evaluations are good and there are critical projects in the pipeline where my involvement is crucial for their success. I'm little confused on how to handle this situation. I don't want to come across threatning or any thing like that.

    Read the article

  • Solving a probabilistic problem

    - by ????????????
    So I am interested in Computational Investing and came across this problem on a wiki page: Write a program to discover the answer to this puzzle:"Let's say men and women are paid equally (from the same uniform distribution). If women date randomly and marry the first man with a higher salary, what fraction of the population will get married?" I don't have much knowledge in probability theory, so I'm not really sure how to implement this in code. My thinking: Populate two arrays(female,male) with random salary values from a uniform distribution. Randomly pair one female and one male array element and see if condition of higher salary is met. If it is, increment a counter. Divide counter by population and get percentage. Is this the correct logic? Do woman continually date until there is no males left with higher salaries than women?

    Read the article

  • Alternative to TOP in SQL Server and Oracle.

    SELECT TOP 5 * FROM EMP ORDER BY SALARY; Above query works in SQL Server. This returns top 5 employees. The problem with this query is it doesn't work with Oracle. In Oracle you would need to write the query as follows. SELECT * FROM EMP WHERE ROWNUM<=5 ORDER BY SALARY If you are looking for a query which runs in both Oracle and SQL Server. Please use below one. select * from (SELECT row_number() over( ORDER by SALARY) as rank, EMP.* FROM EMP) s1 where s1.rank <= 5; span.fullpost {display:none;}

    Read the article

  • Using Oracle Proxy Authentication with JPA (eclipselink-Style)

    - by olaf.heimburger
    Security is a very intriguing topic. You will find it everywhere and you need to implement it everywhere. Yes, you need. Unfortunately, one can easily forget it while implementing the last mile. The Last Mile In a multi-tier application it is a common practice to use connection pools between the business layer and the database layer. Connection pools are quite useful to speed database connection creation and to split the load. Another very common practice is to use a specific, often called technical, user to connect to the database. This user has authentication and authorization rules that apply to all application users. Imagine you've put every effort to define roles for different types of users that use your application. These roles are necessary to differentiate between normal users, premium users, and administrators (I bet you will find or already have more roles in your application). While these user roles are pretty well used within your application, once the flow of execution enters the database everything is gone. Each and every user just has one role and is the same database user. Issues? What Issues? As long as things go well, this is not a real issue. However, things do not go well all the time. Once your application becomes famous performance decreases in certain situations or, more importantly, current and upcoming regulations and laws require that your application must be able to apply different security measures on a per user role basis at every stage of your application. If you only have a bunch of users with the same name and role you are not able to find the application usage profile that causes the performance issue, or which user has accessed data that he/she is not allowed to. Another thread to your role concept is that databases tend to be used by different applications and tools. These tools can be developer tools like SQL*Plus, SQL Developer, etc. or end user applications like BI Publisher, Oracle Forms and so on. These tools have no idea of your applications role concept and access the database the way they think is appropriate. A big oversight for your perfect role model and a big nightmare for your Chief Security Officer. Speaking of the CSO, brings up another issue: Password management. Once your technical user account is compromised, every user is able to do things that he/she is not expected to do from the design of your application. Counter Measures In the Oracle world a common counter measure is to use Virtual Private Database (VPD). This restricts the values a database user can see to the allowed minimum. However, it doesn't help in regard of a connection pool user, because this one is still not the real user. Oracle Proxy Authentication Another feature of the Oracle database is Proxy Authentication. First introduced with version 9i it is a quite useful feature for nearly every situation. The main idea behind Proxy Authentication is, to create a crippled database user who has only connect rights. Even if this user is compromised the risks are well understood and fairly limited. This user can be used in every situation in which you need to connect to the database, no matter which tool or application (see above) you use.The proxy user is perfect for multi-tier connection pools. CREATE USER app_user IDENTIFIED BY abcd1234; GRANT CREATE SESSION TO app_user; But what if you need to access real data? Well, this is the primary use case, isn't it? Now is the time to bring the application's role concept into play. You define database roles that define the grants for your identified user groups. Once you have these groups you grant access through the proxy user with the application role to the specific user. CREATE ROLE app_role_a; GRANT app_role_a TO scott; ALTER USER scott GRANT CONNECT THROUGH app_user WITH ROLE app_role_a; Now, hr has permission to connect to the database through the proxy user. Through the role you can restrict the hr's rights the are needed for the application only. If hr connects to the database directly all assigned role and permissions apply. Testing the Setup To test the setup you can use SQL*Plus and connect to your database: $ sqlplus app_user[hr]/abcd1234 Java Persistence API The Java Persistence API (JPA) is a fairly easy means to build applications that retrieve data from the database and put it into Java objects. You use plain old Java objects (POJOs) and mixin some Java annotations that define how the attributes of the object are used for storing data from the database into the Java object. Here is a sample for objects from the HR sample schema EMPLOYEES table. When using Java annotations you only specify what can not be deduced from the code. If your Java class name is Employee but the table name is EMPLOYEES, you need to specify the table name, otherwise it will fail. package demo.proxy.ejb; import java.io.Serializable; import java.sql.Timestamp; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @NamedQueries({ @NamedQuery(name = "Employee.findAll", query = "select o from Employee o") }) @Table(name = "EMPLOYEES") public class Employee implements Serializable { @Column(name="COMMISSION_PCT") private Double commissionPct; @Column(name="DEPARTMENT_ID") private Long departmentId; @Column(nullable = false, unique = true, length = 25) private String email; @Id @Column(name="EMPLOYEE_ID", nullable = false) private Long employeeId; @Column(name="FIRST_NAME", length = 20) private String firstName; @Column(name="HIRE_DATE", nullable = false) private Timestamp hireDate; @Column(name="JOB_ID", nullable = false, length = 10) private String jobId; @Column(name="LAST_NAME", nullable = false, length = 25) private String lastName; @Column(name="PHONE_NUMBER", length = 20) private String phoneNumber; private Double salary; @ManyToOne @JoinColumn(name = "MANAGER_ID") private Employee employee; @OneToMany(mappedBy = "employee") private List employeeList; public Employee() { } public Employee(Double commissionPct, Long departmentId, String email, Long employeeId, String firstName, Timestamp hireDate, String jobId, String lastName, Employee employee, String phoneNumber, Double salary) { this.commissionPct = commissionPct; this.departmentId = departmentId; this.email = email; this.employeeId = employeeId; this.firstName = firstName; this.hireDate = hireDate; this.jobId = jobId; this.lastName = lastName; this.employee = employee; this.phoneNumber = phoneNumber; this.salary = salary; } public Double getCommissionPct() { return commissionPct; } public void setCommissionPct(Double commissionPct) { this.commissionPct = commissionPct; } public Long getDepartmentId() { return departmentId; } public void setDepartmentId(Long departmentId) { this.departmentId = departmentId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getEmployeeId() { return employeeId; } public void setEmployeeId(Long employeeId) { this.employeeId = employeeId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public Timestamp getHireDate() { return hireDate; } public void setHireDate(Timestamp hireDate) { this.hireDate = hireDate; } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } public List getEmployeeList() { return employeeList; } public void setEmployeeList(List employeeList) { this.employeeList = employeeList; } public Employee addEmployee(Employee employee) { getEmployeeList().add(employee); employee.setEmployee(this); return employee; } public Employee removeEmployee(Employee employee) { getEmployeeList().remove(employee); employee.setEmployee(null); return employee; } } JPA could be used in standalone applications and Java EE containers. In both worlds you normally create a Facade to retrieve or store the values of the Entities to or from the database. The Facade does this via an EntityManager which will be injected by the Java EE container. Here is sample Facade Session Bean for a Java EE container. package demo.proxy.ejb; import java.util.HashMap; import java.util.List; import javax.ejb.Local; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; import oracle.jdbc.driver.OracleConnection; import org.eclipse.persistence.config.EntityManagerProperties; import org.eclipse.persistence.internal.jpa.EntityManagerImpl; @Stateless(name = "DataFacade", mappedName = "ProxyUser-TestEJB-DataFacade") @Remote @Local public class DataFacadeBean implements DataFacade, DataFacadeLocal { @PersistenceContext(unitName = "TestEJB") private EntityManager em; private String username; public Object queryByRange(String jpqlStmt, int firstResult, int maxResults) { // setSessionUser(); Query query = em.createQuery(jpqlStmt); if (firstResult 0) { query = query.setFirstResult(firstResult); } if (maxResults 0) { query = query.setMaxResults(maxResults); } return query.getResultList(); } public Employee persistEmployee(Employee employee) { // setSessionUser(); em.persist(employee); return employee; } public Employee mergeEmployee(Employee employee) { // setSessionUser(); return em.merge(employee); } public void removeEmployee(Employee employee) { // setSessionUser(); employee = em.find(Employee.class, employee.getEmployeeId()); em.remove(employee); } /** select o from Employee o */ public List getEmployeeFindAll() { Query q = em.createNamedQuery("Employee.findAll"); return q.getResultList(); } Putting Both Together To use Proxy Authentication with JPA and within a Java EE container you have to take care of the additional requirements: Use an OCI JDBC driver Provide the user name that connects through the proxy user Use an OCI JDBC driver To use the OCI JDBC driver you need to set up your JDBC data source file to use the correct JDBC URL. hr jdbc:oracle:oci8:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SID=XE))) oracle.jdbc.OracleDriver user app_user 62C32F70E98297522AD97E15439FAC0E SQL SELECT 1 FROM DUAL jdbc/hrDS Application Additionally you need to make sure that the version of the shared libraries of the OCI driver match the version of the JDBC driver in your Java EE container or Java application and are within your PATH (on Windows) or LD_LIBRARY_PATH (on most Unix-based systems). Installing the Oracle Database Instance Client software works perfectly. Provide the user name that connects through the proxy user This part needs some modification of your application software and session facade. Session Facade Changes In the Session Facade we must ensure that every call that goes through the EntityManager must be prepared correctly and uniquely assigned to this session. The second is really important, as the EntityManager works with a connection pool and can not guarantee that we set the proxy user on the connection that will be used for the database activities. To avoid changing every method call of the Session Facade we provide a method to set the username of the user that connects through the proxy user. This method needs to be called by the Facade client bfore doing anything else. public void setUsername(String name) { username = name; } Next we provide a means to instruct the TopLink EntityManager Delegate to use Oracle Proxy Authentication. (I love small helper methods to hide the nitty-gritty details and avoid repeating myself.) private void setSessionUser() { setSessionUser(username); } private void setSessionUser(String user) { if (user != null && !user.isEmpty()) { EntityManagerImpl emDelegate = ((EntityManagerImpl)em.getDelegate()); emDelegate.setProperty(EntityManagerProperties.ORACLE_PROXY_TYPE, OracleConnection.PROXYTYPE_USER_NAME); emDelegate.setProperty(OracleConnection.PROXY_USER_NAME, user); emDelegate.setProperty(EntityManagerProperties.EXCLUSIVE_CONNECTION_MODE, "Always"); } } The final step is use the EJB 3.0 AroundInvoke interceptor. This interceptor will be called around every method invocation. We therefore check whether the Facade methods will be called or not. If so, we set the user for proxy authentication and the normal method flow continues. @AroundInvoke public Object proxyInterceptor(InvocationContext invocationCtx) throws Exception { if (invocationCtx.getTarget() instanceof DataFacadeBean) { setSessionUser(); } return invocationCtx.proceed(); } Benefits Using Oracle Proxy Authentification has a number of additional benefits appart from implementing the role model of your application: Fine grained access control for temporary users of the account, without compromising the original password. Enabling database auditing and logging. Better identification of performance bottlenecks. References Effective Oracle Database 10g Security by Design, David Knox TopLink Developer's Guide, Chapter 98

    Read the article

  • print a linear linked list into a table

    - by user1796970
    I am attempting to print some values i have stored into a LLL into a readable table. The data i have stored is the following : DEBBIE STARR F 3 W 1000.00 JOAN JACOBUS F 9 W 925.00 DAVID RENN M 3 H 4.75 ALBERT CAHANA M 3 H 18.75 DOUGLAS SHEER M 5 W 250.00 SHARI BUCHMAN F 9 W 325.00 SARA JONES F 1 H 7.50 RICKY MOFSEN M 6 H 12.50 JEAN BRENNAN F 6 H 5.40 JAMIE MICHAELS F 8 W 150.00 i have stored each firstname, lastname, gender, tenure, payrate, and salary into their own List. And would like to be able to print them out in the same format that they are viewed on the text file i read them in from. i have messed around with a few methods that allow me to traverse and print the Lists, but i end up with ugly output. . . here is my code for the storage of the text file and the format i would like to print out: public class Payroll { private LineWriter lw; private ObjectList output; ListNode input; private ObjectList firstname, lastname, gender, tenure, rate, salary; public Payroll(LineWriter lw) { this.lw = lw; this.firstname = new ObjectList(); this.lastname = new ObjectList(); this.gender = new ObjectList(); this.tenure = new ObjectList(); this.rate = new ObjectList(); this.salary = new ObjectList(); this.output = new ObjectList(); this.input = new ListNode(); } public void readfile() { File file = new File("payfile.txt"); try{ Scanner scanner = new Scanner(file); while(scanner.hasNextLine()) { String line = scanner.nextLine(); Scanner lineScanner = new Scanner(line); lineScanner.useDelimiter("\\s+"); while(lineScanner.hasNext()) { firstname.insert1(lineScanner.next()); lastname.insert1(lineScanner.next()); gender.insert1(lineScanner.next()); tenure.insert1(lineScanner.next()); rate.insert1(lineScanner.next()); salary.insert1(lineScanner.next()); } } }catch(FileNotFoundException e) {e.printStackTrace();} } public void printer(LineWriter lw) { String msg = " FirstName " + " LastName " + " Gender " + " Tenure " + " Pay Rate " + " Salary "; output.insert1(msg); System.out.println(output.getFirst()); System.out.println(" " + firstname.getFirst() + " " + lastname.getFirst() + "\t" + gender.getFirst() + "\t" + tenure.getFirst() + "\t" + rate.getFirst() + "\t" + salary.getFirst()); } }

    Read the article

  • Self join to a table

    - by Mohit
    I have a table like Employee ================== name salary ================== a 10000 b 20000 c 5000 d 40000 i want to get all the employee whose salary is greater than A's salary. I don't want to use any nested or sub query. It has been asked in an interview and hint was to use self join. I really can't figure out how to achieve the same.

    Read the article

  • PHP: Strange behaviour while calling custom php functions

    - by baltusaj
    I am facing a strange behavior while coding in PHP with Flex. Let me explain the situation: I have two funcions lets say: populateTable() //puts some data in a table made with flex createXML() //creates an xml file which is used by Fusion Charts to create a chart Now, if i call populateTable() alone, the table gets populated with data but if i call it with createXML(), the table doesn't get populated but createXML() does it's work i.e. creates an xml file. Even if i run following code, only xml file gets generated but table remains empty whereas i called populateTable() before createXML(). Any idea what may be going wrong? MXML Part <mx:HTTPService id="userRequest" url="request.php" method="POST" resultFormat="e4x"> <mx:request xmlns=""> <getResult>send</getResult> </mx:request> and <mx:DataGrid id="dgUserRequest" dataProvider="{userRequest.lastResult.user}" x="28.5" y="36" width="525" height="250" > <mx:columns> <mx:DataGridColumn headerText="No." dataField="no" /> <mx:DataGridColumn headerText="Name" dataField="name"/> <mx:DataGridColumn headerText="Age" dataField="age"/> </mx:columns> PHP Part <?php //-------------------------------------------------------------------------- function initialize($username,$password,$database) //-------------------------------------------------------------------------- { # Connect to the database $link = mysql_connect("localhost", $username,$password); if (!$link) { die('Could not connected to the database : ' . mysql_error()); } # Select the database $db_selected = mysql_select_db($database, $link); if (!$db_selected) { die ('Could not select the DB : ' . mysql_error()); } // populateTable(); createXML(); # Close database connection } //-------------------------------------------------------------------------- populateTable() //-------------------------------------------------------------------------- { if($_POST['getResult'] == 'send') { $Result = mysql_query("SELECT * FROM session" ); $Return = "<Users>"; $no = 1; while ( $row = mysql_fetch_object( $Result ) ) { $Return .= "<user><no>".$no."</no><name>".$row->name."</name><age>".$row->age."</age><salary>". $row->salary."</salary></session>"; $no=$no+1; $Return .= "</Users>"; mysql_free_result( $Result ); print ($Return); } //-------------------------------------------------------------------------- createXML() //-------------------------------------------------------------------------- { $users=array ( "0"=>array("",0), "1"=>array("Obama",0), "2"=>array("Zardari",0), "3"=>array("Imran Khan",0), "4"=>array("Ahmadenijad",0) ); $selectedUsers=array(1,4); //this means only obama and ahmadenijad are selected and the xml file will contain info related to them only //Extracting salaries of selected users $size=count($users); for($i = 0; $i<$size; $i++) { //initialize temp which will calculate total throughput for each protocol separately $salary = 0; $result = mysql_query("SELECT salary FROM userInfo where name='$users[$selectedUsers[$i]][0]'"); $row = mysql_fetch_array($result)) $salary = $row['salary']; } $users[$selectedUsers[$i]][1]=$salary; } //creating XML string $chartContent = "<chart caption=\"Users Vs Salaries\" formatNumberScale=\"0\" pieSliceDepth=\"30\" startingAngle=\"125\">"; for($i=0;$i<$size;$i++) { $chartContent .= "<set label=\"".$users[$selectedUsers[$i]][0]."\" value=\"".$users[$selectedUsers[$i]][1]."\"/>"; } $chartContent .= "<styles>" . "<definition>" . "<style type=\"font\" name=\"CaptionFont\" size=\"16\" color=\"666666\"/>" . "<style type=\"font\" name=\"SubCaptionFont\" bold=\"0\"/>" . "</definition>" . "<application>" . "<apply toObject=\"caption\" styles=\"CaptionFont\"/>" . "<apply toObject=\"SubCaption\" styles=\"SubCaptionFont\"/>" . "</application>" . "</styles>" . "</chart>"; $file_handle = fopen('ChartData.xml','w'); fwrite($file_handle,$chartContent); fclose($file_handle); } initialize("root","","hiddenpeak"); ?>

    Read the article

  • Aggregate Functions on subsets of data based on current row values with SQL

    - by aasukisuki
    Hopefully that title makes sense... Let's say I have an employee table: ID | Name | Title | Salary ---------------------------- 1 | Bob | Manager | 15285 2 | Joe | Worker | 10250 3 | Al | Worker | 11050 4 | Paul | Manager | 16025 5 | John | Worker | 10450 What I'd like to do is write a query that will give me the above table, along with an averaged salary column, based on the employee title: ID | Name | Title | Salary | Pos Avg -------------------------------------- 1 | Bob | Manager | 15285 | 15655 2 | Joe | Worker | 10250 | 10583 3 | Al | Worker | 11050 | 10583 4 | Paul | Manager | 16025 | 15655 5 | John | Worker | 10450 | 10583 I've tried doing this with a sub-query along the lines of: Select *, (select Avg(e2.salary) from employee e2 where e2.title = e.title) from employee e But I've come to realize that the sub-query is executed first, and has no knowledge of the table alias'd e I'm sure I'm missing something REALLY obvious here, can anyone point me in the right diretion?

    Read the article

  • Ruby - calling constructor without arguments & removal of new line characters

    - by Raj
    I am a newbie at Ruby, I have written down a sample program. I dont understand the following: Why constructor without any arguments are not called in Ruby? How do we access the class variable outside the class' definition? Why does it always append newline characters at the end of the string? How do we strip it? Code: class Employee attr_reader :empid attr_writer :empid attr_writer :name def name return @name.upcase end attr_accessor :salary @@employeeCount = 0 def initiaze() @@employeeCount += 1 puts ("Initialize called!") end def getCount return @@employeeCount end end anEmp = Employee.new print ("Enter new employee name: ") anEmp.name = gets() print ("Enter #{anEmp.name}'s employee ID: ") anEmp.empid = gets() print ("Enter salary for #{anEmp.name}: ") anEmp.salary = gets() theEmpName = anEmp.name.split.join("\n") theEmpID = anEmp.empid.split.join("\n") theEmpSalary = anEmp.salary.split.join("\n") anEmp = Employee.new() anEmp = Employee.new() theCount = anEmp.getCount puts ("New employee #{theEmpName} with employee ID #{theEmpID} has been enrolled, welcome to hell! You have been paid as low as $ #{theEmpSalary}") puts ("Total number of employees created = #{theCount}") Output: Enter new employee name: Lionel Messi Enter LIONEL MESSI 's employee ID: 10 Enter salary for LIONEL MESSI : 10000000 New employee LIONEL MESSI with employee ID 10 has been enrolled, welcome to hell! You have been paid as low as $ 10000000 Total number of employees created = 0 Thanks

    Read the article

  • How to convert an ORM to its subclass using Hibernate ?

    - by Gaaston
    Hi everybody, For example, I have two classes : Person and Employee (Employee is a subclass of Person). Person : has a lastname and a firstname. Employee : has also a salary. On the client-side, I have a single HTML form where i can fill the person informations (like lastname and firstname). I also have a "switch" between "Person" and "Employee", and if the switch is on Employee I can fill the salary field. On the server-side, Servlets receive informations from the client and use the Hibernate framework to create/update data to/from the database. The mapping i'm using is a single table for persons and employee, with a discriminator. I don't know how to convert a Person in an Employee. I firstly tried to : load the Person p from the database create an empty Employee e object copy values from p into e set the salary value save e into the database But i couldn't, as I also copy the ID, and so Hibernate told me they where two instanciated ORM with the same id. And I can't cast a Person into an Employee directly, as Person is Employee's superclass. There seems to be a dirty way : delete the person, and create an employee with the same informations, but I don't really like it.. So I'd appreciate any help on that :) Some precisions : The person class : public class Person { protected int id; protected String firstName; protected String lastName; // usual getters and setters } The employee class : public class Employee extends Person { // string for now protected String salary; // usual getters and setters } And in the servlet : // type is the "switch" if(request.getParameter("type").equals("Employee")) { Employee employee = daoPerson.getEmployee(Integer.valueOf(request.getParameter("ID"))); modifyPerson(employee, request); employee.setSalary(request.getParameter("salary")); daoPerson.save(employee ); } else { Person person = daoPerson.getPerson(Integer.valueOf(request.getParameter("ID"))); modifyPerson(employee, request); daoPerson.save(person); } And finally, the loading (in the dao) : public Contact getPerson(int ID){ Session session = HibernateSessionFactory.getSession(); Person p = (Person) session.load(Person.class, new Integer(ID)); return p; } public Contact getEmployee(int ID){ Session session = HibernateSessionFactory.getSession(); Employee = (Employee) session.load(Employee.class, new Integer(ID)); return p; } With this, i'm getting a ClassCastException when trying to load a Person using getEmployee. XML Hibernate mapping : <class name="domain.Person" table="PERSON" discriminator-value="P"> <id name="id" type="int"> <column name="ID" /> <generator class="native" /> </id> <discriminator column="type" type="character"/> <property name="firstName" type="java.lang.String"> <column name="FIRSTNAME" /> </property> <property name="lastName" type="java.lang.String"> <column name="LASTNAME" /> </property> <subclass name="domain.Employee" discriminator-value="E"> <property name="salary" column="SALARY" type="java.lang.String" /> </subclass> </class> Is it clear enough ? :-/

    Read the article

  • Java inheritance and super() isn't working as expected

    - by dwwilson66
    For a homework assignment, I'm working with the following. It's an assigned class structure, I know it's not the best design by a long shot. Class | Extends | Variables -------------------------------------------------------- Person | None | firstName, lastName, streetAddress, zipCode, phone CollegeEmployee | Person | ssn, salary,deptName Faculty | CollegeEmployee | tenure(boolean) Student | person | GPA,major So in the Faculty class... public class Faculty extends CollegeEmployee { protected String booleanFlag; protected boolean tenured; public Faculty(String firstName, String lastName, String streetAddress, String zipCode, String phoneNumber,String ssn, String department,double salary) { super(firstName,lastName,streetAddress,zipCode,phoneNumber, ssn,department,salary); String booleanFlag = JOptionPane.showInputDialog (null, "Tenured (Y/N)?"); if(booleanFlag.equals("Y")) tenured = true; else tenured = false; } } It was my understanding that super() in Faculty would allow access to the variables in CollegeEmployee as well as Person. With the code above, it compiles fine when I ONLY include the Person variables. As soon as I try to use ssn, department, or salary I get the following compile errors. Faculty.java:15: error: constructor CollegeEmployee in class CollegeEmployee can not be applied to the given types: super(firstName,lastName,streetAddress,zipCode,phoneNumber,ssn,department,salary); ^ Required: String,String,String,String,String Found: String,String,String,String,String,String,String,String reason: actual and formal argument lists differ in length I'm completely confused by this error...which is the actual and formal? Person has five arguments, CollegeEmployee has 3, so my guess is that something's funky with how the parameters are being passed...but I'm not quite sure where to begin fixing it. What am I missing?

    Read the article

  • PeopleSoft New Design Solves Navigation Problem

    - by Applications User Experience
    Anna Budovsky, User Experience Principal Designer, Applications User Experience In PeopleSoft we strive to improve User Experience on all levels. Simplifying navigation and streamlining access to the most important pages is always an important goal. No one likes to waste time waiting for pages to load and watching a spinning glass going on and on. Those performance-affecting server trips, page-load waits and just-too-many clicks were complained about for a long time. Something had to be done. A few new designs came in PeopleSoft 9.2 helping users to access their everyday work areas easier and faster. For example, Dashboard and Work Center aggregate most accessed information sections on a single page; Related Information allows users to complete transaction-related-research without interrupting a transaction and Secure Search gets users to a specific page directly. Today we’ll talk about the Actions menu. Most PeopleSoft pages are shared between individual products and product lines. It means changing the content on a single page involves Oracle development and quality assurance time for making and testing the changes. In order to streamline the navigation and cut down on accessing PeopleSoft pages one-page-at-a-time, we introduced a new menu design. The new menu allows accessing shared pages without the Oracle development team making any local changes, and it works as an additional one-click-path to specific high-traffic actionable pages. Let’s look at how many steps it took to Change Salary for an employee in HCM 9.1 before: Figure 1. BEFORE: The 6 steps a user would take to Change Salary in PeopleSoft HCM 9.1 In PeopleSoft 9.1 it took 5 steps + page loading time + additional verification time for making sure a correct employee is selected from the table. In PeopleSoft 9.2 it only takes 2 steps. To complete Ad Hoc Change Salary action, the user can start from the HCM Manager's Dashboard, click the Action menu within a table, choose a menu option, and access a correct employee’s details page to take an action. Figure 2. AFTER: The 2 steps a user would take to Change Salary in PeopleSoft HCM 9.2 The new menu is placed on a row level which ensures the user accesses the correct employee’s details page. The Actions menu separates menu options into hierarchical sections which help to scan and access the correct option quickly. The new menu’s small size and its structure enabled users to access high-traffic pages from any page and from any part of the page. No more spinning hourglass, no more multiple pages upload. The flexible design fits anywhere on a page and provides a fast and reliable path to the correct destination within the product. Now users can: Access any target page no matter how far it is buried from the starting point; Reduce navigation and page-load time; Improve productivity and reduce errors. The new menu design is available and widely used in all PeopleSoft 9.2 product lines.

    Read the article

  • Alternative to TOP in SQL Server and Oracle.

    SELECT TOP 5 * FROM EMP ORDER BY SALARY;above query works in SQL Server. This returns top 5 employees. The problem with this query is it doesn't work with Oracle.In Oracle you would need to write the query as follows.SELECT * FROM EMP WHERE ROWNUMIf you are looking for a query which runs in both Oracle and SQL Server. Please use below one.select * from (SELECT row_number() over( ORDER by SALARY) as rank, EMP.* FROM EMP) s1 where s1.rank span.fullpost {display:none;}

    Read the article

  • Linked List manipulation, issues retrieving data c++

    - by floatfil
    I'm trying to implement some functions to manipulate a linked list. The implementation is a template typename T and the class is 'List' which includes a 'head' pointer and also a struct: struct Node { // the node in a linked list T* data; // pointer to actual data, operations in T Node* next; // pointer to a Node }; Since it is a template, and 'T' can be any data, how do I go about checking the data of a list to see if it matches the data input into the function? The function is called 'retrieve' and takes two parameters, the data and a pointer: bool retrieve(T target, T*& ptr); // This is the prototype we need to use for the project "bool retrieve : similar to remove, but not removed from list. If there are duplicates in the list, the first one encountered is retrieved. Second parameter is unreliable if return value is false. E.g., " Employee target("duck", "donald"); success = company1.retrieve(target, oneEmployee); if (success) { cout << "Found in list: " << *oneEmployee << endl; } And the function is called like this: company4.retrieve(emp3, oneEmployee) So that when you cout *oneEmployee, you'll get the data of that pointer (in this case the data is of type Employee). (Also, this is assuming all data types have the apropriate overloaded operators) I hope this makes sense so far, but my issue is in comparing the data in the parameter and the data while going through the list. (The data types that we use all include overloads for equality operators, so oneData == twoData is valid) This is what I have so far: template <typename T> bool List<T>::retrieve(T target , T*& ptr) { List<T>::Node* dummyPtr = head; // point dummy pointer to what the list's head points to for(;;) { if (*dummyPtr->data == target) { // EDIT: it now compiles, but it breaks here and I get an Access Violation error. ptr = dummyPtr->data; // set the parameter pointer to the dummy pointer return true; // return true } else { dummyPtr = dummyPtr->next; // else, move to the next data node } } return false; } Here is the implementation for the Employee class: //-------------------------- constructor ----------------------------------- Employee::Employee(string last, string first, int id, int sal) { idNumber = (id >= 0 && id <= MAXID? id : -1); salary = (sal >= 0 ? sal : -1); lastName = last; firstName = first; } //-------------------------- destructor ------------------------------------ // Needed so that memory for strings is properly deallocated Employee::~Employee() { } //---------------------- copy constructor ----------------------------------- Employee::Employee(const Employee& E) { lastName = E.lastName; firstName = E.firstName; idNumber = E.idNumber; salary = E.salary; } //-------------------------- operator= --------------------------------------- Employee& Employee::operator=(const Employee& E) { if (&E != this) { idNumber = E.idNumber; salary = E.salary; lastName = E.lastName; firstName = E.firstName; } return *this; } //----------------------------- setData ------------------------------------ // set data from file bool Employee::setData(ifstream& inFile) { inFile >> lastName >> firstName >> idNumber >> salary; return idNumber >= 0 && idNumber <= MAXID && salary >= 0; } //------------------------------- < ---------------------------------------- // < defined by value of name bool Employee::operator<(const Employee& E) const { return lastName < E.lastName || (lastName == E.lastName && firstName < E.firstName); } //------------------------------- <= ---------------------------------------- // < defined by value of inamedNumber bool Employee::operator<=(const Employee& E) const { return *this < E || *this == E; } //------------------------------- > ---------------------------------------- // > defined by value of name bool Employee::operator>(const Employee& E) const { return lastName > E.lastName || (lastName == E.lastName && firstName > E.firstName); } //------------------------------- >= ---------------------------------------- // < defined by value of name bool Employee::operator>=(const Employee& E) const { return *this > E || *this == E; } //----------------- operator == (equality) ---------------- // if name of calling and passed object are equal, // return true, otherwise false // bool Employee::operator==(const Employee& E) const { return lastName == E.lastName && firstName == E.firstName; } //----------------- operator != (inequality) ---------------- // return opposite value of operator== bool Employee::operator!=(const Employee& E) const { return !(*this == E); } //------------------------------- << --------------------------------------- // display Employee object ostream& operator<<(ostream& output, const Employee& E) { output << setw(4) << E.idNumber << setw(7) << E.salary << " " << E.lastName << " " << E.firstName << endl; return output; } I will include a check for NULL pointer but I just want to get this working and will test it on a list that includes the data I am checking. Thanks to whoever can help and as usual, this is for a course so I don't expect or want the answer, but any tips as to what might be going wrong will help immensely!

    Read the article

  • SQL SERVER – Import CSV into Database – Transferring File Content into a Database Table using CSVexpress

    - by pinaldave
    One of the most common data integration tasks I run into is a desire to move data from a file into a database table.  Generally the user is familiar with his data, the structure of the file, and the database table, but is unfamiliar with data integration tools and therefore views this task as something that is difficult.  What these users really need is a point and click approach that minimizes the learning curve for the data integration tool.  This is what CSVexpress (www.CSVexpress.com) is all about!  It is based on expressor Studio, a data integration tool I’ve been reviewing over the last several months. With CSVexpress, moving data between data sources can be as simple as providing the database connection details, describing the structure of the incoming and outgoing data and then connecting two pre-programmed operators.   There’s no need to learn the intricacies of the data integration tool or to write code.  Let’s look at an example. Suppose I have a comma separated value data file with data similar to the following, which is a listing of terminated employees that includes their hiring and termination date, department, job description, and final salary. EMP_ID,STRT_DATE,END_DATE,JOB_ID,DEPT_ID,SALARY 102,13-JAN-93,24-JUL-98 17:00,Programmer,60,"$85,000" 101,21-SEP-89,27-OCT-93 17:00,Account Representative,110,"$65,000" 103,28-OCT-93,15-MAR-97 17:00,Account Manager,110,"$75,000" 304,17-FEB-96,19-DEC-99 17:00,Marketing,20,"$45,000" 333,24-MAR-98,31-DEC-99 17:00,Data Entry Clerk,50,"$35,000" 100,17-SEP-87,17-JUN-93 17:00,Administrative Assistant,90,"$40,000" 334,24-MAR-98,31-DEC-98 17:00,Sales Representative,80,"$40,000" 400,01-JAN-99,31-DEC-99 17:00,Sales Manager,80,"$55,000" Notice the concise format used for the date values, the fact that the termination date includes both date and time information, and that the salary is clearly identified as money by the dollar sign and digit grouping.  In moving this data to a database table I want to express the dates using a format that includes the century since it’s obvious that this listing could include employees who left the company in both the 20th and 21st centuries, and I want the salary to be stored as a decimal value without the currency symbol and grouping character.  Most data integration tools would require coding within a transformation operation to effect these changes, but not expressor Studio.  Directives for these modifications are included in the description of the incoming data. Besides starting the expressor Studio tool and opening a project, the first step is to create connection artifacts, which describe to expressor where data is stored.  For this example, two connection artifacts are required: a file connection, which encapsulates the file system location of my file; and a database connection, which encapsulates the database connection information.  With expressor Studio, I use wizards to create these artifacts. First click New Connection > File Connection in the Home tab of expressor Studio’s ribbon bar, which starts the File Connection wizard.  In the first window, I enter the path to the directory that contains the input file.  Note that the file connection artifact only specifies the file system location, not the name of the file. Then I click Next and enter a meaningful name for this connection artifact; clicking Finish closes the wizard and saves the artifact. To create the Database Connection artifact, I must know the location of, or instance name, of the target database and have the credentials of an account with sufficient privileges to write to the target table.  To use expressor Studio’s features to the fullest, this account should also have the authority to create a table. I click the New Connection > Database Connection in the Home tab of expressor Studio’s ribbon bar, which starts the Database Connection wizard.  expressor Studio includes high-performance drivers for many relational database management systems, so I can simply make a selection from the “Supplied database drivers” drop down control.  If my desired RDBMS isn’t listed, I can optionally use an existing ODBC DSN by selecting the “Existing DSN” radio button. In the following window, I enter the connection details.  With Microsoft SQL Server, I may choose to use Windows Authentication rather than rather than account credentials.  After clicking Next, I enter a meaningful name for this connection artifact and clicking Finish closes the wizard and saves the artifact. Now I create a schema artifact, which describes the structure of the file data.  When expressor reads a file, all data fields are typed as strings.  In some use cases this may be exactly what is needed and there is no need to edit the schema artifact.  But in this example, editing the schema artifact will be used to specify how the data should be transformed; that is, reformat the dates to include century designations, change the employee and job ID’s to integers, and convert the salary to a decimal value. Again a wizard is used to create the schema artifact.  I click New Schema > Delimited Schema in the Home tab of expressor Studio’s ribbon bar, which starts the Database Connection wizard.  In the first window, I click Get Data from File, which then displays a listing of the file connections in the project.  When I click on the file connection I previously created, a browse window opens to this file system location; I then select the file and click Open, which imports 10 lines from the file into the wizard. I now view the file’s content and confirm that the appropriate delimiter characters are selected in the “Field Delimiter” and “Record Delimiter” drop down controls; then I click Next. Since the input file includes a header row, I can easily indicate that fields in the file should be identified through the corresponding header value by clicking “Set All Names from Selected Row. “ Alternatively, I could enter a different identifier into the Field Details > Name text box.  I click Next and enter a meaningful name for this schema artifact; clicking Finish closes the wizard and saves the artifact. Now I open the schema artifact in the schema editor.  When I first view the schema’s content, I note that the types of all attributes in the Semantic Type (the right-hand panel) are strings and that the attribute names are the same as the field names in the data file.  To change an attribute’s name and type, I highlight the attribute and click Edit in the Attributes grouping on the Schema > Edit tab of the editor’s ribbon bar.  This opens the Edit Attribute window; I can change the attribute name and select the desired type from the “Data type” drop down control.  In this example, I change the name of each attribute to the name of the corresponding database table column (EmployeeID, StartingDate, TerminationDate, JobDescription, DepartmentID, and FinalSalary).  Then for the EmployeeID and DepartmentID attributes, I select Integer as the data type, for the StartingDate and TerminationDate attributes, I select Datetime as the data type, and for the FinalSalary attribute, I select the Decimal type. But I can do much more in the schema editor.  For the datetime attributes, I can set a constraint that ensures that the data adheres to some predetermined specifications; a starting date must be later than January 1, 1980 (the date on which the company began operations) and a termination date must be earlier than 11:59 PM on December 31, 1999.  I simply select the appropriate constraint and enter the value (1980-01-01 00:00 as the starting date and 1999-12-31 11:59 as the termination date). As a last step in setting up these datetime conversions, I edit the mapping, describing the format of each datetime type in the source file. I highlight the mapping line for the StartingDate attribute and click Edit Mapping in the Mappings grouping on the Schema > Edit tab of the editor’s ribbon bar.  This opens the Edit Mapping window in which I either enter, or select, a format that describes how the datetime values are represented in the file.  Note the use of Y01 as the syntax for the year.  This syntax is the indicator to expressor Studio to derive the century by setting any year later than 01 to the 20th century and any year before 01 to the 21st century.  As each datetime value is read from the file, the year values are transformed into century and year values. For the TerminationDate attribute, my format also indicates that the datetime value includes hours and minutes. And now to the Salary attribute. I open its mapping and in the Edit Mapping window select the Currency tab and the “Use currency” check box.  This indicates that the file data will include the dollar sign (or in Europe the Pound or Euro sign), which should be removed. And on the Grouping tab, I select the “Use grouping” checkbox and enter 3 into the “Group size” text box, a comma into the “Grouping character” text box, and a decimal point into the “Decimal separator” character text box. These entries allow the string to be properly converted into a decimal value. By making these entries into the schema that describes my input file, I’ve specified how I want the data transformed prior to writing to the database table and completely removed the requirement for coding within the data integration application itself. Assembling the data integration application is simple.  Onto the canvas I drag the Read File and Write Table operators, connecting the output of the Read File operator to the input of the Write Table operator. Next, I select the Read File operator and its Properties panel opens on the right-hand side of expressor Studio.  For each property, I can select an appropriate entry from the corresponding drop down control.  Clicking on the button to the right of the “File name” text box opens the file system location specified in the file connection artifact, allowing me to select the appropriate input file.  I indicate also that the first row in the file, the header row, should be skipped, and that any record that fails one of the datetime constraints should be skipped. I then select the Write Table operator and in its Properties panel specify the database connection, normal for the “Mode,” and the “Truncate” and “Create Missing Table” options.  If my target table does not yet exist, expressor will create the table using the information encapsulated in the schema artifact assigned to the operator. The last task needed to complete the application is to create the schema artifact used by the Write Table operator.  This is extremely easy as another wizard is capable of using the schema artifact assigned to the Read Table operator to create a schema artifact for the Write Table operator.  In the Write Table Properties panel, I click the drop down control to the right of the “Schema” property and select “New Table Schema from Upstream Output…” from the drop down menu. The wizard first displays the table description and in its second screen asks me to select the database connection artifact that specifies the RDBMS in which the target table will exist.  The wizard then connects to the RDBMS and retrieves a list of database schemas from which I make a selection.  The fourth screen gives me the opportunity to fine tune the table’s description.  In this example, I set the width of the JobDescription column to a maximum of 40 characters and select money as the type of the LastSalary column.  I also provide the name for the table. This completes development of the application.  The entire application was created through the use of wizards and the required data transformations specified through simple constraints and specifications rather than through coding.  To develop this application, I only needed a basic understanding of expressor Studio, a level of expertise that can be gained by working through a few introductory tutorials.  expressor Studio is as close to a point and click data integration tool as one could want and I urge you to try this product if you have a need to move data between files or from files to database tables. Check out CSVexpress in more detail.  It offers a few basic video tutorials and a preview of expressor Studio 3.5, which will support the reading and writing of data into Salesforce.com. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, PostADay, SQL, SQL Authority, SQL Documentation, SQL Download, SQL Query, SQL Server, SQL Tips and Tricks, SQLServer, T SQL, Technology

    Read the article

  • programming question

    - by shivam
    using System; using System.Data; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace datasynchronization { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string connectString = @"Data Source=MOON\SQL2005;Initial Catalog=databaseA;Integrated Security=True"; using (var srcCon = new SqlConnection(connectString)) //connection to source table { srcCon.Open();//source table connection open SqlCommand cmd = new SqlCommand();// sqlobject for source table cmd.Connection = srcCon; string connectionString = @"Data Source=MOON\SQL2005;Initial Catalog=databaseB;Integrated Security=True"; using (var tgtCon = new SqlConnection(connectionString)) //connection to target table { tgtCon.Open(); //target table connection open SqlCommand objcmd1 = new SqlCommand();//sqlobject for target table objcmd1.Connection = tgtCon; objcmd1.CommandText = "SELECT MAX(date) FROM Table_2"; //query to findout the max date from target table var maxdate = objcmd1.ExecuteScalar(); // store the value of max date into the variable maxdate cmd.CommandText = string.Format("SELECT id,date,name,city,salary,region FROM Table_1 where date >'{0}'", maxdate); //select query to fetch rows from source table using (var reader = cmd.ExecuteReader()) { SqlCommand objcmd = new SqlCommand(); objcmd.Connection = tgtCon; objcmd.CommandText = "INSERT INTO Table_2(id,date,name,city,salary,region)VALUES(@id,@date,@name,@city,@salary,@region)"; objcmd.Parameters.Add("@id", SqlDbType.Int); objcmd.Parameters.Add("@date", SqlDbType.DateTime); objcmd.Parameters.Add("@name", SqlDbType.NVarChar); objcmd.Parameters.Add("@city", SqlDbType.NVarChar); objcmd.Parameters.Add("@salary", SqlDbType.Int); objcmd.Parameters.Add("@region", SqlDbType.Char); while (reader.Read()) { var order1 = reader[0].ToString(); var order2 = reader[1].ToString(); var order3 = reader[2].ToString(); var order4 = reader[3].ToString(); var order5 = reader[4].ToString(); var order6 = reader[5].ToString(); objcmd.Parameters["@id"].Value = order1; objcmd.Parameters["@date"].Value = order2; objcmd.Parameters["@name"].Value = order3; objcmd.Parameters["@city"].Value = order4; objcmd.Parameters["@salary"].Value = order5; objcmd.Parameters["@region"].Value = order6; objcmd.ExecuteNonQuery(); } } tgtCon.Close(); } srcCon.Close(); } } } } how can i organize the above written code in an efficient way?

    Read the article

  • printing reverse in singly link list using pointers

    - by theoneabhinav
    i have been trying this code. i think the logic is ok but the program terminates abruptly when the display_rev function is called here is code of display_rev void display_rev(emp_node *head) { emp_node *p=head, *q; while(p->next != NULL) p=p->next; while(p!=head || p==head){ q=head; display_rec(p); while(q->next != p) q=q->next; p=q; } } here is my whole code #include<stdio.h> #include<stdlib.h> #include<ctype.h> #include<string.h> //Declarations=============================================================== typedef struct //employee record { int emp_id; char name[150]; char mob_no[11]; float salary; int proj[5]; struct emp_node *next; } emp_node; emp_node* add_rec(emp_node*); emp_node* create_db(emp_node*); emp_node* search_db(emp_node*, int); emp_node* delete_rec(emp_node*, int); void read_name(emp_node*); void read_mob(emp_node*); void display_db(emp_node*); void display_rec(emp_node*); void display_rev(emp_node*); void modify_rec(emp_node*); void swtch(emp_node*); //=========================================================================== int main() { char ans; emp_node *head = NULL; head = create_db(head); display_db(head); do { swtch(head); printf("\n\n\tDo you want to continue (y/n) : "); getchar(); scanf("%c", &ans); } while (ans == 'y' || ans == 'Y'); return 0; } //Definitions================================================================ emp_node* create_db(emp_node *head) //database creation { int i = 1, no; emp_node *p; printf("Enter number of employees:"); scanf("%d", &no); printf("\n\n"); head = (emp_node *) malloc(sizeof(emp_node)); head = add_rec(head); head->next = NULL; p = head; while (i < no) { p->next = (emp_node *) malloc(sizeof(emp_node)); p = p->next; p = add_rec(p); p->next = NULL; i++; } return head; } emp_node* add_rec(emp_node *p) //new record { int j; printf("\n\tEmployee ID : "); scanf("%d", &(p->emp_id)); printf("\n\tFirst Name:"); read_name(p); printf("\n\tMobile No.:"); read_mob(p); printf("\n\tSalary :"); scanf("%f", &(p->salary)); printf( "\n\tEnter \"1\" for the projects employee is working on, otherwise enter \"0\": \n"); for (j = 0; j < 5; j++) { printf("\n\t\tProject No. %d : ", j + 1); scanf("%d", &(p->proj[j])); while (p->proj[j] != 1 && p->proj[j] != 0) { printf("\n\nInvalid entry!! Please re-enter."); printf("\n\t\tProject No. %d : ", j + 1); scanf("%d", &(p->proj[j])); } } printf("\n\n\n"); return p; } void read_name(emp_node *p) //validation for name { int j, len; scanf("%s", p->name); len = strlen(p->name); for (j = 0; j < len; j++) { if (!isalpha(p->name[j])) { printf( "\n\n\tInvalid name!!Can contain only characters. Please Re-enter.\n"); printf("\n\tName : "); read_name(p); } } } void read_mob(emp_node *p) //validation for mobile no. { int j; scanf("%s", p->mob_no); while (strlen(p->mob_no) != 10) { printf("\n\nInvalid Mobile No!!Please Re-enter"); printf("\n\n\tMobile No.:"); read_mob(p); } for (j = 0; j < 10; j++) { if (!(48 <= p->mob_no[j] && p->mob_no[j] <= 57)) { printf( "\n\nInvalid Mobile No!!Can contain only digits. Please Re-enter."); printf("\n\n\tMobile No.:"); read_mob(p); } } } void display_db(emp_node *head) //displaying whole database { emp_node *p; p = head; printf("\n\n\t\t****** EMPLOYEE DATABASE ******\n"); printf( "\n=============================================================================="); printf("\n Id.\t Name\t\t Mobile No\t Salary\t Projects\n"); while (p != NULL) { display_rec(p); p = p->next; printf("\n\n\n"); } printf( "\n=============================================================================="); } void swtch(emp_node *head) //function for menu and switch case { int cho, x; emp_node *p; printf("\n\n\t\t****** MENU ******"); printf( "\n\n\t1. insert Record\n\t2. Search Record\n\t3. Modify Record\n\t4. Delete Record\n\t5. Display Reverse\n\t6. Exit"); printf("\n\tWhich operation do you want to perform? "); scanf("%d", &cho); switch (cho) { case 1: p=head; while(p->next != NULL) p=p->next; p->next = (emp_node *) malloc(sizeof(emp_node)); p=p->next; p = add_rec(p); p->next = NULL; display_db(head); break; case 2: printf("\n\n\tEnter employee ID whose record is to be Searched :"); scanf("%d", &x); p = search_db(head, x); if (p == NULL) printf("\n\nRecord not found."); else display_rec(p); break; case 3: printf("\n\n\tEnter employee ID whose record is to be modified :"); scanf("%d", &x); p = search_db(head, x); if (p == NULL) printf("\n\nRecord not found."); else modify_rec(p); display_db(head); break; case 4: printf("\n\n\tEnter employee ID whose record is to be deleted :"); scanf("%d", &x); head = delete_rec(head, x); display_db(head); break; case 5: display_rev(head); case 6: exit(0); default: printf("Invalid Choice!! Please try again."); } } emp_node* search_db(emp_node *head, int id) //search database { emp_node *p = head; while (p != NULL) { if (p->emp_id == id) return p; p = p->next; } return NULL; } void display_rec(emp_node *p) //display a single record { int j; printf("\n %d", p->emp_id); printf("\t %10s", p->name); printf("\t %10s", p->mob_no); printf("\t %05.2f", p->salary); printf("\t "); for (j = 0; j < 5; j++) { if (p->proj[j] == 1) printf(" %d,", j + 1); } } void modify_rec(emp_node *p) //modifying a record { int j, cho; char ch1, edt; do { printf( "\n\t1. Name\n\t2. Email Address\n\t3. Mobile No.\n\t4. Salary\n\t5. Date of birth\n\t6. Projects\n"); printf("Enter your choice : "); scanf("%d", &cho); switch (cho) { case 1: printf("\n\tPrevious name:%s", p->name); printf("\n\tDo you want to edit ? (y/n)"); getchar(); scanf("%c", &ch1); if (ch1 == 'y' || ch1 == 'Y') { printf("\n\tEnter New Name:"); read_name(p); } break; case 2: printf("\n\tPrevious Mobile No. : %s", p->mob_no); printf("\n\tDo you want to edit ? (y/n)"); getchar(); scanf("%c", &ch1); if (ch1 == 'y' || ch1 == 'Y') { printf("\n\tEnter New Mobile No. :"); read_mob(p); } break; case 3: printf("\n\tPrevious salary is : %f", p->salary); printf("\n\tDo you want to edit ? (y/n)"); getchar(); scanf("%c", &ch1); if (ch1 == 'y' || ch1 == 'Y') { printf("\n\tEnter New salary:"); scanf("%f", &(p->salary)); } break; case 4: printf("the employee is currently working on project no. "); for (j = 0; j < 5; j++) { if (p->proj[j] == 1) printf(" %d,", j + 1); } printf("\n\tDo you want to edit ? (y/n)"); getchar(); scanf("%c", &ch1); if (ch1 == 'y' || ch1 == 'Y') { printf( "\n\tEnter \"1\" for the projects employee is working on : \n"); for (j = 0; j < 5; j++) { printf("\n\t\tProject No. %d : ", j + 1); scanf("%d", &(p->proj[j])); while (p->proj[j] != 1) { printf("\n\nInvalid entry!! Please re-enter."); printf("\n\t\tProject No. %d : ", j + 1); scanf("%d", &(p->proj[j])); } } } break; default: printf("\n\nInvalid Choice!! Please Try again."); } printf("\n\nDo you want to edit any other fields ?(y/n)"); getchar(); scanf("%c", &edt); } while (edt == 'y' || edt == 'Y'); } emp_node* delete_rec(emp_node *head, int id) //physical deletion of record { emp_node *p = head, *q; if (head->emp_id == id) { head = head->next; free(p); return head; } else { q = p->next; while (q->emp_id != id) { p = p->next; q = q->next; } if (q->next == NULL) p->next = NULL; else p->next = q->next; free(q); return head; } } void display_rev(emp_node *head) { emp_node *p=head, *q; while(p->next != NULL) p=p->next; while(p!=head || p==head){ q=head; display_rec(p); while(q->next != p) q=q->next; p=q; } }

    Read the article

  • Can operator<< in derived class call another operator<< in base class in c++?

    - by ivory
    In my code, Manager is derived from Employee and each of them have an operator<< override. class Employee{ protected: int salary; int rank; public: int getSalary()const{return salary;} int getRank()const{return rank;} Employee(int s, int r):salary(s), rank(r){}; }; ostream& operator<< (ostream& out, Employee& e){ out << "Salary: " << e.getSalary() << " Rank: " << e.getRank() << endl; return out; } class Manager: public Employee{ public: Manager(int s, int r): Employee(s, r){}; }; ostream& operator<< (ostream& out, Manager& m){ out << "Manager: "; cout << (Employee)m << endl; //can not compile, how to call function of Employee? return out; } I hoped cout << (Employee)m << endl; would call ostream& operator<< (ostream& out, Employee& e), but it failed.

    Read the article

  • Unable to send '+' through AJAX post?

    - by Harish Kurup
    I am using Ajax POST method to send data, but i am not able to send '+'(operator to the server i.e if i want to send 1+ or 20k+ it will only send 1 or 20k..just wipe out '+') HTML code goes here.. <form method='post' onsubmit='return false;' action='#'> <input type='input' name='salary' id='salary' /> <input type='submit' onclick='submitVal();' /> </form> and javascript code goes here, function submitVal() { var sal=document.getElementById("salary").value; alert(sal); var request=getHttpRequest(); request.open('post','updateSal.php',false); request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); request.send("sal="+sal); if(request.readyState == 4) { alert("update"); } } function getHttpRequest() { var request=false; if(window.XMLHttpRequest) { request=new XMLHttpRequest(); } else if(window.ActiveXObject) { try { request=new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { request=new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { request=false; } } } return request; } in the function submitVal() it first alert's the salary value as it is(if 1+ then alerts 1+), but when it is posted it just post's value without '+' operator which is needed... is it any problem with query string, as the PHP backend code is working fine...

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >