Android listener for onResume() on all applications

Question: I know this could be an issue with security and privacy, but let's assume for now that the user has provided a service with the necessary permissions. The thing my service needs to know is this:
Whenever an onResume() of an activity is called, my service should know which activity was that
Is there any broadcast receiver that I could register? Or does anyone know of any other way?
The idea is as Android has a battery usage application that can break down how much percentage of battery was consumed by an application, I want to capture how much time is a user interfacing with an application, for which I guess I would need to keep track of its onResume calls.
Comment: "Is there any broadcast receiver that I could register?" -- no. "Or does anyone know of any other way?" -- you could write a custom ROM that has an altered version of Android that offers this. Otherwise, you'll have difficulty determining what *process* is in the foreground on current versions of Android, let alone anything finer-grained than that, such as specific activity classes.
Answer: I think you could implement the Observer design pattern. By following it you could think every Activity as an Observable (and have the notify() method inside the onResume() of each of your app's activities) and lastly have a Service that works as the Observer. In that case, when the Observer's update() method gets called then you know you should do something.
Comment: Hi Joaquin, just added an edit to give a clearer idea of what I want to acheive. Is it possible to do via some system provided broadcast if I want to know this for other applications that I have no control over?
Comment: Talk about Broadcasta, Services or whatever else, is out of this discussion. Please check the Observer design pattern and you'll get what I mean. I'm talking you about how to design the system, not about its implementation. Broadcast or Service or whatever you use will work as the Observer. In fact, you could have a BroadcastSender object that is an Observer of the activities and that also knows how to send broadcasts.


how to force class component rerender

Question: I have a class component which receives a list of beds.
I then pass this list of beds down to a bed component that shows the beds.
Some of the beds are occupied and others are available.
I have a button on the occupied beds to enable you to swap beds. So sending the patient to a different bed.
It all works well except for the fact that the screen does not update.
I have added a variable in the redux state which I can track that it changed, but the components stil does not update or refresh.
I have added the connect to the bottom to connect with redux store.
Im not sure how else to re-render the component
Its a big piece of code so not sure what I can post here to help with the question.
The only thing I can say is we normally use redux-forms and its relatively easy to detect changes from there and to run initialize, but because this is a situation without a form Im not sure how to force a rerender.
Comment: In theory, with react if you show in html a variable and that variable will be updated (in redux or in local state using useState hook) component will be authomatically re-rendered. Have you tried to put a console.log in useEffect with that variable in deps list in component that is not re-rendering?
Comment: @GiovanniEsposito Sorry, but its a Class Component so no hooks.
Comment: same question but with `componentDidUpdate` instead of useEffect.
Answer: You can force a component to update by updating the components internal state or by updating the key value on a component. Which will likely involve updating state in a level above it.
<Component key={someVariable} />

how to force class component rerender


Custom File Hierarchy in emacs

Question: I've read many questions about project-management in emacs, though they don't seem to be getting at how I like to work (which dates back to Borland days).
Basically, I'd like to create my own hierarchy of files from which I can open files for editing.  This would be distinct from the directory structure : Often there are files that make logical sense to be collected together from an editing point of view, but are not in the same directory, etc.
At the moment, I've been working with scitepm, which is a side-bar launcher for the editor SciTE (a Scintilla derivative).  But it seems to me that emacs must be able to do something similar - I just can't tease out my specific use-case from the various descriptions of eproject, speedbar, etc...
Any pointers?  Or is my workflow hopelessly retro?
Answer: Vanilla Emacs, out of the box, offers some features that can help:

Filesets:  persistent sets of files --- see (emacs) Filesets.
Dired can be opened on an explicit set of files, regardless of what directories they are in.  Just pass a list of absolute file names as the DIRNAME argument to command dired.
TAGS files give you direct or searchable access to "definitions" in a given set of files.  A definition can be anything, in principle, but it is typically a function, variable, class, etc. definition (IOW, programming constructs).

Bookmark+ offers some more features that can help (bookmarks are typically peristent):

Dired bookmarks: Any set of files and subdirectories, together with the inserted subdirectories, set of Dired markings, hidden inserted subdirectories, and "omitted" files and subdirs.
Autofile bookmarks: Bookmark any file without even visiting it.
Bookmark tagging: Categorize bookmarks any ways you like. Tags define sets of bookmarks.  Sort by tags, search wrt tags,...
Multiple bookmark files: Another way to define sets of bookmarks.
Desktop bookmarks: Emacs session states --- bring back filesets, whatever in a new session.
Composite, or sequence bookmarks combine the effect of multiple bookmarks.

Icicles offers other features that can help:
Here is a good entry point to its support for projects: Icicles - Support for Projects.

It lets you easily save and restore sets of file names persistently (or session only).  This includes emacs filesets but also more flexible sets of files and directories.  You can complete against a saved set of file names when you use C-x C-f etc.  The file names saved in a collection can be anywhere on your file system (or remote).
It enhances the Bookmark+ features in various ways.
It enhances the use of Emacs TAGS files and code navigation.
It enhances the use of Dired in various ways.
It provides features for searching across a set of files or buffers, including a persistent set.
Answer: Have a look at www.emacswiki.org/emacs/BookmarkPlus.
It's got a lot of options and customization. What might be interesting
for you is that you can have multiple bookmark files, each storing multiple
bookmarks, and then one or more master bookmark files that stores them,
besides the normal bookmarks... you get the point:)
I'm mainly using bookmark+ because it allows to bind functions to bookmarks
as well.
Comment: Your detail at the end about binding functions to bookmarks is very helpful.  Usually, lists of features of a package don't focus on the most important stuff : Normally the coolest/latest stuff.  Which is why I had to look for comments here : Thank you.
Answer: As I'm working on improving one major language mode, I tried several approaches to creating projects / groups of files. The thing that I settled upon hasn't been mentioned here yet, so I'll say a couple of words about it. It's EDE. It comes with CEDET, but really is a separate thing. It has several ready-made project templates, specifically for Emacs Lisp, C and I think I, eventually, saw a customization for Android Java development.
This is different from other solutions in that you would need to write some Emacs Lisp code to customize it to do what you like. On the other side, it has many library functions already in place. Such as: it has centralized project management, way to serialize/deserialize settings, APIs to be accessed through menu, API for modifying project settings by means of widgets. It uses overall a very clean approach to solving this in terms of how it is programmed.
Below isn't a polished version of the code, but might give you an idea of what it may look like: http://code.google.com/p/haxe-mode/source/browse/trunk/lisp/ede/haxe.el
Comment: Wow - nicely commented code!  And I'm sure it will help a lot of people - particularly those that need to crank out projects that have the same basic gameplan.  However, for my purposes (which are lots of small 'sketch' projects - often in different languages, etc), this seems far too preplanned - since I'm also trying to get a feel for the logic of the layout too.

Custom File Hierarchy in emacs


which software to use for cleaning up files and increase performance of a computer under ubuntu?

Question:
Possible Duplicate:
Is system cleanup/optimization needed

i am looking for a sofware that would clean up registry , temporary and log files on ubuntu.
Is there an equivalent to the windows CCleaner freeware?
cheers
Comment: You should specify the problem you try to solve. There is no 'registry' to clean up for instance. If you computer is slow, you might need to uninstall stuff, but an automatic program will only get you so far with that. If you need more space you might want to check log and temp files, but if you don't, they're not really slowing you down much.
Comment: "registry , temporary and log files" if they exist they do -not- make your system slow.
Comment: Please be easy on new users. He never stated unnecessary files are making his computer slow.
Comment: To the people who are voting to *delete* this question: Maybe consider asking for a merge instead? Not only does this have valuable answers, but [duplicate questions are considered often to serve an important purpose](http://askubuntu.com/help/privileges/moderator-tools). While I'm pleased people are voting to delete old, off-topic/unclear posts with no useful information in them, I'm worried that some recently active delete voters may not be familiar with the reason most duplicates are not manually deleted. (Actually I think *nothing* needs to happen here, but a merge might be acceptable.)
Answer: Usually, there is no need of a cleaning software to speed up an Ubuntu machine. There is no registry in Linux and temp files are on /tmp directory which is not saved when you shutdown the machine.
Log files are on /var/log and have absolutely nothing to do with the speed of the machine (while they do not fill up the disk of course). Each log has several files because the old ones are compressed and a new one is created. The compressed (old) ones are usually in the form /var/log/logfilename.#.gz. Usually 2 files of each log are not compressed, the current one and the one before it (usually named logfilename.1). It is not needed and won't speed up your machine but if you need some small extra disk space, you can delete all the compressed ones if you don't need them (sudo rm /var/log/*.gz should work but you may need to do some adaptations depending on the names of your log files).
A few little things you can do manually:
Due to the package management automatic dependencies installations, you may have auto installed package that are not needed anymore. Remove them with: sudo apt-get autoremove
Look at your swap to see if it is used heavily (not enough RAM):
free -m

The last line will tell you swap size, used and free. If use is high and you see on the above line -/+ buffers/cache that free memory is short, you may need to increase your RAM to speed up your machine. If swap is near 100% used, you need to increase swap space (but that is another question :) )
Browsers caches usually can be cleaned from the browser preferences.
Or as suggested in other answers, you can use Ubuntu Tweak! :)
Answer: You can use http://ubuntu-tweak.com/
It let you clean cache from browsers, packages no longer needed, old kernel, and many more.
Comment: Oh, it seems we were typing at the same time and you came first :)
Comment: Why isn't Ubuntu-tweak in the official repos?
Answer: I don't think there's such thing as a registry in Ubuntu. You have a package index, package and config files, cookies, etc.
To clean up Ubuntu, you can use Ubuntu Tweak
Also, take a look at these tips
Hope it helps.


Explicitly scope a variable inside a function vs closure

Question: I have the 'phone_dlg_manager' constructor function and its private methods show and init_country_code_combobox. The dialog reference is held in the phone_dlg variable. The show method triggers init_country_code_combobox and I have two options:
1) Explicitly pass the variable country_combobox that the init_country_code_combobox methods needs:
function phone_dlg_manager(ctx, open_dlg_button, edit_ctrl, item)
{
    var phone_dlg;
    show();
    function show()
    {
        phone_dlg = ctx.application.ui.create_dialog(0, "PhoneEditorDlg");
        init_country_code_combobox(phone_dlg.country);
        read_to_dialog_controls(this._form_item);
        phone_dlg.visible = true;
    }

    function init_country_code_combobox(country_combobox)
    {
        country_combobox.items.clear();
        country_combobox.items.start_adding();
        country_combobox.items.finish_adding();
    }
}

2) Since phone_dlg is accessible withing init_country_code_combobox through closure, I can access the property that I need without explicitly passing the variable:
function phone_dlg_manager(ctx, open_dlg_button, edit_ctrl, item)
{
    var phone_dlg;
    show();
    function show()
    {
        phone_dlg = ctx.application.ui.create_dialog(0, "PhoneEditorDlg");
        init_country_code_combobox(phone_dlg.country);
        read_to_dialog_controls(this._form_item);
        phone_dlg.visible = true;
    }

    function init_country_code_combobox()
    {
        var country_combobox = phone_dlg.country;
        country_combobox.items.clear();
        country_combobox.items.start_adding();
        country_combobox.items.finish_adding();
    }
}

