text:
Q: Eating Exceptions in c# om nom nom Given that eating exceptions is always bad juju and re-throwing the exception loses the call stack, what's the proper way to re-factor the following?
Eating Exceptions:
try
{
  … do something meaningful
}
catch(SomeException ex)
{
   // eat exception
}

A: Catch and handle specific types of exceptions. Good practice is to not just catch System.Exception. A robust routine will strongly type the exceptions it knows how to handle.
Exceptions shouldn't be used for control flow, but there are often specific unwind procedures that need to be taken based on the type of exception.
Depending on the specific type, you may or may not choose to rethrow it. For example, an ASP parsing exception being thrown to an error page that USES the code causing the exception will cause an infinite loop.
try
{

}
catch( FileIOException )
{
    // unwind and re-throw as determined by the specific exception type
}
catch( UnauthorizedAccessException )
{
    // unwind and re-throw as determined by the specific exception type
}
catch( SomeOtherException )
{
    // unwind and re-throw as determined by the specific exception type
}
catch( Exception )
{
   // log and re-throw...add your own message, capture the call stack, etc.

   // throw original exception
   throw;

   // OR, throw your own custom exception that provides more specific detail and captures
   // the original exception as the inner exception
   throw new MyStronglyTypedException();
}
finally
{
     // always clean up
}

A: Most people think it's utterly evil to eat/suppress exceptions, especially with catch-alls. (Ironically, they use the catch all response of "don't use catch-alls, it's evil" :-). I don't understand the religious fervour with which people parrot this view, because if used sensibly, there is nothing wrong with this approach.

*

*In my book, the worst case scenario is that my program catastrophically exits -> this creates a very unhappy customer with a total data loss situation. An unhandled exception is guaranteed to cause this every time. So failing to handle an exception is statistically more dangerous than any risk of instability that may occur if an exception is suppressed. In light of this, anything we can reasonably do to protect against an unhandled exception occurring is a good thing.

*Many people seem to forget that catch alls can often handle any exception correctly, even if they don't know the details of what the exception was. By this I mean that they can guarantee that the program state remains stable, and the program continues to run within its design parameters. Or there may even be side effects such as the user finding a button unresponsive, but they still won't lose any data (i.e. graceful degradation is better than a fatal crash). For example, sometimes you want to return one value on success and a default if you fail for any reason. Part of designing code is knowing when to report errors to the user and when to fix a problem on their behalf so their program "just works". In this situation, a well designed catch-all is often the correct tool for the job.

*Exceptions worry me. Fundamentally an exception is a guaranteed program crash if I don't handle it. If I only add specific exception handling for the exceptions I expect, my program is inherently fragile. Consider how easily it can be broken:

*

*If a programmer forgets to document one exception they might throw, I won't know I need to catch it, and my code will have a vulnerability I'm not aware of.

*If someone updates a method so that it throws a new exception type, that new exception could ripple up the call stack until it hits my code. But my code was not built to handle the exception. Don't tell me that the libraries I'm calling will never change.

*Every exception type you specifically handle is another code path to be tested. It significantly multiplies the complexity of testing and/or the risks that a broken bit of handling code might go unnoticed.

