text:
Q: Why is it unnecessary to add 1 when mixing quotes in this use case of .slice() and concatenation? In this tutorial, the section "Making new strings from old parts" gives the task of cutting out undesired data to a achieve human-readable format for train station names.

e.g.

Original string: MAN675847583748sjt567654;Manchester Piccadilly

Desired string: MAN: Manchester Piccadilly

const list = document.querySelector('.output ul');
list.innerHTML = '';
let stations = ['MAN675847583748sjt567654;Manchester Piccadilly',
                'GNF576746573fhdg4737dh4;Greenfield',
                'LIV5hg65hd737456236dch46dg4;Liverpool Lime Street',
                'SYB4f65hf75f736463;Stalybridge',
                'HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield'];

for (let i = 0; i < stations.length; i++) {
  let input = stations[i];
  let code = input.slice(0,3);
  let semiC = input.indexOf(';');
  let name = input.slice(semiC + 1);
  let result = code + ': ' + name;
  let listItem = document.createElement('li');
  listItem.textContent = result;
  list.appendChild(listItem);
}

My solution:

let stations = ['MAN675847583748sjt567654;Manchester Piccadilly',
                'GNF576746573fhdg4737dh4;Greenfield',
                'LIV5hg65hd737456236dch46dg4;Liverpool Lime Street',
                'SYB4f65hf75f736463;Stalybridge',
                'HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield'];
for (let i = 0; i < stations.length; i++) {
  let input = stations[i];
  let stationAbbr = input.slice(0,3);
  let semicolon = input.indexOf(';');
  let stationName = input.slice(semicolon);
  let station = stationAbbr + ': " + stationName;
  let listItem = document.createElement('li');
  listItem.textContent = station;
  list.appendChild(listItem);
}

Tutorial solution:
for (let i = 0; i < stations.length; i++) {
  let input = stations[i];
  let code = input.slice(0,3);
  let semiC = input.indexOf(';');
  let name = input.slice(semiC + 1);
  let result = code + ': ' + name;
  let listItem = document.createElement('li');
  listItem.textContent = result;
  list.appendChild(listItem);
}

The tutorial's construction of result is functionally equivalent to my station.

As you can see, however, I made the mistake of mixing single/double quotes when declaring station.

This actually yields the desired outcome, but fixing the quotes adds a semicolon in middle of the output.

Why does mixing quotes here remove the need to specify + 1 in stationName and name?

A: Going to the tutorial, your code block isn't valid javascript and not working. You can confirm this by pasting the code in the console. Starting a string with ' requires it to finish with '. Using " hasn't signalled for it to end the string and instead becomes part of it.
The tutorial input window doesn't seem to alert you of any errors or update the output when the code cannot execute. I can replicate your issue by selecting show the solution then pasting your code over it. The correct answer remains but that it due to the solution code.
That + 1 is needed to select the character after the semicolon, which will be the start of the station name.


text:
Q: Disable HTML respond format in whole Rails App I use pure javascript frontend template to handle all requests with Rails via JSON API
However,
I don't know why sometimes the exception will give me the error message in HTML format.
Because I've already set the API request format in JSON
Controller (I only keep format.json in the controller)
format.json { render json: @city.errors, status: :unprocessable_entity }

Route.rb
  namespace :api do
    namespace :v1, defaults: {format: 'json'} do
    resources country do
        resources city do
            .....
        end
    end
    end
  end

A:
I don't know why sometimes the exception will give me the error
  message in HTML format.

It's not dependent on your app, it is all about the request and request headers, if somebody make a request as html rails try to render html.

A: Exceptions are rendered in html outside of your controller. You should do it by yourself:
your controller:
begin
  code_for_ok
rescue #some exception
  render json: @city.errors, status: :unprocessable_entity
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I prevent any ActiveRecord::PreparedStatementCacheExpired errors immediately after running `rake db:migrate`? I am working on a Rails 5.x application, and I use Postgres as my database.
I often run rake db:migrate on my production servers. Sometimes the migration will add a new column to the database, and this causes some controller actions to crash with the following error:
ActiveRecord::PreparedStatementCacheExpired: ERROR: cached plan must not change result type

This is happening in a critical controller action that needs to have zero downtime, so I need to find a way to prevent this crash from ever happening.
Should I catch the ActiveRecord::PreparedStatementCacheExpired error and retry the save? Or should I add some locking to this particular controller action, so that I don't start serving any new requests while a database migration is running?
What would be the best way to prevent this crash from ever happening again?

A: I was able to fix this issue in some places by using this retry_on_expired_cache helper:
class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  class << self
    # Retry automatically on ActiveRecord::PreparedStatementCacheExpired.
    # (Do not use this for transactions with side-effects unless it is acceptable
    # for these side-effects to occasionally happen twice.)
    def retry_on_expired_cache(*_args)
      retried ||= false
      yield
    rescue ActiveRecord::PreparedStatementCacheExpired
      raise if retried

      retried = true
      retry
    end
  end
end

I would use it like this:
  MyModel.retry_on_expired_cache do
    @my_model.save
  end