The second option seems easier to understand when reading code, however it makes the init_country_code_combobox function know more than it needs. Which option should I choose?
Thanks
Answer: This is mostly a matter of style. Option 1 is a little cleaner, and more extensible, since you can use init_country_code_combobox() to initialize more than just the one dialog. But if this is unlikely to be necessary, option 2 is not unreasonable.
Comment: Thanks for you answer! So I'd probably go with the option 2 then, since someone reading my code may not understand the reasons for explicitly passing the variable.


action text images attachments woking locally but not on production

Question: my question is similar to this one but my hardware is different.
I'm working on a Ubuntu dedicated private server (not on AWS)
I've implemented action_text in my Rails app, and locally (in development) it works fine.
But in production, images attachments are only correctly displayed while editing form, but after form validation, in show views, the image attachments can't be displayed.

while editing (image ok) :

edit image url looks like this :
https://www.deviaweb.fr/rails/active_storage/blobs/redirect/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBRQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--3926192ea6a92df6336b784d3dea6ac43028ca83/anonymous.png

in show views (image can't be displayed) :

show image url looks like this :
https://www.deviaweb.fr/rails/active_storage/representations/redirect/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBRQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--3926192ea6a92df6336b784d3dea6ac43028ca83/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaDdCem9MWm05eWJXRjBTU0lJY0c1bkJqb0dSVlE2RkhKbGMybDZaVjkwYjE5c2FXMXBkRnNIYVFJQUJHa0NBQU09IiwiZXhwIjpudWxsLCJwdXIiOiJ2YXJpYXRpb24ifX0=--060997ce63768510108f6e5dec3e2f5b17d3dc9c/anonymous.png

the urls for image are different in edit page and in show page ! why ????
What am I doing wrong ?
Do I have to configure CORS on my Ubuntu dedicated server ? If yes, How ?
Thanks in advance for your help.

here are my files :
config/routes.rb
Rails.application.routes.draw do
  resources :applis
  root to: "pages#home"
end

app/models/appli.rb
class Appli < ApplicationRecord
  has_rich_text :description
end

app/controllers/applis_controller.rb
class ApplisController < ApplicationController
  before_action :set_appli, only: %i[ show edit update destroy ]
  before_action :authenticate_user!, except: [:show, :index]

  def index
    @applis = Appli.all
  end

  def show
  end

  def new
    @appli = Appli.new
  end

  def edit
  end

  def create
    @appli = Appli.new(appli_params)

    respond_to do |format|
      if @appli.save
        format.html { redirect_to appli_url(@appli), notice: "Appli was successfully created." }
        format.json { render :show, status: :created, location: @appli }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @appli.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @appli.update(appli_params)
        format.html { redirect_to applis_path, notice: "Appli was successfully updated." }
        format.json { render :show, status: :ok, location: @appli }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @appli.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @appli.destroy

    respond_to do |format|
      format.html { redirect_to applis_url, notice: "Appli was successfully destroyed." }
      format.json { head :no_content }
    end
  end

  private
    def set_appli
      @appli = Appli.find(params[:id])
    end

    def appli_params
      params.require(:appli).permit(:title, :description)
    end
end

app/views/applis/_form.html.erb
<%= form_with(model: appli) do |form| %>
  <% if appli.errors.any? %>

<%= pluralize(appli.errors.count, "error") %> prohibited this appli from being saved:

        <% appli.errors.each do |error| %>

<%= error.full_message %>

        <% end %>

  <% end %>

    <%= form.label :title, style: "display: block" %>
    <%= form.text_field :title %>

    <%= form.label :description, style: "display: block" %>
    <%= form.rich_text_area :description %>

    <%= form.submit %>

<% end %>

app/views/applis/_appli.html.erb
<div id="<%= dom_id appli %>">

<%= appli.title %>

<%= appli.description %>

config/environments/production.rb
require "active_support/core_ext/integer/time"

Rails.application.configure do

  config.action_mailer.default_url_options = { host: "https://www.deviaweb.fr" }

  config.default_url_options = { host: "https://www.deviaweb.fr" }

  # Settings specified here will take precedence over those in config/application.rb.

  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both threaded web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
  # or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
  # config.require_master_key = true

  # Disable serving static files from the `/public` folder by default since
  # Apache or NGINX already handles this.
  config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present?

  # Compress CSS using a preprocessor.
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = true
  config.serve_static_assets = true

  # Enable serving of images, stylesheets, and JavaScripts from an asset server.
  # config.asset_host = "http://assets.example.com"

  # Specifies the header that your server uses for sending files.
  # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache
  config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX

  # Store uploaded files on the local file system (see config/storage.yml for options).
  config.active_storage.service = :local

  # Mount Action Cable outside main process or domain.
  # config.action_cable.mount_path = nil
  # config.action_cable.url = "wss://example.com/cable"
  # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ]

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  # config.force_ssl = true

  # Include generic and useful information about system operation, but avoid logging too much
  # information to avoid inadvertent exposure of personally identifiable information (PII).
  config.log_level = :info

  # Prepend all log lines with the following tags.
  config.log_tags = [ :request_id ]

  # Use a different cache store in production.
  # config.cache_store = :mem_cache_store

  # Use a real queuing backend for Active Job (and separate queues per environment).
  # config.active_job.queue_adapter     = :resque
  # config.active_job.queue_name_prefix = "deviaweb_fr_production"

  config.action_mailer.perform_caching = false

  # Ignore bad email addresses and do not raise email delivery errors.
  # Set this to true and configure the email server for immediate delivery to raise delivery errors.
  # config.action_mailer.raise_delivery_errors = false

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation cannot be found).
  config.i18n.fallbacks = true

  # Don't log any deprecations.
  config.active_support.report_deprecations = false

  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = ::Logger::Formatter.new

  # Use a different logger for distributed setups.
  # require "syslog/logger"
  # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new "app-name")

  if ENV["RAILS_LOG_TO_STDOUT"].present?
    logger           = ActiveSupport::Logger.new(STDOUT)
    logger.formatter = config.log_formatter
    config.logger    = ActiveSupport::TaggedLogging.new(logger)
  end

  config.active_record.dump_schema_after_migration = false
end

config/storage.yml
test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

app/javascript/application.js
import "trix"
import "@rails/actiontext"

app/assets/stylesheets/application.scss
@import "trix/dist/trix";
@import "actiontext";

I'm deploying to production using Capistrano, but I've failed commands and a warning message while deploying :
capistrano.log (only the failed and warnings logs)

 DEBUG [dd561607] Running [ -L /home/deploy/deviaweb/releases/20221022121910/log ] as deploy@my_server_ip
 DEBUG [dd561607] Command: [ -L /home/deploy/deviaweb/releases/20221022121910/log ]
 DEBUG [dd561607] Finished in 0.121 seconds with exit status 1 (failed).
 DEBUG [db9d98cb] Running [ -L /home/deploy/deviaweb/releases/20221022121910/tmp/pids ] as deploy@my_server_ip
 DEBUG [db9d98cb] Command: [ -L /home/deploy/deviaweb/releases/20221022121910/tmp/pids ]
 DEBUG [db9d98cb] Finished in 0.121 seconds with exit status 1 (failed).
 DEBUG [e1a94393] Running [ -L /home/deploy/deviaweb/releases/20221022121910/tmp/cache ] as deploy@my_server_ip
 DEBUG [e1a94393] Command: [ -L /home/deploy/deviaweb/releases/20221022121910/tmp/cache ]
 DEBUG [e1a94393] Finished in 0.128 seconds with exit status 1 (failed).
 DEBUG [8505c6a7] Running [ -d /home/deploy/deviaweb/releases/20221022121910/tmp/cache ] as deploy@my_server_ip
 DEBUG [8505c6a7] Command: [ -d /home/deploy/deviaweb/releases/20221022121910/tmp/cache ]
 DEBUG [8505c6a7] Finished in 0.122 seconds with exit status 1 (failed).
 DEBUG [7726cad7] Running [ -L /home/deploy/deviaweb/releases/20221022121910/tmp/sockets ] as deploy@my_server_ip
 DEBUG [7726cad7] Command: [ -L /home/deploy/deviaweb/releases/20221022121910/tmp/sockets ]
 DEBUG [7726cad7] Finished in 0.121 seconds with exit status 1 (failed).
 DEBUG [22766157] Running [ -d /home/deploy/deviaweb/releases/20221022121910/tmp/sockets ] as deploy@my_server_ip
 DEBUG [22766157] Command: [ -d /home/deploy/deviaweb/releases/20221022121910/tmp/sockets ]
 DEBUG [22766157] Finished in 0.123 seconds with exit status 1 (failed).
 DEBUG [b010a982] Running [ -L /home/deploy/deviaweb/releases/20221022121910/vendor/bundle ] as deploy@my_server_ip
 DEBUG [b010a982] Command: [ -L /home/deploy/deviaweb/releases/20221022121910/vendor/bundle ]
 DEBUG [b010a982] Finished in 0.122 seconds with exit status 1 (failed).
 DEBUG [0fba4998] Running [ -d /home/deploy/deviaweb/releases/20221022121910/vendor/bundle ] as deploy@my_server_ip
 DEBUG [0fba4998] Command: [ -d /home/deploy/deviaweb/releases/20221022121910/vendor/bundle ]
 DEBUG [0fba4998] Finished in 0.123 seconds with exit status 1 (failed).
 DEBUG [e14770e8] Running [ -L /home/deploy/deviaweb/releases/20221022121910/.bundle ] as deploy@my_server_ip
 DEBUG [e14770e8] Command: [ -L /home/deploy/deviaweb/releases/20221022121910/.bundle ]
 DEBUG [e14770e8] Finished in 0.122 seconds with exit status 1 (failed).
 DEBUG [88e8095e] Running [ -d /home/deploy/deviaweb/releases/20221022121910/.bundle ] as deploy@my_server_ip
 DEBUG [88e8095e] Command: [ -d /home/deploy/deviaweb/releases/20221022121910/.bundle ]
 DEBUG [88e8095e] Finished in 0.123 seconds with exit status 1 (failed).
 DEBUG [8fc5e0b3] Running [ -L /home/deploy/deviaweb/releases/20221022121910/public/system ] as deploy@my_server_ip
 DEBUG [8fc5e0b3] Command: [ -L /home/deploy/deviaweb/releases/20221022121910/public/system ]
 DEBUG [8fc5e0b3] Finished in 0.173 seconds with exit status 1 (failed).
 DEBUG [30611cdb] Running [ -d /home/deploy/deviaweb/releases/20221022121910/public/system ] as deploy@my_server_ip
 DEBUG [30611cdb] Command: [ -d /home/deploy/deviaweb/releases/20221022121910/public/system ]
 DEBUG [30611cdb] Finished in 0.128 seconds with exit status 1 (failed).
 DEBUG [d3504989] Running [ -L /home/deploy/deviaweb/releases/20221022121910/public/uploads ] as deploy@my_server_ip
 DEBUG [d3504989] Command: [ -L /home/deploy/deviaweb/releases/20221022121910/public/uploads ]
 DEBUG [d3504989] Finished in 0.151 seconds with exit status 1 (failed).
 DEBUG [b7ab3a35] Running [ -d /home/deploy/deviaweb/releases/20221022121910/public/uploads ] as deploy@my_server_ip
 DEBUG [b7ab3a35] Command: [ -d /home/deploy/deviaweb/releases/20221022121910/public/uploads ]
 DEBUG [b7ab3a35] Finished in 0.125 seconds with exit status 1 (failed).
 DEBUG [ddd629a2] Running [ -L /home/deploy/deviaweb/releases/20221022121910/storage ] as deploy@my_server_ip
 DEBUG [ddd629a2] Command: [ -L /home/deploy/deviaweb/releases/20221022121910/storage ]
 DEBUG [ddd629a2] Finished in 0.125 seconds with exit status 1 (failed).
 DEBUG [abf6dda9] Running [ -L /home/deploy/deviaweb/releases/20221022121910/public/assets ] as deploy@my_server_ip
 DEBUG [abf6dda9] Command: [ -L /home/deploy/deviaweb/releases/20221022121910/public/assets ]
 DEBUG [abf6dda9] Finished in 0.126 seconds with exit status 1 (failed).
 DEBUG [edb6d951] Running [ -d /home/deploy/deviaweb/releases/20221022121910/public/assets ] as deploy@my_server_ip
 DEBUG [edb6d951] Command: [ -d /home/deploy/deviaweb/releases/20221022121910/public/assets ]
 DEBUG [edb6d951] Finished in 0.125 seconds with exit status 1 (failed).

 DEBUG [5703ad55]   warning " > @firstname.lastname@example.com" has incorrect peer dependency "trix@^1.3.1".