*The view underpinning the "suppression is evil" view is that all exceptions represent an instability or error - but in many cases programmers use exceptions to return little more than status information. For example, FileNotFound. The programmer writing file I/O code has decided on my behalf that a missing file is a fatal error. And it might be. It is up to me to catch this and decide that actually it's a common and perfectly normal,  or expected, situation. A lot of the time, suppressing exceptions is necessary to simply stop someone else's "decision" taking out my application. The old approach of simply ignoring error return codes wasn't always a bad thing, especially given the amount of effort it takes to catch and suppress the myriad "status" exceptions that are bandied about.
The trick to silently eating/suppressing exceptions is just to be sure that this is the correct way to handle them. (And in many cases, it's not). So there may be no need to refactor your example code - it might not be bad juju.

A: try
{
 ...
}
catch(SomeException e)
{
 //Do whatever is needed with e
 throw; //This rethrows and preserves call stack.
}

A: That all depends on where the code lives.
In the depths of the system? If that is the case then I would gather some form of standard error handling should exist across the product, if not it needs to.
If it is on the presentation side for instance it may have no value to anyone except the code, and in that case additional logic may need to be placed in a finally block.
Or let it roll up hill altogether and don't wrap it in a try catch if you aren't going to do anything useful in the catch anyways.
… do something meaningful

A: Your code can be rewritten (to eat exception) like this
try
{
  … do something meaningful
}
catch
{
   // eat exception
}

But I don't understand what you want to do by refactoring!!
Edit:
Re-throwing using throw; doesn't work always. Read this ->
http://weblogs.asp.net/fmarguerie/archive/2008/01/02/rethrowing-exceptions-and-preserving-the-full-call-stack-trace.aspx

A: To add to the excellent comments already provided.
There are three way to "re-throw" an exception:
catch (Exception ex)
{
   throw;
}

The above preserves the call stack of the original exception.
catch (Exception ex)
{
   throw ex;
}

The above eats the original exception chain and begins a new one.
catch (Exception ex)
{
   throw new MyException("blah", ex);
}

The above adds the original exception to the InnerException of a new chain. This can be the best of both worlds, but which one is correct is highly dependent on what you need.

A: In general, it's not a good idea to catch the general Exception unless you can actually handle it.  I think the right answer is a combination of Tim's and Joshua's answers.  If there are specific exceptions that you can handle and remain in a good state, for example FileNotFoundException you should catch it, handle it, and move on, as seen here:
try
{
    // do something meaningful
}
catch(FileNotFoundException)
{
    MessageBox.Show("The file does not exist.");
}

If you can't handle it and remain in a good state, don't catch it in the first place.
However, one case where you would want to catch the general Exception and re-throw it would be if you have any cleanup that you will need to do, for example aborting a database transaction, before the exception bubbles up.  We can accomplish this by extending the previous example like so:
try
{
    BeginTransaction();

    // do something meaningful

    CommitTransaction();
}
catch(FileNotFoundException)
{
    MessageBox.Show("The file does not exist.");
    AbortTransaction();
}
catch(Exception)
{
    AbortTransaction();
    throw;                  // using "throw;" instead of "throw ex;" preserves
                            // the stack trace
}

A: Refactor it to:
// No try
{
   … do something meaningful
}
// No catch

and let the exception be handled at the main loop.

A: if the catch() block only rethrows exception and does not do any real exception handling then you don't need try..catch at all.

A: Part of the problem with eating exceptions is that it's inherently unclear what they're hiding.  So... the question of the proper refactoring isn't easily answered.  Ideally, however, you'd remove the try...catch clause entirely; it's unnecessary in most cases.
Best practice is to avoid try...catch entirely wherever possible; if you must deal with exceptions, then do so as locally and specifically as possible and don't propagate them up the stack; finally, include a global unhandled exception handler that does the appropriate logging (and perhaps offers to restart the application if necessary).

A: Unless the catch block actually does something with the exception (e.g., logging it to a system error file), there is no need to even have the try/catch block.
That being said, if the exception is worth informing the user about (e.g, logging it), then by all means use a catch block to do so.
One particularly bad pitfall of ignoring exceptions is that certain (fatal) exceptions should cause the program to terminate. Such exceptions (e.g., failure to load a class) leave the program in an unstable state, which will only lead to disaster later on in the execution. In these cases, logging the exception and then gracefully terminating is the only reasonable thing to do.

A: You can rethrow exception without losing call stack just re-throw as
catch(Exception e)
{
  throw;
}

Why would you need this?
Usage example:
Somewhere in your app you have 3rd party code and you wrap it, and if it throws exceptions you throw WrappingException.
When you execute some other code you might get exception either from 3rdparty or either from your own so you may need:
try
{
//code that runs 3rd party
//your code, but it may throw Null ref or any other exception
}
catch( WrappingException)
{
 throw;
}
catch( Exception e)
{
 throw new MyAppLayer3Exception("there was exception...", e);
}

In this case you do not wrap WrappingException with your MyAppLayer3Exception.
So, at the top level of you application you may catch all exceptions and by knowing Type of exception you will know where from it came!
Hope it helps.

A: The particular way in which exceptions are eaten is not important. Never eat exceptions by any means!
Only catch exceptions that are expected to occur and which you can do something about. Examples of this include file and network IO, security exceptions, etc. For those cases you can display an explaination of what happened to the user, and sometimes you can recover gracefully.
Do not catch exceptions that should never occur. Examples of these are null-reference exceptions, invalid operation exceptions, etc. The code should be written so that these exceptions will never happen, so there is no need to catch them. If those exceptions are happending, then fix the bugs. Don't swallow the exceptions.
It is OK to log all exceptions, but this should be done with the unhandled exception handler on the program and any threads that are created. This is not done with a try/catch.

A: eating exceptions is not always "bad juju". There is no magic here; just write code to do what you need to do. As a matter of hygiene, if you catch an exception and ignore it, comment as to why you are doing it.
try
{
 .....
}
catch (something)
{
  // we can safely ignore ex becuase ....
}

A: Sometimes, it's just best not to deal with exceptions if you really don't want to deal with the added responsibility that comes with exceptions. For example, rather than catching an NullReferenceException, why not just make sure that the object exists before you try to do something with it?
if (yourObject != null)
{
    ... do something meaningful with yourObject ...
}

Exceptions are best reserved to handle those things you really have no control over, such as the sudden loss of a connection, or things which have the potential to kill a long-running process, such as a data import.  When an exception is thrown, regardless of the reason, your application has reached a point of instability. You catch the exception to return the application to a point of stability by cleaning up the mess, e.g. disposing of the lost connection and creating a new one OR logging the line where the error occurred and advancing to the next line.
I've been dealing with exception handling for the last 15 years, starting with the first six versions of Delphi, up to (and including) .NET 1.0-4.0. It is a powerful tool, but it is a tool that is often overused. I have found consistently, during that time, the most effective exception handling process is deferring to if-then before try-catch.

A: One major problem with the exception hierarchy is that exceptions are categorized based upon what happened, rather than based upon the system state.  Some exceptions mean "a function couldn't perform its task, but it didn't disturb the system state either".  Others mean "Run for your lives!  The whole system is melting down!"  In many cases, it would be entirely proper for a routine which could handle the failure of a called method to swallow any and all exceptions of the former type; in other cases, such exceptions should be rethrown in a manner which indicates possible state corruption (e.g. because there was a failure in an operation necessary to reset the system state; even though the attempt to perform that operation didn't disturb anything, the fact that the state wasn't reset means it's corrupted).
It would be possible for one to manage one's own exceptions into such a hierarchy, but I don't know any good way to deal with other exceptions.


text:
Q: ReactJS / Javascript conditional statements I am using arrow keys to move the circle object. Now I want to limit it to the height and witdth of the svg area. My conditional statements partially work as once the ball gets to any of the 'walls' it gets stuck and does not move anywhere. I understand why it does it but can't think of a way to prevent it from doing it.
Edit: CodePen: http://codepen.io/wasteland/pen/GZvWeo?editors=0110
Thanks

class App extends React.Component {
  constructor(props) {
    super(props)
    // Why you need to bind _handleKey:
    // https://facebook.github.io/react/docs/reusable-components.html#no-autobinding
    this._handleKey = this._handleKey.bind(this)
    this.state = {
      h: 200,
      w: 800,
      x: 50,
      y: 50,
      r: 20,
      stroke: "none",
      fill: "#6F90A2"
    }
  }
  _currentPosition() {
    // Display the current position
    console.log(this.state.x, this.state.y);
  }

  _handleKey(e){
    // Define key codes and movement vectors
    const vector = {
     37: [-1, 0],
     38: [0, -1],
     39: [1, 0],
     40: [0, 1]
    };
    // Display the current position
    this._currentPosition()

    // Detect key presses and change the position accordingly
   if (e.keyCode in vector) {
        if (this.state.x < this.state.w - this.state.r &&
         this.state.x > this.state.r &&
         this.state.y > this.state.r &&
         this.state.y < this.state.h - this.state.r) {
          this.setState({
            x: this.state.x + vector[e.keyCode][0],
            y: this.state.y + vector[e.keyCode][1]
          })
      }
  }
  }

   componentDidMount() {
     document.addEventListener("keydown", this._handleKey, false);
  }
   render() {
    return (
      <div>
        <Circle { ...this.state } />
      </div>
    )
  }
}

Thank you
Edit:
Following a suggestion below, I tried the following, which fails when you're in one of the four corners:
 if (e.keyCode in vector) {
      if (this.state.x < this.state.w - this.state.r &&
      this.state.x > this.state.r &&
         this.state.y > this.state.r &&
         this.state.y < this.state.h - this.state.r) {
        this.setState({
          x: this.state.x + vector[e.keyCode][0],
          y: this.state.y + vector[e.keyCode][1]
        })
      } else {
        this.setState({
          x: this.state.x - vector[e.keyCode][0],
          y: this.state.y - vector[e.keyCode][1]
        })

      }
        }

A: Handle the x and y coordinates separately. See newX and newY in _handleKey here: http://codepen.io/Sphinxxxx/pen/pyWYNG?editors=0010

redpajama_set_name: RedPajamaStackExchange


text:
Q: Idiomatic way to handle JPA criteria ordering in Kotlin I have a CriteriaBuilder-based query that can be ordered by several different properties.
Currently it's being handled somehow like this:
when(filters.sortBy) {
    "foo" -> query.orderBy(if(isAsc) cb.asc("bar") else cb.desc("bar"))
    "baz" -> query.orderBy(if(isAsc) cb.asc("quux") else cb.desc("quux"))
}

It's definitely not the most readable or maintainable code I've ever written.
Is there a better and possibly more idiomatic way to do this in Kotlin, given that it doesn't have the ternary ? : operator?
Note that some of the properties I need to order by may be subproperties of the root object, so just extracting this to a method that takes a string as the name of the order clause may not be easy.

A: when is an expression, so you can use it's result directly as an argument in query.orderBy()
Also, local function would help to eliminate if-else duplication part
 fun query(...) {
    ...
    fun sort(name: String) = if (isAsc) cb.asc(name) else cb.desc(name)
    query.orderBy(sort(
            when (filters.sortBy) {
                "foo" -> "bar"
                "baz" -> "quux"
            }
    ))
    ...
 }


text:
Q: joomla database import error hello am trying to import the database to mysql through phpmyadmin but am getting following error:

--
-- Database: `final`
--
-- --------------------------------------------------------
--
-- Table structure for table `nqjr5_assets`
--
CREATE TABLE `nqjr5_assets` (
  `id` int(10) UNSIGNED NOT NULL COMMENT 'Primary Key',
  `parent_id` int(11) NOT NULL DEFAULT '0'COMMENT AS `Nested set parent.`,
  `lft` int(11) NOT NULL DEFAULT '0'COMMENT AS `Nested set lft.`,
  `rgt` int(11) NOT NULL DEFAULT '0'COMMENT AS `Nested set rgt.`,
  `level` int(10) UNSIGNED NOT NULL COMMENT 'The cached level in the nested tree.',
  `name` varchar(50) NOT NULL COMMENT 'The unique name for the asset.\n',
  `title` varchar(100) NOT NULL COMMENT 'The descriptive title for the asset.',
  `rules` varchar(5120) NOT NULL COMMENT 'JSON encoded access control.'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS `Nested set parent.`,
  `lft` int(11) NOT NULL DEFAULT '0'COMMENT AS `Nested ' at line 13

A: Your syntax is wrong. it should be like this

CREATE TABLE nqjr5_assets (
    id int(10) UNSIGNED NOT NULL COMMENT 'Primary Key',
    parent_id int(11) NOT NULL DEFAULT '0' COMMENT 'Nested set parent.',
    lft int(11) NOT NULL DEFAULT '0'COMMENT 'Nested set lft.',
    rgt int(11) NOT NULL DEFAULT '0'COMMENT 'Nested set rgt.',
    level int(10) UNSIGNED NOT NULL COMMENT 'The cached level in the nested tree.',
    name varchar(50) NOT NULL COMMENT 'The unique name for the asset.\n',
    title varchar(100) NOT NULL COMMENT 'The descriptive title for the asset.',
    rules varchar(5120) NOT NULL COMMENT 'JSON encoded access control.' )
    ENGINE=InnoDB DEFAULT CHARSET=utf8;


text:
Q: Power BI: a visualization to dynamically show a network interaction Network visual with dynamic selection
Is anyone aware of a network association visual with dynamic selection formatting? Essentially, something like network navigator (or zoom charts drill down graph pro) but with the ability to select nodes and have associated nodes highlighted in some way. I've not been able to find this functionality using the zoom charts free trial or with any other visual. TIA

A: If you happen to have basic knowledge of Python, here's a solution based on NetworkX for creating a graph and gravis for creating an interactive graph visualization where you can highlight the neighborhood of a node by hovering with the mouse over it.
Disclosure: I'm the author of gravis. I hope this concrete example is useful for your requirements.
import gravis as gv
import networkx as nx

graph = nx.les_miserables_graph()
gv.d3(graph, edge_size_data_source='weight', use_edge_size_normalization=True, node_hover_neighborhood=True)

Result if you use this code inside a Jupyter notebook and hover over the node Myriel. You can also use a regular Python interpreter and see the visualization in a webbrowser window that pops up.


text:
Q: Class Loading issue in Wildfly 16 During my migration from weblogic to wildfly 16, I need to implement the concept of a shared library but all I am is getting class loading issues. I am new to the concept of modules.
I created a folder for the library with jars in modules and created a module.xml. I used jboss-deployment-structure.xml to map the dependency to the shared library. The EAR gets the external jar but I am getting a class not found for the jar inside the EAR. It seems the jar inside the EAR is being excluded when I add the jboss-deployment-structure.xml to the EAR. Without the
jboss-deployment-structure.xml I am able to deploy and login to my application but cant implement the functionalities of the shared jar.

The above image is the jboss-deployment-structure.xml I used.

The above image is the module.xml I used.

This is the server log I got on deployment with reference to the module created, It shows that the file "FileItem" is not found in the location I created but the jar with that class is already present in the EAR. Why is it not being read ?

A: According to the error in the screenshot, JBoss is not able to resolve your dependency com.lib. The module you created i.e. com.lib should be present in one of the following locations :

*

*$JBOSS_HOME/modules/

*$JBOSS_HOME/modules/system/layers/base

e.g. For location according to 1, The directory structure will be like :

$JBOSS_HOME/modules/com/lib/main

You will have following files at this location

*

*module.xml

*ebsUtility.jar

*SessionHandler.jar


text:
Q: Background Service gets killed on clearing from recents in MIUI Jugnoo Driver App has not been whitelisted in the Auto Start but yet it again starts the service after some time !
How jugnoo rider app runs even it is not Auto start too
I have done notification stuff , changed the manifest to stopWithTask="false" .

A: I have created a service for same issue,
please check it out with this.
It will help you
public class GpsServices extends Service implements LocationListener, GpsStatus.Listener {
Data data;
private LocationManager mLocationManager;
private SharedPreferences sharedPreferences;
private Data.onGpsServiceUpdate onGpsServiceUpdate;
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
public  String gps_notification = "gps_channel";

@SuppressLint("MissingPermission")
@Override
public void onCreate() {

    // Start up the thread running the service.  Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block.  We also make it
    // background priority so CPU-intensive work will not disrupt our UI.
    HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

    if (data == null) {
        data = new Data(onGpsServiceUpdate);
    } else {
        data.setOnGpsServiceUpdate(onGpsServiceUpdate);
    }

    gpsListener();

    mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    if (mLocationManager.getAllProviders().indexOf(LocationManager.GPS_PROVIDER) >= 0) {
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, this);
    } else {
        Log.w("SideMenuActivity", "No GPS location provider found. GPS data display will not be available.");
    }

    if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Toast.makeText(this, "Gps not enabled", Toast.LENGTH_SHORT).show();
    }

}

public void onLocationChanged(Location location) {

    Gson gson = new Gson();
    String json = sharedPreferences.getString("data", "");
    data = gson.fromJson(json, Data.class);

    if (data == null) {
        data = new Data(onGpsServiceUpdate);
    } else {
        data.setOnGpsServiceUpdate(onGpsServiceUpdate);
    }

    String speed = String.format(Locale.ENGLISH, "%.0f", location.getSpeed() * 3.6);

    Toast.makeText(this, speed, Toast.LENGTH_SHORT).show();

    Log.e("isRunningFalse", speed);
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // For each start request, send a message to start a job and deliver the
    // start ID so we know which request we're stopping when we finish the job
    Message msg = mServiceHandler.obtainMessage();
    msg.arg1 = startId;//needed for stop.

    if (intent != null) {
        msg.setData(intent.getExtras());
        mServiceHandler.sendMessage(msg);
    } else {
        Toast.makeText(GpsServices.this, "The Intent to start is null?!", Toast.LENGTH_SHORT).show();
    }

    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    // We don't provide binding, so return null
    return null;
}

/* Remove the locationlistener updates when Services is stopped */
@Override
public void onDestroy() {
    mLocationManager.removeUpdates(this);
    mLocationManager.removeGpsStatusListener(this);
    stopForeground(true);
}

@Override
public void onGpsStatusChanged(int event) {
    switch (event) {
        case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
            @SuppressLint("MissingPermission") GpsStatus gpsStatus = mLocationManager.getGpsStatus(null);
            int satsInView = 0;
            int satsUsed = 0;
            Iterable<GpsSatellite> sats = gpsStatus.getSatellites();
            for (GpsSatellite sat : sats) {
                satsInView++;
                if (sat.usedInFix()) {
                    satsUsed++;
                }
            }

            if (satsUsed == 0) {
                data.setRunning(false);
                stopService(new Intent(getBaseContext(), GpsServices.class));
            //                    firstfix = true;
            }
            break;

        case GpsStatus.GPS_EVENT_STOPPED:
            if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                Toast.makeText(this, "Gps not enabled.", Toast.LENGTH_SHORT).show();
            }
            break;
        case GpsStatus.GPS_EVENT_FIRST_FIX:
            break;
    }
}

@Override
public void onProviderDisabled(String provider) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {
        //promote to foreground and create persistent notification.
        //in Oreo we only have a few seconds to do this or the service is killed.
        Notification notification = getNotification("App is running");
        startForeground(msg.arg1, notification);  //not sure what the ID needs to be.
        // Normally we would do some work here, like download a file.
        // For our example, we just sleep for 5 seconds then display toasts.
        //setup how many messages
        int times = 1, i;

        Bundle extras = msg.getData();
        if (extras != null) {
            times = 1000*60*60*24;  //default is one
        }
        //loop that many times, sleeping for 5 seconds.
        for (i = 0; i < times; i++) {
            synchronized (this) {
                try {
                    wait(5000); //5 second sleep
                } catch (InterruptedException e) {
                }
            }
            String info = i + "GPS SPEED LOG";
            Log.d("intentServer", info);
            //make a toast
            //unable to ensure the toasts will always show, so use a handler and post it for later.
            // Toast.makeText(MyForeGroundService.this, info, Toast.LENGTH_SHORT).show();
        }
        // Stop the service using the startId, so that we don't stop
        // the service in the middle of handling another job
        //            stopSelf(msg.arg1);  //notification will go away as well.
    }
}

// build a persistent notification and return it.
public Notification getNotification(String message) {

    return new NotificationCompat.Builder(getApplicationContext(), gps_notification)
            .setSmallIcon(android.R.drawable.ic_menu_mylocation)
            .setOngoing(true)  //persistent notification!
            .setChannelId(gps_notification)
            .setContentTitle("Gps Service")   //Title message top row.
            .setContentText(message)  //message when looking at the notification, second row
            .build();  //finally build and return a Notification.
}
         }


text:
Q: accelerometer - Movement pattern recognition (iphone) I have to find the best approach for tackling a problem for trying to recognize physical movements - with an iPhone in a pocket - like waling, stopping, turning left/right, sitting.
I was thinking on just heuristically find the data corresponding to each action, then to check the incoming values against this data (with a threshold) and see what's happening.
That's a very rough approach, of course, so maybe using something like the Support Vector Machine
methods, but this seems too complicated for the amount of time I have to develop this.
Which approach would you suggest here?

A: Walking: Do an fft on the gravity direction signal. Measure its frequency response for walking at different speeds and then set a simple threshold.
Stopping: if the average power i.e. total energy in the signal over the last few seconds drops below a certain threshold then you can say the user has stopped.
Turning left,right: Use the gravity vector and the gyroscopes rotation speed vector to determine whether the user is rotating clockwise or counterclockwise
Sitting: This will be very hard to determine but if youre lucky the SVM will find the right pattern.
Each of the above can be given a weighting and then you will have to find a good way to obtain training data to train your SVM. Maybe stream the signals from the phone to a webserver and simultaneously record the users motions by hand.
Your best starting point is Apples Sample code: CoreMotionTeapot
Alternatively you could analyze the GPS signal. This will give you a very good way to determine the users larger scale motion like walking/moving or changing heading etc.


text:
Q: Slow Boot in Ubuntu 22.04 - Geoclue issue? I run ubuntu 22.04 and today my computer started being very slow to reboot (I was having trouble with nordvpn and was trying multiple things to fix it following their support team advice. When I restarted my system following their instructions I got the slow boo issue). It gets to the login screen at the usual speed, but after I put my password it goes to a black screen and  takes a few minutes to load the desktop. I looked at my log with journalctl --since today and there was a 1 minute and a half gap apparently due to geoclue (see output below showing the jump in time around the time I have the issue with geoclue). What should I do?
I tried just removing geoclue with sudo apt-get remove geoclue-2.0. However, it also wants to remove the following packages: gdm3 geoclue-2.0 gir1.2-geoclue-2.0 gnome-calendar gnome-control-center  gnome-initial-setup gnome-settings-daemon gnome-shell gnome-shell-extension-appindicator gnome-shell-extension-desktop-icons-ng gnome-shell-extension-ubuntu-dock libgeoclue-2-0 ubuntu-desktop ubuntu-desktop-minimal ubuntu-session. What should I do in this case to solve my issue?
I am not a super experienced user, so let me know if I am wrong. Thanks for your help!
LOG OUTPUT:
nov 23 13:38:10 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2619]: dbus-update-activation-environment: setting GTK_MODULES=gail:atk-bridge
nov 23 13:38:10 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2627]: dbus-update-activation-environment: setting QT_ACCESSIBILITY=1
nov 23 13:38:10 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2629]: /etc/X11/Xsession.d/90x11-common_ssh-agent: linha 9: has_option: comando não encontrado
nov 23 13:38:12 roberto-IdeaPad-Gaming-3-15IMH05 systemd[1]: systemd-localed.service: Deactivated successfully.
nov 23 13:38:12 roberto-IdeaPad-Gaming-3-15IMH05 systemd[1]: systemd-hostnamed.service: Deactivated successfully.
nov 23 13:38:13 roberto-IdeaPad-Gaming-3-15IMH05 systemd[1]: fprintd.service: Deactivated successfully.
nov 23 13:38:15 roberto-IdeaPad-Gaming-3-15IMH05 systemd[1]: systemd-timedated.service: Deactivated successfully.
nov 23 13:38:42 roberto-IdeaPad-Gaming-3-15IMH05 geoclue[1615]: Service not used for 60 seconds. Shutting down..
nov 23 13:38:42 roberto-IdeaPad-Gaming-3-15IMH05 systemd[1]: geoclue.service: Deactivated successfully.
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting SHELL=/bin/bash
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting QT_ACCESSIBILITY=1
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting XDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/etc/xdg
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting LANGUAGE=pt_BR:pt:en
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting DESKTOP_SESSION=ubuntu
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting GTK_MODULES=gail:atk-bridge
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting PWD=/home/roberto
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting XDG_SESSION_DESKTOP=ubuntu
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting LOGNAME=roberto
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting XDG_SESSION_TYPE=x11
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting GPG_AGENT_INFO=/run/user/1000/gnupg/S.gpg-agent:0:1
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting SYSTEMD_EXEC_PID=2021
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting XAUTHORITY=/run/user/1000/gdm/Xauthority
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting WINDOWPATH=2
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting HOME=/home/roberto
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting USERNAME=roberto
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting IM_CONFIG_PHASE=1
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting LANG=pt_BR.UTF-8
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting XDG_CURRENT_DESKTOP=ubuntu:GNOME
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting XDG_SESSION_CLASS=user
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting USER=roberto
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting DISPLAY=:1
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting SHLVL=1
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting XDG_RUNTIME_DIR=/run/user/1000
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting XDG_DATA_DIRS=/usr/share/ubuntu:/usr/share/gnome:/home/roberto/.local/share/flatpak>
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting PATH=/home/roberto/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin>
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting GDMSESSION=ubuntu
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus
nov 23 13:40:19 roberto-IdeaPad-Gaming-3-15IMH05 /usr/libexec/gdm-x-session[2645]: dbus-update-activation-environment: setting _=/usr/bin/dbus-update-activation-environment
nov 23 13:40:20 roberto-IdeaPad-Gaming-3-15IMH05 dbus-daemon[2045]: [session uid=1000 pid=2045] Activating via systemd: service name='org.a11y.Bus' unit='at-spi-dbus-bus.service' requested by ':1.23' (uid=1000 >
nov 23 13:40:20 roberto-IdeaPad-Gaming-3-15IMH05 systemd[2021]: Starting Accessibility services bus...
nov 23 13:40:20 roberto-IdeaPad-Gaming-3-15IMH05 dbus-daemon[2045]: [session uid=1000 pid=2045] Successfully activated service 'org.a11y.Bus'


text:
Q: K-fold cross-validation for testing model accuracy in MATLAB I'm having some trouble truly understanding what's going in MATLAB's built-in functions of cross-validation. My goal is to develop a model for binary classification and test its accuracy by using cross-validation. I'm looking at comparing a few different models, but I'll just use k-nearest neighbor classification for the purposes of this example. I'm providing code for two simplified versions of cross-validation:
% INPUTS:
% data = NxM matrix, where N = observations and M = features
% labels = Nx1 matrix with the true labels of each observation

%% Version 1
model = fitcknn(data,labels,'NumNeighbors',kVal); %kVal is some iteratively-determined value

% Calculate misclassification error
cvmodel = crossval(model,'kfold',10);
cvError = kfoldLoss(cvmodel);

% Generate confusion matrix
predictedLabels = predict(model,data);
R = confusionmat(predictedLabels,labels);

%% Version 2
indices = crossvalind('kfold',labels,10);
confusionMatrix = cell(1,1);
errorMat = zeros(1,10);
for i = 1:10
    test = (indices==i);
    train = ~test;
    knn = fitcknn(data(train,:),labels(train),'NumNeighbors',kVal);
    y = knn.predict(data(test,:));
    index = cellfun(@strcmp,y,labels(test));
    errorMat(i) = sum(index)/length(y);
    confusionMatrix{i} = confusionmat(labels(test),y);
end

% Calculate misclassification error
cvError = 1-mean(errorMat);

% Generate confusion matrix
R = cat(3,confusionMatrix{:});
R = sum(R,3);

Which of these two approaches is the correct implementation? Or are both equivalent? This question can be generalized to other types of classification models in MATLAB, e.g. discriminant analysis. Appreciate any and all input, thanks in advance!

A: If you are asking whether the crossval method's 'kfold' option  is the same as carrying out the k-fold training yourself and combining the results, then it is in principle the same. It is possible that I'm missing something in your code that is a bit different. For instance, I don't know off-hand whether the MATLAB function take the averages of the error rates or weights them by any slight difference in sample sizes across the k folds. But I believe the two approaches are basically the same.


text:
Q: Parallel Foreach loop missing data to bring from nested async method calls I am working on C# Parallel.ForEach loop. Within the parallel loop, I am calling async method ProcessMyData and ProcessMyData calling another async method GetMarkedData where in GetMarkedData method, I am calling the API services to pull record from database via Azure Function API but with parallel loop, I never received data for first thread while this method GetMarkedData been called for remaining record and I never receive data in parallel loop however it do work fine in classic loop.
Parallel.ForEach(myList, options, async item=>
{
    var processDataList = await ProcessMyData(item.Id);
});

protected async Task<List<myRecord>> ProcessMyData(recordId)
{
    //my code...

    var data = await GetMarkedData(recordId);
    // remaining code...
}

public virtual async Task<IEnumerable<Record>> GetMarkedData(recordId id)
{
    using (var myService = HttpClientUtilities...)
    {
        var markedRecordlist = myService.GetData(...)
    }
}


text:
Q: How to fix Class 'Illuminate\Notifications\Notification' not found? Every time I try to run my Test.php file, which is meant to send a notification, I am getting the error message:
Fatal error: Class 'Illuminate\Notifications\Notification' not found in /Users/Macbook/app/app/Http/Controllers/Test.php on line 12.
Here is my Test.php file:
<?php

namespace App\Notifications;

// use app\vendor\laravel\framework\src\Illuminate\Notifications\Notification;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use App\User;

class Test extends Notification
{
    use Queueable;

   /**
   * Create a new notification instance.
   *
   * @return void
   */

public $test;

public function __construct($test)
{
    $this->test = $test;
}

/**
 * Get the notification's delivery channels.
 *
 * @param  mixed  $notifiable
 * @return array
 */
public function via($notifiable)
{
    return ['database'];
}

/**
 * Get the mail representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    /**
    $url = url('/test/'.$this->test->id);

    return (new MailMessage)
                ->greeting('Hello!')
                ->line('The introduction to the notification.')
                ->action('Notification Action', $url)
                ->line('Thank you for using our application!');
    */
}

/**
 * Get the array representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return array
 */
public function toDatabase($notifiable)
{
    return [
        'data' => 'You have a new notification.',
        'from' => $this->message->name,
        'name'=> $this->message->email,
        'subject' => $this->message->subject,
        'body' => $this->message->body
    ];
}
}

I am trying to send notifications using the Database method. Could anyone help me out? It's just odd because I am sure that Illuminate\Notifications\Notification exists.

A:
Notifications may be sent in two ways: using the notify method of the Notifiable trait or using the Notification facade.

https://laravel.com/docs/5.3/notifications#sending-notifications
Option 1
You can use notify() method:
$user->notify(new AgendamentoPendente(1));

Also, make sure User class uses Notifiable trait:
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

Option 2
Using facade with full namespace:
\Notification::send($user, new AgendamentoPendente(1));


text:
Q: Gain iOS root access I don't know is this is possible, but can I change stock iOS files? More specifically, I wan't  to edit the file "SystemVersion.plist" in "/System/Library/CoreServices/" and I use NSDictionary. This is how my code looks like:
NSFileManager *fm = [[NSFileManager alloc] init];
NSArray *array;
fm = [NSFileManager defaultManager];

[fm changeCurrentDirectoryPath:@"/System/Library/CoreServices/"];
array = [fm contentsOfDirectoryAtPath:fm.currentDirectoryPath error:NULL];
NSLog(@"Path:%@ Items:%@", fm.currentDirectoryPath, array);

NSDictionary *systemVersion = [[NSDictionary alloc]  initWithContentsOfFile:@"SystemVersion.plist"];
[systemVersion setValue:@"7.0" forKey:@"ProductVersion"];
[systemVersion writeToFile:@"/System/Library/CoreServices/SystemVersion.plist" atomically:NO]; //This code doesn't overwrite the current file!

I've looked all over the internet, and not found an answer! I hope that I'm left with no choice than jailbreaking
UPDATE:
Is it better that I ask then how I can gain root access from c or objective-c?

A: It cannot be done using public API and I doubt that there is an easy to use private API.
But there certainly are exploitable security issues that allow programs to gain root access. Without those jailbreaking would not be possible at all. So if you really want root access you should study how jailbreaks are done. This is not going to be easy.


text: Q: Send Notifications from code Firebase i am making an application that uses Firebase as the backend and swift in xcode. What i have is i can add products to the database and users can view and see those products. But what i want to do is that whenever i add a new product i want to send notifications to all registered users. How can i achieve that? I have seen tutorials and Firebase's own documentation but all these send notifications via Firebase console. How can i achieve this through swift code? I am using Swift 3.0 and xcode 8.3.2. Please let me know how can i achieve this.


text:
Q: How to exclude a specific string constant? Can regular expression be utilized to match any string except a specific string constant (i.e. "ABC")?
Is it possible to exclude just one specific string constant?

A: In .NET you can use grouping to your advantage like this:
http://regexhero.net/tester/?id=65b32601-2326-4ece-912b-6dcefd883f31
You'll notice that:
(ABC)|(.)

Will grab everything except ABC in the 2nd group.  Parenthesis surround each group.  So (ABC) is group 1 and (.) is group 2.
So you just grab the 2nd group like this in a replace:
$2

Or in .NET look at the Groups collection inside the Regex class for a little more control.
You should be able to do something similar in most other regex implementations as well.
UPDATE: I found a much faster way to do this here:
http://regexhero.net/tester/?id=997ce4a2-878c-41f2-9d28-34e0c5080e03
It still uses grouping (I can't find a way that doesn't use grouping).  But this method is over 10X faster than the first.

A: This isn't easy, unless your regexp engine has special support for it. The easiest way would be to use a negative-match option, for example:
$var !~ /^foo$/
    or die "too much foo";

If not, you have to do something evil:
$var =~ /^(($)|([^f].*)|(f[^o].*)|(fo[^o].*)|(foo.+))$/
    or die "too much foo";

That one basically says "if it starts with non-f, the rest can be anything; if it starts with f, non-o, the rest can be anything; otherwise, if it starts fo, the next character had better not be another o".

A: Try this regular expression:
^(.{0,2}|([^A]..|A[^B].|AB[^C])|.{4,})$

It describes three cases:

*

*less than three arbitrary character

*exactly three characters, while either

*

*the first is not A, or

*the first is A but the second is not B, or

*the first is A, the second B but the third is not C

*more than three arbitrary characters

A: You could use negative lookahead, or something like this:
^([^A]|A([^B]|B([^C]|$)|$)|$).*$

Maybe it could be simplified a bit.

A: You have to use a negative lookahead assertion.
(?!^ABC$)

You could for example use the following.
(?!^ABC$)(^.*$)

If this does not work in your editor, try this. It is tested to work in ruby and javascript:
^((?!ABC).)*$


text:
Q: Combine multiple source sets to make a decision I'm working on a project in which I am using ocr-engine and tensorflow to identify the vehicle number plate and vehicle model respectively. I also have a database which contains Vehicle Information (for eg, owner, number plate, vehicle brand, color, etc).
Simple flow:

*

*Image input

*Number plate recognition using OCR

*Vehicle model (eg Hyundai,Toyota, Honda, etc) using Tensorflow

*Query (2. and 3.) in database to find the owner
Now, the fact is ocr-engine is not 100% accurate, let's consider INDXXXX0007 as the best result of the engine.
When I query this result in database I get
Set 1,

*

*Owner1 - INDXXXX0004 (95% match)

*Owner2 - INDXXXX0009 (95% match)

In such cases, I use tensorflow data to make a decision
Set 2, where vehicle model shows:

*

*Hyundai (95.00%)

*Honda (90.00%)

Here comes my main problem, tensorflow sometimes gives me false-positive values. For eg, the actual vehicle is Honda but the model shows more confidence for Hyundai (ref, Set2).
What should be a possible way to avoid such problems or How can I combine both sets to make a decision?


text:
Q: How do I reverse the order of the digits of an integer using recursion in C programming? Problem statement :

Given a 32-bit signed integer, reverse digits of an integer.

Note: Assume we are dealing with an environment that could only store
integers within the 32-bit signed integer range: [ −2^31,  2^31 − 1]. For
the purpose of this problem, assume that your function returns 0 when
the reversed integer overflows.

I'm trying to implement the recursive function reverseRec(), It's working for smaller values but it's a mess for the edge cases.
int reverseRec(int x)
{
    if(abs(x)<=9)
    {
        return x;
    }
    else
    {
        return reverseRec(x/10) + ((x%10)*(pow(10, (floor(log10(abs(x)))))));
    }
}

I've implemented non recursive function which is working just fine :
int reverse(int x)
{
    long long val = 0;
    do{
        val = val*10 + (x%10);
        x /= 10;
    }while(x);

    return (val < INT_MIN || val > INT_MAX) ? 0 : val;
}

Here I use variable val of long long type to check the result with MAX and MIN of signed int type but the description of the problem specifically mentioned that we need to deal within the range of 32-bit integer, although somehow it got accepted but I'm just curious If there is a way to implement a recursive function using only int datatype ?
One more thing even if I consider using long long I'm failing to implement it in the recursive function reverseRec().

A:
If there is a way to implement a recursive function using only int datatype ?
(and) returns 0 when the reversed integer overflows

Yes.
For such +/- problems, I like to fold the int values to one side and negate as needed. The folding to one side (- or +) simplifies overflow detection as only a single side needs testing
I prefer folding to the negative side as there are more negatives, than positives.  (With 32-bit int, really didn't make any difference for this problem.)
As code forms the reversed value, test if the following r * 10 + least_digit may overflow before doing it.

An int only recursive solution to reverse an int.  Overflow returns 0.
#include <limits.h>
#include <stdio.h>

static int reverse_recurse(int i, int r) {
  if (i) {
    int least_digit = i % 10;
    if (r <= INT_MIN / 10 && (r < INT_MIN / 10 || least_digit < INT_MIN % 10)) {
      return 1; /// Overflow indication
    }
    r = reverse_recurse(i / 10, r * 10 + least_digit);
  }
  return r;
}

// Reverse an int, overflow returns 0
int reverse_int(int i) {
  // Proceed with negative values, they have more range than + side
  int r = reverse_recurse(i > 0 ? -i : i, 0);
  if (r > 0) {
    return 0;
  }
  if (i > 0) {
    if (r < -INT_MAX) {
      return 0;
    }
    r = -r;
  }
  return r;
}

Test
int main(void) {
  int t[] = {0, 1, 42, 1234567890, 1234567892, INT_MAX, INT_MIN};
  for (unsigned i = 0; i < sizeof t / sizeof t[0]; i++) {
    printf("%11d %11d\n", t[i], reverse_int(t[i]));
    if (t[i] != INT_MIN) {
      printf("%11d %11d\n", -t[i], reverse_int(-t[i]));
    }
  }
}

Output
          0           0
          0           0
          1           1
         -1          -1
         42          24
        -42         -24
 1234567890   987654321
-1234567890  -987654321
 1234567892           0
-1234567892           0
 2147483647           0
-2147483647           0
-2147483648           0

A: You could add a second parameter:
int reverseRec(int x, int reversed)
{
    if(x == 0)
    {
        return reversed;
    }
    else
    {
        return reverseRec(x/10, reversed * 10 + x%10);
    }
}

And call the function passing the 0 for the second parameter. If you want negative numbers you can check the sign before and pass the absolute value to this function.

A:
In trying to learn C programming I programed this question and get some correct results and some incorrect.  I don't see the reason for the difference.

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <math.h>  // requires adding link to math -lm as in: gcc b.c -lm -o q11

    int ReverseInt(int startValue, int decimalPlace)
    {
        if(decimalPlace == 0)  // if done returns value
        {
            return startValue;
        }
    int temp = startValue % 10;  // gets units digit
    int newStart = (startValue -temp)/10; // computes new starting value after removing one digit
    int newDecimal = decimalPlace -1;

    int value = temp*pow(10,decimalPlace);
    return value + ReverseInt(newStart,newDecimal);  // calls itself recursively until done
    }

    int main()
    {
        int x, decimalP, startValue;
        printf("Input number to be reversed \n Please note number must be less than 214748364 :");
        scanf("%d", &x);
        if (x > 214748364)
        {
            printf("Input number to be reversed \n Please note number must be less than 214748364 :");
            scanf("%d", &x);
        }
        decimalP = round(log10(x));  // computes the number of powers of 10 -  0 being units etc.
        startValue = ReverseInt(x, decimalP);  // calls function with number to be reversed and powers of 10
        printf("\n reverse of %d is %d \n", x, startValue);
    }

Output is:  reverse of 1234 is 4321 but then  reverse of 4321 is 12340

A: I am assuming by reversing an integer you mean turning 129 to 921 or 120 to 21.
You need an initial method to initialize your recursive function.
Your recursive function must figure out how many decimal places your integer uses. This can be found by using log base 10 with the value and then converting the result to a integer.

*

*log10 (103) approx. 2.04 => 2

Modulus the initial value by 10 to get the ones place and store it in a variable called temp
Subtract the ones place from the initial value and store that in a variable called newStart.

*

*divide this value by 10

Subtract one from the decimal place and store in another variable called newDecimal.
Return the ones place times 10 to the power of the decimal place and add it to the function where the initial value is newStart and the decimalPlace is newDecimal.
#include <stdio.h>
#include <math.h>

int ReverseInt(int startValue, int decimalPlace);

int main()
{
    int i = -54;
    int positive = i < 0? i*-1 : i;
    double d = log10(positive);
    int output = ReverseInt(positive,(int)d);
    int correctedOutput = i < 0? output*-1 : output;
    printf("%d \n",correctedOutput);
    return 0;
}

int ReverseInt(int startValue, int decimalPlace)
{
    if(decimalPlace == 0)
    {
        return startValue;
    }
    int temp = startValue % 10;
    int newStart = (startValue -temp)/10;
    int newDecimal = decimalPlace -1;

    int value = temp*pow(10,decimalPlace);
    return value + ReverseInt(newStart,newDecimal);
}

A: It's late and nothing better does not come into my mind. No float calculations. Of course, integer has to be big enough to accommodate the result. Otherwise it is an UB.
int rev(int x, int partial, int *max)
{
    int result;
    if(x / partial < 10 && (int)(x / partial) > -10)
    {
        *max = partial;
        return abs(x % 10) * partial;
    }
    result = rev(x, partial * 10, max) + abs(((x / (int)(*max / partial)) % 10) * partial);
    return result;
}

int reverse(int x)
{
    int max;
    return rev(x, 1, &max) * ((x < 0) ? -1 : 1);
}

int main(void){

  printf("%d", reverse(-456789));
}

https://godbolt.org/z/M1eezf
unsigned rev(unsigned x, unsigned partial, unsigned *max)
{
    unsigned result;
    if(x / partial < 10)
    {
        *max = partial;
        return (x % 10) * partial;
    }
    result = rev(x, partial * 10, max) + (x / (*max / partial) % 10) * partial;
    return result;
}

unsigned reverse(unsigned x)
{
    unsigned max;
    return rev(x, 1, &max);
}

int main(void){

  printf("%u", reverse(123456));
}

when using long long to store the result all possible integers can be reversed
long long rev(int x, long long partial, long long *max)
{
    long long result;
    if(x / partial < 10 && (int)(x / partial) > -10)
    {
        *max = partial;
        return abs(x % 10) * partial;
    }
    result = rev(x, partial * 10, max) + abs(((x / (int)(*max / partial)) % 10) * partial);
    return result;
}

long long reverse(int x)
{
    long long max;
    return rev(x, 1, &max) * ((x < 0) ? -1 : 1);
}

int main(void){

  printf("%d reversed %lld\n", INT_MIN, reverse(INT_MIN));
  printf("%d reversed %lld\n", INT_MAX, reverse(INT_MAX));
}

https://godbolt.org/z/KMfbxz


text:
Q: Strings and dates conditions data = [{'A':"re", "B": 120630, "C": 120630, "D": "Sunday"}, {'A':"aeg", "B": 121228, "C": 130104, "D": "Monday"}, {'A':"aab", "B": 120601, "C": 120608, "D": "Sunday"}, {'A':"bbe", "B": 120925, "C": 120630, "D": "Monday"}, {'A':"feh", "B": 120726, "C": 120803, "D": "Monday"}, {'A':"dd", "B": 120622, "C": 120630, "D": "Monday"}]
df = pd.DataFrame(data)
df["B"] = pd.to_datetime (df["B"], format="%y%m%d")
df["C"] = pd.to_datetime (df["C"], format="%y%m%d")

I want to select the rows with both conditions:

*

*Column D is "Monday".

*Column B date is 7 or 8 days before Column C date.

I mean, I want to get these rows:
aeg 2012-12-28 2013-01-04  Monday

feh 2012-07-26 2012-08-03  Monday

dd  2012-06-22 2012-06-30  Monday

I´ve tried:
df[(df["D"] == "Monday") & (df["B"] < df["C"])]

But this code doesn´t satisfy the second condition (Column B date is 7 or 8 days before Column C date).
Any other idea?
Thank you.

A: This is one way.
df.loc[(df["D"] == "Monday") & (df["B"] - df["C"]).dt.days.isin({-7, -8})]

#      A          B          C       D
# 1  aeg 2012-12-28 2013-01-04  Monday
# 4  feh 2012-07-26 2012-08-03  Monday
# 5   dd 2012-06-22 2012-06-30  Monday


text:
Q: homomorphism from ZxZ to Q I have this problem. I like to find ring homomorphism from $(\mathbb Q,+,-)$ to ($\mathbb Z\times \mathbb Z,+,-)$ and
homomorphism from $(\mathbb Z\times \mathbb Z,+,-)$ to $(\mathbb Q,+,-)$.
My solution:
Let f is homomorphism. Suppose that $f(1)=(a,b)$, with $a,b∈\mathbb Z$. Since $f$ is a ring homomorphism it follows that in particular, $f(q)=f(q⋅1)=q⋅f(1)=q(a,b)$, with $q∈\mathbb Q$.
That is all I did, becauseI do not know the next step.
Many thanks.

A: Apart from $x \mapsto (0, 0)$ (if you allow that as a ring homomorphism), no such ring homomorphism can exist from $\Bbb{Q}$ to $\Bbb{Z}\times\Bbb{Z}$, because if $f$ were a ring homomorphism from $\Bbb{Q}$ to $\Bbb{Z}\times\Bbb{Z}$, then $f(1/2)$ would be an element, $x$ say, of $\Bbb{Z}\times\Bbb{Z}$ such that $2x = (1, 1)$, which is impossible.
As for the oppositve direction, $(x, y) \mapsto x$ and $(x, y) \mapsto y$ both define ring homomorphisms from $\Bbb{Z}\times\Bbb{Z}$ to $\Bbb{Z}\subseteq\Bbb{Q}$.

A: Not only is there no ring homomorphism, but there is no nontrivial group homomorphism $\Bbb Q\to\Bbb Z\times\Bbb Z$, and there are only two nontrivial ring homomorphisms from $\Bbb Z\times\Bbb Z$ to $\Bbb Q$.
The group $(\Bbb Q,+)$ is divisible, that is, for every $g\in\Bbb Q$ and every nonzero $n\in\Bbb Z$, there is $g'\in\Bbb Q$ such that $ng'=g$. However, you can easily see that the image (under a homomorphism) of a divisible group must be divisible. The only divisible subgroup of $\Bbb Z\times\Bbb Z$ is the trivial subgroup.
An idempotent $e$ in a ring $R$ is an element such that $e^2=e$; a homomorphism must take idempotents to idempotents. The ring $\Bbb Z\times\Bbb Z$ has four such elements, namely $(0,0)$, $(1,0)$, $0,1)$, and $(1,1)$. The answer of Rob Arthan correctly identifies the homomorphisms that take $(1,0)$ and $0,1)$ to $1\in\Bbb Q$; any homomorphism taking $(1,1)$ to $1\in\Bbb Q$ must be one of these, since if both go to $1$, then $(1,1)\mapsto2\in\Bbb Q$, not an idempotent. So there are only two nontrivial ring homomorphisms from $\Bbb Z\times\Bbb Z$ to $\Bbb Q$.

A: $Q(p/q) \to  Z(p,q)$
$p/q+r/s = (ps + qr)/qs$
The addition operation in $\mathbb Z\times \mathbb Z$
has to be defined as: $(p,q) + (r,s) = (ps+qr,qs)$


text:
Q: How do I disable the sign up link for the aws amplify vue authenticator? I'm using the amplify-authenticator component from the aws-amplify-vue library to enable authentication for my app. I'm trying to figure out how to disable the "Create Account" link on the front end and I can't seem to find anything in the documentation or online.  I've seen a few places where users disabled it by hiding it with css and a few places where users were able to disable it with the react library, but I haven't found anything specific for the vue library. It's possible I'm just missing the documentation, but does anyone know how to remove the sign up functionality from the vue amplify authenticator?
Component

<template>
  <v-container>
    <amplify-authenticator></amplify-authenticator>
  </v-container>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { Auth } from "aws-amplify";
import logger from "../logging";
import { components } from "aws-amplify-vue";
import { AmplifyEventBus } from "aws-amplify-vue";

@Component({
  components: {
    ...components
  }
})
export default class Login extends Vue {
  async created() {
    try {
      // This function throws an error if no user is logged in
      await Auth.currentAuthenticatedUser({ bypassCache: true });
      this.$router.push("/instruments");
    } catch (e) {
      logger.silly("No user currently logged in");

      AmplifyEventBus.$on("authState", async info => {
        logger.silly("signedIn");
        logger.silly(info);
        if (info === "signedIn") {
          const user = await Auth.currentAuthenticatedUser({
            bypassCache: true
          });
          this.$router.push("/instruments");
        } else {
          logger.error(`Failed to login`);
          alert("Failed to login");
        }
      });
    }
  }
}
</script>

<style scoped></style>

Update 1
Based on @asimpledevice's answer I tried the below without success:
<template>
  <v-container class="d-flex justify-center align-center">
    <amplify-authenticator
      :authConfig="authConfiguration"
    ></amplify-authenticator>
  </v-container>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { Auth } from "aws-amplify";
import StoreTypes from "../store-types";
import logger from "../logging";
import { components } from "aws-amplify-vue";
import { AmplifyEventBus } from "aws-amplify-vue";

@Component({
  components: {
    ...components
  }
})
export default class Login extends Vue {
  async mounted() {
    try {
      // This function throws an error if no user is logged in
      await Auth.currentAuthenticatedUser({ bypassCache: true });
      this.$router.push("/instruments");
    } catch (e) {
      const self = this;
      AmplifyEventBus.$on("authState", async info => {
        if (info === "signedIn") {
          this.$store.dispatch(StoreTypes.types.LOAD_CURRENT_USER);
          const nextLocation =
            self.$route.query.redirect !== null &&
            self.$route.query.redirect !== undefined
              ? (self.$route.query.redirect as string)
              : "/instruments";
          this.$router.push(nextLocation).catch(err => {});
        }
      });
    }
  }

  authConfiguration() {
    return {
      signInConfig: {
        isSignUpDisplayed: false
      }
    };
  }
}
</script>

A: You can hide the "sign up" section via the "signInConfig" object.
  configurationOptions: any = {
    signInConfig: {
      isSignUpDisplayed: false
    }
  };

You can then pass this object in as a prop to the  component:
    <amplify-authenticator
      :authConfig="configurationOptions"
    ></amplify-authenticator>

NOTE: You must make the config object a local property.  The config will not work if it is a function or computed property. Your full solution would be the following:
<template>
  <v-container class="d-flex justify-center align-center">
    <amplify-authenticator
      :authConfig="configurationOptions"
    ></amplify-authenticator>
  </v-container>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { Auth } from "aws-amplify";
import StoreTypes from "../store-types";
import logger from "../logging";
import { components } from "aws-amplify-vue";
import { AmplifyEventBus } from "aws-amplify-vue";

@Component({
  components: {
    ...components
  }
})
export default class Login extends Vue {
  configurationOptions: any = {
    signInConfig: {
      isSignUpDisplayed: false
    }
  };

  async mounted() {
    try {
      // This function throws an error if no user is logged in
      await Auth.currentAuthenticatedUser({ bypassCache: true });
      this.$router.push("/instruments");
    } catch (e) {
      const self = this;
      AmplifyEventBus.$on("authState", async info => {
        if (info === "signedIn") {
          this.$store.dispatch(StoreTypes.types.LOAD_CURRENT_USER);
          const nextLocation =
            self.$route.query.redirect !== null &&
            self.$route.query.redirect !== undefined
              ? (self.$route.query.redirect as string)
              : "/instruments";
          this.$router.push(nextLocation).catch(err => {});
        }
      });
    }
  }
}
</script>

<style></style>

A: With @aws-amplify/auth ^3.2.6 and @aws-amplify/ui-vue ^0.2.20 this works as documented in Sign In docs
<template>
  <div>
    <amplify-authenticator username-alias="email">
      <amplify-sign-in slot="sign-in" :hide-sign-up="true"
        username-alias="email">
      </amplify-sign-in>
    </amplify-authenticator>
  </div>
</template>

A: I got this to work with a simplified inline expression:
<amplify-authenticator :authConfig="{ signInConfig: { isSignUpDisplayed: false } }" />

A: I tried this, in Angular 8 it works.
<amplify-authenticator>
  <amplify-sign-in slot="sign-in" hide-sign-up="true"></amplify-sign-in>
</amplify-authenticator>

A: If you're using withAuthenticator:
const withAuthenticatorOptions = {
  hideSignUp: true
}

export default withAuthenticator(MyApp, withAuthenticatorOptions);

AWS doc


text:
Q: How do I use userChrome.css to remove the magnifying glass from modern versions of Firefox/Iceweasel? A quick google search will find a lot of sites saying to add this to userChrome.css:
#go-button-stack, .search-go-button-stack {
  display: none !important;
}

to remove the magnifying glass from the search bar, but on Iceweasel 17 and Firefox 25 on Linux, that doesn't have an effect. All of the sites I can find mention it as a solution for Firefox 2 and 3, but is there a way to remove this icon in recent versions?

A: This works for Firefox 25:
.search-go-button {
display: none !important;
}


text:
Q: How to have console messages in English? I am French and use my Debian system in French.
However, I would like to have error messages in terminal in English. It allows me to post them on English speaking websites.
How can I change my locale to do so? I precise I don't want to have all my system in English.

A: You can call an application with the following syntax:
For example you want the English manpages (for just a single command):
user@host:~# LC_ALL=C man ls

Or you run into an error (my system is in German):
user@host:~$ ls -la /root/
ls: Öffnen von Verzeichnis /root/ nicht möglich: Keine Berechtigung

user@host:~$ LC_ALL=C ls -l /root/
ls: cannot open directory /root/: Permission denied

A: You have to change LANG and LANGUAGE variable in current shell.
Put
export LANG=en_US.UTF-8
export LANGUAGE=en

in your shell rc file ( for bash it is ~/.bashrc ) and restart the terminal session ( or just source the rc file one more time with source ~/.bashrc or even just restart bash with exec bash )
Note, that you have to generate this locale before.
Also you can use export LANG=C.
Also there are other LANG variables (from man bash):
   LANG   Used to determine the  locale  category  for  any  category  not
          specifically selected with a variable starting with LC_.
   LANGUAGE
          Used   to   set   messages   languages  (as  LC_MESSAGES)  to  a
          multi-valued value, e.g., setting it to fr:de:en will use French
          messages  where they exist; if not, it will use German messages,
          and  will  fall  back  to  English  if neither German nor French
          messages are available.
   LC_ALL This  variable  overrides  the  value  of LANG and any other LC_
          variable specifying a locale category.
   LC_COLLATE
          This variable determines the collation order used  when  sorting
          the  results  of pathname expansion, and determines the behavior
          of  range  expressions,  equivalence  classes,   and   collating
          sequences within pathname expansion and pattern matching.
   LC_CTYPE
          This  variable  determines  the interpretation of characters and
          the behavior of character classes within pathname expansion  and
          pattern matching.
   LC_MESSAGES
          This  variable  determines  the locale used to translate double-
          quoted strings preceded by a $.
   LC_NUMERIC
          This variable determines the locale  category  used  for  number
          formatting.

A: If you just want the error messages and not the whole locale, you can use:
export LC_MESSAGES=C

A: Try referencing this:
1)  https://wiki.debian.org/ChangeLanguage
In short, you want to set your LOCALE (via LANG), preferrably in your .bashrc.
export LANG=en_US.UTF-8


text:
Q: Creating and Using Classes If I create an instance of the class below and call the spawn function from my controller, the sprite will appear but I won't be able to change any of its properties.
class Hero: SKSpriteNode
{
    var hero = SKSpriteNode(imageNamed: "hero3")

    func spawn(parentNode: SKNode, position: CGPoint, size: CGSize = CGSize(width: 50, height: 50))
    {
        hero.size = size
        hero.position = position
        hero.physicsBody = SKPhysicsBody(circleOfRadius: 25)
        hero.physicsBody?.allowsRotation = false
        hero.zPosition = 10
        parentNode.addChild(hero)
    }
}

If I get rid of the hero property and change everything to self, it works fine.
class Hero: SKSpriteNode
{
    func spawn(parentNode: SKNode, position: CGPoint, size:CGSize = CGSize(width: 50, height: 50))
    {
        self.size = size
        self.position = position
        self.texture = SKTexture(imageNamed: "hero3")
        self.physicsBody = SKPhysicsBody(circleOfRadius: 25)
        self.physicsBody?.allowsRotation = false
        self.zPosition = 10
        parentNode.addChild(self)
    }
}

I'm sure this is swift 101, but can someone please explain why the first version doesn't work as expected?

A: In your first example, you created a var (basically a SpriteNode inside the SpriteNode).
When you instantiate the class like let hero = Hero(....) you now have a SpriteNode called hero, with a property called hero.  You can change either.  Calling hero.size would change the base hero, and hero.hero.size would change the inside SpriteNode....this is probably not the behavior you were looking for.
The second class looks correct, if you are just trying to create a SpriteNode and modify it.  The class is a subclass of SpritNode, so it's already a SpriteNode - no need to create one inside it like the first one.
Hope this helps!

A: Your Hero class inherits from SKSpriteNode, so it is essentially an SKSpriteNode already, which means you don't need to create a hero SKSpriteNode variable.
In your first class, when you use hero.size = size, you're accessing the properties of the variable within your class instead of on the class itself. Then you add the hero SKSpriteNode as a child along with all its properties, but your class SKSpriteNode, which holds the variable doesn't have set properties size or a physics body. You can think of the class as a container that's holding the variable SKSpriteNode.
In your second function, when you use self.size = size, you're accessing the class's properties and giving the class SKSpriteNode all the properties you need to use it in other classes.


text:
Q: How to use the match Function with two criteria in VBA I am trying to use the "MATCH" function  in order to get the Row (named RICRow) number of a name which is contained in the "RIC" column (A). Because there are always two names in the RIC column (e.g."Tom") it is necessary to take the column(L) "RIC_FID" into consideration which contains a unique value corresponding to the names (e.g. 295). The VBA code below keeps yielding the error msg: type mismatch
RICRow = Application.WorksheetFunction.Match(RIC & RIC_FID, protokoll.Range("A1:A500") & protokoll.Range("L1:L500"), 0)

A: this one solved the issue:
RICRow = protokoll.Evaluate("match(""" & RIC & "" & RIC_FID & """, A:A&L:L, 0)")


text:
Q: low priority linux filesystem Does anybody know of a some sort of (virtual) filesystem that will run as a low priority i.e. All other regular disk activity will take priority?
The reason for this is an application I am developing has a large amount of background disk IO to perform.  The IO is not time critical but it currently writes at the maximum possible speed causing high iowait times and slowing down the entire system.
I've thought of spawning a new process and using ionice to set a priority but this seems a bit messy and I'd rather my application was not aware of hardware limitations.
Has anybody come across a fs that will do this or has another suggestion to solve the problem?
Any input much appreciated

A: If possible, you can write application run as low priority or set their limit to utilize the CPU utilization under /etc/security/limits.conf


text:
Q: Using expressions in the SELECT list to thin down a CASE statement I have a query I'm working through rewriting - it has a huge bunch of case statements in the select list that all basically look like this:
select
    Column1 =
        case when (Something = 2) and (SomethingElse is null) and (AnotherThing in (1, 2))
        then 1
        else 0
        end,
    Column2 =
        case when (Something = 3) and (SomethingElse is not null) and (AnotherThing in (2, 3))
        then 1
        else 0
        end,
    ...

With particular note to the "when <expressions> then 1 else 0" logic common across all of them.
It seems really bloated and wordy, a heavy-handed use of the case statement - my programming brain is telling me this could be achieved much more succinctly with some basic binary &ing logic, removing the case entirely:
select
    Column1 = (Something = 2) & (SomethingElse is null) & (AnotherThing in (1, 2)),
    Column2 = (Something = 3) & (SomethingElse is not null) & (AnotherThing in (2, 3)),
    ...

Unfortunately whilst SQL Server is able to handle something like select 1 & 0 (returns 0), it seems to choke on parsing expressions in the select list (Incorrect syntax near '=') - is it possible to do something like this? Some kind of evaluation function, maybe?

A: T-SQL doesn't support Booleans like that. But you could use CROSS APPLY with a subquery that uses CASE to produce a bunch of 1s and 0s, and then combine them in the SELECT clause using the bitwise operators & and |.

A: Unfortunately you are not going to really get around SQL's verbosity here.
You could write a function (of family of functions) to reduce the amount of text in the query, so you have something like:
select
    Column1 = dbo.YeyOrNay(Something, 2, SomethingElse, 1, AnotherThing, 1, 2),
    Column2 = dbo.YeyOrNay(Something, 3, SomethingElse, 0, AnotherThing, 2, 3),
    ...

or
select
    Column1 = dbo.Col1Func(Something, SomethingElse, AnotherThing),
    Column2 = dbo.col2Func(Something, SomethingElse, AnotherThing),
...

but while that makes the SELECT neater you might be reducing the clarity (and efficiency, though if you write the functions carefully the query planner will unroll them to reduce this effect) of the code more generally.

A: If you're trying to make your lines shorter then you could use IIF( ..., 1, 0 ) instead of CASE ... THEN 1 ELSE 0 END.
SELECT
    Column1 = IIF(@Something = 2 AND @SomethingElse IS     NULL AND @AnotherThing IN (1,2), 1, 0)
    Column2 = IIF(@Something = 3 AND @SomethingElse IS NOT NULL AND @AnotherThing IN (2,3), 1, 0)
;

Note:  Only available from SQL Server 2012 onwards.


text:
Q: A question about unital Algebra over a Field Let $F$ be a field and $(K,\bullet)$ be a unital $F$-algebra. For each $v \in K$ let $S(v)$ be the set of all $a \in F$ satisfying the condition that $v -a.1_K $ does not have an inverse with respect to the operation $\bullet$. If $v \in K$ has a multiplicative inverse $v^{-1}$ with respect to this operation, show that either $S(v) = \emptyset = S(v^{-1})$ or $S(v) \neq \emptyset$ and $S(v^{-1}) = \{ a^{-1} \text{ where }a \in S(v)  \}$.
If $K$ is associative then the problem becomes easy, and in that case $v^{-1}$ is uniquely defined. However I am stuck on the case $K$ isn't associative.
The problem is from Golan's book on Linear Algebra (Third Ed, Exercise 131), and an inverse of $v \in K$ is defined as an element $u \in K$ satisfying $u \bullet v = v \bullet u = 1_K$.


text:
Q: JQuery UI loading another MVC view in modal breaks css I an using this upload code from GitHub in my project:https://github.com/blackcity/Backload
I want to open this upload view in a modal dialog box from another view. This works fine except the css from the upload page breaks the styles on the main view even after the modal is closed.
    $(document).ready(function() {

    $('#upload').click(function () {
        $('#dialog').dialog('open');
        return false;
    });

    $('#dialog').dialog({
        autoOpen: false,
        resizeable: false,
        modal: true,
        position: 'center',
        width: 700,
        open: function () {
            $(this).load('/upload/');
        }
    });
});

View

dialog here

Upload picture

I haven't worked with a modal dialog before so maybe there an conventional way to prevent the styles from remaining on the main view. Maybe something can be added to the close function?

A: This file upload project I downloaded from the link above is using bootstrap styles which were breaking the styles on my view when the upload view dialog opened. I eventually removed some styles from the bootstrap.debug.css which were overwriting my styles.


text:
Q: Are there any preconditions for using SessionAsSigner on Xpage? Are there any preconditions for using SessionAsSigner on Xpage? My case is quite simple. On beforePageLoad event I call my java code where I require sessionAsSigner. I'm trying to use
ExtLibUtil.getCurrentSessionAsSigner() but it returns null . I tried to resolve the sessionAsSigner variable with other techniques with same same result. Its always null. I have missed something here probably ...

A: As 'Per Henrik Lausten' pointed in above comment, the SessionAsSigner returns proper object only and only when all design elements are signed by the same ID. I can't however imagine how this feature can be used in real life because I cant assure that all design elements are signed by the same id for next several years ...
Any database action like those mentioned below will simply break my app (or at least the sessionAsSigner relied feature):
a) administrator opens the app in designer with automatic build enabled(default in DDE, I cant really be sure that all admins disabled this feature manualy) which causes recompilation of app and potential signature update on some xpages
... or ...
b) my collegue will simply update any application part with no knowledge that all signatures must be the same to not break anything.
Any such action will cause my application stop working :-( which is rather stupid.
... or do I miss something here??


text:
Q: Charts or Graphs in Rails I have a Rails 3.2.14 app that I'd like to add graphs to on our app's dashboard.
I've looked at HighCharts, and it seems like a really good option though there's a license fee associated with this so I'm looking for other options to easily graph data.  I've also watched the Railscast Morris.JS tutorial and it might be a good fit since it's free.
I have a model (Call) where I'd like to graph the calls by hour for the last 24 hours. I'd also like to do other charts for calls by day for the last week, calls by day for the last month. Using either HighCharts (if we decide to pay for it) or Morris.js, what's the best way to do this?
I also am looking at Chartkick as a simple way to embed graphs into my app but haven't had much experience with this.

A: This is a good place to start:
<%= column_chart Call.group_by_hour_of_day(:created_at, format: "%l %P").count %>

You need to install the groupdate gem first to get this to work.
There's good info at chartkick.com


text:
Q: Cannot configure PHP built-in server in PhpStorm I am following JetBrains' official instructions on setting up the built-in server HERE
I am currently on the "Enabling a built-in Web server" section:

*

*Download PHP 5.4.0 or higher.

Done! There is now a folder on my desktop named "php-7.1.4", untouched since download, now for number 2: "Configure the downloaded PHP interpreter in PhpStorm" (HERE)
I am stuck on 4.2, when I select the directory of the folder on my desktop, nothing happens. It does not "display the version of the PHP engine detected in the specified folder", as per the instructions. It simply continues to say PHP is not installed.
What do I do?

A: After abandoning the built-in server in favour of MAMP, I have found the solution. The download from php.net seems to be all kinds of messed up.
My solution is to download MAMP and use the php executable it provides (MAMP/bin/php/php[version]/bin/php), but then just continue without using the MAMP server.
Works fine!


text:
Q: Understanding resignFirstResponder with UITextField I'm trying to get rid of the keyboard when the user touch outside my UITextField, by using this method:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [mainTextController resignFirstResponder];
    [super touchesBegan:touches withEvent:event];
}

However, this seems to call a method that is called after pressing the return button on the keyboard, but I just want the keyboard to vanish, not to press return for me.
How can I accomplish that?
Thanks!
EDIT: tGilani's answer is the most straight-forward way, works like a charm, without changing to UIControl. But I guess jonkroll's answer also works.

A: Here's how I've handled this before.  First create a method on your view controller that will dismiss the keyboard by resigning first responder status on your text field:
- (IBAction)dismissKeyboard:(id)sender
{
    [mainTextController resignFirstResponder];
}

Next, in your storyboard scene for your ViewController (or nib, if you are not using storyboards) change the class of your ViewController's view property from UIView to UIControl.  The view property is effectively the background behind your other UI elements.  The class type needs to be changed because UIView cannot respond to touch events, but UIControl (which is a direct subclass of UIView) can respond to them.
Finally, in your ViewController's viewDidLoad: method, tell your view controller to execute your dismissKeyboard method when the view receives a UIControlEventTouchDown event.
- (void)viewDidLoad
{
    [super viewDidLoad];
    UIControl *viewControl = (UIControl*)self.view;
    [viewControl addTarget:self action:@selector(dismissKeyboard:) forControlEvents:UIControlEventTouchDown];
}

EDIT:
Part of your concern seems to be that textFieldDidEndEditing: is called when the keyboard is dismissed.  That is unavoidable, it will always be called whenever a text field loses focus (i.e. first responder status).  It sounds like your problem is that you have put code to perform when the user clicks the return button in textFieldDidEndEditing:.  If you do not want that code to run when the user touches outside of the text field, that is not the proper place to put it.
Instead, I would put that code in a separate method:
- (IBAction)textFieldReturn:(id)sender
{
    if ([mainTextController isFirstResponder]) {
            [mainTextController resignFirstResponder];

            // put code to run after return key pressed here...
        }
    }
}

and then call that method via Target-Action when your text field sends the control event UIControlEventEditingDidEndOnExit.
[mainTextController addTarget:self action:@selector(textFieldReturn:) forControlEvents:UIControlEventEditingDidEndOnExit];

Note that UIControlEventEditingDidEndOnExit is different than UIControlEventEditingDidEnd.  The former is called when editing ends by the user touching outside the control, the latter is called when editing ends by the user pressing the return key.

A: try
[self.view endEditing:YES];

Update:
Take a boolean value and set it to false in init method. In your textFieldShouldReturn delegate method method, execute the code if it is false, skip otherwise
- (BOOL) textFieldShouldReturn:(UITextField*)textField
{
    if (!boolean)
    {
        // YOur code logic here
    }
    boolean = false;
}

in your method where you call the endEditing method, set boolean to true.
boolean = YES;
[self.view endEditing:YES];

A: You need to change your ViewController's view property from UIView to UIControl using the Identity Inspector:
From there, you simply create an IBAction and tell the textfield to dismiss (which I am assuming is your mainTextController). If mainTextController is not the textfield you want the keyboard to dismiss on then change the resignFirstReaponder method to your textfield like so.
- (IBAction)backgroundTap:(id)sender {
[myTextField resignFirstResponder];
}

then from there go back into your View Contoller's .xib file and connect the action to the Control View and select "Touch Down".


text:
Q: Filtro para exibir resultado em relatorio em Excel com banco MySQL e PHP Não estou conseguindo criar um filtro por meio dessa query que filtra uma pesquisa no banco MySQL com PHP. Comecei a editar ele, mas o problema é que não consigo gerar esse método utilizando uma variável que está presente na tela. Por exemplo, fiz da seguinte forma:
$result = $obj->getAll('usuarios_id IN (SELECT usuarios_id FROM usuarios WHERE empresas_id = 12');

Nesse caso ele funciona, e exibe os resultados da empresa_id = 12. Estou tentando modificar para passar um parâmetro ao invés de valor fixo (12). Tentei assim:
$result = $obj->getAll('usuarios_id IN (SELECT usuarios_id FROM usuarios WHERE empresas_id = ".$empresa."');

Não me retorna nenhum resultado. Estou tendo dificuldades de passar esse parâmetro de $empresa. O método ficou assim:
public function excelRelatorio() { $arrayRow = array('Nome','Forma Pagamento','Status', 'KM','Valor', 'Valor Extra', 'Data'); $this->geraExcelRelatorio($arrayRow); }

private function geraExcel($arrayRow,$empresa)
{

    $this->load->helper('xls');

    $arr[] = $arrayRow;

    $obj = new Viagem();
    $result = $obj->getAll('usuarios_id IN (SELECT usuarios_id FROM usuarios WHERE empresas_id = ".$empresa."');

    if (isset($result) && count($result) > 0) {

        foreach ($result['rows'] as $v) {

            $arr[] = array(

                utf8_decode($v->getUsuario()->getNome()), $v->getFormaPagamento()->getNome(), $v->getStatus()->getNome(), $v->getDistancia(), $v->getValor(), $v->getValorExtra(), dataHoraBr($v->getDataCriado()), $v->getEntregador()->getNome()

            );

        }

    }

    array_to_xls($arr, 'financeiro'.date("m-d-y").'.xls');
}


text:
Q: Any possible way to set LINK ALIAS for regular Link Tracking (i.e., not Web Analytics Connector) I've done my digging here, but can't get a solution.  I'd like to set a LINK ALIAS via AMPscript, but I always see my AMPscript in Link Tracking (image attached).
I tried CONCAT with no luck.
I tried TreatAsContent with no luck
All of the information here speaks to the Web Analytics Connector, but that's not what I'm after.  I just need the LINK NAME to appear in regular Email Tracking under Link View in Regular reports.
I've attached an image, but I know you smart people know what I'm talking about.
Any hacks to suggest?


text:
Q: Replace values in numpy array equal to list of values I have a numpy array - image with various values:
example
image = [1 ,2 ,2, 3, 4, 4, 4, 4,
5, 6, 6 ,7 ,8 ,8 ,8 ,8]
I want to replace only those numbers occurring less than twice - by a specific number, let's say 0.
I managed to create the list of those numbers like this:
(unique, counts) = np.unique(image, return_counts=True)
frequencies = np.asarray((unique, counts)).T
freq = frequencies[frequencies[:,1] < 2,0]
print(freq)
array([1, 3, 5, 7], dtype=int64)

How do I replace those numbers by zero?
the outcome should look like :
[0 ,2 ,2, 0, 4, 4, 4, 4,
0, 6, 6 ,0 ,8 ,8 ,8 ,8]
Thanks in advance!

A: If both image and freq are numpy arrays:
freq = np.array([1, 3, 5, 7])
image = np.array([1 ,2 ,2, 3, 4, 4, 4, 4, 5, 6, 6 ,7 ,8 ,8 ,8 ,8])

Solution 1
You can then find the indices of image entries appearing in freq, then set them to zero:
image[np.argwhere(np.isin(image, freq)).ravel()] = 0

Based on: Get indices of items in numpy array, where values is in list.

Solution 2
Use np.in1d:
image = np.where(np.in1d(image,freq),0,image)

More info: Numpy - check if elements of a array belong to another array

Solution 3
You can also use a list comprehension:
image = [each if each not in freq else 0 for each in image]

Can find more info here: if/else in a list comprehension.

The last one will result in a list, not a numpy array, but other than that, all of these yield the same result.

A: You could compare each item to the rest of the array to form a 2D matrix and sum each count.  Then assign the items meeting the frequency condition with the desired value:
import numpy as np

img = np.array([1 ,2 ,2, 3, 4, 4, 4, 4, 5, 6, 6 ,7 ,8 ,8 ,8 ,8])

img[np.sum(img==img[:,None],axis=1)<2] = 0

array([0, 2, 2, 0, 4, 4, 4, 4, 0, 6, 6, 0, 8, 8, 8, 8])

Probably not very efficient but it should work.


text:
Q: Google plus login, Android singing in prompt is repeatedly occure while login I am new to android development. I am integrating google plus login into my App, I am little bit confusing that the Singing in prompt of google is occurring repeatedly. I can't understand why, is anything wrong with me?
I am following Google Developer Site to make this thing. I tested the app using multiple google account but 2 of them are works fine but rest of the account did not.

A: Have you tried:

How do I debug my Google+ integration?

By enabling logging, you can diagnose network issues when working with the Google APIs.
To enable logging, run the following command:
adb shell setprop log.tag.GooglePlusPlatform VERBOSE

To disable logging, run the following command:
adb shell setprop log.tag.GooglePlusPlatform ""

Permission which you have to add:

To access Google+ APIs:

<uses-permission android:name="android.permission.INTERNET" />

To retrieve the account name (email) as part of sign-in:

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

To retrieve OAuth 2.0 tokens or invalidate tokens to disconnect a user. This disconnect option is required to comply with the Google+ Sign-In developer policies:
<uses-permission android:name="android.permission.USE_CREDENTIALS" />

See, if that helps.

A: protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

onCreate(Bundle bundle){
mGoogleApiClient = new GoogleApiClient.Builder(YourActivity.this)
                .addConnectionCallbacks(YourActivity.this)
                .addOnConnectionFailedListener(YourActivity.this).addApi(Plus.API)
                .addScope(Plus.SCOPE_PLUS_LOGIN).build();
}

btn_gpluslogin.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        signInWithGplus();
                    }
                });

private void signInWithGplus() {
        if (!mGoogleApiClient.isConnecting()) {
            mSignInClicked = true;
            resolveSignInError();
        }
    }

private void resolveSignInError() {
        if (mConnectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
            } catch (IntentSender.SendIntentException e) {
                mIntentInProgress = false;
                mGoogleApiClient.connect();
            }
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        if (!result.hasResolution()) {
            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
                    0).show();
            return;
        }

        if (!mIntentInProgress) {
            // Store the ConnectionResult for later usage
            mConnectionResult = result;

            if (mSignInClicked) {
                // The user has already clicked 'sign-in' so we attempt to
                // resolve all
                // errors until the user is signed in, or they cancel.
                resolveSignInError();
            }
        }

    }

@Override
    public void onConnected(Bundle arg0) {
        mSignInClicked = false;
        Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();

        // Get user's information
        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
        boolean isSignedUp = pref.getBoolean("isSignedUp", false);
        if (!isSignedUp)
            getGProfileInformation();

        // Update the UI after signin
    }

private void updateUI(boolean isSignedIn) {
        if (isSignedIn) {
            getGProfileInformation();
        } else {
            btn_gpluslogin.setVisibility(View.VISIBLE);
        }
    }

    /**
     * Fetching user's information name, email, profile pic
     */
    private void getGProfileInformation() {
        try {
            if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
                Person currentPerson = Plus.PeopleApi
                        .getCurrentPerson(mGoogleApiClient);
                Log.d("Google Info", currentPerson.toString());
                String personName = currentPerson.getDisplayName();
                String email = Plus.AccountApi.getAccountName(mGoogleApiClient);

            } else {
                Toast.makeText(getApplicationContext(),
                        "Person information is null", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

A: Since you did not provided any code, let me guess. If you say you have problems with certain accounts and others not, it seems to me these problematic accounts have not authorized your app. Please check (while logged in a browser) this configuration:
https://security.google.com/settings/security/permissions?pli=1
Or this?
https://plus.google.com/u/0/apps
And look for your app in the list. Maybe your permissions were denied or something. Perhaps you just need to grant them again, reset and try again.

A: Here is what I bet is happening.
In onConnectionFailed you are starting the resolution from the connectionResult.  This then launches the Activity to resolve the failure and should return the result to onActivityResult.  However you need to make sure not to get into a resolution loop.
So in onConnectionFailed, do this:
private boolean mIsResolving = false;
// ...
public void onConnectionFailed(ConnectionResult connectionResult) {
  if (connectionResult.hasResolution() && !mIsResolving) {
    mIsResolving = true;
    connectionResult.startResolutionForResult(this, RC_SIGN_IN);
  }
}

Then in onActivityResult do this:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (requestCode == RC_SIGN_IN) {
    if (resultCode == RESULT_OK) {
      mIsResolving = false;
      mGoogleApitClient.connect();
    } else {
      // ...
    }
  }
}