vendredi 31 mars 2017

Often use a class, should I create a new one or reset its properties?

VPacket *packet;

This class 'VPacket' I use it for store specific data from tcp connection. and if I use it very often, should I create every time(1) or just change its property(2).

(1)

-(void) didReceivedData: (NSData *)data {
    if ([VPacket isVPacket: data]) {
        packet = [[VPacket alloc] packetWithData: data];
        //use it...
    }
}

(2)

-(void) didReceivedData: (NSData *)data {
    if ([VPacket isVPacket: data]) {
        packet.data = data;
        //use it...
    }
}

The class I've built need to use it like (1). I think it's much clear than (2). (for other user) But I didn't concern about speed, memory and so on.

So I want to know what's the benefits between these two solutions before the class is getting much bigger than right now.

Thanks for your time!




how i can acess to elements of arraylist

hi i want to know how i can access to elements of arraylist in java? i have this class .

class flight 
{
    public String start;
    public String end;
    public int timethatend ;
    public int timethatstart;
    flight ( int ts , int tf , String s , String e )
    {
        this.start = s;
        this.end =e;
        this.timethatend = tf;
        this.timethatstart = ts;
    }   
}

and i have this arraylist in my main class

ArrayList<flight>list = new ArrayList<flight>();

now i want print the elements of arraylist i use this syntax

System.out.println(list.get(0));

but the out put is this flight@1f96302 what should i do?




How do I to make a member variable equal another member variable which is set in main()?

Consider the following C++ code for my program: CODE

When I run this program, it outputs the following:

**Chocolate mass: 41

Chocolate density: nan**

I want the program to output the volume variable divided by the mass variable. It seems to be doing this correctly, but it is dividing the values initialized to the variables in the object class, rather than dividing the values assigned to the variables in the main() function. How do I fix this?

All help is greatly appreciated!




Correctly Writing a Range Based Constructor

I had a question to do with writing a range based constructor for a class but couldn't find the right phrasing to search for help on google.

Suppose I am writing a simple class:

// foo.h
#ifndef FOO_H
#define FOO_H

#include <iostream>

class Foo {
public:
    Foo() {
        std::cout << "Default constructor called" << std::endl;
    }
    template<class InputIterator> Foo(InputIterator first, InputIterator last) {
        std::cout << "Range based constructor called" << std::endl;
    }

    Foo(size_t first, int last) {
        std::cout << "size_t, int constructor called" << std::endl;
    }

};

#endif // FOO_H

and have a cpp file

#include <iostream>
#include "foo.h"

using std::cout;    using std::endl;

int main() {
    Foo f_default;
    Foo f_range("hello", "world");
    Foo f_int(314, 159);       // want this to call size_t, int ctctr
    return 0;
}

In the third line in main, we create a Foo f_int(314, 159) which intuitively we want to call the size_t, int constructor. However it is matching the generic template constructor for ranges instead. Is there a way issues like this are addressed in C++? I feel like I am incorrectly dealing with writing range based constructors.

I can imagine you can use template specialization maybe, but don't really see how.




failed to convert datetime and int into string

hai good day im just crteating a class registration would you like to help me please.. I have a problem of my code I don't know why it is getting an error the first error is

'Error CS1503 Argument 8: cannot convert from 'int' to 'string' from reg.age

the second is

Error CS1503 Argument 7: cannot convert from 'System.DateTime' to 'string' from reg.birthdate

that table tblUser_Registration is my entity class here is the emage enter image description here

that age and birthdate is gitteng an error that i have already assign int and datetime

 using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Data.Sql;
    using System.Data.SqlClient;


namespace database_registration
{

   public class registration
    {
        public static DataClasses1DataContext db = null;
        public static void add(tblUser_Registration reg)
        {
            db = new DataClasses1DataContext();
            db.sp_Insert(reg.username, reg.password, reg.firstname, reg.lastname, reg.middleinitial, reg.gender, reg.birthdate, reg.age, reg.address, reg.securityanswer, reg.securityquestion);


        }

but when I try to convert into the string the birthdate and age in my windows form that have been crated its look like these I'm

using System.Windows.Forms;


namespace database_registration
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string count;
        tblUser_Registration reg = new tblUser_Registration(); // I'm just Initialize the entity class tblUser_Registration so that it will call or readable all properties on this form1
        DataClasses1DataContext db = new DataClasses1DataContext();
        ErrorMassage er = new ErrorMassage();


        private void Form1_Load(object sender, EventArgs e)
        {
            dgv_Adduser.DataSource = repositories.View();
            count = dgv_Adduser.Rows.Count.ToString();


        }

        private void btn_Add_Click(object sender, EventArgs e)
        {

             int age = DateTime.Now.Year - dtp_Birthdate.Value.Year - (DateTime.Now.DayOfYear < dtp_Birthdate.Value.DayOfYear ? 1 : 0);

            if (string.IsNullOrWhiteSpace(txt_Username.Text) || string.IsNullOrWhiteSpace(txt_Password.Text) ||
                string.IsNullOrWhiteSpace(txt_FirstName.Text) || string.IsNullOrWhiteSpace(Cmb_MiddleName.Text) ||
                string.IsNullOrWhiteSpace(txt_lastname.Text) || string.IsNullOrWhiteSpace(cmb_gender.Text) ||
                string.IsNullOrWhiteSpace(dtp_Birthdate.Text) || string.IsNullOrWhiteSpace(txt_Address.Text) ||
                string.IsNullOrWhiteSpace(cmb_secuQuestion.Text) || string.IsNullOrWhiteSpace(txt_securty_answer.Text) || string.IsNullOrWhiteSpace(txt_search.Text))
            {
                er.BlankWhite();
            }

            else if (age < 0)
            {
                MessageBox.Show("Invalid age and birthYear");

            }

            else
            {
                reg.username = txt_Username.Text;
                reg.password = txt_Password.Text;
                reg.firstname = txt_FirstName.Text;
                reg.middleinitial = Cmb_MiddleName.Text;
                reg.lastname = txt_lastname.Text;
                reg.gender = cmb_gender.Text;

                reg.birthdate = Convert.ToDateTime(dtp_Birthdate);
                reg.age = Convert.ToInt32(txt_age.Text);
                reg.address = txt_Address.Text;
                reg.securityquestion = cmb_secuQuestion.Text;
                reg.securityanswer = txt_securty_answer.Text;
                repositories.add(reg);
                dgv_Adduser.DataSource = repositories.View();

                Clear();
                count = dgv_Adduser.Rows.Count.ToString();

            }


        } 




I cant compile program that uses class and list

I wrote a program that allows the user to enter 3 names, and then displays the list of the names.

I cant compile this program. The error message says "error: request for member ‘list’ in ‘input’, which is of non-class type ‘Name()’ input.list(); "

I dont understand what I did wrong.

#include <iostream>
#include<list>
#include<string>
using namespace std;

class Name
{
    std::list<string> namelist;
    public:
    Name();
    void list();
};

Name::Name()
{
    int i;
    string input[i];
    for(i=0; i<3; i++)
    {

        cout<<"Insert name: "<<input[i]<<endl;
        namelist.push_front(input[i]);
    }

}

void Name::list()
{

    for (std::list<string>::iterator NL = namelist.begin(); NL !=  namelist.end(); NL++)
    std::cout << *NL << ' ';
    std::cout << '\n';
}

int main()
{

    Name input();
    input.list();
    return 0;
}




No instance of a constructor when trying to declare a derived class from another derived class

So I have declared a class called Employee

class Employee {
protected:
    string firstName;
    string lastName;
    string jobTitle;
    int salary;
public:
    Employee(const string &, const string &,const string &, int);
    void calculateSalary(int);

    string getName() const;
    string getJobTitle() const;
    int getSalary() const;

    void print() const;

};

Employee::Employee(const string &first, const string &last, const string &title, int base) {
    firstName = first;
    lastName = last;
    jobTitle = title;
    salary = base;
}

void Employee::calculateSalary(int) {
    salary = salary;
}

string Employee::getName() const{
    return firstName + " " + lastName;
}

string Employee::getJobTitle() const{
    return jobTitle;
}

int Employee::getSalary() const{
    return salary;
}

void Employee::print() const {
    cout << "Name: " << getName() << endl;
    cout << "Job Title: " << getJobTitle() << endl;
    cout << "Salary: " << getSalary() << endl << endl;
}

I then created a derived class called TechnicalStaff like so:

class TechnicalStaff : public Employee {
private:
    int profitSharing;
public:
    TechnicalStaff(const string &, const string &, const string &, int, int);
    void calculateSalary(int, int);
    int getProfitSharing();
    void print();
};
TechnicalStaff::TechnicalStaff(const string &first, const string &last,    const string &title, int base, int profit) :
    Employee(first, last, title, base) {
    profitSharing = profit;
    calculateSalary(base, profit);
}

void TechnicalStaff::calculateSalary(int base, int profit) {
    salary = base + profit;
}


int TechnicalStaff::getProfitSharing() {
    return profitSharing;
}

void TechnicalStaff::print() {
    cout << "Name: " << getName() << endl;
    cout << "Job Title: " << getJobTitle() << endl;
    cout << "Profit Sharing: " << getProfitSharing() << endl;
    cout << "Salary: " << getSalary() << endl << endl;
}

I have tried to declare another derived class SoftwareEngineer from the previously stated TechnicalStaff class.

class SoftwareEngineer : public TechnicalStaff {
private:
    int overtimePay;
public:
    SoftwareEngineer(const string &, const string &, const string &, int, int, int);
    void calculateSalary(int, int);
    int getOvertimePay();
    void print();
};

Here is where my problems happen, I get an error saying no instance of overloaded function on the line where I decleare the constructor of the class.

How can I fix this? Any help would be great.




In C++ classes, do I only need to define static and global functions/methods or data?

I noticed pretty much everyone and in every tutorial they create the prototype for a function in the .h file, then define the rest of the class in a separate .cpp file. However, from my understanding, .h pretty much pastes the code when included in a .cpp file, but it can not have statics and globals defined inside it, so they must be defined in a .cpp file. Only defining static and global things in the .cpp file has worked so far. Am I missing something? Is this bad practice? Why are we taught by default to define every function and variable including non-static and global ones in the .cpp file?




JavaScript ES6 - Assigning methods to super

I am currently trying to figure out a way to assign methods to the super object in a class, in order to extend a functionality inside a class.

I want to create a "Component" class and have each class that extends the "Component" class have different methods depending on the component needs. I want to use the term "describe" for the method that would extend the super object. Therefore, I am describing the component.

Here is an example:

class Component {
    constructor (args) {
        this.template = args.template;
    }

