问:
C# Searching List of Arrays for specific value and returning related value
I hope this isn't a foolishly simple question. Im very simply trying to figure out how to manipulate a relatively simple table in SQLite through C#.

Im looking to take a parameter and search a List of Arrays for one such array where the parameter matches, and return a related variable within that same array.

For example where an array in the list might be.

```<code>Name          IATA

Brisbane        BNE
</code>```

The sqlbind:

```<code>public static List<Airport> LoadAirports()
{
    using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
    {
        var output = cnn.Query<Airport>("select * from Airport", new DynamicParameters());
        return output.ToList();
    }
}
</code>```

The Class:

```<code>class Airport
{
    int Id { get; set; }
    string Name { get; set; }
    string LocationName { get; set; }
    string IATA { get; set; }
    string PortType { get; set; }
    string PortOwner { get; set; }
    string MotherPort { get; set; }
    bool Active { get; set; }
    bool IsApplyMeetAndGreet { get; set; }
    decimal MeetAndGreet { get; set; }
}
</code>```

The main Program:

```<code>List<Airport> Airports = new List<Airport>();
public FreightCalculator()
{
    LoadAirportsList();
    string OriginName = OriginInput.Value;
    var OriginAirport = Airports.Where(s => s.Name == OriginName);
}
private void LoadAirportsList()
{
    Airports = SqliteDataAccess.LoadAirports();
}
</code>```

Ive tried various combinations of Where, Equals, For each indexing etc. Always getting an error of some kind.

The Error with the above Airports.Where is that the s.Name is inaccessible due to its protection level.

If I do:

```<code>var OriginAirport = Airports.Where(Name => Name == OriginName);
</code>```

I get an error where the operand == cannot be used with Airport and String (Though Name is a string in Airport.)

Im either missing something simple or making this more complicated than it needs to be. Once I find the matching Airport, I need to return the IATA code.

Which I envisage looking like this:

```<code>var OriginIATA = OriginAirport.IATA;
</code>```