Comment: how are you storing images/files? locally? => ```config.active_storage.service = :local```
Comment: yes, locally in my dedicated server
Answer: I solved the problem !
my production server was running Ubuntu 18.04, but locally I was using Ubuntu 20.04.
The problem was with libvips. On Ubuntu 18.04, you can not install Vips with a version superior than vips-8.4 (or something similar). But loccaly (Ubuntu 20.04) I was using vips-8.9.1.
I upgraded my server to Ubuntu 20.04 to be able to use latest version of Vips (8.9.1) and now everything works fine.
Hope this helped !


Should I replace this fixture box or get creative with the mounting?

Question: I recently took down a ceiling fan/light in order to replace it with track lighting. After disassembling the fan I was left with this fixture box:

As you can see there are two holes in which to affix the mounting bracket with two provided screws. However, either the screws are too small or the thread inside each hole is stripped as I can easily pull the screws back out after attempting to tighten them. So I a wondering if I am better of replacing the mount or attempting to get bigger screws or tighten with a nut?
Comment: 8/32 or 10/32 machine screws are for fixture boxes, you could try one of these sizes.
Answer: Ceiling fans, when properly mounted, are put on specialized mounting/junction boxes that are especially strong, have a very secure mount for the fan and are hard screwed into a beam or stud.
What you have there looks like a pancake style fan box. See this example:

Every junction box has threaded holes for mounting fixtues such as your track lighting base. The studs in your picture appear to be the bolt holders for the fan.  If they are stripped, it is not safe to hang things from them and oversized bolts are a risky work-around.
It may be that other screw holes in the bottom are properly threaded for standard fixture mounting. Check them using the bolts that came with the fixture.  If they are not (and there are usually several unthreaded holes in junction boxes), you should probably replace the box with a new one with intact mounting tabs/holes.
Answer: If you're trying to re-use an old fan mount to affix a rail light system, you probably shouldn't use it in that way.  Instead, install the rail on suitable new mounts and cleanly patch up plaster after removing old fan mount box.
Comment: Make sure you aren't hiding any junctions in the wall, they need to be in accessible junction boxes. And presumably, the track lighting has a mount for the round box so there shouldn't be a need to cover it up.
Comment: @chris: it looks like you've accidentally created a duplicate user account; if you register your account, you'll be able to take credit for the answers you've previously provided.  I've flagged for a moderator to merge this account with the previous one you created: http://diy.stackexchange.com/users/6933/chris


The range of $f(x)=\cos^{2n}(x)+\sin^{2n}(x)$

Question: I have $f(x)=\cos^{2n}(x)+\sin^{2n}(x),\; n\in \mathbb{N},\; n\geq 2,\;x\in \mathbb{R}$
I need to find the range of the function.
I took $n=2$ and I got $f(x)=1-\frac{1}{2}\sin^{2}(2x)$ and the range of this is $[1/2,1]$
Also, for $n=3$ I got $[1/4,1]$.
How to find the range for $n$?
Comment: $$\cos^mx+\sin^mx\le\cos^2x+\sin^2x$$ for $m\ge2$
Comment: Simply use $f'=0$.
Comment: https://math.stackexchange.com/questions/1410604/prove-ab-2n-leq-anbn-2 says $$\ge\dfrac1{2^{n-1}}$$
Comment: Thank you for your help :)
Answer: With $t=\cos^2(x)$ such that $0\le t\le 1$, you bracket
$$t^n+(1-t)^n.$$
The stationary points are the roots of
$$t^{n-1}-(1-t)^{n-1}=0$$ or $$t=\frac12.$$
Hence,
$$f(x)\in[2^{1-n},1].$$

Without derivatives:
$$t^n+(1-t)^n$$ is obviously symmetric around $t=\dfrac12$, and with $s:=t+\dfrac12$,
$$\left(\frac12+s\right)^n+\left(\frac12-s\right)^n.$$
If we develop using the binomial formula, only even degree terms will remain so that the polynomial is monotonic for $s>0$. Hence the minimum is achieved for $s=0$, and the maximum for $s=\dfrac12$.
Comment: @Nosrati: yes, I was proofreading.
Comment: Thank you for your answer!
Answer: Hint:
You have to find the range of the function $f(t)=t^n+(1-t)^n,\quad t\in[0,1]$
Comment: Thank you for your help:)


How to get the mending enchantment?

Question: I have a skeleton farm and I enchanted DOZENS of items already. I never saw "mending" though. The Wiki says, that you find this on the lower enchanting levels, but I never saw it.
Note: (Normally) Before I enchant an item, I look through all of them and check on each what I would get: Helmet, Chestplate, Leggings, Boots, Sword, Bow. I think chances that I really never could have seen it are pretty low.
Can you get this enchantment only from the end and from books? I saw some enchanted items in the end cities with mending.
Answer: Mending is a treasure enchantment, which you can only find in the world, you can not create it yourself on an enchanting table.
Treasure enchantments can be obtained by

Fishing
Chests in dungeons, temples, mineshafts, End cities etc.
Trading (villagers charge double price for treasure enchantments)

Mending can be found on many items, including, for example, Fishing Rods.
Sources: 1.9 changelog, enchantment mechanics, trading pages.
Comment: If you plan to obtain Mending through plain old normal fishing, you'll need saint's patience. It's a rare drop (enchanted book is a rare drop in fishing and Mending is one of many, many enchanted books you can find) - and fishing is slow enough by itself. You may look up AFK fishing farms, to make it even somewhat viable method, Finding (or breeding!) a villager with this trade is the best, most sustainable method of obtaining multiple Mending books.
Comment: Wow. Can i fish anywhere for that?
Comment: @TrudleR Yes, fishing does not depend on location, you can fish in a 1-meter block in your base (though it is hard not to hit a block with your bobber). Fishing speed only depends on weather, sky sight (fish outside during rain for maximum efficiency) and Lure enchantment. Drop rates depend on Luck of the Sea enchantment and Potions of Luck (uncraftable in 1.9).
Comment: @OrcJMR I thought a pond had to be at least a certain depth in order to fish. Or is that something added by certain mod packs?
Comment: @Nzall nope. The bobber must only be in water. Just tested with a single block of water in 18w03a - absolutely no problem, the bobber doesn't even get stuck in the floor! The only downside is that you can't see the particles of approaching fish - but the depth of 1 m is totally fine.
Answer: It is possible to get mending from an enchantment table, but it is very hard and I would suggest having a very good xp farm as well as using books if you want to get it from an enchantment table. I know people say that it's a treasure enchantment and you can't get it from an enchantment table, but I did. Also, before anyone asks, yes, I am sure I got it from an enchantment table.
Comment: This is very simply incorrect.
Comment: The minecraft wiki specifically says that Mending is a Treasure Enchantment, meaning that it CANNOT be made in an Enchanting table

How to get the mending enchantment?


Tips for speed-running

Question: As you might have known, I can have only 2 convoys on my first save due to a glitch.
 I want to speed-run through a new save to get all 3 convoys.
Do you guys have any tips for speed-running?
Answer:
Do only the main objectives for each story mission.
do not worry about side missions and item collection.

You can go back and complete the above after you get your 3rd convoy.

Murder guards instead of spending large amounts of time to sneak around them, when given the option. When your notoriety goes up just bribe the town crier. You should still sneak when possible, but don't get carried away with it.
climbing buildings and trees isn't the answer. Unlike in previous AC games, the rooftops are not an efficient way to get around in cities.
in open combat, kill enemies with guns. I like to disarm the weak enemies and use their muskets on the difficult ones. I hear that smokebombs+hidden blade is effecient for killing large groups, the only limiting factor is the number of bombs you can carry.
fast travel

Tips for speed-running


Probability of an odd amount of sixes when rolling a 6-sided die 10 times.

Question: Rolling a fair die 10 times, what is the probability it will give an odd amount of sixes?

So the outcomes I'm interested in are:
1 six in 10 rolls
or
3 sixes in 10 rolls
or
5 sixes in 10 rolls
or
7 sixes in 10 rolls
or
9 sixes in 10 rolls

Can the probability of getting 1 six in 10 rolls be described as $ 1 - ({5 \over 6})^9$  ?
And if the above is correct, I should be able to continue with
the probability of getting 3 sixes in 10 rolls as $ 1 - ({5 \over 6})^7$
the probability of getting 5 sixes in 10 rolls as $ 1 - ({5 \over 6})^5$
the probability of getting 7 sixes in 10 rolls as $ 1 - ({5 \over 6})^3$
the probability of getting 9 sixes in 10 rolls as $ 1 - ({5 \over 6})^1$
All I need to do now is to add them together, correct?
$$
P (\text{odd  amount  of  sixes  in  10  rolls}) = (1 - {5 \over 6}^9) + (1 - {5 \over 6}^7) + (1 - {5 \over 6}^5) + (1 - {5 \over 6}^3) + (1 - {5 \over 6}^1)
$$
Help is appreciated,
Comment: See about [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution).
Comment: Yes! Binomial distribution is the way to go!
Answer: No no no!
Probability for exactly $n \space (\in \{0,1,\dots 10\})$ amount of sixes in ten rolls is
$${10\choose n}  \left(\frac{1}{6}\right)^n \left(\frac{5}{6}\right)^{10-n}$$
Now sum these for odd numbers and you have your solution.
Comment: I somehow thought the first was correct but it's not: $1-(5/6)^9 \neq {6 \choose 1}(1/6)^1(5/6)^9$.
Comment: The meaning of the probability $1−(5/6)^{10}$ is that there is at least $1$ six. Notice there must be $10$ in the exponent in this case.
Answer: Your start is correct but not the calculations,
See here
The formula is $\boxed{\color{red}{\text{Pr}(X=k)=\binom{n}{k}p^k(1-p)^{n-k}}}$ for $k$ successe in $n$ trials
$k=1:\quad$For  $1$ six in $10$ rolls $X\sim B(10,\frac 1 6),\quad\text{Pr}(X=1)=\binom{10}{1}(1/6)^1(1-1/6)^{10-1}$
$k=3:\quad$For  $3$ six in $10$ rolls $Y\sim B(10,\frac 1 6),\quad\text{Pr}(Y=3)=\binom{10}{3}(1/6)^3(1-1/6)^{10-3}$
Do the same for $k=5,7,9$. The answer is the sum of the probabilitys.
Comment: But why is the binomial coefficient relevant? Lets say that I want to get a six on the very first flip, that's $(1/6)$ and then for the remaining 9 flips I don't want a six. Then it makes sense to me to multiply $(1/6)$ with $(5/6)^9$. It's not completely clear to me why I would multiply it with the binomial coefficient
Comment: @user3067688 This is the formula of [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution) $\binom{n}{k}$ is the number of possibilities for $k$ success in $n$ trials
Answer: Here's a recursion for solving this problem:
Let $A_n$ be the event of having an odd number of sixes after $n$ rolls.
We have that $P(A_n)=\frac56 P(A_{n-1})+\frac16(1-P(A_{n-1}))=\frac23 P(A_{n-1})+\frac16$.
You should be able to use this to solve your problem, either by working out the values to $P(A_{10})$ explicitly, or by solving the recursion (i.e., getting a nonrecursive formula for $P(A_n)$).
Edit: The initial condition is $P(A_0)=0$.