Unfortunately this was like playing "whack-a-mole", because this crash just kept happening all over my application during my rolling deploys (I'm not able to restart all the Rails processes at the same time.)
I finally learned that I can turn off prepared_statements to completely avoid this issue. (See this other question and answers on StackOverflow.)
I was worried about the performance penalty, but I found many reports from people who had set prepared_statements: false, and they hadn't noticed any problems. e.g. https://news.ycombinator.com/item?id=7264171
I created a file at config/initializers/disable_prepared_statements.rb:
db_configuration = ActiveRecord::Base.configurations[Rails.env]
db_configuration.merge!('prepared_statements' => false)
ActiveRecord::Base.establish_connection(db_configuration)

This allows me to continue setting the database configuration from the DATABASE_URL env variable, and 'prepared_statements' => false will be injected into the configuration.
This completely solves the ActiveRecord::PreparedStatementCacheExpired errors and makes it much easier to achieve high-availability for my service while still being able to modify the database.

A: This is solved in Rails 7 by this pull request where an option was added to prepared statements to enumerate the columns when generating those sql statements instead of using table_name.*:
https://github.com/rails/rails/pull/41718
There is no fix  for Rails 6.1 and down. Only Rails 7.
Also, this only fixes it if you are adding columns. If you are removing columns then you will want to add the column to ignored_columns in the first deploy of your app like this:
class Student < ApplicationRecord
  self.ignored_columns = [:my_column_name]
end

And then in the next deploy you can drop the column.


text:
Q: dataset wont update database I'am trying to update database after row has been deleted from dataset like this:
SqlCommand mySelectCommand = new SqlCommand("select * from NameDB", c);
                SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(mySelectCommand);
                TheNewDataSet ds = new TheNewDataSet();
mySqlDataAdapter.Fill(ds, "NameDB");
DataRow[] FilteredRow = ds.Tables["NameDB"].Select("PName like '" + listBox2.SelectedValue.ToString() + "'");
                foreach (DataRow drr in FilteredRow)
                {
                    ds.Tables["NameDB"].Rows.Remove(drr);
                }
                mySqlDataAdapter.Update(ds, "NameDB");
                c.Close();

And nothing happened to database, rows not deleted. According to debugger rows filtered correctly and deleted from DataSet normally. Where is mistake?

A: Looks like you are missing insert/update/delete commands on the sqldataadapter?
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.updatecommand.aspx

A: Ok, first - it is not the dataset doing updates. NEVER EVER. It is the Adapter. The DataSet does not talk to the database.
But: you dont delete the rows, you - kill them (rows.remove).
http://msdn.microsoft.com/en-us/library/feh3ed13(v=vs.80).aspx
You should not use REMOVE but DELETE, which keeps the row with a status to delete it. THe way you do it you remove it, so the adapter never sees it. With ".Delete" the adpater sees the row as deleted, so it can act upon it.

A: I ran into a similar problem today at work, so I would like to answer what I understood, so that this could be of some help in the future for others as well as myself.
From what I understood today, .Remove will take the rows of visually from the grid, but would not mark them as the rows to be deleted when you do AcceptChanges to save the changes to the database. As TomTom mentioned, you should use .Delete instead, which will mark those rows as the one's that needs to be deleted when persisting. If you debug your program and see the dataset in visualizer(?), you could see the difference. If I am correct, .Delete will have the rows marked with exclamation, and .Remove, I think just removes.


text:
Q: How to reference generic Alamofire DataResponse value I would like to write a method that can accept any Alamofire DataResponse value. For example, I might pass in DataResponse<Any> or DataResponse<String>. I cannot find a way to get this to work however. For example if I try just using "DataResonse" like this
static func isTimeout(response: DataResponse) -> Bool {
    if let error = response.result.error {
        if error._code == NSURLErrorTimedOut {
            return true
        }
    }
    return false
}

I get a compile error:
Reference to generic type 'DataResponse' requires arguments in <...>
Insert <Any>.

However if I change the parameter type to be DataResponse<Any>, it will not work for when I have DataResponse<String>. The compile error I get when I try to pass DataResponse<String> into the function is:
Cannot convert value of type 'DataResponse<String>' to expected argument type 'DataResponse<Any>'

I also tried DataResponse<AnyObject> and got the same error as above
and DataResponse<Value> and got this error:
Use of undeclared type 'Value'

Any ideas on how to do this so I don't have to duplicate functions just for the slightly different parameter type?

A: Your forget to infer the generic type. Try this:
static func isTimeout<T>(response: DataResponse<T>) -> Bool {


text:
Q: Can you use Laplace transform to show a function is convex? First, I should say I just know about Laplace transform through Wikipedia.
My question is,
Can you use Laplace transform to show a function is convex? If so, is there any link to an example?
I have a function $\frac{T(z)}{g(z)}$ that I want to show is convex.
If it helps this is the specific question: normal distribution hazard rate increasing function

A: Let's suppose that $f:[0,\infty)\to\Bbb R$ is convex and of slower than exponential growth, so that it has a Laplace transform. Then $f'_+$ (the right-hand derivative of $f$) is right-continuous and non-decreasing. As such $f'_+$ is  the "distribution function" of a measure $\mu$ on $[0,\infty)$: $\mu((a,b]) =f'_+(b)-f'_+(a)$ for $0\le a<b$. Integrate by parts to see that
$$
\lambda^2 \hat f(\lambda)-\lambda f(0)=\int_0^\infty e^{-\lambda x}\mu(dx)=\hat\mu(\lambda), \qquad\lambda>0,
$$
where the $\hat{}$ denotes Laplace transform. It is known that a function is the Laplace transform of a positive measure (like $\mu$) if and only if it is smooth and its derivatives (starting with the zeroth, which must be non-negative) alternate in sign. (Such a function is said to be completely monotone.) Thus it seems that for $f$ to be convex, the function $0<\lambda\mapsto \lambda^2\hat f(\lambda)-\lambda f(0)$ must be completely monotone.


text:
Q: Android floating button and advanced webiew do not work I have a floating button with the android advanced web view, everything displays nicely but when I click the floating button it registers the click in the webview and changes page. Its like I am clicking through the webview.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
    tools:context="net.seekadventure.seekadventure.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

    </android.support.design.widget.AppBarLayout>

    <im.delight.android.webview.AdvancedWebView
        android:id="@+id/newWeb"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        >

    </im.delight.android.webview.AdvancedWebView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_gravity="bottom|end"
        android:layout_marginBottom="24dp"
        android:layout_marginEnd="21dp"
        android:src="@drawable/ic_share" />

    <ProgressBar
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/loader"
        android:layout_weight="1"
        android:layout_gravity="center_vertical|center_horizontal|center"/>

</android.support.design.widget.CoordinatorLayout>

A: Try this make your FloatingActionButton
    android:clickable="true"
    android:focusableInTouchMode="true"
    android:focusable="true"

SAMPLE CODE
<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_gravity="bottom|end"
    android:layout_marginBottom="24dp"
    android:layout_marginEnd="21dp"
    android:clickable="true"
    android:focusableInTouchMode="true"
    android:focusable="true"
    android:src="@drawable/ic_menu_send" />


text:
Q: How do I allow for multiple possible responses in a discord.py command? I'm attempting to set up a Discord bot while being relatively new to discord.py (and in reality, Python 3). I want to add the command "greet", which will prompt the user to say "hello" to it. It only responds to "hello", however, when I want it to respond to both "hello" and "Hello".
The only things I could think about fixing it was placing them in an or statement, which in theory should've made Python 3 and the bot choose between the two responses (as shown below).
@client.event
async def on_message(message):
    if message.content.startswith('~greet'):
        await client.send_message(message.channel, 'Say hello')
        msg = await client.wait_for_message(author=message.author, content=('hello' or 'Hello'))
        await client.send_message(message.channel, 'Hello.')

The original code I had for it was simple and only allowed for the one response of hello.
@client.event
async def on_message(message):
    if message.content.startswith('~greet'):
        await client.send_message(message.channel, 'Say hello')
        msg = await client.wait_for_message(author=message.author, content=('hello' or 'Hello'))
        await client.send_message(message.channel, 'Hello.')

For some reason I can't wrap my head around, it's still not recognizing 'Hello', and only ever allowing me to say 'hello' in response.

A: You should use command notation instead of checking for each message using on_message because it will make your code more readable. What will happen if you have 10 commands? Will you check for 10 strings in your on_message?
If thats's rewrite branch then the commands.Bot accepts a case_insensitive parameter:
bot = commands.Bot(command_prefix='!', case_insensitive=True)

Alternatively, if you want to use multiple words for the same command you can use aliases for example:
@bot.command(aliases=['info', 'stats', 'status'])
    async def about(self):
        # your code here

A: or doesn't behave how you think it does.  'hello' or 'Hello' is evaluated before being passed to wait_for_message, and is equal to 'hello'.
Instead, you can provide a check function to wait_for_message:
def is_hello(message):
    return message.content.lower() == 'hello'

msg = await client.wait_for_message(author=message.author, check=is_hello)


text:
Q: I am trying to improve my run times with Chapel for matrix multiplication I am trying to improve my matrix multiplication speed.
Is there other implementations I can do that would speed it up
Here are my results so far, I tried doing 8192 but it took over 2 hours and my ssh connection timed out.

here is my implementation:
use Random, Time;
var t : Timer;
t.start();

config const size = 10;
var grid : [1..size, 1..size] real;
var grid2 : [1..size, 1..size] real;
var grid3 : [1..size, 1..size] real;

fillRandom(grid);
fillRandom(grid2);

//t.start();
forall i in 1..size {
    forall j in 1..size {
        forall k in 1..size {
            grid3[i,j] += grid[i,k] * grid2[k,j];
        }
    }
}
t.stop();
writeln("Done!:");
writeln(t.elapsed(),"seconds");
writeln("Size of matrix was:", size);
t.clear();

I am comparing times to an MPI implementation in c++. I am wondering if there is a way to distribute my matrix to my two locales similar to MPI?

A: This kind of nesting of the forall loops does not give the best performance in our current implementation. Your algorithm will execute faster if you iterate over a single 2-d domain that defines the iteration space of (i,j). Having a serial loop over k will avoid the data race on updating grid3[i,j]. For example:
....
const D2 = {1..size, 1..size};
forall (i,j) in D2 do
  for k in 1..size do
    grid3[i,j] += grid[i,k] * grid2[k,j];

To distribute your matrices, you could use for example the Block distribution - see the example in our online docs. When you distribute, you will of course need to be mindful of the additional communication between locales.
When testing performance, be sure to compile with --fast .

A: In Chapel, forall loops do not automatically distribute work or data across distinct locales (think: compute nodes or memories).  Instead, the forall loop invokes the parallel iterator associated with the thing over which you're iterating.
So, if you're iterating over something that is local to a single locale like a range (as in your code's use of 1..size) or a non-distributed domain or array (like grid in your code), all of the tasks used to implement the parallel loop will execute locally on the original locale.  In contrast, if you are iterating over a distributed domain or array (e.g., one that is Block-distributed), or invoking a distributed iterator (e.g., one from the DistributedIters module), the tasks will be distributed across all the locales that the iterand targets.
As a result, any Chapel program that does not refer to other locales—whether explicitly via on-clauses or implicitly via abstractions that wrap on-clauses, like the distributed arrays and iterators mentioned above—will never use resources other than the initial locale's.
I also wanted to offer a side note on distributed algorithms:  Even if you were to update your program above to distribute the grid arrays and forall loops across multiple locales, the triply-nested loop approach is rarely an optimal matrix multiplication algorithm on distributed memory systems, as it doesn't optimize for locality very well.  Better might be to investigate matrix multiplication algorithms designed for distributed memory (e.g., SUMMA).

A:
Ex-post remark: see the benchmarked Vass' proposed performance edge on the hosted eco-system, would be great to reproduce this on multi-locale silicon so as to prove it universal for larger scales...

Performance? Benchmark! ... always, no exceptions, no excuse - surprises not seldom -ccflags -O3
This is what makes chapel so great. Thanks a lot the Chapel team for developing and improving such great computing tool for the HPC over more than the last decade.
With a full love in true-[PARALLEL] efforts, the performance is always a result of both the design practices and underlying system hardware, never a just syntax-constructor granted "bonus".
Using a TiO.run online IDE  for demo-test, the results for a single locale silicon are these:
TiO.run platform uses   1 numLocales,
               having   2 physical CPU-cores accessible (numPU-s)
                 with   2 maxTaskPar parallelism limit

For grid{1,2,3}[ 128, 128] the tested forall sum-product took       3.124 [us] incl. fillRandom()-ops
For grid{1,2,3}[ 128, 128] the tested forall sum-product took       2.183 [us] excl. fillRandom()-ops
For grid{1,2,3}[ 128, 128] the Vass-proposed sum-product took       1.925 [us] excl. fillRandom()-ops

For grid{1,2,3}[ 256, 256] the tested forall sum-product took      28.593 [us] incl. fillRandom()-ops
For grid{1,2,3}[ 256, 256] the tested forall sum-product took      25.254 [us] excl. fillRandom()-ops
For grid{1,2,3}[ 256, 256] the Vass-proposed sum-product took      21.493 [us] excl. fillRandom()-ops

For grid{1,2,3}[1024,1024] the tested forall sum-product took   2.658.560 [us] incl. fillRandom()-ops
For grid{1,2,3}[1024,1024] the tested forall sum-product took   2.604.783 [us] excl. fillRandom()-ops
For grid{1,2,3}[1024,1024] the Vass-proposed sum-product took   2.103.592 [us] excl. fillRandom()-ops

For grid{1,2,3}[2048,2048] the tested forall sum-product took  27.137.060 [us] incl. fillRandom()-ops
For grid{1,2,3}[2048,2048] the tested forall sum-product took  26.945.871 [us] excl. fillRandom()-ops
For grid{1,2,3}[2048,2048] the Vass-proposed sum-product took  25.351.754 [us] excl. fillRandom()-ops

For grid{1,2,3}[2176,2176] the tested forall sum-product took  45.561.399 [us] incl. fillRandom()-ops
For grid{1,2,3}[2176,2176] the tested forall sum-product took  45.375.282 [us] excl. fillRandom()-ops
For grid{1,2,3}[2176,2176] the Vass-proposed sum-product took  41.304.391 [us] excl. fillRandom()-ops

--fast --ccflags -O3

For grid{1,2,3}[2176,2176] the tested forall sum-product took  39.680.133 [us] incl. fillRandom()-ops
For grid{1,2,3}[2176,2176] the tested forall sum-product took  39.494.035 [us] excl. fillRandom()-ops
For grid{1,2,3}[2176,2176] the Vass-proposed sum-product took  44.611.009 [us] excl. fillRandom()-ops

RESULTS:
On a single-locale ( single, virtualised processor, 2 cores, running all public time-constrained ( < 60 [s] ) time-shared public workloads online IDE ) device the still sub-optimal ( Vass' approach being further about 20% faster ) yields  for grid scales 2048x2048 about ~ 4.17 x faster results than the Nvidia Jetson-hosted computing. This performance edge seems to further grow larger for larger memory layouts, as the scope of the memory-I/O grows and CPU-L1/L2/L3-cache pre-fetching will (ought follow the ~ O(n^3) scaling) further improve the CPU-based NUMA platforms' performance edge.
Would be great to see the achievable performance and ~ O(n^3) scaling obedience as being executed on multi-locale devices and native Cray NUMA cluster platforms.

use Random, Time, IO.FormattedIO;
var t1 : Timer;
var t2 : Timer;

t1.start(); //----------------------------------------------------------------[1]

config const size = 2048;

var grid1 : [1..size, 1..size] real;
var grid2 : [1..size, 1..size] real;
var grid3 : [1..size, 1..size] real;

fillRandom(grid1);
fillRandom(grid2);

t2.start(); //====================================[2]

forall i in 1..size {
    forall j in 1..size {
        forall k in 1..size {
            grid3[i,j] += grid1[i,k] * grid2[k,j];
        }
    }
}

t2.stop(); //=====================================[2]
t1.stop(); //-----------------------------------------------------------------[1]
             writef( "For grid{1,2,3}[%4i,%4i] the tested forall sum-product took %12i [us] incl. fillRandom()-ops\n",
                      size,
                      size,
                      t1.elapsed( TimeUnits.microseconds )
                      );
             writef( "For grid{1,2,3}[%4i,%4i] the tested forall sum-product took %12i [us] excl. fillRandom()-ops\n",
                      size,
                      size,
                      t2.elapsed( TimeUnits.microseconds )
                      );
///////////////////////////////////////////////////////////////////////////////////
t1.clear();
t2.clear();

const D3 = {1..size, 1..size, 1..size};

t2.start(); //====================================[3]

forall (i,j,k) in D3 do
  grid3[i,j] += grid1[i,k] * grid2[k,j];

t2.stop(); //=====================================[3]
             writef( "For grid{1,2,3}[%4i,%4i] the Vass-proposed sum-product took %12i [us] excl. fillRandom()-ops\n",
                      size,
                      size,
                      t2.elapsed( TimeUnits.microseconds )
                      );
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
//       TiO.run platform uses   1 numLocales, having   2 physical CPU-cores accessible (numPU-s) with   2 maxTaskPar parallelism limit
writef( "TiO.run platform uses %3i numLocales, having %3i physical CPU-cores accessible (numPU-s) with %3i maxTaskPar parallelism limit\n",
                      numLocales,
                      here.numPUs( false, true ),
                      here.maxTaskPar
                      );


text:
Q: cound't start express app using pm2 I do nodemon it's fine but too bad nodemon isn't restart the app when something happened.
Where's what i've tried in my ubuntu server :

*

*npm install pm2 -g

*go to my app directory and do pm2 start app.js

*pm2 startup ubuntu
My app still has 502 bad gateway error. Sigh why does this happens? I do nodemon it's running.. Strange thing is in the terminal pm2 did show an app and it's online :(

A: 1) Check if your application is listed in PM2, use the command pm2 list
2) Running apps should  be listed, you can either find an online or errored
status for each app

3) If your app is online, try to curl localhost:port ( if this works, something is wrong with your firewall or nginx / apache configuration)
4) If it is errored, please check pm2 log   -  ~/.pm2/pm2.log'

