Cannot locate libsdl2-2.o.so file

I’m following an SDL C++ tutorial and they advised me to copy that file (libsdl2-2.o.so) into my project file to remove any errors occurring if the code was on a different computer. I have installed both libsdl2-2.0 and libsdl2-dev onto my machine, but cannot find their files in /lib/x86_64-linux-gnu (like in the tutorial). Is it maybe stored in a different location now, or what?

Note: I can run code including the SDL header with no problem, so it does exist on my computer, somewhere…

I did try

locate libsdl2-2.o.so

but with no luck

Go to Source
Author: Netsu

How can I hide a flag from `strings` command

I want to create RE CTF, that the user needs to discover which string he need to write in order to execute a function that will print the flag, but, with a simple strings command in shell, we can discover the flag in the printf function. So, how can we make this not to happen?

#include <stdio.h>

void print_flag() {
    printf("secret_string discovered. flag: {eAsy_p3asy}");
}

int main()
{
    int c;
    c = getchar();
    while (c != 'secret_string') {
        putchar(c);
        c = getchar();
    }
    print_flag();
    return 0;
}

Go to Source
Author: ArlichBachman

Doing a validation check on a AJAX post and returning the error message

I have an AJAX post that does this

  $.ajax({
                    type: "POST",
                    url: "@MyWebSite.Url/myController/myView",
                    contentType: "application/json; charset=utf-8",
                    data:
                    JSON.stringify({ myModel: myData }),
                    dataType: "json",
                    traditional: true,
                    success: function () {
                        alert('Success!');
                    },
                    error: function () {
                        alert('Error! ');
                    }

My controller does the validation check but it is not correctly returning the error message.
This is what my controller looks like

 if (totalQty < part.QtyInItem)
                    {
                        //ModelState.AddModelError("", "There is " + part.QtyInItem + " of Part " + part.PartName + " used in item " + part.ItemID + " but you only handled " + totalQty + ". Please verify you are handling all parts used in the item.");
                        //RedirectToAction("myControler", myModel);
                        return this.Json(new { success = false, message = "There is " + part.QtyInItem + " of Part " + part.PartName + " used in item " + part.ItemID + " but you only handled " + totalQty + ". Please verify you are handling all parts used in the item." });
                    }

When I tried adding an error to the model state it just returned “ERROR!” and not the error message I had associated with it. And when I try doing the this.JSON return it returns “success” to the view and not the error message.

How can I do this validation check for my AJAX post

Go to Source
Author: ryan

How is design using C different from C++?

A employer is looking for C programmers, and I’m told they say that …

Good C design isn’t the same as good C++ design

… and so they’re looking for candidates experienced with C and not only C++.

How is the design of a large C system (hundreds of thousands or millions of lines of code) very different from that of C++?

Are the skills required of a developer very different, what differences should an experienced developer expect?

I’ve read Why are most Linux programs written in C? — including Linus’ little “two minute hate” at http://harmful.cat-v.org/software/c++/linus — but that doesn’t answer my question, which might be, “How is a well-designed C system unlike well-designed C++?” Or are they similar, and is Linus’ argument all there is to it?

I read Lakos’ Large-scale C++ Software Design — is there anything at all like that for C?


I’m trying to write this such that it isn’t a duplicate of:

Please assume I already know the differences between the langages.

I used C in the early 90s (before C++ became popular on PCs), and for writing device drivers on Windows (in the kernel where the C++ run-time library wasn’t supported), and I learned C++ incrementally as a superset of C.

IMO there’s obvious mapping between C and C++, like what’s written in one can be written in the other, for example:

  • C — a “file pointer” or “file handle”, plus an API of related functions which take a handle-or-pointer as a parameter, plus an underlying data structure (possibly hidden/encapsulated) which contains state associated with each handle
  • C++ — ditto except that “data structure” and “associated functions” and encapsulated in a class, as data members and methods

C++ has additional syntactic and type-checking sugar (e.g. templates and operator overloading), and its destructors allow RAII and reference-counting smart pointers, but apart from that …

And C has no first-class/language support for polymorphism, but e.g. a device driver on Windows is an installable plug-in, which has entry points which it exports, more or less like a vtable.

Go to Source
Author: ChrisW

What goes into a computer deciding how many memory locations to assign for specific data types in C?

I have learned file memory management and some very simple CPU assembly for manual memory manipulation, but I feel like there is a gap in my knowledge when it comes to modern, complex computers, OSs, and compilers. What I am wondering is what goes into the decision process to allocate a set amount of memory for different data types. On x86 systems its seems that 8 locations of byte-addressable memory are allocated for pointers consisting of 48-bit addresses. Is the system of allocation similar to that of Linux’s buddy system for files? Why 8 bytes instead of 6? Can it only split in half (limited to powers of 2) or is there a purposeful reason it goes for 8 bytes instead of 6?

I am wondering about the whole process. When you run a program and its program memory is loaded into memory alongside the compile-time set variables, I assume that the compiler has already previously decided based on the computer system how many memory locations to ask for for each variable data type. But how does it decide this?

Any resources you could point me towards would be helpful! Thanks!

Go to Source
Author: infinity8-room

C++ array takes input more than its size

I used to know that arrays in c++ doesn’t elements more than specified only except resizable array or using dynamic memory allocation. But in the simple code below if I put a value in the 3rd or 4th index it compiles and runs without error, when I put value in 5th index it compiles fine but gives a runtime error and for the 6th index compiles and runs fine and it seem to go on like this randomly.

Is it some concepts I didnt know or I did something wrong?

#include <iostream>
using namespace std;

int main(){

    int arr[2]={2,2};

    arr[0] = 1;
    arr[1] = 2;
    arr[2] = 3;
    arr[4] = 4;
    arr[5] = 5; //gives a runtime error
    arr[6] = 6;

}

Go to Source
Author: Abdullah Al Nahian

Managing the disposal of network connections

I am writing a class — let’s call it MessageSender — that needs to perform operations over the network. It basically does these things:

  1. Take some configuration
  2. establish a connection
  3. send stuff

If we ignore the cleanup of any resources, this would look like this:

var sender = new MessageSender("127.0.0.1");
sender.Connect();
sender.SendMessage("Hello world");

The thing I am unsure about is how to manage the disposal of the established connection. I thought of three options, of which I ended up implementing the last one.

(1) Having a dedicated Disconnect() method the user must call:

var sender = new MessageSender("127.0.0.1");
sender.Connect();
sender.SendMessage("Hello world");
sender.Disconnect();

(2) The MessageSender implements IDisposable:

using (var sender = new MessageSender("127.0.0.1"))
{
    sender.Connect();
    sender.SendMessage("Hello world");
}

(3) The Connect() method returns an IDisposable:

var sender = new MessageSender("127.0.0.1");
using (var connection = sender.Connect())
{
    sender.SendMessage("Hello world");
}

I have never seen the third option anywhere, but it does seem to have some advantages:

  • Construction, and hence configuration of the message sender is separated from establishing a connection. E.g. the object itself can be some other classes’ member, constructed and passed down as a dependency to others, while the execution and therefore the actual connection can be deferred to some Run() method.
  • The need for connection tear-down is a direct result from the connection set-up and cannot be (accidentally) separated.
  • If implemented that way, Connect() could be called multiple times.
  • Using IDisposable in general over a dedicated tear-down method gives you better language support, e.g. the using-clauses I used in both (2) and (3).

Potential pitfalls I see for all of the above solutions:

  • Failing to run the tear-down logik. This includes:
    • for (1): Forgetting to call Disconnect()
    • for (2) and (3): Forgetting to propery handle disposables
    • for (3): Ignoring the return value of Connect() entirely
  • MessageSender needs to keep track of its connection state to disallow multiple calls to Connect().
  • Calling SendMessage can fail at runtime depending on the current connection state.

Are there advantages to other approaches or disadvantages to my approach I am not aware of?

Here’s a somewhat simplified version of my actual code:

public sealed class MessageSender
{
    private readonly Some3rdPartyNetworkClient _client;
    private bool _connected = false;

    public MessageSender(string connectionString)
    {
        _client = new Some3rdPartyNetworkClient(connectionString);
    }

    public void SendMessage(string message)
    {
        if (!_connected) throw new InvalidOperationException("not connected.");
        _client.SendMessage(message);
    }

    private sealed class DelegateDisposer : IDisposable
    {
        private readonly Action _dispose;
        public DelegateDisposer(Action dispose) => _dispose = dispose;
        public void Dispose() => _dispose();
    }

    public IDisposable Connect()
    {
        if (_connected) throw new InvalidOperationException("Can only ever connect once.");
        _connected = true;
        
        _client.Connect();
        var tokenSource = new CancellationTokenSource();
        Task checkConnectivityWorker = CheckConnectivityWorker(tokenSource.Token);
        return new DelegateDisposer(() =>
        {
            tokenSource.Cancel();
            if (!checkConnectivityWorker.IsCanceled) checkConnectivityWorker.Wait();
            _client.Disconnect();
        });
    }

    private async Task CheckConnectivityWorker(CancellationToken cancellationToken)
    {
        // some stuff that needs to be done continuously while the connection is active
    }
}

Go to Source
Author: Felk

Load single module based on configuration using dependency injection

I’m working on an application that will run on multiple systems and may use different modules to communicate with external systems, but on each system, only one module will be used at a time. As it should be possible to change the used module on a specific system, the same application with all modules should be deployed to all systems. For simplicity, let’s assume that there are two modules called Foo and Bar.

Both modules have their own module descriptor that registers the module components to the dependency injection container:

public class FooModule : IModule
{
    public void Configure(IServiceCollection services)
    {
        services.AddTransient<IService, FooService>();
        // Register dependencies of FooService
    }
}

I know that Autofac supports modules out of the box (even with support for configuration) and there are several libraries that add such a feature to Microsoft.Extensions.DependencyInjection, but I want to ask this question with a general look at the concept of dependency injection.

If the services of all modules should be used at the same time, I would be done. Given they implement the same service, I could inject them using IEnumerable<IService>. But in my use case, there is a component that requires a single IService and I want to select the implementation based on a configuration (e.g. from a file).

Now there are several approaches where to apply that configuration and I’m not sure which one should be preferred:

1st approach – load single assembly

I could read the configuration and then load only the external assembly that contains the IModule that should be used. This would require the introduction of some “magic” link between the configuration values and the names of the module assemblies, as the core application should not know the extension modules beforehand.

2nd approach – call single module

All the assemblies are loaded, but using a link between the configuration values and the names of the module classes (or namespaces), only the one module that should be used will be called to setup the passed IServiceCollection.

3rd approach – let the module decide

The modules decide on their own if they are configured and therefor should provide their service implementation. Instead of evaluating the configuration in the core application, the configuration gets passed to the modules:

public class FooModule : IModule
{
    public void Configure(IServiceCollection services, IConfiguration configuration)
    {
        if (configuration.GetSection("foo").Exists())
        {
            services.AddTransient<IService, FooService>();
        }
    }
}

4th approach – use some DI container feature

I know that Autofac or other DI containers support named / keyed service registrations that would basically solve this problem and therefor answer this question for me. However, I guess there is a reason why other DI containers like Microsoft.Extensions.DependencyInjection do not provide this feature.


What approach would you prefer? Is there an approach or some variation that I missed? Is there anything else I should keep in mind when designing a system in that way?

Go to Source
Author: Lukas K├Ârfer

Dependency Injection with MVVM pattern in Simple WPF Application

I’ve been trying to follow the advice in this answer

The problem is I get the error: No matching constructor found on type ‘FreecycleFrontEnd.MainWindow when the application starts up

Code below:

public partial class App : Application
    {
        private static readonly Logger log = LogManager.GetCurrentClassLogger();
        private IKernel container;


    protected override void OnStartup(StartupEventArgs e)
    {
        log.Debug("Application Starting Up");

        IocKernel.Initialize(new IocConfiguration());
        base.OnStartup(e);
       

    }

}
public partial class MainWindow : Window
{
    private IWebController _controller;
    public MainWindow(IWebController controller)
    {
        this._controller = controller;
        InitializeComponent();
        Loaded += onLoaded;
    }

 public class IocConfiguration : NinjectModule
{
    public override void Load()
    {

        Bind<IWebController>().To<WebController>().InSingletonScope();
        Bind<UserControlViewModel>().ToSelf().InTransientScope(); // Create new instance every time
    }
}
public static class IocKernel
{
    private static StandardKernel _kernel;

    public static T Get<T>()
    {
        return _kernel.Get<T>();
    }

    public static void Initialize(params INinjectModule[] modules)
    {
        if (_kernel == null)
        {
            _kernel = new StandardKernel(modules);
        }
    }
}

The code compiles, and executes up to base.OnStartup(e);
The Ninject configuration executes.

What have I missed?

Go to Source
Author: tonydev314

How to check data has been received correctly with CRC – much confusion here

I am trying to process some serial data (sent over UART). Its coming from a radio controlled receiver, is 27 bytes long. The last 2 bytes of this are a 16bit CRC check according to the spec.

The checksum is derived from the preceding 25 bytes

Along with the protocol there is this information on the checksum calculation:

 u16 CRC16(u16 crc, u8 value)
 {
     u8 i;
     crc = crc ^ (s16)value<<8;
     for(i = 0; i < 8; i++)
     {
         if(crc & 0x8000)
             crc = crc << 1^0x1021;
         else
             crc = crc << 1;
     }
     return crc;
 }

I have had to do a little ‘translation’ of this, as I am using an STM32 microcontroller, and the variables need to be declared a little different (uint16_t instead of u16 for example).

That said I think I have got completely the wrong end of the stick anyway…..

The code above appears to ‘only’ process a single byte of data, passed to the function in variable ‘value’

It appears to also want a 16bit integer named ‘crc’ passed to it, which is where the confusion started……

I have the 27 byte packet of data. I have converted the last 2 bytes into the 16 bit checksum and have made sure that I have the endianness of this correct (the message is big endian, the stm32 is little endian, so you cant do a memcpy, you need to do a bit of bit shifting).

But how do I now get an answer as to whether the preceding 25 bytes of data have been received correctly.

Any help gratefully received. I’ve googled and read and just got myself more confused….

Many thanks

James

Go to Source
Author: James Hounslow

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