text:
Q: Cannot validate Chosen select with jQuery Validate (not unobtrusive) I am trying to make simple DropDownList validation (clear jQuery - no unobtrusive) in my ASP.NET MVC 4 application.
I have fields in model:
[DisplayName("Wybierz płatnika")]
public virtual int? studyPayerId { get; set; }
public virtual IList<StudyPayer> PayersList { get; set; }

Then in controller I do:
var payers = RisDbPersistanceManager.RetrieveEquals<StudyPayer>("IsActive", true);
if (payers != null)
{
  model.PayersList = payers;  // it is populated
}
model.studyPayerId = null;

And in my View:

...

$('#studyPayerId').rules('add',
{
    required: true,
    messages: {
        required: "Proszę wybrać płatnika!"
    }
});
...

    @Html.LabelFor(x => x.studyPayerId)

    @Html.DropDownListFor(x => x.studyPayerId, new SelectList(Model.PayersList, "Id", "Name", Model.studyPayerId), "-- wybierz płatnika --")
    @Html.ValidationMessageFor(x => x.studyPayerId)

In simple TextBox fields everything works - validates my field on Submit button click. But DropDownList does not display any message when I did not choose anything and leave "-- wybierz płatnika --" selection.
EDIT
  <select id="Gender" class="error" name="Gender" style="display: none;">
  Proszę wybrać płeć!

    -- nieokreślona --

A: *

*This is JavaScript so you'll need to show us the RENDERED and relevant HTML code as seen by the browser, not your model, view or controller.  Since I cannot see your rendered HTML, I use generic naming in my demo code below.

*

*The first option element must have a value="" attribute.

*The select element must have a name attribute even if you don't use it.

*I don't see your call to the .validate() method.  The plugin must first get initialized with the .validate() method.  You cannot use the .rules() method without it.
jQuery:
$(document).ready(function () {

    $('#myform').validate(); // <- INITIALIZE plugin

    $('#studyPayerId').rules('add', {
        required: true,
        messages: {
            required: "Proszę wybrać płatnika!"
        }
    });

});

Rendered HTML:
<form id="myform">
    <select name="myselect" id="studyPayerId">
        <option value="">-- wybierz płatnika --</option>
        <option value="1">option 1</option>
    </select>

    <input type="submit" />
</form>

Working DEMO:  http://jsfiddle.net/nwLqdemu/

I do not understand why you're using the .rules() method.  Usually that's is only used when rules need to be added and removed dynamically; or when rules get applied to an entire group of elements at once, because that would be too lengthy to be included within the .validate() method.
Otherwise, you'd simply declare rules within the .validate() method upon initialization...
$(document).ready(function () {

    // INITIALIZE plugin

    $('#myform').validate({
        rules: {
            myselect: {  // <- NAME attribute
                required: true
            }
        },
        messages: {
            myselect: {  // <- NAME attribute
                required: "Proszę wybrać płatnika!"
            }
        }
    });

});

Working DEMO 2:  http://jsfiddle.net/nwLqdemu/1/

Please see the SO Tag Wiki page for a basic demo and hints on proper usage.

EDIT:
Since you never mentioned using the "Chosen" plugin for creating your drop down list, there is no way anyone could have answered this question.  However, since the jQuery Validate plugin ignores hidden elements by default, you'll need to change the ignore option to [] in order to "ignore nothing" and validate the element hidden by Chosen.


text:
Q: Mod_Rewrite unexpected behavior L flag my web application structure is:
/var/www/myapp/
    - www/
        - index.php
        - css.php
        - .htaccess

the virtual host is configured as:
<VirtualHost *:80>
        ServerName www.example.org
        DocumentRoot /var/www/myapp/www
        DirectoryIndex index.php index.html
        <Directory /var/www/myapp/www>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>
</VirtualHost>

In /var/www/myapp/www/.htaccess there is:
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /
    RewriteRule css css.php [L,NC]
    RewriteRule .* index.php
</IfModule>

