text:
Q: using ORDER BY in a prepared statement I'm creating a web app that displays a table using data from a database using Java MVC.
I have a prepared statement that I'm using to generate the table that works fine until i try and use ORDER BY.
I'm quite confused as when I run this query in the mySQL workbench it works fine:
SELECT * FROM appointments ORDER BY date

However when i put it into my prepared statement in the browser it returns an unordered list.
public void doRead(){
    String query = "SELECT * FROM appointments ORDER BY date";

    try {
        PreparedStatement ps = this.connection.prepareStatement(query);
        this.results = ps.executeQuery();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Would appreciate any help.
as requested im printing the table with this method here:
try {
        while(this.results.next()){
            Appointment appointment = new Appointment();
            appointment.setAppointmentID(this.results.getInt("appointment_id"));
            appointment.setDescription(this.results.getString("description"));
            appointment.setDate(this.results.getString("date"));

            table += "
";
            table += "";
            table += appointment.getDescription();
            table += "	";
            table += "";
            table += appointment.getDate();
            table += "	";
            table += "
";
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    table += "
";
    return table;
}

the output in browser:
Dentist 2015-09-17
Dentist 2015-09-17
Dentist 2015-09-17
Dentist 2015-10-09
Dentist 2015-09-03
Dentist 2015-09-03
Dentist 2015-09-03

A: DATE is a reserved word. Use backticks:
String query = "SELECT * FROM appointments ORDER BY `date`";

Also better make results a local variable and close it.
Tip:
Use a StringBuilder instead of String for table. Much faster, less memory hungry. Better even would be to pass a PrintWriter for outputting.

A: Try adding a sort order "ASC":
SELECT * FROM appointments ORDER BY date ASC


text:
Q: Getting decorated methods of a given class from within that class Given a class and a set of its methods - how can you determine from within that class which methods have been decorated with a certain decorator?
My goal is to basically get the actual values of the methods that are decorated, so something like:
class A():
    def get_values(self):
      ...
      # returned {'a-special-name': 1, 'b': 2}

    @my_dec('a-special-name')  # Ideally be able to also put optional name
    def a(self):
      return 1

    @my_dec
    def b(self):
      return 2

Any idea on how to accomplish this?
Edit: this should also work on parent classes, that is, if A is a subclass of:
class B():
    @my_dec
    def c(self):
        return 3

then get_values() of A instance should return {'a-special-name': 1, 'b': 2, 'c': 3} (order is irrelevant of course)
Edit: class based decorator that works but not with inheritance. Any idea how to make it work with inheritance but without having to decorate the class itself?
class my_dec(object):
    def __init__(self, func, name=None):
        self.func = func
        self.name = name or func.__name__
        self.func._some_flag = True

    def __get__(self, instance, cls=None):
        if instance is None:
            return self
        return self.func(instance)

A: If you can define the decorator yourself, then simply have it "mark" the method object in some way:
def my_dec(method):
    method._this_be_decorated = True
    return method

The class can then look for those marked methods; something like:
from inspect import isfunction

class A:
    def get_values(self):
        return filter(lambda i: isfunction(i) and hasattr(i, '_this_be_decorated'),
                      vars(type(self)).values())

This will return an iterable of function objects which you can process further as needed.

A: def my_dec(name):
    if callable(name):
        # name is callable – take its name
        func = name # no make the code more readable
        func.special_name = func.__name__
        return func
    else:
        # name is the name to give – add an inner layer of functions
        def inner(function_object):
            function_object.special_name = name
            return function_object
        return inner

class A():
    def get_values(self):
        # return a dict of special name to call result mapping for every class member that has a special_name.
        return {func.special_name: func(self) for func in self.__class__.__dict__.values() if hasattr(func, 'special_name')}
      # returned {'a-special-name': 1, 'b': 2}
    @my_dec('a-special-name')  # Ideally be able to also put optional name
    def a(self):
      return 1
    @my_dec
    def b(self):
      return 2
    def no_dec(self):
      return 42

should do what you want.

A: As deceze mentions, decorators can do whatever they want so there's no reliable generic answer. If you "own" the decorator you can add special properties to it's return value ie (Q&D py2.7 example):
def mydec(name=''):
    # py27 hack - for py3 you want nonlocal instead
    n = [name]

    def innerdec(func):
        # py27 hack - for py3 you want nonlocal instead
        name = n[0] or func.__name__
        def wrapper(*args, **kw):
            print("in mydec.wrapper for {}".format(name))
            return func(*args, **kw)
        wrapper.ismydec = True # so we know this is decorated by mydec
        wrapper.func = func # so we can get the original func
        wrapper.name = name
        return wrapper
    return innerdec

def collect_dec(cls):
      decorated = {}
      for attname in dir(cls):
          obj = getattr(cls, attname)
          if getattr(obj, "ismydec", False):
              decorated[obj.name] = obj.func
      cls._decorated_funcs = decorated
      return cls

@collect_dec
class A():
    def get_values(self):
        return {
            name:func(self) for name, func in self._decorated_funcs.items()
            }

    @mydec('a-special-name')  # Ideally be able to also put optional name
    def a(self):
      return 1

    @mydec() # no name
    def b(self):
      return 2

a = A()
print(a.get_values())

Which outputs:
{'a-special-name': 1, 'b': 2}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can't I memcpy an int to a char[] without getting the address of the int? This might be a duplicate, but I haven't found any other question dealing with my exact situation (yet).
Here's what I'm trying to do:
int n = 12;
char s[sizeof(n)];
memcpy(s, (char *)n, sizeof(n));
printf("%d", s);

Basically, I want to copy n into s without having to get the address of n. When I run this, it gives me a segmentation fault. This, however, works:
printf("%d", (char *)n);

So I know that the problem is in the memcpy call. Why can't I memcpy an int into a char[] like this?

A: You get a segmentation fault because what you're trying to do is not what your code states.
int n = 12;
char s[sizeof(n)];
memcpy(s, (char *)n, sizeof(n));

You wanted to say:

"copy the sizeof(int) bytes representing the value of n into s".

But memcpy() is about copying memory objects, not values. An object resides at a given address, and contains a given value. Taking n gives the value, taking &n gives the address.
And the construct (char *)n tells the compiler to interpret the value of n as the address of a char, so what you are saying is:

"copy the sizeof(int) bytes at the address contained in n into s."

Since n = 12, you are reading from address 0x00000012... which is most likely not a legal address to read from (hence the segfault).
By taking the address of n before casting that (instead of the value) into char *, your statement matches your intent:
int n = 12;
char s[sizeof(n)];
memcpy(s, (char *)&n, sizeof(n));

"copy the sizeof(int) bytes at the address of n into s".

A: You don't need to take the address of s since the name of an array in this context evaluates to the address of the first element. Since the integer n is not an array, that doesn't apply, which is why you must take the address.
Of course you can use an int array too, to get around this, but it's extremely silly and a very bad idea in general:
int n[1];
char s[sizeof n];
memcpy(s, n, sizeof n);

This works because n now evaluates to &n[0], i.e. the address of the first (and only!) element in the array.
Note that sizeof is not a function, it does not need parentheses for this usage.


text:
Q: Transfer user to the link from the email after logging in I have this code that sends email every time a new post is created. It sends an email to all users from the database with a certain link. The thing is, users can't (shouldn't) be allowed to view the post if they are not signed in. How do I make this in such a way that after I click on the link on the email, it redirects me to the log in page and then redirects me back to the original link from the email?
What's the approach to this?

A: *

*if(Yii::app()->user->isGUest)
You can use this condition to check if the user is authenticated or not.

*$this->redirect('path/where you want to redirect');
You can use this statement to redirect the user to the desired URL from any action of any controller or from anywhere.

*Yii::app()->user->returnUrl
This statement stores your destiny Url. In other words, suppose You are going to project/blog/create, But in order to access this action you need to be authenticated. SO if you are not authenticated , it will redirect you to the login page. And if you are successfully logged in, you can go to your desired Url which is stored in Yii::app()->user->returnUrl
Eg:-
public function actionCreateBlog()
            {
            if(!Yii::app()->user->isGUest)
            {
            // create the blog here
            }
            else
            {
            Yii::app()->user->loginRequired();
            }

Then in your login action you can do this
public function actionLogin()
    {
        $model=new LoginForm;

        // collect user input data
        if(isset($_POST['LoginForm']))
        {
            $model->attributes=$_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if($model->validate() && $model->login())
                $this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form
        $this->render('login',array('model'=>$model));
    }

}

A: This answer addresses the general approach, basically to detect that you're not logged in but saving the current location in a variable that is passed into the login page so that it can redirect you back to the link:
Redirecting to previous page after login? PHP
To implement it using yii, this answer adds more context
Redirect page after login in Yii framework

A: You can do this in simple way.
In your controller, you have accessRules function to set the user role for all action functions of that controller. Here you can restrict the user access. So After login, yii will do redirection.
For ex, you have function called
 public function actionView($id)

For this view function, you need to set logged in user privilage, you have to set rules as below.
In accessRules set,
'actions' => array('view'), 'users' => array('@'), // @ for logged in user


text:
Q: closest numeric value in database using Prisma Client Is there any way I could re-write this SQL query using Prisma Client.
SELECT TOP 1 * FROM [myTable]
WHERE Name = 'Test' and Size = 2 and PType = 'p'
ORDER BY ABS( Area - @input )

A: You can use queryRaw and directly pass the raw SQL to execute it.
It would look like this:
const result = await prisma.$queryRaw`SELECT TOP 1 * FROM [myTable]
WHERE Name = 'Test' and Size = 2 and PType = 'p'
ORDER BY ABS( Area - @input )`


text:
Q: math.SE has been stuck in read-only mode for 7 hours Since this answer doesn't seem to be drawing any attention from anyone who can do something about it, I'm posting it as a question. The Mathematics Stack Exchange has been in read-only mode for 7 hours now; it seems that the other Stack Exchange sites are back to normal, so perhaps Mathematics was somehow forgotten in the process of switching back?

A: { cross-posted from Why is MSE still down (read-only)? }
What happened?
During our planned maintenance window on March 17th/18th, a sequence of events in our Colorado data center left Mathematics Stack Exchange in read-only mode for several hours after the maintenance was finished.
TL;DR
The site is back up. The maintenance window was officially closed on March 18th at 01:28 UTC, at which point all other sites were fully operational, but Mathematics remained in read-only mode until it was manually corrected at roughly 11:46 UTC.
What caused the issue?
A number of factors contributed to the issue itself and our failure to recognize it. The long version:

*

*As part of our manual failover process, we move all sites to read-only mode due to a performance issue we've been experiencing for months but have yet to solve.

*This involves shifting site traffic to our web servers in Colorado, where they can read data from the secondaries there without any impact from operations happening in New York.

*Fundamentally, the application should not try to write to a read-only secondary; if successive attempts fail, the source site is automatically switched to read-only mode for safety, because it's a clear sign that something is awry.

*In this case, the Mathematics site did try to write to a read-only secondary following a very specific (non-nefarious) sequence of events from an end user.

*Because this happened while all of the other sites were in read-only mode, any notifications about this site specifically were silenced for maintenance, as we were intentionally setting the entire network read-only and also doing maintenance that would cause significant alert noise anyway.

What contributed to the duration?
At the end of our maintenance window, we spot check a handful of things, including a few specific web sites (but certainly not all of them). We don't manually open every single web site in a browser to ensure the banner is gone, or test that we can successfully post a comment or vote on a post.
In this case, all of the places we checked at 01:30 UTC looked good, including our open-source monitoring tool, OpServer - which provides a fantastic pulse on the state of our databases. If a specific site's primary database couldn't be written to, we certainly would have seen it there. But the site itself does not surface its status there - that is shown elsewhere, on an internal dashboard. So we went to bed.
How can we improve?
We can improve internal notifications and time to resolution for this scenario:

*

*We can manually detect when a site is automatically shifted to read-only in response to a scenario like the above {done}

*We can automate and alert on that monitor

*We can further improve the way the application attempts to write to the database during maintenance

*We can add to our maintenance window runbooks:

*

*Checking the internal dashboard in addition to OpServer and other checks {done}

*Increasing the number of sites we spot check

*Waiting an hour and checking meta (though there are a lot of individual meta sites to check, too)


text:
Q: How to get lat n lng center point of map in android? I am building an android application where user is getting latLng by long touching in Google map.
Here is the code:
    public class MainActivitytut extends FragmentActivity{

GoogleMap googleMap;
MarkerOptions markerOptions;
LatLng latLng;
private TextView myAddress;
String lat;
TextView txtmapinfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maintut);

    //onBackPressed();
    SupportMapFragment supportMapFragment = (SupportMapFragment)
            getSupportFragmentManager().findFragmentById(R.id.map);

    // Getting a reference to the map
        googleMap = supportMapFragment.getMap();

        // Setting a click event handler for the map
        googleMap.setOnMapClickListener(new OnMapClickListener() {

            @Override
            public void onMapClick(LatLng arg0) {

                // Getting the Latitude and Longitude of the touched location
                latLng = arg0;
                lat = latLng.toString();
            //  Toast.makeText(getApplicationContext(), lat,
        //             Toast.LENGTH_LONG).show();
            //  getMyLocationAddress();
                // Clears the previously touched position
                googleMap.clear();

                // Animating to the touched position
                googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

                // Creating a marker
                markerOptions = new MarkerOptions();

                // Setting the position for the marker
                markerOptions.position(latLng);

                // Placing a marker on the touched position
                googleMap.addMarker(markerOptions);

                // Adding Marker on the touched location with address
                new ReverseGeocodingTask(getBaseContext()).execute(latLng);

            }
        });

  }

protected void putExtra(String string, CharSequence text) {
    // TODO Auto-generated method stub

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is
    // present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;

}
}

I had used lat = map.getCameraPosition().target; and when I toast the value of lat, it is toasting 0.0
What I need is that when on swiping the map the latlng change and toast.

A: Wait until the map has loaded and then call getCameraPosition:
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
    @Override
    public void onMapLoaded() {
        LatLng pos = mMap.getCameraPosition().target;
        Log.e("", "Pos: " + pos.toString());
        mMap.addMarker(new MarkerOptions().position(pos));
    }
});


