How do I get the current GPS location programmatically in Asp.Net MVC C#

I am working on a Asp.Net MVC 5 Application for getting gy06n gps live data from hosted server to store in mysql

Let’s say I have GPS Device and I want to use the GPS location in my application, what api / code should i use?

For Example if i have travel agency and i have 2 cars and both cars has gt06n GPS device the condition is “if My GPS enable car stop more then 2.5 min on road in that case i need a single ping from my Gps device.”

Go to Source
Author: Chandan

c++: How to exchange input and output for this code?

Here is the code below. The code is about RSA.

#include "rsa.h"

int main()
{
  RSA rsa(13, 77);
  rsa.crypt("plainFile", "cipherFile");
  return 0;
}

rsa.cpp

#include "rsa.h"
#include <fstream>
#include <cmath>

RSA :: RSA(int k, int m)
: key(k), modulus(m)
{
}
RSA :: ~RSA()
{
}
void RSA :: crypt(const char* inFile, const char* outFile)
{
  ifstream  istrm(inFile, ios :: in);   
  ofstream  ostrm(outFile, ios :: out);
  int base, result;
  while (istrm >> base)
  {
    result = modulo(base, key, modulus);
    ostrm << result;
    ostrm << ' ';
  }
  istrm.close();
  ostrm.close();
}
int RSA:: modulo(int base, int power, int modulus)
{
  int result = 1;
  for (int i = 0; i < power; i++)
  {
    result = (result * base) % modulus;
  }
  return result;
}

rsa.h

#ifndef RSA_H
#define RSA_H
#include <iostream>
using namespace std;

class RSA
{
  private:
    int key;
    int modulus;
    int modulo(int base, int power, int modulus);
  public: 
    RSA(int key, int modulus);
    ~RSA();
    void crypt(const char* inFile, const char* outFile);
};
#endif

The output should be

Contents of Plaintext File:
14 27 12 45 9 64 22 8
Contents of Ciphertext File:
49 48 12 45 58 36 22 50

Now I would like to make this output become input, and get this output

#include “rsa.h”
int main ()
{
RSA rsa (13, 77); // 13 is the value of e and 77 is value of n
rsa.crypt (“plainFile”, “cipherFile”); return 0;
}

I try to exchange input and output but don’t know where to start, can I just change a little bit to do that? or I need to rewrite the code? anyone can help? How should I do it? Thanks.

Go to Source
Author: Maggie L

finds the number of fans of each team and prints them in CSharp

I have this question about Arrays, the concept is really simple but the problem is I don’t know almost anything about Csharp, I am trying to help a friend who cant understand English very will, I told him how to solve the problem but without coding, can you help me write the code? also the question wasn’t in English, I tried to write it as clear as possible:
The fan.txt file contains the name and team information (GS, FB, or BJK).
by reading this information; The program that prints the names of the GS holders in the GS.txt file, the names of the FB holders in the FB.txt file, the names of the BJK holders in the BJK.txt file, and also finds the number of fans of each team and prints them on the form.
Sample file contents are below.

Go to Source
Author: flowery

Why I don’t have any changes in my ObservableCollection when I have made some in my DataGrid?

I have a class Employee :Person

Class Employee

 [Serializable]
    public enum Education
    {
        secondary, specialized_secondary, high
    }

    [Serializable]
    public enum MarriageStatus
    {
        single, married, divorced
    }

    [Serializable]
    public class Employee : Person, INotifyPropertyChanged
    {
        private Education _teaching;
        private MarriageStatus _status;
        private string _photoPath;

        public Education Teaching
        {
            get { return _teaching; }
            set
            {
                _teaching = value;
                OnPropertyChanged("Teaching");
            }
        }

        public MarriageStatus Status
        {
            get { return _status; }
            set
            {
                _status = value;
                OnPropertyChanged("Status");
            }
        }

        public string PhotoPath
        {
            get { return _photoPath; }
            set
            {
                _photoPath = value;
                OnPropertyChanged("Status");
            }
        }

        private ObservableCollection<Employee> _employeesList = null;

        public  new event PropertyChangedEventHandler PropertyChanged;

        public new void OnPropertyChanged([CallerMemberName]string prop = "")
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }

        public ObservableCollection<Employee> EmployeesList
        {
            get
            {
                if (_employeesList != null)
                {
                    return _employeesList;
                }
               
                    _employeesList = new ObservableCollection<Employee>();

                    _employeesList.Add(new Employee()
                    {
                        Id = 1,

                        FirstName = "Igor",
                        LastName = "Krivonos",
                        DateBirthday = new DateTime(1999, 8, 15),
                        INN = "111111111",
                        Teaching = Education.high,
                        Status = MarriageStatus.married,
                        PhotoPath = "Photo/IgorKrivonos.jpg"

                    });

                return _employeesList;
            }
        }

    }