Frontier points of set is always closed

Question:
consider set $S \subseteq \mathbb{R}^n$ define $S_{F} =
\{ \textbf{x} \in \mathbb{R}^n : \textbf{x}\,\, \text{is frontier point of } S  \}$ where a point $ \textbf{x} \in \mathbb{R}^n$ is called a frontier point of set $S$ if every neighborhood of $\textbf{x}$ contains both points in $S$ and $\mathbb{R}^n -S$.prove that $S_{F}$ is closed

we have to show that $S_{F}$ is closed which is equivalent to showing that $\mathbb{R}^n -S_{F}$ is open
consider arbitrary $\textbf{a} \in \mathbb{R}^n -S_{F}$ we have to show that there exists $\delta>0$ s.t $B(\textbf{a} , \delta) \subset \mathbb{R}^n - S_{F}$
assume for contradiction that there is no such $\delta$
which implies that $\forall \delta>0$ $\exists \textbf{b}  \in B(\textbf{a} , \delta) \cap S_{F}$

and I am struck here, can someone tell how to proceed ?
Answer: If $\forall\ \delta>0 \exists \textbf{b} \in B_{\delta}(\textbf{a}) \cap S_F$, then $\textbf{a}\in (S_F)_F$. But $(S_F)_F\subset S_F$. Then, $\textbf{a}\in S_F$.  For otherwise, $S_F\cap \mathbb{R}^n-S_F=\emptyset$. You can assume previosly that $S_F\neq \mathbb{R}^n$ and $S_F \neq \emptyset$ ('cause both cases are immediate) and you will have your contradiction.
Another way to see this:
We can translate your definition of $x\in S_F$ by
$$\forall\ \epsilon>0: B_{\epsilon}(x) \cap S \neq \emptyset \wedge \forall\ \epsilon>0: B_{\epsilon}(x) \cap \mathbb{R}^n-S \neq \emptyset $$
If $y\not\in S_F$, then
$$\exists\ \epsilon_0>0 : B_{\epsilon_0}(y)\cap S = \emptyset \vee \exists\ \epsilon_0>0 : B_{\epsilon_0}(y)\cap \mathbb{R}^n - S = \emptyset $$
if
$$\exists\ \epsilon_0>0 : B_{\epsilon_0}(y)\cap \mathbb{R}^n - S = \emptyset$$
Then,
$$\exists\ \epsilon_0 >0 : B_{\epsilon_0}(y) \subset S$$
That is, all ball is contained in $\mathbb{R}^n - S_F$. For otherwise, if
$$\exists\ \epsilon_0>0 : B_{\epsilon_0}(y)\cap \mathbb{R}^n - S = \emptyset$$
then
$$\exists\ \epsilon_0 >0 : B_{\epsilon_0}(y) \subset \mathbb{R}^n-S$$
For the same reason, we can conclude that $\mathbb{R}^n - S_F$ is open.
Comment: let me explain better
Comment: Now the proof is correct.
Comment: also, your definition seems wrong right ? it shoul be $\forall \epsilon > 0 :  \Big( B_{\epsilon}(x) \cap S \neq \phi \Big)  \land \Big( B_{\epsilon}(x) \cap \mathbb{R}^n -S \neq \phi \Big) $

Frontier points of set is always closed


Does it Matter if I use a 50 amp breaker in my main panel to hook up a 30 amp generator?

Question: I have a 50 amp breaker and space to put it in my main panel. Can I use that breaker or do I need to use a 30 amp  does it matter?
I will install a main panel interlock switch and a 30 Amp Generator NEMA L14-30P Power Inlet Box for 4 Prong Generator Cord, 125/250 Volt, 7500 Watts, to plug in the 7000 watt 30 amp generator. I will make the generator a floating neutral as well.
Comment: It's not right to put what is presumably 10/3 on a 50 amp breaker, not code compliant  UNLESS there was an upstream breaker sub panel with a 30 amp breaker for the genset inlet. I don't even know if that's code compliant, but it would be safe and future proof.  As always, breakers are there to protect installed wiring, not devices unless hard wired.,   Also your genset probably has over-current protection built in, so while what you are asking isn't terribly unsafe, it's certainly not up to code.  30 amp breakers are pretty cheep, just buy one and do it right.
Comment: Breakers are cheap, don't worry about it, just get the right ampacity for the job.
Comment: That would be fun. The 50 amp breaker would stay cool as cucumber while the generator is burning up
Comment: I presume you have read all the other answers about generators, and know that some form of lockout or transfer switch is absolutely necessary so your generator can absolutely never be connected to the power lines, to avoid endangering line workers. And that you should never use a suicide cord, to avoid endangering yourself.
Answer: The generator presumably has a 30A breaker of its own, which protects the generator.
Using a larger input breaker with appropriate gauge wires and 50A inlet (for the 50A breaker on the inlet) is fine. Then if you put in a 50A generator later, no change needed at the panel.
You'll need to make a cord to adapt the 30A outlet to a 50A inlet. If sticking with a 30A inlet you'll need 50A wire to it, and it's a dubious arrangement .vs. a 50A inlet.
Answer: Breakers are cheap
So don't sweat bullets over reusing the 50A.  Also, breaker types must match the panel, so if it's handy but the wrong type you can't use it anyway.  E.G. if you have a Siemens QP breaker but a Square D panel.
Now if you want to install 50A for future use that's fine.  You can use 50A wire (#6 NM if all indoors, #6 UF, or #8 any other copper wire type, or #6 aluminum if you can find an inlet certified for aluminum wire).  The inlet will need to match the breaker.  NEC 210.21.
A 30A breaker would let you use cheaper and easier to handle #10 wire.  Don't know about the cost of a 30A inlet vs a 50A inlet.
Comment: c /stile/style/
Comment: 75 seconds read, it could be shorter, but you are getting better in executive stile without unnecessary side track, but at least you did not complain about made in China
Comment: I guess an "executive stile" is that thing which only allows executives into the area and prevents all the peasants/employees from entering ...
Comment: Nah, the stile is the upright on a door/window. So the executive stile is the one that's on a clear path to the top!
Answer: The main thing (since there is the most of it) that a breaker protects is the wire. For 30A that is typically 10 AWG copper cable or individual wires in conduit, for 50A that is typically 6 AWG copper cable, 8 AWG copper individual wires in conduit or 6 AWG aluminum individual wires in conduit.
The second thing is any receptacles or other parts. The 14-30 inlet is almost certainly rated for only 30A.
The last thing is the devices/appliances - i.e., what's at the end of the circuit. This gets interesting. A generator is producing the power, so it realistically can't produce a lot more than 30A if it is rated for 7,000W/30A. It can probably surge a bit (e.g., for motor startup) but that's OK for wires, breakers and everything else too. In addition, the generator very likely has its own over-current protection - e.g., a 30A fuse or breaker on the 30A outlet.
So the big question really is the wire. If you actually have wire that is rated for a 50A circuit then you could, in theory, replace that 30A inlet with a 50A inlet and I think you would be fine. On the other hand, if as is likely the case you only have 30A 10 AWG cable then there is real risk (and code violation) in using a 50A breaker and 50A inlet. That's because the next owner would see 50A inlet and get a bigger generator and overload the wire when in use. But almost nobody upsizes wire unnecessarily, with the exception of using 12 AWG on a 15A circuit, which is fairly common. But 8 AWG on a 30A circuit? Not likely.
Comment: @Ruskes if 30 seconds is all you want to put into answering a question, Yahoo Answers may be more your speed lol.
Comment: @Ruskes (a) some people like long detailed explanations, some don't, which is why I sometimes put in a TL;DR; (b) The breaker size *defines* the circuit - if you put on a 50A breaker, it is now a 50A circuit, not a 30A circuit - which then makes 10 AWG wire a code violation. Similarly, a 15A breaker with 12 AWG wire (larger than needed but common and valid) is*by definition* a 15A circuit - it isn't a 20A circuit by virtue of the wire any more than a 50A breaker + 10 AWG wire would be a 30A circuit.
Comment: If installing wire it's a great suggestion to consider oversizing it. When did anybody say "I wish my whole-house backup generator had _less_ capacity!"? When I did my inlet I had 100 ft to cover and a 6500 W generator (for now) -- I used aluminum THHN, 4 gauge I think (?), a 60A breaker in the interlock, and an L14-30 inlet. In my case the inspector agreed that the interlock breaker, being on the load end of the circuit, is really just a switch. The breaker in the generator provides the overcurrent protection. Meanwhile my wiring is all set for a bigger, hard-wired generator in the future.
Comment: @GregHill Agreed. With wire that matches (or exceeds) the breaker, and overcurrent protection in the generator, it is only a matter of getting approval of the inlet itself. Which while you would be exceeding specs if you forced a 50A generator output into that inlet (using an illegal adapter cord...) odds are the inlet itself can handle it, whereas the 100' of wire if significantly undersized would not.
Comment: 30 seconds worth of answer effort matches well with the 30 seconds worth of effort some people put into writing questions. Sadly, both lead to more questions and confusion than necessary.
Comment: and in executive stile summary, you should not use 50 amp breaker on 30 amp circuit.
Comment: @manassehkatz-Moving2Codidact the main difference is, I only take 30 seconds out of they life, while you take at least 10 minutes with the lecture. As much the lecture is correct, most people are intelligent and do not need it.
Answer: Supply breakers can be any size up-to the ampacity of the panel, and that's the role this inlet breaker is taking so 50A is fine feeding from a 30A inlet.
Power comes in through this breaker, the thing downstream from this breaker is a 200A (or whatever size) panel.
The breaker doesn't protect the wiring from the inlet because it doesn't control current into that wiring. that protection comes from the generator.


Find if a metric space complete

Question: Let $(\mathbb{R},d)$ be a metric space with a distance function $d(x,y)=|f(x)-f(y)|,$ where
$$
f(x) =
\begin{cases}
&\displaystyle\frac{1}{x-2}, \quad &\text{$x < 2$} \\
&\ln \ x, \quad &\text{$x\ge 2$.}
\end{cases}
$$
Is this metric space a complete metric space? If it is not what is the completion of it?
Answer: Hint: $f$ is an isometry from $(\mathbb{R},d)$ to a subset of $\mathbb{R}$ endowed with the canonical metric of $\mathbb{R}$.
Answer: First of all we consider our particular case. This space is not complete and an example can be the Cauchy sequence $\{-n+2\}_n$. In fact this sequence is Cauchy
if $n,m\geq M $, then $|f(-n+2)-f(-m+2)|=|\frac{1}{n}-\frac{1}{m}|\leq \frac{2}{M}$
Conversely, is not a convergent sequence on $(\mathbb{R},d)$. By contradiction, we suppose $\{-n+2\}_n$ is convergent to some $\alpha \in \mathbb{R}$. Then one get
$0=\lim_{n\to \infty}d(-n+2, \alpha)=\lim_{n\to\infty } |\frac{1}{n}-f(\alpha)|=|0-f(\alpha)|=|f(\alpha)|$
This means $f(\alpha)=0$ and this is not possible because $f^{-1}(0)=\emptyset$
Thus $(\mathbb{R},d)$ is not a complete space.
What is the obstruction to the positive answer? The problem is that the image of $f$ is not a closed subset of $\mathbb{R}$ but only the subset $(-\infty ,0)\cup [ln(2), \infty)$
If one want to complete this space it is more convenient to study the problem in a more general way, in order to understand what it happens in a general situation.
We consider a bijective function $f: X\to Y$. If $Y$ is a topological space, then it is possible to inherit a natural topological structure on $X$ by $f$ such that $X$ and $Y$ are homeomorphic topological spaces and $f$ is an homeomorphism.
Morevoer, if $(Y,d_Y)$ is a metric space inducing that topology on $Y$, then one can get a metric $d_X$ on $X$ such that the induced topology is the topology inherited on $X$ by $f$ and $f$ is not only an homeomorphism but also an isometry with respect the two metrics fixed respectively on $X$ and $Y$. The metric induced on $X$ will be clearly
$d_X(x,y):=d_Y(f(x),f(y))$
In this way one can observe $(Y,d)$ is a complete metric space if and only if   $X$ is a complete metric space.
At this point we can consider our particular case. The bijection in this case is the following
$f: \mathbb{R} \to (-\infty ,0)\cup [ln(2), \infty)\subseteq \mathbb{R}$
and so $(\mathbb{R}, d)$  can not be a complete metric space because $((-\infty ,0)\cup [ln(2), \infty), |\cdot |)$ is not complete. In fact a subset of a complete metric space ( that in this case is $(\mathbb{R}, |\cdot|)$ ) is complete if and only if it is closed and in our case $(-\infty ,0)\cup [ln(2), \infty)$ is not closed.
At this point it is clear what is a completion of $(\mathbb{R}, d)$. The completion will be simply the complete space
$cl ((-\infty ,0)\cup [ln(2), \infty))=(-\infty ,0]\cup [ln(2), \infty)$
with the metric $|\cdot |$.

Find if a metric space complete


Cinderblock cmu masonry question

Question: I'm replacing a 7ft. Basement Wall with 10" block. We tried to demo carefully as to save some interlocking blocks in the corners. A few broke resulting in a few cuts having to be made.
My question is, when dealing with a cut which ends up going through one of the two cores in the block, should the cut side face the existing wall butting up to it, or should the cut piece face towards the new wall being put up?
Thanks.
Answer: It doesn't make a difference. Either way is fine, just make sure the cut is even so the mortar joint is even.
If you're concerned about it being weakened, fill the core with grout after the block is in place.
Comment: That's what I thought. Yes, being it's the corner. I was doing vertical rebar and grout.

Cinderblock cmu masonry question


What is the purpose of a Smurf account in League of Legends?

Question:
Possible Duplicate:
What is Smurfing in online games?

I understand that a Smurf account is a less-used account owned by a player with a much better account, but I don't understand why you'd want to have one in League of Legends... It's not like other games where you can use a Smurf as a Mule to hold your less-important items. What is the point of an accomplished 1400~ elo player having a Smurf account?
Comment: Not sure this was a dupe. The title certainly matched the dupe, but this was more about why one would smurf in LoL, versus what smurfing means.
Comment: What is a smurf account != Why smurf in game X
Comment: Upon further reading, the close reason as dupe is not actually correct. It should still be closed, because it is not constructive, but it is *not* actually a dupe. :(
Answer: High-ranked players (generally around level 30) will use smurf accounts for a few different reasons, some reasonable, others less-so:

Playing with less-skilled friends, or with friends who are new to the game. The high elo player doesn't want to instantly drag that person up against the type of opponents that they typically face, so they create a new account and play at a lower level.
Spending time with a new champion (or champions). This is less-true of very high elo players, but some players do want to spend time learning how a different kind of champion works. They will create a smurf account and exclusively play a single champion in a low-pressure environment. This is far less popular now, of course, with the Coop vs. AI games being available.
Pub-stomping is also, unfortunately, a reason someone might want a smurf. Some people like the utter domination that comes with being so much more skilled at the game. This practice is often frowned upon, but does still happen.
Pro players sometimes create smurfs to mask their identity. If you watch their streams, you'll notice they're constantly receiving friend requests, etc. And sometimes they just don't want to deal with it. This reprieve is usually short-lived.
As user22193 pointed out in another answer, another reason to create a smurf is if you change server realms. For instance, Team Solomid was high-ranked on the NA servers, but created EU-W accounts and had to get their accounts up to level 30 and their Elos back to a stable position near the top of the ladder.
M2tM: Smurf accounts can be played on if you decide to dodge a ranked game before it starts.  If people in a ranked game lobby are making you nervous about your win chance and you close the game you are unable to queue for another game for at least 30 minutes.  Your smurf will be available to play on, however. *This is now 5 minutes for the first dodge, then it ramps up.

There are other potential reasons (that should just be edited into this answer), but those are the primary causes for smurfing in League of Legends.
Answer: It's a different account, a secondary account where you can try new things or just practice more until you become good enough to get up your elo.
Answer: There is one other reason for a smurf-like account being created.  With all the different servers League of Legends is being played, if you want to play on a different server, then you ultimately have to create a new account.  This happened a few months ago when North American team, Team SoloMid, moved to the gaming house and decided to all create EU West accounts.  The end result is you had 5 of the best players in the world creating lvl 1 summoners in EU West and generally destroying the competition in Normal games until they finally reached Summoner level 30.
On the Less-skilled friends, it is simply the game is more fun when you win.  So if you want your friend to play with you, you want to do what you can to let your friend win that first game, and one way to do so is to lower the competition of who you face by being on a lower level account.
On the second point, I am guilty of this.  My first summoners (main) I played most tank and tanky support.  Since then, the metagame changed, and I had no experience playing carries.  In fact, I lacked the runes and champions that qualify as carries, so I decided to create a new summoner (smurf) to only buy things for carries and focus purely on that style of play.
Answer: Many people have smurf accounts that they used to gain level 10's for freind recruitment awards.
However, professional players often have smurfs they use in this scenario:
Top rated players (ie: 2400 elo) will sit on their rank until they're either passed or about to hit the 3-week elo decay, at that point one of their friends who is similarly rated will log into their smurf who will be about 1600-1800 elo, and duo queue. They can then stomp the opposing team and keep their elo up without risking decay. Other high elo players will often create smurfs to play with their low elo friends.


How to dump remote mysql database and import it locally using bash script

Question: Trying to dump a remote wordpress database using that shell script:
db_name=$(php -r 'include("public_html/local-config.php");echo DB_NAME;');
db_user=$(php -r 'include("public_html/local-config.php");echo DB_USER;');
db_password=$(php -r 'include("public_html/local-config.php");echo DB_PASSWORD;');
db_host=$(php -r 'include("public_html/local-config.php");echo DB_HOST;');
mysqldump --user="$db_user" --password="$db_password" "$db_name";

To have the dump locally I run this in my local terminal (host in .ssh/config):
ssh host 'bash -s' < thatscript.sh > dump.sql

Then I would do mysql localdb < dump.sql to import it locally.
Now I tried to put the ssh and local mysql part into the script as well, so that I can just fire up the script and it does everything.
I tried to put the original script into a function and then call it using
mysql localdb < $(ssh host 'bash -s' < myDumpFunction)

but that assumes a file called myDumpFunction and obviously does not work. How would I call the function in that case correctly?
Any other ideas on how to achieve a one line database sync for a local dev system are appreciated as well.
Answer: What about writing another .sh file and starting it with ssh connection ? Do not forget to change chmod. Script should be executable.
example:
ssh username@ipaddr(remotePc) start.sh

Comment: I did consider that but then I have two scripts hanging around to do one job. That did not seem very elegant to me, thats why I wondered how to do it in one script.
Comment: So you can use upstart function. But I always use such solutions, because it is useful and practical while working ssh connection or remotely.
Comment: @mcnesium if this solution works, click as solved for other users
Comment: Thank you for reminding me, but as I already stated, your answer is not really suitable for my problem, sorry.


nmcli not showing connection

Question: I imported L2TP/IPsec VPN connection configuration file from Ubuntu mate 20.04 /etc/NetworkManager/system-connections/ to Ubuntu server 20.04
Next, on the Ubuntu server 20.04 PC, I check the nmcli connection "sudo nmcli con" in response I get an "empty field"
How to solve this problem? enter image description here
Comment: did you restart network manager?
Comment: Please show the status of devices known to NetworkManager: $ nmcli d
Comment: Hello. Problem solved.
Answer: Problem solved.
I switched to Network-Manager in Netplan.
Since 17.10 Ubuntu Server, the Netplan utility has been used to manage the network configuration.
So, create this file:
/etc/netplan/00-enable-network-manager.yaml

And put this content and save:
network:
  version: 2
  renderer: NetworkManager

Then disable the default configuration:
cd /etc/netplan
sudo mv 00-installer-config.yaml 00-installer-config.yaml.bak

It may need a restart of the NetworkManager service or maybe a reboot.
IMPORTANT: before doing so, be sure that you have physical access to the server, since it may be not reachable after this change.

nmcli not showing connection


New light switch has blue, black, and white wires. Wall has black, white, and ground. Can I make it work?

Question: I bought a new light switch that is supposed to allow me to automate my lights easier. Here is what it looks like:

It has blue, black, and white wires. Coming out of my wall, however, I only have a white, black, and ground. The instructions say that I need two white wires or else the switch won't work:

Do I need to have a major rewire operation done to get this light to work? Any suggestions or ideas?
Comment: Not a direct answer, but for cases where you have no neutral in the switch (many older installs; NEC 2011 now requires neutral at switches), there are many switches/timers/etc sold as "No neutral required". If you are faced with rewiring, simply using a different switch may be a much cheaper/easier option.
Answer: You'll need to run a grounded (neutral) conductor into the box. It sounds like the power is supplied to the fixture, and only a switch loop is run to the switch. You'll have to run a 3 conductor cable with ground (14/3 or 12/3), from the fixture to the switch.  If there is conduit between the fixture box and the switch box, you can simply pull an additional conductor.


How to display class attributes for a class object initialized in XAML

Question: I have a class Employee in a WPF Project:
class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
}

And I am creating an instance of it emp2 in my XAML file:
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:Employee x:Key="emp2" ID="20" Name="Second Employee "></local:Employee>
    </Window.Resources>
    <StackPanel>

    </StackPanel>
</Window>

However this only displays the datatype of emp2 i.e. WpfApplication1.Employee. How do I display the ID and Name of emp2
Comment: Try emp2.ID, emp2.Name
Comment: It says `The resource emp2.ID could not be resolved`
Comment: have you checked it runtime ?
Comment: It doesn't run as there is an error in the XAML file which throws an XMLParseException if we try to proceed
Answer: WPF uses the concept of DataTemplates to give you the possibility to decide how data objects should be presented. Therefore you could define a DataTemplate for the class Employee and then use a ContentControl which uses the instance of the Employee class as its Content. The DataTemplate could contain controls to show the values.
<Window.Resources>
    <local:Employee x:Key="emp2" ID="20" Name="Second Employee "></local:Employee>
    <DataTemplate DataType={x:Type local:Employee}">
        <StackPanel>
            <TextBlock Text={Binding ID} />
            <TextBlock Text={Binding Name} />
        </StackPanel>
    </DataTemplate>
</Window.Resources>
<StackPanel>
    <ContentControl Content="{StaticResource emp2}" />
</StackPanel>

Comment: You're welcome. You could use  or have a look at the control
Answer: Like this:

Or implement the ToString method override of the Employee class
public override string ToString()
{
    return string.Format("{0} {1}", Id, Name);
}

Answer: Your binding's just a wee bit off:

Answer: You have multiple options:

Use DataTemplates (MatthiasG's answer)
Quick and dirty: Implement ToString() in class Employee, simple but not very flexible.
Use StaticResource as Binding Source:
<StackPanel>

</StackPanel>


Enumerating process handles, weird issue

Question: I scan for opened handles to my process and print them in the console.

I start my process
I attach cheat engine
I run the enumeration of opened handles
I see which process has a handle to my process

The weird issue at this point is as follows, check the code:
array<Accessor^>^ AntiCheat::ScanHandles()
{
    List<Accessor^>^ accessorList = gcnew List<Accessor^>();

    if (!EnableDebugPrivilege(true))
        printf("EnableDebugPrivilege failed: %d\n", GetLastError());

    tNtQuerySystemInformation oNtQuerySystemInformation = (tNtQuerySystemInformation)GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQuerySystemInformation");

    PSYSTEM_HANDLE_INFORMATION handleInfo = new SYSTEM_HANDLE_INFORMATION;
    SYSTEM_INFORMATION_CLASS infoClass = (SYSTEM_INFORMATION_CLASS)16; // SystemHandleInformation
    DWORD size = sizeof(SYSTEM_HANDLE_INFORMATION);
    DWORD needed = 0;
    NTSTATUS status = oNtQuerySystemInformation(infoClass, handleInfo, size, &needed);
    while (!NT_SUCCESS(status))
    {
        if (needed == 0)
            return nullptr;
        // The previously supplied buffer wasn't enough.
        delete handleInfo;
        size = needed + 1024;
        handleInfo = (PSYSTEM_HANDLE_INFORMATION)new BYTE[size];
        status = oNtQuerySystemInformation(infoClass, handleInfo, size, &needed);
    }

    HANDLE currentProcess = GetCurrentProcess();
    DWORD currentProcessId = GetProcessId(currentProcess);
    for (DWORD i = 0; i < handleInfo->dwCount; i++)
    {
        //printf(".");
        SYSTEM_HANDLE handle = handleInfo->Handles[i];

        HANDLE procHandle = OpenProcess(PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, handle.dwProcessId);
        if (GetLastError() == ERROR_ACCESS_DENIED)
            continue;

        HANDLE dupl = 0;
        if (!DuplicateHandle(procHandle, (HANDLE)handle.wValue, currentProcess, &dupl, 0, false, DUPLICATE_SAME_ACCESS))
            continue;

        DWORD procId = GetProcessId(dupl);
        if (procId == currentProcessId)
        {
            printf("accessing us\n");
            char processName[MAX_PATH];
            GetModuleFileNameEx((HMODULE)procHandle, NULL, processName, MAX_PATH);
            accessorList->Add(gcnew Accessor(gcnew String(processName), handle.GrantedAccess));
        }

        CloseHandle(dupl);
    }

    return accessorList->ToArray();
}

If I uncomment the line with printf(".");, I see 3 opened handles to my process (cheatengine). If it's commented (runs way faster), there is no opened handle. However I don't know why this affects my code. Im surprised, does anyone know why this happens? Or how to find out how to find the handles without my printf("."); line?
Another issue is: each time I call the function, the number of allocated bytes duplicates. And I don't know why.
Comment: Maybe the first time calling a C IO function causes it to open handles to standard in, out, and error?
Comment: You are not ignoring array items where `handle.dwProcessId` equals `currentProcessId`, so you end up opening a new handle to your own process.  You are only interested in other processes where `handle.dwProcessId` is not equal to `currentProcessId`.
Comment: @RemyLebeau assuming the Handle is a process handle, GetProcessId gets the id of the handle, and if it equals to my process, I see its a handle to my process, which is what I'm looking for. Anyway the other problem is: The number of allocated bytes duplicate each call (NtQuerySystemInformation returns ERROR_INFO_LENGTH_MISMATCH).
Answer: I see logic problems with your code.
You are not ignoring array items where handle.dwProcessId equals currentProcessId, so you end up opening handles to your own process. Since you are only interested in looking for other processes, you should be ignoring items where handle.dwProcessId is equal to currentProcessId.
You are not checking if OpenProcess() fails for any reason other than ERROR_ACCESS_DENIED.  Do not call GetLastError() unless OpenProcess() actually returns NULL first.
You are not closing an opened handle if DuplicateHandle() fails. And why are you duplicating each source handle just to call GetProcessId() on it? You already have their process IDs from the array, so the whole DuplicateHandle()+GetProcessId() is completely unnecessary.
You are taking the wrong approach anyway.  Have a look at this discussion:
Enumerating the processes referencing an object

Use NtQuerySystemInformation with SystemInformationClass set to SystemHandleInformation. This fills in an array of SYSTEM_HANDLE_INFORMATION structures, which are defined as:
typedef struct _SYSTEM_HANDLE_INFORMATION {
    ULONG ProcessId;
    UCHAR ObjectTypeNumber;
    UCHAR Flags;
    USHORT Handle;
    PVOID Object;
    ACCESS_MASK GrantedAccess;
 } SYSTEM_HANDLE_INFORMATION;

Search for the entry corresponding to the handle you opened with ProcessID equal to GetCurrentProcessId(), then find all entries with the same Object pointer.

Although the discussion shows the wrong declaration for SYSTEM_HANDLE_INFORMATION.  The following article shows the correct one:
HOWTO: Enumerate handles

#define SystemHandleInformation 16

typedef NTSTATUS (NTAPI *_NtQuerySystemInformation)(
    ULONG SystemInformationClass,
    PVOID SystemInformation,
    ULONG SystemInformationLength,
    PULONG ReturnLength
    );

/* The following structure is actually called SYSTEM_HANDLE_TABLE_ENTRY_INFO, but SYSTEM_HANDLE is shorter. */
typedef struct _SYSTEM_HANDLE
{
    ULONG ProcessId;
    BYTE ObjectTypeNumber;
    BYTE Flags;
    USHORT Handle;
    PVOID Object;
    ACCESS_MASK GrantedAccess;
 } SYSTEM_HANDLE, *PSYSTEM_HANDLE;

typedef struct _SYSTEM_HANDLE_INFORMATION
{
  ULONG HandleCount; /* Or NumberOfHandles if you prefer. */
  SYSTEM_HANDLE Handles[1];
} SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;

With that said, try something more like this:
array<Accessor^>^ AntiCheat::ScanHandles()
{
    List<Accessor^>^ accessorList = gcnew List<Accessor^>();

    if (!EnableDebugPrivilege(true))
        printf("EnableDebugPrivilege failed: %d\n", GetLastError());

    tNtQuerySystemInformation oNtQuerySystemInformation = (tNtQuerySystemInformation) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQuerySystemInformation");

    DWORD currentProcessId = GetCurrentProcessId();
    HANDLE currentProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, currentProcessId);
    PVOID currentProcessAddr = nullptr;

    DWORD size = sizeof(SYSTEM_HANDLE_INFORMATION);
    DWORD needed = 0;
    PSYSTEM_HANDLE_INFORMATION handleInfo = (PSYSTEM_HANDLE_INFORMATION) new BYTE[size];
    SYSTEM_INFORMATION_CLASS infoClass = (SYSTEM_INFORMATION_CLASS) 16; // SystemHandleInformation
    NTSTATUS status = oNtQuerySystemInformation(infoClass, handleInfo, size, &needed);
    while (status == STATUS_INFO_LENGTH_MISMATCH)
    {
        // The previously supplied buffer wasn't enough.
        delete[] handleInfo;
        size += 1024;
        handleInfo = (PSYSTEM_HANDLE_INFORMATION) new BYTE[size];
        status = oNtQuerySystemInformation(infoClass, handleInfo, size, &needed);
    }
    if (status != 0)
    {
        delete[] handleInfo;
        return nullptr;
    }

    for (DWORD i = 0; i < handleInfo->dwCount; i++)
    {
        SYSTEM_HANDLE &handle = handleInfo->Handles[i];

        if ((handle.dwProcessId == currentProcessId) &&
            (currentProcess == (HANDLE)handle.wValue))
        {
            currentProcessAddr = handle.pAddress;
            break;
        }
    }

    for (DWORD i = 0; i < handleInfo->dwCount; i++)
    {
        SYSTEM_HANDLE &handle = handleInfo->Handles[i];

        if ((handle.dwProcessId != currentProcessId) &&
            (handle.pAddress == currentProcessAddr))
        {
            printf("accessing us\n");

            HANDLE procHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, handle.dwProcessId);
            if (procHandle != 0)
            {
                char processName[MAX_PATH+1];
                DWORD len = GetModuleFileNameEx((HMODULE)procHandle, NULL, processName, MAX_PATH);
                CloseHandle(procHandle);
                processName[len] = '\0';
                accessorList->Add(gcnew Accessor(gcnew String(processName), handle.GrantedAccess));
            }
            else
                accessorList->Add(gcnew Accessor(gcnew String("unknown"), handle.GrantedAccess));
        }
    }

    CloseHandle(currentProcess);

    delete[] handleInfo;
    return accessorList->ToArray();
}