text:
Q: How to get the difference in minutes between two dates in Microsoft Excel? I am doing some work in Excel and am running into a bit of a problem. The instruments I am working with save the date and the time of the measurements and I can read this data into Excel with the following format:
   A           B
1 Date:      Time:
2 12/11/12   2:36:25
3 12/12/12   1:46:14

What I am looking to do is find the difference in the two date/time stamps in mins so that I can create a decay curve from the data. So In Excel, I am looking to Make this (if the number of mins in this example is wrong I just calculated it by hand quickly):
   A           B                 C
1 Date:      Time:       Time Elapsed (Minutes)
2 12/11/12   2:36:25               -
3 12/12/12   1:46:14            1436.82

I Have looked around for a bit and found several methods for the difference in time but they always assume that the dates are the same. I exaggerated the time between my measurements some but that roll over of days is what is causing me grief. Any suggestions or hints as to how to go about this would be great. Even If I could find the difference between the date and times in hrs or days in a decimal format, I could just multiple by a constant to get my answer. Please note, I do have experience with programming and Excel but please explain in details. I sometimes get lost in steps.

A: To add a bit more perspective, Excel stores date and times as serial numbers.
Here is a Reference material to read up.
I would suggest you to use the following:
Combine date to it's time and then do the difference. So it will not cause you any issues of next day or anything.
Please refer to the image with calculations. You may leave your total minutes cell as general or number format.

*

*MS EXCEL Article: Calculate the difference between two times

*Example as per this article

A: time and date are both stored as numerical, decimal values (floating point actually). Dates are the whole numbers and time is the decimal part (1/24 = 1 hour, 1/24*1/60 is one minute etc...)
Date-time difference is calculated as:
date2-date1

time2-time1

which will give you the answer in days, now multiply by 24 (hours in day) and then by 60 (minutes in hour) and you are there:
time elapsed = ((date2-date1) + (time2-time1)) * 24 * 60

or
C3 = ((A3-A2)+(B3-B2))*24*60

A: Neat way to do this is:
=MOD(end-start,1)*24

where start and end are formatted as "09:00" and "17:00"
Midnight shift
If start and end time are on the same day the MOD function does not affect anything. If the end time crosses midnight, and the end is earlier then start (say you start 23PM and finish 1AM, so result is 2 hours), the MOD function flips the sign of the difference.
Note that this formula calculates the difference between two times (actually two dates) as decimal value. If you want to see the result as time, display the result as time (ctrl+shift+2).
https://exceljet.net/formula/time-difference-in-hours-as-decimal-value

A: *

*get n day between two dates, by using days360 function =days360(dateA,dateB)

*find minute with this formula using timeA as reference =(timeB-$timeA+n*"24:00")*1440

*voila you get minutes between two time and dates

A: I think =TEXT(<cellA> - <cellB>; "[h]:mm:ss") is a more concise answer. This way, you can have your column as a datetime.


text:
Q: How do I server-redirect to the default error page from an error code set with the header() function? I wanna know if there is a posibility of making the apache server auto redirect to its default error page from an error code set within the header() function.
lets say I have my page.php, this page has this:
<?php header("HTTP/1.1 404 Not Found"); ?>

The browser (using web dev tools in chrome), shows that the response has been sent but it doesn't redirect to its default error page, maybe is because the file still exists.
what i want to do, is redirect specific files to the default error pages by myself but keeping the exact URL showing in the browser, is the same action the server does when you enter a non-existing URL

A: If I remember correctly, you can just configure Apache to use a specific 404 page in httpd.conf and it will keep the URL the same, but deliver the 404 error page:
ErrorDocument 404 /404.php

and in /404.php, just put something like:

        <title>Object not found</title>

Object not found

The object <?php echo($_SERVER['PHP_SELF']); ?> could not be found on this server.

A: To get the HTTP response code you can use the http_response_code() function. Example:
if( http_response_code() == 404 )
{
    // Redirect to your valid custom page
    header("Location: http://www.mypage.com/page_not_found.php" );
}

A: Redirect to a page that does not exist. Then you get the apache created 404 because you have, indeed, landed on a page that does not exist.
This allows you to 'decide' who gets that page and who bounces. Of course, if they have a "nofollow" directive in their web client, it'll fail.
I don't know of a way to both Have a php page there And have apache decide 404 after checking the page in question. It has already relinquished control to PHP. So you likely need to push the request back to apache by deflecting to a non-existent file. You could even get funny and redirect to the same file name ... but end it in .html instead of php, and if that does not exist Poof you have a 404 error for web browsers.


text:
Q: C#, SignalR, Owin self host - I'm not able to unsucribe events First, I'm sorry for me English.
I try to write a code for RFID reader and I would like to use C# + SignalR + Owin.
I have following code.
namespace SignalRSelfHost {
   using System;
   using Microsoft.Owin.Hosting;
   using Microsoft.AspNet.SignalR;
   using Owin;
   using Microsoft.Owin.Cors;
   using ReaderSDK;

   class Program{
      static void Main(string[] args) {
        using (WebApp.Start<Startup>("http://localhost:8080/")) {
            Console.WriteLine("Server running at http://localhost:8080/");
            Console.ReadLine();
        }
      }
   }

   public class Startup {
      public void Configuration(IAppBuilder app) {
         app.UseCors(CorsOptions.AllowAll);
         app.MapSignalR();
      }
   }

   //class for basic reader settings with reader event + event handler
   public class RFIDReader {
      public Reader reader = new Reader();
      //definition event, what I'll fire for MyHub class
      public event Action<string> TagToClient;