A: If pm2.log shows "... had too many unstable restarts ...", try the solution https://stackoverflow.com/a/30651668/3054511


text:
Q: Why should I use Firewall Zones and not just Address Objects? I appreciate Firewall Address Objects and Address Groups - they simplify management by letting me give a name to a group of addresses.
But I don't understand what Firewall Zones (LAN, WAN, DMZ, etc.) do for me over Address Groups.  I know all firewalls have them, so there must be a good reason.  But what do I gain by stating a rule applies to all traffic from LAN Zone to WAN Zone which comes from LAN Address Group to WAN Address Group? Why not just mention the Address Groups?

A: Firewall zones help document what is happening.  The standard groups have standard restrictions.  It is much easy to identify the fault in this rule.
Allow port 80 from NET to LAN
It isn't clear when you have this
Allow port 80 from 0.0.0.0/0 to 192.0.2.0/16
Typically zones will be assigned to interfaces or vlans with or without address restrictions.  With tight rulesets, machines in the wrong zone may refuse to run correctly.

A: Each firewall zone corresponds with a specified security requirement. A group of network blocks may correspond with same specified security requirement. A firewall zone may accommodate a group of network blocks or objects. Firewall is network security device, it use zones to separate network.
LAN and WAN are not firewall zone names. Trust and untrust are firewall zone names or network security terms.

A: Address groups are traditionally sequential IP addresses, say 192.168.0.0./24 but your LAN may comprise of 192.168.0.0/24 and 10.1.1.0/24 and not all firewalls will permit joining these together in a single group
Secondly, the LAN segments are not always defined by IP address, but there are devices that assign designations to physical ports. So everything that is inbound on Port 1 is from the DMZ, and Port 2 is from the LAN, and Port 3 is the Internet (A Snapgear SG530 is the first device I can think of off the top of my head that is configured like this).


text:
Q: Periodic app restarts in a Docker container We're running a Node.js/Express application which runs for a few hours and will then start to throw 504 errors for no good reason. Since we're currently unable to track these errors down we need to restart the application every hour or so to ensure it's still running during the weekend.
Our Ubuntu server runs Dokku, which then has a container setup for our application. Every time the application spits a 504 we have to run docker restart appid as root.
So what's the best way of automatically restarting the node process every hour?

A:
throw 504 errors for no good reason

It's throwing these because you application is crashing

currently unable to track these errors down

You have to track them down. They are very likely unhandled exceptions which you can catch and log via:
process.on('uncaughtException', function(error) {
   //look Ma, I died
});

So what's the best way of automatically restarting the node process every hour?

Since I'd feel bad not at least attempting to address you actual question, even though you are most certainly fixing the symptom instead of the problem in a seriously bad way...
Use cron. Put a script in /etc/cron.hourly/restart_express to do it. Make sure the script file has execute permissions and conforms to the run-parts naming constraints (no dots, etc).


text:
Q: org.springframework.web.servlet.DispatcherServlet noHandlerFound : Spring MVC I am new to spring MVC. I tried creating small hello world app but it is not running as expected.
I am always getting error
org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/FitnessTracker/greeting.html] in DispatcherServlet with name 'fitTrackerServlet'
I know this error is very common and there are lots of links available on the google but none of them worked for me. Any help would be appreciated.
Here is the code snippet
HelloController.java
@Controller
public class HelloController {

@RequestMapping(value = "/greeting")
public String sayHello(Model model) {
model.addAttribute("greeting","Hello World!!!!");
return "hello";
}}

hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
Insert title here
</title>
</head>
<body>
<h1>
${greeting}
</h1>
</body>
</html>

fitTrackerServlet-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc
                    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
                    http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context.xsd">

<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="com.firstspringmvc.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/jsp/"
        p:suffix=".jsp"/>
</beans>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
    <servlet-name>fitTrackerServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>fitTrackerServlet</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

Project Structure

A: The URL /greeting does not have any .html at the end, so the servlet will not going to use the DispatcherServlet, because *.html pattern does not match the /greeting, and this will result in 404.
Change your web.xml such:
<servlet-mapping>
    <servlet-name>fitTrackerServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>


text:
Q: Upload file to Azure Datalake Store from local using Java SDK Is there any way to upload files from local to ADLS using Java SDK? I have tried using the following code to upload but the code is not getting compiled as it says the constructor is not visible.
com.microsoft.azure.datalake.store.Utils ut=new com.microsoft.azure.datalake.store.Utils(adlStoreclient);

ut.upload(filePathToUpload, fileToUpload, IfExists.OVERWRITE);

A: I checked the official doc, there are create,list,delete methods etc. except upload and download method in Java SDK.
Then I searched the Azure Data Lake java sdk source code , it also doesn't seem to contain upload and download method in ADLStoreClient Class.
Based on this situation, I suggest you using REST API to upload file to ADL.
You need to follow this doc to upload data into ADL via REST API. How to get the application id and secretkey you could refer to official document. More detail steps to get the permission to access the datalake you could refer to another SO thread.
Get Access Token sample code:
private static String clientId = "***";
private static String authTokenEndpoint = "https://login.microsoftonline.com/***/oauth2/token";
private static String clientKey = "***";

public static void main(String[] args) throws IOException {
        AccessTokenProvider provider = new ClientCredsTokenProvider(authTokenEndpoint, clientId, clientKey);
        String accessToken=provider.getToken().accessToken;
}

Then use this Upload Data steps to upload your local file into ADL.
Hope it helps you.