Now, if I call www.example.org I'm correctly redirected to index.php, but if I call www.example.org/css I'm still redirected always to index.php.
If I drop the line "RewriteRule .* index.php" and then call www.example.org/css, I'm correctly redirected to css.php.
What's wrong?
Thanks all very much
======== EDIT =========
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b7080058/initial] (3) [perdir /var/www/sviluppo/mattia_dev/example/www/] add path info postfix: /var/www/sviluppo/mattia_dev/example/www/DEV_2 -> /var/www/sviluppo/mattia_dev/example/www/DEV_2/css/example1/test.css
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b7080058/initial] (3) [perdir /var/www/sviluppo/mattia_dev/example/www/] strip per-dir prefix: /var/www/sviluppo/mattia_dev/example/www/DEV_2/css/example1/test.css -> DEV_2/css/example1/test.css
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b7080058/initial] (3) [perdir /var/www/sviluppo/mattia_dev/example/www/] applying pattern '^(DEV|TEST|PROD)\_[0-9]+\/(css|js|image|static)\/(.+)$' to uri 'DEV_2/css/example1/test.css'
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b7080058/initial] (2) [perdir /var/www/sviluppo/mattia_dev/example/www/] rewrite 'DEV_2/css/example1/test.css' -> 'css/example1/test.css'
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b7080058/initial] (3) [perdir /var/www/sviluppo/mattia_dev/example/www/] add per-dir prefix: css/example1/test.css -> /var/www/sviluppo/mattia_dev/example/www/css/example1/test.css
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b7080058/initial] (2) [perdir /var/www/sviluppo/mattia_dev/example/www/] trying to replace prefix /var/www/sviluppo/mattia_dev/example/www/ with /
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b7080058/initial] (5) strip matching prefix: /var/www/sviluppo/mattia_dev/example/www/css/example1/test.css -> css/example1/test.css
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b7080058/initial] (4) add subst prefix: css/example1/test.css -> /css/example1/test.css
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b7080058/initial] (1) [perdir /var/www/sviluppo/mattia_dev/example/www/] internal redirect with /css/example1/test.css [INTERNAL REDIRECT]
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b63188e8/initial/redir#1] (3) [perdir /var/www/sviluppo/mattia_dev/example/www/] strip per-dir prefix: /var/www/sviluppo/mattia_dev/example/www/css/example1/test.css -> css/example1/test.css
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b63188e8/initial/redir#1] (3) [perdir /var/www/sviluppo/mattia_dev/example/www/] applying pattern '^(DEV|TEST|PROD)\_[0-9]+\/(css|js|image|static)\/(.+)$' to uri 'css/example1/test.css'
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b63188e8/initial/redir#1] (3) [perdir /var/www/sviluppo/mattia_dev/example/www/] strip per-dir prefix: /var/www/sviluppo/mattia_dev/example/www/css/example1/test.css -> css/example1/test.css
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b63188e8/initial/redir#1] (3) [perdir /var/www/sviluppo/mattia_dev/example/www/] applying pattern '.*' to uri 'css/example1/test.css'
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b63188e8/initial/redir#1] (2) [perdir /var/www/sviluppo/mattia_dev/example/www/] rewrite 'css/example1/test.css' -> 'index.php'
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b63188e8/initial/redir#1] (3) [perdir /var/www/sviluppo/mattia_dev/example/www/] add per-dir prefix: index.php -> /var/www/sviluppo/mattia_dev/example/www/index.php
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b63188e8/initial/redir#1] (2) [perdir /var/www/sviluppo/mattia_dev/example/www/] trying to replace prefix /var/www/sviluppo/mattia_dev/example/www/ with /
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b63188e8/initial/redir#1] (5) strip matching prefix: /var/www/sviluppo/mattia_dev/example/www/index.php -> index.php
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b63188e8/initial/redir#1] (4) add subst prefix: index.php -> /index.php
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b63188e8/initial/redir#1] (1) [perdir /var/www/sviluppo/mattia_dev/example/www/] internal redirect with /index.php [INTERNAL REDIRECT]
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b6310db8/initial/redir#2] (3) [perdir /var/www/sviluppo/mattia_dev/example/www/] strip per-dir prefix: /var/www/sviluppo/mattia_dev/example/www/index.php -> index.php
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b6310db8/initial/redir#2] (3) [perdir /var/www/sviluppo/mattia_dev/example/www/] applying pattern '^(DEV|TEST|PROD)\_[0-9]+\/(css|js|image|static)\/(.+)$' to uri 'index.php'
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b6310db8/initial/redir#2] (3) [perdir /var/www/sviluppo/mattia_dev/example/www/] strip per-dir prefix: /var/www/sviluppo/mattia_dev/example/www/index.php -> index.php
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b6310db8/initial/redir#2] (3) [perdir /var/www/sviluppo/mattia_dev/example/www/] applying pattern '.*' to uri 'index.php'
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b6310db8/initial/redir#2] (2) [perdir /var/www/sviluppo/mattia_dev/example/www/] rewrite 'index.php' -> 'index.php'
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b6310db8/initial/redir#2] (3) [perdir /var/www/sviluppo/mattia_dev/example/www/] add per-dir prefix: index.php -> /var/www/sviluppo/mattia_dev/example/www/index.php
192.168.1.8 - - [14/Jul/2012:19:07:21 +0200] [www.example.org/sid#b747b6c0][rid#b6310db8/initial/redir#2] (1) [perdir /var/www/sviluppo/mattia_dev/example/www/] initial URL equal rewritten URL: /var/www/sviluppo/mattia_dev/example/www/index.php [IGNORING REWRITE]

Seems that a first redirect occurs but the mod_rewrite doesn't stop causing an internal redirect. Then, the changed url, is passed to mod_rewrite another time and a second redirect occured but now matching the second rule.
I can't understand it because I've placed the [L] flag just to ensure that the mod_rewrite stops.
Thanks another time

A: You are missing an important fact about the L flag:

It is therefore important, if you are using RewriteRule directives in one of these [.htaccess, <Directory>] contexts, that you take explicit steps to avoid rules looping, and not count solely on the [L] flag to terminate execution of a series of rules

From: L|last (Flag); bold by me
That means, only by using the L does not have your desired effect to prevent the interal redirect. The INTERNAL REDIRECT happens here because it must happen, you have specified it with your .htaccess configuration. The L flag is not the right flag to prevent the INTERNAL REDIRECT.
Let's look closer at your question and what actually happens:

I can't understand it because I've placed the [L] flag just to ensure that the mod_rewrite stops.

Is just that you have the wrong undestanding of the L flag. It will only stop for the current rewriting, meaning, the RewriteRule directives beneath it are not going to be processed in the current round (the inner loop).
If the URI changed L will re-inject into the the next round (the outer loop) as the following technical details flowchart shows:

To highlight where the L flag kicks in and where the INTERNAL REDIRECT happens, this is the same graphic with some annotations for your specfic (first) URI rewrite:

It shows that the L flag only exits the inner loop but if the URI has been rewritten (changed) - as in your case - the outer loop takes care that the changed URI will be passed again to all your rewrite rules.
Instead you might want to formulate a condition as the following example from that part of the manual shows:
RewriteBase /
RewriteCond %{REQUEST_URI} !=/index.php
RewriteRule ^(.*) /index.php?req=$1 [L,PT]

(PT has it's own manual entry, is is more or less not part of the solution, just noting because I quoted the example as-is)
What you actually want to use is the END flag:
RewriteRule css css.php [END,NC]

However contact your system administrator if you have the needed apache version for it (Available in 2.3.9 and later). If not, you need to operate with RewriteCond.

A: hakre's answer illustrates well what is happening. Besides using the END flag you have a few more options:

*

*Use %{ENV:REDIRECT_STATUS} to prevent any further rewrites. This will change after an internal redirect. See this page for more information what is actually happening:
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule css css.php [L,NC]

*Use %{THE_REQUEST} to match against the request that was made to the server. Since this does not change when you internally redirect, this can be used to prevent further redirects
RewriteCond %{THE_REQUEST} ^(GET|POST)\ /css\ HTTP
RewriteRule ^ css.php [L,NC]

*Use a dummy variable in the query string. This would allow to prevent redirecting by defining this variable in a link, but we will use it here to prevent multiple passes:
RewriteCond %{QUERY_STRING} !noredir=1
RewriteRule css css.php?noredir=1 [L,QSA,NC]

Please note that for each of these examples you need to use this construction for each individual rule.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Criar laço e passar para argumentos de uma função? Tenho o seguinte código em Python:
storage.tableWidget.setColumnWidth(0, 30)
storage.tableWidget.setColumnWidth(1, 140)
storage.tableWidget.setColumnWidth(2, 90)
storage.tableWidget.setColumnWidth(3, 55)
storage.tableWidget.setColumnWidth(4, 60)
storage.tableWidget.setColumnWidth(5, 40)

ele acessa cada coluna em um tableWidget(primeiro argumento) e define o tamanho da célula(segundo argumento).
Me falta conhecimento, mas creio que seja possível diminuir esse código com algum laço, tendo em mente que o primeiro argumento é sequencial (0,1,2,3,4,5).
Alguém pode me dar uma luz?
obrigado.

A: Você pode fazer utilizando enumerate:
tamanho_celula = [30, 140, 90, 55, 60, 40]

for col, tamanho in enumerate(tamanho_celula):
    storage.tableWidget.setColumnWidth(col, tamanho)

Na primeira linha você cria uma lista com os valores do tamanho da célula e dentro do for você itera.


text:
Q: Haskell (nested) ReaderT how can you access the inner monad of a ReaderT.
In my case I have the typ:
newtype VCSSetupAction a = VCSSetupAction (ReaderT (Maybe VCSConf) IDEM a)
    deriving (Monad, MonadIO, MonadReader (Maybe VCSConf))

I cann access the (Maybe VCSConf) in a function running in this Monad like
commitAction' :: Common.VCSAction ()
commitAction' = do
   config <- ask
   ...

but I should also be able to access the inner IDEM which turns out to be of type:
type IDEM = ReaderT IDERef IO

so I want to be able to do something like
commitAction' :: Common.VCSAction ()
commitAction' = do
   config <- ask
   ideRef <- lift $ ask -- this does not compile/work

I still do not understand Monads well enough for this. Thanks for any help.

A: To use lift directly, your newtype would have to derive MonadTrans, but since it's not a transformer, this is not appropriate in this case. Instead, you can just wrap the action in your data constructor. Now you're dealing directly with the ReaderT, so you can use its lift.
ideRef <- VCSSetupAction $ lift $ ask

You might want to define a helper for this to make things cleaner.


text:
Q: Are Android Context objects serializable? I declared a non-final static SharedPreferences object called PREFS together with the other constants in my Constants.java class:
public static SharedPreferences PREFS = null;

My reason for doing so is that my app is comprised of about 6 different AsyncTasks that keep accessing the same shared prefs file, and I didn't want to get the SharedPreferences and its Editor every time. On my app's first run, I make a call to getSharedPreferences() in my MainActivity and store it to PREFS so that it points to an instance before the AsyncTasks are fired, and therefore avoid a NullPointerException.
However, I kept getting NullPointerExceptions from the AsyncTasks anyway. All stack traces point to the line where I make a call to Constants.PREFS to get a value. My theory is that after some time, Android kills my app's process, so the next time the alarm for any of my AsyncTasks goes off, the value of Constants.PREFS would already be null.
My question is: Should I make a static variable for Context instead? Will its state be persisted even when Android kills off my process? I always pass a reference of Context to my AsyncTasks when the latter are instantiated so they can call on getSystemService(), and that never throws a NullPointerException. However, I don't see Context extending Serializable from the Android docs.

A: Use Application class to share preferences globally across the application.
public class MyApp extends Application {
    private static Context mAppContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mAppContext = getApplicationContext();
    }

    public static SharedPreferences getPreferences(){
        return mAppContext.getSharedPreferences("my_app_preferences",MODE_MULTI_PROCESS);
    }
}

Tell android you want your custom Application class, by mentioning it in the manifest:
<application android:name=".MyApp" android:label="@string/app_name" android:icon="@drawable/ic_launcher">

Now from anywhere, just call
MyApp.getPreferences().edit().putBoolean("pref1",true). . . put more stuff . .commit()

MODE_MULTI_PROCESS ensures all AsyncTask threads get synchronized access to same instance of SharedPreferences. Also, commit() is atomic, and will persist changes to the disk.
The above pattern is also handy for accessing resources from anywhere.
Update
It seems that static reference to context causes troubles with new Instant Run feature.
Hence, the context can be required as a parameter of utility method:
public static SharedPreferences getPreferences(context){
    return context.getSharedPreferences("my_app_preferences",MODE_MULTI_PROCESS);
}


text:
Q: How to set the length of a line using openlayers I'm trying edit a polygon by changing the length of some lines by code. Found this method to calculate based on the bearing.
But I didn't find anything on how to calculate the bearing, before I start research my math notes and code this bearing calculation, any recomendations ?
thanks


text:
Q: Should I create ViewModel for each View? I'm new in programming, maybe my question is stupid, but I try to understand this concept right. In my small asp.net core web application I have entity classes, for example, product, a unit of measure for these products. I store them in a database, using entity framework. My entities are very simple and I pass them straight to the View (pulling them off a repository). My mentor says that in big serious projects people never do like this and it's not right at all, that in a well-written code View layer shouldn't know about entities and data layers at all, they should be totally independent. Does it mean that I should create ViewModel class for each View, even if they equal to my Entity classes? What are the best practices on this topic?

A: You most definitely shouldn't. These kinds of global rules rarely apply.
Let's see about the MVVM pattern:

A criticism of the pattern comes from MVVM creator John Gossman himself,[12] who points out that the overhead in implementing MVVM is "overkill" for simple UI operations.

I think that answers your question on creating a view model for everything.
If the model does not fit the view or is complicated enough then you can use ViewModel.
Your mentor's idea (I guess) is that you should always think in terms of Domain objects instead of database objects. But as you'll see in any example, there is no reason not to use a POCO object straight out of the db if it fits the view.

A: Though not a rule but it is practiced as standard in many projects. Entity objects are not directly passed on to your view. Please refer the link.
For instance, you might want to hide some properties in the view. In such case if there is an intermediate class like Data Transfer Objects defined, client will be exposed only to the DTO class and not your DB class objects.


text:
Q: Implement Oracle Paging For ANY Query? I've found a lot of examples of paging in Oracle.  The particular one I'm using now looks a like this:
SELECT * FROM (
  SELECT a.*, ROWNUM RNUM FROM (
    **Select * From SomeTable**) a
  WHERE ROWNUM <= 500) b
WHERE b.RNUM >= 1

The line in bold represents the 'original' query.  The rest of the SQL there is to implement the paging.  The problem I'm running into is a query that is perfectly valid by itself; will fail when I place it inside of my paging code.
As an example - this query will fail:
SELECT TABLE1.*, TABLE1.SomeValue FROM TABLE1

With a ambiguous column error.  But, without my extra code; it will run just fine.  I have a large number of 'saved' queries, but I have to ensure that my paging solution doesn't invalidate them.
I've used SQL Developer as my Oracle querying tool and it manages to implement paging that works even with the above query that fails when I wrap it in the paging code.  Can anyone tell me how they manage to pull it off?

A: First off, the original query would need to have an ORDER BY clause in order to make the paging solution work reasonably.  Otherwise, it would be perfectly valid for Oracle to return the same 500 rows for the first page, the second page, and the Nth page.
SQL Developer is not changing your query to implement paging.  It is simply sending the full query to Oracle and paging the results itself using JDBC.  The JDBC client application can specify a fetch size which controls how many rows are returned from the database to the client at a time.  The client application can then wait for the user to either decide to go to the next page or to do something else in which case the cursor is closed.
Whether the SQL Developer approach makes sense depends heavily on the architecture of your application.  If you're trying to page data in a stateless web application, it probably doesn't work because you're not going to hold a database session open across multiple page requests.  On the other hand, if you've got a fat client application with a dedicated Oracle database connection, it's quite reasonable.

A: First of all,
What's the point in doing
SELECT TABLE1.*, TABLE1.someValue from TABLE1

Wouldn't TABLE1.* automatically select "someValue", so why query it redundantly ?
Secondly for pagination, try the analytical query approach
SELECT * FROM {
    SELECT col1, col2, col3
    , row_number() OVER (order by col1) position
    FROM TABLE1
} WHERE rn >= p_seek and rn < (p_seek+p_count)

p_seek is the starting position and p_count is the number of rows to fetch.
Here instead of col1, col2, col3, etc you can do TABLE1.*, TABLE1.someValue etc.


text:
Q: Autosave on 'belongs_to` Association Fails To Save Associated Model I have a Parent model that maintains a set of Tags based on an aggregation of all the tags of its children:
model Parent
   before_save :agregate_tags

   has_many :children
   has_many :tags

   def agregate_tags
     self.tags = self.children.flat_map(&:tags).uniq
   end

end

The Child model:
class Child
   belongs_to :parent, autosave: true
   has_many :tags
end

When I save the Child the parent is not saved. Why might this be?
When I save child here are no errors and there is no database activity related to Parent. It seems that no attempt is made to save it.
If I create a before_save callback on Child and save parent there, it saves successfully without error.

A: How are you saving child?  If you're not creating or modifying an association with parent, rails doesn't modify the parent record.  Would you really want rails updating parent needlessly every time you modify a child?
You'll need to use before_save to do what you wish (as you've mentioned).


text:
Q: How to bypass the Local Development Server for Google App Engine? The Local Development Server for Google App Engine is great for testing - but we would also like to test against our databases in Google's cloud as well.
We tried setting the --host option for the Local Development Server in the hopes that we could bypass localhost - but it throws an error that it cannot bind our services on Google's x.appspot.com (i.e. where x is our project.)
How does one bypass the local development server so our Python App Engine app connects to Google Cloud SQL and Cloud DataStore in in the Cloud rather than the local versions?