I have realized INotifyPropety event but I am not sure about this. I am new in this field and trying everything that might help. All my Employee informaiton is shown in DataGrid When I change any cell there it will not show in debuger any changes. I want to serialize it to save changes. Why my changing is not working? Sorry for my English.

Here is my xaml code:

Window x:Class="Employee_DataGrid.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Employee_DataGrid"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:model="clr-namespace:Employee_DataGrid.Model"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <model:Employee x:Key="employees"></model:Employee>
        <ObjectDataProvider MethodName="GetValues"
                    ObjectType="{x:Type sys:Enum}"
                    x:Key="status">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="model:MarriageStatus" />
               
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
        <ObjectDataProvider MethodName="GetValues"
                    ObjectType="{x:Type sys:Enum}"
                    x:Key="education">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="model:Education" />
               
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
       
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            
        </Grid.ColumnDefinitions>
        <!--Button for serialization-->
        <Button    Grid.Column="1" Click="Button_Click" >
            <TextBlock TextAlignment="Center" FontSize="35" FontFamily="TimesNewRoman" FontWeight="Bold" Width="30" TextWrapping="Wrap">Save  Data</TextBlock>
        </Button>
        <DataGrid AutoGenerateColumns="False" CanUserAddRows="False"
            ItemsSource="{Binding Source={StaticResource employees}, Path=EmployeesList}">
            <!--DataGrid Columns-->
            <DataGrid.Columns>
                <!--DataGridTextColumn for Full names and Inn-->
                <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"></DataGridTextColumn>
                <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"></DataGridTextColumn>
                <DataGridTextColumn Header="INN" Binding="{Binding INN}"></DataGridTextColumn>
                <!--DataGridComboBoxColumn for Marriage Status-->
                <DataGridComboBoxColumn Header="Status" 
                        ItemsSource="{Binding Source={StaticResource status}}" 
                        SelectedValueBinding="{Binding Status}" >

                </DataGridComboBoxColumn>
                <!--DataGridTemplateColumn for Birthday-->
                <DataGridTemplateColumn Header="Date Birthday">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <DatePicker  SelectedDate="{Binding DateBirthday, StringFormat='MM.dd.yyyy'}"></DatePicker>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <!--DataGridComboBoxColumn for Education-->
                <DataGridComboBoxColumn Header="Education"
                                        ItemsSource="{Binding Source={StaticResource education}}"
                                        SelectedValueBinding="{Binding Teaching}" >
                    
                </DataGridComboBoxColumn>
<!--DataGridTemplateColumn for Photos-->
                <DataGridTemplateColumn Header="Employees Photos">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Image DockPanel.Dock="Right"
                               HorizontalAlignment="Right"
                               Width="70"
                               Source="{Binding Path=PhotoPath}"></Image>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>


            </DataGrid.Columns>
        </DataGrid>

    </Grid>
</Window>

I inherit some propeties from Person Class Here is my Person Class:

[Serializable]
    public class Person: INotifyPropertyChanged
    {
        private int _id;
        private string _firstName;
        private string _lastName;
        private System.DateTime _dateBirthday;
        private string _inn;

        public int Id
        {
            get { return _id; }
            set
            {
                _id = value;
                OnPropertyChanged("Id");
            }
        }

         public string FirstName
        {
            get { return _firstName; }
            set
            {
                _firstName = value;
                OnPropertyChanged("FirstName");
            }
        }

         public string LastName
        {
            get { return _lastName; }
            set
            {
                _lastName = value;
                OnPropertyChanged("LastName");
            }
        }

         public System.DateTime DateBirthday
        {
            get { return _dateBirthday; }
            set
            {
                _dateBirthday = value;
                OnPropertyChanged("DateBirthday");
            }
        }

        public string INN
        {
            get { return _inn; }
            set
            {
                _inn = value;
                OnPropertyChanged("INN");
            }
        }


       
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName]string prop = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
        }

Here I have realized INotifyPropety as well.

Main Window class

[Serializable]
    public partial class MainWindow : Window
    {
      public  Employee Employee { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            Employee = new Employee();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Helpers.Serializing(Employee.EmployeesList, "employees.bin");
        }
    }

Go to Source
Author: Alex

How to manage project dependency per Project Type

I am working on a small nuget package (MakeNot). In short, I added some Extention Methods for String,Bool and also ModelStateDictionary.
In order to have access to ModelStateDictionary I should have installed below package which has its own dependency.

Microsoft.AspNetCore.Mvc.Abstractions

and I set TargetFramework like below in order to let applications based on .Net Framework to use it:

 <TargetFrameworks>net461;netstandard2.0</TargetFrameworks>

My question is, when I want to use this package in Windows form application it downloads Microsoft.AspNetCore.Mvc.Abstractions and its dependency which is not required for this type of projects.
enter image description here