A: I managed to solve the issue.
The SDK provides a method to upload files like I mentioned in my question. Also, I had mentioned that the constructor was not visible. So, I found the upload methods from the sdk here (https://github.com/Azure/azure-data-lake-store-java/blob/master/src/main/java/com/microsoft/azure/datalake/store/Utils.java) and implemented the same concept to stream the data to ADLS from my local file.


text:
Q: opening a project in Qt which already has been created in Qt I have created a simple GUI in Qt as a part of an example. Now I am trying to load the project in Qt again. So I go to File -> Open File or Project. Then I navigate to the folder that associated .pro file is located and open it. Unfortunately, none of the .cpp and .ui files show up at this point. It just looks like a blank project with nothing in there. Even in this condition, I can compile and run the project without any issue. I have tried 2-3 more projects that I already have created in the past and I see the same thing. Am I missing something here? Should I add all other files individually every time (really do not think so)?
I have also tried to open .user file in Qt, but it only shows XML file and nothing else.
Thanks for your help
Content of .pro file:
#-------------------------------------------------
#
# Project created by QtCreator 2015-01-08T13:07:39
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = new
TEMPLATE = app

SOURCES += main.cpp\
    mainwindow.cpp

HEADERS  += mainwindow.h

FORMS    += mainwindow.ui

A: Your sidebar is probably not set to show any project items. In "Edit" mode, click the drop-down menu on the top-left and select "Projects".
See also: User Interface | Qt Creator


text:
Q: Drag and Drop Matching Type game with groupings in flash sorry for the misunderstandings in my program, i'm quite new here and i am also new in using flash. here is the sample output that i used in my code
![sample output(http://i1114.photobucket.com/albums/k532/deadmaster2903/sample.jpg)

and here is the code i used:
 var objectoriginalX:Number;
 var objectoriginalY:Number;
 var score:Number = 0;
 var count:Number = 30;
 var myTimer:Timer = new Timer(1000,count);
 myTimer.addEventListener(TimerEvent.TIMER, countdown);
 myTimer.start();
 if (myText_txt.text == "0")
 {
myText_txt.text ="Times Up!";
 }
 function countdown(event:TimerEvent):void
 {
myText_txt.text = String((count)-myTimer.currentCount);
 }
 //fall
 fallapple_mc.buttonMode = true;
 fallapple_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 fallapple_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 fallchicory_mc.buttonMode = true;
 fallchicory_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 fallchicory_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 fallchilipeppers_mc.buttonMode = true;
 fallchilipeppers_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 fallchilipeppers_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 fallchinesecabbage_mc.buttonMode = true;
 fallchinesecabbage_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 fallchinesecabbage_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 fallcranberries_mc.buttonMode = true;
 fallcranberries_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 fallcranberries_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 fallcucumber_mc.buttonMode = true;
 fallcucumber_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 fallcucumber_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 falldates_mc.buttonMode = true;
 falldates_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 falldates_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 fallgrapes_mc.buttonMode = true;
 fallgrapes_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 fallgrapes_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 fallleaflettuce_mc.buttonMode = true;
 fallleaflettuce_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 fallleaflettuce_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 fallnuts_mc.buttonMode = true;
 fallnuts_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 fallnuts_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 fallpersimmon_mc.buttonMode = true;
 fallpersimmon_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 fallpersimmon_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 fallpomegranates_mc.buttonMode = true;
 fallpomegranates_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 fallpomegranates_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 //spring
 springasparagus_mc.buttonMode = true;
 springasparagus_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 springasparagus_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 springbasil_mc.buttonMode = true;
 springbasil_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 springbasil_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 springbeans_mc.buttonMode = true;
 springbeans_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 springbeans_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 springbeets_mc.buttonMode = true;
 springbeets_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 springbeets_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 springberries_mc.buttonMode = true;
 springberries_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 springberries_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 springiceberg_mc.buttonMode = true;
 springiceberg_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 springiceberg_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 springmango_mc.buttonMode = true;
 springmango_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 springmango_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 springpapaya_mc.buttonMode = true;
 springpapaya_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 springpapaya_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 springpeas_mc.buttonMode = true;
 springpeas_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 springpeas_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 springradish_mc.buttonMode = true;
 springradish_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 springradish_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 springrhubarb_mc.buttonMode = true;
 springrhubarb_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 springrhubarb_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 springshallots_mc.buttonMode = true;
 springshallots_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 springshallots_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 //summer
 summerapricot_mc.buttonMode = true;
 summerapricot_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 summerapricot_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 summerbellpepper_mc.buttonMode = true;
 summerbellpepper_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 summerbellpepper_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 summerbrocolli_mc.buttonMode = true;
 summerbrocolli_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 summerbrocolli_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 summercherries_mc.buttonMode = true;
 summercherries_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 summercherries_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 summercorn_mc.buttonMode = true;
 summercorn_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 summercorn_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 summerfigs_mc.buttonMode = true;
 summerfigs_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 summerfigs_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 summerokra_mc.buttonMode = true;
 summerokra_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 summerokra_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 summerpeaches_mc.buttonMode = true;
 summerpeaches_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 summerpeaches_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 summerplum_mc.buttonMode = true;
 summerplum_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 summerplum_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 summersquash_mc.buttonMode = true;
 summersquash_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 summersquash_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 summertomato_mc.buttonMode = true;
 summertomato_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 summertomato_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 summerwatermelon_mc.buttonMode = true;
 summerwatermelon_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 summerwatermelon_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 //winter
 winteravocado_mc.buttonMode = true;
 winteravocado_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 winteravocado_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 winterbrusselsprouts_mc.buttonMode = true;
 winterbrusselsprouts_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 winterbrusselsprouts_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 wintercabbage_mc.buttonMode = true;
 wintercabbage_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 wintercabbage_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 wintercauliflower_mc.buttonMode = true;
 wintercauliflower_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 wintercauliflower_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 winterceleryroots_mc.buttonMode = true;
 winterceleryroots_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 winterceleryroots_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 winterfennel_mc.buttonMode = true;
 winterfennel_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 winterfennel_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 wintergrapefruit_mc.buttonMode = true;
 wintergrapefruit_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 wintergrapefruit_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 wintermandarin_mc.buttonMode = true;
 wintermandarin_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 wintermandarin_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 wintermushrooms_mc.buttonMode = true;
 wintermushrooms_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 wintermushrooms_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 winterpears_mc.buttonMode = true;
 winterpears_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 winterpears_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 winterspinach_mc.buttonMode = true;
 winterspinach_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 winterspinach_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
 wintersquash_mc.buttonMode = true;
 wintersquash_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
 wintersquash_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);

 function pickupObject(event:MouseEvent):void
 {
event.target.startDrag(true);
event.target.parent.addChild(event.target);
objectoriginalX = event.target.x;
objectoriginalY = event.target.y;
response_txt.text = " ";
 }
 function dropObject(event:MouseEvent):void
 {
event.target.stopDrag();
var matchingTargetName:String = "target" + event.target.name;
var matchingTarget:DisplayObject = getChildByName(matchingTargetName);
if (event.target.dropTarget != null && event.target.dropTarget.parent == matchingTarget)
{
    event.target.removeEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
    event.target.removeEventListener(MouseEvent.MOUSE_UP, dropObject);
    event.target.buttonMode = false;
    event.target.x = matchingTarget.x;
    event.target.y = matchingTarget.y;
    response_txt.text = "You did it!";
    score++;
    scoreField.text = String(score);
}
else
{
    event.target.x = objectoriginalX;
    event.target.y = objectoriginalY;
    response_txt.text = "Try again";
}
 };

so from what i have said before, if you could see the gray boxes and are named with their specified type, that is the dog/cat box i was referring to before. and the images above are the kinds i was talking to

so the problem were as you could see in the image, the chicory vegetables is placed under the fall (where it belongs to) in the 2nd box, from the code reference i have seen, they do it this way.
OBJECT which is the item is only equal to 1 CONTAINER which is the box
i kept on searching for ways that will let 1 image if dragged and dropped to the specified group types, it will be correct (even if yo place it on the 1st box, the image will automatically be in the 2nd box if the group is true)
also, i noticed my timer isn't working, and the text that states whether the answer is true or false produces wrong or incomplete output. if you see ou i it that was what im referring to which is supposed to be you did it
thanks for those who will answer. im still searching for solutions but i cant seem to find the same problem that i am having

A: It is very hard to answer this question as you're not showing us any code, therefore I'll answer it with the concept I think is correct.
If I understood you correctly, you have a hierarchy of concepts, that is, first there is dog, then there is Golden Retrievers and Labrador, and the same for cats. You need to organize your code or your graphics, in a way that the Labrador and Golden Retriever are "sons" of Dog, that way it is very easy to verify if they're a dog or not. You can do this either with hierarchy (super and sub classes), or by making the Labrador box a son of the Dog box, that is, the .parent of the Labrador box will point to the Dog box.
If you need a better answer, you'll have to elaborate more on your question, either by showing us some code or how your .fla is organized and how you're verifying things.

A: OK.
Here is what I think you want:
Make a Fruit go into "Fall" group, but whatever gray box you place it on (inside "Fall"), make that specific fruit always drop itself to box #2 (second box in the top row)
Here is how to attempt to do that (these are code snipets):
fallapple_mc.buttonMode = true;
fallapple_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
fallapple_mc.addEventListener(MouseEvent.MOUSE_UP, dropObject);
fallapple_mc.droppedGroupName = "Fall"; //I can't use the fallapple_mc.name, since it's "fallapple_mc", not the group name that I want so I have to input the required value manually into this variable
fallapple_mc.droppedBoxIndex = 2; // here I manually input the correct box index for the group

Now that the required data is setup, you have to change the dropObject function a little bit (and a few other things, more about that later):
function dropObject(event:MouseEvent):void
{
    event.target.stopDrag();
    //CHANGES BELLOW
    //var matchingTargetName:String = "target" + event.target.name;
    var matchingTargetName:String = "target" + event.target["droppedGroupName"]; //dynamic access to a variable (the []s) to stop the compiler from being annoying for you...
    var matchingTarget:DisplayObject = getChildByName(matchingTargetName);
    if (event.target.dropTarget != null && event.target.dropTarget.parent == matchingTarget)
    {
        event.target.removeEventListener(MouseEvent.MOUSE_DOWN, pickupObject);
        event.target.removeEventListener(MouseEvent.MOUSE_UP, dropObject);
        event.target.buttonMode = false;
        //CHANGES BELLOW
        //event.target.x = matchingTarget.x;
        //event.target.y = matchingTarget.y;
        event.target.x = matchingTarget.getChildByName("box"+event.target["droppedBoxIndex"]).x; //Here getChild returned the *correct box* so i use it's x and y to position it (might be off a little)!
        event.target.y = matchingTarget.getChildByName("box"+event.target["droppedBoxIndex"]).y;
        response_txt.text = "You did it!";
        score++;
        scoreField.text = String(score);
     }
     else
     {
        event.target.x = objectoriginalX;
        event.target.y = objectoriginalY;
        response_txt.text = "Try again";
     }
 };

Prerequisites:
1) Above changes will fail if you do not change instance names of the Fall group movieclip to "targetFall".
2) Above will fail if inside movieclip 'targetFall' you do not make the boxes (movieclips) have instance names on them. Those boxes need to have instance names like "box1", "box2", "box3" etc in order for this code to function.
That should give you something rudimentary to start to toy with... expect this code to fail, I am programming blind, but it's close to how it should look so trace trace trace variables and their values or debug debug debug the #### out of this until you get it to work...
If you get stuck, feel free to ask for clarifications/help in the comments of this answer...