      public RFIDReader() {
         try {
            //connect to reader
            reader.Connect("xx.xx.xx.xx");
            // event from reader and handler
            reader.TagsComing += TagsComingHandler;
         }
         catch (Exception ex) {
            Console.WriteLine(ex.Message);
         }
      }

      //handler for event readerTagsComming
      void TagsComingHandler(Reader sender, Tags packet) {
         foreach (Tag tag in packet) {
           //fire event for MyHub class
           TagToClient(tag.toString());
         }
      }
   }

   //MyHub class for communication via SignalR
   public class MyHub : Hub {
      static RFIDReader rfidreader = new RFIDReader();

      // this method is activated from JavaScript client of course
      // JavaScript client code is not relevant for this example
      public void ReaderStart() {
        //start of reader reads
        rfidreader.start();
        //here I want unsucribe handler - it doesn't works
        rfidreader.TagToClient -= TagToClientHandler;
        //here I subcribe handler
        rfidreader.TagToClient += TagToClientHandler;
      }

      //handler for event TagToClient
      void TagToClientHandler(string tagNumber){
         Console.WriteLine(tagNumber);
      }

      //this method is also activated from JavaScript client
      public void ReaderStop() {
         //stop of readers reads
         rfidreader.stop();
      }

   }

}

My problem is, that I'm not able unsucribe event handler TagToClientHandler and if I repeatedly perform method ReaderStart in MyHub class, I get a data from reader twice, thrice, etc..
I have there unsubscribing of this handler, however, it has no effect.
Does somebody have any idea?

A: static void TagToClientHandler(string tagNumber){
    Console.WriteLine(tagNumber);
}

define void TagToClientHandler as static should do the trick, else probably everytime the handler has another reference and -= won't remove anything
or just set TagToClient to null
rfidreader.TagToClient = null

A: Hub instances are transient and you will get a new instance for each request. As a result storing any kind of data that is supposed to be used across multiple calls or subscribing to events is not going to work. You need to have a separate way for storing things whose lifetime is longer than the lifetime of the Hub but still accessible from the Hub so that you can invoke methods from your hub (the simplest thing might be just a static property on the hub but you need to think if it will work if you have multiple clients and they all will start invoking methods (also think about threading)).
Note that the Hub class has OnConnected/OnDisconnected events that can also be useful in your case to track connections.

A: The problem is your static initializer
static RFIDReader rfidreader = new RFIDReader();

Since MyHub is transient, a new one is instantiated on every call.  That means you are reinitializing rfidreader on every call.  You should add a constructor to the class, check for null and only initialize it if null
public class MyHub : Hub {
   static RFIDReader rfidreader = null;

   public MyHub() {
      if (rfidreader == null) {
         rfidreader = new rfidreader();
   }

...
}


text:
Q: Can anyone identify the following signal? Im currently working on trying to reverse engineer a USB puzzle board I was given. (its a ATMega168 based device with a standard FTDI USB to UART chip) and all the information you are given is you may need programming and electronic investigation tools to work it out.

Anyway I found the following signal on the SCA pin from the MCU but cant identify what it is. its on the i2c bus, clock line goes high and stays high.

Anyone know what it is?  If it helps I can send a dump of the MCU which will runin AVS Studio 4 simulate and let you interact with the uart whrre the main  puzzles are.
also is there any way I can work out what pins are used for what? im sure I need to interface with them in some way to activate things.  the board has the following pins exposed for connections on the back via pads on the pcb.  on the front is a standard SPI bus connector which all I dont know how to check if their is anything on there I can interface with using a bus pirate. (new to MCUs and the bus pirate but did managed to use it to pull a copy of the code from it)

*

*VCC

*GND

*PCINT19/OC2B/INT1

*PCINT0/CLKO/ICP1

*PCINT1/OC1A

*INT0/PCINT18

*VCC

*GND

*ADC1/PCINT9

*ADC0/PCINT8

*ADC4/SDA/PCINT12

*ADC5/SCL/PCINT13

*VCC

*GND

*SCK/PCINT5

*PCINT4/MISO

*PCINT3/OC2A/MOSI

*PCINT2/SS/OC1B

A: That is definitely one of those "keys" you're looking for.
It seems to be a UART signal and the 1st 2 bytes are 'k' (0x6b 01101011) 'y' (0x79 01111001).
To decode the rest from your scope trace, remember that the idle state between bytes is high (1) and that each byte begins with a start bit (0).
The data bits themselves are back-to-front, so the least significant bit is first after the start bit.
Alternatively, you could find the baud rate by measuring the period of 1 bit and then feeding the signal to something with a UART to display it for you.

A: Looks a lot like an UART signal. You can output that at any GPIO pin unsing a so-called software UART - which just uses a timer to toggle the pin at the correct times. Your logic analyser software should have a decoder for that.
The numbers in the screenshot make no sense to me, but it could be a common rate like 1200 or 9600 baud.


text:
Q: jQuery tabs won't mark current selected index I'm using jQuery UI tabs for a project with the AJAX approach. When you select and option from the listed tabs the content gets changed but the current tab stays the same.
Here's my js code:
 $('#tabs').tabs({
                select: function (event, ui) {
                    var url = $.data(ui.tab, 'load.tabs');
                    if (url) {
                        location.href = url;
                        return false;
                    }
                    return true;
                }
            });

And here's my HTML:

                    <%= Html.TabLink("Inicio", "Dashboard","List") %>

                    <%= Html.TabLink("Mis Listas", "Index", "List")%>

                    <%= Html.TabLink("Mis Amigos", "FriendDetail", "List")%>

                    <%= Html.TabLink("Invitar", "Invite","List") %>

            <asp:ContentPlaceHolder ID="MainContent" runat="server" />

Am I missing something?

A: Returning false is halting the remainder of the code necessary to switch to the tab you've selected. If you're attempting to stop the user from redirecting and simply showing a new URL, use window.location.replace()
e.g.
$('#tabs').tabs({
     select: function (event, ui) {
          var url = $.data(ui.tab, 'load.tabs');
          if (url)
               window.location.replace("asdadf");
     }
});


text:
Q: Capturing data in clip from smaller extent What I am trying to perform is a clip what captures the shoreline on a town in CT. I have the town boundary and I can use the buffer to extrude the polygon but I have wondering if there was an easier way.

as you can see its the negative space in the boundary of the town polygon that I am hoping the fill.

A: One way to do this (with a basic license) is with the Union tool. Create a polygon that contains the entire shoreline and extent to which you need the sea to cover.

Then use this new feature and your land feature as input to the tool. This should result in a new feature class that contains various features, of which one should be the sea boundary you need.

Delete all the other features you do not need.


text:
Q: How to tell Traefik not to try to connect to docker.sock when using AWS ECS and Fargate I am setting up a environment for a web application on AWS ECS using Fargate. The Setup uses several containers for front and backends and Traefik (also in a container) for routing behind an ALB. I am using ecs-cli and docker-compose files for deployments and everything works quite fine.
Despite everything is working properly the traefik container is logging errors continuously about not being able to connect to docker.sock
time="2019-09-12T21:54:13Z" level=error msg="Failed to retrieve information of the docker client and server host: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?"
time="2019-09-12T21:54:13Z" level=error msg="Provider connection error Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?, retrying in 3.829225701s"

I very much understand that traefik won't be able to connect to the docker.sock in that environment and as I configured the ECS Provider apparently correctly it does not need to connect to the socket. Hence it still tries.

traefik.toml
[entryPoints]
  ...

[ecs]
clusters = ["cluster-name"]
watch = true
refreshSeconds = 15
exposedByDefault = true
region = "eu-west-1"
domain = "ecs.domain"

[retry]

docker-comopse.yml
version: "3"
services:
  proxy:
    image: ${custom-image-with-toml-baked-in}
    command: --api --docker
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080"
    labels:
      - "traefik.enable=true"
      - "traefik.backend=traefik"
      - "traefik.frontend.rule=Host:traefik.ecs.domain"
      - "traefik.port=8080"
    logging:
      driver: awslogs
      ...

...

So as I mentioned it looks like Traefik still wants to connect to docker.sock while I cannot find a way to tell Traefik to only rely on ECS.

A: So while reviewing my question I scrutinised the line command: --api --docker in my docker-compose file and it turns out that the error comes from the --docker option...
This line is legacy stuff from earlier simple docker deployments, so removing this option worked for me.
docker-compose.yml
version: "3"
services:
  proxy:
    image: ${custom-image-with-toml-baked-in}
    command: --api
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080"
    labels:
      - "traefik.enable=true"
      - "traefik.backend=traefik"
      - "traefik.frontend.rule=Host:traefik.ecs.domain"
      - "traefik.port=8080"
    logging:
      driver: awslogs
      ...

...

So in case anyone runs into the same stupid issue, I hope this monologue can help.


text:
Q: Angular.js How can i set a constant in the login controller I have a simple login controller thats handles the app login process. on the module level, i have created a constant like this:
.constant('MyConstant', [{
    id: null,
    user: null
}])

In my Login controller i pass in the constant like so:
.controller('loginController', [
    '$scope',
    'MyConstant',
    function ($scope, MyConstant) {
        //here i want to change the constants data like this:
        MyConstant.user = 'My new username'
    }
])

But when i call the constant here i get undefined?
How is the proper way to handle this? Or is it better to do this entirely different?
And then when calling other controlers i want to be able to use this new data:
 .controller('otherController', [
         '$scope',
         'MyConstant',
        function ($scope, MyConstant) {
            //this should return 'My new username'
            console.log(MyConstant.user);
        }
    ])

A: Try to replace:
.constant('MyConstant', [{
    id: null,
    user: null
}])

to
.constant('MyConstant', {
    id: null,
    user: null
})

and add constant service in controller:
.controller('otherController', [
    '$scope', 'MyConstant',
    function ($scope, MyConstant) {
        //this should return 'My new username'
        console.log(MyConstant.user);
    }
])

And used as shared service(define in root) so that can use in any controller(whole application)
should work.

A: You forgot to inject MyConstant in otherController.
But that should not resolve your issue.
A constant is useful for API endpoints, or any value that you don't have to change inside of your app.
Why would you not use a service/factory ?
See http://bguiz.github.io/js-standards/angularjs/constants/


text:
Q: Column not found at liquibase migration for H2 in-memory database I had to replace my PostgreSQL database with an H2 in-memory database and my migration started to fail. The create table script runs but the insert fails.
ChangeSet classpath:database/changelog/create-default-user.xml::createUserTable::ethero ran successfully in 7ms
Change Set classpath:database/changelog/create-default-user.xml::insertDefaultUser::ethero failed.  Error: Column "username" not found; SQL statement:

Error Stacktrace
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibase' defined in class path resource [org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration$LiquibaseConfiguration.class]: Invocation of init method failed; nested exception is liquibase.exception.MigrationFailedException: Migration failed for change set classpath:database/changelog/create-default-user.xml::insertDefaultUser::ethero:
     Reason: liquibase.exception.DatabaseException: Column "username" not found; SQL statement:
INSERT INTO usr ("username", "password") VALUES ('admin', 'password') [42122-200] [Failed SQL: (42122) INSERT INTO usr ("username", "password") VALUES ('admin', 'password')]

Create table script
create table user_authorities (username varchar(255) not null , authorities varchar(255));
create table usr (username varchar(255) not null , password varchar(255), image_url varchar(255))

Insert user script
INSERT INTO usr ("username", "password") VALUES ('admin', 'password');
INSERT INTO user_authorities ("username", "authorities") VALUES ('admin', 'ADMIN');
INSERT INTO user_authorities ("username", "authorities") VALUES ('admin', 'USER');

Spring boot configuration
spring:
  profiles:
    active: dev
  datasource:
    url: jdbc:h2:mem:pc;DB_CLOSE_DELAY=-1;
    username: sa
    password: sa
    driver-class-name: org.h2.Driver
  jpa:
    generate-ddl: true
    hibernate:
      ddl-auto: update
    show-sql: true