A: Cloud Datastore
There is now a client google-cloud-python that allows you to directly access the datastore assuming the client has the correct credentials.
The easiest way to try this out is in a Cloud Shell -
$ sudo pip install --upgrade google-cloud
$ python
>>> from google.cloud import datastore
>>> client = datastore.Client(project='YOUR-PROJECT-ID')
>>> query = client.query(kind='YOUR-ENTITY')
>>> for result in query.fetch():
>>>   print(result)

You can find more information on authentication in the docs.
Cloud SQL
You can connect to a Cloud SQL instance through the following ways:

*

*IP address (with and without SSL)

*Cloud SQL Proxy (binary or Docker image)

*MySQL Socket Library (Java only)

*Go Proxy Library (Go only)

*Cloud Shell (uses temporary IP whitelisting)

I'd recommend connecting through the Cloud SQL Proxy.
Alternative for testing
I believe it's also worth asking yourself what you are trying to test and whether you can avoid connecting to the prod DB directly. I'd recommend setting up a staging environment instead where you can import a subset of prod data on a regular basis through a script, properly anonymizing sensitive user data and running your E2E tests against that environment to avoid any potential negative side effects on your production system.


text:
Q: How can I run many concurrent commands using QProcess with c ++ I edited the code, The "deneme" variable is a command in the setup.csh file. In the setup.ssh "deneme" command: alias deneme "ls -la". My purpose is to run a command guide in that setup.csh.
Termainal command:
[intern2atlas SETUP]$ source setup.csh
output : /sw/mentor/questasim/10.4a.2
[intern2atlas SETUP]$ deneme
Output: -rw-r----- intern2 Domain Users 4096 Nov 8 14:56 setup.csh,
(I want to run these commands simultaneously with QProcess)
I want to run the "deneme" command in setup.csh
QProcess *process1=new QProcess(this);
process1->setWorkingDirectory("/home/intern2/elif/SETUP");

process1->start("tcsh",QStringList() <<"-c"<<"\"\"source /home/intern2/elif/SETUP/setup.csh\"\"" << "deneme" );

process->waitForBytesWritten();
process1->waitForFinished();
ui.textedit->append(process.readAllStandartOutput());

"deneme" command not working
Gui code and output

Output:

Terminal output:


text:
Q: Decoding error: typeMismatch "Expected to decode Array but found a dictionary instead." I am struggling to decode a JSON. I am trying to decode my JSON with
let decodedData = try decoder.decode(Country.self, from: data)

Here's the codable struct:
struct CountryData: Codable {

    let translations: Name
    let capital: String
    let currencies: [String]

}

struct Name: Codable {
    let fr: String
}

typealias Country = [CountryData]

Here's the JSON:
[
    {
        "name": "Norway",
        "topLevelDomain": [
            ".no"
        ],
        "alpha2Code": "NO",
        "alpha3Code": "NOR",
        "callingCodes": [
            "47"
        ],
        "capital": "Oslo",
        "altSpellings": [
            "NO",
            "Norge",
            "Noreg",
            "Kingdom of Norway",
            "Kongeriket Norge",
            "Kongeriket Noreg"
        ],
        "region": "Europe",
        "subregion": "Northern Europe",
        "population": 5176998,
        "latlng": [
            62.0,
            10.0
        ],
        "demonym": "Norwegian",
        "area": 323802.0,
        "gini": 25.8,
        "timezones": [
            "UTC+01:00"
        ],
        "borders": [
            "FIN",
            "SWE",
            "RUS"
        ],
        "nativeName": "Norge",
        "numericCode": "578",
        "currencies": [
            "NOK"
        ],
        "languages": [
            "no",
            "nb",
            "nn"
        ],
        "translations": {
            "de": "Norwegen",
            "es": "Noruega",
            "fr": "Norvège",
            "ja": "ノルウェー",
            "it": "Norvegia"
        },
        "relevance": "1.5"
    }
]

Error I got:
Decoding error: typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

I couldn't figure out what I have done wrong, I have tried checking my struct with app.quicktype tool but couldn't spot any issue. I am new to Swift, it will be great if someone can give me some advice how on how to resolve this. Thanks

A: your code is correct

I already try it in playground


text:
Q: How do I export data from An Object? I am trying to export an object called coffeeTree from a file called Coffee_Tree.js into a js file called coffee.js so I can grab data from the object. But, I keep getting this:
Uncaught ReferenceError: coffee is not defined
    at Coffee_Tree.js:2
This is the code I have so Far, I am still A js beginner, But I can't figure out what to do I changed the html type to module, but that didn't work.
Here's my code so far:
Coffee_Tree.js
export default coffeeTree = {
    refill: () => {
        coffee.isEmpty = false;
        console.log('refilled');
    },
    drink: () => {
        coffee.isEmpty = true;
        console.log('chug');
    },
    isEmpty: true,
}

coffee.js
import coffeeTree from './Coffee_Tree.js';

console.log(coffeeTree);

Again in the Console I just keep getting this error:
Uncaught ReferenceError: coffee is not defined
    at Coffee_Tree.js:2

A: You need to
(1) use the proper variable name (either coffeeTree or coffee - pick one, don't use both)
(2) An expression exported as default does not get put into the current scope as an identifier. You're currently implicitly creating a global variable and running in sloppy mode. One of the main purposes of having a module system is to avoid global variables when possible. Use named exports instead so that the object can reference itself inside its methods, and without assigning to the global object:
export const coffee = {
    refill: () => {
        coffee.isEmpty = false;
        console.log('refilled');
    },
    drink: () => {
        coffee.isEmpty = true;
        console.log('chug');
    },
    isEmpty: true,
};

import { coffee } from './Coffee_Tree.js';
console.log(coffee);

(I'd also highly recommend using strict mode, if at all possible - if you read the error messages and try to debug them, it'll help you avoid these sorts of mistakes)


text:
Q: Clickable table I created a simple function in JS that generates a table. Now I want to do this: when I click on some cell of the table, the page will alert the value what is inside the cell: variable b, as you can see in the code. I tried it, but I didn´t managed it. is inside the code. I also used Jquery.
The code: JS
    function gen() {
        var rowData = '';
        for (var a = 0; a < 5; a++) {
            rowData += '
';
            for (var i = 0; i < 3; i++) {

                rowData += '';

                rowData += b;

                rowData += '	';

                b++;

            }
            rowData += "
";

        }

        $('#myTableId2').append(rowData);

    }

HTML:

 <button onclick="gen()">Generate</button>

A: I see you're using jQuery.  You can attach a click() event to each  element as I do below.
Note that since b is undefined in your example, I took the liberty of giving it a random value for illustrative purposes.

function gen() {
  let b = Math.floor(Math.random() * 1000) + 1; //generate random value
  var rowData = '';
  for (var a = 0; a < 5; a++) {
    rowData += '
';
    for (var i = 0; i < 3; i++) {

      rowData += '';

      rowData += b;

      rowData += '	';

      b++;

    }
    rowData += "
";

  }

  $('#myTableId2').append(rowData);

  //attach the click event using jQuery
  $("td").click(function(){alert(this.innerText)});

}

<button onclick="gen()">Generate</button>

A: rowData += '';


text:
Q: What happens if you expel the Jews? I haven't been able to find complete informations about expelling the Jews.

*

*how much gold do you get if you do it?

*how much gold does calling them back cost?

*does being heretic (i.e. Cathar) change anything?

A: From the wiki :

*

*Gains 5 time of yearly income in gold, -100 prestige, banish all Jewish courtiers

*Occasional -50 point technology events

*Removes negative opinion modifier from clergy

*Cancels any loan from Jews

*Gains Expelled Jews modifier : -2 diplomacy and -10% global tax modifier

*Gains Arbitrary if currently owns money from Jews

And obviously, you won't be able to borrow money from them anymore.


text:
Q: load more scroll based on div height Load more/infinite scroll button that is based on the div height. Lets say I have a div at 500px in height and the content inside the div is equal to 1000px. How would I load only 500px of the div and with a button load the remaining 500px of the div on click?
I hope this is clear?

A: I would do it with javascript and css
DEMO http://jsfiddle.net/kevinPHPkevin/tnTPw/2/
$('.div').click(function () {
                $(this).addClass('height');

            });


text:
Q: C# newbie - if inside if which is inside another if and so on & try-catch inside try-catch which is inside another try-catch Would you excuse a newbie to C# @ Windows Phone development, I'm starting this because I want to write a weather app for my Windows Phone, hope that wouldn't be a stupid reason.
Also apologize for my poor English.
Mostly speaking, my code is copy & paste from the internet, I also find a lot of help from Stackoverflow, I own you a thanks!
So far, my code runs just fine, I just have some newbie questions regarding the code structure or coding behavior, or something else.
You can see the part of my code as following (you can ignore the detail, but only care about the if and try-catch blocks):
StreamReader LastReader = null;
if (IsolatedStorageSettings.ApplicationSettings.Contains("UpdateAllDay"))
{
    try
    {
        if (IsolatedStorageSettings.ApplicationSettings["UpdateAllDay"].ToString() == "false")
        {
            try
            {
                if (IsolatedStorageSettings.ApplicationSettings.Contains("UpdateStartTime") && IsolatedStorageSettings.ApplicationSettings.Contains("UpdateEndTime"))
                {
                    try
                    {
                        if (DateTime.Now > Convert.ToDateTime(IsolatedStorageSettings.ApplicationSettings["UpdateStartTime"].ToString()) && DateTime.Now < Convert.ToDateTime(IsolatedStorageSettings.ApplicationSettings["UpdateEndTime"].ToString()))
                        {
                            IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication();
                            if (IsolatedStorageSettings.ApplicationSettings.Contains("UpdateRate") && isoFile.FileExists("LastUpdateTime.txt"))
                            {
                                try
                                {
                                    LastReader = new StreamReader(new IsolatedStorageFileStream("LastUpdateTime.txt", FileMode.Open, isoFile));
                                    if ((DateTime.Now - Convert.ToDateTime(LastReader.ReadLine())).TotalSeconds >Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["UpdateRate"].ToString()))
                                    {
                                        LastReader.Close();
                                        if (IsolatedStorageSettings.ApplicationSettings.Contains("CityID"))
                                        {
                                            HttpClient client = new HttpClient();
                                            string url = "http://m.weather.com.cn/data/{0}.html";
                                            string baseUrl = string.Format(url, IsolatedStorageSettings.ApplicationSettings["CityID"].ToString());
                                            try
                                            {
                                                string WeatherResult = await client.GetStringAsync(baseUrl);

                                                if (WeatherResult != null)
                                                {
                                                    StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("WeatherResult.txt", FileMode.OpenOrCreate, isoFile));
                                                    Writer.WriteLine(WeatherResult);
                                                    Writer.Close();

                                                    RootWeatherCore apiData = JsonConvert.DeserializeObject<RootWeatherCore>(WeatherResult);
                                                    await GetData(apiData);

                                                    StreamWriter LastUpdateTime_Writer = new StreamWriter(new IsolatedStorageFileStream("LastUpdateTime.txt", FileMode.OpenOrCreate, isoFile));
                                                    LastUpdateTime_Writer.WriteLine(DateTime.Now);
                                                    LastUpdateTime_Writer.Close();

                                                    return "true";
                                                }
                                            }
                                            catch (Exception) { return "1"; }
                                        }
                                    }

                                }
                                catch (Exception) { return "1"; }
                            }
                        }
                        return "1";
                    }
                    catch (Exception) { return "1"; }
                }
            }
            catch (Exception) { return "1"; }
        }
        else
        {
            IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication();
            if (IsolatedStorageSettings.ApplicationSettings.Contains("UpdateRate") && isoFile.FileExists("LastUpdateTime.txt"))
            {
                try
                {
                    LastReader = new StreamReader(new IsolatedStorageFileStream("LastUpdateTime.txt", FileMode.Open, isoFile));
                    if ((DateTime.Now - Convert.ToDateTime(LastReader.ReadLine())).TotalSeconds > Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["UpdateRate"].ToString()))
                    {
                        LastReader.Close();
                        if (IsolatedStorageSettings.ApplicationSettings.Contains("CityID"))
                        {
                            HttpClient client = new HttpClient();
                            string url = "http://m.weather.com.cn/data/{0}.html";
                            string baseUrl = string.Format(url, IsolatedStorageSettings.ApplicationSettings["CityID"].ToString());
                            try
                            {
                                string WeatherResult = await client.GetStringAsync(baseUrl);

                                if (WeatherResult != null)
                                {
                                    StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("WeatherResult.txt", FileMode.OpenOrCreate, isoFile));
                                    Writer.WriteLine(WeatherResult);
                                    Writer.Close();

                                    RootWeatherCore apiData = JsonConvert.DeserializeObject<RootWeatherCore>(WeatherResult);
                                    await GetData(apiData);

                                    StreamWriter LastUpdateTime_Writer = new StreamWriter(new IsolatedStorageFileStream("LastUpdateTime.txt", FileMode.OpenOrCreate, isoFile));
                                    LastUpdateTime_Writer.WriteLine(DateTime.Now);
                                    LastUpdateTime_Writer.Close();

                                    return "true";
                                }
                            }
                            catch (Exception) { return "1"; }
                        }
                    }
                }
                catch (Exception) { return "1"; }
            }
            return "1";
        }
    }
    catch (Exception) { return "1"; }
}