Is there a way to handle this ? or Have I done it right ?

Go to Source
Author: osman Rahimi

Catch signal when a command fails

I’m trying to build a shell that gives you suggestions if you have a typing error, but I’m having trouble to catch the error.

The user will type something and after parsing it, I will use the execvp() function. The problem I’m having is that if the command is wrong I need to catch that error. I was thinking to use a signal handler, but first I need to know what signal does the bash send when a process uses a command incorrectly.

Go to Source
Author: alvarogv

how to prevent the implicit conversion of double value to integer

I am taking user input as integer and selecting the function to run depending on it. However, When I enter 12.3 as car_choice, it takes the 1 as input, runs the program for the first case. How can I prevent this? I am using C++.

int car_choice;
std::cout << "Please enter the vehicle types for calculationsn";
do
{

    std::cout << "Please enter your choice in number:n";
    std::cout << "1) VW Carn";
    std::cout << "2) Audi Carn";
    std::cout << "3) Toyota Carn";
    std::cout << "4) Do not want to enter any number and to stopn";
    std::cin >> car_choice;
} while (car_choice != 1 && car_choice != 2 &&
    car_choice != 3 && car_choice != 4);

Go to Source
Author: Surendra

Can syntactic `await` always be elided?

(This question isn’t a duplicate of Why do we need the async keyword? – it’s more of the opposite: I’m not questioning the async keyword – I’m asking if compilers could elide the use of await completely behind the scenes, making async code syntactically identical to synchronous code)

The await keyword in many languages provides a succinct way to describe a continuation or for constructing coroutines – but I’ve wondered if it was necessary at all, as in situations where I’ve used it, the compiler should be smart enough to know when a task/promise/future should be awaited or not: by deferring any await until the Task is consumed as though it were awaited.

As an example, consider this async C# code that runs two Tasks concurrently:

    Task<Foo> fooTask = GetFooAsync();
    Task<Bar> barTask = GetBarAsync();

    DoSomethingElseSynchronously();

    Foo foo = await fooTask;
    Bar bar = await barTask;

    Foo foo2 = foo.Clone();
    DoSomething( foo2, foo, bar );