  liquibase:
    change-log: classpath:database/changelog-master.xml
    url: jdbc:h2:mem:pc;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE

Spring boot version: 2.4.3

A: PostgreSQL and few other DBMS are different from others: they convert unquoted identifiers to lower case. H2 and many others convert unquoted identifiers to upper case and such behavior is actually a standard one.
If you want to use both DBMS for a some reason, you can add ;DATABASE_TO_LOWER=TRUE to JDBC url of H2, with this parameter H2 will treat case of identifiers in the same way as PostgreSQL does.
But if you want to use only the H2, it would be better not to use such settings and adjust your SQL to use upper case letters in quoted identifiers.
Anyway, mixing quoted and unquoted identifiers is a bad practice. Usually it's better  to always quote or never quote them. Note that there are various reserved words and these words cannot be used as unquoted identifiers.


text:
Q: Crispy forms CheckboxSelectMultiple display inline I am having a lot of difficulty getting a MultipleChoiceField list to display inline using crispy. I have tried adding div's between by displaying the form using
{{ for field in form }}

but it places the div's between each selectbox AND the select boxes label.
This is where I create the CheckboxSelectMultiple:
preferred_topics = forms.MultipleChoiceField(choices=TOPICS, required=False, widget=forms.CheckboxSelectMultiple())

And I am printing it out with:
{{  form|crispy }}

I also have many other form types before and after this field (text boxes etc)
Thank you.

A: You will probably need to use the {% crispy %} tags and FormHelper. This will allow you to use InlineField.
There is also the table option which doesn't use divs.


text:
Q: CascadeType problem in One to Many Relation I have two classes which have a Unidirectional One to Many relation with each other.
public class Offer{
    ...
    @OneToMany(cascade=CascadeType.ALL)
    @JoinTable(name = "Offer_Fields",
    joinColumns =
    @JoinColumn(name = "OFFER_ID"),
    inverseJoinColumns =
    @JoinColumn(name = "FIELDMAPPER_ID"))
    private Set<FieldMapper> fields = new HashSet<FieldMapper>();
}

@Entity
@Table(name = "FieldMapper")
public class FieldMapper implements Serializable {
   @Id
   @Column(name = "FIELDMAPPER_ID")
   @GeneratedValue
   private int id;
   @OneToOne(cascade=CascadeType.ALL)
   @JoinColumn(name = "multilingual_field_fk")
   private MultiLingual field;
   @OneToOne(cascade=CascadeType.ALL)
   @JoinColumn(name = "multilingual_value_fk")
   private MultiLingual value;
}

I want to store an Offer with a set of FieldMapper to database.
When I Use CascadeType.ALL in my OneToMany, I got this error:
org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions

and when I change CascadeType to something else I got this error:
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.RCSTT.library.FieldMapper

and here is where I save Offer :
public void insert(Offer offer) throws SQLException {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    session.save(offer);
    tx.commit();
    session.close();
}

and I don't use session in somewhere else.
in tx.commit(); line throws explained exceptions.
Thanks for your help.

A: The first exception leads me to believe that this is not a problem with your mapping/entities but with how the object lifecycle or Hibernate session is handled.
Are the FieldMappers that you're trying to save already persistent (in another session)? You might need to detach those first.


text:
Q: Object has no method getColumnType In my play application I send some JSON output to my view in order to show a google pie chart. Things go wrong when it renders the js
Object {cols: [{id: 'title', label: 'Title' , type: 'string'},{id: 'unitPrice', label: 'Unit Price', type: 'int'}],rows: [ has no method 'getColumnType'×

This message is all I get from trying and draw a pie chart using the Google Chart API.
What does this even mean? "no method 'getColumnType'"
Any insight would be greatly appriciated. my code, so far:
<!DOCTYPE html>

<title>PayView</title>

        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

A: You can also give a parameter to the function
function drawChart(draw)
{
    if(draw > 0)
    {
      var data=....;
      var options = ....;
      var chart = ....;
      chart.draw(data,options)
    }
}

And you call this function in your ajax giving a value like drawChart(1)

A: You're trying to use the "googleData" string built from the results of the ajax call before that call has completed.
You're going to have to rig up something that waits for the completion of the google library load as well as your ajax call.  That could look something like this:
        var loads = 0;
        google.load("visualization", "1", {packages:["corechart"]});
        google.setOnLoadCallback(function() {
          ++loads;
          if (loads == 2)
            drawVisualization();
        });

    // then in your "ready" handler:

            success: function(data, textStatus, jqXHR){
                process_items(data);
                ++loads:
                if (loads == 2)
                  drawVisualization();
            },

That (inelegant) setup increments a counter when the ajax call finishes and when the google thing finishes.  Both handlers check to see if they're the last one to finish, and invoke the "draw" function if so.


text:
Q: Mocking objects instantiated inside a class to be tested So I am learning TDD using the many resources here on SO, but I just cant seem to figure out what I do with private/protected objects instantiated inside a given method/constructor. Lets say I have a connection string. That connection string is used to construct a Sqlcommand or Sqlhelper. Well I want to mock that Sqlhelper so that when I test other methods I don't have to rely on the results coming from my database. But I cant access the Sqlhelper.
How do I work around this?

A: Its generally best (except for a very few rare occasions) to test only the public interface of the class as a whole. Try not to use one of the workaround methods (such as private objects) unless you really have to. Accessing private members of classes in tests tends to look good at first as theres less code to write to test an object, however when things start to change (and they will) anything accessing the internals of a class makes it more difficult to change its implementation, this can be crippling to a project if most of the tests are written in this way.
In this particular case you are interacting with an external dependency outside of your control (i.e. SqlHelper), I'd recommend wrapping the SqlHelper object in your own object that implements an ISqlHelper interface (or a more reasonably named interface for your scenario).
e.g.
public interface ISqlHelperWrapper
{
    void ExecuteQuery();
}

Then inject this in through the constructor of you're object under test:
public class SqlConsumer
{
   private ISqlHelperWrapper _sqlHelper;

   public SqlConsumer(ISqlHelperWrapper helper)
   {
       this._sqlHelper = helper;
   }

   public void QuerySomething()
   {
       this._sqlHelper.ExecuteQuery();
   }
}

Not only is this a better design (you've isolated the sql implementation specific stuff from the SqlConsumer, and given it fewer reasons to change). But you can now mock the ISqlHelper instance using a mocking framework as well as switch the implementation on construction.
Given your connectionstring scenario above, you could initialise the sqlhelperwrapper (There are better names for this) with the connectionstring and your SqlConsumer object doesn't need to know about it.


text:
Q: sql, keep only max value and delete others I have this sort of table :

-id | name | memo
-1   |  Gotham |  s1ep1
-2   |  Gotham |  s1ep3
-3   |  Gotham |  s1ep5

I would like to keep the entry with the max(memo) and delete others, so just keep the third one (ep5).
I can retrieve the result of all max(memo) group by name like this :
    SELECT id,max(memo) FROM `reminder` group by name

But I don't find the proper way to delete others, even looking at similar topics.
I expected something like "delete every entries that are not in my selection".
    delete from reminder where not exists (SELECT id,max(memo) FROM `reminder` group by name)

But it doesn't work, "You can't specify target table 'reminder' for update in FROM clause". I must do it badly. Thanks for help.

A: You can do this with a join:
delete r
    from reminder r left join
         (select name, max(memo) as maxmemo
          from reminder
          group by name
         ) rn
         on r.name = rn.name and r.memo = rn.maxmemo
    where rn.name is null;

As an aside.  More typically, one wants to keep the row with the highest id.  The structure is the same, just the columns are different:
delete r
    from reminder r left join
         (select name, max(id) as maxid
          from reminder
          group by name
         ) rn
         on r.name = rn.name and r.id = rn.maxid
    where rn.name is null;


text:
Q: How to add persistent connection support to a load-balanced HTTP webservice We are working on an HTTP webservice load-balanced using haproxy. The webservice is accessed via SSL. It is a RESTful HTTP service and simply accepts JSON, does some work, and returns JSON. There is no notion of a session.
We have redundant load-balancers set up in front of a pair of redundant webservice servers. Each server sits behind Apache, where Apache is used as a proxy in order to handle SSL and logging. If it matters, our webservice is a Clojure (java) application using compojure (jetty) to handle HTTP.
This is a brief diagram showing the path of a client request through our existing system.
client request -> haproxy (load balancing) -> apache (ssl, logging) -> webservice
We would like any connection to the load-balancer to establish a persistent connection and then be served by the same server for all subsequent requests sent through that persistent connection. In other words, we don't want a persistent connection to haproxy making requests to more than one webservice server.
How would you recommend that we get this working? How can we "pin" a given connection to the load-balancer to a specific webservice server? How could we prevent accidentally loading down a specific webservice server with multiple intensive requests?

A: You're looking for HAProxy's cookie directive, which will ensure that clients stick to the same backend.
As far as avoiding overloading a given backend, you'll be completely dependent on the initial load balancing - moving clients to a different server mid-session doesn't fit with session persistence being enforced from the load balancer.  If the load issue is a big one, then maybe reconsider having HAProxy do session persistence, keeping a centralized session state among the backends instead?

A: Using balance source in the defaults block, along with removing option httpclose entries did the trick.


text:
Q: Multiple belongs_to joins to the same table (In Rails 4.2 did the ability to do this in a clean way change?) With the latest way that joins and the where clauses work in Rails 4.2, it appears there is not a clean (using symbols...or just not using string SQL) way to join to the same table from a single query.
For instance, we have a user model, and it has a reference to a home address, and a work address. If we want to get all of the users that live and work in Indianapolis, what is the best way to go about building this query?
The ideal option would be something like this:
User.joins(:home_address).join(:work_address).
  where(home_address: { city: 'Indianapolis' } ).
  where(work_address: { city: 'Indianapolis' } ).count

However, the home_address and work_address (which are belongs_to associations on the User model) don't have any effect on the where clause. You have two user addresses, and obviously that is nearly good enough (since I am querying on that table twice).
Here is something that works, but just isn't as clean as the solution from above:
User.joins('INNER JOIN addresses as home_address ON home_address_id = home_address.id').
  joins('INNER JOIN addresses as work_address ON work_address_id = work_address.id').
  where(home_address: { city: 'Indianapolis' } ).
  where(work_address: { city: 'Indianapolis' } ).count

So the point of the question is, was this intentional (in previous versions of Rails, the belongs_to association name could be referenced in the where clause)? And, if it was, is there a technique that I'm not seeing of how to clean this up without using string SQL?
To be clear, in an earlier version of Rails, the belongs_to association worked for this type of query:
That used to work...in Rails 4.2 it no longer works:
irb(main):001:0> User.joins(:home_address, :work_address).where(home_address: { city: 'Indianapolis' }, work_address: { city: 'Indianapolis' }).to_sql
"SELECT \"users\".* FROM \"users\" INNER JOIN \"addresses\" ON \"addresses\".\"id\" = \"users\".\"home_address_id\" INNER JOIN \"addresses\" \"work_addresses_users\" ON \"work_addresses_users\".\"id\" = \"users\".\"work_address_id\" WHERE ((\"addresses\".\"city\" = 'Indianapolis' AND \"work_addresses_users\".\"city\" = 'Indianapolis'))"
irb(main):002:0> Rails::VERSION::STRING
"4.0.5"
irb(main):003:0>

However in the latest version of Rails, it no longer works:
[1] pry(main)> User.joins(:home_address, :work_address).
[1] pry(main)* where(home_address: { city: 'Indianapolis' }, work_address: { city: 'Indianapolis' }).count
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "home_address"
LINE 1: ...ses_users"."id" = "users"."work_address_id" WHERE "home_addr...
                                                             ^
: SELECT COUNT(*) FROM "users" INNER JOIN "addresses" ON "addresses"."id" = "users"."home_address_id" INNER JOIN "addresses" "work_addresses_users" ON "work_addresses_users"."id" = "users"."work_address_id" WHERE "home_address"."city" = $1 AND "work_address"."city" = $2
from /Users/ar3/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:637:in `prepare'
[2] pry(main)> Rails::VERSION::STRING
"4.2.1"
[3] pry(main)> User.last.home_address.present?
true
[4] pry(main)> User.last.work_address.present?
true
[5] pry(main)> User.joins(:home_address, :work_address).where(home_address: { city: 'Indianapolis' }, work_address: { city: 'Indianapolis' }).to_sql
"SELECT \"users\".* FROM \"users\" INNER JOIN \"addresses\" ON \"addresses\".\"id\" = \"users\".\"home_address_id\" INNER JOIN \"addresses\" \"work_addresses_users\" ON \"work_addresses_users\".\"id\" = \"users\".\"work_address_id\" WHERE \"home_address\".\"city\" = 'Indianapolis' AND \"work_address\".\"city\" = 'Indianapolis'"
[6] pry(main)>

Notice the difference in the .to_sql...one uses the alias defined by the belongs_to association, the new one, uses whatever we put in the where hash.

A: where clauses in ActiveRecord always use table names. As long as you are querying for the same thing on both associations you can do:
User.joins(:home_address, :work_address)
  .where(addresses: { city: 'Indianapolis' }).count

addresses being your table which contains the addresses.
But if you need a different where clause for both home_address and work_address then as far as I know you're out of luck. Someone correct me if I'm wrong, I couldn't find a way.
This is a great example where you can use STI though to enable you to do this an improve your architecture.


text:
Q: moveToThread() and than start() works with not constructed object? I have something like this:

main.cpp

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    static Communication *c = new Communication();
    return a.exec();
}

communication.cpp

t is Qthread object...
Communication::Communication()
{
    client = new EchoClient(QUrl(QStringLiteral("ws://localhost:1234")), 0);
    client->moveToThread(&t);
    connect(&t, SIGNAL(started()), client, SLOT(proces()));
    t.start(QThread::HighestPriority);
}

How is it possible that when I call constructor, that object is not created yet but will be in next iteration of main loop? I am trying to achieve that firstly, object will be created and than moved to thread and will be paralely listenning to messages while waiting for user input.
Thx
EDIT
I just want to add client to another thread because in main thread I want to wait for user input like this if I enhance this a little bit
Communication::Communication()
{
    client = new EchoClient(QUrl(QStringLiteral("ws://localhost:1234")), 0);
    client->moveToThread(&t);
    connect(&t, SIGNAL(started()), client, SLOT(proces()));
    t.start(QThread::HighestPriority);

std::cout << "\n***************CLIENT MENU***************\n";
std::cout << "(1): SHOW
std::cout << "(2): EXIT\n";
std::cout << "***************************************************\n";

std::cin >> m_choice;

}

Problem is it will show menu and it will be blocked and not recieve any message

A: Console I/O is blocking: when cin >> m_choice is waiting for user input in the main thread, the main thread can't do anything else. The event loop won't run, no slots in the main thread will run, etc.
You may wish to move the console I/O based menu system to a dedicated thread, and interface it with the rest of the system via signals/slots.


text:
Q: Packaging mp3 files into Qt app Since I found mp3 files can't be retrieved by QMediaPlayer from resource, I figure it out to use them as local file. I use this cmd with a little modification to copy files into installation directory:
copydata.commands = $(COPY_DIR) $$PWD/resources/sound $$OUT_PWD/HomeControl.app/Contents/MacOS
first.depends = $(first) copydata
export(first.depends)
export(copydata.commands)
QMAKE_EXTRA_TARGETS += first copydata

So those files existed in the /HomeControl.app/Contents/MacOS/sound. From Qt Creator the app plays the mp3 perfectly, but if executed from the build directory it doesn't play the mp3 at all! Really don't know why.
arm away btn clicked
current media:  "file:///Dev/Qt_Sample/build-test_widgets-Desktop_Qt_5_3_0_clang_64bit-Debug/HomeControl.app/Contents/MacOS/sound/System_Arm_Away.mp3"
disarm stay btn clicked
current media:  "file:///Dev/Qt_Sample/build-test_widgets-Desktop_Qt_5_3_0_clang_64bit-Debug/HomeControl.app/Contents/MacOS/sound/System_Disarmed.mp3"

Is there any difference from executing in the Qt creator & directly from the App? Like debug mode or what?
Or is there other ways to correctly deploy mp3 files into the bundle?

A: This is how I build in resources for OS X bundles:
mac {
    Resources.files = dirInTheProjectDirectory
    Resources.path = Contents/MacOS
    QMAKE_BUNDLE_DATA += Resources
}

You can call Resources whatever you fancy.
That copies them to Contents/MacOS/dirInTheProjectDirectory. You can then access them with QDir(QCoreApplication::applicationDirPath()+"/dirInTheProjectDirectory/");
The likely problem is when you're accessing them in your code you're pointing to the path in the build directory, and not the path that's within your bundle.

A: Here's my final solution. Thank you @nicholas-smith.
In the .pro file:
# deploy with mp3 folder
mac {
    Resources.files = ./resources/sound
    Resources.path = Contents/MacOS
    QMAKE_BUNDLE_DATA += Resources
}

Then accessing those file with:
// pass the path of mp3 to the QMediaPlayer
playAudio(QCoreApplication::applicationDirPath()
    + "/sound/System_Disarmed.mp3");

From log it shows:
arm away btn clicked
current media:  "file:///Dev/Qt_Sample/build-test_widgets-Desktop_Qt_5_3_0_clang_64bit-Debug/HomeControl.app/Contents/MacOS/sound/System_Arm_Away.mp3"


text:
Q: Error when using Model.save() to MongoDB The issue that I am having is this:
I have two Schemas, one is a User, and the other is a Message.
Now, when I try to post  a message from one User to another, a message.id is created, however the text for the message and the author are not saving.
Here are my Schemas
var mongoose = require("mongoose");

var messageSchema = mongoose.Schema({
    text: { type: String },
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        name: { type: String }
    }
});

module.exports = mongoose.model("Message", messageSchema);

And User
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var uniqueValidator = require('mongoose-unique-validator');

var UserSchema = mongoose.Schema({
    username: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    first_name: { type: String, required: true },
    middle_initial: { type: String, required: true },
    last_name: { type: String, required: true },
    phone: { type: Number, required: true },
    address: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    isManager: Boolean,
    isSysAdmin: Boolean,
    points_accrued: Number,
    id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    },
    messages: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Message"
        }
    ]
});

UserSchema.plugin(passportLocalMongoose);
UserSchema.plugin(uniqueValidator);

module.exports = mongoose.model("User", UserSchema);

And Lastly here is my route
var express    = require("express"),
    router     = express.Router({ mergeParams: true }),
    User       = require("../models/user"),
    Message    = require("../models/message"),
    middleware = require("../middleware");

//INDEX SHOW USER INFO
router.get("/", middleware.isLoggedIn, function (req, res) {
    res.render("users/index");
});

// Gets messages for regular Employees, not Admins
router.get("/messages", middleware.isLoggedIn, function (req, res) {
    User.find({}, function (err, allUsers) {
        if (err) {
            console.log("Error Occured");
            console.log(err);
        } else {
            res.render("users/messages", { users: allUsers });
        }
    })
});

//================//
// POST A MESSAGE //
//================//

router.post("/messages", middleware.isLoggedIn, function (req, res) {
    User.findByUsername(req.body.reciever, function (err, foundUser) {
        if(err){
            console.log(err, "Could Not Find User");
            res.redirect("back");
        } else {
            console.log("User Found...");
            console.log(foundUser);
            Message.create(req.body.newMessage, function (err, newMessage) {
                if(err){
                    req.flash("error", "Whoops! Something went wrong...");
                    console.log(err);
                    res.redirect("/users/messages");
                } else {
                    newMessage.author.id = req.user._id;
                    newMessage.author.name = req.user.first_name + " " + req.user.middle_initial + " " + req.user.last_name;
                    newMessage.save();
                    // console.log(message.text);
                    foundUser.messages.push(newMessage);
                    foundUser.save();
                    req.flash("success", "Message Sent!");
                    res.redirect("/users/messages");
                }
            });
        }
    });
});

module.exports = router;

Now when I try to use <%= message.text %> I receive nothing, and when I try to console.log(message.text) in my ejs file I get undefined. When I try <%= message %> I get the ID for the message. Lastly, in my route, I can console.log(req.body.newMessage) and so on and it does comeback with the data. However when I try something like console.log(foundUser.messages[0].text) I get undefined even though I just used .save() on the Message and foundUser. I am really confused and if anyone can shine light on this that would be super helpful. I have tried pretty much everything that I could. Thanks!
UPDATE!!!!!!!
As it turns out, the Schema is correctly saving, however my issue still remains that I cannot view anything but the ID for the message. Here is that the data Object looks like:
{
    "_id": {
        "$oid": "5b26c60f25d6c9248c91b5ee"
    },
    "text": "hey",
    "__v": 0,
    "author": {
        "id": {
            "$oid": "5b25b6c25813b101b4887dec"
        },
        "name": "Scott W Selke"
    }
}


text:
Q: com.google.firebase.auth.FirebaseAuth is not linked I try Firebase push notification in a separate Android studio project and it
 work fin but when I integrate it in a existing project I had this problem .
Error :
 D/FirebaseApp: com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
Depend:
 dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })

       compile project(':library')
      compile 'com.android.support:appcompat-v7:25.3.1'

        compile 'com.baoyz.swipemenulistview:library:1.3.0'

        compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
    }
    apply plugin: 'com.google.gms.google-services'

A: Use implementation instead of compile. Also, make sure you have implemented Firebase Auth in your project.


text:
Q: Read DOM after jQuery drag and drop Good day!
I tried to do drag and drop using jQuery and read DOM after it. In drop function I use append() method to append draggable to new place. But it is likely that draggable is removed from old location only after drop() method is finished rather than append() method is finished.
It may sounds strange, but here is an example.
Here is my javascript:

    $(document).ready(function(){

                    $('div.drag').draggable({
                        helper : 'clone',
                        opacity : 0.3
                    });

                    $('td.cell').droppable({
                        accept : function(draggable){
                            if($(this).find('.drag').length > 0){
                                return false;
                            }
                            return true;
                        },
                        drop : function(event, ui) {
                            $(this).append(ui.draggable);

                            $('#myTable').change();
                        }

                    });

                    $('#myTable').change(function() {
                        var table = document.getElementById('myTable');
                        var trList = table.getElementsByTagName('tr');

                        var resultString = '';
                        for (var i=0; i < trList.length; i++)
                        {
                            var tdList = trList[i].getElementsByTagName('td');
                            for (var j=0; j < tdList.length; j++)
                            {
                                if(tdList[j].getElementsByTagName('div').length > 0){
                                    resultString+='row' + i + ' column ' + j + ';';
                                }
                            }

                        }

                        $('#result').text(resultString);
                    });
                });

Here is my html snippet:

drag me

So, when I drag there is not new position only in the result div, but previous position is also present!
How can I avoid it?


text:
Q: Do we use "can have" + past participle for past possibility? Is it possible to use Can have + Past Participle for past possibilities?
I Know  could have or might have are mostly used, but is the following possible?

It could have been Bill's note
It might have been Bill's note
It can have been Bill's note

A: While you might be able to invent a sentence where you can argue that can have is valid, the short answer to your question is No. Choose either could have or might have.

A: Correct: It could have been Bill's note.
Correct: It might have been Bill's note.
Incorrect: It can have been Bill's note.
We can use 'cannot have' or 'could not have' when we think a past event was impossible.
It cannot have been Bill's note. or It could not have been Bill's note.


text:
Q: Relatively prime numbers proof. How do I rather quickly prove that $$a=2500137802, b=1420515313, c=3920653117$$ are relatively prime numbers? I know it has something to do with Euclidean algorithm, but still doesn't ring a bell to me.

A: Hint $\ $ Any common divisor divides $\,2\, =\, 3920653117 -2500137802 - 1420515313$


text:
Q: Java "Variable Name" Can't be resolved, Error with Variable in IF Statement Scanner scan = new Scanner(System.in);

System.out.println("Enter up to 5 Tests:");
int test1 = scan.nextInt();
if (test1 > -1){
  int test2 = scan.nextInt();
} else {
  if (test2 > -1){
    int test3 = scan.nextInt();
  } else {
    if (test3 > -1){
      int test4 = scan.nextInt();
    } else {
      if (test4 > -1){
        int test5 = scan.nextInt();
      }
    }
  }
}

I get a compile error that "test2 cannot be resolved to a variable," which happens for every variable except test1. I assume that it is because test2 doesn't exist until we make it by entering a value. What can I do here to make Java happy?

A: You are defining test2 inside this block -
if (test1 > -1){
    int test2 = scan.nextInt();
}

so, you won't be able to access it outside. This is how Java works. Similar is true for test3 and test4 (would have been true for test5 too if you would've accessed it outside its definition block).
To make the variables available to the entire method, you could do something like this -
public static void main (String str[]) throws IOException {

    int test1, test2, test3, test4, test5;

    // rest of your code;
}

To learn more about variable scope, take a quick look.
You may also like to initialize your variables with some initial value, as testing them directly without initialization in the if condition will lead you into trouble.

A: it is because test2,test3 and test4 are local variables.Make test2,test3 and test4 as global variables
test2,test3 and test4 are defined with in if blocks
Try with the following code
public static void main (String str[]) throws IOException {

          Scanner scan = new Scanner(System.in);
int test1=0,test2=0,test3=0,test4=0,test5=0;
          System.out.println("Enter up to 5 Tests:");
          test1 = scan.nextInt();
          if (test1 > -1){
          test2 = scan.nextInt();
          } else {
            if (test2 > -1){
          test3 = scan.nextInt();
          } else {
            if (test3 > -1){
          test4 = scan.nextInt();
          } else {
            if (test4 > -1){
          test5 = scan.nextInt();
            }}}}

A: Basically, test2, test3, etc. are declared in one scope, but after that scope closes, they are no longer available. As a fix (judging by what you're trying to do), I'd suggest declaring them at the beginning of the method as such:=declare the ints at the beginning of the method:
public static void main(String str[])
        throws IOException
{
    int test1 = -1, test2 = -1, test3 = -1, test4 = -1, test5 = -1;

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter up to 5 Tests:");
    test1 = scan.nextInt();
    if(test1 > -1)
    {
        test2 = scan.nextInt();
    }
    else
    {
        if(test2 > -1)
        {
            test3 = scan.nextInt();
        }
        else
        {
            if(test3 > -1)
            {
                test4 = scan.nextInt();
            }
            else
            {
                if(test4 > -1)
                {
                    test5 = scan.nextInt();
                }
            }
        }
    }
}

Furthermore, it doesn't look like your method will do what you want it to; if test1 is valid, it takes in test2, but finishes there. To that end, what you're probably wanting to do is this:
public static void main(String str[])
        throws IOException
{
    int test1 = -1, test2 = -1, test3 = -1, test4 = -1, test5 = -1;

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter up to 5 Tests:");

    test1 = scan.nextInt();
    if(test1 > -1)
    {
        test2 = scan.nextInt();
    }
    if(test2 > -1)
    {
        test3 = scan.nextInt();
    }
    if(test3 > -1)
    {
        test4 = scan.nextInt();
    }
    if(test4 > -1)
    {
        test5 = scan.nextInt();
    }

    // Work with the tests.
}

A: Since test2 is not visible to out side first if statement you will get this error. Define your variables such that they can access entire if else blocks.


text:
Q: I have a problem with Jdbc.getConnection from google app script At the moment I use mysql for connection to my google app script, however some days ago, I have problem with the function Jdbc.getConnection of GAS, I here share my error. I need to help guys. thanks.
My error

A: This is a known issue and reported in the Issue Tracker. You may star the issue to get updates when Google resolves it at their end.


text:
Q: WSL2 can not access windows ip (retreived by `ip route | grep default | awk '{print $3}` ) Test code:
winip=$(ip route | grep default | awk '{print $3}')
ping $winip

result:

Actually I want to use a proxy service host on windows .  I saw many people success with above command, why I faied ? Or wsl2 go into new problem ?

A: OK. Thanks to the kindness of this site owner https://lengthmin.me/posts/wsl2-network-tricks/ .
I find it is due to windows firewall ...
But seems add wsl2 path to whitelist doesn't take effect, need shutdown firewall down to work around the problem.

Thanks to https://github.com/microsoft/WSL/issues/4585#issuecomment-610061194
This is the solution
New-NetFirewallRule -DisplayName "WSL" -Direction Inbound  -InterfaceAlias "vEthernet (WSL)"  -Action Allow


text:
Q: Semiconductors and energy bands The valence and conduction band of a semi-conductor are often drawn as here click.
This plot has essentially two features and I would like to understand them.
The peak and the valley of the two bands coincide, in what sense is this a characteristic feature for a semiconductor. I mean, I could have that they don't agree at all, would this necessarily mean that my material is not a semiconductor. I don't think so, as this should mostly depend on the energy gap. So why is this important in these drawings?
Both bands are drawn as parabolas ( with opposite curvatures), where does this come from?

A: If the valence band maximum and the conduction band minimum are on the same position in k-space, this means that you have a direct gap semiconductor (GaAs, InAs, ...). If the CB minimum is at a finite k-value, it would be an indirect gap semiconductor (like Si, Ge, AlAs, ...)
The bands appear as parabolas due to the dispersion of a quasi-free electron/hole
$$ E(k) = \frac{\hbar^2 k^2}{2 m^{\ast}} $$
Real bandstructures are not perfectly parabolic, but it serves as a good approximation around k = 0.


text:
Q: Remember each folder's view settings in Windows 7? I know this functionality is not available as a built-in option for Windows 7.  However, I'm asking because I'm curious if anybody here has found a way to achieve this effect through other means (perhaps a 3rd party utility, or some other trick).
Please keep in mind that I'm not interesting in remembering window position and sizes.  I only care about the view/layout settings (icons/list/details/etc).  I'm also not interested in setting a single default view for every folder.
I understand this might not be possible, but I wanted to take the chance asking.

A: The view is attached to the library. Or, more precisely, the library type (Music, Video, Documents etc). The folder view as seen from outside the library can be different.
All included folders and sub-folders in a library will always share the same folder view.
The most one can do is have separate "Arrange by" view settings in each added right-click -> New -> Folder created in the library itself.
One "workaround" I know of, is to setup a second library with the view you want. You can even have the same folders in it.
The extremely long thread
Is Remember each folder's view settings functionality gone for good?
has this solution by a guy named Gray (which I haven't tested) :

There are two scenarios with remembering views (Windows 7):

*

*Libraries - Don't Remember

*Folders / Favourites - DO Remember (Easy Fix : Add My Docs to Favourites - see below)

  Library Behavior
Lets say you click Documents, then choose 'medium icons', wherever you
  navigate within Documents from then on stays in 'med icon' view.
NB Choosing Organize>Fold & Search Options>View>'Apply to Folders' and
  'Reset Folders' are not available in Libraries.
Folders / Favorites
Folders do remember views by default. So if you navigate to
  C:\users\xxx\Documents etc each individual folder in the tree will
  remember whatever you set it to.
Likewise if you add 'My Documents' to Favorites and navigate from
  there. To add 'My Docs' to Favorites you need to navigate to your User
  Folder e.g:

*

*Start Menu > User Folder > My Docs

*Right-click Favorites > Add current location to favorites

  DO NOT add 'My Docs' to Favorites from within Libraries. As it is
  'Libraries' that ignore last view setting.
NB Choosing Organize>Fold & Search Options>View>'Apply to Folders' and
  'Reset Folders' are available in Folders. So you can make all folders
  copy your current view (Apply to folders).

A:
Remember each folder's view settings in Windows 7? I know this functionality is not available as a built-in option for Windows 7.

Sure it is. Windows automatically stores all related information about Explorer windows in the registry in ShellBags.

However, I'm asking because I'm curious if anybody here has found a way to achieve this effect through other means (perhaps a 3rd party utility, or some other trick).

It happens automatically, so no third-party tool should be needed. There do exist a few tools that let you view them, but there aren't any tools that let you save or restore them. (Actually, I wrote one back in the day for XP, but ShellBags changed a lot with Vista and I never had enough motivation to bother updating it.)

I'm not interesting in remembering window position and sizes. I only care about the view/layout settings (icons/list/details/etc). I'm also not interested in setting a single default view for every folder.

They're the same thing; Windows stores all of those settings in the ShellBags.

I understand this might not be possible, but I wanted to take the chance asking.

Windows should automatically save the view mode for each folder, but it defaults to saving only the most recent 400 folder settings. You can increase this so that it saves more (or less) by modifying (or adding if necessary), the following the BagMRU Size registry entry:
Windows Registry Editor Version 5.00

;Save folder settings for 1,000 folders (1000=3E8 hex)
[HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell]
"BagMRU Size"=dword:000003E8

;This is supposedly where you set it for 64-bit systems, but the above one works just fine
[HKEY_CURRENT_USER\Software\Classes\Wow6432Node\Local Settings\Software\Microsoft\Windows\Shell]
"BagMRU Size"=dword:000003E8

If necessary, you can try manually saving and restoring the folder settings by exporting and importing the registry key HKCR\Software\Microsoft\Windows\Shell (make sure to close Windows Explorer before restoring).
Additionally, there existed since the Windows 95 days, a rumor that holding the Ctrl when clicking the [x] button to close an Explorer window will force Windows to save that folder's settings, but that was never definitively proven to be real, and certainly not proven to still apply to recent versions of Windows.

A: I'm running Win7 x64 and it does seem to remember my folder settings (I say seem to because I have never actively checked it until now). My Pictures folder shows as large tiles and pretty  much everything else is detailed view.
According to some posts here though, if it is part of a Library (or at least accessed through a Library link) it will not remember the folder layout (although that also seems to work ok for me...)
EDIT: Having done some more playing, I think what the users in the link I posted mean is; If you change the layout of a folder within explorer having accesses the folder the "normal" way, if you then navigate to that same folder through a library link, the layout will not have changed and will be the same layout you used last time you access the folder through the library link (If that makes any sense whatsoever!).

A: Set the customization for 1 folder type (music, documents,videos, pictures all data). Now select the root dir, change the folder type to the customized view and select to apply this layout to all subfolders.


text:
Q: Is there any build tool like maven in racket? I'm from java world and enthusiasm with Racket.
Want to know is where a tools similar as Maven position.If you not family with Maven, there are SBT in Scala, gradle in Android, mix in Elixir, etc, as build tool.
Specify, I need the feature to define a project:
1. manage dependencies.
2. build to library(which is called package in racket).
3. build to executable app.
I have try with raco which has many features include build to library or to executable app and install a directory as a local package.
What I want to achieve is manage dependencies from a package central repository.
raco pkg install can't defined in a project file like pom.xml
Thanks a lot.
Update
There is a tool called PLaneT could define require package which from a central repository but official website called it as old package system.
New package system in here, but not find any feature like or could replace PLaneT.

A: The package repository for Racket is here:
http://pkgs.racket-lang.org/

The Racket philosophy is not to have external tools, but embed
build information into the program. There is a tool to download and
install packages though -- it is called raco. See the Racket
docs for more information on raco.
If you prefer a more graphical approach, try out the package manager in DrRacket.


text:
Q: Are buffer overflows no longer a threat these days? After following buffer overflow examples and reading on them in various books/websites it seems there are lots of preventative measures in place to protect against them these days. ASLR, /GS flag security cookie, stack-protector in linux, etc, etc...
Some of the examples I have looked at give instructions on how to disable certain security features so that the examples will run...This seems like a really stupid idea to me - when running code against a real system you are not going to have the luxury of disabling its security features.
So what is the deal with buffer overflows these days, have them been rendered redundant by advances in security or are they still of use?

A: Yes, they are of use, and yes, the protections are routinely turned off, off by default, or non-existant on various platforms.
To make the point explicit, I'm sure a modern product developed by smart people like Google Chrome would never have something as mundane as a buffer overflow. (Pick any word; those are just from 2011.)

EDIT To the question of why. Lots of answers. One simple one is that canaries only protect the return address, not the individual variables on the stack. Nor do stack canaries or non-executable stacks protect against heap-based overflows. If you have writable vtables (or any kind of function pointer), then attackers can rewrite your function calls on the stack or heap without touching the canary. There's a major performance trade-off for every additional protection you put in. And the stricter you make your execution environment, the more likely you won't be able to reuse legacy code without reworking it (and retesting it).
Attackers have to be more clever today than when Aleph One was writing about stack smashing. Some of the older attacks don't work widely anymore. But the basic idea of a buffer overflow has many forms, and many of those forms still work.

A: Three words:  "Defense In Depth".
The meaning:  The more you can do to prevent vulnerabilities, the better.  Don't rely on any one thing (or even a couple of things) to protect you.  They could be broken -- or, as you've seen, disabled.
Consider that even if you turn on all the paranoid security measures, if someone figures out how (or is lucky enough) to bypass any or all of the countermeasures put in place by your OS, then your only remaining defense is the correctness and robustness of your own code.
Plus, arbitrary code execution is just the worst of the worst as far as vulnerabilities go.  Whether your broken code allows arbitrary native code execution or just crashes, that's still someone else causing your computer to do something it shouldn't, and potentially costing you lots of money.

A: A lot of these countermeasures can be defeated by advanced exploitation techniques such as Return Oriented Programming (ROP). To answer your question, anti-exploitation techniques have made things much more difficult for a would-be attacker to exploit a buffer overflow but it's absolutely still possible and the severity of the consequences when one is successfully exploited is very high, as they typically allow arbitrary code execution.


text: Q: How can I create an exfat partition that can be mounted without root? I am using "mkfs.exfat /dev/sdb1" and it works beautifully, except only a root user can modify the contents. I have looked through all of the options I can find for mkfs and cannot figure this out. Thanks.


text:
Q: Error when using PEAKachu for peak calling I am trying to use PEAKachu to call peaks for RNA eclip pair-end data. I installed PEAKachu on slurm by building from the source:
make readme_rst
make package
pip3 install --user dist/PEAKachu-0.2.0.tar.gz

Then, I used the command to run PEAKachu:
peakachu adaptive -M 200 -m 0.0 -Q 0.05 -c control.bam -t experiment.bam  -o peakachu

But it returned an error after running for 1 minute:
** Converting reads to bed format for 1 libraries...
expdupsorted generated an exception: A process in the process pool was terminated abruptly while the future was running or pending.
Traceback (most recent call last):
  File "/jet/home/li6/.local/bin/peakachu", line 162, in <module>
    sys.exit(main())
  File "/jet/home/li6/.local/bin/peakachu", line 140, in main
    args.func(controller)
  File "/jet/home/li6/.local/bin/peakachu", line 150, in adaptive_approach
    controller.adaptive_approach()
  File "/jet/home/li6/.local/lib/python3.8/site-packages/peakachulib/controller.py", line 131, in adaptive_approach
    adaptive.generate_combined_bed_file()
  File "/jet/home/li6/.local/lib/python3.8/site-packages/peakachulib/adaptive.py", line 84, in generate_combined_bed_file
    replicon]["reads"].add(lib.replicon_dict[replicon][
KeyError: 'reads'

I am so confused because I tracked back to see what the code was doing, and the relevant part of code is:
80 for replicon in sorted(self._replicon_dict):
81             self._replicon_dict[replicon]["reads"] = pd.Series()
82             for lib_name, lib in exp_lib_dict.items():
83                 self._replicon_dict[replicon]["reads"] = self._replicon_dict[
84                    replicon]["reads"].add(lib.replicon_dict[replicon][
85                        "reads"], fill_value=0)

As in line 81, it has created the key "reads" for _replicon_dict[replicon], how I can solve this problem? Thanks in advance.


text:
Q: Unity saving inputfield I am making a 2D platformer where I want the users inputted name to hover over there character.
This is what the menu screen looks like
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class set_usernames : MonoBehaviour {

    public InputField name;
    public InputField second_name;

    private string Bader_input_name;
    private string Dwarf_input_name;

    public void updatename(string name){

    }
    public void setget()
    {
        //Debug.Log (name.text);
        Bader_input_name = name.text;
        Dwarf_input_name = second_name.text;

        //Application.loadedLevel("game");
        Debug.Log ("name was " + Bader_input_name);
        Debug.Log ("name was " + Dwarf_input_name);
        SceneManager.LoadScene ("map_select");
    }
}

This is the error message I get

A: Basically what that means is that you are trying to access an object that's not instantiated. I have no idea how are you trying to access the input but the easiest way is to make two public inputs in your UIController drag and drop them in Unity and access the Text property of input objects like so: myInput.Text.


text:
Q: Are @PathVariable or @RequestBody needed in external function signature? I have one question about convention. Everything works ok (thanks god), but I am not sure, if annotations (@PathVariable and @RequestBody) are needed in my AttributeService class method signature:
@Autowired
private AttributeRepository attributeRepository;

public Attribute create(@RequestBody Attribute attribute) {
    return attributeRepository.save(attribute);
}

It will probably work with, or without them, but do they have any purpose outside my @RestController controller?
Controller method looks like this (here I need these annotations of course):
@PostMapping(consumes = "application/json")
public Attribute create(
        @RequestBody Attribute attribute
) {
    return attributeService.create(attribute);
}

I mean, it makes me confused if I browse my service class and I see yellow annotations, and I am mistaken that I am in Controller class :)
Another question, is it okay if they have the same name "create"? Name of controller's method does not actually matter, because it is called automatically, but I am asking about convention. I find it easy to make them with same name, so I know quickly match that create() from controller is calling create() in service (if I have many methods like this).
Thank you

A: Yes, these annotations are needed to provide automatic deserialization of the text in the response body or path variable to the corresponding Java object in the Controller.  In your service class you work with the Java object, so these annotations are redundant here.
As for the naming convention, it's up to you and your peers :)

A: There is no sense in using @RequestBody in methods of your AttributeService. No framework will ever process this annotation.
In my opinion, read for GET, create for POST, update for PUT and delete for DELETE are good method names for HTTP methods, respectively. As you stated, any name will work.


text:
Q: Cannot modify an evaluated object originating in an imported file I am trying to delete a file from my visual studio project, but this dialogue pops up and prevent me from doing that. What does it mean and how do I resolve this problem?
There is a xamarin thread about this but no solution there.
https://forums.xamarin.com/discussion/25719/cannot-modify-an-evaluated-object-originating-in-an-imported-file

A: We have no idea what the real problem is, but we do find a fix by comparing this project with some other project files that we have.
The fix is to open the .Shared.vcxitems file in an text editor and replace this:
  <ItemGroup>
    <ProjectCapability Include="$(MSBuildThisFileDirectory)SourceItemsFromImports" />
  </ItemGroup>

with this
  <ItemGroup>
    <ProjectCapability Include="SourceItemsFromImports" />
  </ItemGroup>

A: Restarting Visual Studio fixed the issue for me.

A: I ran across this question as well as a couple others related to the error message, specifically. My issue was different from the OP's as it had to do with NuGet packages not installing/uninstalling/updating.
I opened the .CSProj files only to see the package reference completely missing for Microsoft.NET.Test.Sdk, ie some VS file somewhere was caching this bad reference, even after killing all existing .vs directories. So I just added it manually, ran nuget restore, and was back in business.
Basically, I modified this block of project file XML:
  <ItemGroup>
    <PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
      <Version>6.2.8</Version>
    </PackageReference>
    <PackageReference Include="MSTest.TestAdapter">
      <Version>1.4.0</Version>
    </PackageReference>
    <PackageReference Include="MSTest.TestFramework">
      <Version>1.4.0</Version>
    </PackageReference>
  </ItemGroup>

to this:
  <ItemGroup>
    <PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
      <Version>6.2.8</Version>
    </PackageReference>
    <PackageReference Include="MSTest.TestAdapter">
      <Version>1.4.0</Version>
    </PackageReference>
    <PackageReference Include="MSTest.TestFramework">
      <Version>1.4.0</Version>
    </PackageReference>
    <PackageReference Include="Microsoft.NET.Test.Sdk">
      <Version>16.1.1</Version>
    </PackageReference>
  </ItemGroup>

A: In my solution happend because there was NuGet packages source pointing to non-existent local folder, changed it in Package Manager Settings.

A: My workaround was to open the .vcxitems and .vcxitems.filters, mentioned in the error message, in text editor and delete the file directly in the xml. Also I want to note that this error appears for me only when I tried to delete files that were part of different .vcxitems that was imported into main project. You can check your main project for <Import Project="xyz.vcxitems" />.


text:
Q: trying to set the logging for REALM / Tomcat and Intellij I am using Intellij 11 and trying to debug REALM and LDAP
i found this article
Configure debug logging for Realms and Authentication
the problem is that i am modifying the CATALINA_HOME/conf/logging.properties and
intellij seems to be ignoring it.
Any suggestions or help would be appreciated
thanks

A: It appears to be a bug in Tomcat integration. I've created an issue in YouTrack, please vote.


text:
Q: Bash script pass ssh command to remote server and bring back the prompt I am restarting bunch of remote servers via bash script but the script waits for me to break before moving on.
#!/bin/bash
main()
{
        hostlist=("server1" "server2")
        echo -e "----- Reatsrting all servers -----"
        for host in ${hostlist[@]};
        do
                echo "----- Restarting $host -----"
                ssh -t $host "sudo reboot -f now"
                echo "----- Restart of $host complete -----"
        done
        echo "----- All servers restarted -----"
}
main

The result of above script is
----- Reatsrting all servers -----
----- Restarting server1 -----
packet_write_wait: Connection to 10.10.1.11 port 22: Broken pipe
----- Restart of server1 complete -----
----- Restarting server2 -----
packet_write_wait: Connection to 10.10.1.12 port 22: Broken pipe
----- Restart of server2 complete -----
----- All servers restarted -----

If you notice the "packet_write_wait: Connection to ...", this happens as the server takes time to restart and i have to manually break it by hitting enter, when i do that i get the packet_write_wait line and the script moves on with next code.
Is there a way by which i can just shoot the restart command and forget so i can move on with the rest of the script (get my prompt back without manually intervening)?

A: Putting it all together, with the advice from comments.
#!/bin/bash
main()
{
        hostlist=("server1" "server2")
        echo -e "----- Reatsrting all servers -----"
        for host in ${hostlist[@]};
        do
                echo "----- Restarting $host -----"
                ssh -t $host 'sudo reboot -f now &'
                echo "----- Restart of $host complete -----"
        done
        echo "----- All servers restarted -----"
}
main