Would it scare you? Actually I was scared when I wrote this out. It looks kind of urgly or poorly structured, isn't it?
So, my question is, is it a good practice or behavior to use too much loop of if block inside another if block, and try-catch block inside another try-catch block?
I have so many if block because I think the app would function differently under different conditions.
And I use try-catch a lot because I need to handle with the Isolated Storage in Windows Phone environment, which is suggested by many guru from Stackoverflow and also other website.
Is this a normal coding structure or behavior? Then I should get used to it.
Or is there a better method that I am not aware of?
Or would it be a good idea to use a single & "big" try-catch to put all the code inside it? (If I don't care what's the exact exceptions)
Any suggestions or comments would be appreciated, thanks!

A: That structure definitely looks overly complex. The only reason that I  could think that you would have so many nested try...catch blocks is that you think certain operations may fail for a particular reason.
The problem with doing the handling that way is that comes in on how and when you want to handle the exception in one of the nested catches.
If this is the case you can have multiple catch statements for a single try.
Something like this:
try
{
 //Do Something
}
catch(<ExceptionType1> e1) {}
catch(<ExcetionType2> e2){}
catch(Exception e){}

Or if you do not care about the exception you can simply have a general catch that catches all
try
{
 //Do Something
}
catch {}

A: for starters, having try blocks inside each other doesn't do anything as they don't catch different exceptions.
also your catch blocks returns 1. and functions end when they hit a return function. so all ur try/catch is equivalent to a big catch block.
In general  its a good idea to avoid so many nested if's. I'm not familiar with windows phone programming, but a good object oriented solution is to write a function like this
boolean isCorrectCondition(ApplicationSetting as)
{
    return condition1 && condition2 && ... && last condition;
}

and instead of ur monstrous nest of if statements have something like
if(isCorrectCondition(as)) {
// do something here
}


text:
Q: Eclipse validation error deploying EAR to WebLogic: cvc-complex-type.2.4c: Expected element 'module@http://java.sun.com/xml/ns/javaee' Out of the box, it is not possible to deploy an EAR to Oracle WebLogic using Eclipse.
Environment details:

*

*Eclipse version: Indigo (includes Oracle Enterprise Pack for Eclipse 12.1.1.0.0)

*Weblogic version: 10.3.5 (11gR1)

Oracle guide: http://www.oracle.com/technetwork/articles/javaee/marx-oepe-spring-095718.html
The error I receive when trying to start the server is:
java.lang.Exception: Exception received from deployment driver. See Error Log view for more detail.
    at oracle.eclipse.tools.weblogic.server.internal.DeploymentProgressListener.watch(DeploymentProgressListener.java:190)
    at oracle.eclipse.tools.weblogic.server.internal.WlsJ2EEDeploymentHelper.deploy(WlsJ2EEDeploymentHelper.java:486)
    at oracle.eclipse.tools.weblogic.server.internal.WeblogicServerBehaviour.publishWeblogicModules(WeblogicServerBehaviour.java:1466)
    at oracle.eclipse.tools.weblogic.server.internal.WeblogicServerBehaviour.publishToServer(WeblogicServerBehaviour.java:898)
    at oracle.eclipse.tools.weblogic.server.internal.WeblogicServerBehaviour.publishOnce(WeblogicServerBehaviour.java:686)
    at oracle.eclipse.tools.weblogic.server.internal.WeblogicServerBehaviour.publish(WeblogicServerBehaviour.java:539)
    at org.eclipse.wst.server.core.model.ServerBehaviourDelegate.publish(ServerBehaviourDelegate.java:774)
    at org.eclipse.wst.server.core.internal.Server.publishImpl(Server.java:3027)
    at org.eclipse.wst.server.core.internal.Server$PublishJob.run(Server.java:341)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
Caused by: weblogic.management.DeploymentException: VALIDATION PROBLEMS WERE FOUND
  problem: cvc-complex-type.2.4c: Expected element 'module@http://java.sun.com/xml/ns/javaee' before the end of the content in element application@http://java.sun.com/xml/ns/javaee:<null>
    at weblogic.application.internal.EarDeploymentFactory.findOrCreateComponentMBeans(EarDeploymentFactory.java:193)
    at weblogic.application.internal.MBeanFactoryImpl.findOrCreateComponentMBeans(MBeanFactoryImpl.java:48)
    at weblogic.application.internal.MBeanFactoryImpl.createComponentMBeans(MBeanFactoryImpl.java:110)
    at weblogic.application.internal.MBeanFactoryImpl.initializeMBeans(MBeanFactoryImpl.java:76)
    at weblogic.management.deploy.internal.MBeanConverter.createApplicationMBean(MBeanConverter.java:89)
    at weblogic.management.deploy.internal.MBeanConverter.createApplicationForAppDeployment(MBeanConverter.java:67)
    at weblogic.management.deploy.internal.MBeanConverter.setupNew81MBean(MBeanConverter.java:315)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.compatibilityProcessor(ActivateOperation.java:81)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.setupPrepare(AbstractOperation.java:295)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doPrepare(ActivateOperation.java:97)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.prepare(AbstractOperation.java:217)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentPrepare(DeploymentManager.java:747)
    at weblogic.deploy.internal.targetserver.DeploymentManager.prepareDeploymentList(DeploymentManager.java:1216)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handlePrepare(DeploymentManager.java:250)
    at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.prepare(DeploymentServiceDispatcher.java:159)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doPrepareCallback(DeploymentReceiverCallbackDeliverer.java:171)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$000(DeploymentReceiverCallbackDeliverer.java:13)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$1.run(DeploymentReceiverCallbackDeliverer.java:46)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:528)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:178)
Caused by: weblogic.descriptor.DescriptorException: VALIDATION PROBLEMS WERE FOUND
  problem: cvc-complex-type.2.4c: Expected element 'module@http://java.sun.com/xml/ns/javaee' before the end of the content in element application@http://java.sun.com/xml/ns/javaee:<null>

    at weblogic.descriptor.internal.MarshallerFactory$1.evaluateResults(MarshallerFactory.java:245)
    at weblogic.descriptor.internal.MarshallerFactory$1.evaluateResults(MarshallerFactory.java:231)
    at weblogic.descriptor.internal.MarshallerFactory$1.createDescriptor(MarshallerFactory.java:155)
    at weblogic.descriptor.BasicDescriptorManager.createDescriptor(BasicDescriptorManager.java:323)
    at weblogic.application.descriptor.AbstractDescriptorLoader2.getDescriptorBeanFromReader(AbstractDescriptorLoader2.java:788)
    at weblogic.application.descriptor.AbstractDescriptorLoader2.createDescriptorBean(AbstractDescriptorLoader2.java:409)
    at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBeanWithoutPlan(AbstractDescriptorLoader2.java:759)
    at weblogic.application.descriptor.AbstractDescriptorLoader2.loadDescriptorBean(AbstractDescriptorLoader2.java:768)
    at weblogic.application.ApplicationDescriptor.getApplicationDescriptor(ApplicationDescriptor.java:296)
    at weblogic.application.internal.EarDeploymentFactory.findOrCreateComponentMBeans(EarDeploymentFactory.java:178)

I am posting this up in the hope that someone who has been bitten by this before can simply reel off the answer - this question features heavily on Oracle and DevX forums when I post the stack into Google, and has not been answered.
Note: Company constraints insist on the use of the specific version of the software quoted at the top of the question - I am fully aware that this version of WebLogic is not Java EE 6 compliant.

A: Thanks for the steer guys. It appears that my application.xml file is a red herring - whilst I do have one, my Maven POM has a plugin which generates its own during build. The problem was that, for Eclipse, the Deployment Assembly (Right Click > Deployment Assembly) did not contain any references to the WAR and JAR project dependenices. I wrongly assumed that Eclipse would simply detect and use an application.xml file found in the folder hierarchy. An empty application.xml file was being created, and thus the stack trace correctly bemoans the lack of modules to deploy.

A: My problem was with the web.xml file, for some reason, my Eclipse modified the "faces / dynamic web module" of my project, and with it, the header of the web.xml file. The new web.xml file didn't have the "<web-app xmlns:xsi" full header, as soon as I fixed that, the weblogic stopped with the exceptions.