I was thinking that the compiler (or rather, some static-analysis code rewriter that runs before the real C#-to-IL compiler) could allow it to be written like so:

    Foo foo = GetFooAsync();
    Bar bar = GetFooAsync();

    DoSomethingElseSynchronously();

    Foo foo2 = foo.Clone();
    DoSomething( foo2, foo, bar );

The deferred-await would result in the above code being the same as though it were written like this:

    Task<Foo> fooTask = GetFooAsync();
    Task<Bar> barTask = GetBarAsync();

    DoSomethingElseSynchronously();

    Foo foo2 = (await fooTask).Clone();
    DoSomething( foo2, (await fooTask), await barTask );

Of course this only works if the re-inserted await is both idempotent (which is ostensibly is, at least with the stock Task<T> in .NET) and side-effect free (so reordering the await statements should not affect the correctness of the program).

I imagine most async C# code tends to immediately await a Task because most async APIs do not support concurrent operations on the same resources, so you must await one operation before starting another on the same object (e.g. DbContext doesn’t support multiple concurrent queries, and FileStream requires each async read or write operation to be completed before starting another – though I might be wrong if FileSteam fully supports Windows’ Overlapped IO functionality) – there’s no built-in way in .NET for an asynchronous API to declare support for concurrent operations but a simple addition to the TaskCompletionSoure and Task API could enable this.

Another example of concurrent async operations is firing off a batch of HTTP requests using a single HttpClient instance – for example a web-crawler might work like this:

List<Uri> uris = ...

HttpClient httpClient = ...

List<Task<List<Uri>>> tasks = uris
    .Select( u => httpClient.GetAsync() /* Returns HttpResponseMessage */ )
    .Select( response => ReadPageUrisAsync( response ) /* Returns Task<List<Uri>> */ )
    .ToList();

List<Uri> foundUris = ( await Task.WhenAll( tasks ) )
    .SelectMany( uris => uris )
    .Distinct()
    .ToList();

If the await were syntactically elided, the compiler should be smart enough to infer that Task.WhenAll( tasks ) call-site expected an awaited return value because the following Linq expression only works if the IEnumerable<T> source parameter for .SelectMany is a List<List<Uri>> and not a List<TaskList<List<Uri>>> (I do appreciate this kind of type-inference is a hard problem – I’m using it as a contrived example).

So – assuming that a program’s asynchronous operations can be safely awaited out-of-order, is there a reason or situation where await couldn’t be syntactically elided?

Go to Source
Author: Dai

How to test C++ code when using C functions

I wrote a c++ class, this class uses the c function library written by a third party.

extern "C" {
#include "nats/nats.h"
}

class NatsConnection {
  public:
  void Connect() {
    natsConnection_Connect(&natsConnection_, natsOptions_);
    natsConnection_SubscribeSync(&natsSubscription_, natsConnection_,
                                 configuration_.subject.c_str());
    // some other c++ code.
  }
}

The above class uses functions imported from c: natsConnection_Connect, natsConnection_SubscribeSync.

Now I need to write a unit test to cover some other c++ code, I am using gtest, I know how to mock a C++ class, but once I use the C code I don’t know how to start.

how do i write the test? Is there has a best practice?

Go to Source
Author: MengHan Yu

boat and boat register program in C++

Create the following two classes.
1. Boat – this class contains:
i. a private instance variable name of type String which is initialised to “unknown”
ii. a private instance variable, boatClass, of type String initialised to “unknown”
iii. a private instance variable, regNum, of type int initialised to -1
iv. a method called toString that has no formal parameters and returns the boat’s name, class
and registration number, as a String, in the following format:
Boat name, Class = boatClass, Registration # = KA regNum
where the words in italics should be replaced with the values of the corresponding instance
variables.
COMP2741/COMP8741 Practical 2, Checkpoints 9-16
Flinders University Page 2 of 7 2020
2. BoatMaker – refactor the class that contains the main method created when the project was
created (possibly called Practical2) by changing its name to BoatMaker (right-click on its name
and select “Refactor->Rename” or Shift-F6). Modify the main method so that it:
i. Prints the message “Starting boat application”
ii. Defines a variable called myBoat of type Boat, initialised to a new Boat object.
iii. Prints the value of myBoat (causing the toString method to be called on the object
referred to by myBoat).
Run the project. The following output should be prod

Go to Source
Author: Rajwinder Chahal

How to timeout call if takes more than x milliseconds?

I am working with C# language and was working on getting data out of cassandra so I was working with below code which gets data from Cassandra and it works fine.

Only problem I have is in my ProcessCassQuery method – I am passing CancellationToken.None to my requestExecuter Function which might not be the right thing to do.

And I need to timeout the query if it takes more than 800 milliseconds so how can I use CancellationToken here properly to timeout the query? Cassandra driver doesn’t handle CancellationToken yet so I need to do this outside through some other ways. This code will be called at a very high throughput so it needs to be efficient while timing out the call.

/**
 *
 * Below method does multiple async calls on each table for their corresponding id's by limiting it down using Semaphore.
 *
 */
private async Task<List<T>> ProcessCassQueries<T>(IList<int> ids, Func<CancellationToken, int, Task<T>> mapperFunc, string msg) where T : class
{
    var tasks = ids.Select(async id => 
    {
        await semaphore.WaitAsync();
        try
        {
            return await ProcessCassQuery(ct => mapperFunc(ct, id), msg);
        }
        finally
        {
            semaphore.Release();
        }
    });

  return (await Task.WhenAll(tasks)).Where(e => e != null).ToList();
}

// this might not be good idea to do it. how can I improve below method?
private Task<T> ProcessCassQuery<T>(Func<CancellationToken, Task<T>> requestExecuter, string msg) where T : class
{
    return requestExecuter(CancellationToken.None);
}

Go to Source
Author: dragons

Which key-value database should I use and why?

Which key-value database should I use and why?

I have an application that scrapes webpages. Once a webpage is scraped, it has a unique identifier which is a string and it has the associated content which is also a string. I need to persist the webpage content, so that the next time I scrape the data for the same webpage I need to know whether the webpage has changed or not.

So either I might be storing the page identifier mapped with its checksum or simply its content. Anyhow, the basic need of storage is simple – a string to string map.

I think it is a use case for a key-value database. Since, my needs are very simple I don’t need a database full of fancy features. What could be a good open source key-value database that suits my simple needs?

Also, is it even necessary to use a database? I can fall back to a file storing the key-value. Will I lose performance if I use a database over a file?

Go to Source
Author: Navjot Singh

System.InvalidCastException: Can’t convert infinite timestamp values to DateTime

System.InvalidCastException: Can’t convert infinite timestamp values to DateTime

I am having a weird issue which seem to be specific to my postgres database on my test server, and not on my local database.

Everytime I insert somerthing to my database I get an error

System.InvalidCastException: Can't convert infinite timestamp values to DateTime

And I cannot seem to understand why I am getting this error on a remote server and not able to replicate it locally?

from a google search it seems to be fixable by adding Convert Infinity DateTime to true

but this does not seem to work?

but then again it seem to be specific to the environment it is running on? can this somehow affect? maybe something like a version where it does not work on or something else?

I cannot seem to understand why it work on one database but not on another?

I should be using the latest postgresql-12 but somehow i can check this?

Exception":"System.InvalidCastException: Can't convert infinite timestamp values to DateTimen   at Npgsql.NpgsqlDataReader.GetValue(Int32 ordinal)n   

Go to Source
Author: kafka