Comment: You might want to open the handle to local process before you call NTQuerySystemInformation :)


Laravel route list returns error

Question: When i try to show list of available routes artisan returns the following error:
   $ php artisan route:list

      [ReflectionException]
      Class API does not exist

It worked a while ago but now i can't get it to work.
Laravel version is:
$ php artisan -V
Laravel Framework version 5.1.10 (LTS)

Is it possible to debug somehow this error?
Comment: Did you try clearing your compiled list?
Comment: Did you try composer dump-autoload?
Comment: yes i tried clear-compiled and composer dump-autoload. doesn't help
Answer: What's your php version ? I think, if you are under php5.5, then change the shell.
Comment: it worked with the current php version: PHP 5.6.4-4ubuntu6.2 (cli) (built: Jul  2 2015 15:29:28)
Answer: You can find what's wrong in the storage/logs/laravel-YYYY-MM-DD.log file.
Check it, resolve and run artisan again.
Comment: thanks a lot, i found unused routes. after fixing it route:list doesn't return an error.

Laravel route list returns error


Have an image be centered on mobile page view

Question: I am using a site built in mobile wrap for scroll for an area I call rafters shown on this page here.
Website URL
http://www51.myfantasyleague.com/2017/options?L=24837&F=0001&O=01
Code in use.