text:
Q: How do I fetch the values from the xml using xmlstarlet in linux The XML file is as below : test.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<metadata>
  <entries>
    <entry>
      <key><![CDATA[bip:DisplayName]]></key>
      <value><![CDATA[MY_Test_Free_Quantity_DM]]></value>
    </entry>
    <entry>
      <key><![CDATA[DESCRIPTION]]></key>
      <value><![CDATA[undefined]]></value>
    </entry>
    <entry>
      <key><![CDATA[propertyMap]]></key>
      <value><![CDATA[1]]></value>
    </entry>
    <entry>
      <key><![CDATA[path]]></key>
      <value><![CDATA[%2FCustom%2FOpen+Quantity+Report%2FData+Models%2FMY_Test_Free_Quantity_DM.xdo]]></value>
    </entry>
  </entries>
</metadata>

Need to extract "%2FCustom%2FOpen+Quantity+Report%2FData+Models%2FMY_Test_Free_Quantity_DM.xdo"

A: $ xmlstarlet sel -t -m "/metadata/entries/entry[key='path']" -v value your.xml
%2FCustom%2FOpen+Quantity+Report%2FData+Models%2FMY_Test_Free_Quantity_DM.xdo


text:
Q: React router does not render page after refresh page I'm creating an simple admin panel with react. For developing and building this project I use snowpack.
In index.jsx file I have this:
<Router basename="admin">
 <Switch>
  <Route path="/pages" component={Pages} />
  <Route exact path="/login" component={Login} />
 </Switch>
</Router>

And in Pages.jsx I have this:

  <BrowserRouter>

Pages

    <Switch>
    {
      pages.length !== 0
      ? pages.map(page => {
        return <Route exact key={page.id} path={'/admin/pages/' + page.path}><Page /></Route>
      })
      : null
    }
    </Switch>
    </BrowserRouter>

Pages I get from the server.
Application is work. And if I use 'http://example.com/admin' I can refresh and react render container (HTML block which I didn't add, cause it's not an issue), but if I refresh on all pages except 'http://example.com/admin' I get:

GET http://localhost:8081/admin/index.js net::ERR_ABORTED 404 (Not Found)

snowpack.config.mjs:
/** @type {import("snowpack").SnowpackUserConfig } */

export default {
  mount: {
    dist: "/",
    src: "/"
  },
  routes: [
    {
      match: 'routes',
      src: '.*',
      dest: '/index.html',
    },
  ],
  plugins: [
    "@snowpack/plugin-sass",
    "@snowpack/plugin-react-refresh",
    "@snowpack/plugin-dotenv",
  ]
}

What I could change or add to fix this?
P.S. Login page also don't render after refresh


text:
Q: iOS migration from Website to app iOS. I have a mobile web site and a mobile app for the same. i want the user to be able to navigate from web to my app through a link. Is it possible for this feature to be feasible when the app is not installed. I know i can use smart app banners when the app is already installed and this feature can be implemented then. But the main problem i am facing is when the user is asked to install the app (from smart app banners) for a particular page of my website. How can i automatically redirect the user to same page on my app from where he clicked the app banner on first launch of app ?

A: This is a problem that Branch, the company I'm working for, solves. It's actually fairly simple to explain, but quite a bit more tricky to implement yourself.
Apple doesn't currently allow you to persist information like that through an install (through the App Store), so you'll need an intermediate server. Now, depending on what devices you want to support, this gets more and more tricky. You mentioned you're only on iOS now, but if you expand to Android, this becomes even more complicated (with the fragmentation of Android devices and browsers, etc). For now, I'll just explain for iOS though. It's basically a two step process, starting with the smart banner on your mobile web page.
The smart banner, when clicked, will try to
 * Launch the app if possible. We do this by trying to load via the app's URI scheme.
 * If the URI Scheme fails (not installed), we send a device fingerprint to our servers based on IP, model, etc. and then send the user to the app store.