    getTemplate () {
        return this.template;
    }

    describe () {
    //The magic should happen here
    }
}

Class Controller describer

class Controller {
    constructor () {

    }

    getEvents () {
        return {};
    }
}

Extending the Component class. Then, using the "describe" method to inject other methods from other classes.

class example extends Component {
    constructor () {
        super({template: '<div></div>'});
        super.describe({
            Controller
        });

        super.getTemplate();
        super.getEvents();
    }
}

var app = new App({
    example
});

Is it possible? Thank you :)




ES6: Classes: Can't get external JS class to work

Just so I'm clear, here's what I have, maybe someone can confirm.

1) ES6 Classes defined inside an HTML file work fine. let x = new glob(213); // works good

2) But total failure, once I move class glob code to an external JS and reference it with . The new glob(213); fails. Even if I Babel glob.js to create ES5 code.

Is this the current state of play with ES6 classes? I'm not using import but do have export. Or do I need to use a bundler, like Webpack, to smoosh everything into a single all.js to get external classes to work?

Rather disappointed if this is the current state of play, or am I being overly demanding. (We've been using external files use for decades.)

Thanks, from a frustrated JS coder.

INTERNAL version

<body style="font-family: sans-serif; line-height: 2">
<p id="showResults" style="font-size: 20pt;"></p>


<script>

class glob {
  constructor(mass) {
    this.mass = mass;
  }
  getMass() {
    return this.mass;
  }

}

let gg = new glob(213);
let gm = gg.getMass();

showAll  =  " ";
showAll += `glob mass =  ${gm}<br>`
document.getElementById("showResults").innerHTML = showAll;
</script>


</body>

EXTERNAL VERSION

'use strict';

class glob {
  constructor(mass) {
    this.mass = mass;
  }
  getMass() {
    return this.mass;
  }

}
export default glob;

Then in HTML

<body style="font-family: sans-serif; line-height: 2">
<p id="showResults" style="font-size: 20pt;"></p>

<script src="build/glob.js"></script>

<script>
alert(1);  //Shows
let gg = new glob(213);
alert(2);  // Never shows

And Babel

npm run babel -silent  -- --presets es2015 src/g*.js --out-dir build




How do you create objects within a function, contained within a class and determine they have the same value

Within a class, I have a few functions declared. I want to write a new function that will create five new objects. These objects can all have a variable that is either true or false. I want this function to stop running when all of these objects have the same Boolean value.

How do I do this in python 3?




Association between Player and Team

So the main idea is to have a Team with max 10 Players. Of course Player is a class and Team is a class aswell. Team basically is an Array of Player.The thing is that I want a Player to belong in a team and i want the Class Player to have a member variable which contains the Team in which the Player belongs. Additionally Player and Team are classes Defined in different files (.cpp) and its respective headers (.h)

Player.h

Class Player
{
    Team team;
    ...
}

Team.h

#include "Player.h"
Class Team
{
     Player players[10];
     ...
}

both files have guards so they cannot be defined more than 1 time




Python class information from variable

In the following code:

class species:
    def __init__(self, continent):
        self.continent=continent

giraffe = species("africa")

animal = "giraffe"

EDIT: animal is a string

can i retrieve "africa" from var "animal"?




I have a class file which does not output the result due to code segment being the wrong length

Below is the hexdump of the class file in question. I have no idea about why this code doesn't run and it gives a java.lang.ClassFormatError: Code segment has wrong length in class file fibo when running in terminal using java fibo. Does anybody with a expertise in this understand why the code length is incorrect?

ca fe ba be 00 00 00 34  00 1f 0c 00 19 00 1e 01 
00 16 28 5b 4c 6a 61 76  61 2f 6c 61 6e 67 2f 53  
74 72 69 6e 67 3b 29 56  01 00 10 6a 61 76 61 2f 
6c 61 6e 67 2f 4f 62 6a  65 63 74 01 00 06 3c 69  
6e 69 74 3e 07 00 03 0c  00 04 00 0a 07 00 13 0a  
00 07 00 1c 01 00 09 66  69 62 6f 2e 6a 61 76 61  
01 00 03 28 29 56 07 00  16 01 00 04 43 6f 64 65  
01 00 04 66 69 62 6f 01  00 04 6d 61 69 6e 01 00  
0d 53 74 61 63 6b 4d 61  70 54 61 62 6c 65 09 00 
0b 00 01 01 00 0a 53 6f  75 72 63 65 46 69 6c 65  
01 00 04 28 49 29 56 01  00 13 6a 61 76 61 2f 69  
6f 2f 50 72 69 6e 74 53  74 72 65 61 6d 01 00 07  
70 72 69 6e 74 6c 6e 0a  00 05 00 06 01 00 10 6a  
61 76 61 2f 6c 61 6e 67  2f 53 79 73 74 65 6d 01  
00 04 28 49 29 49 0c 00  1b 00 17 01 00 03 6f 75  
74 07 00 0d 01 00 09 66  69 62 6f 6e 61 63 63 69 
0c 00 14 00 12 0a 00 1a  00 18 01 00 15 4c 6a 61 
76 61 2f 69 6f 2f 50 72  69 6e 74 53 74 72 65 61  
6d 3b 00 21 00 1a 00 05  00 00 00 00 00 03 00 01  
00 04 00 0a 00 01 00 0c  00 00 00 11 00 01 00 01  
00 00 00 05 2a b7 00 15  b1 00 00 00 00 00 09 00  
0e 00 02 00 01 00 0c 00  00 00 18 00 02 00 01 00  
00 00 0c b2 00 10 10 0a  b8 00 1d b6 00 08 b1 00
00 00 00 00 09 00 1b 00  17 00 01 00 0c 00 00 00  
37 00 03 00 01 00 00 00  1b 1a 9a 00 05 03 ac 1a 
04 a0 00 05 04 ac 1a 04  64 b8 00 1d 1a 05 64 b8 
00 1d 60 ac 00 00 00 01  00 0f 00 00 00 04 00 02  
06 06 00 01 00 11 00 00  00 02 00 09 



Cannot convert from 'initializer-list' to UserController

I have this class:

class UserController
{
private:
    Repo repo;
    Repo adoption;
public:
    UserController(const Repo& r, const Repo& a) : repo(r), adoption(a) {}

    Dog get(int index) { return this->repo.get(index); };
};

When I try to create an object of type UserController, like this:

UserController controller{ repo1, repo2 };

it gives me the error: "error C2440: 'initializing' : cannot convert from 'initializer-list' to 'UserController'". Why?




Why java constructor called twice?

enter image description here

In the example below why is the protection constructor called again , as i see no mention of it , any kind of correction is most welcome




Stuck with php and oop, can not get started [on hold]

i was given an obligatory assignment and I am completely stuck. I just need help with getting started, so giving me good leads on what to do, with examples would be perfect! The assignment is as followed:

Booking of tickets online. We are looking at a small part of a system that allows a user book movie tickets online. There should be used an object oriented model to solve the task. Create a form that can receive personal information for the person who wants to book tickets. In a form the user should be able to enter a name, phone number and email address etc. Also make a list-box, for example, which lists various types of tickets. Also create a field indicating the number of tickets desired (it is not necessary that you can order several different types of tickets in the same order). Create a confirm order button that directs you to a new php page that will list out the information entered. Show the user the time and date on this page as well. Here the user should be able confirm the order information before a new confimation button is pressed. The information should then be saved to a database. If the customer wishes to cancel the booking it shall be done on this confirmation page. In addition to this, it should be possible to list out the orders that are placed using the form via a hyperlink el. Input from the form must be validated RegEx both the client (via JavaScript) and the server (PHP). It is not necessary to take into account the possibility of SQL injection beyond check with Regex. Object Model: Create a minimum of two classes, one for the customer and for the order. These will then have all the necessary attributes and methods (functions) in order to receive data from the form and store them.

All help and even any help is considered very helpful!




xlwings Python error in specifying Inputs into Classes

I am trying to input data (spot rates, and maturity) from Excel into python code using the xlwing module.

In my python file (pythonLearn.py), I have the following lines

import os
import numbers
import xlwings as xw
import datetime as dt
import numpy as np
import YieldCurve as yc


@xw.func
def py_Rate(T, spot_rate):
    yc.add_spot_rate(T, spot_rate)

In my class module file (YieldCurve.py), I have the following code

import math

class ForwardRates(object): # create a bootstrap yieldcurve

    def __init__(self):
        self.forward_rates = []
        self.spot_rates = dict()

    def add_spot_rate(self, T, spot_rate):
        self.spot_rates[T] = spot_rate

    def __calculate_forward_rate___(self, T1, T2):
        R1 = self.spot_rates[T1]
        R2 = self.spot_rates[T2]
        forward_rate = (R2*T2 - R1*T1)/(T2 - T1)
        return forward_rate

    def get_forward_rates(self):
        periods = sorted(self.spot_rates.keys())
        for T2, T1 in zip(periods, periods[1:]):
            forward_rate = self.__calculate_forward_rate___(T1, T2)
            self.forward_rates.append(forward_rate)
        return self.forward_rates

When I try to add spot rates with the command (in Excel), '= py_Rate(1.0, 10.5); I get the following error

AttributeError: 'module' object has no attribute 'add_spot_rate' fr.add_spot_rate(T, spot_rate) File "c:\users\admin\documents\pythonlearning\pythonLearningExcel5.py", line 155, in py_Rate ret = func(*args) File "C:\Python34\lib\site-ckages\xlwings\udfs.py", ine 250, in call_udf res = call_udf(script, fname, args, this_workbook, FromVariant(caller)) File "C:\Python34\lib\site-packages\xlwings\server.py", line 190, in CallUDF return func(*args) File "C:\Python34\lib\site-packages\win32com\server\policy.py", line 586, in invokeex return S_OK, -1, self.invokeex(dispid, lcid, wFlags, args, None, None) File "C:\Python34\lib\site-packages\win32com\server\policy.py", line 283, in invoke return self.invoke(dispid, lcid, wFlags, args) File "C:\Python34\lib\site-packages\win32com\server\policy.py", line 278, in Invoke

Any xlwings/python (3.4 is my version, by-the-way) who can help?

Kind regards




Create instances of dynamically given classes in Java

I need a function to create instances of a dynamically given class in java.

I had found many samples but in all of them, the class to be instantiated was known before runtime.

There are user defined classes:

class Student { //some code }
class Teacher { //some code }
class Course { //some code }

What I need is

List<class> MyFunction(<class>) {

  List<class> items = new ArrayList<class>();

  for(int i = 0; i < 5; i++) {

    create_a_new_class_instance;

    items.add(new_created_instance);
  }

  return items;

}

How will I use

List<Student> students = MyFunction(Student);
List<Teacher> teachers = MyFunction(Teacher);
List<Course> courses = MyFunction(Course);

Hope someone helps.

This is my first question in Stackoverflow, sorry for any inconvenience.

Utku




Get Values to the Array Angular 2

I have Admin.ts Class

        export class AdminValues{

          nameAd:String;
          email_addr:String;
          passwrd:String;


           constructor(adminName:String,adminEmail:String,adminPassword:String){

            this.nameAd=adminName;
            this.email_addr=adminEmail;
            this.passwrd=adminPassword;
          }

} 

I am completely new to the Angular 2.i have create admin form (AdminForm Component)to get input.i want create Angular 2 service to add new admins to the Admin Type Array .How should i do that?




Custom variable field to python log record

I am trying to add a custom format field in my library. I know this is either done with a Filter or a LoggerAdapter object. However, in the examples I have seen (like this one: How do I add custom field to Python log format string?) the custom field they want to generate is static and known when the logger is created.

I need to be able to send a variable to my log record that I really don't know until just before I write the log record. I guess I am just not seeing the solution but how best to accomplish this?

Currently I set up my logger this way:

import logging

class MyClass:
    filehandler = logging.handlers.RotatingRileHandler(r'C:\Users\Me\Desktop\Logs', 
            maxBytes=1000000, backupCount=4, encoding='ASCII')
    formatter = logging.Formatter('[%(asctime)s] : %(levelname)-8s: Para: %(parameter)-15s'
                                  ' - %(message)s')
    # parameter is my custom name I want to inject
    self.logger = logging.getLogger(__name__)
    self.logger.setLevel(logging.DEBUG)
    self.logger.addHandler(file_handler)

    d = {'parameter': ''}
    self.logger = logging.LoggerAdapter(self.logger, extra=d)

And in my test I write:

my_obj = MyClass()
my_obj.logger.error('This is my error.', extra={'parameter': 'True'}

but this makes the parameter field '' (blank string) always. Is there a way to set up the d dictionary for each time I make the log call (error(), debug(), etc.)?




PHP Undefined offset: 0 Error

<?php
class data_download{
     public $content; 
     function data_download_() { 
           $this->content = file_get_contents('http://ift.tt/1jXKT14'); 
            return $this->content;
      }
      function search($start, $end, $text) {
           @preg_match_all('/' . preg_quote($start, '/') . '(.*?)' . preg_quote($end, '/') . '/i', $text, $m); 
           return @$m[1];
     }
}
$d_download = new data_download();
$printer = $d_download->search('title>"', '</title>', $d_download->content); 
print_r($printer[0]); ;
 ?>

I wrote a bot service with php but it gives the following error. What is the reason?

E_NOTICE : type 8 -- Undefined offset: 0 -- at line 12




What is it called when you have a file whose entire functionality is imported from different classes in different files?

I have 3 command files: cmdA.py, cmdB.py, and cmdC.py that all contain a corresponding class with functions.

cmdA.py has a class called cmdA which contains a handful of functions.

#cmdA.py

class cmdA:
        def parse_cmdA:
            #code

        def union_cmdA:
            #code

        def read_cmdA:
            #code

        def write_cmdA:
            #code

The same formatting applies to cmdB.py and cmdC.py

I have 2 device files whose functionalities will consist of a combination of those command files.

device1.py imports cmdA and cmdC giving it its unique functionality.

device2.py imports cmdA and cmdB to give it it's unique functionality.

#device1.py

from cmdA import cmdA
from cmdC import cmdC

class device1:
        def __init__(<params>):
            containMethods(self,cmdA(self))
            contianMethods(self, cmdC(self))

When testing device1, it will only accept and run commands from cmdA and cmdC. It will not accept and run commands from cmdB. The same concept applies to device2.

What is this system called?

I like this idea of defining specific functionalities within it's own class files so that I can create a variety of devices that can share certain functions without me having to redefine those functions multiple times. I just don't know the technical term for it.




Can I access a class without an __init__? - Python

I want to be able to print "hello harry" from a module. This is my module (called test23):

class tool:

    def handle(self,name):
        self.name = "hello " + name

This is my script:

import test23

harry= test23.tool().handle(" harry")
print harry.name

I can't seem to print "hello harry" inside my script idle. How would I go about doing this?




Initializing Class Properties In Swift

So I'm trying to create a Playground that functions as a 'presentation', meaning that I have multiple slides and it's interactive-ish. I'm new to Swift, so would really use some help.

This is my main code

import UIKit
import SpriteKit
import PlaygroundSupport

let frame = CGRect(x: 0, y: 0, width: 640, height: 480)

let view = SKView(frame: frame)
view.showsDrawCount = true
view.showsNodeCount = true
view.showsFPS = true

let scene = MainScene(size: CGSize(width: 640, height: 480))
view.presentScene(scene) //error here, explained below
PlaygroundPage.current.liveView = view

This is my MainScene.swift code -

import UIKit
import SpriteKit
import PlaygroundSupport

public class Slide: SKView {

    public var title: SKLabelNode!
    public var info: UITextView!

    public func setter() {

        self.title = SKLabelNode(fontNamed: "Chalkduster")
        self.title.verticalAlignmentMode = .center
        self.title.color = SKColor.white
        self.title.position = CGPoint(x: frame.midX, y: 440)

        let framer = CGRect(x: 40, y: 60, width: 560, height: 360)

        self.info = UITextView(frame: framer)
        self.info.font = UIFont(name: "Chalkduster", size: 20)
        self.info.textAlignment = .center
        self.info.textColor = UIColor.white
        self.info.backgroundColor = UIColor.black
    }


}

public class MainScene: SKScene {

    public var button1 = SKSpriteNode(imageNamed: "Next")
    public var button2 = SKSpriteNode(imageNamed: "Previous")

    public var scene1: Slide?

    public override func didMove(to view: SKView) {

        backgroundColor = SKColor.black
        scene1?.setter()
        setScene1()
    }

    public func setScene1() {

        scene1?.title = SKLabelNode(fontNamed: "Chalkduster")
        scene1?.title.text = "Title."
        scene1?.title.position = CGPoint(x: frame.midX, y: frame.midY)
        scene1?.info.text = "Text."

        addChild(title)
        addButtons()
    }

    public func addButtons() {

        self.button1.position = CGPoint(x: 600, y: 40)
        self.button2.position = CGPoint(x: 40, y: 40)
        addChild(self.button1)
        addChild(self.button2)
    }

}

Basically, I was tying to setup multiple slides through functions that would change the previous slide's title/info. However, I thought it would be much better to have an SKView class defined for my slides in order to use SKTransition.

However, with my current code, I'm running into an execution interrupted error. Also, when I change stuff around, the error kind of followed me into either Expected Declaration or no Class Initializers for MainScene.swift.

Really, I just want to fix up my declaration of the class Slide and then use that class to make multiple slides.




Is there any issue sharing class member on either both of doInBackground and onPostExecute of AsyncTask of android?

The following is my example code.

private class PostLikes extends AsyncTask<Integer, Void, Void> {
 String type_id, msg;

 @Override
 protected Void doInBackground(Integer... params) {
//....
//....
  type_id = jsonobject2.getString("type_id");
  msg = jsonobject2.getString("msg");
  return null;
 }

 @Override
 protected void onPostExecute(Void result) {
  if (type_id.equals("1")) {
    Toast.makeText(getApplicationContext(), "error, Toast.LENGTH_SHORT).show();
  } else {
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
  }
 }

}

The standard way of using AsyncTask is to make doInBackground function return some result of the background thread to onPostExecute function. That code is working well but I want to know whether any issue exist in the above code. Thanks.




class httpresponse results in 405 - django

I am new to django and I am trying to understand class views.

In urls.py (main) I have:

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('webapp.urls')),
]

in webapp folder I have:

urls.py (webapp):

from django.conf.urls import url
from webapp.views import Firstapp

urlpatterns = [
    url(r'^whatever$', Firstapp.as_view()),

]

views.py (webapp):

from django.shortcuts import render
from django.views import View
from django.http import HttpResponse

class Firstapp(View):

    def something(self):
        return HttpResponse('Yes it works!')

As I have said, I am trying to use class views and I would appreciate if you could help me understand why class returns 405 error. Thank you. CMD returns 0 problems.




how pass parameter to php class by class()::function()

How pass parameter to PHP class by class()::function()?

class greenHouse{
    public function __construct(connection $con){
    }

    public function show(){
    }

}

$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass::$namefunction();

works

$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass($con)::$namefunction();

doesn't work

I want to pass a parameter to the class with $nameclass($con)::$namefunction();. How do I do that in PHP?




Access to functions from extended classes

I have a parent class and two classes that are extending it. The question is how to call a function from one extended class that is in other extended class?

code is below:

    // PARENT CLASS
class Controller {
    function __construct() {
        try {
            $this->db = new Database(); // WORKS FINE
        } catch (PDOException $e) {
            die('Database connection could not be established.');
        }
    }
}
class Api extends Controller { 
    function __construct() {
        parent::__construct();
    }
    function RenderForm() { 
        // from here I want to call function that is inside Forms class
    }
}

class Forms extends Controller { 
    function __construct() {
        parent::__construct();
    }
    function ReturnForm() { 
        $this->db->query("SOME QUERY");

        // code here builds a form for output and stores it as $HTML;

        return $HTML;

    }
}




CSS - Trying to apply styling to a class within a class within a modal popup

EDIT: I have still not found a solution however i have managed to avoid the issue entirely. If someone know why this doesn't work it would be incredibly helpful so i know for the future. Thank you

-

I can't seem to get this to work and i've tried searching everywhere for an answer.

This is the gist of it (all nested within a modalPopup Panel.

<div class="body">                
<div>
     <div class="left">
         <asp:Label runat="server" Text="Name:" />
    </div>
     <div class="right">
         <asp:TextBox runat="server" ID="txtName" Text="" />
     </div>
</div>

Also i should add that i can add styles to the body class with no issue.

I have tried these in CSS:

.modalPopup .body.left {}

.modalPopup .body .left {}

.modalPopup .body > left {}

.modalPopUp .body > .left {}

And the same for the right class.

Am i missing something incredibly obvious?

I can give you more code/information if needed feel free to ask away.

Thank you in advance.

EDIT:

Here is all the Code

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="smsBatchUI.Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolKit" %>


<!DOCTYPE html>
<link href="modalpopup.css" rel="stylesheet" />
<html xmlns="http://ift.tt/lH0Osb">
<head runat="server">
    <script src="http://ift.tt/2ks3P0N"></script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <div>
            <asp:Button ID="Button2" Text="Pop Up" runat="server" style="display:none" />
            <ajaxToolKit:ModalPopupExtender TargetControlID="Button2" ID="mp1" runat="server" PopupControlID="Panel1"
                    CancelControlID="ButtonCancel" BackgroundCssClass="modalBackground">
            </ajaxToolKit:ModalPopupExtender>
            <asp:Panel ID="Panel1" runat="server" style="display:normal" align="center" CssClass="modalPopup">
                <div class="header">
                    <header>
                        Batch SMS Messaging
                    </header>
                </div>
                <div class="body">
                    <asp:CheckBox ID="chkVerify" runat="server" style="display:none" Checked="false" AutoPostBack="true" /><br />

                    <div>
                        <div class="left">
                            <asp:Label runat="server" Text="Name:" />
                        </div>
                        <div class="right">
                            <asp:TextBox runat="server" ID="txtName" Text="" />
                        </div>
                    </div>

                    <div>
                        <div class="left">
                            <asp:Label runat="server" Text="Number:" />
                        </div>
                        <div class="right">
                            <asp:TextBox runat="server" ID="txtNo" />
                        </div>
                    </div>

                    <div>
                        <div class="left">
                            <asp:Label runat="server" Text="Message:  " />
                        </div>
                        <div class="right">
                            <asp:TextBox runat="server" ID="txtMessage" />
                        </div>
                    </div>

                    <div>
                        <div class="left">
                            <asp:Label runat="server" Text="Template: " />
                        </div>
                        <div class="right">
                            <asp:DropDownList runat="server" Width="200px" ID="ddlTemplate">
                                <asp:ListItem Text="Select Template" Value="DefaultValue"></asp:ListItem>
                                <asp:ListItem Text="HR" Value="HR"></asp:ListItem>
                                <asp:ListItem Text="CT" Value="CT"></asp:ListItem>
                                <asp:ListItem Text="IT" Value="IT"></asp:ListItem>
                            </asp:DropDownList>
                        </div>
                    </div>

                    <div>
                        <div class="left">
                            <asp:Label runat="server" Text="Send Date: " />
                        </div>
                        <div class="right">
                            <asp:TextBox runat="server" ID="txtDate" Text="YYYY-MM-DD" /><asp:Label runat="server" Text="(YYYY-MM-DD)" Font-Size="10px" />
                        </div>
                    </div>


                    <asp:Label runat="server" Text="Preview" style="padding-top: 0px" /> 
                    <br />
                    <asp:TextBox runat="server"  Height="150px" Width="300px" ID="txtPreview" Text="Click Preview to see your message before you Submit it." TextMode="MultiLine" /> <br />
                </div>
                <div class="footer">
                    <asp:Button runat="server" Text="Preview" ID="btnPreview" OnClientClick="Preview();" />
                    <asp:Button runat="server" Text="Submit" ID="btnSubmit" OnClick="btnSubmit_Click" OnClientClick="Validate()" /> <br />
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                    <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="btnUpload_Click" /> <br /> <br />
                    <asp:Button ID="ButtonCancel" runat="server" Text="Close" />
                </div>
            </asp:Panel>
        </div>
    </form>
</body>
</html>

And the CSS:

body { color: #373d3f; }
.modalBackground
    {
        background-color: floralwhite;
        filter: alpha(opacity=60);
        opacity: 0.6;
    }
.modalPopup
    {
        background-color: #E8ECED;
        width: 400px;
        border:1px solid #666666;
        border-radius: 12px;
        padding:0
    }
.modalPopup .header
    {
        background-color: #014B96;
        height: 30px;
        color: White;
        line-height: 30px;
        text-align: center;
        font-weight: bold;
        border-top-left-radius: 8px;
        border-top-right-radius: 8px;
        font-family: Helvetica, Arial;
    }
.modalPopup .body
    {
        min-height: 50px;
        line-height: 30px;
        text-align: center;
        font-weight: bold;
        padding-left: 10px;
        padding-right: 10px;
        font-family: Helvetica, Arial;
        display: inline-block;
    }
.modalPopup > .body > .left
    {
        width: 30%;
        float: left;
        text-align: right;
    }
.modalPopup > .body >.right
    {
        width: 65%;
        margin-left: 10px;
        float:left;
    }
.modalPopup .buttonalignleft
    {
        text-align: left;
    }
.modalPopup .footer
    {
        padding: 6px;
    }




Field with extension .class in java classes

I have such question. I know that I can use name of class with extension class in my classes/methods. For example I can write such mock

MyClass myClass = Mockito.mock(MyClass.class, Mockito.CALLS_REAL_METHODS);

But I never crated in my class MyClass any field called like that.

Could someone please explain why I could reference MyClass.class, how it called correctly, where it is created and preferably with link to the source where I could read about this.

Thanks.




Python Multiple Classes Error in Calling specific class

I am a newbie, and picking up Python (3.4) and trying to work on classes.

I have created a module BootstrapYieldCurve, with two classes (BootstrapYieldCurve and ForwardRates) inside.

When I import the module, I can call and manipulate the BootstrapYieldCurve class, but I get an error from calling the ForwardRates class.

Would someone be able to advise if the code is wrong, or the way I call the class in Python Shell?

>>> from BootstrapYieldCurve import ForwardRates
>>> Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    from BootstrapYieldCurve import ForwardRates
ImportError: cannot import name 'ForwardRates'

This is my module code structure

import math

class BootstrapYieldCurve():
    def __init__(self):
    def add_instrument(..........):
    ..........
class ForwardRates():
    def .........




Unable to dinamically create objects from MongoDB results in Python 3.5.2

I'm pretty new to Python even though I have some OOP experience from working with PHP in the past.

I'm trying to create a module that will query mongoDB and create objects in a dictionary for every document it gets back from the db. The documents data will generate entries in the object's attributes dictionary.

#!/usr/bin/python3
from django.db import models
from pymongo import MongoClient

# abstract Class() blueprint
class Clase():
    attributes = {}

mongodb_connection = MongoClient('mongodb://localhost:27017/')
bi_db = mongodb_connection['bi']
sales_collection = bi_db['sales_data_it']
documents = sales_collection.find( {} )
print ('Documents: %d' % documents.count())

# Create instances from mongoDB documents
instance_dict = {}
i = 0
for result in documents:
    print('+++++++++++++++++++++++++++++')
    print('creating instance[%d]' % i)  
    instance_dict[i] = Clase()  # create an object in instance_dict for each result

    for key, value in result.items() : # for every result log key,values into attributes dictionary
        print(result)
        instance_dict[i].attributes[key] = value
        print(key, ' = ', value, i)
    i += 1

# print ('Instances Created: %d' % len(instance_dict.keys()))
print('-------------INSTANCE 0--------------------')
print(instance_dict[0].attributes)
print('-------------INSTANCE 1--------------------')
print(instance_dict[1].attributes)

My test database contains only 2 documents and the logic appears to work when debugging this code using the print() function. However, when reading the created objects attributes I see that they both contain the data for the second document instead of each containing the data for their respective document. Not sure if that made sense. Here's the output from my terminal when running this script:

root@django:~/Desktop/scripts# ./test.py 
Documents: 2
+++++++++++++++++++++++++++++
creating instance[0]
Members  =  ['Marco Ravaglia', 'Mattia Castelluccia', 'Alberto Ballerini'] 0
_id  =  58d8e4492b9afb1045503665 0
Performance  =  0.85 0
Team Name  =  NCA-Milan 0
+++++++++++++++++++++++++++++
creating instance[1]
Team Leader  =  Isidoro De Pascale 1
Members  =  ['Marinka Piacente', 'Luca Lo Monaco', 'Matteo Ferri'] 1
_id  =  58d8e4492b9afb1045503666 1
Team Name  =  NCA-Napoli 1
-------------INSTANCE 0--------------------
{'Team Leader': 'Isidoro De Pascale', 'Members': ['Marinka Piacente', 'Luca Lo Monaco', 'Matteo Ferri'], '_id': ObjectId('58d8e4492b9afb1045503666'), 'Performance': '0.85', 'Team Name': 'NCA-Napoli'}
-------------INSTANCE 1--------------------
{'Team Leader': 'Isidoro De Pascale', 'Members': ['Marinka Piacente', 'Luca Lo Monaco', 'Matteo Ferri'], '_id': ObjectId('58d8e4492b9afb1045503666'), 'Performance': '0.85', 'Team Name': 'NCA-Napoli'}

As you can see both instances contain the same data. I dont understand why... Sorry if this has been asked before but I've looked for an answer to this problem without success. I've also made my best to debug the problem but I just can't get to the bottom of it. I'm going crazy so any help would be greatly appreciated.

Thanks in advance!!!




how to cast up to super class when there is an override function in the sub class

A super-class Car and a sub-class Jaguar was created. The function info() -> Void in the sub-class overrided the super-class function. A instance named theAuto of type Jaguar had been created.

Problem:

Seems I cannot up cased the theAuto to the type of Car, please see the code snippet and its comments

class Car {
        func info() {
                print("You've got a car")
        }
}

class Jaguar : Car {
       override func info() {
               print("You've got a Jaguar")
       }
}

let theAuto = Jaguar()
theAuto.info() // --> You've got a Jaguar
let Auto = theAuto as Car // casting but seems not working 
Auto.info() // --> You've got a Jaguar
print(type(of: Auto)) // fail to casting

Question:

I think I didn't fully understand the concept of casting together with override scenario. Why I cannot make the up casting? Is the override action limited my upper casting?

many thanks for your help and time




python error where __str__ returns a NoneType

class Pixel:
  """Representing a 'pixel' aka one character on the screen
  is mostly gonne be used in Map using a tuple location and a
  character that can be changed"""

  def __init__(self, char='#', location=(0,0)):
    assert type(char) == str
    assert type(location[0]) == int and type(location[1]) == int
    self.location = location
    self.x = self.location[0]
    self.y = self.location[1]
    self.char = char

  def __str__(self):
    return(self.char)



class Map:
  """Representing a map by having diffferent characters
  on different lines and being able to manipulate the 
  characters, thus playing a game"""

  def __init__(self, file=None):
    self.pixels = {}
    if not file:
      self.rows = 3
      self.colls = 3
      for r in range(self.rows):
        for c in range(self.colls):
          self.pixels[(r, c)] = Pixel('#', (r, c))

  def __str__(self):
    print(self.pixels)
    for c in range(self.colls):
      print('')
      for r in range(self.rows):
        print(self.pixels[(r, c)], end='')





a = Map()
print(a)

I am trying to make a class that defines a grid where each place in the grid has a character, but when I run the code I get an error that tells me that __str__ returns a NoneType. I know I am not yet handeling file imput when initiating Map but that isn't the problem here, here is the output I got.

{(0, 1): <__main__.Pixel object at 0x7f31612a3080>,
 (1, 2): <__main__.Pixel object at 0x7f31612a3470>,
 (0, 0): <__main__.Pixel object at 0x7f31612a3048>,
 (2, 0): <__main__.Pixel object at 0x7f31612a34a8>,
 (1, 0): <__main__.Pixel object at 0x7f31612a32b0>,
 (2, 2): <__main__.Pixel object at 0x7f31612a3390>,
 (0, 2): <__main__.Pixel object at 0x7f31612a30b8>,
 (2, 1): <__main__.Pixel object at 0x7f31612a3358>,
 (1, 1): <__main__.Pixel object at 0x7f31612a32e8>}

###
###
###Traceback (most recent call last):
  File "main.py", line 45, in <module>
    print(a)
TypeError: __str__ returned non-string (type NoneType)
exited with non-zero status

what am I missing?




Access subclass type from its superclasses function

Is there a way to have a function in a superclass, that can (when called through a subclass) access said subclasses type?

I want a universal info() in my masterclass that can be called an give information about the type of the subclass.




How and where should I use the keyword "use" in php

I used use the keyword "use" generally above the class definition. Like this:

<?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;
use \Codeception\Specify;

class agpaypalTest extends \Codeception\Test\Unit
{
    protected $tester;
    ...

But now I realised, that I have to put the line for the trait Specify into the class definition. Like this:

 <?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;

class agpaypalTest extends \Codeception\Test\Unit
{
    use \Codeception\Specify;

    protected $tester;
    ...

I think it is because the package \Codeception\Specify; is a trait. But I do not understand why I couldn't reuse this trait when I set the line use \Codeception\Specify; before the class definition?

I would be happy if someone could point me to a hint or an explanaiton that explains to me where I should use the keyword "use" the best.




JSON to XML class conversions

I cannot seem to line up the class of the Json into Linq XML.

The c.first, c.second and the c.third are highlighted and states:

"Are you missing a using directive or assembly reference."

        var serializer = new JavaScriptSerializer();
        var json1 = "[count:[place:{first:1,second:2,third:3}],[place:{first:11,second:22,third:33}],[place:{first:111,second:222,third:333}]]]";
        var jsons = serializer.Serialize(json1);
        var jsona = serializer.Deserialize<List<jClass>>(jsons);
        var xmld = new XDocument(
            new XElement("count", jsona.Select(c =>
                new XElement("place",
                    new XElement("first", c.first),
                    new XElement("second", c.second),
                    new XElement("third", c.third)
                )
            ))
        );

Class.cs

public class jClass
{
    public jNumber[] count { get; set; }
}
public class jNumber
{
    public jTopThree[] place { get; set; }
}
public class jTopThree
{
    public int first { get; set; }
    public int second { get; set; }
    public int third { get; set; }
}




Can I define and use functions outside classes and pass objects to them?

This is what I implemented:-

class point {
public:
    int x;
    int y;
    void setdata(int a,int b){
        x=a;
        y=b;
    }
};

bool issame(point ph, point p1, point p2){
if((p1.y - p2.y)/(p1.x - p2.x) == (ph.y - p2.y)/(ph.x - p2.x)){
    return true;
} 
else return false;
}

But values of ph,p1,p2 are not passing to issame()




Silex with Doctrine and PHP classes

So, I'm trying to get around in Silex. Just learn the way it works and I'm trying to use Doctrine in it. I can use it on the index.php, but I'd also like to use it in my classes. These lines are used in the normal root file (index.php):

$images = $app['db']->prepare("SELECT * FROM images");
$images->execute();

$images = $images->fetchAll(\PDO::FETCH_CLASS, \AI\Models\Image::class);

So that would give me the ability to do something with the images. But I don't want to work this way. I'd like classes to do it all for me, so that I just script some methods which do all the hard work for me. That would let me just run one line for each Route in index.php

The problem is that I don't know how to connect with Doctrine from inside my classes. Because there is no '$app' in there. I think it would be weird to start the app inside of a class.

So let's say I wanted to create a user class. This SQL would give me all the users: "SELECT * FROM users". But how would I use Doctrine inside the User class?

<?php

namespace Models;

class User {

    public function find($user){
        if($user) {
            $field = (is_numeric($user)) ? 'id' : 'username';

            $sql = "SELECT * FROM users";

            $data = // RUN QUERY $SQL 
            if($data->count()) {
                $this->_data = $data->all();
                return true;
            }
        }
        return false;
    }

}




Programatically fire crossbrowser html input type image click event with the help of webbrowser control

how to call a html image button clicik not by clicking on html image but by calling the click method in your code.

this is my html image type now i want to call a click by my code that is written in my class file.First of all i load all the html element of the particular page (this is the login page) .Now i want to fire a button from my class file.With the help of web browser element i load all the contents of this page and done the following things..

Console.WriteLine(wb.Document.Body.InnerHtml);

HtmlDocument doc = wb.Document;

HtmlElement username = doc.GetElementById("CphPageMiddle_txtUserID");

HtmlElement password = doc.GetElementById("CphPageMiddle_txtPassword");

NOW I SET ATTRIBUTES TO USERNAME AND PASSWORD

username.SetAttribute("value", "ID");

password.SetAttribute("value", "PWD");

NOW I WANT TO KNOW HOW I CAN FIRE THE ABOVE HTML INPUT TYPE IMAGE

AND AFTER FIRE THE HTML ELEMENT GO TO THE RESPECTIVE PAGE.

HERE IS MY FULL CODE GIVEN BELOW-

class Program {

private static bool completed = false;

private static WebBrowser wb;

[STAThread]

static void Main(string[] args)

{

wb = new WebBrowser();

wb.DocumentCompleted += new

WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);

//wb.Navigate("http://ift.tt/2npDSiY");

wb.Navigate(@"www.example.com");

while (!completed)

{

Application.DoEvents();

Thread.Sleep(100);

}

Console.Write("\n\nDone with it!\n\n");

Console.ReadLine();

}

static void wb_DocumentCompleted(object sender,

WebBrowserDocumentCompletedEventArgs e)

{ try {

if (!completed)

{

Console.WriteLine(wb.Document.Body.InnerHtml);

HtmlDocument doc = wb.Document;

HtmlElement username = doc.GetElementById("CphPageMiddle_txtUserID");

HtmlElement password = doc.GetElementById("CphPageMiddle_txtPassword");

// HtmlElement submit = doc.get("btnLogin");

username.SetAttribute("value", "ID");

password.SetAttribute("value", "PWD");

// submit.InvokeMember("click");

//after click on login button return to main page by navigate to the main page here.....

wb = new WebBrowser();

wb.DocumentCompleted += new

WebBrowserDocumentCompletedEventHandler(wb_DocumentCompletedlanding);

wb.Navigate(@"http://ift.tt/2mUQvGN");

if (wb.Url.ToString().IndexOf("LandingPage.aspx") > -1)

{

completed = false;

while(!completed)

{

Application.DoEvents();

Thread.Sleep(100);

}

}

Console.WriteLine();

completed = true;

}

}

catch(Exception ex)

{

throw ex;

}

}

static void wb_DocumentCompletedlanding(object sender,

WebBrowserDocumentCompletedEventArgs e)

{ try

{

if (!completed)

{

Console.WriteLine(wb.Document.Body.InnerHtml);

}

}

catch (Exception ex)

{

throw ex;

}

}

}

Any help will be greatly appreciated.Please give me the needfull help.Thanks.




Getting Link Error 2005..Cant figure out why

Im just trying to create a basic class but I'm getting link error 2005.

Here is my class defintion:

Employee.h

#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <iostream>
#include <string>
using namespace std;

class Employee {
private:
    string firstName;
    string lastName;
    string jobTitle;
    float baseSalary;
    float salary;
public:
    Employee(const string &, const string &,const string &, float);
    void calculateSalary(float);

    string getName() const;
    string getJobTitle() const;
    float getSalary() const;

    void print() const;

};
#endif

Employee.cpp

#include <iostream>
#include <string>

using namespace std;

#include "Employee.h"

Employee::Employee(const string &first, const string &last, const string &title, float base) {
    firstName = first;
    lastName = last;
    jobTitle = title;
    baseSalary = base;
}

void Employee::calculateSalary(float baseSalary) {
    salary = baseSalary;
}

string Employee::getName() const{
    return firstName + " " + lastName;
}

string Employee::getJobTitle() const{
    return jobTitle;
}

float Employee::getSalary() const{
    return salary;
}

void Employee::print() const {
    cout << "Name: " << firstName << " " << lastName << endl;
    cout << "Job Title: " << jobTitle << endl;
    cout << "Salary: " << salary << endl;
}

I feel like this is something obvious but cannot figure it out. I have rewrote the class multiple times.

Here are my errors:

Error   LNK2005 "public: void __thiscall Employee::calculateSalary(float)" (?calculateSalary@Employee@@QAEXM@Z) already defined in Employee.obj Lab 8 (2)   C:\Users\Zack Sloan\documents\visual studio 2017\Projects\Lab 8 (2)\Lab 8 (2)\Source.obj    1   
Error   LNK2005 "public: float __thiscall Employee::getSalary(void)const " (?getSalary@Employee@@QBEMXZ) already defined in Employee.obj    Lab 8 (2)   C:\Users\Zack Sloan\documents\visual studio 2017\Projects\Lab 8 (2)\Lab 8 (2)\Source.obj    1
Error   LNK2005 "public: void __thiscall Employee::print(void)const " (?print@Employee@@QBEXXZ) already defined in Employee.obj Lab 8 (2)   C:\Users\Zack Sloan\documents\visual studio 2017\Projects\Lab 8 (2)\Lab 8 (2)\Source.obj    1




jeudi 30 mars 2017

how to send data rapidly between a service and an activty

how can i send data from a service to an activity if that activity is running without restarting service or activity. actually i have a Asynctask class inside my service that downloads a file and i wanna show the percentage of downloading on a Progress-bar inside an activity . can any one tell me how should i do that? i tried interface in asynctask but it make a new request and my progress bar is null.

public class Downloader extends AsyncTask<Combine,String,Combine> {
Responcer1 responder;
HttpURLConnection connection;
int id;
int position;


public Downloader(int position){
    this.position=position;
}
@Override
protected void onPreExecute() {
    super.onPreExecute();

    responder=new SavedLinks();
    responder.start(position);
}

@Override
protected Combine doInBackground(Combine... param) {

    try {
        int position=param[0].position;
        Log.i("downloader",param[0].caption+param[0].link+param[0].url+param[0].user);
        id=param[0].id;

        connection = null;
        URL url;
        url = new URL(param[0].link);
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(45000);
        connection.setReadTimeout(5000);
        InputStream in = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");}
        in.close();
        connection.disconnect();
        return saperate(sb.toString(),param[0]);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }}

}




How can I compare two objects with different constructors [duplicate]

This question already has an answer here:

First time really dealing with classes and objects, I am pretty new to this. I created 2 constructors to make CombinationLock objects with 3 int values. I had to make one lock object using the default constructor and one object using the other constructor. Eventually I had to change the value of the one using the default constructor to match the values of the other of the other lock and now the 2 locks have the same combinations.

I want to compare the 2 lock objects using an .equals() method to show that the locks have the same combinations. (Only the 3 combination int values, not the boolean)

public class CombinationLock {

    private int num1;
    private int num2;
    private int num3;
    private boolean isOpen;

    public CombinationLock() {
        num1 = 0;
        num2 = 0;
        num3 = 0;
        isOpen = false;

    }

public CombinationLock(int passedNum1, int passedNum2, int passedNum3){
        num1 = passedNum1;
        num2 = passedNum2;
        num3 = passedNum3;
        isOpen = true;

}




python two objects of same class shares its member variables

I'm quite new on Python classes, but never would except such a behavior, when executing this small example:

#!/usr/bin/python

class Object:
    pixels = []

    def __init__(self):
        pixels = []

    def addPixel(self, x,y):
        self.pixels.append([x,y])


o1 = Object()
o2 = Object()

o1.addPixel(5,3)

print(o1)
print(o2)
print (o2.pixels)

The output is:

<__main__.Object instance at 0x7feb4cc83710>
<__main__.Object instance at 0x7feb4cc837a0>
[[5, 3]]

So although they are on different memory addresses, o2 has the pixels from o1? Why this behavior is done by Python and how to avoid it (I would like to have two completely independent objects).




Can't get jquery resize function to work properly

I'm trying to create a function that checks the browser window width and applies or removes classes depending on what the width is. However, I either can't seem to remove one of the classes and can't get the function based on the classes to work either.

The concept is: On window resize, IF the window width exceeds 480px to have the class "deskop" applied to the figure ".grid-block", and the class "mobile" removed. ELSE, if the window width goes below 481px to have the class "desktop" removed and "mobile" applied. Then, if a ".grid-block" has the class "desktop", allow this mousover effect to take place. If the figure has the class "mobile", prevent the mouseover.

My problems are: I couldn't get the class applying/removing resize function to fire properly, so I borrowed and revised some code I found and it ended up looking like this...

$(window).load(function() {
  (function($) {
    var $window = $(window),
    $block = $('.grid-block');

    function resize() {
      if ($window.width() < 481) {
        return $block.addClass('mobile');
      }
      $block.removeClass('mobile');
      if ($window.width() > 480) {
        return $block.addClass('desktop');
      }
      $block.removeClass('desktop');
    }
    $window
    .resize(resize)
    .trigger('resize')
  })(jQuery);
});

This function assigns the mobile class properly, but it always keeps the desktop class. So be it- I thought- so I revised the function to omit using the desktop class and to have my functions based entirely on the figure element having the mobile class or not, like so...

if (!$('.grid-block').hasClass("mobile")) {
  $('.grid-block').mouseover(function() {
    $(this).find("figcaption").removeClass("testopacity");
  });
  $('.grid-block').mouseout(function() {
    $(this).find("figcaption").addClass("testopacity");
  });
} 

Instead of checking to see if the ".grid-block" figure has the "mobile" class applied, it just goes ahead with the mouseover function no matter what the browser window width is.

What is wrong with my functions? Why doesn't the first one remove the desktop class, and why doesn't the second one check for the mobile class before performing it's function?




Why is my Silex autoloader (composer) not loading a class?

I'm using composer to load classes. It does work for a provider, but it does not load my classes folder. This is my composer.json :

{
    "require": {
        "silex/silex": "~1.3",
        "twig/twig": "^1.33",
        "doctrine/dbal": "^2.5",
        "uploadcare/uploadcare-php": "^1.5",
        "symfony/twig-bridge": "^2.8",
        "symfony/form": "^2.8",
        "symfony/security-csrf": "^2.8",
        "symfony/validator": "^2.8",
        "symfony/config": "^2.8",
        "symfony/translation": "^2.8"
    },
    "autoload": {
        "psr-4": {
            "Models\\": "app/Models/",
            "Providers\\": "app/Providers/"
        }
    }
}

And this is my folder structure:

Webshop
--app
----Config
----Models
---->>Session.php
----Providers
--public
----index.php
--vendor
--views
--composer.jason
--composer.lock

This line is in index.php:

require_once __DIR__.'/../vendor/autoload.php';

But I get this error for some reason:

Fatal error: Class 'Session' not found in E:\Software\XAMPP\htdocs\Webshop\public\index.php on line 32

And in case you might need it, I can give you the session class of course. If anything needs to be added. Please ask and I'll add it within a minute.




I am trying to make a list of animals and recall them when i enter 3 in the menu

I can not for the life of me figure out why this doesn't work i simply want to have the user input turn into a list i can recall later by pressing 3 if anyone can help show me why i can not use my lists in different classes that would be very helpful.

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;

  namespace Brackeys_classes_tutorial
  {


    public class Animal
{
    //class Variables





    public static int dogtrue { get; set; }
    public static int Count = 0;
    public static string name { get; set; }
    public  static int age { get; set; }
    public static float happiness { get; set; }
    public static List<string> list = new List<string>();
    public static List<int> list2 = new List<int>();
    public static List<float> list3 = new List<float>();

    //Class Constructors
    public Animal()//uses default constructer 
    when no variables put in    under construction of new animal
    {






        if (dogtrue == 1)
        {

            Console.WriteLine("Write the Name of the Dog");

            name = Console.ReadLine();
            list.Add(name);

            Console.WriteLine("Write the Age of the Dog");

            age = Convert.ToInt32(Console.ReadLine());
            list2.Add(age);

            Console.WriteLine("Write the Happiness of the Dog");

            happiness = Convert.ToSingle(Console.ReadLine());
            list3.Add(happiness);


            Count++;

        }



        else if (dogtrue == 2)
        {
            Console.WriteLine("Write the Name of Cat");

            name = Console.ReadLine();
            list.Add(name);


            Console.WriteLine("Write the Age of Cat");

            age = Convert.ToInt32(Console.ReadLine());
            list2.Add(age);

            Console.WriteLine("Write the Happiness of Cat");

            happiness = Convert.ToSingle(Console.ReadLine());
            list3.Add(happiness);

            Count++;
        }
        else {
            Console.WriteLine("error");
            Console.ReadKey();
        }
    }




    //Class Methods
    public void Print()
    {

        Console.WriteLine("Name: " + name);
        Console.WriteLine("Age: " + age);
        Console.WriteLine("Happiness: " + happiness);


    }
  }











  class Program
  {


     static void Main(string[] args)
     {

        Console.WriteLine("Hello welcome to Pet Inventory.");
        Console.WriteLine();
        Console.WriteLine("\"Press the enter key\" after defining first  

        pets details to enter new pet information.");

    Nanimal:

        Console.WriteLine();
        Console.WriteLine("Is the new animal a Cat or Dog \"press\" 1 for 

        Dog 2 for Cat or 3 for current inventory");
        Animal.dogtrue = Convert.ToInt32(Console.ReadLine());
        if (Animal.dogtrue == 1)
        {
            Animal dog = new Animal();
            dog.Print();

            Console.WriteLine();
            Console.WriteLine("Num of Animals: " + Animal.Count);//counts 

            each animal in instance



            Console.ReadKey();

            goto Nanimal;
        }

        else if (Animal.dogtrue == 2)
        {
            Console.WriteLine();

            Animal cat = new Animal();
            cat.Print();

            Console.WriteLine();
            Console.WriteLine("Num of Animals: " + Animal.Count);





            Console.ReadKey();
            goto Nanimal;
        }
        else if (Animal.dogtrue == 3)

This is my problem area ******************************

        {

            foreach (string x in list)
            {
                Console.WriteLine(x);

            }
            foreach (int b in list2)
            {
                Console.WriteLine(b);

            }
            foreach (float c in list3)
            {
                Console.WriteLine(c);

            }
            Console.ReadKey();

           goto Nanimal;
        }


            else {
            Console.WriteLine("error");
            Console.ReadKey();
            goto Nanimal;

        }
      }
     }
    }




Swift: Calling UIAlertController from a Utilities Class

I am currently trying to learn and advance my skills more as a Swift developer, and this may come across as a dumb question but I'm curious.

Problem
In my code I am constantly repeating UIAlertController creation and presentation code so much that it looks sloppy. Also with Dispatching it to the main thread, it takes up to 5 lines, and I repeat this code throughout my project multiple times, on multiple View Controllers. So instead I have created a "Utilities" class and in that class I have a function that displays a UIAlertController.

Question
What I was wondering is, is this bad coding practice? Is it sloppy to constantly call on this function from another class, creating a new UIAlertController constantly? Does this slow my application done? Or is this perfectly fine?

Code incase it matters:

class Utils {

func displayError(viewController: UIViewController, title: String, message: String, action: UIAlertAction?) {
    let ac = UIAlertController(title: title,
                               message: message,
                               preferredStyle: .alert)

    if action == nil {
        ac.addAction(UIAlertAction(title: "Ok", style: .cancel))
    } else {
        ac.addAction(action!)
    }

    DispatchQueue.main.async {
        viewController.present(ac, animated: true)
    }
}
}

Thank you in advanced.




How to create different class objects in class constructor and overloading operators (C++)

I need yours help. I'm quite newbie in C++ (still learning) and I struggling with class constructor which include object from different class. The task is to create Rectangle class which will be described by objects (Point class) , each corner is a object with x,y coordinates. Additionally I need overload operators << and >> in the way that by ">>" user input coordinates of each point during Rectangle object creation by constructor. When I using code as below I have error incomplete type is not allowed" on fields from p1 to p4.

List item

    #include <iostream>

using namespace std;

class Point;
class Rectangle
{
public:
    Rectangle(int p1x = 0, int p1y = 0, int p2x = 0, int p2y = 0, int p3x = 0, int p3y = 0, int p4x = 0, int p4y = 0) : p1(p1x, p1y), p2(p2x, p2y), p3(p3x, p3y), p4(p4x, p4y) 
    {

    };

    friend ostream & operator << (ostream &os, const Rectangle &rect);

private:
    Point p1, p2, p3, p4;
    void change_cordinates(Rectangle &);
    int height, width;
};"

From the other hand, when i use #include "Point.h" directive I have problem with overloading << and >> with error "function Rectangle is not a type name"

I don't know if it's clear, but I hope I described my problem peaty clear (if not correct me please or ask)




TypeError: unsupported operand type(s) for +=: 'method' and 'int' (Python)

I am making a small game in the console that takes place over several days. It involves a miner and his mining pursuits. The game starts by initializing the miners ore and money amounts as 0. When he mines, my function chooses a random integer between 20 and 71 that will then award him that amount in 'ore'. I am trying to assign the ore that has been mined to my player's ore amount. I am having a reoccuring error that states that += is an unsupported operand for method and int. Full code and trace is below.

Code

import pyautogui as pag
import time
import sys
import random


class Miner:
    def __init__(self, oreDeposit, moneyDeposit):
        self.oreAmount = oreDeposit
        self.moneyAmount = moneyDeposit

    def oreDeposit(self, oreAmount):
        self.oreDeposit += oreAmount

    def oreWithdraw(self, oreAmount):
        self.oreWithdraw -= oreAmount
# -------------end of ore

    def moneyDeposit(self, moneyAmount):
        self.moneyDeposit += moneyAmount

    def moneyWithdraw(self, moneyAmount):
        self.moneyWithdraw -= moneyAmount
# -------------end of money

    def oreBalance(self):
        return self.oreAmount

    def moneyBalance(self):
        return self.moneyAmount
# -------------end of balances

def miningAction():
    x = random.randint(20, 71)
    for i in range(x):
        time.sleep(0.1)
        print(i)
        oreRecovered = i
        player.oreDeposit(oreRecovered)

player = Miner(0, 0)
miningAction()
print (player.oreAmount)

Full traceback

0
Traceback (most recent call last):
  File "C:/Users/InsanePainz/PycharmProjects/BoardGame/mine.py", line 41, in <module>
    miningAction()
  File "C:/Users/InsanePainz/PycharmProjects/BoardGame/mine.py", line 38, in miningAction
    player.oreDeposit(oreRecovered)
  File "C:/Users/InsanePainz/PycharmProjects/BoardGame/mine.py", line 12, in oreDeposit
    self.oreDeposit += oreAmount
TypeError: unsupported operand type(s) for +=: 'method' and 'int'

Process finished with exit code 1




How to add different classes to element within for each loop using PHP

I need one help.I need to assign different class name to div element within the loop. I am explaining my code below.

<?php
    $sql="select * from category order by id desc";
    $catdata=$dbobj->db_get_data($sql);
    foreach ($catdata as $v) {
?>
      <div class="col-sm-3">
       <a href="javascript:void(0)" class="item-exhibitation maploc"><?php echo $v['name'] ?></a><!-- activemap1 -->
      </div>

 <?php } ?>

Here i need to keep class name dynamic and all were given below.

$classarr = array("item-exhibitation maploc","item-parking maploc","item-offices maploc","item-storage maploc");

The above 4 are my classes and these will be assigned dynamically. After 4 iteration once again it will take from first. Please help me.




I am not sure what the following is expecting for

I am really appreciate for those who helps!!

Here is the question: Consider a class MotorBoat that represents motorboats. A motorboat has private attributes for:

  • The capacity of the fuel tank
  • The amount of fuel in the tank
  • The amount of fuel in the tank
  • The maximum speed of the boat

  • The current speed of the boat

  • The efficiency of the boat’s motor

The distance traveled

The class has methods to:

Change the speed of the boat

Operate the boat for an amount of time at the current speed

Refuel the boat with some amount of fuel

Return the amount of fuel in the tank

Return the distance traveled so far If the boat has efficiency e, the amount of fuel used when traveling at a speed s for time t is e x s2 x t. The distance traveled in that time is s x t.

And here is what I got by so far:

public class MotorBoat {

//the capacity of the fuel tank
private double capaity;
//the amount of fuel in the tank
private double amount;
//the maximum speed of the boat
private double maxSpeed;
//the current speed of the boat
private double curSpeed;
//the efficiency of the boat's motor
private double efficiency;
//the distance traveled
private double distance;



//Change the speed of the boat
public void changeSpeed(double newSpeed)
{
    this.curSpeed = newSpeed;
}
//Operate the boat for an amount of time at the current speed
public void operateAmount(double newAmount)
{
    this.amount = newAmount;
}

//Refuel the boat with some amount of fuel
//I don't get this one

//Return the amount of fuel in the tank
public double getAmount()
{
    return amount;
}
//Return the distance traveled so far
public double getDistance()
{
    return distance;
}

//If the boat has efficiency e, the amount of fuel used when traveling at a speed s for time t is e x s2 x t.  The distance traveled in that time is s x t.

public double amountUsed()
{
    double amountUsed = this.efficiency*(this.curSpeed*this.curSpeed)*(this.getDistance()/this.curSpeed);
    return amountUsed();
}


public static void main(String[] args) {

    MotorBoat boat = new MotorBoat();
    System.out.println("Current Speed: " + boat.curSpeed);

    boat.changeSpeed(200);
    System.out.println("Current Speed: " + boat.curSpeed);

    System.out.println("Fuel Amount: " + boat.getAmount()); 
    boat.operateAmount(2000);
    System.out.println("Fuel Amount: " + boat.getAmount()); 

    System.out.println("Distance Traveled: " + boat.getDistance()); 

    boat.amountUsed(); 
    System.out.println("Fuel Amount: " + boat.amountUsed()); 

}

}




Is it possible to implement comparator in single class?

Generally I saw- To implement comparator in java collections we need 2 classes , one class call the sort function and 2nd class implement comparator.. I want to know Is there any way to implement whole comparator concept in a single class??




Including file inside a class php

I am doing something using classes in php for very first time. I am trying to fetch an return object array items in class.

This is my class

class User {

    $dbconn = include("config.php");
    private $dbHost     = $dbconn->host;
    private $dbUsername = $dbconn->username;
    private $dbPassword = $dbconn->pass;
    private $dbName     = $dbconn->database;
    private $userTbl    = 'users';

    function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
}

This is my config.php file

return (object) array(
    'host' => 'localhost',
    'username' => 'my_user',
    'pass' => 'my_pass',
    'database' => 'my_db'
);

How do i do it?

PHP Parse error:  syntax error, unexpected '$dbconn' (T_VARIABLE)




C#: I need to input a value, and extract information of an object

I'm programming in Unity, using the language C#.

I need to be able to input a random value, search through a list of objects in a class, and find the one with an ID that matches the random value. To make things more complicated, I also have to extract all information I can on that item. I have the random input, which is the following line of code:

firstCard = Random.Range (1, 18);

Then I have the cards:

public class Card {
public int CardID;
public string element;
public int value;
public string color;

public Card (int cardids, string elementals, int values, string coloring) {
    this.CardID = cardids;
    this.element = elementals;
    this.value = values;
    this.color = coloring;
    }
}

public class CardList : MonoBehaviour {
    public Card a = new Card(1,"Fire",3,"Blue");
    //Other cards appear here.
}

So if the random number returns 1, I want it to retun "Fire", 3, and "Blue" because the CardID matches the random number. These two groups of code are in two different files, if that changes anything.




my phone numbes book class is not working

I am doing some kind of phone-book, but something in my class is not okay, i do not know why, im stuck since monday...

If someone see any mistake, please let me know it.

Check code on my screenshoots:




Python - Call Classes's Method's Function from Another Class Method

Is it possible to access a function defined within a class method in another class? Here is what I mean:

class MethodWithFunctions:

    def hello(self):
        def function(text):
            return 'Hello ' + text

class INeedHello(Object):

    @staticmethod
    def hellothere(text):
        print MethodWithFunctions(function(text))

INeedHello.hellothere('John!')
>>> 'Hello John!'

I'd like to avoid making the MethodWithFunctions class a parent class if possible for my context but if this is the only way that is fine.




how can i add foreign key to existing class in django

I have simple models of country and town:

from django.db import models

class Country(models.Model):
    name = models.CharField(max_length=50)

class Town(models.Model):
    belongs_to = models.ForeignKey(country, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)

Now, I would like to play around a bit... and I would like to add continent. I guess correct way from the start would be to do this:

from django.db import models

class Continent(models.Model):
    name = models.CharField(max_length=50)

class Country(models.Model):
    belongs_to = models.ForeignKey(continent, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)

class Cown(models.Model):
    belongs_to = models.ForeignKey(country, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)

If I do that and save the file, add continents in admin.py to admin.site.register(continent), start with makemigrations... I get this:

You are trying to add a non-nullable field 'belongs' to country without a default; we can't do that (the database needs som ething to populate existing rows). Please select a fix:

1.) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2.) Quit, and let me add a default in models.py

I get stuck here, because I do not know what to do from here?




how to use for loop in class for user inputs python

I have created employee details using class by giving pre defined inputs.

Here are my codes:

class Employees(object):
    def __init__(self,emplname,position,idno,salary):
        self.emplname=emplname
        self.position=position
        self.idno=idno
        self.salary=salary

    def print_details(self):
        print "Employee name :", self.emplname
        print "Employee position :", self.position
        print "Employee idno :", self.idno
        print "Employee salary :", self.salary

class Empldb(Employees):
    def __init__(self,emplname,position,idno,salary,age):
        Employees.__init__(self,emplname,position,idno,salary)
        self.age=age

new_router1=Empldb("Abc","Trainee","101","15823","13")
new_router1.print_details( )

I have a few doubts. 1. How to get inputs from user using for loop in class function? eg: No of employees=2

name=Abc position=trainee Idno=123 salary=20000
name=def position=trainee Idno=456 salary=20000

  1. How to save these outputs into a dict so that I can write it as a csv later. dict.update was giving me errors

Im confused about which way I should try to code to get user inputs so I couldnt include for loop in it. I would be thankful if you could help me, as Im a novice in python




Is it possible to create custom literals in C++?

I have written a simple complex number class.

To initialize an object, I use:

My_Complex A (2,3);

and to assign values I use:

A.set_value(2,3);

Is there a way to make it more natural like:

A = (2,3);

Or even

A = 2p3i;

but not

A = "2+3i";

In another words, is it possible to create custom literals in C++?

If no, how the string literals created if the string type is not part of the core language?




Python 3 "Object() takes n parameters"

This is my code:

class Student:
    def ___init__(self, id, surname, name, initials):
        self.id = id
        self.surname = surname
        self.name = name
        self.initials = initials
    def display(self):
        print(self.name, self.surname)
        print("ID= {}".format(self.id))

s1 = Student("21564013", "Aydın", "Atacan", "AA")

And this is the error i get:

Traceback (most recent call last):
  File "E:\Hacettepe\GMT104\Week 03\Assign\assingment.py", line 27, in <module>
    s1 = Student("21664013", "Aydın", "Atacan", "AA")
TypeError: object() takes no parameters

What can i do about it?




calling a list from inside a class in a different script python

I have created a remote object style property database. I am trying to create a search function to:

  1. search by postcode
  2. search by price range

I am struggling to call the dictionary-style list that is within the warehouse script i.e.

from __future__ import print_function
import Pyro4

@Pyro4.expose
class Warehouse(object):
    def __init__(self):
**I WANT TO CALL THIS LIST HERE (NOTE IT IS DYNAMIC AND MAY HAVE MORE/LESS)**
        self.contents ={"1000":["John", "1", "CF24 4AN", 200000], "1001":["Bob", "2", "CF10 1EN", 250000]}

    def list_contents(self):
        return self.contents



    def store(self, name, propid,owner,housenumber,postcode,price):
        self.contents.update({propid: [owner,housenumber,postcode,price]})
        print("{0} took the {1}.".format(name, item))



    def take(self, name, item):
        del self.contents[item]
        print("{0} took the {1}.".format(name, item))


def main():
    warehouse = Warehouse()
    Pyro4.Daemon.serveSimple(
        {
            warehouse: "propertylist.warehouse"
        },
        ns=True)


if __name__ == "__main__":

    main()

by code used to visit the warehouse and that the search function is contained is in a different script, namely below

    # This is the code that visits the warehouse.
import sys
import Pyro4
import Pyro4.util
from personcwk import Person
from warehousecwk import Warehouse

sys.excepthook = Pyro4.util.excepthook


def menu(employee):

    print("""\nMENU:

1 - Browse all properties
2 - Search property list
3 - Add property
4 - Remove property
5 - Exit
""")

    try:

        select_option = int(input("Select an option: "))

        while select_option not in (1, 2, 3, 4, 5):
            select_option = int(input("Please select an option: "))

        if select_option == 1:
            browse_option(employee)

        elif select_option == 2:
            search_option(warehouse)

        elif select_option == 3:
            add_option(employee)

        elif select_option == 4:
            remove_option(employee)

        elif select_option == 5:
            exit

    except ValueError:
        print("\nInput a number")
        menu(employee)



def browse_option(employee):
    print("The property list contains:", warehouse.list_contents())
    menu(employee)

def search_option(warehouse):
    print("""\nSEARCH BY:

1 - Postcode
2 - Price range
""")

    try:

        select_search_option = int(input("Select an option: "))

        while select_search_option not in (1, 2):
            select_search_option = int(input("Please select an option: "))

        if select_search_option == 1:
            search_postcode(warehouse)

        elif select_search_option ==2:
            search_price()

    except ValueError:
        print("\nInput a number")
        search_option(employee)

        exit


def add_option(employee):
    employee.add_p(warehouse)
    menu(employee)


def remove_option(employee):
    Person.remove_p(employee,warehouse)
    menu(employee)

**THIS IS THE SEARCH FUNCTION IM TRYING TO CREATE**
def search_postcode(warehouse):
    searchfor = str(input("Please enter a postcode: "))
    for k in warehouse:
        for v in warehouse[k]:
            if searchfor in v:
                print(k, ":", warehouse[k])
    return None

    exit


def search_price():
    exit


warehouse = Pyro4.Proxy("PYRONAME:propertylist.warehouse")

employee = Person("Employee")

menu(employee)

but I get the error:

TypeError: 'Proxy' object is not iterable.

So my question is, how can I search the contents list in the init of the Warehouse class through a function defined in a completely different script?




Implementing jQuery Bootgrid error: Non-invocable member cannot be used like a method

I'm implementing jQuery bootgrid with my ASP.Net MVC application. I'm just having an issue with the following code:

var tResult = BootgridResponseData<List<Contact>>()
    {
        current = model.current,
        rowCount = model.rowCount,
        rows = contacts,
        total = contacts.Count
    };

This gives me the following error:

Non-invocable member 'BootgridResponseData' cannot be used like a method.

My BootgridResponseData class is defined as follows:

public class BootgridResponseData<T> where T : class
{
    public int current { get; set; } //? current page
    public int rowCount { get; set; } //? rows per page
    public IEnumerable<T> rows { get; set; } //? items
    public int total { get; set; } //? total rows for whole query
}

Any idea what's wrong here. I'm not 100% sure what I'm doing right here because I've been guided into doing it this way so far.

Any help would be very much appreciated.




js: how to access a class defined inside require from the outside (accessibility issue)

This question is bothering me for a while. I'm trying to call a class from outside require (accessibility issue), my code looks like the above.

require(['foo'],
    (foo) => {
        class Bar {
            hello() {
                return "hello";
            }
        }
    });
bar = new Bar();
//uncaught ReferenceError: Chart is not defined

I've found one workaround, this is done by using window.Bar = class Bar...

require(['foo'],
    (foo) => {
        window.Bar = class Bar {
            hello() {
                return "hello";
            }
        }
    });
bar = new Bar();
//OK

However, this is not a convenient solution when it comes to converting it using Babel.

Do you know any other more correct way to export/define this class so that it could be called from an upper level?

Thanx in advance




Inequalities as python parameters

Firstly, Sry fo the bad title of this question I simply don't know a better one. If you have a better one => Tell me!

So my problem is that I would like to write a simplex solver in Python by myself to deeply understand how they work.

Therefore, I would like to have something like this in my program:

 m.addConstr(x[0] <= 7)

Which basically should add a constraint to my model m. This works in Gurobi which is just wonderful cause it's so easy to read. The problem is that x[0] has to be an object where I itself can define what should happen when there is an inequality or equality or whatever, right?

I am happy to figure out most of the stuff by myself would just like to get an idea how this works.




Assigning variables to python classes

I am trying to understand how classes and iterators work. I was trying to modify code from http://ift.tt/2ojSTUl to parse input from a different format. My input looks like this:

PRIMER PICKING RESULTS FOR chr11:108168100-108168100

Using mispriming library humrep_and_simple.txt
Using 1-based sequence positions
OLIGO            start  len      tm     gc%  any_th  3'_th hairpin   rep seq
LEFT PRIMER         70   20   58.19   55.00    0.00   0.00    0.00 10.00 GGTAGTGTTGTGAGGGAAGC
RIGHT PRIMER       199   23   56.94   39.13    2.25   0.00    0.00 12.00 AGAAATCTTTGGGTATACTGGGT
SEQUENCE SIZE: 201
INCLUDED REGION SIZE: 201

PRODUCT SIZE: 130, PAIR ANY_TH COMPL: 0.00, PAIR 3'_TH COMPL: 0.00
(additional sets of primer picking results below)

The only changes I made to the code is to the parse function

def parse(handle):
    while True:
        line = handle.readline()
        if line.strip(): break
    record = None
    primer = None
    while True:
        if line.startswith('PRIMER PICKING RESULTS'):
            if record is not None: yield record
            record = Record()
            primer = None
        elif line.startswith('LEFT PRIMER'):
            if not primer:# or primer.size == 0:
                primer = Primers()
                record.primers.append(primer)
            words = line.split()
            primer.forward_start = int(words[2])
            primer.forward_length = int(words[3])
            primer.forward_tm = float(words[4])
            primer.forward_gc = float(words[5])
            primer.forward_seq = words[10]
        elif line.startswith('RIGHT PRIMER'):
            if not primer:# or primer.size == 0:
                primer = Primers()
                record.primers.append(primer)
            words = line.split()
            primer.reverse_start = int(words[2])
            primer.reverse_length = int(words[3])
            primer.reverse_tm = float(words[4])
            primer.reverse_gc = float(words[5])
            primer.reverse_seq = words[10]
        elif line.startswith('PRODUCT SIZE'):
            if not primer or primer.size == 0:
                primer = Primers()
                record.primers.append(primer)
            items = line.split(",")
            primer.size = int(items[0][14:])
        else: pass
        try:
            line = next(handle)
        except StopIteration:
            break
    if record:
        yield record

When I tested my code:

primer_record = parser.parse(outfile) 
for record in primer_record:
    primerset = record.primers[0]
    print(primerset.forward_start, primerset.reverse_start)

I can get the correct primerset.forward_start=70 (all the values from "LEFT PRIMER" has been successfully recorded and output), but primerset.reverse_start (as well as other values in "RIGHT PRIMER", and "PRODUCT SIZE",)=0. So my code must not be recording the values correctly. Why is my script not capturing values after "LEFT PRIMER"?

I'm sorry if this is a silly question and I don't really understand how the code works, but I've tried to search for the answer for a long time without success. Can anyone enlighten me pls?




c++ class-to-class data transfer

I am working in c++, i want to input from text file then transfer to the variables in the class. I have 2 classes: class A and class B which are present by:

class A{
public:
double i;
double r;
double function(double s){
i = s*s+r;
return i;};

class B: public A{
public:
A A;
int c;
double e;
e = A.r;
c = A.function(c);
double h;
h=e+c;};

int main()
{
ifstream data;
double f[3];
data.open("A.txt", ios::in);
for (int i = 0; i <3; i++){
data>> f[i];}
A A;
A.r = f[0];
};

the "r" that I input in class A didn't remain values when I use it in class B. I don't know how to deal with this problem. please help me!! thank you co much!!!




Requiring a class in Javascript

I'm trying to require a class in javascript (using node if you want to know) and at the moment its not erroring on the require but not really requiring right, heres the class code

class npc {
    constructor(name, dialog) {
        this.name = name;
        this.dialog = dialog;

    }

    rdialog() {
        this.tts = dialog[Math.floor(Math.random()*dialog.lensgth)];
        return this.tts;
    }
}

and here's the way I'm trying to require it var npc = require('../Npcs/npc.js'); i keep getting a empty object {} cant seem to find a answer when i get somewhat further i end up with a function named npc