STYLE SHEET
@media only screen and (max-width:48.000em){
 div.mobile-wrap > center > img {
     margin:0 auto 0px -296px;
  }
}

You will see on desktop and maybe ipad view it looks nice and centered.
I am trying to achieve on iPhone view the banner to be centered when the page loads, I have it this way by added the media query -296px, however scroll this image and now look at the top dark bar, it is short on one side and very long on other site, because of this -296px..
Is there anyway to get this graphic to load center on all devices properly, while swiping left or right will have the same equal results on either side of the graphic? Not like I have it now with the -296 value.?
Maybe some more inline html code for the img scr? I have center tags there and it works nice for desktop view as it is on center.
thx
Answer: You don't need a  or media-queries for this. To have an image centered in its container, give it a padding-left: 50%; and a negative margin-left of the half of its width:

.mobile-wrap {
  overflow: hidden;
}
img {
  padding-left: 50%;
  margin-left: -425px; /* pixel value has to be half of the image width */
}

Comment: thx for this, I will run with it....I will also assume that you can get this to center on page load, but the long top bar has to be shrunk down also per this alignment, rather than the rafter and bar center on page load, and scrolling left or right would reveal equal lengths of the bar....


How to move geojson polygon in leaflet?

Question: Say I have a geojson box I've added to leaflet. How can I allow the user to "click and drag the box" to a new location, which in turn updates all the coordinates automatically? I know how to edit the boundary/points that make up the shape using leaflet editing, but am not sure how to actually move the shape.
Answer: There is a Leaflet.Draw.Drag plugin for Leaflet Draw that allows you to move polygons when you enter edit mode. It does seem to be a bit finicky about the version, though. At least in a few quick experiments, I was only able to get it to work using Leaflet Draw version 0.2.3. If you have an existing L.GeoJson layer, you can simply specify that as the featureGroup in the edit options of the draw control:
var drawControl = new L.Control.Draw({
  edit: {
    featureGroup: yourGeoJsonLayer,
    edit: {
      selectedPathOptions: {
        maintainColor: true,
        moveMarkers: true
      }
    }
  }
});