The second part is then within the app:
 * When it launches, it needs to ask the server if it was launched via a link click. (whether directly into the app or through the app store and now into the app).
 * It sends along a similar fingerprint, and then the server (if the device matches) will send back the relevant info (the page id, or whatever you use).
 * If the page id is present, you need to present the view controller with that content to the user (you may need to persist this info in your app through a login, if it's behind an auth wall).


text:
Q: Creating dynamic link by requesting data from front-end in Node.js and Express.js This is kind of hard for me to explain but I am trying to shorten my code by creating one link instead of 50 for downloading a form. I will try to explain this a bit better using my code.
I have 5 get requests that do exactly the same thing but download a different file.
router.get('/form1', function (req, res) {
    var file = __dirname + '/../public/forms/form1.pdf';
    res.download(file);
});

router.get('/form2', function (req, res) {
    var file = __dirname + '/../public/forms/form2.pdf';
    res.download(file);
});
etc...

and my front-end link are;
FORM 1
FORM 2
etc...

Is there anything I can do to make this a more dynamic? The only way I can think of is something like this;
router.get('/:formName', function (req, res) {
    // some how do a "req.params.formName"
    var file = __dirname + '/../public/forms/' + req.params.formName + '.pdf';
    res.download(file); // Set disposition and send it.
});

But I don't know how I will get the formName or if thats even possible.

A: Here are some more options to clarify:

*

*Option 1: If you have a folder on the server with a fairly manageable directory structure, simply use express.static to map the physical folder to a virtual one with automatic download:
app.use('/download', express.static(path.join(__dirname, '/public/forms/')))

This will result in any link from the front-end with href='/download/something.pdf' working as long as that file is on the server in the path you mapped (i.e. in /public/forms).

*Option 2 (which David E above answered in essence): In your original code, if you wanted to generate a path handler for a link that looks like /download/form1, /download/form2, it's a very minor modification:
router.get('/download/:formNumber', function (req, res) {
    var file = __dirname + '/public/forms/' + req.params.formNumber + '.pdf';
    res.download(file);
});

*Option 3: You want to authenticate access to the files and potentially support multiple, complex URL schemes to a single handler that can lookup the appropriate physical path and send the file:
router.get('/download/:path[forms|images|files]/:formNumber1', fileRequestHandler);
router.get('/public/downloadFolder2/:formNumber2', fileRequestHandler);
router.get('/public/downloadFolder3/:formNumber3', fileRequestHandler);
function fileRequestHandler(req, res) {
    // Check authentication here - example below from Passport
    if(!req.isAuthenticated())
        return res.status(401).send({err: 'Unauthorized'});

    // Check which form number is supplied and map to appropriate physical file
    if(req.params.formNumber1) {
        // in this example, req.params.path can be one of three allowed sample values - forms or images or files
        var file = __dirname + '/public/' + req.params.path + '/' + req.params.formNumber + '.pdf';
        res.download(file);
    } else if(req.params.formNumber2) {
        // etc.
    }
}

Note: Ezra Chang's point about path validity is important.

A: This response assumes that your route lives in index.js.
router.get('/form/:formName', (req, res, next) => {
  res.download(`${__dirname}/../public/forms/${req.params.formName}.pdf`);
});

FORM 2

Be careful about your path. I don't know whether you can start at a directory, go up a level, then down again.


text:
Q: Assigning a local variable whose name is given as a string Within this itteration:
a1=[1,2,3,4,5]
a2=[1,2,3,4,5]
a1.each_with_index{|a, i| ... = a + a2[i]}

I want to assign to different local variables b1, b2, ..., b5, each per iteration to get:
b1 # => 2
b2 # => 4
b3 # => 6
b4 # => 8
b5 # => 10

I tried:
a1.each_with_index{|a, i| ('b' + i.to_s) = a + a2[i]}

but this doesn't work. Anyone got any ideas?

A: Try using instance_variable_set

A: What you are trying to do (dynamically creating local variables) doesn't make a lot of sense to me. Why don't you just use an array.
a1=[1,2,3,4,5]
a2=[1,2,3,4,5]

a1.zip(a2).inject([]) { |b, (x1, x2)| b << x1 + x2 }

=> [2, 4, 6, 8, 10]

You will achieve the same result. The item in position b[0] will be the sum of a1[0] + a2[0].
There is no easy way to dynamically define a local variable exactly because it does not make a lot of sense. In fact, you will have hard time trying to use those variables anywhere because your code will depend on runtime generated variables.
In other words, how would you ever be able to use b4, if you don't even know if b4 was ever generated. That's why an array is more convenient, you can know the size of the array and access all its items.
You can generate a local variable using eval, but as I said, it's definitely not the best approach.

A: You can use Binding#local_variable_set to set already existing local variables. However, when you use it to set a new local variable (IOW to define one), the new local variable will be defined inside the Binding object but not the outside Binding you created it from.
The same thing happens with eval. Up to Ruby 1.8, eval leaked local variables to the outside scope, but that leak was plugged with Ruby 1.9.
In short, what you want is not possible.

A: You have to use a Binding object.
a1=[1,2,3,4,5]
a2=[1,2,3,4,5]
b = binding()
a1.each_with_index{ |a, i| eval("b#{i + 1} = #{a + a2[i]}", b) }
(1..5).each do |i|
    eval("puts b#{i}", b)
end

Now that the local variable is set you will be able to access it through that binding.
You can see an example HERE


text:
Q: Proving that specific ring is isomorphic to quotient ring let's consider the ring $\mathbb Z[\sqrt 2] := {a+b\sqrt{2} \mid a,b\in \mathbb Z}$. I now want to prove that $\mathbb Z[\sqrt 2]  \cong \mathbb Z [X]/(X^2-2)\mathbb Z[X]$.
What I found on the Internet is how to prove that $\mathbb C \cong \mathbb R[X]/(X^2+1)\mathbb R[X]$: http://people.virginia.edu/~mve2x/3354_Fall2010/lecture26.pdf (page 3)
I really like their approach there because it is clear that they construct an explicit ring isomorphism. However, I cannot take their ring isomorphism because they explicitly exploit that $\mathbb R$ is a field ...
Kind regards,
MathIsFun

A: Take $\varphi :\mathbb Z[X]\to \mathbb Z[\sqrt 2]$ defined by $$\varphi (p(X))=p(\sqrt 2).$$
This is obviously surjective. Moreover $$\varphi (p(X))=0\iff X^2-2\mid p(X).$$
I let you conclude.


text:
Q: Firebase Java Admin SDK beginner from SQL I'm working on a client's Point-of-Sales (POS) software. I was going to use django with MySQL but the client can't pay for a host, so I decided to write it in Java with Firebase. I'm having some trouble thinking in terms of Firebase coming from MySQL.
According to the Firebase documentation, to do relations like I would in SQL, it would have to look like:
inventory : {
    CD001 : {
        genre : {
            "CLASSICAL" : TRUE
    }
}
genre : {
    CLASSICAL : {
        Name : "CLASSICAL"
        inventory : {
            CD001 : TRUE
        }
    }
}

Whereas in SQL I would just put the genre primary key as a foreign key in inventory. Is there a better way to do this in Firebase? It seems for every product that has the genre CLASSICAL I would have to make two updateChildAsync(). Also, any changes (like removing a genre from inventory) I would also have to loop through two DatabaseReference.
If I were to use push to get the generated primary key it would be even worse because I would have to loop through each child just to get the genre name.
I know this may not be the optimal way to make a POS, but given the constraints of the project and that I like learning new stuff, I'm going to stick with it.

A: In NoSQL you will often have the same values in multiple places, to allow the specific use-cases of your app. This is normal, but may take some getting used to if you're coming from a background in relational databases.
To get to grips with Firebase's NoSQL model, I recommend reading NoSQL data modeling, watching Firebase for SQL developers (for Firebase Realtime Database) and Getting to know Clouf Firestore.
For a good example of how to model many-to-many relationships, see Many to Many relationship in Firebase. Your example looks more like a categorization problem, in which case I also recommend reading Firebase query if child of child contains a value.


text:
Q: Execute sqlplus from ant fails to find DYLD_LIBRARY_PATH I'm attempting to run a SQL script from within Apache Ant using the execute tag for sqlplus.
    <exec dir="src/sql" executable="sqlplus" failonerror="true" output="src/sql/test.sql.err">
        <arg value="${db.login}"/>
        <arg value="@test.sql"/>
    </exec>

Sqlplus is working from the command line using the same arguments.
Ant, however returns:
dyld: Library not loaded: /ade/b/2649109290/oracle/sqlplus/lib/libsqlplus.dylib

For the command line I have set:
export DYLD_LIBRARY_PATH=/Applications/instantclient_11_2/

Is there an equivalent action I need to take for Ant to find the libraries?

A: One option is to give SQLcl a try.
 It's the sql scripting engine from sqldev which is sqlplus , plus a lot more
http://www.oracle.com/technetwork/developer-tools/sqlcl/overview/sqlcl-index-2994757.html
The benefit is there there's no libraries it's self contained and uses the JDBC Thin driver for db connectivity.
Here's your ANT example..
<project name="sqlcl" basedir=".">
  <property name="db.login" value="klrice/klrice"/>
  <target name="sqlcl">

  <exec dir="." executable="/Users/klrice/Downloads/sqlcl/bin/sql"
        failonerror="true"
        output="sql/test.sql.err">
        <arg value="${db.login}"/>
        <arg value="@sql/dual.sql"/>
    </exec>
</target>
</project>

Then running...
$ ant sqlcl
Buildfile: /Users/klrice/build.xml

sqlcl:

BUILD SUCCESSFUL
Total time: 3 seconds
587211042:~ klrice$ more sql/test.sql.err

SQLcl: Release 17.4.0 Production on Wed Mar 07 21:59:54 2018

Copyright (c) 1982, 2018, Oracle.  All rights reserved.

Last Successful login time: Wed Mar 07 2018 22:00:08 -05:00

Connected to:
Oracle Database 12c Standard Edition Release 12.1.0.2.0 - 64bit Production

login.sql found in the CWD. DB access is restricted for login.sql.
Adjust the SQLPATH to include the path to enable full functionality.

         1
----------
         1

Disconnected from Oracle Database 12c Standard Edition Release 12.1.0.2.0 - 64bit Production

A: Using the solution @kris-rice suggested, here is my implementation including checking for errors...
<!-- =================================================================== -->
<!-- load plsql tox -->
<!-- =================================================================== -->
<target name="compile.plsql.tox" description="compile plsql for tox">
    <echo message="compile.plsql.tox --------------------"/>
    <mkdir dir="tmp/log"/>
    <exec dir="src/sql" executable="sql" failonerror="true" output="src/sql/tox.all.sql.err">
        <arg value="${db.login.tox}"/>
        <arg value="@tox.all.sql"/>
    </exec>
    <echo message="looking for plsql errors -------------------"/>
    <exec dir="src/sql" executable="grep" failonerror="false" resultproperty="found">
        <arg value="LINE/COL ERROR"/>
        <arg value="tox.all.sql.err"/>
    </exec>
    <fail message="plsql compile errors">
        <condition>
            <equals arg1="${found}" arg2="0"/>
        </condition>
    </fail>
    <echo message="looking for line item errors ---------------"/>
    <exec dir="src/sql" executable="grep" failonerror="false" resultproperty="found">
        <arg value="ERROR at"/>
        <arg value="tox.all.sql.err"/>
    </exec>
    <fail message="sql compile errors">
        <condition>
            <equals arg1="${found}" arg2="0"/>
        </condition>
    </fail>
    <echo message="compile.plsql.tox --------------------"/>
</target>
<!-- =================================================================== -->


text:
Q: if condition onclick - jQuery $('.product-nav li a').click(function() {
  $('.product-nav li').removeClass('active');
  $(this).parent().addClass('active');
  if( $(this).hasClass('tshirts') ){
    $('product').hide();
    $('.product.tshirt').show();
  }
});

.. active class is assigned correctly but the products are not hidden/shown as desired because I think the if condition is not recognized on click?

A: What element is product?
$('product').hide();

You are missing the .
$('.product').hide();

A: It shouldn't have a problem reaching your condition.
You seem to have a typo though. On line #5, you're running a jQuery selector for <product> elements. Do you mean to select elements with the class product? (i.e. $('.product'))?

A:   $('.product-nav li').removeClass('active');
  $(this).parent().addClass('active');

The 1st line removes it, the 2nd line adds it back in.
Do you mean:
$(this).parent().addClass('tshirts');


text:
Q: If I have a MySQL table with multiple colum values the same, how do I delete all but two of the most recent entries? I know this sounds like a duplicate of a few questions, and it may well be, but I've searched through and tried my own implementation of several possible solutions but all of them seem to result in some form of infinite recursion that just chews 100% CPU and does nothing.  That could be because I'm doing it wrong or they aren't appropriate for me, I don't know.
I have a MySQL table structured as follows :
        +--------+------+-----+-------+--------+--------+----------------+
        |   id   | fid  | bid | dec_a | varc_a | varc_b | dec_b | varc_c |
        +--------+------+-----+-------+--------+--------+----------------+
        | 106861 | 4192 |  22 | 1.40  | blah   | blahbr | 0.2   | blahca |
        | 108620 | 4192 |  22 | 1.55  | blah   | blahbe | 0.2   | blahca |
        | 108621 | 4192 |  22 | 1.55  | blah   | blahbq | 0.2   | blahca |
        | 108622 | 4192 |  22 | 1.55  | blah   | blahbw | 0.2   | blahca |
        | 108623 | 4192 |  22 | 1.55  | blah   | blahbe | 0.2   | blahca |
        | 108624 | 4192 |  22 | 1.55  | blah   | blahbf | 0.2   | blahca |
        | 106863 | 4192 |  33 | 1.40  | blah   | blahba | 0.2   | blahca |
        +--------+------+-----+-------+--------+--------+-------+--------+

The "id" value is a BIGINT auto-incrementing value and the data is added in proper chronological order from the source, so I am viewing this as the timestamp.
To establish which data is duplicated I am using the "fid", "bid", "varc_a", "dec_b" and "varc_c" columns. From the example above you can see that there are 6 duplicates based on those columns and those are the first six rows, the seventh row shows where there is variation in the "bid" column but obviously any variation in any of those columns excludes the row as a duplicate.
I can easily visualise what I want to do : There are potentially millions of entries in the database, I want to exclude the 2 most recent rows of data based on the entry id where the "fid", "bid", "varc_a", "dec_b" and "varc_c" column values are the same and then sweep away what's left.
For the life of me I can't figure out how to do that using just MySQL and, as I say, all of the questions and answers I've looked at don't seem to be doing what I want to do or I'm not understanding what's proposed.
I know I can do this with PHP+MySQL by trawling through the data and removing the duplicates but considering I can do it in such a horribly inefficient way quite easily I'm thinking that I'm missing something obvious and I should be able to do it with MySQL alone ?
: Note :
Mike's answer is excellent and it did precisely what I need with a little tweaking given the context of my question.  What I ended up using was this :
DROP TEMPORARY TABLE IF EXISTS keepers1, keepers2, keepers_all;

CREATE TEMPORARY TABLE keepers1 (KEY(id)) ENGINE=MEMORY AS
SELECT fid, bid, varc_a, dec_b, var_c, MAX(id) AS id
FROM market_prices
GROUP BY fid, bid, varc_a, dec_b, varc_c;

CREATE TEMPORARY TABLE keepers2 AS
SELECT fid, bid, varc_a, dec_b, varc_c, MAX(id) AS id
FROM market_prices AS k
WHERE NOT EXISTS (SELECT 1 FROM keepers1 WHERE id = k.id)
GROUP BY  fid, bid, varc_a, dec_b, varc_c;

CREATE TEMPORARY TABLE keepers_all (KEY(id)) ENGINE=MEMORY AS
SELECT id FROM keepers1
UNION ALL
SELECT id FROM keepers2;

DELETE k.* FROM market_prices AS k WHERE NOT EXISTS (SELECT 2 FROM keepers_all WHERE id = k.id);

When grouping be sure to just use the columns that are duplicated and in that last statement your SELECT should be the number of records you want to keep, I needed a SELECT 2 at the end there.
Time to raise a glass to the man of the hour!

A: You will need to write a stored procedure. You can create the stored procedure either via PHP, or MySQL directly:
Creating via PHP
$createProc = "DROP PROCEDURE IF EXISTS `remove_dups`;
    CREATE DEFINER=`root`@`localhost` PROCEDURE `remove_dups`( In id varchar(255))
    BEGIN
        ...my code...
    END;";

$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

//create the stored procedure
$stmt = $conn->prepare($createProc);

$stmt->execute();

Create via MySQL GUI
Simply put the create statement in the text box and run it (against the proper DB):
    CREATE DEFINER=`root`@`localhost` PROCEDURE `remove_dups`( In id varchar(255))
    BEGIN
        ...my code...
    END;";

Then you can call this procedure either from PHP or MySQL.
In your stored proc, you'll want to declare some variables to store the values in and do a check to find rows with the same values (using a cursor), and then check the id against the previous row's. If all the values are the same, delete to one with the lower id.

A: This may be a solution for your problem.
However, since there is no date-time column I am assuming that the id column is the primary key. And it is Auto_increment. So my assumption is that the larger the number the newer the record. (it should be true unless you had some old data dumps into the table)
Make sure you back up your data before you delete as this will cause you a permanent data lost. Even better, you can make a copy of the current table into a different table and work on he new table to make sure the logic below is correct. Then change the queries that I have below to read from tbl_new instead on tbl
you can duplicate your table via something like
CREATE TABLE tbl_new LIKE tbl;

I have left comments for every query
DROP TEMPORARY TABLE IF EXISTS keepers1, keepers2, keepers_all;
-- get the #1 top records
CREATE TEMPORARY TABLE keepers1 (KEY(id)) ENGINE=MEMORY AS
SELECT fid, bid, dec_a, varc_a, varc_b, dec_b, varc_c, MAX(id) AS id
FROM tbl
GROUP BY fid, bid, dec_a, varc_a, varc_b, dec_b, varc_c;

-- get the #2 top records
CREATE TEMPORARY TABLE keepers2 AS
SELECT fid, bid, dec_a, varc_a, varc_b, dec_b, varc_c, MAX(id) AS id
FROM tbl AS k
WHERE NOT EXISTS (SELECT 1 FROM keepers1 WHERE id = k.id)
GROUP BY fid, bid, dec_a, varc_a, varc_b, dec_b, varc_c;

-- create a temp table where you have all he ids that you want to keep
CREATE TEMPORARY TABLE keepers_all (KEY(id)) ENGINE=MEMORY AS
SELECT id FROM keepers1
UNION ALL
SELECT id FROM keepers2;

-- delete all records that you don't want to keep
DELETE k.* FROM tbl AS k WHERE NOT EXISTS (SELECT 1 FROM keepers_all WHERE id = k.id);

if this is a one time clean up job then you should be able to execute the queries from the console. but if you are looking for a recruiting Job them you should probably take this code and put it in a procedure.
Note: here I am using MEMORY TEMPORARY tables for better performance. You may run into an issue that say "Table is Full" this is because you have too many records. then you can increase the value max_heap_table_size for the session
something like
SET SESSION tmp_table_size = 1024 * 1024 * 1024 * 2; -- this will set it to 2G
SET SESSION max_heap_table_size = 1024 * 1024 * 1024 * 2; -- this will set it to 2G

This will give you your current value
SELECT VARIABLES LIKE 'max_heap_table_size';
SELECT VARIABLES LIKE 'tmp_table_size';


text:
Q: bacula-dir.conf configuration to backup wordpress website I'm the beginner of bacula backup solution. I'm trying to backup my website built by wordpress.
This is the Job and FileSet to backup documents root directory.
Job {
  Name = WebServerBackup
  Pool = File
  Client = losttemple-fd
  JobDefs = DefaultJob
  FileSet = WebServerFiles
}

FileSet {
  Name = WebServeFiles
  Include {
    Options {
      signature = MD5
    }
    File = /var/www
  }
}

But the problem is a database, MySQL. Could you please tell me how to backup wordpress website's database by bacula? Is it impossible to backup just some directories?

Thanks. deagh.
I need to run script in remote webserver.
So I added the RunsOnClient option in RunScript.
RunScript {
  RunsWhen = Before
  FailJobOnError = Yes
  RunsOnClient = Yes
  Command = "mysqldump ..."
}

A: You have to add mysqldump or a script which dumps your database before the job run:
RunScript {
   RunsWhen = Before
   FailJobOnError = Yes
   Command = "mysqldump ..."
}

If you need to run script in remote webserver, add the RunsOnClient option in RunScript.
RunScript {
  RunsWhen = Before
  FailJobOnError = Yes
  RunsOnClient = Yes
  Command = "mysqldump ..."
}


text:
Q: SD card mount error I m running into a mount problem with my SD Card. Linux returns this error message when I try to mount my SD:
mount -a
mount: special device /dev/mmcblk0p1 does not exist

Here is the entry in /etc/fstab:
# SD cards
/dev/mmcblk0p1    /sdcard1    auto    rw,auto,sync,flush,uid=1003,gid=1000

The directory /sdcard1 is present, however the device /dev/mmcblk0 and /dev/mmcblk0p1 does not exist.
I uploaded the output of my u-boot configuration, FDT and boot up sequence (output of dmesg) : http://www6.zippyshare.com/v/oG25SwZu/file.html
I m working with a TX48 COM with Linux 3.16 Kernel. I'm new to FDT and does not really know what to do to solve this problem.
I tested the baseboard and SD Card with a TX25 module running the old Linux 2.6.31 Kernel and was able to access the SD card.
Thanks in advance for your help


text:
Q: Can this be a proof of Euler's formula? Let $z=\cos\theta+i\sin\theta$.
We know $z\overline{z}=1$.
$$\overline{z}=\cos\theta-i\sin\theta=\cos(-\theta)+i\sin(-\theta)$$
Suppose $z=e^{i\theta}$. If this is true, this satisfies $z\overline{z}=1$.
$$\overline{z}=\cos(-\theta)+i\sin(-\theta)=e^{-i\theta}$$
$$e^{i\theta}e^{-i\theta}=e^{i\theta-i\theta}=e^0$$
So $z=e^{i\theta}$
$$\boxed{e^{i\theta}=\cos\theta+i\sin\theta}$$

A: See https://en.wikipedia.org/wiki/Begging_the_question. You cannot a priori suppose to be right, then try to not find a contradiction.


text:
Q: XML import into EXCEL via VBA doesnt refresh I am trying to import an XML content into a excel via macro.
I have tried recording the steps and the automatic code created by EXCEL VBA is as below:
code:
Sub Macro4()
'
' Macro4 Macro
'

Sheets("Temp").Select
    Workbooks.Open Filename:= _
        "C:\Users\BERAAR1\Desktop\Utilization_matrix\Requests_Weekly.xml"
    Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    Windows("test.xlsm").Activate
    Sheets("Temp").Select
    ActiveSheet.Paste
    Windows("Requests_Weekly.xml").Activate
    ActiveWindow.Close
End Sub

When I execute the macro again,that just reads only header and the content of the XML doesn't load into the excel.
Could you please recommend any tweaks to the code so that I can import XML into EXCEL without any issue ?

A: Sub test_user2075017()
    ImportXML "C:\Users\BERAAR1\Desktop\Utilization_matrix\Requests_Weekly.xml"
End Sub

And the called sub:
Sub ImportXML(XML_Path As String)
    Dim wB As Workbook
    Set wB = Workbooks.Open(filename:=XML_Path)
    With wB.Sheets(1)
        .Range(.Range("A1"), _
               .Cells(.Cells(.Rows.count,"A").End(xlUp).Row, _
                      .Cells(1,.Columns.count).End(xlToLeft).Column)).Copy
    End With 'wB.Sheets(1)

    With ThisWorkbook.Sheets("Temp")
        .Cells.Clear
        .Range("A1").Paste
    End With 'ThisWorkbook.Sheets ("Temp")

    MsgBox wB.Name & " was imported in sheet : Temp", vbOKOnly + vbInformation
    wB.Close False
End Sub


text:
Q: Try Multiple Ports in Ansible I am writing an ansible playbook to provision a web server for me. Part of this process involves using the geerlingguy/ansible-role-security role (which I use to change the default ssh port). However, since the port changes, you cannot run the playbook over and over without changing the ansible_ssh_port variable. This seems to go against the whole point of idempotence, since you have to edit the playbook between runs. So I was wondering if there was a way to describe 2 ports for ansible to try. That way it would use port 22 the first time the script runs, but all other times it would use the other port.
I tried searching for ways to try different ports, but I couldn't find anything.

A: I had the similar scenario and found an workaround using wait_for and set_fact modules.
The idea is to set ansible_port if a port is accessible.
Below is a sample that checks and sets a port specified using port1 variable. It's not necessary to use ignore_errors or check the result in this sample scenario but could be useful if multiple ports needed to be tested. Also, delegate_to: localhost may be used if a play is using a remote host.
Extend the implementation further using loops, block, rescue etc. as appropriate.
- name: test1
  wait_for:
    host: hostname
    port: "{{ port1 }}"
    timeout: 10
  ignore_errors: yes
  register: result
  delegate_to: localhost

- name: set ansible_port
  set_fact:
    ansible_port: "{{ port1 }}"
  when: not result.failed

A: I had similar issue when it got failed in the gather fact step so I
Disabled gather facts in my playbook:
- hosts: all
  gather_facts: no
  vars:
    refused: "port 22: Connection refused"

Added the tasks that checks the connection (default port is 22)
  - name: Check ssh port
    command: /bin/true
    ignore_unreachable: yes
    register: result
    become: yes

  - name: set ansible_port
    set_fact:
      ansible_port: {{ port }}
    when: result.msg is defined and refused in result.msg


text:
Q: Gauge Pressure and Bar Pressure I ran into a problem trying to calculate the absolute pressure of an isolated system.
I was given that the gauge pressure in a tire is 200kPa or 2 bars. To get the absolute pressure I would have to add 101.3kPa correct or would I have to add 100kPa because that would be adding 1 bar.

A: Its not clear what are you exactly asking! But I guess you are screwing with conversion factors.
 1 bar is 1.01325 atm and inversly
1 atm is  0.987...bar. So for 1 atm you need to add 0.987bar.


text:
Q: RecyclerView Overwrite last element a couple times I'm using MVVC pattern and I'm populating a recyclerView with data from database using Room. At the Logcat, data return correctly and is looped correctly, but recyclerview display seven elements and in the eighth starts to overwrite it with the nineth and tenth elements e after that create 2 more elements with the first 2 elements from list.
I'm coudn't find what is wrong with my code.
So, I'm asking for some help.
AvaliacaoFragment.kt:
class AvaliacaoFragment : Fragment() {

    private lateinit var ctx: Context
    private var _binding: FragmentAvaliacaoBinding? = null
    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!
    private lateinit var textoSemSecoes: TextView
    private lateinit var nomeAvaliacao: TextView
    private lateinit var dataAvaliacao: TextView
    private val args by navArgs<AvaliacaoFragmentArgs>()

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        _binding = FragmentAvaliacaoBinding.inflate(inflater, container, false)
        return binding.root
        // return inflater.inflate(R.layout.fragment_avaliacoes, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        ctx = view.context

        // dialogNovaAvaliacao = MaterialAlertDialogBuilder(ctx, android.R.style.Theme_DeviceDefault_Light_NoActionBar_Fullscreen)
        // dialogNovaAvaliacao = MaterialAlertDialogBuilder(ctx,R.style.AlertDialogTheme)
        // val builder = MaterialDatePicker.Builder.datePicker()

        textoSemSecoes = view.findViewById(R.id.texto_sem_secoes)
        nomeAvaliacao = view.findViewById(R.id.nome_avaliacao)
        dataAvaliacao = view.findViewById(R.id.data_avaliacao)

        nomeAvaliacao.text = args.currentAvaliacao.nome
        dataAvaliacao.text = args.currentAvaliacao.dataCriacao

        /*
        btnAddAvaliacao = view.findViewById(R.id.btn_add_avaliacao)
        btnAddAvaliacao.setOnClickListener {
            findNavController().navigate(R.id.action_navigation_avaliacoes_to_addAvaliacaoFragment)
        }
        */

        // Recycler
        val recyclerAdapter = SecaoAdapter()
        val recyclerView = binding.secaoRecyclerView
        recyclerView.adapter = recyclerAdapter
        recyclerView.layoutManager = LinearLayoutManager(requireContext())

        // ViewModelFactory para passar argumentos para a ViewModel
        val factory = object : ViewModelProvider.Factory {
            override fun <T : ViewModel?> create(modelClass: Class<T>): T {
                return SecaoViewModel(Application(), args.currentAvaliacao.id) as T
            }
        }

        // ViewModel
        mSecaoViewModel = ViewModelProvider(this, factory).get(SecaoViewModel::class.java)
        mSecaoViewModel.readAllData.observe(viewLifecycleOwner, Observer { secaoList ->
            if(secaoList.isNotEmpty()){
                Log.d(TAG, "secaoList: ${secaoList.toString()}")
                Log.d(TAG, "secaoList.size: ${secaoList.size}")
                textoSemSecoes.visibility = View.GONE
                recyclerView.visibility = View.VISIBLE
                recyclerAdapter.setData(secaoList.sortedBy { it.codigo.toInt() })
            } else {
                textoSemSecoes.visibility = View.VISIBLE
                recyclerView.visibility = View.GONE
            }
        })

    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        private val TAG: String = AvaliacaoFragment::class.java.name

        lateinit var mSecaoViewModel: SecaoViewModel
        private lateinit var btnAddSecao: FloatingActionButton
        private lateinit var dialogNovaSecao: MaterialAlertDialogBuilder

    }
}

SecaoAdapter.kt:
class SecaoAdapter: RecyclerView.Adapter<SecaoAdapter.SecaoViewHolder>() {

    private val TAG: String = SecaoAdapter::class.java.name
    private var secaoList = emptyList<Secao>()
    private lateinit var binding: ItemSecaoBinding

    class SecaoViewHolder(itemBinding: ItemSecaoBinding): RecyclerView.ViewHolder(itemBinding.root) {

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SecaoViewHolder {
        binding = ItemSecaoBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return SecaoViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return secaoList.size
    }
    override fun onBindViewHolder(holder: SecaoViewHolder, position: Int) {
        Log.d(TAG, "position: $position")
        val currentItem = secaoList[position]
        Log.d(TAG, "currentItem: ${currentItem.toString()}")

        binding.secaoCodigo.text = currentItem.codigo
        binding.secaoNome.text = currentItem.nome
        binding.secaoMediaTotal.text = currentItem.mediaPositivo.toString()
        binding.secaoPerguntasNaoAplicaveis.text = currentItem.qdePerguntasNaoAplicaveis.toString()
        binding.secaoPerguntasRespondidas.text = currentItem.qdePerguntasRespondidas.toString()
        binding.secaoPerguntasTotais.text = currentItem.qdePerguntas.toString()

        binding.cardSecao.setOnClickListener {
            val action = AvaliacaoFragmentDirections.actionAvaliacaoFragmentToSecaoFragment(currentItem)
            holder.itemView.findNavController().navigate(action)
        }
    }

    fun setData(secao: List<Secao>){
        this.secaoList = secao
        notifyDataSetChanged()
    }
}

fragment_avaliacao.xml:
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
tools:context=".ui.secoes.AvaliacaoFragment">

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/container_titulo_avaliacao"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            >

            <TextView
                android:id="@+id/nome_avaliacao"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:text="@string/padrao_avaliacao_sem_nome"
                android:textSize="24sp"
                android:textColor="@color/colorIcons"
                android:textAlignment="center"
                />

            <TextView
                android:id="@+id/data_avaliacao"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="16dp"
                android:text="@string/padrao_formato_data_hora"
                android:textSize="14sp"
                android:textColor="@color/colorPrimaryLight"
                android:textAlignment="center"
                />

        </LinearLayout>

        <TextView
            android:id="@+id/texto_sem_secoes"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@+id/container_titulo_avaliacao"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:layout_marginStart="8dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="8dp"
            android:textAlignment="center"
            android:textSize="16sp"
            android:text="@string/nenhuma_secao_criada"
            android:textColor="@color/colorPrimaryLight"
            />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/secaoRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintTop_toBottomOf="@+id/container_titulo_avaliacao"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout></androidx.constraintlayout.widget.ConstraintLayout>

Logcat loop from secaoList at the SecaoAdapter (is looping correctly to all elements):

I create a gif to show what is happening with the elements on recyclerView:

Here you can see that it displays seventh element then eighth is replaced by nineth and subsequently replaced by tenth. And final two elements (that should be ninth and tenth) is constructed with first and second list elements.
Thanks for the help in advance.

A: So the mistake here is that you are referencing only one binding in your adapter which is getting overwritten. Every time you call onCreateViewHolder you are changing the binding reference. The reason this looks okay to start with is that the onCreateViewHolder calls are followed by the onBindViewHolder calls for items visible on the screen. However as you scroll, just onBindViewHolder is called in order to rebind the recycled views.
What you should be doing is using your ViewHolder to store the individual bindings and then obtaining a reference in onBindViewHolder with something like holder.binding.
I would recommend you have a read into the view holder pattern and how to implement it!


text:
Q: ipset rules being ignored when blocking Amazon Web Services I'm downloading the list of CIDRs for Amazon Web Services here:
https://ip-ranges.amazonaws.com/ip-ranges.json
And then putting them on a ipset with the line:
sudo ipset -q -A tor $ip

And blocking with iptables with the line:
sudo iptables -A INPUT -m set --match-set tor src -j DROP

In total there are about 65,000 IPs in the ipset tor. It also has tor IPs blocked and a few others and this is working fine for those, but for some reason it seems unable to block any Amazon IPs.
Any ideas?
Full list of rules:
sudo ipset -N whitelist nethash
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -m set --match-set whitelist src -j ACCEPT
sudo iptables -N BLOCK24
sudo iptables -A BLOCK24 -m recent --name blocked --set
sudo iptables -A INPUT -m state --state NEW -m recent --set
sudo iptables -A INPUT -m state --state NEW -m recent --update --seconds 300 --hitcount 200 -j BLOCK24
sudo iptables -A INPUT -m recent --name blocked --rcheck --seconds 86400 -j BLOCK24
sudo iptables -A BLOCK24 -j LOG --log-prefix='[NETFILTER] ' --log-level 7
sudo iptables -A BLOCK24 -j REJECT

Then first I run these to destory and re-create the block list:
sudo iptables -D INPUT -m set --match-set tor src -j DROP
sudo ipset destroy tor
sudo ipset -N tor iphash

Add cira 65K IPs with:
sudo ipset -q -A tor $ip

Add ipset to iptables:
sudo iptables -A INPUT -m set --match-set tor src -j DROP

Again, everything is blocked except Amazon.

A: The set type needs to be hash:net rather than hash:ip as the entries in the JSON file are net/mask notation.


text:
Q: Ckeditor buttons id are changing through browsers Currently using CKEditor, I need to get the buttons id in my toolbar to apply some specific CSS and to get positions of certains button for exemple.
But with Google chrome, the ids of the buttons aren't the same than with mozilla or IE.
An exemple would be more clear:
If i have the samme toolbar, the same code, mozilla will show me this:

    Toolbar

     // My first group of buttons, which contains 2 buttons

         // Code for buttons

    // My second group of buttons

         // Code for buttons

While chrome will display this:

    Toolbar
     // My first group of buttons, which contains 2 buttons

         // Code for buttons

    // My second group of buttons

         // Code for buttons

So my css, for exemple:
#cke_13{
    color: red
}

Will work only with Chrome, because this id do not exist if the code is displayed by mozilla.
For the moment the problem appears only with chrome, all the ids are increased by one.
Does anyone know where the problem could be? Or at least is there a way to choose the id of a button at the creation of it?
I really don't know why this is happening, any solutions would be appreciated.

A: The general way of changing CKEditor skin should be performed by obtaining the source version, making changes in ckeditor/skins and building the editor.
If however you need to change only specific buttons then please note that each button has a unique class assigned which you can change with the same styles or same JavaScript code across different browsers. Please see: .
If you need to change toolbar groups (element holding a group of buttons) then unfortunately there are no unique id's or classes and the only way I can recommend is getting a specific button by its unique class and then getting its closest parent (with JavaScript) which has the class cke_toolbar or cke_toolgroup and is a span.


text:
Q: Flash video player that supports setting cookies? I've tried JWPlayer from my app (C#). It works well, but I can't seem to find cookie support. I need to send a cookie or else the server will return 403 Forbidden. Is there any commercial flash player with cookie support (or I'm missing something in JWPlayer's doc)

A: You could set and get the cookie via C# and pass it to your player with a flashvar.
Or call a js function from the flash movie that will set the cookie.


text:
Q: Error making my first Texworks document I was trying to make my first document using Texworks but in the moment of saving I got this error message:
C:/Users/Nicolò Ruggeri/AppData/Local/MiKTeX/2.9/miktex/log/initexmf.log

You may want to visit the MiKTeX project page (http://miktex.org), if you
need help.
log4cxx: setFile(C:\Users\Nicolò Ruggeri\AppData\Local\MiKTeX\2.9\miktex\log/miktex-pdftex.log,true) call failed.
log4cxx: IO Exception : status code = 720003
log4cxx: No output stream or file set for the appender named [RollingLogFile].

Sorry, but C:\Program Files (x86)\MiKTeX 2.9\miktex\bin\miktex-pdftex.exe did not succeed.

The log file hopefully contains the information to get MiKTeX going again:

  C:/Users/Nicolò Ruggeri/AppData/Local/MiKTeX/2.9/miktex/log/miktex-pdftex.log

You may want to visit the MiKTeX project page (http://miktex.org), if you
need help.

This is what I wrote,based on an online document:
% !TEX encoding = UTF-8
% !TEX program = pdflatex

\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}

\usepackage[utf8]{inputenc}
\usepackage[italian]{babel}

\begin{document}

\title{Un articolo inutile}
\author{A. U. Tore}

\maketitle

\section{Un paragrafo}

Testo che mostra quanto si possa scrivere
 inutilmente.

\subsection{Un paragrafo di secondo livello}

Testo sempre più inutile, ma con léttere accentàte
 e riferimenti allo stranißimo posto chiamato Ööç.

Ci mettiàmo anche un secondo capoverso.

\end{document}

What should I do?

A: I had the same exact problem and fought it for a while. Just got it working!
I believe it behaves the same way as Arduino does with special characters in user name. For me it tries to use AppData under two separate directories.
C:\Users\Filip Granö\AppData and C:\Users\Filip Granö\AppData
When initexmf.exe --quiet --update-fndb tries to update font database it fails and therefore pdflatex fails.
Here's what I did:

*

*closed anything related to miktex

*opened TeXworks as administrator

*tried to run a typeset -> failed

*closed TeXworks

*deleted C:\Users\Filip Granö\AppData (created when ran as administrator)

*opened cmd as administrator

*created a symbolic link: C:\Users\Filip Granö>mklink /D AppData "..\Filip Granö\AppData"

*opened cmd as myself

*ran: C:\Program Files\MiKTeX 2.9\miktex\bin\x64>initexmf.exe --update-fndb  (no output == good)

*tried to run a typeset -> asks to install packages needed

*Install needed packages for user only! - you can set it to do it automatically

Result: it now works for me!