text:
Q: k8s tasks slowdown with no excess CPU or RAM usage I have a small virtualised k8s cluster running on top of KVM on 2 physical machines. After deploying Ceph (a storage framework), all the k8s tasks like creating containers or starting containers became insufferably slow, like taking over a minute to get from creating to starting a container.
I checked the nodes for excess CPU or RAM usages, both work nodes and the master node is well below consuming half the assigned resources. I have about 10-20 pods running on each node at the moment.
I am not sure what to google and given my level of k8s knowledge am completely out of ideas. Anyone with similar experience or could point me in the right direction would be much appreciated!


text:
Q: Exceptions and Error 404 when using StatsManager Okay I tried to play a little bit with the StatsManager but I always got an exception trying to use anything with it when comes to

*

*Set a stat

*Get a stat

Because I doubted myself I had the idea just to use the UWPIntegration sample that is on Github . I also added the Leaderboard items to my own project so the code works with my test sandbox. Logging in works as it should just StatsManager causes the issues.

But as with my own code I just get the same error / exception which is the following. I assume there is a bug in the code provided or the service configuration is not working as intended.

System.AggregateException occurred   HResult=0x80131500   Message=One or more errors occurred.   Source=   StackTrace:    at
  System.Threading.Tasks.Task1.GetResultCore(Boolean
  waitCompletionNotification)    at
  Microsoft.Xbox.Services.XboxLiveHttpRequest.<>c__DisplayClass35_0.<GetResponseWithAuth>b__1(Task1
  getResponseTask) in
  D:\Data\VisualStudio\Projects\xbox-live-api-csharp\Source\api\XboxLiveHttpRequest.cs:line
  117    at System.Threading.Tasks.Task.Execute()
Inner Exception 1: AggregateException: One or more errors occurred.
Inner Exception 2: WebException: The remote server returned an error:
  (404) Not Found.

Issue was found. My service.config used a wrong parameter name, see below in the comments of the solution.

A: There are a few different reasons why this might be the case. Not surprisingly, it means the cloud can't find the stat you've requested.
If you use Fiddler, you can capture the call and share with me the correlationID header. If you don't know Fiddler, let me know and I can help you.
However, some ideas off the top of my head

*

*Make sure that you're in development mode - your sandbox is the one from the dev center site. If you aren't sure, you can use the Windows Device Portal to see what your sandbox is - just click on Xbox Live in the left hand navigation.

*Make sure you have hit "Test" on the dev center page where you defined your featured stats and leaderboards.

*Make sure you are requesting the stat by the ID name you specified in the config window, not the display name.


text:
Q: Get access to or acquire files on Network tab in developer console Is possible to access or acquire the files that are passed to the client from the server, the files displayed on the Network tab in the developer console?
I came across this question that suggests obtaining the logs may be possible with browser extension technology, but it is a really old question and answer. I am also interested in obtaining the files, not the logs.
Is it possible?

A: Yes. you can do it by using Service Workers.
Service Worker is a script which runs on your browser separated from your website. It allows to run background javascript functions which is not need any user interaction (Logs / Analytics).
And
Service worker is a programmable network proxy, allowing you to control how network requests from your page are handled.
Learn More Features of Service Workers

Sample Service worker which will be activated for all /sw.js requests from developers.google.com

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

NOTE : You cannot intercept other website's traffic using service workers. That is browser level control, For that you need to use browser level extensions or packet sniffers such as Wireshark or Brupsuite.


text:
Q: PHP function with parameter I am trying to execute a php  "runMyFunction($para)" function which takes in a string parameter when clicking on an image
 echo '';

and my php funtion is
 function runMyFunction($input) {
    echo  $input;
  }

  if (isset($_GET['similair'])) {
    runMyFunction();
  }

My question is how can I pass another string value so I can use it inside the $_GET checking part to pass it as a parameter in my function
Any help would be much appreciated

A: Assuming you want a second  parameter named param2 and you want pass the value 'test'
echo '
            ';

  function runMyFunction($input) {
      echo  $input;
    }

    if (isset($_GET['similair'])) {
      runMyFunction( $_GET['param2']);
    }


text:
Q: Problema con JQuery desplazando la página a una posición Aquí paso el código html y js (estoy usando Laravel) y pasa que uno de mis botones del Nav no funciona, es el que dice "Sintomas" cuando lo clickeo no hace scroll hasta la parte de sintomas, los otros dos "Perfil" y "Contacto" si funcionan bien.

jQuery(document).ready(function(){
  /* para el scroll fluido y suave */
var perfil = $('#Perfil');
var sintomas = $('#sintomas');
var contacto = $('#contacto');

    if(perfil.length)
    {
      var contentPerfil = perfil.offset().top;

      $('#btn-perfil').on('click', function(e){
        e.preventDefault();
        $('html, body').animate({
          scrollTop : perfil
        }, 500);
      });
    }

    else if(sintomas.length)
    {
      var contentSintomas = sintomas.offset().top;

      $('#btn-sintomas').on('click', function(e){
        e.preventDefault();
        $('html, body').animate({
          scrollTop : sintomas
        }, 500);
      });
    }

    else if(contacto.length)
    {
      var contentContacto = contacto.offset().top;

      $('#btn-contacto').on('click', function(e){
        e.preventDefault();
        $('html, body').animate({
          scrollTop : contacto
        }, 500);
      });
    }
});
<!doctype html>
getLocale()) }}">

      <meta charset="utf-8" />
      <link rel="apple-touch-icon" sizes="76x76" href="../assets/img/apple-icon.png">

      <link rel="icon" href="{{ asset('images/casa.png') }}">

      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
      <title>@yield('title', 'Neumología')</title>
      <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no' name='viewport' />

      <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:400,700|Material+Icons" />
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css">

      <link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet" />
      <link href="{{ asset('css/material-kit.css?v=2.1.1') }}" rel="stylesheet" />
      <link href="{{ asset('css/estilos.css') }}" rel="stylesheet">
      <link rel="stylesheet" href="{{ asset('css/animate.css') }}">

          Neumología
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
          Toggle navigation

          </button>

                Perfil

                Sintomas

                Contacto

        @yield('content')

            ©
            , hecho por favorite
            Cecilia Benítez Casaccia, por una mejor web.

@extends('layouts.app')

@section('title', 'Neumología')

@section('body-class', 'profile-page sidebar-collapse')

@section('content')

Neumologo infantil

Atendemos a todo tipo de niños con problemas respiratorios.

Dr. Bernardo Sanchez Torres

Neumologo pediatra

           La neumologia pediátrica es una rama de la pediatría que se encarga del estudio y manejo de las entidades que
           afectan a todo el sistema respiratorio en los niños, tanto en las vias aéreas altas como bajas.

           Un Neumologo pediatra se encarga de diagnosticar y tratar tanto padecimientos respiratorios agudos como crónicos
           en los niños.

Sintomas

¿Cuáles son los síntomas de la tos seca?

Necesidad permanente de toser

Toser sin expulsar mucosidad

Sensación de irritación, cosquilleo y sequedad en la garganta

La tos suena seca

Pecho despejado, sin repiqueteo ni congestión

La tos puede dificultar el sueño por la noche

Normalmente se siente cansado cuando sufre tos o resfriado.

¿Cuáles son los síntomas del asma?

Tos con o sin producción de flema.

Retracción o tiraje de la piel entre las costillas al respirar.

Dificultad para respirar que empeora con el ejercicio o la actividad.

Sibilancias.

¿Cuáles son los síntomas del resfriado?

Puede tener dolor de garganta, fiebre o escalofríos. Puede sentirse "adolorido".

Tiene goteo nasal, estornudos y escozor en la nariz.

Puede sentirse cansado o muy débil (fatigado), si tiene una enfermedad como un resfriado o influenza (gripe).

Puede sentir como si tuviera un "bulto" o algo atravesado en la garganta.

Podría tener un área blanca o grisácea en la parte posterior de la garganta.

Contacto

Telefono: (021) 2171717

Dirección: Avenida Gral. José Gervasio Artigas 1500

@endsection

)

A: Creo que ya se lo que esta mal

jQuery(document).ready(function(){
  /* para el scroll fluido y suave */
var perfil = $('#Perfil');
var sintomas = $('#sintomas');
var contacto = $('#contacto');

    if(perfil.length)
    {
      var contentPerfil = perfil.offset().top;

      $('#btn-perfil').on('click', function(e){
        e.preventDefault();
        $('html, body').animate({
          scrollTop : contentPerfil
        }, 500);
      });
    }

    else if(sintomas.length)
    {
      var contentSintomas = sintomas.offset().top;

      $('#btn-sintomas').on('click', function(e){
        e.preventDefault();
        $('html, body').animate({
          scrollTop : contentSintomas
        }, 500);
      });
    }

    else if(contacto.length)
    {
      var contentContacto = contacto.offset().top;

      $('#btn-contacto').on('click', function(e){
        e.preventDefault();
        $('html, body').animate({
          scrollTop : contentContacto
        }, 500);
      });
    }
});


text:
Q: Definition with word to be defined instead of counter I know the title is a bit weird but I'll try to explain it in a better way here.
In the beginning of a chapter I'd like to define some basic terms. Currently I'm using
\newmdtheoremenv{mydef}{Definition}

which results in the following:
Is there an easy way to do it without "Definition 1."  but "Machine Learning" ?

A: mdframed lacks the possibility to define unnumbered theorems, but it's not difficult to add it.
Next, a common trick for a variable label can be applied.
\documentclass{article}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{mdframed}

