text:
Q: Is it possible to make atomic operations on singleton object thread safe automatically I have singleton object shared between two units operating on seperate threads.
For example,
Thread A
Singleton.getInstace().incCounter();
Thread B
Singleton.getInstance().decCounter();
Is it possible to implement this atomics to be thread safe without bothering the consumers to do it in thread safe way.
Something like
static Singleton& GetInstance() {

    std::scoped_lock lock(m_mtx);

    static Singleton* singleton = new Singleton();

    return *singleton;
}

I guess this will not work as the lock will be released after the return but incCounter and decCounter will be called without the lock.
Is it somehow possible to keep the lock active till atomic operation is completed.
Is doing a lock within the incCounter and decCounter the only solution here or in unit A and unit B only solution.

A: The current lock accomplishes nothing. A static function-local variable is required by the C++ standard to be initialized in exactly one thread. That is, the compiler will ensure that there can be no race conditions on its initialization. So the lock is protecting against something that can't happen.
You need to put a lock in the increment/decrement functions. And they need to lock the same mutex. Though perhaps they could increment/decrement an atomic variable, in which case you don't need a lock at all.
You could (but probably shouldn't) create a new type LockedSingleton which stores a reference to the singleton and a std::unique_lock. This would be what your GetInstance() returns. LockedSingleton would need to have its own increment/decrement functions which it forwards to its internal singleton reference, as well as any other interface functions.
class LockedSingleton
{
private:
  std::unique_lock<std::mutex> lock_;
  Singleton &obj_;

private: //Only friends can construct. Also, non-copyable.
  LockedSingleton(std::mutex &mtx, Singleton &obj)
    : lock_(mtx)
    , obj_(obj)
  {}

  friend Singleton& GetInstance();

public:

  void incCounter() {obj.incCounter();}
  void decCounter() {obj.decCounter();}

};

static LockedSingleton GetInstance() {
    static Singleton* singleton = new Singleton();

    return LockedSingleton(m_mtx, *singleton);
}

Note that this only works in C++17 and above, due to guaranteed elision, since LockedSingleton is non-copyable.


text:
Q: How do you require variables without a prefix I have a file with some helper functions to be used in two other files. I want to import the functions, but the way I'm used to doing this is not ideal:
helper = require('./helpers')
helper.log()
helper.ok()
...

I'd like to be able to use the functions without the helper prefix (e.g. ok()). How can I do this?
Edit: There are currently 7 helper functions, and that number may grow in the future, so specifying each function by hand seems like it defeats the purpose of using a separate file.

A: You could use object destructuring:
const {log, ok} = require('./helpers');
log();
ok();

A: Unlike ES2015, Python or other languages, you cannot export a specific function from another file and use it directly. What you can do in ES5 is to:
helper = require('./helpers')
var ok = helper.ok;

ok(...);
...

Or if you prefer oneliners:
var ok = require('./helpers').ok

That is I presume you are exporting a single object of the various functions you have in helpers.js.
Whereas in ES2015, you have to write it slightly differently.
First, your helpers.js needs to export the functions separately like this:
export function ok(args) {
  ...
}

export function log(args) {
  ...
}

Then in your main script:
import {ok, log} from './helpers';
ok(...);
log(...);

See more: https://developer.mozilla.org/en/docs/web/javascript/reference/statements/import

A: You can also use node -r ./myfunctions.js (where the argument has to be an absolute path or to start with ./), or you can run .load myfunctions.js in the REPL:
$ cat myfunctions.js
p=console.log
$ node -r ./myfunctions.js
Welcome to Node.js v18.3.0.
Type ".help" for more information.
> p(5)
5
undefined
>
$ node
Welcome to Node.js v18.3.0.
Type ".help" for more information.
> .load myfunctions.js
p=console.log

[Function: log]
> p(5)
5
undefined
$ alias node='node -r ~/myfunctions.js'
$ echo 'p(5)'>script.js
$ node script.js
5

A: Seeing as nobody has yet offered a solution that doesn't involve specifying each function you want to import, here's a solution that is perhaps not ideal, but works:
const helpers = require("./lib")
for (let k in helpers) {
    eval(`var ${k} = helpers.${k}`)
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Design considerations: Java database applications (JPA) I'm about to write a JPA based web application in Java and since it's my first time seriously working with persistent classes and databases in general, I would like to learn if I have to make specific considertions f.i. while designing the overall class structures like building it as flat as possible to keep the count of persistent classes low and the database structure simple. I really don't expect long explanations but would like to get a short overview of general considerations which might not appear to be that obvious to one who is unexperienced with database applications.
Thanks in advance.

A: You should go through this first
http://www.oracle.com/technetwork/articles/marx-jpa-087268.html

A:
general considerations which might not appear to be that obvious to
  one who is unexperienced with database applications

Using an ORM is superficially easy and transparent, but there are many small issues to consider:

*

*Object identity. Understand the root mismatch that relational database work with rows and keys, while in the object world, each object has one identity. There various ways to handle identity correctly, or incorrectly.

*Mapping Data. First understand how you map simple data types (string, number, URL, etc.). See and understand techniques to handle convertion problems (URL or string, byte or blob).

*Mapping Relations. Understand how you map relations (uni- and bi-directional), how to maintain the invariants with proper encapsulation, the issue of "orphans" objects who lost their parent, and how to map several relations to the same class differently, how to load eagerly or lazily and the link with the "N+1" select issue.

*Mapping Inheritance. Understand the mismatch between object, class, and tables. Understand how far you can support inheritance with ORM.

*Working with Sessions. Understand working with sessions: when an object is attached or detached, what's the impact on lazy loading, how to deal with optimistic locking, the link between transaction and session.
There is an abundant literature on JPA and ORM in general. The list above is just what came to my mind.
Ideally, ORM should not impose constraints on your design. However, my advice would be keep it flat and simple.

A: There is no need to make your database simpler because you're using JPA.
One of the main benefits of JPA is that it manages relationships for you.
It would be a pretty crappy API if you had to dumb down your database just to use it!
(espcially since it's typically used in a JavaEE environment)


text:
Q: IAM Policy for OpsCenter backup to S3 user Using OpsCenter 5.1.0 and trying to add S3 as a location for snapshot backups. What are the necessary permissions in AWS IAM for the opscenter user? So far, I have the following policy:
"Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListAllMyBuckets",
                "s3:GetBucketLocation"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetBucketLocation"
            ],
            "Resource": [
                "arn:aws:s3:::cassandra-bkup"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:DeleteObject",
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::cassandra-bkup/*"
            ]
        }
    ]
but backups are still failing. In opscenterd.log, the following error is seen:
WARN: Marking request af93899e-ae89-4ada-8b3b-ef93d0272d61 as failed: {'sstables': {'reporting_test': {u'cards': {'total_size': 9829, 'total_files': 6, 'done_files': 0, 'errors': [u'{:cause :unknown-destination-provider, :message "Specified provider unknown."}', u'{:cause :unknown-destination-provider, :message "Specified provider unknown."}', u'{:cause :unknown-destination-provider, :message "Specified provider unknown."}', u'{:cause :unknown-destination-provider, :message "Specified provider unknown."}', u'{:cause :unknown-destination-provider, :message "Specified provider unknown."}', u'{:cause :unknown-destination-provider, :message "Specified provider unknown."}']}, etc, etc.
Backup to local server succeeds, however.

A: After some trial and error, I found that the following policy worked
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListAllMyBuckets",
                "s3:GetBucketLocation"
            ],
            "Resource": "arn:aws:s3:::*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetBucketLocation",
                "s3:GetBucketAcl"
            ],
            "Resource": [
                "arn:aws:s3:::prod-bkup"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:DeleteObject",
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::prod-bkup/*"
            ]
        }
    ]
}
EDIT: added s3:GetBucketAcl as a required permission


text:
Q: Combine left join with commas So I've got this SQL code :
SELECT *
FROM A a1, AP ap1, P p1, M m1
LEFT JOIN F f1 ON f1.id_f = p1.f1
LEFT JOIN C c1 ON p1.c_id = c1.c_id
LEFT JOIN S s1 on p1.saison_id = s1.s_id
WHERE a1.a_type NOT IN (1)
AND a1.type_c IN (1,2)
AND ap1.a_id = a1.achats_id
AND p1.p_id = ap1.products_id
AND p1.m_id = m1.m_id
ORDER BY a_id ASC

And I get this error :
#1054 - Unknown column 'p1.f1' in 'on clause'

So I have no idea why doesn't it recognize p1.f1 on line 3. Any ideas?

A: You would simply use proper JOIN or INNER JOIN syntax:
SELECT *
FROM A a1 JOIN
     AP ap1
     ON ap1.a_id = a1.achats_id JOIN
     P p1
     ON p1.p_id = ap1.products_id JOIN
     M m1
     ON p1.m_id = m1.m_id LEFT JOIN
     F f1
     ON f1.id_f = p1.f1 LEFT JOIN
     C c1
     ON p1.c_id = c1.c_id LEFT JOIN
     S s1
     ON p1.saison_id = s1.s_id
WHERE a1.a_type NOT IN (1) AND a1.type_c IN (1, 2)
ORDER BY a1.a_id ASC;

Voila!  Problem solved.


text:
Q: example to run SSH commands in linux using perl script I'm using Net::SSH::Any to run SSH commands remotely in linux server. But It has problem with linux. From some sites I came to know I can use OpenSSH. Can anyone suggest me suitable CPAN module to use with small code? I want to supply password also through script.

A: You could use Net::OpenSSH, It loooks like it i an active module:


text:
Q: i couldn't step to the main in keil 5 during debugging i write simple counter program and compiled successfully when I try to debug it, the debugger cursor is not stepping in to the main program[[enter image description here](https://i.stack.imgur.com/a5dxZ.png)](https://i.stack.imgur.com/rVPVr.png)
keil5 debugger doesn't enter to main


text:
Q: good resource for android admob tutorial Is there anyone who has any good tutorial about admob for android apps? from registering , getting the API, placing ads in apps and paying out?
I've never dealt with admob before so I don't understand how to do it. I tried to register in admob, but looks like I need to register my apps in market before I'm able to place ads in my apps. is this really is the way?

A: *

*You don't need your app in the market to use ads in your app(for example, testing your app).  Just follow the tutorial mentioned below and test your app out with ads before submitting.

*on admob's website, click "add site/app". fill in the details that are required.  for the market URL, enter in market://details?id=your.package.name.goes.here.

*these details can be changed anytime, so don't worry about it and change when you want..

*there is no "final" process for when your app is ready to submit.  if it works while testing, nothing more needs to be done before submitting your app.

*see http://code.google.com/mobile/ads/docs/android/fundamentals.html for examples/tutorials installing the ads in your application


text:
Q: Graphics tablet monitor Bosto 22U Mini does not work on 15.04 It used to work on different installs on the very same hardware, but now it maps to both the laptop screen and the actual tablet screen. I tried using xrestrict to no degree of success, neither any kind of reinstall or upgrade made any difference. It seems to work on Kubuntu, so it seems to be an Ubuntu Unity specific problem. I just can't get used to KDE, so priority here is to solve this on Unity....
Running xinput list results on UNIPEN TABLET id=11, I tried running this on xrestrict but I do not know how to check the enter code here-c variable for the CTRC id of the monitor....

A: This sounds like the typical extended desktop 'problem' everyone has with pen devices. Actually Xinput system has a Coordinate Transformation Matrix that should be used to restrict the area of your desktop. But it's annoying to re-calculate and enter this matrix by hand every time you change your screen configuration. So just use this GUI tool here to select which screen to use with your pen or touch device:
http://wenhsinjen.github.io/ptxconf/
We just started this project so let us know if it works for you or not.  We'll fix it straight away if there is a problem.
configuration menu


text:
Q: iOS Swift Parse This query has an outstanding network connection. You have to wait until it's done for index = 1; index < 53; index++ {
        self.query.getObjectInBackgroundWithId(weekDataIDS[index]){  (allInOne: PFObject?, error: NSError?) -> Void in
    //Data comes here
    //saves a lot of colums in parse

    }
}

well i know getting object in background can't be too fast can i do something like;
Data comes and set in app, then return to for loop

A: Create multiple requests and store them all. Or, write some cloud code to do the requests in 1 shot.


text:
Q: Javascript-Jquery Geolocation and locationpicker $(function() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        $('#us2').locationpicker({
            location: {
                latitude: 41.0918692,
                longitude: 29.0602068
            },
            radius: 0,
            scrollwheel: false,
            inputBinding: {
                latitudeInput: $('#us2-lat'),
                longitudeInput: $('#us2-lon'),
                radiusInput: $('#us2-radius'),
                locationNameInput: $('#us2-address')
            }
        });
    }

    function showPosition(position) {
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;

        // Binding UI with the widget
        $('#us2').locationpicker({
            location: {
                latitude:  lat,
                longitude: lon
            },
            radius: 0,
            scrollwheel: false,
            inputBinding: {
                latitudeInput: $('#us2-lat'),
                longitudeInput: $('#us2-lon'),
                radiusInput: $('#us2-radius'),
                locationNameInput: $('#us2-address')
            }
        });
    }
});

I did this script. But I have a problem. When I open the result page and I clicked Share the Location option when it asked, Everythings fine It opens that direction on map. But When I didnt share the location It dont show map becouse of it cant find coordinates. When people dont share their location I want to set this coordinates latitude:  41.0918692 , longitude: 29.0602068 as you can see at the code. But I think if(navigator.geolocation) code doesnt work.


text:
Q: Getting ngmodel value out of duplicated forms Excuse me if this a silly question,but I have tried so much. I have a two form fields which duplicate with add button. So here I am trying to access the input from value formfield using ngmodel. But when I duplicate the set of formfield using add button. The input which I entered in the value form field repeats when I click the add button. This happens when I am using ngmodel to get value. Is there any other way to solve this? Comment down if u have any doubts regarding the question
My sample code: https://codesandbox.io/s/formarraydynamic-forked-t7y9u?file=/src/app/app.component.ts

A: To get the value from Form and show it in UI. You can create a getter property in component which will return the value from that particular field like this.
get values() {
    return this.myForm.value.map(x => x.value);
};

Add then bind this variable into your UI like this.

result:{{values}}

As your form is an formArray you will get your result in an array type.


text:
Q: How to prove this trigonometric identity? $$\sum_{k=1}^n\frac{1}{\displaystyle \sin^4\left(\frac{k\pi}{2n+1}\right)}=\frac8{45}n(n+1)(n^2+n+3)$$
I think it maybe use
$\cos(nx)+i\sin(nx) = \displaystyle\sum_{k=0}^n\binom nki^k(\sin^kx)(\cos^{n-k}x)$.
 But I can't .

A: From this, $$\sin(2n+1)x$$
$$=(2n+1)s-\frac{(2n+1)\{(2n+1)^2-1^2\}}{3!}s^3+\frac{(2n+1)\{(2n+1)^2-1^2\}\{(2n+1)^2-3^2\}}{5!}s^5+\cdots+(-1)^n2^{2n}s^{2n+1}$$
If $\displaystyle\sin(2n+1)x=0,(2n+1)x=k\pi$ where $k$ is any integer
$\displaystyle\implies x=\frac{k\pi}{2n+1}$ where $-n\le k\le n$
So,  $\displaystyle\sin\frac{k\pi}{2n+1},-n\le k\le n$ are the roots of $$(2n+1)s-\frac{(2n+1)\{(2n+1)^2-1^2\}}{3!}s^3+\frac{(2n+1)\{(2n+1)^2-1^2\}\{(2n+1)^2-3^2\}}{5!}s^5+\cdots+(-1)^n2^{2n}s^{2n+1}=0$$
So,  $\displaystyle\sin\frac{k\pi}{2n+1},-n\le k\le n,k\ne0$ are the roots of $$(2n+1)-\frac{(2n+1)\{(2n+1)^2-1^2\}}{3!}s^2+\frac{(2n+1)\{(2n+1)^2-1^2\}\{(2n+1)^2-3^2\}}{5!}s^4+\cdots+(-1)^n2^{2n}s^{2n}=0$$
If we set $\displaystyle\sin^2\frac{k\pi}{2n+1}=\frac1{y_k},1\le k\le n$
$y_k$ will be roots of $$(2n+1)-\frac{(2n+1)\{(2n+1)^2-1^2\}}{3!}\frac1t+\frac{(2n+1)\{(2n+1)^2-1^2\}\{(2n+1)^2-3^2\}}{5!}\frac1{t^2}+\cdots+(-1)^n2^{2n}\frac1{t^n}=0$$
$$\iff t^n(2n+1)-\frac{(2n+1)\{(2n+1)^2-1^2\}}{3!}t^{n-1}+\frac{(2n+1)\{(2n+1)^2-1^2\}\{(2n+1)^2-3^2\}}{5!}t^{n-2}+\cdots+(-1)^n2^{2n}=0$$
Now, we need $\displaystyle\sum_{k=1}^ny_k^2=\left(\sum_{k=1}^n y_k\right)^2-2\sum_{i,j=1,i\ne j}^ny_iy_j$ which can be safely managed by Vieta's Formula


text:
Q: Solve $\ln(4x) = x$ using the Banach contraction theorem I would like to find a solution of:
\begin{equation}
\ln(4x) = x
\end{equation}
My idea was to use the Banach contraction theorem: "If $E$ is a closed non empty set in a Banach space $V$ and $T: E \rightarrow E$ a contraction of constant $\alpha$, then $T$ has only one fixed point $\tilde{x}$ and $\forall x \in E: T^n(x) \rightarrow \tilde x$ for $n \rightarrow +\infty$ and $T^n(x) = T \circ T \circ T \circ \dots \circ T$ $n$ times".
Let's work in $E \equiv \mathbb{R} \ \cap \ [1.1, 3]$, with functions $f: E \rightarrow E$ such as $||f(x)||_E \equiv |f(x)| = f(x)$ in our $E$.
We also define $T: E \rightarrow E: x \mapsto T(x) = \ln(4x)$. Here are $y = x$ and $y = T(x)$ drawn below with Geogebra:

We see that $T$ has a fixed point between $x=2$ and $x=3$, but let's prove it:

*

*$E$ is a non empty closed space;

*$V$ defined by functions from $E$ to $E$ with the norm $||f(x)||_E$ is a Banach space (as $\mathbb{R}$ is a Banach space itself);

*$T(x) \equiv \ln(4x)$ is a contraction: let $x, x' \in E$:

$$||\ln(4x) - \ln(4x')||_E \le \alpha ||x - x'||_E$$
$$\Longleftrightarrow \ln\left(\frac{x}{x'}\right) \le \alpha( x - x')$$
I'm not sure how to prove the end of that part, but as $\frac{\partial \ln(x)}{\partial x} < \frac{\partial x}{\partial x}$ in $E$, I believe this is correct.
Now:
$$T^\infty(x) = \ln(4\ln(4\ln(4\ln(4\ln(4\ln(4 \dots $$
I don't know how to finish this.
Could someone help me finishing this, and occasionnaly help me proving $\ln(4x)$ is contractant please ? Unless it isn't ?


text:
Q: Rails Devise Login 401 Unauthorized What I am trying to do
I am trying to set up the Authentication with Devise in the Session Controller, methods new and create.
I am using Rails 5 and I customized the View new.html.erb.
What is the problem
I am not able to authenticate successfully after signing out from the Account. The problem is connected with the sign_in_params hash, which is passed blank to the new method of the session_controller
Testing of the functionality
I conducted a test of the Login, by including a breakpoint in my Account::SessionsController, I noticed that the sign_in_params hash was blank, then the program exits with 401 Unauthorized.
     8: def new
     9:   self.resource = resource_class.new(sign_in_params)
 => 10:   clean_up_passwords(resource)
    11:   yield resource if block_given?
    12:   respond_with(resource, serialize_options(resource))
    13: end

sign_in_params => {}

My Code
I was able by resetting my code to identify the cause of my problem. It is connected to the custom Devise View that I modified in app/views/devise/sessions/new.html.erb
This is the code:
<form class="login-form" action="index.html">

  <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

        <%= f.email_field :email, autofocus: true, :class => "form-control", :placeholder => "Username" %>

          <%= f.password_field :password, autocomplete: "off", :class => "form-control", :placeholder => "Password" %>

      <% if devise_mapping.rememberable? -%>

          <%= f.check_box :remember_me %>
          <%= f.label :remember_me, :class => "remember_me_Label" %>
           <%= link_to "Forgot Password?", {}, :id => "lostPw" %>

      <% end -%>
      <%= f.submit "Login", :class => "btn btn-primary btn-lg btn-block" %>
      <%= link_to "Signup", new_account_registration_path, :method => :get, class: "btn btn-info btn-lg btn-block signuptext" %>
      <% end %>

</form>

In the log, I have the following important informations, but no errors:
Started GET "/account/index.html?utf8=%E2%9C%93&authenticity_token=s1aA%2FNcZo1HIkF1qJOlrIAlM9rJM3y1ced8tQLiWnGsSugBVs0AYKVJR8QLa1I%2BT500sYu7H1%2BPQ2UwH3JG2ew%3D%3D&account%5Bemail%5D=test%40email.com&account%5Bpassword%5D=[FILTERED]&account%5Bremember_me%5D=0&commit=Login" for 127.0.0.1 at 2017-02-06 19:16:04 +0100 (pid:8311)
2017-02-06 19:16:04.557 [fyi] Processing by AccountController#index as HTML (pid:8311)
2017-02-06 19:16:04.557 [fyi] Parameters: {"utf8"=>"✓", "authenticity_token"=>"s1aA/NcZo1HIkF1qJOlrIAlM9rJM3y1ced8tQLiWnGsSugBVs0AYKVJR8QLa1I+T500sYu7H1+PQ2UwH3JG2ew==", "account"=>{"email"=>"test@email.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Login"} (pid:8311)
2017-02-06 19:16:04.558 [fyi] Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms) (pid:8311)

Following is the solution of the problem
Thanks
Fabrizio Bertoglio

A: Solution
The problem is in the html code of new.html.erb, as I did not remove the html <form> tags from the html and this would cause problems with my <%= form_for > <% end %> rails tag. This is the reason why strong_params is empty.
The form was not submitting any value to the controller, the problem could have been easily discovered by debugging directly the new.html.erb view instead of the controller.
Was helpful having the input from Max, that suggested me to restart all over with Devise, so that I could understand that the problem was connected with the form and not with rails strong parameters.
This is the correct new.html.erb.
<%= form_for(resource, as: resource_name, url: session_path(resource_name), html: { class: "login-form"}) do |f| %>

      <%#= f.label :email %>
      <%= f.email_field :email, autofocus: true, :class => "form-control", :placeholder => "Username" %>

        <%#= f.label :password %>
        <%= f.password_field :password, autocomplete: "off", :class => "form-control", :placeholder => "Password" %>

    <% if devise_mapping.rememberable? -%>

        <%= f.check_box :remember_me %>
        <%= f.label :remember_me, :class => "remember_me_Label" %>
         <%= link_to "Forgot Password?", {}, :id => "lostPw" %>

    <% end -%>
    <%= f.submit "Login", :class => "btn btn-primary btn-lg btn-block" %>
    <%= link_to "Signup", new_registration_path(resource_name), :method => :get, class: "btn btn-info btn-lg btn-block signuptext" %>

    <%= render "devise/shared/links2" %>

<% end %>

            Business Bootstrap Themes by BootstrapMade


text:
Q: Excel XLSM File issue I have created a Macro enabled workbook with a single worksheet for collecting specific data. The VBA project is password protected and also the worksheet is password protected. Size of the file is about 3 Mb.
Now the data is collected from about 20 team members. I am preparing a summary sheet and trying to get all the individual sheets into one workbook.
Move or copy workbook is causing Excel to hang.
Any ideas will be appreciated.
Here is the code in the workbook:
Sub Open_SA()
' Open_SA Macro
' Open Appraisal Form for Self Appraisal
'Get Password
Dim MyPassword As String
MyPassword = "********"
If InputBox("You are not authorized. Please enter password to continue.", "Enter Password") <> MyPassword Then
    Exit Sub
    End If

'Unlock Sheet
Sheets(1).Select
ActiveSheet.Unprotect Password:="********"

'Lock and hide all cells
Cells.Select
Selection.Locked = True
Selection.FormulaHidden = True

'Select SA related cells and Unlock
Range("C6:Z14,C17:Z25,C28:Z36,C39:Z47,W55:X60,W64:X75,W79:X81,A87:H87").Select

Selection.Locked = False
Selection.FormulaHidden = False

'Select L1 related cells and change the font color to background color
Range( _
    "AB7:AD9,AB18:AD20,AB29:AD31,AB40:AD42,Z55:AA60,Z64:AA75,Z79:AA81,L87:S87"). _
    Select

With Selection.Font
    .ThemeColor = xlThemeColorAccent1
    .TintAndShade = 0.599993896298105
End With

'Select L2 related cells and change the font color to background color
Range( _
    "AB12:AD14,AB23:AD25,AB34:AD36,AB45:AD47,AC55:AD60,AC64:AD75,AC79:AD81,W87:AD87"). _
    Select

With Selection.Font
    .ThemeColor = xlThemeColorAccent4
    .TintAndShade = 0.599993896298105
End With

'Hide Evaluation Cells
Range("AF85:AM93").Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
Selection.Borders(xlEdgeLeft).LineStyle = xlNone
Selection.Borders(xlEdgeTop).LineStyle = xlNone
Selection.Borders(xlEdgeBottom).LineStyle = xlNone
Selection.Borders(xlEdgeRight).LineStyle = xlNone
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
With Selection.Font
    .ThemeColor = xlThemeColorDark1
    .TintAndShade = 0
End With

'Activate specific cell range
Range("C6:Z6").Select

'Lock Sheet
Sheets(1).Select
ActiveSheet.Protect Password:="********", DrawingObjects:=True, Contents:=True, Scenarios:= _
    True

'Save workbook
ActiveWorkbook.Save

End Sub

This is one of the modules. There are similar 4 modules.
Another module:
Sub Open_L1()
' Open_L1 Macro
' Open Appraisal Form for L1 Rating
'Get Password
Dim MyPassword As String
MyPassword = "********"
If InputBox("You are not authorized. Please enter password to continue.", "Enter Password") <> MyPassword Then
    Exit Sub
    End If

'Unlock Sheet
Sheets(1).Select
ActiveSheet.Unprotect Password:="********"

'Lock and hide all cells
Cells.Select
Selection.Locked = True
Selection.FormulaHidden = True

'Select L1 related cells, Unlock cells and Set font color to automatic
Range( _
    "AB7:AD9,AB18:AD20,AB29:AD31,AB40:AD42,Z55:AA60,Z64:AA75,Z79:AA81,L87:S87"). _
    Select

Selection.Locked = False
Selection.FormulaHidden = True

With Selection.Font
    .ColorIndex = xlAutomatic
    .TintAndShade = 0
End With

'Select L2 related cells and change the font color to background color
Range( _
    "AB12:AD14,AB23:AD25,AB34:AD36,AB45:AD47,AC55:AD60,AC64:AD75,AC79:AD81,W87:AD87"). _
    Select
With Selection.Font
    .ThemeColor = xlThemeColorAccent4
    .TintAndShade = 0.599993896298105
End With

'Hide Evaluation Cells
Range("AF85:AM93").Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
Selection.Borders(xlEdgeLeft).LineStyle = xlNone
Selection.Borders(xlEdgeTop).LineStyle = xlNone
Selection.Borders(xlEdgeBottom).LineStyle = xlNone
Selection.Borders(xlEdgeRight).LineStyle = xlNone
Selection.Borders(xlInsideVertical).LineStyle = xlNone
Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
With Selection.Font
    .ThemeColor = xlThemeColorDark1
    .TintAndShade = 0
End With

'Activate specific cell range
Range("AB7:AD9").Select

'Lock Sheet
Sheets(1).Select
ActiveSheet.Protect Password:="********", DrawingObjects:=False, Contents:=True, Scenarios:= _
    False

'Save workbook
ActiveWorkbook.Save

End Sub

This is step 2.
Other modules also do the same.
The general structure is:
 1. Get Password
 2. Unlock the sheet
 3. Select specific range of cells and perform an action like Make them visible, Change Font color or Make them hidden
 4. Lock the Sheet
 5. Save the workbook.


text:
Q: Gaussian Probability Distribution? The uncertainty principle states that,
$$\sigma _{{x}}\sigma _{{p}}\geq {\frac {\hbar }{2}}.$$
It is mentioned from many sources that the probability distribution of the particle position and momentum would follow a Gaussian distribution.
Why is it a Gaussian distribution? is this the distribution that minimizes uncertainty? Is this distribution definitely the case for the uncertainty principle or can it be different under different conditions? Has this been proven?
What are the formulas for position and momentum probability distributions of a free particle? How is this derived from the wave function? What would be the formulas of the probability distributions for the position and momentum for a system of 2 identical bosons separated by a distance $R$?

A: I believe this can be attributed to the central limit theorem, which states that a large number of samples from a population with a well-defined variance will follow a gaussian distribution. The key idea is that because of quantum mechanics, we must treat both position and momentum as random variables; the uncertainty principle gives us a relation between the variance of the two quantities.
We cannot talk about the "formula for position" per se; however we can derive a deterministic formula for the wavefunction, which represents the probability density for these random variables. The exact form of the wavefunction is dependent on the problem, but can (in principle) generally be obtained from the Schrödinger equation.
Wikipedia has a good writeup for the free particle. The Hamiltonian for a free particle with fixed momentum $\mathbf{p}$ is $\mathcal{H} = \mathbf{p}^2/2m$ (the potential is zero). Eigenstates of this Hamiltonian are plane-waves in position-space (that is, their wavefunctions oscillate throughout space and time):
$$
\psi(\mathbf{x}, t) = Ae^{i(\mathbf{x}\cdot\mathbf{p}-Et)/\hbar}
$$
that means that the probability distribution is simply:
$$
\left|\psi(\mathbf{x},t)\right|^2 = \left|A\right|^2
$$
which is a constant independent of position $\mathbf{x}$. Note that this wavefunction cannot be renormalized to unity, but the takeaway is that the particle is equally likely to be anywhere. This is consistent with the uncertainty princple: since we specified $\mathbf{p}$ exactly ($\sigma_p=0$), the uncertainty in position is infinite.
For more complex systems, the Hamiltonian is not always exactly known; this is often the case in multi-particle systems, such as atoms. In still other cases, the Hamiltonian is known but cannot be solved analytically.

A: It is not correct that the probability distribution of $x$ and $p$ are Gaussian in general.
Take a simple system of a particle moving in some potential $V(x)$.
The probability distribution of $x$ is the square of the wave-function $\Psi(x)$ of the particle, i.e. the probability of finding your particle in $[x,x+dx]$ is $|\Psi(x)|^2dx$.
The probability distribution of $p$ is the square of the momentum-space wave-function $\Psi(p) = \int dx \Psi(x) e^{ipx}$ (the Fourier transform of $\Psi(x)$).
It is only when the wave-function $\Psi(x)$ is a Gaussian that the uncertainty principle is minimized, i.e. $\sigma_x \sigma_p = \frac{\hbar}{2}$. See (http://en.wikipedia.org/wiki/Fourier_transform#Uncertainty_principle) for a proof that $\frac{\hbar}{2}$ is the lower limit.
Now why exactly the Gaussian?  To minimize the uncertainty product we need a wave-function that is sufficiently well localized both in both real space and Fourier space. If we squeeze a function in real space and it broadens in Fourier space and vice versa. The Gaussian happens to be the unique function that maintains its 'shape' when Fourier transformed, i.e. the Fourier transform of a Gaussian (with variance $\sigma^2$) is just another Gaussian (with variance $1/(4\sigma^2)$) and the product of variance (uncertainty) remains a constant independent of $\sigma$.
Finally, there exist many systems where the uncertainty principle is not minimized. The simplest example is a 'particle in a box' (http://en.wikipedia.org/wiki/Particle_in_a_box). Here the ground state has $\sigma_x\sigma_p = \frac{\hbar}{2} \times \sqrt{\frac{\pi^2}{3}-2}$


text:
Q: How to summarise weighted data Is there a possibility to use weights with dplyr:
summarise

function?
Let us imagine I want to calculate a weighted table
dta = structure(list(PHHWT14 = c(530, 457, 416, 497, 395, 480, 383,
                       420, 499, 424, 504, 497, 449, 406, 492, 470, 418, 407, 403, 362,
                       393, 368, 423, 448, 511, 511, 423, 470, 453, 429, 439, 425, 431,
                       443, 480, 452, 472, 406, 460, 436, 574, 456, 399, 476, 423, 501,
                       399, 459, 396, 409, 423, 399, 383, 433, 436, 413, 403, 414, 410,
                       337, 472, 448, 487, 442, 475, 410, 478, 483, 374, 414, 514, 422,
                       409, 455, 464, 362, 461, 356, 464, 456, 494, 348, 464, 432, 398,
                       426, 418, 429, 516, 363, 455, 413, 388, 508, 381, 439, 330, 385,
                       393, 454), SEX = structure(c(2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L,
                                                    2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L,
                                                    2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
                                                    2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L,
                                                    2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L,
                                                    2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L,
                                                    2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("Female",  "Male"), class = "factor")), row.names = c(NA, 100L), class = "data.frame", .Names = c("PHHWT14",  "SEX"))

Using xtabs:
xtabs(PHHWT14 ~ SEX, dta)

I will get:
SEX
Female   Male
10115  33490

Is there a way to use summarise with weights?
dta %>%
group_by(SEX) %>%
summarise(n())

A: dta %>% group_by(SEX) %>%
  summarise(sum(PHHWT14))

#         SEX sum(PHHWT14)
#    1 Female        10115
#    2   Male        33490

A: You can also use summarise_each. For your example that is the same as the summarise version, but if you have additional columns you would like to summarise, it is very helpful.
dta %>%
  group_by(SEX) %>%
  summarise_each(funs(sum))
## Source: local data frame [2 x 2]
##
##     SEX PHHWT14
## 1 Female   10115
## 2   Male   33490

A: What you meant is grouping by variable, but you can also adjust by weights.
In general if you have a numeric weights variable or grossing up factor you can add additional arguments to the sum() function using dot:
Try this with iris df using dplyr:
library(dplyr)
set.seed(1234)
df <- iris
df[,"weights"] <- rnorm(nrow(df),1,0.1 ) # generate randomized weights
head(df)

df %>%
  group_by(Species) %>%
  summarise_each(funs(sum(. * weights , na.rm = TRUE),  # Weighted Sum
                      weighted.mean(.,w = weights, na.rm = TRUE))) -> agg.df # Weighted Mean

agg.df


text:
Q: Shorter, easier and more effective way of saving data? Thanks to this great community, I managed to make a save system for my game! However, it is kind of long and painful to write. I need help on how to (if possible) make this a little bit shorter and easier.
So, this is what I got (this example uses ONLY 1 variable to get the idea):
GameState = loadsave.loadTable("GameState.json")

if GameState == nil then
    GameState = {
        TotalPixoosGS = 0,
    }

    loadsave.saveTable(GameState, "GameState.json")
end

TotalPixoos = GameState.TotalPixoosGS

Let me quickly explain what I got here: GameState = loadsave.loadTable("GameState.json") is declaration of a table from .json file. I used .loadTable function which I got from here:
https://code.coronalabs.com/code/easy-saveload-table-data-corona-sdk
if GameState == nil then
        GameState = {
            TotalPixoosGS = 0,
        }

If the file doesn't exist, it simply creates default game settings, in this case sets TotalPixoosGS variable to value of 0.
loadsave.saveTable(GameState, "GameState.json")

Again a function from the link above which simply creates .json file from GameState table, calls it GameState.json.
TotalPixoos = GameState.TotalPixoosGS

Finally, assigns the value of GameState.TotalPixoosGS to our variable TotalPixoos (if GameState.json doesn't exist, it will assign the value of 0). So far, pretty straight-forward, right?
Now, this code was called upon OPENING the application.
The following code is what I use upon EXITING application:
if ( event.type == "applicationExit" ) then
      GameState = {
            TotalPixoosGS = TotalPixoos,
      }

      loadsave.saveTable(GameState, "GameState.json")
end

Basically, what this does is: When the app is about to exit, you simply change the value of TotalPixoosGS to our current value of TotalPixoos (that is the variable which changes over time). Finally, we save the GameState table with the new, changed TotalPixoosGS.
Once the app launches again, the process will repeat.
Now, what is the problem? Well, when you have 1 variable, like in this case, it looks simple. However, when you gotta manage over 50 variables, it can be a pain to write. Is there any way I could shorten this?
Anyway, this is just a small chunk of code, to get the idea:
GameState = loadsave.loadTable("GameState.json")

if GameState == nil then
    GameState = {
        TotalPixoosGS = 0,
        PixoosQuantityGS = 0,
        PixoosPerSecondGS = 0,

        BottlesQuantityGS = 0,
        MaxBottlesFoundGS = 0,
        BottlesPriceGS = 0.005,
        WillFindBottlesChanceGS = 10,
        CanFindBottlesGS = 0,

        MaxClickableGS = 5,
        MaxTrashCanValueGS = 5,
    }

    loadsave.saveTable(GameState, "GameState.json")
end

TotalPixoos = GameState.TotalPixoosGS
PixoosQuantity = GameState.PixoosQuantityGS
PixoosPerSecond = GameState.PixoosPerSecondGS

BottlesQuantity = GameState.BottlesQuantityGS
MaxBottlesFound = GameState.MaxBottlesFoundGS
BottlesPrice = GameState.BottlesPriceGS
WillFindBottlesChance = GameState.WillFindBottlesChanceGS
CanFindBottles = GameState.CanFindBottlesGS

MaxClickable = GameState.MaxClickableGS
MaxTrashCanValue = GameState.MaxTrashCanValueGS

See how much of ugly code there is? And this is upon exit:
if ( event.type == "applicationExit" ) then
      GameState = {
            TotalPixoosGS = TotalPixoos,
            PixoosQuantityGS = PixoosQuantity,
            PixoosPerSecondGS = PixoosPerSecond,

            BottlesQuantityGS = BottlesQuantity,
            MaxBottlesFoundGS = MaxBottlesFound,
            BottlesPriceGS = BottlesPrice,
            WillFindBottlesChanceGS = WillFindBottlesChance,
            CanFindBottlesGS = CanFindBottles,

            MaxClickableGS = MaxClickable,
            MaxTrashCanValueGS = MaxTrashCanValue,

       }

       loadsave.saveTable(GameState, "GameState.json")
end

Anyone with a better way, or idea on how to deal with this?

A: The problem here is that you are storing the data in independent global variables that you need to store in the table to save and then fetch from the table to load.
You can avoid needing to do all of that if you just use the table itself as the global variable in your general code.
So instead of writing code that uses TotalPixoosGS or PixoosQuantityGS when checking the values/etc. you write code that uses GameState.TotalPixoosGS and GameState.PixoosQuantityGS instead and then just save and load directly from/to the global GameState table.


text:
Q: Start http web server then open browser I'm trying to start a simple HTTP server then open it in the default browser. I don't know what I'm doing wrong, it's either not starting the server at all, or it's stopping as soon as it gets to the end of the script (isn't it supposed to run forever?).
import BaseHTTPServer, SimpleHTTPServer, webbrowser, thread
def start_server():
  httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 3600), SimpleHTTPServer.SimpleHTTPRequestHandler)
  httpd.serve_forever()
thread.start_new_thread(start_server,())
url = 'http://127.0.0.1:3600'
webbrowser.open_new(url)

A: A thread continues to exist as long as the application continues to run, in the case webbrowser.open_new() is not blocking so the browser will hardly finish running the application, what you should do is make a blocker to prevent the application finish of execute:
import sys
import thread
import webbrowser
import time

import BaseHTTPServer, SimpleHTTPServer

def start_server():
    httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 3600), SimpleHTTPServer.SimpleHTTPRequestHandler)
    httpd.serve_forever()

thread.start_new_thread(start_server,())
url = 'http://127.0.0.1:3600'
webbrowser.open_new(url)

while True:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        sys.exit(0)

A: Here is a Python 3 version of the answer by @eyllanesc using the newer http.server and the threading module
import sys
import time
import threading
import webbrowser
from http.server import HTTPServer, SimpleHTTPRequestHandler

ip = "127.0.0.1"
port = 3600
url = f"http://{ip}:{port}"

def start_server():
    server_address = (ip, port)
    httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
    httpd.serve_forever()

threading.Thread(target=start_server).start()
webbrowser.open_new(url)

while True:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        sys.exit(0)


text:
Q: Can't change linux user password with php script I have the following php script for password change:
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set('display_error', true);
$cmd = 'sudo -u root sh -c \'/usr/bin/echo "username:pass" | sudo /usr/sbin/chpasswd 2>&1\'';
exec($cmd,$output,$return_val);
print_r($output);
echo $return_val;
?>

This script show error in browser:
pam_chauthtok() failed, error: [1] => Authentication token lock busy [2] => chpasswd

But the command
sudo -u root sh -c '/usr/bin/echo "username:pass" | sudo /usr/sbin/chpasswd 2>&1'

work fine.
Can please someone give me a tip, why I get in browser the error above?
Filesystem is in rw mode. Files /etc/{passwd,shadow} have a correct permissions
Thank you in advance

A: The solution was to comment out ProtectSystem=full in php-fpm.service unit:
# Mounts the /usr, /boot, and /etc directories read-only for processes invoked by this unit.
#ProtectSystem=full

A: Browser php runs using www-data user
Add permissions for www-data to use sudo through shell using visudo command and append this line
www-data   ALL=(ALL:ALL) ALL

Its' syntax is
user    hosts=(users:groups)    commands


text:
Q: git cloning in jenkins fatal: The remote end hung up unexpectedly I couldn't clone the git repo in jenkins. The installed git version is 1.7.10. And also I configure the ssh key in the user directory. Using the same configuration, I could clone the git from command line and also in git bash.
But when I tried the same command from jenkins "Execute window batch command" the job failed with an error: fatal: The remote end hung up unexpectedly
C:\JenkinsSlave\workspace\ClonePath>git clone git@giturl.git
Cloning into 'gitrepo'...
fatal: The remote end hung up unexpectedly
Build step 'Execute Windows batch command' marked build as failure
Notifying upstream projects of job completion
Finished: FAILURE

A: I doubt your Jenkins job is running under the user account you think it is. But in any case cloning from the read only resource location is what you would do for most build servers. Try this instead:
git clone git://giturl.git


text:
Q: Динамическое содержимое на страницах битрикса Привет!
Нужно сделать, чтобы на странице выводились, к примеру, автомобиль, описание, а справа - характеристики: мощность, объём двигателя и т.д. Это можно сделать просто страницей и постоянно правый блок с характеристиками верстать. Но это безумно неудобно. Хотелось бы сделать так: чтобы была кнопка типа "Добавить машину", там вводишь характиристики (заранее уже созданы кастомные поля), и машина появлялась в каталоге.
Через какую функцию это делается? Я думаю, надо дейстовать через инфоблоки, я прав? Просто хочу сделать всё по стандартам.
A: Доброго времени суток, @iproger. Прочитал Ваш вопрос и создалось ощущение, что вы мало ознакомились с документацией Битрикса, раз даже задаете такие вопросы:

Через какую функцию это делается?
Я думаю, надо дейстовать через
инфоблоки, я прав?

Ответ такой мой. Конечно, лучше всего делать через инфоблоки. Ссылка на документацию инфоблоков. Если Вы внимательно прочитаете все, что там написано, то, думаю, сразу поймете, как оптимально сделать это. Поля-характеристики машины скорее всего будут пользовательскими полями, потому прочитайте про работу с инфоблоками средствами API.
Можете еще поискать видеоуроки по Битриксу, при работе с инфоблоками, чтобы понять лучше, как выводить данные. Поисковики Вам в помощь.


text:
Q: Bootstrap Hover slideUp slideDown Animation I use this code to make bootstrap dropdown show when mouse hover
var bMobile;  // true if in mobile mode

// Initiate event handlers
function init() {
    "use strict";
    // .navbar-toggle is only visible in mobile mode
    bMobile = $('.navbar-toggle').is(':visible');
    var oMenus = $('.navbar-nav .dropdown'),
        nTimer;
    if (bMobile) {
        // Disable hover events for mobile
        oMenus.off();
    } else {
        oMenus.on({
            'mouseenter touchstart': function(){
                event.preventDefault();
                clearTimeout(nTimer);
                oMenus.removeClass('open');
                $(this).addClass('open');
            },
            'mouseleave': function() {
                nTimer = setTimeout(function() {
                  oMenus.removeClass('open');
                }, 500);
            }
        });
  }
}
$(document).ready(function() {
  // Your other code to run on DOM ready...
  init();
});

$(window).resize(init);

I use this code to remove hover effect from small screens and work on big screens
How can make this code slide animation ?
and if there is code better than this code please add it in comment
I am bad in English, sorry :)

A: I recommend using the http://daneden.github.io/animate.css/ project, and adding the css class you want, i'll try to throw together a quick example
Here's a quick and dirty demo
$($(this).find(".dropdown-menu")[0]).addClass('bounceInUp animated');

http://jsfiddle.net/L8nz8zk2/1/

A: you would want to use something like this to handle the mouse events (no need for the $.on()):
http://api.jquery.com/hover/
so your code would look something like this.
$('CSS SELECTOR OF THE ITEM TO HOVER OVER').hover(function(){
   $('CSS SELECTOR OF THE ITEM THAT NEEDS TO SLIDE DOWN').slideDown();
},function(){
   $('CSS SELECTOR OF THE ITEM THAT NEEDS TO SLIDE UP').slideUp();
});

The Jquery animation of slideDown() and slideUp() is what you're looking for, and this combined with the .hover() jquery event handler should be able to give you what you need.
you can lose the .on() calls.


text:
Q: Hiding an option if its selected in the other select box JavaScript I want to hide the option in the selection box if the option is already selected in another box. I am not sure where the problem is in my code, I tried running it on different editors it didn't work. Here is my code:

    <title>Currency Converter</title>

      <select id="country1" onchange="CheckDropDowns()">
        <option value="">Choose</option>
        <option value="1">Australia</option>
        <option value="2">Indonesian Rupiah</option>
        <option value="3">Chinese Yaun</option>
        <option value="4">Japanese Yen</option>
      </select>
      Convert to
      <select id="country2" onchange="CheckDropDowns()">
        <option value="">Choose</option>
        <option value="1">Australia</option>
        <option value="2">Indonesian Rupiah</option>
        <option value="3">Chinese Yaun</option>
        <option value="4">Japanese Yen</option>
      </select>

A: First determine which select needs to be filtered, then loop through the options setting display to block first(to undo the previous filter), and then if the option's value matches the selected value set it's display to none.
Edit
Above method does not work in every browser. The better HTML5 way is to set and remove the hidden attribute. I've updated the snippet.

window.CheckDropDowns = function(thisSelect) {
  var otherSelectId = ("country1" == thisSelect.id) ? "country2" : "country1";
  var otherSelect = document.getElementById(otherSelectId);

  for (i = 0; i < otherSelect.options.length; i++) {
    //otherSelect.options[i].style.display = 'block';
    otherSelect.options[i].removeAttribute('hidden');
    if (otherSelect.options[i].value == thisSelect.value) {
      //otherSelect.options[i].style.display = 'none';
      otherSelect.options[i].setAttribute('hidden', 'hidden');
    }
  }
}

  <select id="country1" onchange="CheckDropDowns(this)">
    <option value="">Choose</option>
    <option value="1">Australia</option>
    <option value="2">Indonesian Rupiah</option>
    <option value="3">Chinese Yaun</option>
    <option value="4">Japanese Yen</option>
  </select>
  Convert to
  <select id="country2" onchange="CheckDropDowns(this)">
    <option value="">Choose</option>
    <option value="1">Australia</option>
    <option value="2">Indonesian Rupiah</option>
    <option value="3">Chinese Yaun</option>
    <option value="4">Japanese Yen</option>
  </select>

A: I don't know what's wrong with your code, the logic seems convoluted. You can't reliably hide options by setting their display to 'none', in some browsers they remain visible. If it was that simple, life would be easy.
You can hide options by removing them from the list, but then you have to remember where they came from so you can put them back when the selection changes.
In the following, each time an option is selected, if there's one stored it's put back and the one matching the selected option is removed. If the first option is selected, the stored one is just put back, nothing is removed.
This only depends on the two selects having the same class value, they could be related by some other value (e.g. a data-* property).
Hopefully the comments are sufficient.

var matchSelected = (function() {
  // Store for "hidden" node
  var nodeStore = {
    sourceElement: null,
    node: document.createDocumentFragment(),
    index: null
  };

  return function(evt) {
    // Get the element that got the event
    var tgt = this;
    // If there's a stored option, put it back
    if (nodeStore.sourceElement) {
      let sel = nodeStore.sourceElement;
      sel.insertBefore(nodeStore.node.firstChild, sel.options[nodeStore.index]);
      nodeStore.sourceElement = null;
      nodeStore.node = document.createDocumentFragment();
      nodeStore.index = null;
    }
    // If the selected option is the first one, stop here
    if (tgt.selectedIndex == 0) return;
    // Get all selects with the same className
    var sels = document.querySelectorAll('.' + this.className);
    // Get the "other" option
    var other = sels[0] == this ? sels[1] : sels[0];
    // Remove and keep the option on the other element that is the same
    // as the selected option on the target element
    nodeStore.sourceElement = other;
    nodeStore.index = tgt.selectedIndex;
    nodeStore.node.appendChild(other.options[tgt.selectedIndex]);
  }
}());

window.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('.countrySelect').forEach(
    node => node.addEventListener('change', matchSelected, false)
   );
}, false);
<select id="country1" class="countrySelect">
  <option value="" selected>Choose</option>
  <option value="1">Australia Dollar</option>
  <option value="2">Indonesian Rupiah</option>
  <option value="3">Chinese Yaun</option>
  <option value="4">Japanese Yen</option>
</select>
Convert to
<select id="country2" class="countrySelect">
  <option value="" selected>Choose</option>
  <option value="1">Australia Dollar</option>
  <option value="2">Indonesian Rupiah</option>
  <option value="3">Chinese Yaun</option>
  <option value="4">Japanese Yen</option>
</select>


text:
Q: Почему в Fiddler не показывается POSTDATA? Вообщем, я делаю программу ( чекер ), которая проверяет верность данных от аккаунта ( логин и пароль ).
Я, со временем, столкнулся с POST-запросами, скачал программу Fiddler и начал их отслеживать.
Но тут есть одна делема: они практически не показываются.
Например, приведу один кусок кода, взятый с интернета:
POST http://www.----------.com/login/login HTTP/1.1
Host: www.----------.com
Connection: keep-alive
Content-Length: 109
Cache-Control: max-age=0
Origin: http://www.----------.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Referer: http://www.----------.com/login/login
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: xf_session=0c4e132b44ce81bdf93e70c57fe17eb6; __cfduid=d43498195638b2afe52ebaa9e1f97b8b31342586809; __cfduid=d43498195638b2afe52ebaa9e1f97b8b31342586809

login=USERNAME&register=0&password=PASSWORD&remember=1&cookie_check=1&redirect=forum%2F&_xfToken=

Соответственно, последняя строка позволяет понять, что надо отправлять на сервер кодlogin=USERNAME&register=0&password=PASSWORD&remember=1&cookie_check=1&redirect=forum%2F&_xfToken= `.
У меня эта строка отсутствует вообще, даже среди тех немногих POST-запросов, которые до меня доходят.


text:
Q: Angular Call array by index in loop I've error in this code when click CheckAllOptions  to select all checkbox
He select also checkbox in another property
I need only property I clicked it in loop

                <input type="checkbox" name=""  >

{{item.title}}

            <mat-menu #appMenu="matMenu" class="submenu">
                <form action="" method="post">

             <input (input)="type=$event.target.value" type="checkbox"  value="0" > send All

                        <input [(ngModel)]="checkbox.checked" name="checkbox.checked[index]" (input)="type=$event.target.value" type="checkbox"  value="{{checkbox.value}}" >
                        {{checkbox.name}}

                        <button class="sendData" (click)="SendData(item.id)">Send</button>

                </form>
            </mat-menu>

in .ts file
    CheckAllOptions(i) {
    console.log(i);
    let selectedCategory = this.checkboxes
    if (selectedCategory.every(val => val.checked == true))
      selectedCategory.forEach(val => { val.checked = false });
    else
      selectedCategory.forEach(val => { val.checked = true }); }

Array checkbox
    checkboxes: any[] = [
    { name: 'send location', value: '1', checked: false },
    { name: 'send images', value: '2', checked: false },]


text:
Q: Fragment view state not saved on back press when using Android Jetpack Navigation In my app I'm using the Jetpack navigation component and I have an issue with fragment state not being saved when navigating back to a fragment.
When I navigate from MainFragment to SettingsFragment it's via the overflow menu:
NavigationUI.onNavDestinationSelected(item, Navigation.findNavController(view));
When navigating back to MainFragment, the visibility on some views and text in some TextViews is not saved, and my state machine variable has lost its state as well.
I've read solutions where the root view is saved in a global variable in the fragment, and while this solves the visibility issue on views, the TextViews are still empty and the state machine variable is reset.
Is there a proper way to make sure fragment state is saved in this case?

A: If you're using view model then it can save state for you. However, that only works for simple views. For complex views including some custom views that you created, make sure that you have assigned a unique id to those as Android uses those ids to recover their state. You can use generateViewId() method on View to do so. Worst case, you might need to implement onSavedInstanceState and onRestoreInstanceState on your views.
Also, make sure you have not set to setRetainInstance to false in the xml or code.
While doing that please make sure you use parcelize annotation for your parcelable data models as this can save you a lot of time.
I hope your problem is solved by assigning unique IDs and you don't have to deal with saving state. Good luck!


text:
Q: How to implement searching in Haskell I've been following a sample addressbook program in Haskell:
menu = "1.Add address\n2.List addresses\n3.Exit"
main = do
    prompt []

data Address=Address String String String
    deriving Show

prompt :: [Address] -> IO()
prompt addrs=  do
    putStrLn menu
    choice <- getLine
    interpret addrs choice

interpret :: [Address]->String -> IO()
interpret addrs "1" = do
    putStr "Names:"
    names <- getLine

    putStr "Phone:"
    phone <- getLine

    putStr "Email:"
    email <- getLine

    putStrLn "Address added"
    prompt (addAddr(getAddr names phone email) addrs)

interpret addrs "2" = do
    printAddrs addrs
    prompt addrs

interpret addrs "3" = putStrLn "Good bye"
interpret _ _ = putStrLn "Don't know what to do with ya!"

getAddr ::String->String->String->Address
getAddr names phone email = Address names phone email

addAddr::Address->[Address]->[Address]
addAddr addr addrs = addr:addrs

printAddrs::[Address]->IO()
printAddrs addrs= putStrLn (fmtAddresses (tail addrs) (head addrs) "")

fmtAddresses::[Address]->Address->String->String
fmtAddresses addrs (Address names phone email) str
    | (length addrs==0) = currStr
    | (length addrs /=0 ) = fmtAddresses (tail addrs) (head addrs) currStr
    where currStr = str++"Names:"++names++"Phone:"++phone++"Email:"++email++"\n"

The current available functions are just add and print entries. How can I implement a search function for this? Let's say if I put "name" and "ronaldo" in the prompt, it will just display entries with name ronaldo.
By the way, where is the code or container that holds the data (names, phone and email) where I can apply filter or elem function?
Thanks.

A: addrs holds the addresses to search through.
interpret addrs "4" = do
  putStr "Fulltext search keyword:"
  word <- getLine
  printAddrs (filter (\(Address name phone email)
      -> isInfixOf word name
      || isInfixOf word phone
      || isInfixOf word email
    ) addrs)
  prompt addrs


text:
Q: how to store the preferences? i have preferences like this :
<!DOCTYPE overlay SYSTEM "chrome://inlinetrans/locale/options.dtd">

<dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
  id="translate-preferences"
  title="&options.title;"
  buttons="accept, cancel"
  style="padding:0px; margin:0px;"
  ondialogaccept="options.save()"
  onload="options.init();"
  onunload="options.deconstruct();">

  <script src="chrome://inlinetrans/content/options.js" />

  <description value="&options.desc;"
    style="
    background: #fff url('chrome://inlinetrans/skin/options.png') no-repeat;
    min-width:400px;
    min-height:40px;
    padding-left:55px;
    padding-top:10px;
    margin:0px;
    border-bottom: 2px solid #757575;
    font-size:1.5em;"/>

  <vbox style="padding:10px;">
    <groupbox>
      <caption label="&options.ui;"/>
      <label value="&options.results.desc;"/>
    <radiogroup id="display.results" style="padding-left:20px;">
      <radio id="results.cat" value="currenttab" label="&options.results.cat;"/>
          <radio id="results.noncat"  value="newwindow" label="&options.results.noncat;"/>
      </radiogroup>
    </groupbox>
 </vbox>
</dialog>

and this is preference handler i made, but i'm not sure it works :
var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
var t_prefBranch = prefService.getBranch("extensions.inlinetrans.");

var options = {

  result : String,

  init : function() {
    this.updatePrefs()
    t_prefBranch.setCharPref("optionopen", true)

    var Displayresults = document.getElementById("results." + this.result)
        Displayresults.setAttribute("selected", true);
  },

  updatePrefs : function() {

    this.result = t_prefBranch.getCharPref("results")

  },

  save : function() {
    var savepref = document.getElementById("display.results").value

    if (savepref != "") {
        t_prefBranch.setCharPref("results", savepref)
    }

},

reloadOptions : function() {
  this.save()
  this.init()
}

}

thank you so much for your help


text:
Q: extjs - Change setting in property grid and save it to the server I have a property grid Ext.grid.property.grid. I want to use it to allow the user to change his account settings. I achieved to display custom editors, but I'm stuck to get the new value saved to the server.
Ext.define('Mb.view.Settings', {
    extend: 'Ext.grid.property.Grid',
    alias: 'widget.settings',
    requires: ['Ext.tab.Panel'],
    title: Lang._('Options'),
    source: {
        username: Mb.user.name,
        email: Mb.settings.email
    },
    sourceConfig:{
        username: {
            displayName: Lang._('Nom d\'utilisateur'),
            editor: 'displayfield'
        },
        email: {
            displayName: Lang._('Adresse email'),
            editor: {
                xtype: 'textfield',
                vtype: 'email'
            }
        }
    }
});

I look for an event that allows me to trigger an Ajax call to the server to save the new setting, but I cannot find what I'm looking for in the documentation.

A: You are looking in the wrong place: it is the record that changes, meaning you have to look in the attached store: look at the store's datachanged event and then use store.getModifiedRecords().


text:
Q: Job title spelling I have a question regarding my job position and its spelling - I develop mobile apps, what would be the correct spelling of my job position to put on my LinkedIn page:

*

*Mobile Application Developer

*Mobile Applications Developer

*Mobile App Developer

*Mobile Apps Developer

Or something completely different?

A: All of these are correct and clear, but the most typical description for professionals in your field is "Mobile Application Developer."


text:
Q: Pass value from html to php page using ajax and print the return value in div I want to pass some value from my html page to php page using ajax and print the return value in a div
HTML Code :
<!DOCTYPE html>

<title></title>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

        <form>

                    Name :

                        <input type="text" name="nm" id="nm" maxlength="30" class="form-control" placeholder="Name">

                    Class :

                        <select class="form-control" align="center" id="cls">
                            <option value="0">Please Select</option>
                            <option value="First Year">First Year</option>
                            <option value="Second Year">Second Year</option>
                            <option value="Third Year">Third Year</option>
                        </select>

                    Roll No. :

                        <input type="text" name="roll" id="roll" class="form-control" placeholder="Roll No." align="center">

                    DOB :

                        <input type="date" name="dob" id="dob" class="form-control" placeholder="Date of Birth" align="center">

                        <button class="btn btn-primary" name="submit1" id="submit1">Add</button>

        </form>

PHP Code
<?php

$nm = $_POST['nm'];
$cls = $_POST['cls'];
$roll = $_POST['roll'];
$dob = $_POST['dob'];

$date = date_format($date, 'Y-m-d');

$now = time();

$dob = strtotime('Y-m-d', $dob);

$difference = $now - $dob;

$age = floor($difference / 31556926);

echo "Name : ". $nm;

echo "Class : ". $cls;

echo "Roll No. : ". $roll;

echo "Age : ". $age;

?>

I don't know what is wrong with my code. But after I click on "Add" button my address bar looks like this :
index.html?nm=asd&roll=1&dob=1992-08-12&submit1=

even though I am using POST method. Help is needed.

A: Your click function still posts the form.
use Javascript's preventDefault() to counter this
$('#submit1').click(function(event) {
    event.preventDefault();
    var nm = $('#nm').val();
    var cls = $('#cls').val();
    var roll = $('#roll').val();
    var dob = $('#dob').val();
    $.ajax({
        type: 'POST',
        url: 'index.php',
        data: ({ nm: nm, cls: cls, roll: roll, dob: dob }),
        success: function(response) {
            $('#div2').html(response);
        }
    });
});

A: You have to provide the form method as "POST" then alone it will never send the submitted data to the URL which you access.
What problem you face is that you have not specified any method to your <form> attribute and hence it takes the GET method.
First Learn the difference between GET and POST methods


text:
Q: В чём разница между var obj{} и var obj[]? Ведь и то, и то массив, но разница есть.
Например:
var users = [ {"name":"Kurusa", "pass":"Kurusa123"}, {"name":"Zhecky", "pass":"Zhecky123"}, {"name":"Marko", "pass":"Marko123"}, {"name":"Polo", "pass":"Polo123"} ];

И вот так:
var user = { name: "Вася" };

A: Воспринимайте массив var users = [{}, {}, {}]; как коробку с пончиками.
А, собственно, {} как пончик.
У "пончика" есть свойства, которые представляются парами ключ: значение. Например {"тип":"шоколадный", "вес":102.5}.
А коробка на то и есть коробка, она только может вмещать другие вещи (коробки, пончики и другое), и давать возможность доступа к ним по порядку, узнать сколько их всего и т.д.

A: Нет, объект - это не массив.
Словарём его с натяжкой ещё можно назвать, но точно не массивом.
Массив содержит некоторое число элементов один за другим и имеет длину.
Объект содержит именованные свойства с некими значениями.


text:
Q: Extending Recently Viewed & Recently Compared Grids I am struggling to extend the following two files in Magento 2.3.1

\vendor\magento\module-reports\view\frontend\templates\widget\viewed\content\viewed_grid.phtml

and

\vendor\magento\module-reports\view\frontend\templates\widget\compared\content\compared_grid.phtml

I tried extending them at:

\ME\THEME\Magento_Reports\templates\widget\compared\content\compared_grid.phtml

and

\ME\THEME\Magento_Reports\templates\widget\viewed\content\viewed_grid.phtml

I then ran setup:upgrade  and setup:static-content:deploy -f
But no changes took place.
To troubleshoot I then tried editing the files in their original location. Ran setup:upgrade  and setup:static-content:deploy -f
But still no changes?
Are these files no longer used?
To clarify it is the blocks that are inputted into the TinyMce Editor as below image.

Any Help much appreciated.


text:
Q: iOS Push Notificattion production certificate Common Name issue While I am attempting to upload Production certificate on Parse.com for Push notificatation.
There is error message

Unsupported certificate type. Common Name (CN) must contain one of:
  Apple Production IOS Push Services, Apple Development IOS Push
  Services, Pass Type ID, Apple Development Mac Push Services, Apple
  Production Mac Push Services.

After some research I came to know that.
While we are exporting Production certificate from Apple,
Common Name before was : Apple Production IOS Push Services:[Bundle name]
And Now : Apple Push Services:[Bundle name]
May be this is the reason Parse fails to validate certificate.
Please give solution if any.

A: It seems problem is solved now by Parse.
You can face error

Could not connect to Apple with this certificate

If so, revoke your APNS certificate and regenerate it.
And then create .p12 file with this new certificate. and upload it.
I have successfully uploaded .p12 file.


text:
Q: JSF1.2 Messages not rendered Migrating from WAS6.1+JSF1.1+richfaces.3.1.5 to WAS7+JSF1.2+facelets1.1.14+richfaces3.3.3.
Error/Status messages are not rendering using h:messages, even though on debugging the facescontext.getMessages() contains the messages.
On submitting a form, I am validating an input. If the validation fails I am adding an error msg to the facescontext. It can be for multiple inputs. Each error msg is added to the facescontext
    FacesMessage message = new FacesMessage();
    message.setDetail(msg);
    message.setSummary(msg);
message.setSeverity(FacesMessage.SEVERITY_ERROR);

    getFacesContext().addMessage(componentID, message);

and on the xhtml I am displaying it using h:messages
I was using jsp in WAS6.1 and JSF1.1 and this used to work fine
Thanks
Adding more details
My xhtml

<ui:composition template="/template.xhtml">
    <ui:define name="content">

            <h:form id="uploadDoc1" >
                <h:messages/>
                <h:panelGrid id="panelGridContact" headerClass="standardPageHeader" width="100%" cellpadding="5">
                    <f:facet name="header">
                        <h:panelGroup>
                            <h:outputText value="Upload Contact Info" />

                        </h:panelGroup>
                    </f:facet>
                    <h:panelGroup id="msgId">
                        <xyz:errorMessages />
                        <xyz:statusMessages />
                    </h:panelGroup>
                    <h:panelGrid style="text-align: center;font-weight: bold;">
                        <h:outputText value="Click on Browse button to identify CSV file with contact information for upload."/>
                        <h:outputText value="File size limit is 10MB."/>
                        <h:panelGroup>
                            <rich:fileUpload id="fileuploader" fileUploadListener="#{uploadContactCntrl.onSubmit}"
                                acceptedTypes="csv" allowFlash="true" listHeight="50" addControlLabel="Select File" uploadControlLabel="Submit" clearControlLabel="clear"/>
                        </h:panelGroup>
                        <h:outputText value=" "/>
                    </h:panelGrid>
                </h:panelGrid>
            </h:form>

    </ui:define>
</ui:composition>

errorMessages and statusMessages are common tags to display error(validation error) and status((like Update complete) messages
In the the backingbean on submit if an error is encountered (like "File not found" or "Database is down" I call a common method with the error/status message from the resource file.
WebUtils.addCustomErrorMessage("global.error.ContactInfo-DuplicateRecords-UserID", new String[]{userid,Integer.toString(j+1)}, Constants.RESOURCE_BUNDLE_NAME);
or
WebUtils.addCustomStatusMessage("global.error.ContactInfo-successMessage", new String[]{Integer.toString(noOfRowsInserted)}, Constants.RESOURCE_BUNDLE_NAME);
public static void addCustomErrorMessage(String msg, String componentID) {
    FacesMessage message = new FacesMessage();

    message.setDetail(msg);
    message.setSummary(msg);
    message.setSeverity(FacesMessage.SEVERITY_ERROR);

    getFacesContext().addMessage(componentID, message);
}

public static void addCustomStatusMessage(String msg, String componentID) {
    if (errorCodeParameters != null && errorCodeParameters.length > 0)
        msg = MessageFormat.format(msg, (Object[])errorCodeParameters);

    FacesMessage message = new FacesMessage();

    message.setDetail(msg);
    message.setSummary(msg);
    message.setSeverity(FacesMessage.SEVERITY_INFO);

    getFacesContext().addMessage(componentID, message);
}

We also use the same tags to display an error message when an error is encountered on an input field. For e.g. a Firstname field has invalid characters.
As mentioned earlier, this was working fine before we migrated to JSF1.2

A: Your answer need to have xhtml code too, any way i'm giving u sample for using validation in JSF 1.2...
The xhtml code should be like..
    <h:inputText id="txt_project_name"
        value="#{FIS_Project_Master.txt_project_name_value}"
      validator="#{FIS_Project_Master.txt_project_name_validator}"/>

   <h:message id="msg_txt_project_name" for="txt_project_name" />

The java code should be like...
  public void txt_project_name_validator(FacesContext context, UIComponent component, Object value) {
    if (bmwpProjectMstFacade.ispmProjName_exists(value.toString().toUpperCase().trim())) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Warning", "Project Name Already Exist");
        throw new ValidatorException(message);
    }
}


text:
Q: VBA - renaming the files I have few files which, I need to change the names. I have a list of them but without the file extension.

The code will work, only if the list will have the file extensions. Any idea how to solve this issue?
    Sub RenameMultipleFiles()
    With Application.FileDialog(msoFileDialogFolderPicker)
        .AllowMultiSelect = False
        If .Show = -1 Then
            selectDirectory = .SelectedItems(1)
            dFileList = Dir(selectDirectory & Application.PathSeparator & "*")

            Do Until dFileList = ""
                curRow = 0
                On Error Resume Next
                curRow = Application.Match(dFileList, Range("A:A"), 0)
                If curRow > 0 Then
                    Name selectDirectory & Application.PathSeparator & dFileList As _
                    selectDirectory & Application.PathSeparator & Cells(curRow, "B").Value
                End If

                dFileList = Dir
            Loop
        End If
    End With
End Sub

A: This will probably produce your desired results. Please see the end for some concern with your code and use of the On Error Resume Next.
I have made some additions to your existing code to basically, exclude the file extension when matching the file name with the column A list and then appending the extension to the name in column B.
The code has now been edited to incorporate the InStrRev function to provide a dynamic result for the extension length (in a round-a-bout way).
 Sub RenameMultipleFiles()
 Dim CharacterCount As Long
    With Application.FileDialog(msoFileDialogFolderPicker)
        .AllowMultiSelect = False
        If .Show = -1 Then
            selectDirectory = .SelectedItems(1)
            DFileList = Dir(selectDirectory & Application.PathSeparator & "*")
            Do Until DFileList = ""
                CharacterCount = InStrRev(DFileList, ".")
                curRow = 0
                On Error Resume Next
                curRow = Application.Match(Left(DFileList, CharacterCount - 1), Range("A:A"), 0)

                If curRow > 0 Then
                    Name selectDirectory & Application.PathSeparator & DFileList As _
                    selectDirectory & Application.PathSeparator & Cells(curRow, "B").Value & Right(DFileList, Len(DFileList) - CharacterCount + 1)
                End If

                DFileList = Dir
            Loop
        End If
    End With
End Sub

I have made use of the Left(), Right() and Len() functions.
I tested this within a test folder containing Book.xlsx, Book.xls, Doc.doc and Doc.docx.
Column A had Book1 and Doc1 listed.
Column B had New_Book1 and New_Doc1 listed.
After running the routine both files were renamed and retained their file extensions.
Worksheet:

Before running the routine:

After running the routine:

My concern with your code is your use of On Error Resume Next. The reason being if curRow evaluates to an error, the error is passing your If curRow > 0 Then as it is being ignored. This may result in unexpected or undesired results.
As you haven't declared your variables (e.g. Dim curRow As Long) they are implicitly delcared as type Variant meaning any data type can be assigned to the variable. This can also cause unexpected results, per above, you are expecting to assign numbers for your curRow variable however when an error is evaluated, the string "Error 2042" is returned to your variable which then tries to evaluate through your If...Then statement.
I noticed that when I was running some tests of the code, curRow was returning Error 2042 which is the result of the Match() function returning #N/A. This happens when the current targeted file does not match a name in column A. As Error 2042 > 0 = FALSE it should return Runtime Error 13. Type Mismatch but due to On Error Resume Next it still tries to rename the file.
This would be "better" to handle rather than ignore (to avoid unexpected results from ignoring the error), such as (pseudo code):
If curRow = Error 2042 Then
    'Do nothing, go to the next iteration
ElseIf curRow > 0 Then
    'Run desired code
End if

As the error is expected, we now handle it in this environment and allow other errors to still be thrown and/or handled if/as required.


text:
Q: Sveltekit not redirecting from unforeseen route This is my code for /+layout.ts
export const ssr = false;

export const load = (async ({ url }) => {
    let user: null | { user: User, player: SupaPlayer } = await supa.getUser((event, session) => {
        ...
    });

    if (user !== null) {
        ...
        return { ...user, contestants: await supa.getContestants() };
    } else {
        if (!url.pathname.includes('/login')) {
            // I AM REACHING THIS POINT
            throw redirect(301, "/login");
        }
        // return null;
    }

}) satisfies LayoutLoad

I am trying this with a route that does not exist (i.e. there is nothing in /routes) and get two errors:

*

*in the terminal that I am running my code for dev I get Error: Not found: /<route> and a stacktrace - indeed the route does not exist in my code but I would expect Sveltekit not to create errors for that

*in the browser, I get error: Not found: /<route> attributed to manifest.js, and, more importantly, the redirect to /login is not working, and I get Uncaught (in promise) Redirect {status: 301, location: '/login'}
I suspect the initial errors are causing the redirect to fail, as it does work for known routes.
The error seems to originate from manifest.js, which reads as below and which has no obvious default handler for an unknown route
export { matchers } from '/.svelte-kit/generated/client/matchers.js';

export const nodes = [() => import("/.svelte-kit/generated/client/nodes/0.js"),
    () => import("/.svelte-kit/generated/client/nodes/1.js"),
    ...];

export const server_loads = [];

export const dictionary = {
    "/": [2],
    ...
};

export const hooks = {
    handleError: (({ error }) => { console.error(error) }),
};


text:
Q: Unable to decide Java collection My usecase is like in which I need to maintain a collection of unique items. I may need to frequently add or remove items from the collection at an index(which I have as member of the item currently, but I am open to modification), and while doing that I need to update index of items.
I am not able to decide which Java collection would suit my needs best. HashSet and SortedSet both guarantee uniqueness, but not sure how index part can be taken care of.

A: According to the question + comments, you have the following fundamental requirements for the collection:

*

*The elements in the collection must be unique.

*The collection must maintain the elements in an order specified by the user.

*The collection elements must have unique indexes representing the element's current position.

*The indexes must adjust as elements are inserted and deleted.

There is no (single) Java SE collection type that does 1 and 2, 3 or 4.
The only Java SE collection type that supports and can maintain an arbitrary ordering is List, so you need to start with that.  Something like this for instance:
public class MyList<E> extends ArrayList<E> {
    ...

    @Override
    public void add(int pos, <E> e) {
        if (this.contains(e)) {
            throw new SomeException("already in collection");
        }
        this.add(pos, e);
    }
}

Note that HashMap<Integer, E> is a possible alternative, but adjusting the indexes as elements are added and removed is complicated.  (Comparing the performance characteristics is not straightforward, but the chances are that it won't matter in your use-case.)


text:
Q: Turn two arrays output into a table with dynamic updating in Powershell $array1 = @("device1", "device2", "device3")
$array2 = @("alive", "down", "alive")

I want to take the two arrays and output them in table format dynamically so I can change the color of the text depending on if the host is alive or down. I can currently do this, but the drawbacks of the below method outputs everything at once, and I cannot color the lines:
$max = ($array1, $array2 | Measure-Object -Maximum -Property Count).Maximum

(0..$max | `
Select-Object `
@{n="Count";e={"{0,3:N0}" -f $arraycount[$_]}},`
@{n="Device";e={$array1[$_]}},`
@{n="Status";e={$array2[$_]}} `
| Out-String).Trim()

Desired output:
Count Device  Status
----- ------  ------
  1   device1  alive
  2   device2  down
  3   device3  alive

A: First off, might I suggest outputting as HTML if you want something colorful. Since you are generating objects, you could very well use those to create a table in HTML, and have that formatted however you want.
0..$max | `
Select-Object `
@{n="Count";e={"{0,3:N0}" -f $arraycount[$_]}},`
@{n="Device";e={$array1[$_]}},`
@{n="Status";e={$array2[$_]}} `
|ConvertTo-Html -As Table -Prop *

If you want to add a bit of formatting you can define that for the header:
$Header = @"

"@

Then once you convert it to HTML you can do a little replacing to add per-cell formatting for the cells that have 'alive' or 'down' in them:
ForEach-Object{$_ -replace '>alive<',' bgcolor="Green">alive<' -replace '>down<',' bgcolor="Red">down<'}|

Then output to a file, and invoke that file to bring it up in a browser. All together it would be something like:
$Header = @"

"@

0..($array1.Count-1) |
    Select-Object @{n="Count";e={$_+1}}, @{n="Device";e={$array1[$_]}}, @{n="Status";e={$array2[$_]}}|
    ConvertTo-Html -as Table -Property * -Head $Header|
    %{$_ -replace '>alive<',' bgcolor="Green">alive<' -replace '>down<',' bgcolor="Red">down<'}|
    set-content C:\Temp\Report.htm

invoke-item c:\temp\Report.htm

That would create a very simple table (click 'Run code snippet' below to see table):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<colgroup><col/><col/><col/></colgroup>

Count	Device	Status

1	device1	alive

2	device2	down

3	device3	alive

Of coarse, if you want it all within PowerShell, you're stuck with either Write-Host or a module to output your color. What you have works fine, you can just split it on new lines and process each line. If you define your colors in a scriptblock beforehand it makes coloring each line fairly simple:
$array1 = @("device1", "device2", "device3")
$array2 = @("alive", "down", "alive")
$ThisColor={
Switch -RegEx ($_.trim().split(' ')[-1]){
    'alive' {'Green';continue}
    'down'  {'Red';continue}
    default {'White'}
}
}
(0..($array1.Count-1) | Select-Object @{n="Count";e={$_+1}}, @{n="Device";e={$array1[$_]}}, @{n="Status";e={$array2[$_]}} | Out-String).Trim() -split '[\r\n]+'|%{Write-host $_ -ForegroundColor $ThisColor.Invoke($_)}