Im tired and feeling dumb. Please help :(

答:
Since you declared all members of the Airport class as properties I assume you wanted to expose them publicly.

The error you get is because they are private members and can't be accessed outside the class.

Change "Airport" class to:

```<code>class Airport
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string LocationName { get; set; }
    public string IATA { get; set; }
    public string PortType { get; set; }
    public string PortOwner { get; set; }
    public string MotherPort { get; set; }
    public bool Active { get; set; }
    public bool IsApplyMeetAndGreet { get; set; }
    public decimal MeetAndGreet { get; set; }
}
</code>```

Body:
I hope this isn't a foolishly simple question. Im very simply trying to figure out how to manipulate a relatively simple table in SQLite through C#.

Im looking to take a parameter and search a List of Arrays for one such array where the parameter matches, and return a related variable within that same array.

For example where an array in the list might be.

Name          IATA

Brisbane        BNE

The sqlbind:

public static List<Airport> LoadAirports()
{
    using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
    {
        var output = cnn.Query<Airport>("select * from Airport", new DynamicParameters());
        return output.ToList();
    }
}

The Class:

class Airport
{
    int Id { get; set; }
    string Name { get; set; }
    string LocationName { get; set; }
    string IATA { get; set; }
    string PortType { get; set; }
    string PortOwner { get; set; }
    string MotherPort { get; set; }
    bool Active { get; set; }
    bool IsApplyMeetAndGreet { get; set; }
    decimal MeetAndGreet { get; set; }
}

The main Program:

List<Airport> Airports = new List<Airport>();
public FreightCalculator()
{
    LoadAirportsList();
    string OriginName = OriginInput.Value;
    var OriginAirport = Airports.Where(s => s.Name == OriginName);
}
private void LoadAirportsList()
{
    Airports = SqliteDataAccess.LoadAirports();
}

Ive tried various combinations of Where, Equals, For each indexing etc. Always getting an error of some kind.

The Error with the above Airports.Where is that the s.Name is inaccessible due to its protection level.

If I do:

var OriginAirport = Airports.Where(Name => Name == OriginName);

I get an error where the operand == cannot be used with Airport and String (Though Name is a string in Airport.)

Im either missing something simple or making this more complicated than it needs to be. Once I find the matching Airport, I need to return the IATA code.

Which I envisage looking like this:

var OriginIATA = OriginAirport.IATA;

Im tired and feeling dumb. Please help :(

Body:
Since you declared all members of the Airport class as properties I assume you wanted to expose them publicly.

The error you get is because they are private members and can't be accessed outside the class.

Change "Airport" class to:

class Airport
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string LocationName { get; set; }
    public string IATA { get; set; }
    public string PortType { get; set; }
    public string PortOwner { get; set; }
    public string MotherPort { get; set; }
    public bool Active { get; set; }
    public bool IsApplyMeetAndGreet { get; set; }
    public decimal MeetAndGreet { get; set; }
}


来源: stackexchange

问:
How to round a number up or down in Rust?
How to floor or ceil numbers?  I tried to use the round crate but either it doesn't work or I'm using it wrong.

use round::round_down;

fn main() {
  println!("{}", round_down(5.5f64, 0));
}
```

<p>This prints <code>5.5</code> but should print <code>5</code>.</p>

<p>My <code>Cargo.toml</code> file contains this:</p>

```[dependencies]
round = "0.1.0"
```

答:
fn main() {
  let mut num = 5.5_f64;
  num = num.floor();
  print!("{}", num); // 5
}
```

ContentLicense: CC BY-SA 4.0

Body:
How to floor or ceil numbers?  I tried to use the round crate but either it doesn't work or I'm using it wrong.

use round::round_down;

fn main() {
  println!("{}", round_down(5.5f64, 0));
}

This prints 5.5 but should print 5.

My Cargo.toml file contains this:

[dependencies]
round = "0.1.0"


问:
Python Except Specific Key Error
I'm parsing an XML file using Beautiful Soup. Sometimes I have entries that are missing one or more of the keys I'm parsing. I want to setup exceptions to handle this. My code looks something like this:

```<code>for entry in soup.findAll('entry_name'):
    try:
        entry_dict = dict(entry.attrs)
        x = entry_dict["x"]
        y = entry_dict["y"]
        z = entry_dict["z"]

        d[x] = [y, z]
    except KeyError:
        y = "0"
        d[x] = [y, z]
</code>```

The problem is I can have "y", "z" or both "y and z" missing depending on the entry. Is there a way to handle specific KeyErrors? Something like this:

```<code>except KeyError "y":
except KeyError "z":
except KeyError "y","z":
</code>```

答:
A slight variation on Paweł Kordowski answer:</p>

```<code>a = {}
try:
    a['a']
except KeyError as e:
    # 2 other ways to check what the missing key was
    if 'a' in e.args:
        pass
    if 'a' in e:
        pass
    # reraise the exception if not handled
    else:
        raise
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python Except Specific Key Error

Body:
I'm parsing an XML file using Beautiful Soup. Sometimes I have entries that are missing one or more of the keys I'm parsing. I want to setup exceptions to handle this. My code looks something like this:

for entry in soup.findAll('entry_name'):
    try:
        entry_dict = dict(entry.attrs)
        x = entry_dict["x"]
        y = entry_dict["y"]
        z = entry_dict["z"]

        d[x] = [y, z]
    except KeyError:
        y = "0"
        d[x] = [y, z]

The problem is I can have "y", "z" or both "y and z" missing depending on the entry. Is there a way to handle specific KeyErrors? Something like this:

except KeyError "y":
except KeyError "z":
except KeyError "y","z":

Body:
A slight variation on Paweł Kordowski answer:

a = {}
try:
    a['a']
except KeyError as e:
    # 2 other ways to check what the missing key was
    if 'a' in e.args:
        pass
    if 'a' in e:
        pass
    # reraise the exception if not handled
    else:
        raise


问:
Flutter, how to have release and debug app on the same device?
I'm working with flutter on an application (only android for now) which can be downloaded from Google Play.
I have installed the released app on my phone. However, whenever I launch the debug on my device with android studio, it is deleting the released version.
What I would want is having both apps at the same time, like "App" and "App_debug" on my device.

How can I set up my project so there is no conflict between the debug and the release app ?

Thank you.

答:
What're you looking for is called flavors. You can check out more info about it in the flutter official docs or checking out these packages:

https://pub.dev/packages/flutter_flavor

https://pub.dev/packages/flutter_flavorizr


问:
`pydot` failed to call GraphViz.Please install GraphViz and ensure that its executables are in the $PATH
My jupyter server is running in a gcp deep learning vm.

I'm trying to print the model in a Jupyter notebook cell.

```<code>import os, sys
from utils.models.alexnet import alexnet
from keras.utils.vis_utils import plot_model
from keras.optimizers import SGD

model = alexnet(len(class_names))
model.summary()
plot_model(model, to_file="alexnet_model.png", show_shapes=True)
</code>```

I get this error

```<code>`pydot` failed to call GraphViz.Please install GraphViz ([https://www.graphviz.org/](https://www.graphviz.org/)) and ensure that its executables are in the $PATH.
</code>```

I have correctly installed Graphviz in my machine with

apt-get install graphviz

```<code>stat /usr/bin/dot
  File: /usr/bin/dot
  Size: 10568       Blocks: 24         IO Block: 4096   regular file
Device: 801h/2049d  Inode: 142872      Links: 1
Access: (0755/-rwxr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2020-02-10 11:48:19.416617639 +0000
Modify: 2017-02-19 10:32:17.000000000 +0000
Change: 2019-12-13 01:47:41.084977709 +0000
</code>```

The python packages pydot, pydot-ng, pydotplus are also installed.

This is my path variable

```<code>echo $PATH
/usr/local/cuda/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
</code>```

/user/bin is included here.

EDIT

When executed in a jupyter notebook shell.

```<code>print(os.environ["PATH"])
</code>```

/usr/local/cuda/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games

Another wierd thing

I have a simple image dataset with 3 classes and altogether around 2000 images. In my jupyter notebook I first process and load the images into memory. Creating the model and printing it comes next. With the simple dataset it works without error. This happens when I work with large datasets.

答:
I was also getting the same thing so i install conda install python-graphviz
after conda install pydot</p>

Body:
My jupyter server is running in a gcp deep learning vm.

I'm trying to print the model in a Jupyter notebook cell.

import os, sys
from utils.models.alexnet import alexnet
from keras.utils.vis_utils import plot_model
from keras.optimizers import SGD

model = alexnet(len(class_names))
model.summary()
plot_model(model, to_file="alexnet_model.png", show_shapes=True)

I get this error

`pydot` failed to call GraphViz.Please install GraphViz ([https://www.graphviz.org/](https://www.graphviz.org/)) and ensure that its executables are in the $PATH.

I have correctly installed Graphviz in my machine with

apt-get install graphviz

stat /usr/bin/dot
  File: /usr/bin/dot
  Size: 10568       Blocks: 24         IO Block: 4096   regular file
Device: 801h/2049d  Inode: 142872      Links: 1
Access: (0755/-rwxr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2020-02-10 11:48:19.416617639 +0000
Modify: 2017-02-19 10:32:17.000000000 +0000
Change: 2019-12-13 01:47:41.084977709 +0000

The python packages pydot, pydot-ng, pydotplus are also installed.

This is my path variable

echo $PATH
/usr/local/cuda/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games

/user/bin is included here.

EDIT

When executed in a jupyter notebook shell.

print(os.environ["PATH"])

/usr/local/cuda/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games

Another wierd thing

I have a simple image dataset with 3 classes and altogether around 2000 images. In my jupyter notebook I first process and load the images into memory. Creating the model and printing it comes next. With the simple dataset it works without error. This happens when I work with large datasets.


问:
Flutter dropdown menu with ListTiles and row of Buttons
I'm trying to build out a custom dropdown menu that looks like this:

I've managed to implement the ListTiles and Row of Buttons without the dropdown, but I'm not sure how to nest all of that within a dropdown menu class. This is what I've got so far:

```<code>class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: Drawer(),
      body: SizedBox.expand(
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              ListTile(
                onTap: () {},
                leading: CircleAvatar(backgroundColor: Colors.primaries[0]),
                title: Text('All Circles'),
              ),
              Divider(color: Colors.grey.shade400, indent: 72.0, height: 1.0),
              ListTile(
                onTap: () {},
                leading: CircleAvatar(backgroundColor: Colors.primaries[1]),
                title: Text('Pickup'),
              ),
              Divider(color: Colors.grey.shade400, indent: 72.0, height: 1.0),
              ListTile(
                onTap: () {},
                leading: CircleAvatar(backgroundColor: Colors.primaries[2]),
                title: Text('Kappa Delta'),
              ),
              Divider(color: Colors.grey.shade400, indent: 72.0, height: 1.0),
              ListTile(
                onTap: () {},
                leading: CircleAvatar(backgroundColor: Colors.primaries[3]),
                title: Text('Ok Boomer'),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  RaisedButton(
                    child: Text("Join a Circle"),
                    color: Color(0xffb74093),
                    shape: RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(18.0),
                      side: BorderSide(color: Colors.red),
                    ),
                  ),
                  RaisedButton(
                    child: Text("Create a Circle"),
                    color: Colors.red,
                    textColor: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(18.0),
                      side: BorderSide(color: Colors.red),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

答:
I'm not sure you can use ListTile after the items: directly.
If you did run the code above, you're getting errors.
it needs to return DropdownMenuItem instead of ListTile directly

```<code>return DropdownMenuItem<String>(
    value: value,
    child: Row(
    children: <Widget>[
        CircleAvatar(backgroundColor: Colors.primaries[3]),
        Text(value)
    ],
));
</code>```

I think the above code would be relatively correct.

Body:
I'm trying to build out a custom dropdown menu that looks like this:

I've managed to implement the ListTiles and Row of Buttons without the dropdown, but I'm not sure how to nest all of that within a dropdown menu class. This is what I've got so far:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: Drawer(),
      body: SizedBox.expand(
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              ListTile(
                onTap: () {},
                leading: CircleAvatar(backgroundColor: Colors.primaries[0]),
                title: Text('All Circles'),
              ),
              Divider(color: Colors.grey.shade400, indent: 72.0, height: 1.0),
              ListTile(
                onTap: () {},
                leading: CircleAvatar(backgroundColor: Colors.primaries[1]),
                title: Text('Pickup'),
              ),
              Divider(color: Colors.grey.shade400, indent: 72.0, height: 1.0),
              ListTile(
                onTap: () {},
                leading: CircleAvatar(backgroundColor: Colors.primaries[2]),
                title: Text('Kappa Delta'),
              ),
              Divider(color: Colors.grey.shade400, indent: 72.0, height: 1.0),
              ListTile(
                onTap: () {},
                leading: CircleAvatar(backgroundColor: Colors.primaries[3]),
                title: Text('Ok Boomer'),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  RaisedButton(
                    child: Text("Join a Circle"),
                    color: Color(0xffb74093),
                    shape: RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(18.0),
                      side: BorderSide(color: Colors.red),
                    ),
                  ),
                  RaisedButton(
                    child: Text("Create a Circle"),
                    color: Colors.red,
                    textColor: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: new BorderRadius.circular(18.0),
                      side: BorderSide(color: Colors.red),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Body:
I'm not sure you can use ListTile after the items: directly.
If you did run the code above, you're getting errors.
it needs to return DropdownMenuItem instead of ListTile directly

return DropdownMenuItem<String>(
    value: value,
    child: Row(
    children: <Widget>[
        CircleAvatar(backgroundColor: Colors.primaries[3]),
        Text(value)
    ],
));

I think the above code would be relatively correct.


问:
3-tiers application using ASP.NET and Linq 2 Sql with multiple tables
hello everyone i have a problem with my 3-tiers application i don't know how to get data from multiple tables using linq2sql in 3 tiers architecture application here is each layers code

GestionProjetCommon Project

Client Class :

```<code>public class Client
{
    private int _ID;
    public int ID
    {
        get { return _ID; }
        set { _ID = value; }
    }
    private string _Name;
    public string Name
    {
        get { return _Name; }
        set { _Name = value; }
    }
</code>```

}

Project Class :

```<code>public class Projet
{
    private int _ID;
    public int ID
    {
        get { return _ID; }
        set { _ID = value; }
    }
    private string _Title;
    public string Title        {

        get { return _Title; }
        set { _Title= value; }

    }

   private int _IDClient;
    public int IDClient
    {
        get { return _IDClient; }
        set { _IDClient = value; }
    }
}
</code>```

GestionProjetDAL Project

GestionProjetDA Class :

```<code>public class GestionProjetDA
{
    private GestionProjetDADataContext db = new GestionProjetDADataContext();
    public List<GestionProjet.Client> GetClients() //This Works Fine No Problem !
    {
        var req = from clt in db.Clients select clt;

        List<GestionProjet.Client> clientList = new List<GestionProjet.Client>();
        foreach (Clients item in req)
        {
            clientList.Add(new GestionProjet.Client() { ID = item.ID, Nom = item.Nom });
        }
        return clientList;
    }

public List<GestionProjet.Client> GetProjectClient()
    {
        var req = from prj in db.Projets
                  from clt in db.Clients
                  where clt.ID == prj.IDClient
                                  select new
                                  {
                                      Name=clt.Name,
                                      Projet = prj.Title,
                                  };
        List<GestionProjet.Client> clientProjectList = new List<GestionProjet.Client>();
      foreach (var clt in req)
        {
//I Don't know what to do in here and get the Data From both of the Tables
        }

    }
 }
</code>```

GestionProjetBusiness Project

GestionProjetB Class :

```<code> public class GestionProjetB
{
    private GestionProjetDAL.GestionProjetDA GPDA = new GestionProjetDAL.GestionProjetDA();

    public List<Client> GetClients()
    {
        return GPDA.GetClients();
    }

  //Here i Should put the 2nd Method

}
</code>```

Well as you can see i have no problem with getting data from one table but the only problem is getting it from multiple tables.

i've been look for a solution the whole night but i didn't find it please help me
thanks

答:
Create a DTO class,
something like:

```<code>public class ClientDTO
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string ProjectName { get; set; }
    }
</code>```

now write a good linq expression to fill the DTO class:

```<code> public List<GestionProjet.Client> GetProjectClient()
    {
        return (from prj in db.Projets
                  join clt in db.Clients on prj.IDClient equals clt.ID
                                  select new ClientDTO
                                  {
                                      Name = clt.Name,
                                      ProjetName = prj.Title,
                                      ID = clt.ID
                                  }).ToList();

    }
</code>```

I hope I understood your problem right, and pardon me for not testing the code before posting.

Body:
hello everyone i have a problem with my 3-tiers application i don't know how to get data from multiple tables using linq2sql in 3 tiers architecture application here is each layers code

GestionProjetCommon Project

Client Class :

public class Client
{
    private int _ID;
    public int ID
    {
        get { return _ID; }
        set { _ID = value; }
    }
    private string _Name;
    public string Name
    {
        get { return _Name; }
        set { _Name = value; }
    }

}

Project Class :

public class Projet
{
    private int _ID;
    public int ID
    {
        get { return _ID; }
        set { _ID = value; }
    }
    private string _Title;
    public string Title        {

        get { return _Title; }
        set { _Title= value; }

    }

   private int _IDClient;
    public int IDClient
    {
        get { return _IDClient; }
        set { _IDClient = value; }
    }
}

GestionProjetDAL Project

GestionProjetDA Class :

public class GestionProjetDA
{
    private GestionProjetDADataContext db = new GestionProjetDADataContext();
    public List<GestionProjet.Client> GetClients() //This Works Fine No Problem !
    {
        var req = from clt in db.Clients select clt;

        List<GestionProjet.Client> clientList = new List<GestionProjet.Client>();
        foreach (Clients item in req)
        {
            clientList.Add(new GestionProjet.Client() { ID = item.ID, Nom = item.Nom });
        }
        return clientList;
    }

public List<GestionProjet.Client> GetProjectClient()
    {
        var req = from prj in db.Projets
                  from clt in db.Clients
                  where clt.ID == prj.IDClient
                                  select new
                                  {
                                      Name=clt.Name,
                                      Projet = prj.Title,
                                  };
        List<GestionProjet.Client> clientProjectList = new List<GestionProjet.Client>();
      foreach (var clt in req)
        {
//I Don't know what to do in here and get the Data From both of the Tables
        }

    }
 }

GestionProjetBusiness Project

GestionProjetB Class :

 public class GestionProjetB
{
    private GestionProjetDAL.GestionProjetDA GPDA = new GestionProjetDAL.GestionProjetDA();

    public List<Client> GetClients()
    {
        return GPDA.GetClients();
    }

  //Here i Should put the 2nd Method

}

Well as you can see i have no problem with getting data from one table but the only problem is getting it from multiple tables.

i've been look for a solution the whole night but i didn't find it please help me
thanks

Body:
Create a DTO class,
something like:

public class ClientDTO
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string ProjectName { get; set; }
    }

now write a good linq expression to fill the DTO class:

 public List<GestionProjet.Client> GetProjectClient()
    {
        return (from prj in db.Projets
                  join clt in db.Clients on prj.IDClient equals clt.ID
                                  select new ClientDTO
                                  {
                                      Name = clt.Name,
                                      ProjetName = prj.Title,
                                      ID = clt.ID
                                  }).ToList();

    }

I hope I understood your problem right, and pardon me for not testing the code before posting.


问:
GNU Assembler .long Declaration Zeroed Out
When assembling code with GNU Binutils declarations such as:

```<code>.long MY_Label
.long MY_Second_label
</code>```

Assemble without errors but consistently map to zeroed out 32-bit strings when doing a hex dump even when opcodes and other information separate them in the address space. I'm compiling with:

```<code>m68k-elf-gcc -c hello.s -o rom.o -nostdlib -static && m68k-elf-objcopy -O binary rom.o rom.bin
</code>```

And dumping my binary with:

```<code>m68k-elf-objdump -D -m m68k --start-address=0x0000 --prefix-addresses -l -x -b binary --disassemble-zeroes rom.bin
</code>```

What am I missing in my assembly code?

答:
You never linked your .o relocatable so the addresses are still placeholders.  -c tells GCC not to link, just assemble, so -static and -nostdlib are meaningless.

If you use objdump -drwC rom.o you'll see the symbol relocations next to the disassembly (-r option).

Remove the -c from the initial command and keep everything else the same:

```<code>m68k-elf-gcc  hello.s -o rom.elf  -nostdlib -static
</code>```

Body:
When assembling code with GNU Binutils declarations such as:

.long MY_Label
.long MY_Second_label

Assemble without errors but consistently map to zeroed out 32-bit strings when doing a hex dump even when opcodes and other information separate them in the address space. I'm compiling with:

m68k-elf-gcc -c hello.s -o rom.o -nostdlib -static && m68k-elf-objcopy -O binary rom.o rom.bin

And dumping my binary with:

m68k-elf-objdump -D -m m68k --start-address=0x0000 --prefix-addresses -l -x -b binary --disassemble-zeroes rom.bin

What am I missing in my assembly code?

Body:
You never linked your .o relocatable so the addresses are still placeholders.  -c tells GCC not to link, just assemble, so -static and -nostdlib are meaningless.

If you use objdump -drwC rom.o you'll see the symbol relocations next to the disassembly (-r option).

Remove the -c from the initial command and keep everything else the same:

m68k-elf-gcc  hello.s -o rom.elf  -nostdlib -static


问:
Edit DataGridViewCell on readonly object property
I've bound a DataGridView to a BindingList<MyObj> which has the Value property readonly (protected).

So there I have a method to change its value (MyObj.SetValue(string newValue)).

The standard behavior of DataGridView is also to lock the cell editing, but there's no way to "simulate" an editing and then pass the correct method to update the value?

I tried to set the column.ReadOnly = false, but it throws an exception. It doesn't fire the CellBeginEdit event, so will I have to create another textbox in front of it to do this?

答:
As per MSDN, it would seem the only exception will be:

Exceptions
  InvalidOperationException
  There is no owning row when setting this property.

-or-

The owning row is shared when setting this property.

So, check if the is actually an OwningRow, or if that row happens to be shared.

Also, the Remark section says:

The ReadOnly property indicates whether the data displayed by the cell can be edited. > > You can set ReadOnly for individual cells, or you can make an entire row or column of > > cells read-only by setting the DataGridViewRow.ReadOnly or DataGridViewColumn.ReadOnly > > properties. By default, if a cell's parent row or column is set to read-only, the child > cells will adopt the same value. You can override this default behavior by setting > > > > ReadOnly for individual cells.

You can navigate to a read-only cell, and you can set a read-only cell to be the current > cell.

ReadOnly only affects whether a cell is editable; it does not affect whether the user > > can delete rows.

Sounds like it's all there.


问:
LINQ to XML - Elements() works but Elements(XName) does not work
Given below is my xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<Report xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition">
    <Body>
        <ReportItems>
            <Textbox Name="txtCurrentDate">
                <CanGrow>true</CanGrow>
                <KeepTogether>true</KeepTogether>
                <Paragraphs>
                    <Paragraph>
                        <TextRuns>
                            <TextRun>
                                <Value>=Today()</Value>
                                <Style>
                                    <FontWeight>Medium</FontWeight>
                                    <Format>d</Format>
                                </Style>
                            </TextRun>
                        </TextRuns>
                        <Style>
                            <TextAlign>Left</TextAlign>
                        </Style>
                    </Paragraph>
                </Paragraphs>
                <Left>0.36958in</Left>
                <Height>0.22917in</Height>
                <Width>1in</Width>
                <Style>
                    <Border>
                        <Style>None</Style>
                    </Border>
                    <PaddingLeft>2pt</PaddingLeft>
                    <PaddingRight>2pt</PaddingRight>
                    <PaddingTop>2pt</PaddingTop>
                    <PaddingBottom>2pt</PaddingBottom>
                </Style>
            </Textbox>
            <Textbox Name="txtName">
                <CanGrow>true</CanGrow>
                <KeepTogether>true</KeepTogether>
                <Paragraphs>
                    <Paragraph>
                        <TextRuns>
                            <TextRun>
                                <Value>Mark Wilkinson</Value>
                                <Style />
                            </TextRun>
                        </TextRuns>
                        <Style />
                    </Paragraph>
                </Paragraphs>
                <Top>0.22917in</Top>
                <Left>0.36958in</Left>
                <Height>0.20833in</Height>
                <Width>3.22917in</Width>
                <ZIndex>1</ZIndex>
                <Style>
                    <Border>
                        <Style>None</Style>
                    </Border>
                    <PaddingLeft>2pt</PaddingLeft>
                    <PaddingRight>2pt</PaddingRight>
                    <PaddingTop>2pt</PaddingTop>
                    <PaddingBottom>2pt</PaddingBottom>
                </Style>
            </Textbox>
        </ReportItems>
        <Height>6.01667in</Height>
        <Style />
    </Body>
    <Width>7.92333in</Width>
</Report>
</code>```

I want to get all the Textbox names and values. This is what I tried and it does not work:

```<code>XDocument data = XDocument.Load("..\\..\\testxml.rdl");

            var elements = from c in data.Elements("ReportItems")
                           select c;
            foreach (var element in elements)
            {
                Console.WriteLine("Element : " + element.Attribute("Name").Value);

            }
            Console.ReadKey();
</code>```

but when I change the query to something like this

```<code>var elements = from c in data.Elements().Elements().ElementAt(0).Elements().ElementAt(0).Elements()
                           select c;
</code>```

it works.

Any help in this regard is much appreciated.

Edit: With the help of answers I was able to get the desired results. Thank you so much :)

```<code>XDocument data = XDocument.Load("..\\..\\testxml.rdl");
            XNamespace ns = data.Root.Name.Namespace;
            var elements = from c in data.Descendants(ns + "Textbox")
                           select c;
            foreach (var element in elements)
            {
                Console.WriteLine("Element : " + element.Attribute("Name").Value);
            }
            Console.ReadKey();
</code>```

TIA.

Raja

答:
You are looking for Descendants() not Elements() in this case.  Elements() only selects immediate children.

Documentation

XContainer.Descendants Method (XName) - Returns a filtered collection of the descendant elements for this document or element, in document order. Only elements that have a matching XName are included in the collection

XContainer.Elements Method (XName) - Returns a filtered collection of the child elements of this element or document, in document order. Only elements that have a matching XName are included in the collection.

Note: Based on your sample code, using Descendants() will still throw an exception because not all of the ReportItems elements have a Name attribute.  You need to do something like Console.WriteLine("Element : " + (element.Attributes("Name").Any() ? element.Attribute("Name").Value : "(no name)") );

Body:
Given below is my xml:

<?xml version="1.0" encoding="utf-8"?>
<Report xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition">

        <ReportItems>
            <Textbox Name="txtCurrentDate">
                <CanGrow>true</CanGrow>
                <KeepTogether>true</KeepTogether>
                <Paragraphs>
                    <Paragraph>
                        <TextRuns>
                            <TextRun>
                                <Value>=Today()</Value>

                            </TextRun>
                        </TextRuns>

                    </Paragraph>
                </Paragraphs>
                <Left>0.36958in</Left>
                <Height>0.22917in</Height>
                <Width>1in</Width>

                    </Border>
                    <PaddingLeft>2pt</PaddingLeft>
                    <PaddingRight>2pt</PaddingRight>
                    <PaddingTop>2pt</PaddingTop>
                    <PaddingBottom>2pt</PaddingBottom>
                </Style>
            </Textbox>
            <Textbox Name="txtName">
                <CanGrow>true</CanGrow>
                <KeepTogether>true</KeepTogether>
                <Paragraphs>
                    <Paragraph>
                        <TextRuns>
                            <TextRun>
                                <Value>Mark Wilkinson</Value>

                    </Border>
                    <PaddingLeft>2pt</PaddingLeft>
                    <PaddingRight>2pt</PaddingRight>
                    <PaddingTop>2pt</PaddingTop>
                    <PaddingBottom>2pt</PaddingBottom>
                </Style>
            </Textbox>
        </ReportItems>
        <Height>6.01667in</Height>


问:
Getting Null Value joining 3 tables
Below is the Query,I had joined 3 tables supplier is main table. The actual scenario is I want all the data from table account payable table though it is not their in purchase order table, so I have joined using FULL Outer with supplier and Purchase Order, but the supplier details were not coming against the data of account payable though supplier key is available.

```<code>SELECT ISNULL(dbo.Supplier.supplier_key,dbo.Fact_AccountPayables.supplier_key) AS supplier_key,
                  dbo.Supplier.Supplier,
                  dbo.Supplier.Name,
                  dbo.Supplier.Status,
                  dbo.Supplier.AddressCode,
                  dbo.Supplier.Address,
                  dbo.Supplier.HouseNo,
                  dbo.Supplier.Street,
                  dbo.Supplier.City,
                  dbo.Supplier.Country,
                  dbo.Supplier.ZipCode,
                  dbo.Supplier.StartDate,
                  dbo.Supplier.CreditLimit,
                  dbo.Supplier.FinancialGroup,
                  dbo.Supplier.LastTransactionDate,
                  dbo.Fact_PurchaseOrder.Company,
                  ISNULL(dbo.Fact_PurchaseOrder.[Purchase Order],dbo.Fact_AccountPayables.[PO Number]) AS PurchaseOrder,
                  ISNULL( dbo.Fact_PurchaseOrder.Sequence,dbo.Fact_AccountPayables.Line) AS POSequence,
                  dbo.Fact_PurchaseOrder.[Order Quantity],
                  dbo.Fact_PurchaseOrder.[Per Purchase Unit],
                  dbo.Fact_PurchaseOrder.[Per Quantity Price],
                  dbo.Fact_PurchaseOrder.[Purchase price unit],
                  dbo.Fact_PurchaseOrder.[Total Order Amount],
                  dbo.Fact_PurchaseOrder.Currency,
                  dbo.Fact_PurchaseOrder.[Rate Date],
                  dbo.Fact_PurchaseOrder.[Actual Receipt Date],
                  dbo.Fact_PurchaseOrder.[Receipt No],
                  dbo.Fact_PurchaseOrder.[Receipt Sequence],
                  dbo.Fact_PurchaseOrder.[Received Quantity],
                  dbo.Fact_PurchaseOrder.[Approved Quantity],
                  dbo.Fact_PurchaseOrder.[Purchase Office],
                  dbo.Fact_PurchaseOrder.[Invoice Number],
                  dbo.Fact_PurchaseOrder.[Invoice Date],
                  dbo.Fact_PurchaseOrder.[Invoice Quantity],
                  dbo.Fact_PurchaseOrder.[Invoice Amount],
                  dbo.Fact_AccountPayables.InvoiceNumber,
                  dbo.Fact_AccountPayables.Type AS InvoiceType,
                  dbo.Fact_AccountPayables.[Order Type] AS OrderInvoiceType,
                  dbo.Fact_AccountPayables.AP_Balance_EUR,
                  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
                  dbo.Fact_AccountPayables.supplier_key AS EXPR2,
                  dbo.Fact_AccountPayables.[IntercompanyTrade Order No] AS EXPR23,
                  dbo.Fact_AccountPayables.[IntercompanyTrade Line Number] AS EXPR24,
                  dbo.Fact_AccountPayables.[Intercompany Trade Financial Company] AS EXPR25,
                  dbo.Fact_AccountPayables.[Intercompany Trade Purchase Company] AS EXPR26,
                  dbo.Fact_AccountPayables.InvoiceNumber,
                  dbo.Fact_AccountPayables.DueDate,
                  dbo.Fact_AccountPayables.DocDate,
                  dbo.Fact_PurchaseOrder.[Order Date],
                  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
                  (CASE WHEN dbo.Fact_PurchaseOrder.[Receipt No] = ' ' THEN dbo.Fact_PurchaseOrder.[Total Order Amount]
                        WHEN  dbo.Fact_PurchaseOrder.[Receipt No] != ' ' and dbo.Fact_AccountPayables.InvoiceNumber IS NULL then dbo.Fact_PurchaseOrder.[Total Order Amount] END) AS ORDERBALANCE,
                  (dbo.Supplier.CreditLimit -(ORDERBALANCE + dbo.Fact_AccountPayables.[Invoice Amount_EUR])) AS Availablecredit
    FROM            dbo.Supplier
            LEFT OUTER JOIN dbo.Fact_PurchaseOrder ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key
            full OUTER JOIN dbo.Fact_AccountPayables ON dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key AND
                                                        dbo.Fact_AccountPayables.[PO Number] = dbo.Fact_PurchaseOrder.[Purchase Order]   AND
                                                    dbo.Fact_AccountPayables.[PO Line] = dbo.Fact_PurchaseOrder.Sequence
</code>```

The output is like this:

答:
You have used not only supplier key, but also PO number and PO line as join criterion with full outer join. If there is no  matching entry for these (matching entries for ALL join criteria in the same time) in supplier table you will also see the null values you mentioned.

Just for testing remove temporarily the other join criteria (PO number and line) and leave only the supplier key. Check if you still see the null values in this case.

Title: Getting Null Value joining 3 tables

Body:
Below is the Query,I had joined 3 tables supplier is main table. The actual scenario is I want all the data from table account payable table though it is not their in purchase order table, so I have joined using FULL Outer with supplier and Purchase Order, but the supplier details were not coming against the data of account payable though supplier key is available.

SELECT ISNULL(dbo.Supplier.supplier_key,dbo.Fact_AccountPayables.supplier_key) AS supplier_key,
                  dbo.Supplier.Supplier,
                  dbo.Supplier.Name,
                  dbo.Supplier.Status,
                  dbo.Supplier.AddressCode,
                  dbo.Supplier.Address,
                  dbo.Supplier.HouseNo,
                  dbo.Supplier.Street,
                  dbo.Supplier.City,
                  dbo.Supplier.Country,
                  dbo.Supplier.ZipCode,
                  dbo.Supplier.StartDate,
                  dbo.Supplier.CreditLimit,
                  dbo.Supplier.FinancialGroup,
                  dbo.Supplier.LastTransactionDate,
                  dbo.Fact_PurchaseOrder.Company,
                  ISNULL(dbo.Fact_PurchaseOrder.[Purchase Order],dbo.Fact_AccountPayables.[PO Number]) AS PurchaseOrder,
                  ISNULL( dbo.Fact_PurchaseOrder.Sequence,dbo.Fact_AccountPayables.Line) AS POSequence,
                  dbo.Fact_PurchaseOrder.[Order Quantity],
                  dbo.Fact_PurchaseOrder.[Per Purchase Unit],
                  dbo.Fact_PurchaseOrder.[Per Quantity Price],
                  dbo.Fact_PurchaseOrder.[Purchase price unit],
                  dbo.Fact_PurchaseOrder.[Total Order Amount],
                  dbo.Fact_PurchaseOrder.Currency,
                  dbo.Fact_PurchaseOrder.[Rate Date],
                  dbo.Fact_PurchaseOrder.[Actual Receipt Date],
                  dbo.Fact_PurchaseOrder.[Receipt No],
                  dbo.Fact_PurchaseOrder.[Receipt Sequence],
                  dbo.Fact_PurchaseOrder.[Received Quantity],
                  dbo.Fact_PurchaseOrder.[Approved Quantity],
                  dbo.Fact_PurchaseOrder.[Purchase Office],
                  dbo.Fact_PurchaseOrder.[Invoice Number],
                  dbo.Fact_PurchaseOrder.[Invoice Date],
                  dbo.Fact_PurchaseOrder.[Invoice Quantity],
                  dbo.Fact_PurchaseOrder.[Invoice Amount],
                  dbo.Fact_AccountPayables.InvoiceNumber,
                  dbo.Fact_AccountPayables.Type AS InvoiceType,
                  dbo.Fact_AccountPayables.[Order Type] AS OrderInvoiceType,
                  dbo.Fact_AccountPayables.AP_Balance_EUR,
                  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
                  dbo.Fact_AccountPayables.supplier_key AS EXPR2,
                  dbo.Fact_AccountPayables.[IntercompanyTrade Order No] AS EXPR23,
                  dbo.Fact_AccountPayables.[IntercompanyTrade Line Number] AS EXPR24,
                  dbo.Fact_AccountPayables.[Intercompany Trade Financial Company] AS EXPR25,
                  dbo.Fact_AccountPayables.[Intercompany Trade Purchase Company] AS EXPR26,
                  dbo.Fact_AccountPayables.InvoiceNumber,
                  dbo.Fact_AccountPayables.DueDate,
                  dbo.Fact_AccountPayables.DocDate,
                  dbo.Fact_PurchaseOrder.[Order Date],
                  dbo.Fact_AccountPayables.[Invoice Amount_EUR],
                  (CASE WHEN dbo.Fact_PurchaseOrder.[Receipt No] = ' ' THEN dbo.Fact_PurchaseOrder.[Total Order Amount]
                        WHEN  dbo.Fact_PurchaseOrder.[Receipt No] != ' ' and dbo.Fact_AccountPayables.InvoiceNumber IS NULL then dbo.Fact_PurchaseOrder.[Total Order Amount] END) AS ORDERBALANCE,
                  (dbo.Supplier.CreditLimit -(ORDERBALANCE + dbo.Fact_AccountPayables.[Invoice Amount_EUR])) AS Availablecredit
    FROM            dbo.Supplier
            LEFT OUTER JOIN dbo.Fact_PurchaseOrder ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key
            full OUTER JOIN dbo.Fact_AccountPayables ON dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key AND
                                                        dbo.Fact_AccountPayables.[PO Number] = dbo.Fact_PurchaseOrder.[Purchase Order]   AND
                                                    dbo.Fact_AccountPayables.[PO Line] = dbo.Fact_PurchaseOrder.Sequence

The output is like this:


问:
How to Change Class Name Based on Array's Elements?
I'm a JavaScript newbie so kindly use accessible language.

From the code below, I want to change the class name on certain array elements;
that is for elements orange, yellow, violet to use class btn btn-outline-dark instead. Also, can this be done without adding id or class attributes that's not Bootstrap inside the html (something like document.getElementById() is not desirable)?

I tried:

```<code>function Rainbow(){
    body.style.backgroundColor = colors[index % colors.length]
    index++
    if(index=1,index=2,index=5){
        button.className = 'btn btn-outline-dark'
    }
}
</code>```

but it doesn't work.

Full code (also feel free to improve/fix anything else inside):

```<code><!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <title>Rainbow Colors</title>
    </head>
    <body>
        <div class="container">
            <div class="row vh-100 d-flex align-items-center">
                <div class="col text-center">
                    <button class="btn btn-outline-light">Rainbow</button>
                </div>
            </div>
        </div>

        <script>
            const colors = ['red','orange','yellow','green','blue','violet'],
            body = document.querySelector('body'),
            button = document.querySelector('button')
            let index = 1

            body.style.backgroundColor = colors[0]
            button.onclick = Rainbow

            function Rainbow(){
                body.style.backgroundColor = colors[index % colors.length]
                index++
            }
        </script>
    </body>
</html>
</code>```

答:
This is what you might be looking for, I'm not sure which version of JS you are using but here's an answer</p>

```<code><!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <title>Rainbow Colors</title>
    </head>
    <body>
        <div class="container">
            <div class="row vh-100 d-flex align-items-center">
                <div class="col text-center">
                    <button class="btn btn-outline-light">Rainbow</button>
                </div>
            </div>
        </div>

        <script>
            const colors = ['red','orange','yellow','green','blue','violet'],
            body = document.querySelector('body'),
            button = document.querySelector('button')
            let index = 1

            body.style.backgroundColor = colors[0]
            button.onclick = Rainbow

            function Rainbow(){
                body.style.backgroundColor = colors[index % colors.length]
                color = index % colors.length;
                index++;
                if(color == 1 || color == 2 || color == 5){
                    button.className = 'btn btn-outline-dark'
                }
                else{
                    button.className = 'btn btn-outline-light'
                }
            }
        </script>
    </body>
</html>
</code>```

Body:
I'm a JavaScript newbie so kindly use accessible language.

From the code below, I want to change the class name on certain array elements;
that is for elements orange, yellow, violet to use class btn btn-outline-dark instead. Also, can this be done without adding id or class attributes that's not Bootstrap inside the html (something like document.getElementById() is not desirable)?

I tried:

function Rainbow(){
    body.style.backgroundColor = colors[index % colors.length]
    index++
    if(index=1,index=2,index=5){
        button.className = 'btn btn-outline-dark'
    }
}

but it doesn't work.

Full code (also feel free to improve/fix anything else inside):

<!doctype html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <title>Rainbow Colors</title>

                    <button class="btn btn-outline-light">Rainbow</button>

Body:
This is what you might be looking for, I'm not sure which version of JS you are using but here's an answer

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <title>Rainbow Colors</title>
    </head>
    <body>
        <div class="container">
            <div class="row vh-100 d-flex align-items-center">
                <div class="col text-center">
                    <button class="btn btn-outline-light">Rainbow</button>
                </div>
            </div>
        </div>

        <script>
            const colors = ['red','orange','yellow','green','blue','violet'],
            body = document.querySelector('body'),
            button = document.querySelector('button')
            let index = 1

            body.style.backgroundColor = colors[0]
            button.onclick = Rainbow

            function Rainbow(){
                body.style.backgroundColor = colors[index % colors.length]
                color = index % colors.length;
                index++;
                if(color == 1 || color == 2 || color == 5){
                    button.className = 'btn btn-outline-dark'
                }
                else{
                    button.className = 'btn btn-outline-light'
                }
            }
        </script>
    </body>
</html>


问:
Get latest USN data from Change Journal
The MSDN C++ code only shows how to obtain the change journal records starting from the buffer.
MSDN Code for Reading Change Journal.

My query is how do I fetch just the latest USN records from Change journal. I've increased the buffer size to my requirement.
#define BUF_LEN 789824
Also, I cannot set the buffer to the maximum size as it violates the DWORD max size limit.

The command fsutils usn readjournal c: takes a lot of time to show the output. So, how do I fetch only the latest records from the journal using c++?

答:
Adding a large buffer leads to large memory allocation, which in turn leads to performance degradation. A workaround for this is to keep #define BUF_LEN 4096 (a small value) and increase the value of iterations to the maximum size of the change journal.

```<code>for (I = 0; I <= 2415919104; I++)
</code>```

Here, the large value is simply the output returned by fsutil usn queryjournal C: (or any NTFS journal). Maximum Size     : 0x0000000090000000. (Convert hex value to decimal value)

This worked for me. Hope this helps someone.

Title: Get latest USN data from Change Journal

Body:
Adding a large buffer leads to large memory allocation, which in turn leads to performance degradation. A workaround for this is to keep #define BUF_LEN 4096 (a small value) and increase the value of iterations to the maximum size of the change journal.

for (I = 0; I <= 2415919104; I++)

Here, the large value is simply the output returned by fsutil usn queryjournal C: (or any NTFS journal). Maximum Size     : 0x0000000090000000. (Convert hex value to decimal value)

This worked for me. Hope this helps someone.


问:
the Objective of this program is supposed to be printing cube
cube of Randomly generated values which is not happeneing if I return the value from the main function.If I don't return it in the main function and print it in the user defined function then it is working properly. Where I have used pointers its mandatory.</p>

```<code>#include<iostream>
#include<ctime>
using namespace std;

int* cube(int* ar)
{
    int re[50];
    for (int i = 0; i < 50; i++)
    {
        re[i] = *(ar + i) * *(ar + i)* *(ar + i);

    }
    return re;
}

int main()
{
    srand(time(NULL));
    int ar[50],
        cub[50];
    for (int i = 0; i < 50; i++)
    {
        ar[i] = (rand() % (99 - 50)) + 50;

    }
    int *ptr;
    cout << "Sr.#\tValue\tCube\n";
    ptr = cube(ar);  // this receives the value being returned from the function
    for (int i = 0; i < 50; i++)
    {
        cout << i << '\t' << ar[i] << '\t' << *(ptr + i) << endl;
    }
    return 0;
}
</code>```

答:
It is a bad idea to return pointers or references to local variables.
replace

```<code>int re[50];
</code>```

with

```<code>int* re=new int[50];
</code>```

Body:
cube of Randomly generated values which is not happeneing if I return the value from the main function.If I don't return it in the main function and print it in the user defined function then it is working properly. Where I have used pointers its mandatory.

#include<iostream>
#include<ctime>
using namespace std;

int* cube(int* ar)
{
    int re[50];
    for (int i = 0; i < 50; i++)
    {
        re[i] = *(ar + i) * *(ar + i)* *(ar + i);

    }
    return re;
}

int main()
{
    srand(time(NULL));
    int ar[50],
        cub[50];
    for (int i = 0; i < 50; i++)
    {
        ar[i] = (rand() % (99 - 50)) + 50;

    }
    int *ptr;
    cout << "Sr.#\tValue\tCube\n";
    ptr = cube(ar);  // this receives the value being returned from the function
    for (int i = 0; i < 50; i++)
    {
        cout << i << '\t' << ar[i] << '\t' << *(ptr + i) << endl;
    }
    return 0;
}

Body:
It is a bad idea to return pointers or references to local variables.
replace

int re[50];

with

int* re=new int[50];


问:
Rust trait alias
I am working on a actor project which need alias for the trait because it is so long, but even with the nightly feature #![feature(trait_alias)] seems can not achieve.

In short I write a playground:
I want alias A<T> to be shorter causing I have many generic type on A in real case; and the same time I want to access the type Output = Self; from its implementations B.
Appreciate for any help.

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=5a9bb8d3f76112c0b73ea1da8af34959

```<code>#![feature(trait_alias)]

trait A<T> {
    type Output;
    fn test(a: T) -> Self::Output;
}

//To alias the trait, real situation longer than this.
//attempt 1:
trait B: A<String>{}

//attempt 2:
//trait B : A<String, Output=Self> where Self: std::marker::Sized {}
//impl<T> B for T where T: A<String, Output=T> {}

//attempt 3 with trait_alias:
//trait B = A<String>;

struct SA;

impl B for SA {
    type Output = Self;
}

</code>```

答:
trait alias is only mean to be:

used wherever traits would normally be used as either bounds or trait objects. Source

So, your use case doesn't match, you can't do that.

Title: Rust trait alias

Body:
I am working on a actor project which need alias for the trait because it is so long, but even with the nightly feature #![feature(trait_alias)] seems can not achieve.

In short I write a playground:
I want alias A<T> to be shorter causing I have many generic type on A in real case; and the same time I want to access the type Output = Self; from its implementations B.
Appreciate for any help.

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=5a9bb8d3f76112c0b73ea1da8af34959

#![feature(trait_alias)]

trait A<T> {
    type Output;
    fn test(a: T) -> Self::Output;
}

//To alias the trait, real situation longer than this.
//attempt 1:
trait B: A<String>{}

//attempt 2:
//trait B : A<String, Output=Self> where Self: std::marker::Sized {}
//impl<T> B for T where T: A<String, Output=T> {}

//attempt 3 with trait_alias:
//trait B = A<String>;

struct SA;

impl B for SA {
    type Output = Self;
}


问:
Using jQuery to post back to a controller
I'm using jQuery to post back to my controller, but i'm wondering how you pass values as parameters in the ActionResult.  For example:

I have a jQuery post:

```<code>$.post("Home\PostExample")
</code>```

but i would like to include a value from a dropdown menu:

```<code>@Html.DropDownListFor(m => m.Example, Model.Example, new { @id = "exampleCssId" })
</code>```

into an Actionresult:

```<code>[HttpPost]
public ActionResult PostExample(string myString)
{
    //TODO: Write contents of ActionResult
}
</code>```

Any help would be appreciated.

Thanks.

答:
Here's an example from something I did recently:</p>

```<code>function SaveNewGoal() {
    var data = { Name_E: $("#NewGoal #Name_E").val(),
        Name_F: $("#NewGoal #Name_F").val(),
        Desc_E: $("#NewGoal #Desc_E").val(),
        Desc_F: $("#NewGoal #Desc_F").val()
    };

    $.ajax({
        url: '@Url.Action("CreateJson", "Goal")',
        data: JSON.stringify(data),
        success: SaveNewGoalSuccess,
        error: SaveNewGoalError,
        cache: false,
        type: 'POST',
        contentType: 'application/json, charset=utf-8',
        dataType: 'json'
    });
}

function SaveNewGoalSuccess(data, textStatus, jqXHR) {
    $("#NewGoalContainer").hide();
    // reload the goal list
    ReloadGoals();
}

function SaveNewGoalError(jqXHR, textStatus, errorThrown) {
    $("#NewGoalResult").text("Error: " + jqXHR.responseText);
}
</code>```

Body:
I'm using jQuery to post back to my controller, but i'm wondering how you pass values as parameters in the ActionResult.  For example:

I have a jQuery post:

$.post("Home\PostExample")

but i would like to include a value from a dropdown menu:

@Html.DropDownListFor(m => m.Example, Model.Example, new { @id = "exampleCssId" })

into an Actionresult:

[HttpPost]
public ActionResult PostExample(string myString)
{
    //TODO: Write contents of ActionResult
}

Any help would be appreciated.

Thanks.

Body:
Here's an example from something I did recently:

function SaveNewGoal() {
    var data = { Name_E: $("#NewGoal #Name_E").val(),
        Name_F: $("#NewGoal #Name_F").val(),
        Desc_E: $("#NewGoal #Desc_E").val(),
        Desc_F: $("#NewGoal #Desc_F").val()
    };

    $.ajax({
        url: '@Url.Action("CreateJson", "Goal")',
        data: JSON.stringify(data),
        success: SaveNewGoalSuccess,
        error: SaveNewGoalError,
        cache: false,
        type: 'POST',
        contentType: 'application/json, charset=utf-8',
        dataType: 'json'
    });
}

function SaveNewGoalSuccess(data, textStatus, jqXHR) {
    $("#NewGoalContainer").hide();
    // reload the goal list
    ReloadGoals();
}

function SaveNewGoalError(jqXHR, textStatus, errorThrown) {
    $("#NewGoalResult").text("Error: " + jqXHR.responseText);
}


问:
Understanding nested decorators missing required positional argument error
I wrote two decorators, verbose controls whether or not the defined function prints it's output, announcer will announce when the function is called.

```<code>import os
import sys

def verbose(func):
    '''Sets verbose mode on function'''
    @functools.wraps(func)
    def wrapper_func(verbboo=True, *args, **kwargs):
        # disabling print
        if not verbboo:
            sys.stdout = open(os.devnull, 'w')
        # running func
        ret = func(*args, **kwargs)
        # enabling print again
        if not verbboo:
            sys.stdout = sys.__stdout__
        return ret
    return wrapper_func

def announcer(func, endboo=True):
    '''anounces when function is called and when it finishes; if specified'''
    @functools.wraps(func)
    def wrapper_func(*args, **kwargs):
        print('run {}.{}@{:%Y%m%d%H%M}'.format(
            func.__module__, func.__name__,
            dt.datetime.now())
        )
        ret = func(*args, **kwargs)
        if endboo:
            print('end {}.{}@{:%Y%m%d%H%M}'.format(
                func.__module__, func.__name__,
                dt.datetime.now())
            )
        return ret
    return wrapper_func
</code>```

I then nest the following function with the decorators

```<code>@verbose
@announcer
def f(boo, opboo=True):
    if boo:
        print('This is True')
    if opboo:
        print('This is also True')

    return f

# testing
f(True)
</code>```

But I receive the following error

```<code>run __main__.f@202006021152
Traceback (most recent call last):
  File "/home/user/anaconda3/envs/mpl/lib/python3.8/runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/home/user/anaconda3/envs/mpl/lib/python3.8/runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "/home/user/project/test.py", line 17, in <module>
    f(True)
  File "/home/user/project/decorators.py", line 18, in wrapper_func
    ret = func(*args, **kwargs)
  File "/home/user/project/decorators.py", line 47, in wrapper_func
    ret = func(*args, **kwargs)
TypeError: f() missing 1 required positional argument: 'boo'
</code>```

The error only occurs when I nest verbose on top of announcer. announcer by itself works fine. What is going on?

答:
I think the problem is in this line:

def wrapper_func(verbboo=True, *args, **kwargs):

A function definition has to have all of the positional arguments before any of the keyword arguments.  Probably the keyword argument verbboo interfered with the positional argument boo getting passed through.

When I put the verbboo parameter at the end, it still didn't run, but when I put it between *args and **kwargs, it did run.

Body:
I wrote two decorators, verbose controls whether or not the defined function prints it's output, announcer will announce when the function is called.

import os
import sys

def verbose(func):
    '''Sets verbose mode on function'''
    @functools.wraps(func)
    def wrapper_func(verbboo=True, *args, **kwargs):
        # disabling print
        if not verbboo:
            sys.stdout = open(os.devnull, 'w')
        # running func
        ret = func(*args, **kwargs)
        # enabling print again
        if not verbboo:
            sys.stdout = sys.__stdout__
        return ret
    return wrapper_func

def announcer(func, endboo=True):
    '''anounces when function is called and when it finishes; if specified'''
    @functools.wraps(func)
    def wrapper_func(*args, **kwargs):
        print('run {}.{}@{:%Y%m%d%H%M}'.format(
            func.__module__, func.__name__,
            dt.datetime.now())
        )
        ret = func(*args, **kwargs)
        if endboo:
            print('end {}.{}@{:%Y%m%d%H%M}'.format(
                func.__module__, func.__name__,
                dt.datetime.now())
            )
        return ret
    return wrapper_func

I then nest the following function with the decorators

@verbose
@announcer
def f(boo, opboo=True):
    if boo:
        print('This is True')
    if opboo:
        print('This is also True')

    return f

# testing
f(True)

But I receive the following error

run __main__.f@202006021152
Traceback (most recent call last):
  File "/home/user/anaconda3/envs/mpl/lib/python3.8/runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/home/user/anaconda3/envs/mpl/lib/python3.8/runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "/home/user/project/test.py", line 17, in <module>
    f(True)
  File "/home/user/project/decorators.py", line 18, in wrapper_func
    ret = func(*args, **kwargs)
  File "/home/user/project/decorators.py", line 47, in wrapper_func
    ret = func(*args, **kwargs)
TypeError: f() missing 1 required positional argument: 'boo'

The error only occurs when I nest verbose on top of announcer. announcer by itself works fine. What is going on?


答:
Try your Payable table after that FROM Clause and join the other tables by using LEFT JOIN

```<code>FROM dbo.Fact_AccountPayables
LEFT JOIN dbo.Fact_PurchaseOrder ON  dbo.Fact_AccountPayables.[PO Number] =  dbo.Fact_PurchaseOrder.[Purchase Order]   AND
 dbo.Fact_AccountPayables.[PO Line] =  dbo.Fact_PurchaseOrder.Sequence
LRFT JOIN dbo.Supplier  ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key AND dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key
</code>```

Title: Getting Null Value joining 3 tables

Body:
Try your Payable table after that FROM Clause and join the other tables by using LEFT JOIN

FROM dbo.Fact_AccountPayables
LEFT JOIN dbo.Fact_PurchaseOrder ON  dbo.Fact_AccountPayables.[PO Number] =  dbo.Fact_PurchaseOrder.[Purchase Order]   AND
 dbo.Fact_AccountPayables.[PO Line] =  dbo.Fact_PurchaseOrder.Sequence
LRFT JOIN dbo.Supplier  ON dbo.Supplier.supplier_key = dbo.Fact_PurchaseOrder.buyfrom_supplier_key AND dbo.Fact_AccountPayables.supplier_key = dbo.Supplier.supplier_key


问:
replace string based on array items loop in php
On my website, I have comments.

In my comment string, I find all username mentions like so (username mentions start with /u/, for example /u/felix):

```<code>preg_match_all('#/u/([a-z0-9]+)#i', $comment, $matches);
</code>```

Now I have an array of usernames called $matches.

I want to then replace all username matches in $comment with something like this:

```<code><a href="/u/felix">/u/felix</a>
</code>```

I tried doing a foreach solution with a str_replace, however I run into the problem of having users that contain the usernames of other users. So if we had the users "fel", feli" and "felix, the loop would do it 3 times for "fel".

How can I do this?

答:
If you don't need to extract the usernames, just replace them all at once with a single regexp:

```<code>preg_replace( '#(/u/[a-z0-9]+)#i', '<a href="$1">$1</a>', $comment );
</code>```

No need to worry about similar usernames since each will be matched and replaced without affecting the others.

Body:
On my website, I have comments.

In my comment string, I find all username mentions like so (username mentions start with /u/, for example /u/felix):

preg_match_all('#/u/([a-z0-9]+)#i', $comment, $matches);

Now I have an array of usernames called $matches.

I want to then replace all username matches in $comment with something like this:

/u/felix

I tried doing a foreach solution with a str_replace, however I run into the problem of having users that contain the usernames of other users. So if we had the users "fel", feli" and "felix, the loop would do it 3 times for "fel".

How can I do this?

Body:
If you don't need to extract the usernames, just replace them all at once with a single regexp:

preg_replace( '#(/u/[a-z0-9]+)#i', '<a href="$1">$1</a>', $comment );

No need to worry about similar usernames since each will be matched and replaced without affecting the others.


问:
How do I find all the files that were created today in specific folder using Python
How do I find all the files that were created from 7AM to 7PM from folder and take it as a list in Python</p>

答:
The following code works by storing the current date in a variable(today) and looking for all files inside the directory that have their 'createdAt' timestamp matching that of today's value.</p>

```<code>import os
import datetime as dt

today = dt.datetime.now().date()
dir = "C:/Dev"  #path to directory

for file in os.listdir(dir):
    filetime = dt.datetime.fromtimestamp(
            os.path.getctime(dir + file))
    if filetime.date() == today:
        print(file)

</code>```

Body:
The following code works by storing the current date in a variable(today) and looking for all files inside the directory that have their 'createdAt' timestamp matching that of today's value.

import os
import datetime as dt

today = dt.datetime.now().date()
dir = "C:/Dev"  #path to directory

for file in os.listdir(dir):
    filetime = dt.datetime.fromtimestamp(
            os.path.getctime(dir + file))
    if filetime.date() == today:
        print(file)


问:
Using Microsoft Graph API refresh token with Delphi OAuth2
I am pretty new to OAuth2 and all of the REST components in Delphi (using 10.3 Rio).

My intention is to access the Microsoft Rest API via the Delphi REST components.

For testing, I dropped the RESTClient, RESTRequest, RESTResponse, and OAuth2 components on a Form, and entered the Application ID and Endpoint URLs in the OAuth2 interface.

When I hit "authorize", the Office 365 window pops up and wants me to log in.

Is there a chance to get around this popup, so that the login is executed automatically?

The access_token expires after an hour or so, and I need to refresh it using the refresh_token.

How can I do this with the OAuth2 component?

答:
Have a look at my sample project

https://github.com/geoffsmith82/GmailAuthSMTP

It has a Microsoft login option.  Basically you need to send offline_access as a requested scope and then save the returned refresh token for later use.  When you want to later login, you make a authentication request using the saved refresh_token to get a usable access_token.  The first time you login you will need to login via the web browser still though.


问:
DATEDIFF across several months grouped by months
I need to get this output at the bottom.

答:
There are a few parts to this, however the first part I am assuming that the work month is a date field on the first of each month. I am also assuming start and end date are date fields.

The code I would use is below. I have used "E" for employee table and "L" for Leave table for easy reading. I have also added comments in the code which should help understand.

```<code>-- Assuming the workmonth table is date field set to 1st of each month
SELECT E.EmpID,
       E.WorkMonth,
--- Below case statement is when start and end month are the same.
       CASE
           WHEN(DATEADD(month, DATEDIFF(month, (0), CONVERT([DATETIME], L.StartDate)), (0))) = (DATEADD(month, DATEDIFF(month, (0), CONVERT([DATETIME], L.EndDate)), (0)))
           THEN DATEDIFF(day, L.StartDate, L.EndDate) + 1
---- Below case statement is when you want to calculate start to end of month.
           WHEN(DATEADD(month, DATEDIFF(month, (0), CONVERT([DATETIME], L.StartDate)), (0))) = E.WorkMonth
           THEN DATEDIFF(day, L.StartDate, DATEADD(month, 1, E.WorkMonth))
---- Below case statement is when you want to calculate start of month to end date.
           WHEN(DATEADD(month, DATEDIFF(month, (0), CONVERT([DATETIME], L.endDate)), (0))) = E.WorkMonth
           THEN DATEDIFF(day, E.WorkMonth, L.EndDate) + 1
       END StartMonth

FROM dbo.EmployeeTable AS E
     inner JOIN dbo.LeavTable AS L ON E.EmpID = L.EMPID
-- The join is where you can combine the  months joining tyo the first of the month.
                                           AND E.WorkMonth >= (DATEADD(month, DATEDIFF(month, (0), CONVERT([DATETIME], L.StartDate)), (0)))
                                           AND E.WorkMonth <= (DAETEADD(month, DATEDIFF(month, (0), CONVERT([DATETIME], L.EndDate)), (0)))
</code>```

Body:
There are a few parts to this, however the first part I am assuming that the work month is a date field on the first of each month. I am also assuming start and end date are date fields.

The code I would use is below. I have used "E" for employee table and "L" for Leave table for easy reading. I have also added comments in the code which should help understand.

-- Assuming the workmonth table is date field set to 1st of each month
SELECT E.EmpID,
       E.WorkMonth,
--- Below case statement is when start and end month are the same.
       CASE
           WHEN(DATEADD(month, DATEDIFF(month, (0), CONVERT([DATETIME], L.StartDate)), (0))) = (DATEADD(month, DATEDIFF(month, (0), CONVERT([DATETIME], L.EndDate)), (0)))
           THEN DATEDIFF(day, L.StartDate, L.EndDate) + 1
---- Below case statement is when you want to calculate start to end of month.
           WHEN(DATEADD(month, DATEDIFF(month, (0), CONVERT([DATETIME], L.StartDate)), (0))) = E.WorkMonth
           THEN DATEDIFF(day, L.StartDate, DATEADD(month, 1, E.WorkMonth))
---- Below case statement is when you want to calculate start of month to end date.
           WHEN(DATEADD(month, DATEDIFF(month, (0), CONVERT([DATETIME], L.endDate)), (0))) = E.WorkMonth
           THEN DATEDIFF(day, E.WorkMonth, L.EndDate) + 1
       END StartMonth

FROM dbo.EmployeeTable AS E
     inner JOIN dbo.LeavTable AS L ON E.EmpID = L.EMPID
-- The join is where you can combine the  months joining tyo the first of the month.
                                           AND E.WorkMonth >= (DATEADD(month, DATEDIFF(month, (0), CONVERT([DATETIME], L.StartDate)), (0)))
                                           AND E.WorkMonth <= (DAETEADD(month, DATEDIFF(month, (0), CONVERT([DATETIME], L.EndDate)), (0)))


问:
Text unselectable in IE
I require one HTML element (Label) on my page to be unselectable for IE ... currently I have tried

Unselectable=on

onselectreturn=false;

none of which is helping me out.

For Firefox and Chrome i have set the following CSS property which are working absolutely fine ... but the problem as always with the IE.

CSS properties you have set:

```<code>-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
user-select: none;
</code>```

is there any alternative or IE-hack?

An answer on Stack Overflow has helped me out but not for IE.

答:
Set unselectable to off and it should work.

```<code><label unselectable="off">Something</label>
</code>```

http://jsfiddle.net/sWguE/1/

This also works for me

```<code><label onselect="return false">Something</label>
</code>```

http://jsfiddle.net/sWguE/3/

Title: Text unselectable in IE

Body:
I require one HTML element (Label) on my page to be unselectable for IE ... currently I have tried

Unselectable=on

onselectreturn=false;

none of which is helping me out.

For Firefox and Chrome i have set the following CSS property which are working absolutely fine ... but the problem as always with the IE.

CSS properties you have set:

-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
user-select: none;

is there any alternative or IE-hack?

An answer on Stack Overflow has helped me out but not for IE.

Body:
Set unselectable to off and it should work.

<label unselectable="off">Something</label>

http://jsfiddle.net/sWguE/1/

This also works for me

<label onselect="return false">Something</label>

http://jsfiddle.net/sWguE/3/


问:
Using rails associations for models (undefined method `has_one')
I am trying to open up the registration page to create an account (which has a payment) and I get this error "undefined method `has_one' for Account:Class".  I am not using a database so I am not using active record.  Is there a way around this?

account.rb

```<code>class Account
    include ActiveModel::Model

    attr_accessor :company_name, :phone_number,
                            :card_number, :expiration_month, :expiration_year, :cvv

    has_one :payment
end
</code>```

payment.rb

```<code>class Payment
  include ActiveModel::Model

  attr_accessor :card_number, :expiration_month, :expiration_year, :cvv

  belongs_to :account

  validates :card_number, presence: true, allow_blank: false
  validates :cvv, presence: true, allow_blank: false
end
</code>```

account_controller.rb

```<code>class AccountController < ApplicationController
def register
    @account = Account.new
  end
end
</code>```

答:
Certainly this is a very old question, but I ran across it while trying to solve a similar problem and eventually found that solutions have arisen in the intervening years.  So, given the only posted answer was never marked as "accepted," I thought I'd throw my hat in the ring.

Rails 5 introduced the ActiveRecord Attributes API, and by way of this post by Karol Galanciak describing it you may be interested to take a look at a gem created by the same author.  If you took a look at the issues for that gem, you might be interested to read in issue #12 that the Attributes API functionality is now present in ActiveModel, though it is not publicly documented (the module Attributes is flagged with #:nodoc:, see attributes.rb) and perhaps should not be relied upon to be consistent from version to version, though the wind, soft as it may seem at times, certainly seems to be blowing in the direction of a "public" ActiveModel::Attributes API.

Nevertheless, if you were to throw caution to the wind and use the not-quite-public ActiveModel::Attributes you could do something like this (note: I cobbled this together for my own project and rewrote it a bit to fit your example, your needs may be different than mine):

```<code>class AccountPayment
  include ActiveModel::Model

  attr_accessor :card_number, :expiration_month, :expiration_year, :cvv

  validates :card_number, presence: true, allow_blank: false
  validates :cvv, presence: true, allow_blank: false
end

class AccountPaymentType < ActiveModel::Type::Value
  def cast(value)
    AccountPayment.new(value)
  end
end

class Account
  include ActiveModel::Model
  include ActiveModel::Attributes #being bad and using private API!

  attr_accessor :company_name, :phone_number, :card_number, :expiration_month, :expiration_year, :cvv

  attribute :payment, :account_payment
end
</code>```

And somewhere you must register the type - in rails it'd be in an initializer, but in my code I just stashed it at the top of the equivalent of your Account model:

```<code>ActiveModel::Type.register(:account_payment, AccountPaymentType)
</code>```

Body:
I am trying to open up the registration page to create an account (which has a payment) and I get this error "undefined method `has_one' for Account:Class".  I am not using a database so I am not using active record.  Is there a way around this?

account.rb

class Account
    include ActiveModel::Model

    attr_accessor :company_name, :phone_number,
                            :card_number, :expiration_month, :expiration_year, :cvv

    has_one :payment
end

payment.rb

class Payment
  include ActiveModel::Model

  attr_accessor :card_number, :expiration_month, :expiration_year, :cvv

  belongs_to :account

  validates :card_number, presence: true, allow_blank: false
  validates :cvv, presence: true, allow_blank: false
end

account_controller.rb

class AccountController < ApplicationController
def register
    @account = Account.new
  end
end

Body:
Certainly this is a very old question, but I ran across it while trying to solve a similar problem and eventually found that solutions have arisen in the intervening years.  So, given the only posted answer was never marked as "accepted," I thought I'd throw my hat in the ring.

Rails 5 introduced the ActiveRecord Attributes API, and by way of this post by Karol Galanciak describing it you may be interested to take a look at a gem created by the same author.  If you took a look at the issues for that gem, you might be interested to read in issue #12 that the Attributes API functionality is now present in ActiveModel, though it is not publicly documented (the module Attributes is flagged with #:nodoc:, see attributes.rb) and perhaps should not be relied upon to be consistent from version to version, though the wind, soft as it may seem at times, certainly seems to be blowing in the direction of a "public" ActiveModel::Attributes API.

Nevertheless, if you were to throw caution to the wind and use the not-quite-public ActiveModel::Attributes you could do something like this (note: I cobbled this together for my own project and rewrote it a bit to fit your example, your needs may be different than mine):

class AccountPayment
  include ActiveModel::Model

  attr_accessor :card_number, :expiration_month, :expiration_year, :cvv

  validates :card_number, presence: true, allow_blank: false
  validates :cvv, presence: true, allow_blank: false
end

class AccountPaymentType < ActiveModel::Type::Value
  def cast(value)
    AccountPayment.new(value)
  end
end

class Account
  include ActiveModel::Model
  include ActiveModel::Attributes #being bad and using private API!

  attr_accessor :company_name, :phone_number, :card_number, :expiration_month, :expiration_year, :cvv

  attribute :payment, :account_payment
end

And somewhere you must register the type - in rails it'd be in an initializer, but in my code I just stashed it at the top of the equivalent of your Account model:

ActiveModel::Type.register(:account_payment, AccountPaymentType)


问:
How to set Javascript's variable value inside <input value=''">
I do not know how to formulate this question but it is near close to my issue. I am trying to make a Point of sale system so when client clicks in each product it adds in the table. There are no issues in my code but I do not know how to set the product's price using a textbox when using .append.

This is my code:

```<code>$(".agregarListaF").click(function (e) {
  e.preventDefault();
  var padre = $(this);
  var hijos = padre.children().children("span");
  var i = 0;
  var datos = new Array();

  hijos.each(function () {
    switch (i) {
      case 0:
        datos[0] = $(this).text();
        break;

      case 1:
        padre;
        datos[1] = $(this).text();
        break;

      case 2:
        padre;
        datos[2] = $(this).text();
        break;
    }

    i++;
  });
  console.log(datos[0]);
  console.log(datos[1]);

  $(".detallefactura").append(
    "<tr>" +
      "<td>" +
      datos[0] +
      "</td>" +
      "<td>" +
      datos[1] +
      "</td>" +
      "<td>" +
      "<input type='text' class='form-control text-center' value='1'>" +
      "</td>" +
      "<td>" +
      "<input type='text' class='form-control text-center' value=''>" +
      "</td>" +
      "<td class='tota-sub-fila'>" +
      parseFloat(Math.floor(datos[2]) * parseFloat(1)).toFixed(2) +
      "</td>"
  );
});
</code>```

My issue is in the line:

```<code> + "<td>" + "<input type='text' class='form-control text-center' value=''>" + "</td>"
</code>```

I want to add javascript value variable inside * input value=''* but I know It wont work but I tried it:

```<code>+ "<td>" + "<input type='text' class='form-control text-center' value='datos[2]'>" + "</td>"
</code>```

This is my point of sale view:

In the column precio is where I want to set the price inside that textbox.

How do I solve this?

答:
Please try this code,To How to set Javascript's variable value inside

```<code><!DOCTYPE html>
<html>

<head>
    <title>
        JavaScript| Set the value of an input field.
    </title>
</head>

<body style="text-align:center;" id="body">
    <input type='text' id='id1' />
    <br>
    <br>
    <button onclick="gfg_Run()">
        click to set
    </button>
    <p id="GFG_DOWN" style="color:green; font-size: 20px;font-weight: bold;"></p>

    <script>
        var el_down = document.getElementById("GFG_DOWN");
        var inputF = document.getElementById("id1");
        function gfg_Run() {
            inputF.setAttribute('value', 'defaultValue');
            el_down.innerHTML = "Value = " + "'" + inputF.value + "'";
        }
    </script>
</body>
</html>
</code>```

I hope this information will be useful.

Thank you.

Body:
I do not know how to formulate this question but it is near close to my issue. I am trying to make a Point of sale system so when client clicks in each product it adds in the table. There are no issues in my code but I do not know how to set the product's price using a textbox when using .append.

This is my code:

$(".agregarListaF").click(function (e) {
  e.preventDefault();
  var padre = $(this);
  var hijos = padre.children().children("span");
  var i = 0;
  var datos = new Array();

  hijos.each(function () {
    switch (i) {
      case 0:
        datos[0] = $(this).text();
        break;

      case 1:
        padre;
        datos[1] = $(this).text();
        break;

      case 2:
        padre;
        datos[2] = $(this).text();
        break;
    }

    i++;
  });
  console.log(datos[0]);
  console.log(datos[1]);

  $(".detallefactura").append(
    "
" +
      "" +
      datos[0] +
      "	" +
      "" +
      datos[1] +
      "	" +
      "" +
      "<input type='text' class='form-control text-center' value='1'>" +
      "	" +
      "" +
      "<input type='text' class='form-control text-center' value=''>" +
      "	" +
      "" +
      parseFloat(Math.floor(datos[2]) * parseFloat(1)).toFixed(2) +
      "	"
  );
});

My issue is in the line:

 + "" + "<input type='text' class='form-control text-center' value=''>" + "	"

I want to add javascript value variable inside * input value=''* but I know It wont work but I tried it:

+ "" + "<input type='text' class='form-control text-center' value='datos[2]'>" + "	"

This is my point of sale view:

In the column precio is where I want to set the price inside that textbox.

How do I solve this?

Body:
Please try this code,To How to set Javascript's variable value inside

<!DOCTYPE html>
<html>

<head>
    <title>
        JavaScript| Set the value of an input field.
    </title>
</head>

<body style="text-align:center;" id="body">
    <input type='text' id='id1' />
    <br>
    <br>
    <button onclick="gfg_Run()">
        click to set
    </button>
    <p id="GFG_DOWN" style="color:green; font-size: 20px;font-weight: bold;"></p>

    <script>
        var el_down = document.getElementById("GFG_DOWN");
        var inputF = document.getElementById("id1");
        function gfg_Run() {
            inputF.setAttribute('value', 'defaultValue');
            el_down.innerHTML = "Value = " + "'" + inputF.value + "'";
        }
    </script>
</body>
</html>

I hope this information will be useful.

Thank you.