In the selectedPathOptions, the maintainColor option just keeps the existing style of the layer while you're editing, and the moveMarkers option places a little square marker in the middle of the polygon as a reminder that you can drag the whole thing rather than just edit the vertices.
Here is an example fiddle:
http://fiddle.jshell.net/nathansnider/qk5bsgn8/
Comment: '404 - That page doesn't exist.' Thats the reason why you should better provide code using stack Overflow only. :)

How to move geojson polygon in leaflet?


Swapping between Columns in excel sheet using java

Question: I am new in java. Actually I want to swap two columns in excel sheet using java. I used the code but I didn't get correct output. I add screenshot of my excel sheet. I want to swap system name and date columns.

I also add screenshot of my incorrect output. I got 24 and 29 jan 1900 instead of 1-30th sept 2016.

CellStyle cellStyle1 = workbook11.createCellStyle();
CreationHelper createHelper1 = workbook11.getCreationHelper();
cellStyle1.setDataFormat(createHelper1.createDataFormat().getFormat("d-mmm"));
try {
    if (file11.exists()) {
        String dt = sh1.getRow(0).getCell(1).getStringCellValue();
        if (!dt.equalsIgnoreCase("Date")) {
            Iterator<Row> rowIterator1 = sh1.iterator();
            while (rowIterator1.hasNext()) {
                Row row = rowIterator1.next();
                if (row.getCell(1).getStringCellValue().equalsIgnoreCase("Date")) {
                    Cell cl1 = row.getCell(0);
                    Cell cl2 = row.getCell(1);
                    Cell temp = row.getCell(0);
                    Cell temp1 = row.getCell(1);
                    cl1.setCellValue(temp1.getStringCellValue());
                    cl2.setCellValue(temp.getStringCellValue());
                } else {
                    Cell cl1 = row.getCell(0);
                    Cell cl2 = row.getCell(1);
                    cl2.setCellType(Cell.CELL_TYPE_STRING);
                    cl1.setCellType(Cell.CELL_TYPE_STRING);
                    Cell temp = row.getCell(0);
                    Cell temp1 = row.getCell(1);
                    cl1.setCellValue(temp1.getStringCellValue());
                    cl2.setCellValue(temp.getStringCellValue());
                    row.getCell(1).setCellStyle(cellStyle1);
                }
            }
        }
    }
}