\NewDocumentCommand\newmdtheoremenvnonumber{O{} m m }{%
  \newtheorem*{#2}{#3}
  \BeforeBeginEnvironment{#2}{%
     \begin{mdframed}[#1]}%
  \AfterEndEnvironment{#2}{%
     \end{mdframed}}%
}

\newmdtheoremenvnonumber{mydefinner}{\mydeflabel}
\newcommand{\mydeflabel}{}
\newenvironment{mydef}[1]
 {\renewcommand\mydeflabel{#1}\begin{mydefinner}}
 {\end{mydefinner}}

\newcommand{\attribution}[1]{\textup{(#1)}}

\begin{document}

\begin{mydef}{Machine Learning}
Machine learning is the field of study that gives computers
the ability to learn without being explicitly programmed.
\attribution{Arthur Samuel, 1959}.
\end{mydef}

\end{document}


text:
Q: SQL Join data from 3 tables I have 3 tables:
skill_categories(id, name) -- list of categories
skills(id, skill_category_id, name) -- Sub-categories for each skill category
contributors(id, name, skill_id_1, skill_id_2, skill_id_3) -- A person can have up to 3 skills
I want to query the skill_category_id, skill_category_name, skill_id and skill_name for each skill_id field in a contributor.
From what I have read, I think SQL JOINs can be used to achieve this and have written such a query.
SELECT s.skill_category_id AS skill_category_id,
       sc.name AS skill_category_name,
       s.id AS skill_id,
       s.name AS name
FROM skills AS s
INNER JOIN skill_categories AS sc
      ON s.skill_category_id = sc.id
INNER JOIN contributors AS c
      ON c.skill_id_1 = s.id
      OR c.skill_id_2 = s.id
      OR c.skill_id_3 = s.id
WHERE c.id = $id
ORDER BY s.name, sc.name ASC

Is this the best way to perform such a query?

A: No, this is not the best way -- especially from a performance perspective.  OR (or IN) are performance killers for joins.
It is better to add more joins, one for each skill category.  So, this should have better performance:
SELECT s.skill_category_id AS skill_category_id,  sc.name AS skill_category_name,
       s.id AS skill_id,  s.name AS name
FROM skills s INNER JOIN
     skill_categories sc
     ON s.skill_category_id = sc.id LEFT JOIN
     contributors c1
     ON c.skill_id_1 = s.id LEFT JOIN
     contributors c2
     ON c1.skill_id_2 = s.id LEFT JOIN
     contributors c3
     ON c3.skill_id_3 = s.id
WHERE $id in (c1.id, c2.id, c3.id)
ORDER BY s.name, sc.name ASC

The query would be simpler if you had separate rows for each skill, rather than separate columns.


text:
Q: NSolve fails to solve a nonlinear equation Mathematica can not solve this:
g = 9.82;
ω = 0.5;
h = 5;
y0 = 1;
v = 0;
τ = 0;

NSolve[h + v t - (g t^2)/2 == y0 Sin[ω t], t];

The error code is:

NSolve::nsmet: This system cannot be solved with the methods available to NSolve.

Any suggestions how to solve this equation ?

Background

I need to calculate when and where the jumping ball and sinusoidal ground will collide.
For the first one we know it is falling like:
h = h0 + v0 t - g t^2 / 2

For the ground we know it is moving as:
y = y0 Sin(omega t)

If we calculate h = y, extract t we get the time of the collision.
Finally I need to plot the movement of the ball and the points of collision versus real time.

A: Update: reply to comment to display the move of the ball. Here is a quick Manipulate. You can make improvement as needed

Manipulate[
 tick;

 g = 9.82; y0 = 1; v = 0;
 h = h + v*t - g t^2/2;
 ymin = y0 Sin[w t];
 If[h - radius > ymin + thick, tick = Not[tick]; t = t + delT];
 Grid[{
   {"time", "h"},
   {t, h},
   {
    Graphics[
     {
      {Black, Disk[{0, h}, radius]},
      {Blue, Rectangle[{-1, ymin}, {1, ymin + .2}]},
      If[h - radius <= (ymin + thick),
       {Red, Style[Text["Crash!", {1.5 radius, ymin + 2 thick}], 14]}
       ]
      },
     PlotRange -> {{-1, 1}, {0, 5.5}}, AspectRatio -> Automatic, Axes -> True,
        ImageSize -> 200], SpanFromLeft
    }
   }, Spacings -> {.1, .2}, Frame -> All, FrameStyle -> LightGray]
 ,
 Button["Run", h = 5; t = 0; ymin = 0; tick = Not[tick]],
 {{w, 1, "omega?"}, 0, 10, .1, ImageSize -> Small, Appearance -> "Labeled"},
 {{delT, 0.001, "animation speed?"}, 0.0001, 0.01, .0001, ImageSize -> Small,
       Appearance -> "Labeled"},
 {{tick, True}, None},
 {{h, 5}, None},
 {{t, 0}, None},
 {{ymin, 0}, None},
 {{thick, 0.2}, None},
 {{radius, 0.1}, None},
 TrackedSymbols :> {tick}
 ]

Original answer
If you tell NSolve that time is positive (which it is), it can solve it
g = 9.82;
w = 0.5;
h = 5;
y0 = 1;
v = 0;

NSolve[h + v  t - (g t^2)/2 == y0 Sin[w t] && t > 0, t]


text:
Q: Calculating area between two curves I am working on a program that compares two curve (resulted from diode output so its Voltage/Current curve).
I want to calculate the area between this two curves (BLUE curve is first diode and RED is the second one).

There are 51 data points for each curve (they always have same amount of data poitns). What I am doing at the moment is like this:
public double CalculateArea(double[,] pin1, double[,] pin2)
{
    double voltageArea = 0;
    double currentArea = 0; //Current (Vertical axis) not yet!
    double max = 0;
    double min = 0;

    for (int i = 0; i < pin1.GetLength(0); i++)
    {
        max = Math.Max(Math.Abs(pin1[i, 0]), Math.Abs(pin2[i, 0]));
        min = Math.Min(Math.Abs(pin1[i, 0]), Math.Abs(pin2[i, 0]));

        voltageArea += max - min;
    }

    return voltageArea;
}

This code somehow works, having in mind I do nothing with Current (vertical axis). If the result is somehing near 0 eg 0.05 then the difference between curves is negetable. But I am sure this is not the correct way, I totaly have no idea what is the result of the method I wrote...seems to be difference between Voltage points only.
I really appriciate if you can help me improve this method.

A: First subtract one diode from the other do get the difference in values. Then use the trapezoidal rule, which considers the area under a piece-wise linear function.
class Program
{
    /// <summary>
    /// Calculate integral with trapezoidal rule
    /// </summary>
    /// <param name="h">The step size in x-axis</param>
    /// <param name="y">The array of values to integrate</param>
    /// <returns>The area under the curve y[i,0]</returns>
    public static double Integrate(double h, double[,] y)
    {
        int N=y.GetLength(0);

        double sum=(y[0, 0]+y[N-1, 0])/2;

        for(int i=1; i<N-1; i++)
        {
            sum+=y[i, 0];
        }

        return h*sum;
    }

    static void Main(string[] args)
    {
        int N = 100;
        double[,] y=new double[N, 1];

        for(int i=0; i<y.GetLength(0); i++)
        {
            y[i, 0]=5+5*Math.Sin(2*Math.PI*i/(N-1));
        }

        double x_min=0.5;
        double x_max=3.5;
        double h = (x_max-x_min)/N;

        double area=Integrate(h, y);
        // expected answer is   area = 15.00
        // actual answer is     area = 14.85
    }
}


text:
Q: Creating moving dot plot in MATLAB to video I have 2 matrices
size(X)=size(y)=3600*140

They represent 140 nodes position in 3600 secs
I would like to create a movie of dots what will show them moving let say each 0.001sec will show next all node position
i did:
for ii=1:3600
plot(x(ii,:),y(ii,:));
pause(0.0001);
end

Now it shows me the moving dots as wanted but
I would like each dot to have a colour
I would like to make a movie of those plots

A: here i got it to work. hope it will help someone else
writerObj = VideoWriter('runningNodes.avi');
open(writerObj);
plot(x(1,:),y(1,:));
axis tight
set(gca,'nextplot','replacechildren');
set(gcf,'Renderer','zbuffer');
for ii=1:3600
   plot(x(ii,:),y(ii,:));
   frame = getframe;
   writeVideo(writerObj,frame);
end

close(writerObj);


text:
Q: Syntax error and I do not know why Python I'm getting a syntax error in my code and I can't find the problem
bot = commands.Bot(command_prefix=f'{data["Prefix"]}')

error message:
File "C:\test.py", line 22
    bot = commands.Bot(command_prefix=f'{data["Prefix"]}')
                                                        ^
SyntaxError: invalid syntax

Code around it
try:
    with open('config.json') as (f):
        data = json.load(f)
except FileNotFoundError:
    print("Configuration file can't be found, please create new one, or move it to folder where your exe of bot is")

bot = commands.Bot(command_prefix=f'{data["Prefix"]}')
token = data["Token"]
Channel = data["Channel"]
AdministratorRole = data["AdministratorRole"]
Stocks = data["StockChannel"]


text:
Q: Is there a setting on Google Analytics to suppress use of cookies for users who have not yet given consent According to EU Article 5(3) of the E-Privacy Directive (a.k.a 'The Cookie Laws'), web sites that target EU users have to gain opt-in consent from users before they set a cookie.
See ICO Guidance
I am trying to square this with Google Analytics on my web site.
I would imagine that Google Analytics (GA) can do a certain level of analytic data gathering without requiring the use of cookies.
However, I cannot find any info on this (on the Google sites/settings panels) about how to relay information about the 'state of consent' back to Google during a page request. So, my only option seems to be that I should not embed Google tag code at all if the user has not explicitly given consent. Which seems a bit drastic.
Letting my serverside script set a hasConsentedToCookies=FALSE flag in the JavaScript tags would allow me to instruct Google's services to run in a gracefully degraded fashion.
Is there a setting on Google Analytics to suppress use of cookies
for users that have not yet given consent?
If so, where can I find info on this?

A: Latest Google Analytics (gtag.js) has a "Consent mode" just for that (still in beta):
https://developers.google.com/gtagjs/devguide/consent
It looks like this:
gtag('consent', 'default', {
  analytics_storage: 'denied',
  ad_storage: 'denied'
});

Then you can update these settings at a later time in the case the user consents.

A: You can disable google analytics cookies by adding this code at the top of google analytics code (before line: var _gaq = _gaq || [];):
ga('create', 'UA-XXXXXX-XX', {'storage': 'none'});
ga(function(tracker) {
  var clientId = tracker.get('clientId');
});

However some features of google analytics (for example real time stats) do not work properly after this modification. More about google analytics cookies: https://developers.google.com/analytics/devguides/collection/analyticsjs/domains?hl=en#disableCookies

A: You can disable the use of cookies for Google Analytics by specifying the {'storage' : 'none'} option when creating the tracker instance.
See Google's guide on the subject for more details.

A: I was facing the same problem.
Eventually, I got a solution in the line of Elmer's reply but playing safe regarding IPs, that is without using localStorage
// Create a fake ID instead of storing anything locally
function guidGenerator() {
    var S4 = function() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

...
ga('create', 'UA-XXXXXX-Y', {
        'storage': 'none',
        'clientId': guidGenerator()
});

(-) Every page visited will count as a new visitor in Google Analytics, so I am losing quite a lot of functionalities there.
(+) But I can live with it and I believe I am safe regarding data privacy legislations.
Any feedback or improvement suggestion is more than welcome.

A: As a quick note, the BBC (probably the most popular site in the UK) has taken an interesting approach to complying with cookies - they've displayed a banner to users telling them that cookies are set and provide a couple of links.
This one explains what cookies are. This one lets them manage their cookies, but most interestingly of all they supply a link to Google Analytics to allow users to opt-out of GA in its entirety. So, in summary, the BBC have taken the view that they can tell the user what cookies are set and then provide a link to Google to allow the user to opt out of all GA cookies. For me, that's a lot less hassle than you telling GA to opt-out for an address through JS.

A: I often never ask users to opt out for google analytics, that is because i never set cookies and i never save their ip (and other personal data).
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-98765432-1', 'www.example.com', {
  'anonymizeIp': true
  , 'storage': 'none'
  , 'clientId': window.localStorage.getItem('ga_clientId')
});
ga(function(tracker) {
  window.localStorage.setItem('ga_clientId', tracker.get('clientId'));
});
ga('send', 'pageview');

Also check out this code at Convert Google Analytics cookies to Local/Session Storage
This script will not set any cookies, but still track via google analytics. This will actually have the same effect on privacy as using cookies, because google still records the users IP-address.
That is where the anonymizeIp switch comes in. This tells google to only save an anonymized version of the IP-address. An anonymized IP-address is not considered personal data, so the users privacy will be respected.
AFAIK cookie law is all about privacy and does allow website to track their usage. I am not a lawyer or anything but in my opinion this script complies to the EU cookie law.
Check out this plunk to see it in action: http://plnkr.co/MwH6xwGK00u3CFOTzepK

A: EDIT (2019): The below answer predates GDPR and likely requires revision.
Google Analytics has a new set of APIs to assist with compliance with a cookie opt-out. Here's the documentation, and here's their help docs.
There has been some ambiguity as to whether the EU Cookie Regulations (as implemented in member countries) require that passive web analytics tracking requires opt-in mechanisms for compliance. If you're concerned one way or another, consult an attorney. Google is empowering you to make the decision as to how you want to proceed.
They'll leave implementation details to you, but, the idea is, once you've determined whether or not to track the user in Google Analytics, if the answer is to not track, you'd set the following property to true before Google Analytics runs:
window['ga-disable-UA-XXXXXX-Y'] = true;

Where UA-XXXXXX-Y is your account ID in Google Analytics
As the other posters have noted, Google Analytics relies on cookies. So, you're not able to do any kind of tracking without cookies. If you've determined that someone is not to be cookied for tracking, you'll need to implement something like this:
if(doNotCookie()){
   window['ga-disable-UA-XXXXXX-Y'] = true;
}

Opt In
This does require a little bit of jujitsu for when you first load Google Analytics, since this property will need to be set before Google Analytics runs to prevent tracking from ever happening, which means, for an "opt in to tracking" approach, you'd probably need to implement a mechanism where, on first visit, Google Analytics is automatically disabled in the absence of an opt-in cookie (cookies that determine cookie preferences are explicitly allowed), and then, if an opt-in happens, re-runs Google Analytics. On subsequent pageviews, all would run smoothly.
Could look something like (pseudo-code):
if( hasOptedOut() || hasNotExpressedCookiePreferenceYet() ){ //functions you've defined elsewhere
     window['ga-disable-UA-XXXXXX-Y'] = true;
}
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXX-Y']);
  _gaq.push(['_trackPageview']);

  function onOptIn(){ //have this run when/if they opt-in.
      window['ga-disable-UA-XXXXXX-Y'] = false;
      //...snip...
      //set a cookie to express that the user has opted-in to tracking, for future pageviews
      _gaq.push(['_trackPageview']); // now run the pageview that you 'missed'
   }

Opt Out
With this approach, you'd allow the user to opt-out of tracking, which would mean you'd use a cookie to set the ga-disable-UA-XXXXXX-Y' property and a cookie to manage it in the future:
if( hasOptedOut() ){ // function you've defined elsewhere
     window['ga-disable-UA-XXXXXX-Y'] = true;
}

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXX-Y']);
  _gaq.push(['_trackPageview']);

A: EDIT: There is a Google Analytics setting for this with the Asynchronous GA snippet.
There isn't a Google Analytics setting for this, as you're suggesting, you would need to conditionally exclude the script for those that have not consented if you want to use the Google Analytics Javascript tracking script.
There are some solutions out there already that can be helpful instead of rolling your own.
Javascript: http://cookies.dev.wolf-software.com/demo/index.htm
Here is a solution that allows using Google Analytics basic features without cookies, by doing the tracking server side, this example is in PHP: http://techpad.co.uk/content.php?sid=205

A: Common way to handle this so far is the method used by wolf-software's jquery plugin whereby it prevents the script from running until the user opts in. The ICO updated their guidelines last week, however, to say that it is acceptable to rely on 'implied consent' of the sort used on the BBC site. While I don't really think that's within the spirit of the law, it's what's deemed acceptable by those enforcing it. Given that most of the EU has yet to implement the directive, I'd say it's highly likely they'll follow the UK's lead.
There's an interesting article about the UK updates here:
http://www.redant.com/articles/eu-cookie-law-update-ico-adopts-softly-softly-approach/

A: For a less intrusive UX solution you can set implied consent for google analytical cookies by placing a link to: cookiestatement.eu (no javascript, no popups, no ads)

A: Sorry for being late to answer but I was looking for the same thing recently until I found out a way myself. It may not be the right way to do it but it works. (only works on site in question does not opt-out of GA completely).
I have tested for a few days to make sure.
The way I have managed to do it is using a PHP cookie. First start off with adding the analyticstracking.php include...
<?php include_once('analyticstracking.php'); ?>

and in analyticstracking.php add the following...
<?php
if($_COOKIE['consent_cookie']=="Y"){
?>

<script type="text/javascript">
var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-********-*']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript';     ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' :      'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0];      s.parentNode.insertBefore(ga, s);
  })();
</script>

<?php
}
else{
//do nothing
}
?>

Before the user has consented to cookies Google Analytics won't work and once they have, the 'consent_cookie' will be saved and will allow GA to work but if the 'google' cookie is destroyed it will stop GA from working (Obviously).
Like I said it may not be the right way but I have tried and tested and it does. Hope this helps somebody.

A: Update 2022: Its not about Cookies anymore. Now you need a consent even for loading google fonts from outside the EU. This is because doing so the users IP (very private Information haha) will be send to the USA.
Im not a lawyer but this affects Adsense and Analytics as well. Here you will find a solution how to load Adsense and Analytics only if consent is given: https://stackoverflow.com/questions/70967060/loading-google-adsense-analytics-and-youtube-only-when-consent-is-given
Simply call setTimeout("analyticsladen()", 1); when consent is given:
The new Google Analytics 4 Code is:
 <script>
 window.dataLayer = window.dataLayer || [];
 function gtag(){dataLayer.push(arguments);}
 gtag('js', new Date());

 gtag('config', 'G-####');
 </script>

 <script type="text/javascript">
 function analyticsladen() {
 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = 'https://www.googletagmanager.com/gtag/js?id=G-####';
 document.body.appendChild(script);
 }
 //setTimeout("analyticsladen()", 1);
 </script>

Or you can use the old Google Universal Analytics Code. It will only work till June 2023 (says google):
 <script type="text/javascript">
 var _gaq = _gaq || [];
 _gaq.push(['_setAccount', 'UA-####-#']);
 _gaq.push (['_gat._anonymizeIp']);
 _gaq.push(['_trackPageview']);

 var analyticsladen = function(){
 var ga = document.createElement('script');
   ga.type = 'text/javascript';
   ga.async = true;
   ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

   var s = document.getElementsByTagName('script')[0];
   s.parentNode.insertBefore(ga, s);
   }

 </script>

Funfact: Google ranks my page 4 steps higher scince im not using analytics at all anymore :D

A: There's a few steps to do in order to make GA work only after user accepts the cookie usage.
Disable cookies
   <script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-Y"></script>
-- <script>
-- window.dataLayer = window.dataLayer || [];
-- function gtag(){dataLayer.push(arguments);}
-- gtag('js', new Date());
-- gtag('config', 'UA-XXXXXX-Y');
-- </script>

At the point where GA is implemented, this needs to be updated by just importing the gtag.js script and removing the GA initialisation.
Enable GTag when user accepts cookies
GTag Opt In is a tool that enable and disable GA when user accepts/rejects cookies.
<script src="https://www.npmcdn.com/gtag-opt-in@2.0.0/dist/index.js"></script>
<script>
  GTagOptIn.register('UA-XXXXXX-Y');

  ...
  // On user opt in
  GTagOptIn.optIn();
  // On user opt out
  GTagOptIn.optOut();
  ...
</script>

Library is loaded. GA tracking ID is registered. Later the optIn and optOut functions can bind to user actions' accept/reject.
You can read more about it on How To Implement Google Analytics With Opt In.

A: You can use something like Legal Monster - to block cookies if user didn't give consent for analytical cookies.
legal.js currently supports blocking (and enabling) of analytics and marketing cookies; more categories will be available in the future.
Here is more detailed guide on blocking cookies.

A: GA does not work without cookies, it needs it to 'identify s' the visitor if he/she visited your site before. So there is no setting in GA for this, GA just doesn't records the visitor if it cant create a cookie.
If the user is from the EU and has not opt-in then you should exclude the google-analytics script I think.


text:
Q: how to set label text by accessing key or value from dict i want to acces key from dict. here's a textinput. i gave that textinput an id:word. if any text from that textinput matches any of these key or value from that dict, then the text of a label should be changed to show some text.
i can access key or value from dict.
but problem is when i use if self.ids.word in Dict.keys():
then show something. but self.ids.word is a string data and any key or value from dict is Nonetype class. so self.ids.word cant be in dict. cause str cant be in dict(while dict key or value ls nonetype)
how can i do that?
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.properties import *

Dict={"my": "amar","i":"ami","you":"tumi"}

class pop(Popup):
    add=StringProperty()
    a=app.root.yo.ids.word.text
    if a in Dict.keys():
        self.add=str(a) + str(Dict.get(a))
class yo(BoxLayout):
    def pop(self):
        po=pop()
        po.open()
class go(BoxLayout):
    main=ObjectProperty(None)
    def yo(self):
        self.clear_widgets()
        self.main=yo()
        self.add_widget(self.main)

Builder.load_string('''
<go>:
    Button:
        text:"go"
        on_press:root.yo()
<yo>:
    TextInput:
        id:word
    Button:
        text:"press"
        on_press:root.pop()
<pop>:
    title:"pop"
    size_hint:0.8,0.3
    Label:
        text:root.add

''')

A: Question 2

i want to get these
  key and ids in a popup label. i know in kivy i should use
  a=app.root.yo.ids.word.text. but how to access that id in py code?

Solution

*

*Implement a constructor for class pop().

*Use App.get_running_app() to get an instance of your app

*use root.main to get an instance of your yo object

Snippets - py file
class pop(Popup):
    add = StringProperty()

    def __init__(self, **kwargs):
        super(pop, self).__init__(**kwargs)
        a = App.get_running_app().root.main.ids.word.text
        if a in Dict.keys():
            self.add = str(a) + str(Dict.get(a))

Question 1

but problem is when i use if self.ids.word in Dict.keys(): then show
  something. but self.ids.word is a string data and any key or value
  from dict is Nonetype class. so self.ids.word cant be in dict. cause
  str cant be in dict(while dict key or value ls nonetype)

Solution
self.ids.word is a reference to the TextInput object. Therefore, you want to access the text attribute of the TextInput object.
Replace a = self.ids.word with a = self.ids.word.text


text: Q: выпадающий список в выпадающем списке Добрый день Всем , подскажите пожалуйста как организовать так выпадающий список что б по нажатию на "категория" последний элемент на первой картинке(левой) уходил стягивался в низ и после того как если закрыть елемент "категория" он обратно стягивался


text:
Q: Is the quotient topological space $[0,1]/(0,1)$ contractible? The question is already in the title. Is the quotient space $[0,1]/(0,1)$ contractible ?
Here I have three points, but not in the discrete topology. Further, the only open sets are $\{[(0,1)]\}$ and the whole space. I don't know if that helps.
I feel like this should be easy, but I can't figure it out.
Edit:
I followed @Marcos hint.
But I find a  counterexample where $(0,1) \to [0,1]$ do not have the homotopy extension property. If I take $Y:= \{0\} \times [0,1] \cup (0,1) \times [0,1]$ with the subspace-topology of $\mathbb{R}^2$, $H:(0,1) \times [0,1] \to Y$ as the identity, and $\tilde{H}_0(t) = (t,0)$ this cannot be extended to a homotopy $\tilde{H}:[0,1] \times [0,1] \to Y$.

A: The quotient space $X = [0, 1] / (0, 1)$ consists of three points that we will denote $0, 1$ and $a$, where $a$ is the image of any $x \in (0, 1)$ under the quotient map $[0, 1] \to [0, 1] / (0, 1)$. The topology of $X$ is not Hausdorff, its closed sets are $\emptyset, X, \{0\}, \{1\}$ and $\{0, 1\}$.
One can prove that the map $h \colon X \times [0, 1] \to X$ defined by
$$h(x, t) = \begin{cases}
x & \text{if } t = 0 \\
a & \text{if } t > 0
\end{cases}$$
is a deformation retraction of $X$ onto $\{a\}$. We need to prove the continuity of $h$. For this, we only need to prove that the inverse image of the closed sets $\{0\}$ and $\{1\}$ under $h$ are closed. Indeed, $h^{-1}(\{0\}) = \{0\} \times \{0\}$ and $h^{-1}(\{1\}) = \{1\} \times \{0\}$.

A: You can get intuition for the other answer as follows. Suppose X is a topological space and A a subspace. Suppose one has a deformation retraction of X onto a subspace of A, so that for all $t$ we have $h_t(A) \subset A$. Then quotienting by $A$ we have a map $h: [0,1] \times X \to X/A$ which is the projection for $t = 0$ and a constant map for $t = 1$. Further, if one defines $\sim$ to be the relation $(t,a) \sim (t,a')$ whenever $a, a' \in A$ (and no other points are equivalent to anything other than themselves), this map is constant on $\sim$-equivalence classes, and descends to a map $\big([0,1] \times X\big)/\sim \to X/A$.
When you are lucky, the quotient by the relation above is homeomorphic to $[0,1] \times X/A$ and you have defined a deformation retraction of X/A to a point. This is the case eg when X is compact and A is closed.
Here this is probably not the case but it does suggest the right approach. Let me work with $X = [-1, 1]$ and $A = (-1,1)$ for ease of notation. Then $h_t(s) = (1-t)s$ is an example of a mapping as above. When you quotient by A everywhere this map descends to precisely the map defined in the other answer, and you can check it's continuous directly instead of worrying about whether the quotient topology is correct.


text:
Q: Make Bootstrap's YAMM open on hover I'm using the YAMM to create a mega menu for Bootstrap but I can't figure out how to make the menu appear on mouseover/hover. At the moment it only appears on click.
github demo
jsFiddle

        <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target="#nav1">

        </button>
         Yamm Megamenu

               List

Section Title

                        List Item

                        List Item

                        List Item

                        List Item

                        List Item

                        List Item

Links Title

                         Link Item

                         Link Item

                         Link Item

                         Link Item

                         Link Item

                         Link Item

Section Title

                        List Item

                        List Item

                        List Item

                        List Item

                        List Item

                        List Item

Section Title

                        List Item

                        List Item

                             Link Item

                             Link Item

                             Link Item

               Accordion

                             Collapsible Group Item #1

                              Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

                             Collapsible Group Item #2

                              Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

                             Collapsible Group Item #3

                              Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

                             Collapsible Group Item #1

                              Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

                             Collapsible Group Item #2

                              Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

                             Collapsible Group Item #3

                              Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

               Classic

                   Action

                   Another action

                   Something else here

                   Separated link

               Pictures

A: You need to make display: block when the particular li is hoverd.
Add this in your css code
ul.nav li.dropdown:hover > ul.dropdown-menu {
    display: block;
}

A: A lot of plugins available for show bootstrap dropdown on hover. Here i have used one plugin for demo refer the following url
[http://jsfiddle.net/azhagu/6vYr2/2/][1]

A: @media (min-width: 768px) {
    /* disable dropping down on mouse click */
    ul.nav li.open > ul.dropdown-menu {
        display: none;
    }
    /* enable dropping down on mouse hover */
    ul.nav li.dropdown:hover > ul.dropdown-menu {
        display: block;
    }
}


text:
Q: How can I extract url from json data with escaped "\" in java I need to extract url from json filed. (replace it with "" and do not break the json format), so that there's no url in json.
the url looks in this way
"source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\",
"profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/3475536942\/2b0ccd9e42754adf7e22947037dd8c34_normal.jpeg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/488849893\/1364691799",

...
I noticed that there's "\" in the url to escape the string, I don't know how to deal with it while writing the regex.

A: Simply use a lightweight JSON parser such as this reference implementation in Java
To overwrite, say, the source property to "blah", it is possible to do things as simple as
String newJsonString = new JSONObject(originalJsonString).putString("source","blah").toString();


text:
Q: Reverse blend colors in JavaScript I have found the following snippet to blend two hex colors which works great. (Apologies I cannot remember the source)
    function blendHexColors(c0, c1, p) {
        var f = parseInt(c0.slice(1), 16);
        var t = parseInt(c1.slice(1), 16);
        var R1 = f >> 16;
        var G1 = f >> 8 & 0x00FF;
        var B1 = f & 0x0000FF;
        var R2 = t >> 16;
        var G2 = t >> 8 & 0x00FF;
        var B2 = t & 0x0000FF;

        return "#" + (0x1000000
            + (Math.round((R2 - R1) * p) + R1) * 0x10000
            + (Math.round((G2 - G1) * p) + G1) * 0x100
            + (Math.round((B2 - B1) * p) + B1)).toString(16).slice(1);
    }

I now want a way to reverse this process.
Does anyone know of a way to do this.
my example would be something like this
var blendColor = blendHexColors('#ffffff', '#ff0000', 0.5);
var unblenColors = unblenHexColors(blendColor, '#ff0000', 0.5); // result would be #ffffff

A: After you comment I was able to fix the code and create a fiddle that show how it works (https://jsfiddle.net/zvp4sh26/)
The problem with the original code I posted is that the result of some components (like G and B) had a value of 256 (instead of 255)
function unblendHexColors(c0, c1, p) {
  var f = parseInt(c0.slice(1), 16);
  var t = parseInt(c1.slice(1), 16);
  var R1 = f >> 16;
  var G1 = f >> 8 & 0x00FF;
  var B1 = f & 0x0000FF;
  var R2 = t >> 16;
  var G2 = t >> 8 & 0x00FF;
  var B2 = t & 0x0000FF;
  var d = 1 - p;
  var R3 = (R1 - R2 * p) / d;
  var G3 = (G1 - G2 * p) / d;
  var B3 = (B1 - B2 * p) / d;

  return "#" + (0x1000000
    + (R3 > 255 ? 255 : R3) * 0x10000
    + (G3 > 255 ? 255 : G3) * 0x100
    + (B3 > 255 ? 255 : B3)).toString(16).slice(1);
}

Should work now :)


text:
Q: Arcgis missing method option for "Near" tool I'm using arcgis to find the nearest distance from my lat/lon points to coastline. I use the near tool in arcgis. however, i realize that the "Geodesic option" is missing from the arcgis i'm using. i suspect this is a version problem, does anyone know?
many thanks!

A: The Method parameter (allowing you to choose between PLANAR and GEODESIC) was added in ArcGIS 10.2.1, so you're probably using an older version indeed.
See What's new in ArcGIS 10.2.1 for reference.