Edit:
According to xenteros' answer I've tried the following:
         CellStyle cellStyle1 = workbook11.createCellStyle();
         CreationHelper createHelper1 = workbook11.getCreationHelper();
         cellStyle1.setDataFormat(createHelper1.createDataFormat().getFormat("d-mmm"));
          try {
                if (file11.exists()) {

                  String dt = sh1.getRow(0).getCell(1).getStringCellValue();
                  if (!dt.equalsIgnoreCase("Date")) {
                  Iterator<Row> rowIterator1 = sh1.iterator();
                  while (rowIterator1.hasNext()) {
                  Row row = rowIterator1.next();
                 if (row.getCell(1).getStringCellValue().equalsIgnoreCase("Date")) {
                 Cell cl1 = row.getCell(0);
                 Cell cl2 = row.getCell(1);
                 String temp = new String(cl2.getStringCellValue());
                 cl2.setCellValue(cl1.getStringCellValue());
                 cl1.setCellValue(temp);
          else {

                   Cell cl1 = row.getCell(0);
                   Cell cl2 = row.getCell(1);
                   cl2.setCellType(Cell.CELL_TYPE_STRING);
                   cl1.setCellType(Cell.CELL_TYPE_STRING);
                   String temp = new String(cl2.getStringCellValue());
                   System.out.println(temp);
                   java.util.Date temp2 = cl1.getDateCellValue();
                   cl2.setCellStyle(cellStyle1);
                   cl2.setCellValue(temp2);
                   cl1.setCellType(Cell.CELL_TYPE_STRING);
                   cl1.setCellValue(temp);
           }
}

Comment: Please indent your code properly. As it is now, the structure is hard to guess.
Comment: @RolandIllig as you might see it the edit history, I've already reformated this code twice. Hopefully The OP will leave it as it is.
Comment: Oh, C'mon! I've formatted your code so beutifuly! Why did you destroy it? What are those empty lines for?!
Comment: I have added long explanation to your code. Can You understand it? Did it help you or do you need further explanation?
Answer: You problem is basically about java references or about swap algorithm.
Memory:
+-------------+--------------------+--------+--------+
|   cell 1    |       cell 2       | cell 3 | cell 4 |
+-------------+--------------------+--------+--------+
| ["Date"...] | ["System name"...] |        |        |
+-------------+--------------------+--------+--------+

References before step 5:
+--------+-------+-------+-------+
|  cl1   |  cl2  | temp  | temp1 |
+--------+-------+-------+-------+
| cell 1 | cell2 | cell1 | cell2 |
+--------+-------+-------+-------+

Memory after step 5:
+--------------------+--------------------+--------+--------+
|       cell 1       |       cell 2       | cell 3 | cell 4 |
+--------------------+--------------------+--------+--------+
| ["System name"...] | ["System name"...] |        |        |
+--------------------+--------------------+--------+--------+
References after step 5:
+--------+-------+-------+-------+
|  cl1   |  cl2  | temp  | temp1 |
+--------+-------+-------+-------+
| cell 1 | cell2 | cell1 | cell2 |
+--------+-------+-------+-------+

1. Cell cl1 = row.getCell(0);
2. Cell cl2 = row.getCell(1);
3. Cell temp = row.getCell(0);
4. Cell temp1 = row.getCell(1);
5. cl1.setCellValue(temp1.getStringCellValue());
6. cl2.setCellValue(temp.getStringCellValue());

So... step 6 results in setting cl2 cellValue to temp's (which data is in cell1) value which is at the moment "System name".
The below will work but is unnecessary.
1. Cell cl1 = row.getCell(0);
2. Cell cl2 = row.getCell(1);
3. String temp1 = new String(cl1.getStringCellValue());
4. String temp2 = new String(cl2.getStringCellValue());
5. cl1.setCellValue(temp2);
6. cl2.setCellValue(temp1);

What you're trying to do is to swap the content of the cells. There is no need to swap cells on themselves. See what you can do:
1. Cell cl0 = row.getCell(0);
2. Cell cl1 = row.getCell(1);
3. String temp = new String(cl1.getStringValue());
4. cl1.setStringValue(cl0.getStringValue());
5. cl0.setStringValue(temp);

1. Cell cl0 = row.getCell(0);
2. Cell cl1 = row.getCell(1);
3. String temp = new String(cl1.getStringValue());
4. java.util.Date temp2 = cl0.getDateValue();
5. cl1.setCellStyle(cellStyle1);
6. cl1.setCellValue(temp2);
7. cl0.setCellType(Cell.CELL_TYPE_STRING);
8. cl0.setCellValue(temp);

Edit:
As the OP is very tough, I paste the whole code here.
try {
    if (file11.exists()) {
        String dt = sh1.getRow(0).getCell(1).getStringCellValue();
        if (!dt.equalsIgnoreCase("Date")) {
            Iterator<Row> rowIterator1 = sh1.iterator();
            while (rowIterator1.hasNext()) {
                Row row = rowIterator1.next();
                if (row.getCell(1).getStringCellValue().equalsIgnoreCase("Date")) {
                    Cell cl0 = row.getCell(0);
                    Cell cl1 = row.getCell(1);
                    String temp = new String(cl1.getStringValue());
                    cl1.setStringValue(cl0.getStringValue());
                    cl0.setStringValue(temp);
                } else {
                    Cell cl0 = row.getCell(0);
                    Cell cl1 = row.getCell(1);
                    String temp = new String(cl1.getStringValue());
                    java.util.Date temp2 = cl0.getDateValue();
                    cl1.setCellStyle(cellStyle1);
                    cl1.setCellValue(temp2);
                    cl0.setCellType(Cell.CELL_TYPE_STRING);
                    cl0.setCellValue(temp);
                }
            }
        }
    }
}

Comment: Yes. It's only for the if statement. OK, I'll give you the whole code.
Comment: @abcd I have just added working code for else statement. If it helps, please mark it as a solution and give an upvote.
Comment: Please add your current code to the question. You can [edit] it. The code should be added at the very end with a remark that it is code refering to my answer.
Comment: this code is only swap system name and date row not column. this is not swap all values. May be because of string because temp1 and temp2 are strings.
Comment: Thanks for your efforts to my problem but my code is not going to else statement . this is doing only first row swap and terminate. I don't know why?
Comment: @abcd you misschosen the if. I mean this if-else with condition `row.getCell(1).getStringCellValue().equalsIgnoreCase("Date")`.
Comment: @abcd I added the whole code for you. I'm very disgusted at the moment. You should at least upvote this answer as it's your fault that you can't copy paste my code to yours. If I were your teacher, I would punish your for plagiarism, as I don't believe you know what the code you gave us do.
Answer: I got the answer of this question.
try{
 if (file11.exists()) {
 String dt = sh1.getRow(0).getCell(1).getStringCellValue();
 if (!dt.equalsIgnoreCase("Date")) {
 Iterator<Row> rowIterator1 = sh1.iterator();
 while (rowIterator1.hasNext()) {
 Row row = rowIterator1.next();
 DataFormatter df = new DataFormatter();//instantiate DataFormatter class for reading the cell without changing the cell type
 Cell cl0 = row.getCell(0);
 Cell cl1 = row.getCell(1);
 CellStyle cs1 = cl0.getCellStyle();
 CellStyle cs2 = cl1.getCellStyle();
 String s1 = new String(df.formatCellValue(cl0));//store cell value as string
 String s2 = new String(df.formatCellValue(cl1));//store cell value as string
 cl1.setCellValue(s1);//perform swapping
 cl0.setCellStyle(cs2);
 cl1.setCellStyle(cs1);//perform swapping on formatting
 cl0.setCellValue(s2);//perform swapping
            }
        }
    } else {
        System.out.println("File does not exist..................");
    }
 }
catch (Exception e) {
        } finally {
           FileOutputStream out = new FileOutputStream(Report_File2);
    workbook11.write(out);
    out.close();
}


ASP.Net MVC routes confusion

Question: I have the following URLs for my ASP.Net MVC 2 site:
http://localhost:1919/TimeEntry/SummaryForWeek/15/2011

http://localhost:1919/TimeEntry/SummaryForMonth/4/2011

Both of these are hitting this route:
            routes.MapRoute
        (
            "TimeEntryActionMonthYear", // Route name
            "TimeEntry/{action}/{month}/{year}", // URL with parameters
            new { controller = "TimeEntry", action = "Summary", month = UrlParameter.Optional, year = UrlParameter.Optional } // Parameter defaults
        );

The action for SummaryForWeek is expecting a parameter named "weekNumber" (the 15 value in URL above) whereas the route that is being used is passing a parameter called "month" and consequently the URL for weekSummary fails.  It doesn't make sense to rename the parameter for SummaryForWeek from week to month just so the route works.
Should I add a Route to route table where {action} is hardcoded for "SummaryForWeeks"?  This doesn't make sense either as it bloats the route table.
What am I not understanding (I know this opens me up for some creative comments)?  I'm stuck.
Thanks
Tom
Comment: Binding problem: http://stackoverflow.com/questions/2743223/asp-net-mvc-routing-id-parameter/4304147#4304147
Answer: You either need two routes, or you need a more generic name for your parameters:
TimeEntry/{action}/{subdivision}/{year}

or something similar. Then both actions would have to take these two parameters, one would interpret as month, the other as week.
Comment: i think this is the route I have to take.  This sucks actually.  The processor should be able to identify the action from the URL, find the action in the controller, then start matching parameters in the order they appear in the URL to the parameter signature of the action.  This way, you don't have to worry about naming issues.  Is this the wrong way to look at it?  Thanks for your help.

ASP.Net MVC routes confusion


Create an empty 2d array

Question: I don't like uninitialized VBA arrays, since it's necessary to check if array is initialized, each time prior using UBound() or For Each to avoid an exception, and there is no native VBA function to check it. That is why I initialize arrays, at least doing them empty with a = Array(). This eliminates the need for extra check in most of cases, so there are no problems with 1d arrays.
For the same reason I tried to create an empty 2d array. It's not possible simply do ReDim a(0 To -1, 0 To 0), transpose 1d empty array or something similar. The only way I came across by chance, is to use MSForms.ComboBox, assign empty array to .List property and read it back. Here is the example, which works in Excel and Word, you need to insert UserForm to VBA Project, place ComboBox on it, and add the below code:
Private Sub ComboBox1_Change()

    Dim a()
    ComboBox1.List = Array()
    a = ComboBox1.List
    Debug.Print "1st dimension upper bound = " & UBound(a, 1)
    Debug.Print "2nd dimension upper bound = " & UBound(a, 2)

End Sub

After combo change the output is:
1st dimension upper bound = -1
2nd dimension upper bound = 0

Actually it's really the empty 2d array in debug:

Is there more elegant way to create an empty 2d array, without using ComboBox, or UserForm controls in general?
Comment: I don't know the answer, but I did find a nifty way to crash excel. I'm wondering if this affects others. Try merely writing the following line in a subroutine (save your work first): `a=Array();redim a(,0 to 0)`
Comment: You've got me playing with this now
Comment: I think this is an XY problem.  What you should be asking is _how do I easily check if an array is initialised?_  . A good solution is provided on CPearsom.com [here](http://www.cpearson.com/excel/IsArrayAllocated.aspx)
Comment: @JNevill Instant crashing!
Comment: I must admit the question itself might sound quite broad, so it easily may be treated as XY broblem. Note, I already posted the link [how to check if array is initialized](https://stackoverflow.com/q/183353/2165759), IMO `OERN`-like methods must be the last resort, and the only excuse to use them is the significant simplicity and performance against others. And the real point is about to change 2d array handling pattern and get rid of extra check. You know, "If at first the idea is not absurd, then there is no hope for it."
Comment: I farted around with this yesterday evening and came up empty. I think what has happened here is that you have stumbled into a rare situation where VBA is able to return an array with dimensions `(0 to -1, 0 to 0)` and it can't be repeated through any non-hacky way. My only other thought here was to build a custom library in C# and "reference" that in your code. That isn't a great solution though if you want to distribute this sheet and It's just a guess that you could pull this off in a custom library anyway.
Comment: What's wrong with `Dim arr(1,10) as Variant`? I'm not really understanding the question maybe =)
Comment: I need 2d array containing no elements at all. So that e. g. `For Each` loop skips.
Comment: That's reassuring. Perhaps as a workaround to an empty multidimensional array you instead write a function to test for emptiness that you can then test with an `If` before performing any code that would raise an exception on an empty array. Those are pretty easy to write and don't add much weight to your code. Either way it feels like a hack to get around stupid VBA behavior.
Comment: I just want to get rid of uninitialized arrays and consequent extra checks, and create code which would have uniform flow for any 2d array, regardless of whether it is empty or not.
Answer: This is only going to work for Windows (not for Mac):
Option Explicit

#If Mac Then
#Else
    #If VBA7 Then
        Private Declare PtrSafe Function SafeArrayCreate Lib "OleAut32.dll" (ByVal vt As Integer, ByVal cDims As Long, ByRef rgsabound As SAFEARRAYBOUND) As LongPtr
        Private Declare PtrSafe Function VariantCopy Lib "OleAut32.dll" (pvargDest As Any, pvargSrc As Any) As Long
        Private Declare PtrSafe Function SafeArrayDestroy Lib "OleAut32.dll" (ByVal psa As LongPtr) As Long
    #Else
        Private Declare Function SafeArrayCreate Lib "OleAut32.dll" (ByVal vt As Integer, ByVal cDims As Long, ByRef rgsabound As SAFEARRAYBOUND) As Long
        Private Declare Function VariantCopy Lib "OleAut32.dll" (pvargDest As Variant, pvargSrc As Any) As Long
        Private Declare Function SafeArrayDestroy Lib "OleAut32.dll" (ByVal psa As Long) As Long
    #End If
#End If

Private Type SAFEARRAYBOUND
    cElements As Long
    lLbound As Long
End Type
Private Type tagVariant
    vt As Integer
    wReserved1 As Integer
    wReserved2 As Integer
    wReserved3 As Integer
    #If VBA7 Then
        ptr As LongPtr
    #Else
        ptr As Long
    #End If
End Type

Public Function EmptyArray(ByVal numberOfDimensions As Long, ByVal vType As VbVarType) As Variant
    'In Visual Basic, you can declare arrays with up to 60 dimensions
    Const MAX_DIMENSION As Long = 60

    If numberOfDimensions < 1 Or numberOfDimensions > MAX_DIMENSION Then
        Err.Raise 5, "EmptyArray", "Invalid number of dimensions"
    End If

    #If Mac Then
        Err.Raise 298, "EmptyArray", "OleAut32.dll required"
    #Else
        Dim bounds() As SAFEARRAYBOUND
        #If VBA7 Then
            Dim ptrArray As LongPtr
        #Else
            Dim ptrArray As Long
        #End If
        Dim tVariant As tagVariant
        Dim i As Long
        '
        ReDim bounds(0 To numberOfDimensions - 1)
        '
        'Make lower dimensions [0 to 0] instead of [0 to -1]
        For i = 1 To numberOfDimensions - 1
            bounds(i).cElements = 1
        Next i
        '
        'Create empty array and store pointer
        ptrArray = SafeArrayCreate(vType, numberOfDimensions, bounds(0))
        '
        'Create a Variant pointing to the array
        tVariant.vt = vbArray + vType
        tVariant.ptr = ptrArray
        '
        'Copy result
        VariantCopy EmptyArray, tVariant
        '
        'Clean-up
        SafeArrayDestroy ptrArray
    #End If
End Function

You can now create empty arrays with different number of dimensions and data types:
Sub Test()
    Dim arr2D() As Variant
    Dim arr4D() As Double
    '
    arr2D = EmptyArray(2, vbVariant)
    arr4D = EmptyArray(4, vbDouble)
    Stop
End Sub

Update 30/09/2022
I've created an EmptyArray method (same signature) in my MemoryTools library on GitHub. That version will work on both Windows and Mac.
Answer: Idk man - I think you stumbling onto this property was pretty wild.
I'd probably stop here and just do:
Function Empty2DArray() As Variant
With CreateObject("Forms.ComboBox.1")
    .List = Array()
    Empty2DArray = .List
End With
End Function

And use it like: a = Empty2DArray
You don't need to create the userform or combobox - you can just use CreateObject.
But as others have said, it probably makes more sense to do error handling when checking whether or not your arrays are initialized.

Create an empty 2d array


How to code a loop in Java that access a 2D array using the the data stored in another 2D array that contains the adyacent positions of each position

Question: I have a function that returns all the adyacent positions of a 2D array, something like this:
public static int[][] adyacents(int rows, int columns, int offsetRow, int offsetCol) {...}

The main array and one example of the adyacent array are the following ones to put an example:
char[][] example = {
                {'A', 'B', 'C'},
                {'D', 'E', 'F'},
                {'G', 'H', 'I'}};

int[][] AdyacentsOfA = {
                {0, 1},
                {1, 0},
                {1, 1}};

The only thing I need is to make a loop to access the content of all the different adyacent positions of each position of the main array.
Comment: @OldDogProgrammer that is what the adyacents function does, it returns a [n][2] array where each n is a {row, column}, now i want to make a loop to access the positions that the [n][2] array returned in the main array and do the same for all the positions.
Comment: I can't tell from your example how the adjacent array works.  What is the output supposed to look like?
Comment: @GilbertLeBlanc The main array called "example" is wrtitted by the user in the code, the adyacents function will return a 2D array with al the adyacent positions given the array and the offsets, for example: for example[0][0] will return {{0,1}.{1,0},{1,1}}, for example[1][0] will return {{0,0}.{0,1},{1,1},{2,0}, {2,1} and so on, now i want to make a loop to access the content of each one of the adyacent positions of every position of the array.
Comment: My guess is the return is an `[2][n]` array, where each `n` is a `{row, column`} pair. `n` can have the value  2 (corner), 5 (edge), or 8 (interior).
Comment: I wouldn't use a loop at all.  The largest your adjacent array will be is 8x2.  Create the eight lines and test that each coordinate is inside the bounds with a separate method.
Comment: @WizzzStark,so edit your question and add that.
Answer: I think I understand the question.  Here's one way.
for (int i = 0; i < adyacentsOfA.length; i++) {
    int row = adyacentsOfA[i][0];
    int column = adyacentsOfA[i][1];
    char c = example[row][column];
    // Process c
 }


Local js file cannot load in springboot

Question: I write a springboot project,there is a javascript file locates at "src/main/resources/public/swagger/lib/jquery-1.8.0.min.js"
Now I want to introduce this js file in my html file,which locates at
"src/main/resources/templates/main.html"
I write  in html file
Console log:Failed to load resource: the server responded with a status of 404 ()
is there any wrong?
Thanks!
I think there is no wrong in my path,can anyone help me?
Answer: you should write it with https and full link
like this

Local js file cannot load in springboot