text:
Q: Flutter firebase auth doesn't persist after app is killed I am trying to persist the firebase auth state in a flutter app by using this code from the documentation but when I kill the app in the emulator and open it again it doesn't recognize a user.
I can use sharedpreferences but I want to use only firebase, what am I doing wrong here?
main.dart
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // Create the initialization Future outside of `build`:
  final Future<FirebaseApp> _initialization = Firebase.initializeApp();
  final FirebaseAuth auth = FirebaseAuth.instance;

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      // Initialize FlutterFire:
      future: _initialization,
      builder: (context, snapshot) {
        // Check for errors
        if (snapshot.hasError) {
          return (MaterialApp(
            home: Warning(
              warning: 'Error',
            ),
          ));
        }
        // once complete show your app
        if (snapshot.connectionState == ConnectionState.done) {
          print('CONNECTED');

          if (AuthService().user() == null) {
            return MaterialApp(
              home: LoginPage(),
            );
          } else {
            return MaterialApp(
              home: HomePage(),
            );
          }
        }
        // if nothing happens return loading
        return MaterialApp(
          home: //LoginPage()
              Warning(
            warning: 'Loading',
          ),
        );
      },
    );
  }
}

AuthService class
import 'package:firebase_auth/firebase_auth.dart';
class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  // auth change user stream
  User user() {
    // ignore: deprecated_member_use
    _auth.authStateChanges().listen((User user) {
      if (user == null) {
        return null;
      } else {
        return user;
      }
    });
  }
}

I hope you can help me to understand the problem and solve it, thank you.

A: Since authStateChanges returns a Stream, you'll want to use a StreamBuilder in your code to wrap that asynchronous operation too.
Something like this:
// once complete show your app
if (snapshot.connectionState == ConnectionState.done) {
  print('CONNECTED');
  return StreamBuilder(
    stream: FirebaseAuth.instance. authStateChanges(),
    builder: (BuildContext context, snapshot) {
      if (snapshot.hasData) {
        return MaterialApp(
          home: LoginPage(),
        );
      } else {
        return MaterialApp(
          home: HomePage(),
        );
      }
    }
  )
}

Unrelated: you're repeated the code to create a MaterialApp quite frequently, which is not needed. For example, in the above snippet we could have only one mention of MaterialApp and get the same result with:
// once complete show your app
if (snapshot.connectionState == ConnectionState.done) {
  print('CONNECTED');
  return StreamBuilder(
    stream: FirebaseAuth.instance. authStateChanges(),
    builder: (BuildContext context, snapshot) {
      return MaterialApp(
        home: snapshot.hasData && snapshot.data != null ? HomePage() : LoginPage(),
      )
    }
  )
}

If you do this for all mentions of MaterialApp and other duplication, you can reduce the code significantly, making it less error prone and easier to maintain.

A: It does persist.  You are just not using the auth state listener correctly.  The return statements from your authStateChanges listener are not actually escaping the call to user().  On top of that, the listener could return null the first time.  It's not until some time later that the Firebase SDK determines that the user is actually valid and signed in.  Your listener will get a second callback at that time.  Your code need to be ready for this to happen - it can't just blindly take the first value, as the auth state might change over time.
I suggest adding some debug logging in your auth state listener to see how this actually works.  Also I suggest reading this blog to understand how auth state listeners work in more detail.

A: You can use my code, You can use userChanges() instead of authStateChanges()
final Stream<User?> firebaseUserChanges = firebaseAuth.userChanges();


text:
Q: Add additional data when django form is saved I am looking for some help in my first django app and I am new to programming. I have the below scenario:
Models:
class save_table(models.Model):
   name=models.CharField(max_length=100)
   UniqueuserID = models.CharField(max_length=7)
   UserLocation = models.CharField(max_length=100)
   UserLead = models.CharField(max_length=50)

   def __str__(Self):
      return self.UniqueuserID

class data_table(models.Model):
   UniqueuserID = models.CharField(max_length=7)
   name=models.CharField(max_length=100)
   UserLocation = models.CharField(max_length=100)
   UserLead = models.CharField(max_length=50)

Form:
class save_table_form(forms.ModelForm):

   class Meta:
      model = save_table
      fields = ('UniqueuserID')

   def __init__(self,*args,**kwargs):
      super(save_table_form,self).__init__(*args,**kwargs)

Every user ID that the user will add to the form will have a respective data entry int he second model and I want to save that additional data along with the form. However I did not use a foreign key because I do not want the saved model data in the save_table to change based on the changes in the data_table. Can I add the additional data to the form before saving the form.
if form.is_valid():
   form.save()

Please help..

A: Yes you can add aditional data when saving the form!
overwrite the saving methoud in class save_table_form:
like this :
class save_table_form(forms.ModelForm):
    def save(self, commit=True):
        user_id = self.cleaned_data['id']
        user_photo = self.cleaned_data['photo']
        user_password = self.cleaned_data['password1']
        user = SysUser.objects.get(pk=user_id)
        user.username = self.cleaned_data['username']
        if user_password:
            user.set_password(self.cleaned_data['password1'])
        user.first_name = self.cleaned_data['first_name']
        user.mobile = self.cleaned_data['mobile']
        user.office_id = self.cleaned_data['office_id']
        if user_photo:
            user.image = user_photo
        user.save()
        user.user_permissions.clear()
        user.user_permissions.add(*self.cleaned_data['user_permissions'])
        print('data is saving')
        return user

redpajama_set_name: RedPajamaStackExchange


text:
Q: How To add where Condition if request parameter exist in Laravel 5.5 How To add where Condition if request parameter exist in Laravel 5.5
Suppose:
$a = $request->name;
$b = $request->id;
$c = $request->option;
$d = $request->type;

$cities = Pocities::where('region_id', $state_id)
                    ->where('is_active', 1)
                    ->pluck('uuid')->toArray();

$tours = Tour::select(['id', 'uuid','city_uuid', 'tour_name', 'tour_image', 'is_top_tour','places', 'created_at'])
                ->with(['pocity' => function ($query) {
                    $query->select('id', 'uuid', 'cities_id', 'region_id', 'country_id');
                },'pocity.city','pocity.poregion' ,'pocity.pocountry'])
                ->whereHas('pocity',function ($query) use ($cities) {
                    $query->whereIn('uuid',  $cities);
                })->where('is_active');

if($request->name != ''){
    $tours->where('name', $request->name);
}

if($request->id != ''){
    $tours->where('id', $request->id);
}

if($request->type != ''){
    $tours->where('type', $request->type);
}

$tours->paginate(10);

I have tried this every time given
#query: Builder {#1944
    +connection: MySqlConnection {#621
      #pdo: PDOConnection {#1926
        inTransaction: false
        attributes: {
          CASE: NATURAL
          ERRMODE: EXCEPTION
          AUTOCOMMIT: 1
          PERSISTENT: false
          DRIVER_NAME: "mysql"
          SERVER_INFO: "Uptime: 980  Threads: 7  Questions: 420  Slow queries: 0  Opens: 24  Flush tables: 1  Open tables: 18  Queries per second avg: 0.428"
          ORACLE_NULLS: NATURAL
          CLIENT_VERSION: "mysqlnd 5.0.12-dev - 20150407 - $Id: 38fea24f2847fa7519001be390c98ae0acafe387 $"
          SERVER_VERSION: "5.5.5-10.2.14-MariaDB"
          STATEMENT_CLASS: array:2 [
            0 => "Doctrine\DBAL\Driver\PDOStatement"
            1 => []
          ]
          EMULATE_PREPARES: 0
          CONNECTION_STATUS: "127.0.0.1 via TCP/IP"
          DEFAULT_FETCH_MODE: BOTH
        }
      }

A: You can do with following if above is not working for you.
$tours = Tour::query();
//Add your conditions here
$tours->->with(['pocity' => function ($query) {
                $query->select('id', 'uuid', 'cities_id', 'region_id', 'country_id');
            },'pocity.city','pocity.poregion' ,'pocity.pocountry'])
            ->whereHas('pocity',function ($query) use ($cities) {
                $query->whereIn('uuid',  $cities);
            })->where('is_active')
//Add your conditionally  parameters in this way.
if($request->name != ''){
$tours->where('name', $request->name);
}

$tours->paginate(10);

I am assuming that what column names you are passing is correct.

A: You can you query builder for where clause in laravel5.5
$a = $request->name;
$b = $request->id;
$c = $request->option;
$d = $request->type;

$cities = Pocities::where('region_id', $state_id)
                    ->where('is_active', 1)
                    ->pluck('uuid')->toArray();
$tours = Tour::select(['id', 'uuid','city_uuid', 'tour_name', 'tour_image', 'is_top_tour','places', 'created_at'])
                    ->with(['pocity' => function ($query) {
                        $query->select('id', 'uuid', 'cities_id', 'region_id', 'country_id');
                },'pocity.city','pocity.poregion' ,'pocity.pocountry'])
                ->whereHas('pocity',function ($query) use ($cities) {
                    $query->whereIn('uuid',  $cities);
                })->where('is_active');

if($request->name != '' && $request->id != '' && $request->type != ''){
$tours = Pocities::query();
$tours->where('name', $request->name);
$toursData = $tours->paginate(10);

}


text:
Q: How this equation is attained of the 3 forces of threads and the conductive spheres? Currently I'm new to newtonian-mechanics, so I 've may been asking the trivial question.

As shown in the above diagram, the each insulating thread has stretched the conductive sphere.
The each sphere is same.
$m:=\text{mass of the each conductive sphere}$
$Q:=\text{charge of the each sphere}$
$W:=mg$
$F:=k_{\text{e}}\frac{Q^{2}}{(2r)^{2}}$
$W\sin(\theta)=F\cos(\theta)\tag{1}$
The current problem for me is the above equation.
I drew the blue dashed additional line in the diagram.
So as we assume the blue dashed line as some composite vector, I can easily deduce the (1) however the adequacy of it is uncertain I think.
Because I think that I must consider the 3 forces of the tension of the thread and $F$ and $G$ .
Must I consider the decomposition(s) of the vector(s) of tension, $W,F~$?
Considering these 3 forces, how (1) can be attained?

A: Because the balls are in equilibrium, you know by Newton's Second Law that the net external force is zero, that is, $\Sigma \vec {\bf F} = \vec 0$.
Since the net force is zero, then it does not matter along which axes you choose to decompose your forces -- for the net force to be zero, summing up components of forces along any axis must give zero. That is, you can decompose your forces along the up down directions, the axes along/perpendicular to the rope (as you did to get Eq. 1), or any other axes (see proof below).
I have done a FBD of the ball on the right below:

Notice where I labelled $W \sin\theta$ and $F\cos\theta$. For the net force to be zero, these components must be equal, that is, $W\sin\theta = F\cos\theta$, and there's your Eq 1.

Claim. When a body has zero net external force, calculating the component of the net force along any axis must give zero.
Proof. Let $\Sigma \vec {\bf F}$ be the net force, $$\Sigma \vec {\bf F} = \vec {\bf F}_1 + \vec {\bf F}_2 + \vec {\bf F}_3 + \dots + \vec {\bf F}_n.$$
Suppose $\Sigma \vec {\bf F}=\vec 0$. Now, take the projection along some axis with unit vector $\hat {\bf v}$:
$$\hat {\bf v} \cdot \Sigma \vec {\bf F} = \hat {\bf v} \cdot \vec {\bf F}_1 + \hat {\bf v} \cdot \vec {\bf F}_2 + \hat {\bf v} \cdot \vec {\bf F}_3 + \dots + \hat {\bf v} \cdot \vec {\bf F}_n.$$
Since $\Sigma \vec {\bf F}=\vec 0$, we have,
$$\hat {\bf v} \cdot \vec {\bf F}_1 + \hat {\bf v} \cdot \vec {\bf F}_2 + \hat {\bf v} \cdot \vec {\bf F}_3 + \dots + \hat {\bf v} \cdot \vec {\bf F}_n=0.$$
Notice that each $\hat {\bf v} \cdot \vec {\bf F}_i$ pair is the projection of $\vec {\bf F}_i$ along the $\hat {\bf v}$ axis, and all such projections sum to zero.


text:
Q: Reverse audio file (nodejs) How, using node js platform, reverse (playback version of file) audio file? And how it actually works ?
I already tried to reverse buffer of file:
let fs = require('fs');
var buffertools = require('buffertools');
let reverse = require("buffer-reverse")

let data =  fs.readFileSync('./test.mp3');

fs.writeFileSync('resulty.mp3',new Buffer(buffertools.reverse(data)));

A: You can use fluent-FFMPEG:
// with Audio file on server via fs
ffmpeg
        .input("cdn/" + jobID + "_tmp.mp3")
        .outputOptions(["-c copy", "-af areverse"])
        .save("cdn/" + jobID + "mp3");


text:
Q: AngularJS: Load two url one by one in a newly opened tab on ng-click It's very easy to open two URL one by one by using interval but in the same tab.
e.g.

Click Me

JS:
$scope.openTwoUrl=function(){
    $window.location.href='www.linkone.com';

    //Below will wait for the above link to be fully loaded.
    var interval = setInterval(function() {
        if(document.readyState === 'complete') {
            $window.location.href='linktwo.com';
            clearInterval(interval);
        }
    }, 100);
}

But my requirement is that I want to open these URL to be open one by one in a new tab.
So to open a new tab I use $window.open('www.firstlink.com') and immediately a new tab is opened and now I want that in that newly opened tab my second URL i.e www.secondlink.com to be loaded.
Searched a lot but didn't found anything. Any help or suggestion would be greatly appreciated.
NOTE:
JavaScript: location.href to open in new window/tab?

This question doesn't give me the solution to my problem

A: I don't think this is possible in pure javascript unless you are writing a chrome extension of some sort.
You would need to pass javascript from one tab to the other. That would require cross site-scripting which is a security vulnerability! Websites would never allow that.


text:
Q: how to parse a specific key in a given string using linux shell script I have a following pattern and would like to parse only one field
between /sys/bus/pci/devices/ and /device
Example 1
Input:
/sys/bus/pci/devices/0000:07:00.0/device:0x017a
Required output:
0000:07:00.0
Example 2
Input:
/sys/bus/pci/devices/0000:08:00.0/device:0x0abc
Required output:
0000:08:00.0

A: If your input is always that regular, then a simple cut command will do the job
cut -d/ -f6

eg
% echo /sys/bus/pci/devices/0000:07:00.0/device:0x017a | cut -d/ -f6
0000:07:00.0

% echo /sys/bus/pci/devices/0000:08:00.0/device:0x0abc | cut -d/ -f6
0000:08:00.0

A: If the Input has not a fix number of /, you may also use grep with context:
$ ... | grep -Po 'devices/\K.*?(?=/device)'


text:
Q: data binding from jsp to controller spring mvc model has list as a atribute I tried this way, but still the methods are not initialized and it gives null.
//model class set attribute
 @OneToMany(cascade = CascadeType.ALL, mappedBy = "customer", fetch = FetchType.EAGER)

   private Set<PaymentMethod> methods;

//jsp form

      <input type="checkbox" name="customer.methods[0].type" value="CC">credit card

      <input type="checkbox" name="customer.methods[1].type" value="DC">debit card

      <input type="checkbox" name="customer.methods[2].type" value="PP">pay pal

      <input type="checkbox" name="customer.methods[3].type" value="BC">bank credit

A: You question is quite hard to understand, but from what I can tell at first glance, you're trying to access a list as if it was an array which it isn't.
At least it should be customer.getMethods().get(0).getType() and so on.
The getters are there for clarity. Of course your entity has also to have getters and setters.


text:
Q: Traversing down keys in a dictionary to get a value from known keys I have a Dictionary<string, object> testJson that looks like this:
{
  "Data": {
    "Request": {
      "Id": "ADLFKJ9LKJADFJLSKLDJFAS",
      "Ts": "Fri Apr 04 10:51:54 EDT 2014",
      "Parameters": "advertisers=&responseFormat=json"
    },
    "Response": {
      "Id": null,
      "Ts": null
    },
    "StatusCode": "09",
    "Message": "Processing."
  }
}

I need to get the values for Data ==> Request ==> Id and Data ==> StatusCode and Data ==> Message.
So far, I have
var requestId = (from p in testJson
                             where p.Key.Contains("Id")
                             select p.Value)
                             .FirstOrDefault();

Console.WriteLine(requestId.ToString());

It doesn't seem to be working the way I expect...  requestId is returning null.
Thanks.

A: Assuming that the nested JSON elements are also of type Dictionary<string, object>...
var data = (Dictionary<string, object>)testJson["Data"];
var request = (Dictionary<string, object>)testJson["Request"];

var message = (string)data["Message"];
var status code = (string)data["StatusCode"];
var id = (string)request["Id"];


text:
Q: How to make vim use buffer instead of stdout by default? I searched all over the internet, but didn't find an answer.
I found plugin "AsyncCommand", but I don't want to type :AsyncCommand everytime. I just want vim to pipe stdout to a buffer by default.
Is it even possible? Do you know any plugin that can do this?

A: There is a plugin named Vim Pipe that does exactly this.  Very useful within its scope.


text:
Q: Explain $x^{x^{x^{{\cdots}}}} = \,\,3$ $$x^{x^{x^{\cdot^{\cdot^{\cdot}}}}} =\quad 2$$
This equation has the answer $\sqrt{2}$ by taking $\log$ to both side. This answer is correct because I'd proven it by replacing $x$ with $\sqrt{2}$ then computed the expression repeatedly and the answer is close to $2$.
But now consider,$$x^{x^{x^{\cdot^{\cdot^{\cdot}}}}} =\quad 3$$
I tried using the same solving method and it gave me that $\sqrt[3]{3}$ is the answer but when I tried proving the answer by replacing $x$ with $\sqrt[3]{3}$ and computed it repeatedly, the answer is closer to $2.478052680288297$ and not $3$
I don't know why this happens, could someone explain the answer to $x^{x^{x^{\cdot^{\cdot^{\cdot}}}}} = 3$ ?
I don't think it's $\sqrt[3]{3}$
The first equation problem came from brilliant.org

A: There is one more observation which should be useful for you.
Begin again with the problem of iterated exponentiation to base $b=\sqrt2$. If you start with some value smaller than $x_0 \lt 4$ you arrive at $x_\infty=t_0=2$:
$ \quad \qquad \displaystyle  x_0=1.1 \\
 \quad \qquad   x_k = b ^{x_{k-1}} \qquad \qquad \text{ where } b=\sqrt 2\\
 \quad \qquad   \lim_{k \to \infty} x_{k+1}=x_k=t_0=2
$
so we might call $t_0=2$ a "fixpoint" of that iterated operation, and because from all initial values (in a certain interval) it arrives at the same fixpoint, we call it an "attracting" fixpoint.
For instance
$ \quad \qquad \displaystyle  x_0=5.3 \\
 \quad \qquad   x_k = b ^{x_{k-1}} \\
 \quad \qquad   \lim_{k \to \infty} x_{k+1}= \infty
$
begins outside that interval and the iteration diverges to $\infty$
But if some value is a fixpoint for an operation, then it should also be the fixpoint of the reverse operation, thus we might look at
$  \quad \qquad \displaystyle x_0=1.1 \\
 \quad  \qquad    x_k = \log_b (x_{k-1}) \qquad \qquad \text{where} \log_b(\cdot) = \log(\cdot)/ \log(b) \text{ and } b=\sqrt2\\
 \quad  \qquad      \lim_{k \to \infty} x_{k+1} =x_k= t_{-1} \qquad \qquad \text{ (=some complex value) }
$
But now if you begin at $x_0=5.3$ then we find convergence
$ \quad \qquad \displaystyle x_0=5.3 \\
  \quad \qquad    x_k = \log_b (x_{k-1}) \\
 \quad  \qquad      \lim_{k \to \infty} x_{k+1} =x_k= t_1 = 4
$
$\qquad \qquad $ (and the same for any value $2 \lt x_0 \le 4$)
which is obviously "attracting" for the reverse operation in an interval in which the original operation has a divergent trajectory.
If in a third view we modify $x_0$ only the slightly least bit around $t_1$ then the original operation runs away from $4$, and so we might introduce the name "$t_1=4$ is a repelling fixpoint".
The same can now be applied to your other base where you find $b= 3^{1/3}$ . You can insert the exact value $x_0=3$ as initial value and shall find that it is a fixpoint. However it is a repelling one: if you let $x_0 = 3-\epsilon$ then the original operation iterates to the attracting fixpoint which is a bit larger than 2 and if you apply the reverse operation you'll find the repelling fixpoint $t_1 = 3$ which is what you wanted.

A: Here's a question: if $x = \sqrt[3]{3}$, then what is the value of $y = x^{x^{x^{\dots}}}$?
As you say, if $y$ is a solution to this, then $y \ln x = \ln y$, so that
$$
\frac{\ln y}{y} = \ln(x) = \frac{\ln(3)}{3}
$$
Now, how can we "solve this" for $y$?  As it ends up, there are two solutions for $y$.  The answer you are getting is the second root, $y \approx 2.47805$.
We can, in fact, conclude that the equation $x^{x^{x^{\dots}}} = 3$ has no solution.

So, the salient question is how do we "choose" one value of $y$ over the other?
First of all, we should decide when this sequence converges at all.  For a fixed $a$, define the function $f_a(x) = a^x$. Consider the following recursive definition of a sequence:
$$
x_0 = 1\\
x_n = a^{x_{n-1}}
$$
If any one value for $y  = a^{a^{a^{\dots}}}$ makes sense, it's the limit $\lim_{n \to \infty} x_n$.  This has now become an analysis of fixed-point iteration.
It's relatively easy to show that we can guarantee that this sequence converges as long as near $x = 1$ (our starting point), $|f'(x)| < 1$.  Because $f'(x) = \ln(a) a^x$, we find that $|f'(1)| < 1$ exactly when $a < e$.  So, this sequence will necessarily converge for $a \in (e^{-1},e)$.
As it turns out, however, this is not the only situation in which the sequence converges. In fact, it was shown by Euler (see wiki page and comments below) that the sequence will converge for $e^{-e} < a < e^{1/e}$. Correspondingly, the limit of the sequence will necessarily lie in $(1/e,e)$. Because $3$ lies beyond these bounds, it cannot be the limit of such a sequence.
See also this wikipedia page.

A: $$ x^{x^{x^{\kern3mu\raise1mu{.}\kern3mu\raise6mu{.}\kern3mu\raise12mu{.}}}}=y $$
$$ \ln{x^{x^{x^{\kern3mu\raise1mu{.}\kern3mu\raise6mu{.}\kern3mu\raise12mu{.}}}}}=\ln y $$
$$ x^{x^{x^{\kern3mu\raise1mu{.}\kern3mu\raise6mu{.}\kern3mu\raise12mu{.}}}}\ln{x}=\ln y $$
$$ y\ln{x}=\ln y $$
$$ \ln{x}=(\ln{y})/y $$
$$ \ln{x}=\ln({y^{1/y}}) $$
$$ x= y^{1/y} $$
Substitute in $2$ and $3$ to see why these are the solutions of $x$. They will always be the $y^{\text{th}}$ root of $y$.


text:
Q: Could not connect to the endpoint URL: "http://localhost:8000/" DynamoDB with Python I am trying to follow the tutorial within the documentation:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Python.01.html
as such:
def create_movie_table(dynamodb=None):
    if not dynamodb:
        dynamodb = boto3.resource('dynamodb',
                                  aws_access_key_id="anything",
                                  aws_secret_access_key="anything",
                                  region_name = 'us-east-2',
                                  endpoint_url="http://localhost:8000")

    table = dynamodb.create_table(
        TableName='DailyMovers',
        KeySchema=[
            {
                'AttributeName': 'date',
                'KeyType': 'HASH'  # Partition key
            },
            {
                'AttributeName': 'type',
                'KeyType': 'RANGE'  # Sort key
            }
        ],
        AttributeDefinitions=[
            {
                'AttributeName': 'date',
                'AttributeType': 'S'
            },
            {
                'AttributeName': 'type',
                'AttributeType': 'S'
            },

        ],
        ProvisionedThroughput={
            'ReadCapacityUnits': 5,
            'WriteCapacityUnits': 5
        }
    )
    return table

if __name__ == '__main__':

    create_movie_table()

However, I keep running into the localhost:8000 connection error.
I am installed boto3 properly.
I am not quite sure what I am doing wrong.
Thank you.

A: The version of DynamoDB that runs from localhost for testing is a separate download from Amazon which requires Java to run.  I don't believe it's part of any other package including AWS-cli.  You can find instructions for it at Setting Up DynamoDB Local (Downloadable Version).


text:
Q: Bluetooth broken in IOS 9.1/Xcode 7.1.1 Running IOS 9.1 with Xcode 7.1.1 under 10.11.1. Cut'n'pasted this code from this tutorial; and double check it with several other sources/sites.
http://hatemfaheem.blogspot.ch/2014/12/how-would-you-scan-for-nearby-ble.html
This is the code I have ...
import Foundation
import CoreBluetooth

class BLEManager  {
var centralManager : CBCentralManager!
var bleHandler : BLEHandler // delegate
init() {
    self.bleHandler = BLEHandler()
    self.centralManager = CBCentralManager(delegate: self.bleHandler, queue: nil)
}
}

class BLEHandler : NSObject, CBCentralManagerDelegate {
override init() {
    super.init()
}

func centralManagerDidUpdateState(central: CBCentralManager) {
    switch (central.state)
    {
    case .Unsupported:
        print("BLE is unsupported")
    case .Unauthorized:
        print("BLE is unauthorized")
    case .Unknown:
        print("BLE is unknown")
    case .Resetting:
        print("BLE is reseting")
    case .PoweredOff:
        print("BLE is powered off")
    case .PoweredOn:
        print("BLE is powered on")
        central.scanForPeripheralsWithServices(nil, options: nil)
    default:
        print("BLE default")
    }
}

func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
    print("didConnectPeripheral")
}

func centralManager(central: CBCentralManager!,
    didDiscoverPeripheral peripheral: CBPeripheral!,
    adverismentData: [NSObject : AnyObject]!,
    RSSI: NSNumber!)
{
    print("\(peripheral.name) : \(RSSI) dBm")
}
}

Which I invoke in the View Controller with this code
 override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    var bleManager: BLEManager!
    bleManager = BLEManager()
}

Now I run it on an iPad Air with 9.1 and plug in and unplug and replug an ibeacon but nothing appears on the console, suggesting it simply isn't working. Now I know the ibeacon is working; cause I find it with the ScanBeacon tool by Radius Networks.
OK I understand that ibeacons and Core Bluetooth don't go together so well, but surely didDiscoverPeripheral should be called ? Or have I missed a critical line in my code?

A: Your BLEManager is going out of scope and being deallocated at the end of viewDidLoad. Make it a member variable to give it a longer, more useful lifetime:
var bleManager = BLEManager()

override func viewDidLoad() {
    // etc
}


text:
Q: Block a div on click when .hover is already applied? I have an element that when hovered will .show() a div on the right side of the screen. That div have 'display: none' by default. When mouse is no longer hovering the element, .hide() is executed:
var gacHoverElement = ".gacPreviewPostContainer";
$(gacHoverElement).hover(function() {
        var idx = $(this).index(gacHoverElement);
        $("#gacHover" + idx).show();
    },function() {
        var idx = $(this).index(gacHoverElement);
        $("#gacHover" + idx).hide();
    });

The code works just fine, and now I'd like to have an .click() function that if the element is clicked, the div sticks on the right side even if the mouse hovers out of the element. I tried a few things with no success.
Any ideas?
Example:

var gacHoverElement = ".gacPreviewPostContainer";
$(gacHoverElement).hover(function() {
     var idx = $(gacHoverElement).index(gacHoverElement);
     $("#gacHover" + idx).show();
    },function() {
     var idx = $(gacHoverElement).index(gacHoverElement);
     $("#gacHover" + idx).hide();
    });
.gacPreviewPostContainer {background-color: aqua;width: 50px;height: 50px;text-align: center;font-size: 10px;line-height: 45px;cursor: pointer;margin-bottom: 5px;}
.gacHoverContainer {overflow: auto;display: none;background-color: #EEEEEE;height: 100%;width: 30%;position: fixed;top: 0;right: 0;z-index:2003;border-left: 6px solid #448aff;box-shadow: rgba(0, 0, 0, 0.2) 0px -2px 10px;padding: 20px;}
.gacHoverContainer {display: none;}

Preview

Preview

Preview

Preview

A: WORKING EXAMPLE WITH CLICK TOGGLING HIDE/SHOW:

var gacHoverElement = ".gacPreviewPostContainer";

var attachHover = function() {
  console.log("attaching");
  $(gacHoverElement).hover(function() {
    var idx = $(this).index(gacHoverElement);
    $("#gacHover" + idx).show();
  }, function myhandler() {
    var idx = $(this).index(gacHoverElement);
    $("#gacHover" + idx).hide();
  });
}
$(gacHoverElement).each(function() {
  $(this).click(function() {
    var ev = $._data(this, 'events');
    if (ev && ev.mouseover && ev.mouseout) {
      $(gacHoverElement).unbind('mouseenter mouseleave')
    } else {
      attachHover();
    }
  })
})
attachHover();
.gacPreviewPostContainer {
  background-color: aqua;
  width: 50px;
  height: 50px;
  text-align: center;
  font-size: 10px;
  line-height: 45px;
  cursor: pointer;
  margin-bottom: 5px;
}
.gacHoverContainer {
  overflow: auto;
  display: none;
  background-color: #EEEEEE;
  height: 100%;
  width: 30%;
  position: fixed;
  top: 0;
  right: 0;
  z-index: 2003;
  border-left: 6px solid #448aff;
  box-shadow: rgba(0, 0, 0, 0.2) 0px -2px 10px;
  padding: 20px;
}
.gacHoverContainer {
  display: none;
}

Preview1

Preview2

Preview3

Preview4

11111111111111111111

22222222222222222222

33333333333333333333

44444444444444444444


text:
Q: Significantly Slower DB Dumps on AWS RDS After Turning on Encryption? Turning on encryption on an AWS RDS MySQL instance results in significantly slower database dumps (using mysqldump).
mysqldump -u test -p -h xxx.aws.com > dump.sql

Is there a reason for significantly slower DBdumps on AWS RDS after turning on encryption?

A: mysqldump reads all of your data.  If the encryption is at the disk, then it takes time to decrypt the data before mysqldump can access it.  Hence, the total action is slower.
Do you have any metrics on how much slower (percentage)?
Also, since RDS does key management, there may be a slight, one-time, delay to get the key.

A: Encryptions typically compress the data as their first step. It is not needed, but it is the common practice on various, mainly security reasons: in short, the compressed byte stream will be practically redundancy-free, like a random bytestream, which significantly reduces the possibilities of various cryptological attacks.
If you have a slow network connection to your aws VM, then the performance improvement due to the lesser data flow can be higher as the loss due to the CPU need of the compression (+ encryption). It depends also on the applied compression.
In other configurations (slow CPU + fast network) the transfer of the encrypted bytestream might be longer.
If it annoys you, check the CPU usage on the VM. You may play with the MySQL encryption/compression parameters on both of the server and the client side.

A: The reason is that your mysqldump command is missing some parameters.
There's nothing related about turning Encryption on your RDS instance.
Please add --set-gtid-purged=OFF, --quick and --compress on command parameters that will boost your dump speed:
New mysqldump:
mysqldump -u test -p -h xxx.aws.com --set-gtid-purged=OFF --quick --compress > dump.sql

If you want your dump file to be in gzip format (small file size), so:
mysqldump -u test -p -h xxx.aws.com --set-gtid-purged=OFF --quick --compress | gzip > gziped_dump.sql.gz


text:
Q: Align Visual Studio Code and Visual Studio Key Mappings Is there an easy way to align the shortcut key mappings from Visual Studio with Visual Studio Code?
Example
Visual Studio auto-format document
CTRL + K + D
Visual Studio Code auto-format document
CTRL + SHIFT + F I want to replace this with the above shortcut.

A: There is a Visual Studio Code extension called Visual Studio Keymap.
I haven't tried it myself but the example you gave is listed in the description.
Here is a link to it: https://marketplace.visualstudio.com/items?itemName=ms-vscode.vs-keybindings

A: The code formatting is available in Visual Studio Code through the following shortcuts:

*

*On Windows Shift + Alt + F.

*On Mac Shift + Option + F.

*On Ubuntu Ctrl + Shift + I.


text:
Q: How to show that likelihood ratio test statistic for exponential distributions' rate parameter $\lambda$ has $\chi^2$ distribution with 1 df? Let $X_1, X_2, ..., X_n$ be iid. random variables with pdf. exponential. Let $H_0 = \theta = \theta_0 $ and $H_1 = \theta = \theta_1$. Then test statistic for likelihood ratio would be:
$$ LR = \frac{f(X_1, X_2, ..., X_n \mid\theta_0)}{f(X_1, X_2, ..., X_n \mid\theta_1)} = \frac{\theta_0^{-n}\exp \{-\sum_i  X_i/\theta_0 \}}{\theta_1^{-n}\exp \left\{-\sum_i  X_i/\theta_1 \right\}} = \left(\frac{\theta_0}{\theta_1}\right)^{-n}e^{\left(\frac{1}{\theta_1} - \frac{1}{\theta_0}\right) \sum_{i} X_{i}}$$
How to show that $LR \rightarrow \chi^2_1 \ $ ? Thanks in advance!

A: Let $x \mapsto f(x \mid \theta)$ be a parametrised density function on a sample space $\mathrm{X}$ (so that $x$ are the possible observations) and with parameter $\theta$ assumed a priori to lie in some $\Omega_0 \subset \mathbf{R}^{d_0}.$ (Do not confuse this with a priori Bayesian distributions.) Suppose that $n$ independent samples are taken and write
$$
f_n(\mathbf{x}_n \mid \theta) = f_n(x_1, \ldots, x_n \mid \theta) = \prod_{k = 1}^n f(x_k \mid \theta)
$$
for the likelihood of the sample.
Suppose $\Omega_1$ is an open set such that $\Omega_0 \subset \Omega_1$ and we further assume that $\Omega_0$ is embedded in a $d_0$-dimensional subspace of $\mathbf{R}^{d_1}$ ($d_0 = 0$ not excluded, meaning $\Omega_0$ is a single point). Let
$$
\ell_n^*(\mathbf{x}_n \mid \mathrm{H}_i) = \sup_{\theta \in \Omega_i} \log f_n(\mathbf{x}_n \mid \theta)
$$
the log-likelihood optimised over the hypothesis $\mathrm{H}_i$ that $\theta \in \Omega_i.$
Wilk's theorem: Suppose that $f$ satisfy some measure-theoretic regularity conditions, and that for each $n,$ $\theta \mapsto f_n(\mathbf{x}_n \mid \theta)$ has maximimisers
$$
\theta_1^* = \theta_{1,n}^*(\mathbf{x}_n)
$$ in the interior of $\Omega_1,$ and
$$
\theta_0^* = \theta_{0,n}^*(\mathbf{x}_n)
$$
the interior of $\Omega_0$ relative to the subspace it is embbed into.
In other words, we assume that
$$
\ell_n^*(\mathbf{x_n} \mid \mathrm{H}_i) = \log f_n(\mathbf{x}_n \mid \theta_i^*).
$$
Then, as $n \to \infty$ ("as the number of sampled observations increases unlimitedly")
$$
-2\log \dfrac{f_n(\mathbf{x}_n \mid \theta_0^*)}{f_n(\mathbf{x}_n \mid \theta_1^*)} = 2 \big( \ell_n^*(\mathbf{x}_n \mid \mathrm{H}_1) - \ell_n^*(\mathbf{x}_n \mid \mathrm{H}_0) \big) \to \chi^2_{d_1 - d_0}
$$
Notes:

*

*Wilk's theorem uses the ratio of likelihoods principle. The likelihood of a sample is a metric that, well, estimates how likely is to see what we saw if the parameter we assume is $\theta.$ The ratio of likelihoods (likelihood ratio) $\dfrac{f_n(\mathbf{x}_n \mid \theta_0^*)}{f_n(\mathbf{x}_n \mid \theta_1^*)}$ is always $\leq 1,$ so the log-likelihood ratio is therefore $\geq 0.$ The likelihood ratio principle state that if the likelihood ratio is too small (equiv. the log-likelihood is too big) then the hypothesis $\mathrm{H}_0$ is incompatible with the data and as such there is evidence suggesting that $\mathrm{H}_1$ holds. How unlikely depends on the actual density $f,$ however, Wilk's theorem states that for large samples, we do not depend (thankfully) on $f$ but on the $\chi^2$-disitribution (so, Wilk's theorem is sort of a central limit theorem for the likelihood ratio principle).

*Wilk's theorem can be extended to the case where $\Omega_0$ is a single point (i.e. specifies the parameter exactly).

*I am not sure if Wilk's theorem has an extension (or what would that extension even mean) if you specify both parameters. The usual proof uses that $\Omega_0 \subset \Omega_1$.

*To use Wilk's theorem, you need to find the ratio of the likelihoods evaluated at the optimisers of both hypotheses.

*The degrees of freedom will then be the difference in dimensions of the two hypothesis, namely $d_1 - d_0.$ When you specify both hypothesis to be a single parameter, you will reach a zero, so certainly something is wrong with your formulation.

*Check the following link too https://stats.stackexchange.com/questions/101520/what-are-the-regularity-conditions-for-likelihood-ratio-test


text:
Q: URL Path is not loading in xsl-Fo we are working with PDf/A with antenna house,in xsl-fo added color profile with url local file system facing error below
1)if we dont add color profile we getting error like below
jp.co.antenna.XfoJavaCtl.XfoException: PDF output error. (3500)
Empty Output Intent Error
2)if we add color profile in xsl-fo error like below
jp.co.antenna.XfoJavaCtl.XfoException:PDF output error. (3352) Load ICC Color Profile Error:
   <fo:Declarations>
     <fo:color-profile src="url('xx/sRGB.icc')" color-profile-name="sRGB IEC61966-2.1" />

or
     <fo:color-profile src="url(file:///xx/sRGB.icc)" color-profile-name="sRGB IEC61966-2.1" />
   </fo:Declarations>

Kindly help on this ??


text:
Q: Appropriate Method of Counting counts from a Quadrature Encoder I'm using an Mbed to drive a DC motor which will follow a trapezoidal trajectory.
What is the most appropriate way to determine position from the quadrature encoder?
Should I use interrupts, or is there a risk of the trajectory routine (which calculates theoretical position) falling behind?
Alternatively, I could poll/sample the encoder in fixed time steps, but I'd imagine this would miss out many encoder counts.
How is this problem usually dealt with?

A: It's best if you have quadrature encoder hardware to handle the encoder pulses, unless the speed is very low. Many microcontrollers have at least one such peripheral on the chip.

A: You have to poll the state of the two Q input often enough not to miss a state transition. How quickly this is depends on how quickly the Q inputs can change, and only you can tell that. The correct way to do the counting is to use a 4-state FSM, which handles bounding and direction changes correctly.
How do you check often enough?

*

*as Sphero stated, using Q-decoder hardware is a perfect way, and it will liklely be fast enough for any purpose.

*you can use a timed or on-change interrupt to tickle your FSM. How fast you can do this depends on your system, and how much of its resources you want to spend on this task.

*for in-frequently changing Q-inputs you could just poll the inputs.

A: A very great deal is going to depend on your motor/encoder setup, which you have not specified. Let's say (just as a starting point) the your motor shaft can run at a maximum of 600 rpm (10 rps) and your encoder produces 64 pulses per channel. That is, if you run the shaft at 10 rps, you get a 640 Hz square wave on each channel.
When using a quadrature encoder, you can derive 4 times as many position events, corresponding to both the rising and falling edges of the two channels, for a shaft resolution of 256 points per revolution, or 2560 points per second.
You have not provided a processor board specification, either, but let's say that it allows 4 channels of digital inputs. Then you can look at both your encoder channels, and also a pair of channels which have inverted versions of your encoder lines. Now you can write your software to generate an interrupt on each of the rising edges of the 4 inputs. At each interrupt you examine the two encoder lines and determine the local position. At the same time, you read your real-time clock to determine the time since the last encoder tick, and from that determine the shaft velocity. Can you do that in (let's say) 1/10 of the time between ticks? That's 40 usec. Also, you'll need to find some way to prevent any other interrupts from preempting your encoder routines for more than 400 usec. If you don't, you lose position information, and any process which prevents immediate time interval measurement will screw up your shaft rate calculation.
With only a small about of hardware (a couple of exclusive-OR gates and an RC delay) you can produce a single input which will generate interrupts for all four encoder transitions, so you could get away with 3 digital inputs.
If the transition frequency is low, as Wouter van Ooijen says, you can try simply polling the encoder outputs, but be aware that this will introduce uncertainties in your shaft velocity calculations, especially if your processor is doing anything else which may have higher priority, and any such uncertainty will degrade your ability to hold to a desired velocity profile, trapezoidal or otherwise.
Overall, I'd advise you listen to Spehro.


text:
Q: Maplace + Rails 4 receiving dates dynamically I'm using maplace.js with Rails 4, its pretty. Is almost all work how I want, but I need, onclick in even icon take the show_infowindow (this a option the maplace.js), but I don't know! (html = show_infowindow)
This is my code:
 new Maplace({
   locations: #{@localizacoes.to_json(:only => [:latitude, :longitude, :nome]).gsub('latitude', 'lat').gsub('longitude', 'lon').gsub('nome',     'title')},
   map_div : '#gmap-dropdown',
   shared: {
     html: '#{@localizacoes.find(params[:id]).created_at}'
   }
 }).Load();

The error is:
 Coundn't find Localizacao without an ID
Please, someone help me? I'm trying more than 1 week! Thanks!


text:
Q: Not able to mock the method inside flask URL I written below url in flask
@app_url.route('/createvm', methods=['GET', 'POST'], defaults={'buildid': None})
def form(buildid):
    command = prepare_ansible_command(data)
    success,reason = run_command(command)
    # here run_coomand method not returning mock return value.
    ....

writing below unit test case
@patch('app.vm_create.utility.run_command')
def test_vm_create_negative3(self, run_command_mock):
    run_command_mock.return_value = True, "response123456"
    from app.vm_create.utility import run_command
    #I checked run_command here it's returning mock return value (True, "response123456")
    with self.client:
        resp = self.client.post("/signin/", data={"username": self.act.username,
                                "password": self.password, "token":True})
        resp= self.client.post("/createvm", data=data)

The run_commnad returning mocked return value inside test method.
It's not returning mock return value inside view function (createvm)
running the above test using pytest
pytest test_app.py -k "test_vm_create_negative3"

A: Solved! This is what it was happening: run_command() function was implemented in app.vm_create.utility.py, but it was imported by app.vm_create.controllers.py. When I tried to mock run_command by patching app.vm_create.utility.run_command (in utility where it was implemented), it didn't work. However, this worked:
@patch("app.vm_create.controllers.run_command")
def test_etc:
    etc

As you can see, I'm still patching run_command(), but this time, with the path of the module which is importing it, controllers.


text:
Q: How do I stop Python from generating a new line each time? I have created a translator for Morse code in Python and the code works fine except for one problem. When it translates the message into Morse code, it places each character onto a new line. I need the entire translation to stay in one line and I cannot figure out how to make it stay in one line, nor why it is generating a new line each time for each character. Please help! Here is the code:
print("\n\tMenu Options: \n")
print("\t1. Type a phrase and have it translated into Morse Code. \n\t2. Exit program \n")

# Define the main function.

def main():
    charactersList = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0',
                      '1','2','3','4','5','6','7','8','9','.',',','?','!',' ']

    morse = ['.- ','-... ','-.-. ','-.. ','. ','..-. ','--. ','.... ','.. ','.--- ','-.- ','.-.. ','-- ','-. ','--- ','.--. ','--.- ',
             '.-. ','... ','- ','..- ','...- ','.-- ','-..- ','-.-- ','--.. ','----- ','.---- ','..--- ','...-- ','....- ','..... ',
             '-.... ','--... ','---.. ','----. ','.-.-.- ','--..-- ','..--.. ','-.-.-- ','/ ']

    print("\nPlease select a menu option by typing 1 or 2.")
    choice = int(input("\nMenu Choice: "))

    # Start the while loop within the main function.

    while choice != 2:

        if choice == 1:

            print("\nPlease type the phrase you would like translated into Morse Code.")
            translatee=input()
            translatee=translatee.lower()

            for x in translatee:

                if x in charactersList:
                    print("Translation: ",morse[charactersList.index(x)])

        else:
            print("Error: Please select a valid menu option.")

        # See what the users' next choices are.

        choice = int(input("\nMenu Choice: "))

    print("\n\tExited.")

# Call the main function.

main()

input(exit)

Here is an example of the output:
screenshot of output

A: Replace:
for x in translatee:

    if x in charactersList:
        print("Translation: ",morse[charactersList.index(x)])

By:
print("Translation:")
for x in translatee:

    if x in charactersList:
        print(morse[charactersList.index(x)], end=' ')

to prevent Python to create a new line for each translated character. By default, end='\n' that's why python creates a new line.

A: Use end= in the print statement and move Translation outside the loop.
if choice == 1:

        print("\nPlease type the phrase you would like translated into Morse Code.")
        translatee=input()
        translatee=translatee.lower()
        print("Translation: ") # <-- add print line here
        for x in translatee:

            if x in charactersList:
                print(morse[charactersList.index(x)], end=' ') # add end= here

A: You could accomplish this by keeping track of whether or not this is the first iteration of the for loop using a variable such as firstTime, the first time you enter the for loop you will need to check if firstTime is true and then set it to false and print out the morse code with Translation: at the start, this way nn the next iteration of the for loop the print statement will not print out Translation: at the start. You can stop the print function from automatically ending the line by adding end="" at the end of the print statement. The firstTime variable should be inside of the if statement in the while loop so that it is reset to true every time the user wants to translate morse code.
Here is the new code:
print("\n\tMenu Options: \n")
print("\t1. Type a phrase and have it translated into Morse Code. \n\t2. Exit program \n")

# Define the main function.

def main():
    charactersList = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0',
                      '1','2','3','4','5','6','7','8','9','.',',','?','!',' ']

    morse = ['.- ','-... ','-.-. ','-.. ','. ','..-. ','--. ','.... ','.. ','.--- ','-.- ','.-.. ','-- ','-. ','--- ','.--. ','--.- ',
             '.-. ','... ','- ','..- ','...- ','.-- ','-..- ','-.-- ','--.. ','----- ','.---- ','..--- ','...-- ','....- ','..... ',
             '-.... ','--... ','---.. ','----. ','.-.-.- ','--..-- ','..--.. ','-.-.-- ','/ ']

    print("\nPlease select a menu option by typing 1 or 2.")
    choice = int(input("\nMenu Choice: "))

    # Start the while loop within the main function.

    while choice != 2:

        if choice == 1:
            firstTime = True

            print("\nPlease type the phrase you would like translated into Morse Code.")
            translatee=input()
            translatee=translatee.lower()

            for x in translatee:

                if x in charactersList:
                    if firstTime:
                        firstTime = False
                        print("Translation: ",morse[charactersList.index(x)], end="")
                    else:
                        print(morse[charactersList.index(x)], end="")

        else:
            print("Error: Please select a valid menu option.")

        # See what the users' next choices are.

        choice = int(input("\nMenu Choice: "))

    print("\n\tExited.")

# Call the main function.

main()

input(exit)

This is the output when I ran it and told it to translate it works!

    Menu Options:

    1. Type a phrase and have it translated into Morse Code.
    2. Exit program

Please select a menu option by typing 1 or 2.

Menu Choice: 1

Please type the phrase you would like translated into Morse Code.
it works!
Translation:  .. - / .-- --- .-. -.- ... -.-.--
Menu Choice:


text:
Q: Dataset returns undefined (not in console) I struggle with this simple thing:
Body tag looks like this:
<body class="home page-template-default page page-id-12 page-parent logged-in admin-bar elementor-default elementor-kit-77 elementor-page elementor-page-12 customize-support" data-elementor-device-mode="tablet">

When I put console.log(document.querySelector('body').dataset.elementorDeviceMode); directly in chrome console, I get "tablet". When I put the same line of code into my js file, I get "undefined".
Can somebody tell me what I'm doing wrong?


text:
Q: Python ndb Datastore put list to Datastore I am trying to populate a Datastore with my older course notes so that in future I can add notes like a comments board or guestbook.
I can't seem to get the previous notes in the Datastore and have been trolling over GAE documentation and searching the web to no avail.
Here is my code:
import time
import cgi
import os
import jinja2
import webapp2
from google.appengine.ext import ndb

jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True)

dataEntery = [[1, 4, 'Networks','''

A network is a group of entities that can communicate, even
'''],
[2, 4, 'Measuring Networks','''

The two main ways of measuring a network are;

      '''], etc]

class CourseData(ndb.Model):
    id_index = ndb.IntegerProperty()
    stage_number = ndb.IntegerProperty()
    note_title = ndb.StringProperty(indexed=False)
    note_content = ndb.StringProperty(indexed=False)

for a in dataEntery:
    newEntry = CourseData(id_index=a[0], stage_number=a[1], note_title=a[2], note_content=a[3])
    newEntry.put()
    time.sleep(.2)

class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.out.write('''
            <!DOCTYPE HTML>

                        <title>Lee's Notes</title>
                        <link href="../styles.css" rel="stylesheet" type="text/css">

Lee's Notes on Intro to Programming

                    ''')
        query = CourseData.query(stage_number == 4).fetch()
        self.response.out.write('

%s
' % cgi.escape(query.note_title), cgi.escape(query.note_title))
        self.response.out.write('%s
' % cgi.escape(query.note_content))

app = webapp2.WSGIApplication([
        ('/', MainHandler)], debug=True)

A: First thing to note is that the appengine datastore is eventually consistent. Read this article: https://cloud.google.com/appengine/docs/python/datastore/structuring_for_strong_consistency?hl=en
For you're case you don't really need a query. Make a good index and then retrieval is a lot easier with a key.get(). Note, this is assuming you don't want to use id_index...
for a in dataEntery:
    entityKey = ndb.Key(CourseData._get_kind(), stage_number=a[1])
    newEntry = CourseData(key=entityKey, id_index=a[0], stage_number=a[1], note_title=a[2], note_content=a[3])
    newEntry.put()

Retrieval then becomes:
entity_key = CourseData.build_key(4)


text:
Q: Cluster-issuer secret wont replicate with multiple ingress I was under the impression that the main point of cluster-issuer is that its namespaced and doesn't have to be recreated across different resources, in general there could be one main cluster-issuer that will manage all ingresses across the cluster.
From what I am seeing the cluster-issuer can only create one secret and if its in use by one ingress the second wont wont be created properly cause its already taken.
Is there anyway to create one cluster-issuer to manage all ingresses across the cluster?
Code included below
Cluster-issuer.yaml
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-grafana
  namespace: cert-manager
spec:
  acme:
    server: https://acme-v02.api.letsencrypt.org/directory
    email: foo@gmail.com
    privateKeySecretRef:
      name: letsencrypt-grafana
    solvers:
    - selector:
        dnsZones:
          - "foo.com"
      dns01:
        route53:
          region: eu-central-1
          hostedZoneID: foo
          accessKeyID: foo
          secretAccessKeySecretRef:
            name: aws-route53-creds
            key: password.txt

Ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: grafana-ingress
  namespace: loki
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-grafana
    kubernetes.io/tls-acme: "true"
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/proxy-body-size:  "125m"
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx
  tls:
  - hosts:
    - grafana.foo.com
    secretName: letsencrypt-grafana # < cert-manager will store the created certificate in this secret.
  rules:
  - host: grafana.foo.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: loki-grafana
            port:
              number: 80

A: i would recommend creating the wildcard certificate using issuer/clusterissuer.
So you will be having the single secret with wildcard cert so you can use that across all ingress.
As you are already using DNS verification it will work well, as wildcard not supports the HTTP
apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
  name: letsencrypt-prod
spec:
  acme:
    email: test123@gmail.com
    server: https://acme-v02.api.letsencrypt.org/directory
    privateKeySecretRef:
      name: letsencrypt-prod
    solvers:
    - selector:
        dnsZones:
          - "devops.example.in"
      dns01:
        route53:
          region: us-east-1
          hostedZoneID: Z0152EXAMPLE
          accessKeyID: AKIA5EXAMPLE
          secretAccessKeySecretRef:
            name: route53-secret
            key: secret-access-key
---
apiVersion: cert-manager.io/v1alpha2
kind: Certificate
metadata:
  name: le-crt
spec:
  secretName: tls-secret
  issuerRef:
    kind: Issuer
    name: letsencrypt-prod
  commonName: "*.devops.example.in"
  dnsNames:
    - "*.devops.example.in"

Read my full article : https://medium.com/@harsh.manvar111/wild-card-certificate-using-cert-manager-in-kubernetes-3406b042d5a2
Ingress & secret example
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/ssl-redirect: "false"
    certmanager.k8s.io/issuer: "letsencrypt-prod"
    certmanager.k8s.io/acme-challenge-type: dns01
    certmanager.k8s.io/acme-dns01-provider: route53
  name: ingress-resource-tls
  namespace: default
spec:
  rules:
  - host: "hello.devops.example.in"
    http:
      paths:
      - backend:
          serviceName: hello-app
          servicePort: 8080
        path: /
        pathType: ImplementationSpecific
  tls:
  - hosts:
    - "hello.devops.example.in"
    secretName: tls-secret

A: @Harsh Manvar while I do appreciate your anwser I found something that is a better suit for my needs.
Cert-manager documentation contains multiple options to sync secrets across namespaces
The one I chose was reflector. The steps to install are included in the documentation but just for the sake of service i'll post here aswell
Requirements: Helm
Installation:
helm repo add emberstack https://emberstack.github.io/helm-charts
helm repo update
helm upgrade --install reflector emberstack/reflector

Setup:
Add the following annotation to your secret reflector.v1.k8s.emberstack.com/reflection-allowed: "true", it should look like the following
apiVersion: v1
kind: Secret
metadata:
 name: source-secret
 annotations:
   reflector.v1.k8s.emberstack.com/reflection-allowed: "true"

Done! Your secret should be replicated within all namespaces. For multiple ingress configurations within the same namespace you could edit your ingress.yaml like this
Ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: jenkins-ingress
  namespace: jenkins
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-global
    kubernetes.io/tls-acme: "true"
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/proxy-body-size:  "125m"
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx
  tls:
  - hosts:
    - jenkins.foo.com
    - nginx.foo.com
    secretName: letsencrypt-global # < cert-manager will store the created certificate in this secret.
  rules:
  - host: jenkins.foo.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: jenkins
            port:
              number: 80
  - host: nginx.foo.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: nginx
            port:
              number: 80


text:
Q: Large files download issue with EKS + NGINX + JETTY I'm having trouble with a large file download, 3GB. This is my set up JETTY 9.4 + NGINX (helm chart from https://kubernetes.github.io/ingress-nginx/) on Kubernetes (AWS EKS). It works for smaller files. With such large files I get a "Failed - network error" on the client side. On the jetty side I get a connection reset by peer exception. On the NGINX side nothing apparent, at least not in the log files.
If I download the file directly from the service, ie using kubectl port-forward, there is no problem. So it looks like it's an issue with either EKS or NGINX. I set the usual NGINX suspects to their recommended values but to no avail.
This is my ingress yaml
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress
  namespace: webapps
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/client-max-body-size: "0"
    nginx.ingress.kubernetes.io/proxy-body-size: "0"
    nginx.ingress.kubernetes.io/proxy-buffering: "off"
    nginx.ingress.kubernetes.io/proxy-max-temp-file-size: "0"
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/force-ssl-redirect: "false"
spec:
  tls:
    - hosts:
        - my.website.com
      secretName: tls-secret
  rules:
    - host: my.website.com
      http:
        paths:
          - backend:
              serviceName: servicename
              servicePort: 8080
            path: /

I also checked the generated nginx conf and it looks OK.
Any recommendation at what to look at next?

A: can you please try with Nginx ingress annotation to increase read and send timeout
nginx.ingress.kubernetes.io/proxy-read-timeout: "1800"
nginx.ingress.kubernetes.io/proxy-send-timeout: "1800"


text:
Q: Creating json array and writing it to file im new in json, php and javascript. I want to save form datas in a json file. I created a form using both html and javascript and created an ajax request to post it php. In my php file im planning to write it to a file. Now my codes work but i want to make it json array. This is what i have right now.
{
"Brand": "Ferrari",
"Model": "458 Italia",
"Year": "2010 - 2015",
"body": "2-seat Berlinetta, 2-seat Spider",
"engine": "4.5L Ferrari F136F V8",
"power": "562bhp @9000rpm",
"torque": "540nm @6000rpm",
"transmission": "7-speed dual clutch",
"topSpeed": "325kph",
"acceleration": "3.3 sec"
}

But I want to do it like this.
{
"cars": [
    "Brand": "Ferrari",
    "Model": "458 Italia",
    "Year": "2010 - 2015",
    "body": "2-seat Berlinetta, 2-seat Spider",
    "engine": "4.5L Ferrari F136F V8",
    "power": "562bhp @9000rpm",
    "torque": "540nm @6000rpm",
    "transmission": "7-speed dual clutch",
    "topSpeed": "325kph",
    "acceleration": "3.3 sec"]
}

Should i do it in my php file? Any suggestions which way should i do it? To inform you this is my php file
<?php
$json = $_POST['json'];
$info = json_encode($json, JSON_PRETTY_PRINT);

$file = fopen('cars.txt', 'a');
fwrite($file, "\n". $info);
fclose($file);
?>

and as a last question, as you can see i am using .txt file can i make it to .json file? Does it change anything? Thank you all for you attention.

A: In this case you must use also json_decode
<?php
   $json = $_POST["json"];
   $decode = json_decode($json);

   if (!$decode) {
       exit(); // invalid JSON.
   }

   $final = array(
      "cars" => $decode
   );

   file_put_contents("filename.json", json_encode($final, JSON_PRETTY_PRINT));
?>

A: What you want is probabbly this:
<?php
function read_cars_from_file_and_decode($file) {
    // write a function that reads the content of the file
    // and writes it in decoded form into $cars

    if (!$cars) {
        $cars = array('cars' => array())
    }
    return $cars
}

// depending on the structure of the json POST variable you might
// need to decode $_POST['json'] as user123123123 pointed out
$new_car = $_POST['json'];

// read existing cars from file by calling the function defined above
$file_name = 'cars.json';
$cars = read_cars_from_file_and_decode($file_name)

// append the new car to the array
$cars['car'][] = $new_car;

// write $cars to file again. This needs to be improved to make sure
// the file is completely overwritten. But I leave that to you.
// append definitly doesn't work here so I changed that already.
$info = json_encode($cars, JSON_PRETTY_PRINT);

$file = fopen($file_name, 'w');
fwrite($file, "\n". $info);
fclose($file);
?>

The $json variable is a named array with an array of cars inside. since you only send one car, we simply put the car in the array.
A .json file is essentially also a text file. So yes, you can change it to a json file.
EDIT: I edited my code sample to implement adding of the car to the existing cars in the file.


text:
Q: Run a macro with embedded Excel sheet in Access My problem is quite simple but I haven't found a solution so far...
I created a form in Access called Form1.
In this form, I inserted an "Unbound Object Frame", which is a new macro-enabled Excel worksheet.
In the Excel sheet, I create a macro we can call "ExcelMacro".
I want to know how to run macros in this Excel sheet from Access, e.g. in my Access macro, run "ExcelMacro"
I do NOT want to link my Excel sheet to an external Excel workbook.
Do you have any ideas?
Thanks a lot for your help!
Edit:
In case you need some additional information:
Name of Unbound Object Frame: xlObject
OLE Class: Microsoft Excel Macro-Enabled 12
Class: Excel.SheetMacroEnabled.12
Sheet name: Sheet1

A: You can use the following in Access:
Public Sub RunExcelMacro()
    Dim excelApp As Object
    Set excelApp = GetObject(, "Excel.Application")
    excelApp.Run "HelloWorld"
End Sub

Where "HelloWorld" is the name of the Excel Macro.
GetObject(, "Excel.Application") gets the latest opened Excel application. This needs to be the Excel application that is running your embedded worksheet. If it's another, it will fail.
Also, the worksheet needs to be open, else it will fail (you can add either of the following code segments to open it before running this).
Me.MyOLEUnbound.Verb = 0 'vbOLEPrimary
Me.MyOLEUnbound.Action = 7

or
Me.MyOLEUnbound.AutoActivate = 1 'vbOLEActivateGetFocus
Me.MyOLEUnbound.SetFocus

To make sure there are no other instances of Excel running, and possibly quit them if they are (note: these make use of runtime errors and error handlers)
Public Function IsExcelRunning() As Boolean
    IsExcelRunning = True
    On Error GoTo ReturnFalse:
    Dim obj As Object
    Set obj = GetObject(, "Excel.Application")
    Exit Function
ReturnFalse:
    IsExcelRunning = False
End Function

Public Sub CloseAllExcel()
    Dim obj As Object
    On Error GoTo ExitSub
    Dim i As Integer
    'There shouldn't be more than 10000 running Excel applications
    'Can use While True too, but small risk of infinite loop
    For i = 0 To 10000
        Set obj = GetObject(, "Excel.Application")
        obj.Quit
    Next i
ExitSub:
End Sub


text:
Q: Types to add in field from database Agile Toolkit I've discovering Agile Toolkit and I have problem with finding addField('field')->type().
What kind of types could there be and where can I find them?
I need type 'set', but addField('field')->type('set') is not working.
Thank you in advance.

A: ATK4 is distributed with simple usable basic types which is limited to the following list:

*

*string

*date

*datetime

*text

*int

*real

*boolean

*password

*list

As for the set type, the nearest would be that of a list type.
example:
 $this->addField('month')->type('list')->caption('Month')
    ->listData(array(
        1 => 'Jan',
        2 => 'Feb',
        3 => 'Mar',
        4 => 'Apr',
        5 => 'May',
        6 => 'Jun',
        7 => 'Jul',
        8 => 'Aug',
        9 => 'Sep',
       10 => 'Oct',
       11 => 'Nov',
       12 => 'Dec'));

also, there is a special treatment to boolean types in ATK4 Models and does not directly correspond to the same boolean type in MySQL which is simply equivalent to TINYINT(1).
in order to make use of a type boolean for a table field in ATK4, it has to be declared as an enum('Y','N') and prepended with an is_ on its field name.
example:
 CREATE TABLE foo (
 id INT(11) NOT NULL AUTO_INCREMENT,
 :
 is_active ENUM('Y','N') NOT NULL DEFAULT 'Y',
 :
 PRIMARY KEY (id)
 ) DEFAULT CHARSET=utf8;

with this, the MVCGrid, MVCForm and CRUD can treat the is_active as a special field and be displayed as a graphical check mark on grids and a check box button on forms.

A: The best source for types of fields that I have found is here:
ATK4 API Reference
Of course, I am less that a month into ATK4 and is a good starting point. The examples supplied with ATK4 are helpful and the Jobeet example has some good info. Dive in!


text:
Q: The error is Conversion from string "" to type 'Double' is not valid Private Sub btntambah_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btntambah.Click
    Dim n As Integer
    For n = 0 To lv1.Items.Count - 1
        If lv1.Items(n).Text = txtkdbrng.Text Then
            MsgBox("Data Buku Sudah Ada Dalam List")
            Exit Sub
        End If
    Next
    lv1.Items.Add(txtkdbrng.Text)
    lv1.Items(n).SubItems.Add(txtnmbrng.Text)
    lv1.Items(n).SubItems.Add(txtharga.Text)
    lv1.Items(n).SubItems.Add(txtjmlhhrg.Text)
    lv1.Items(n).SubItems.Add(txttotal.Text)
    lv1.Items(n).SubItems.Add(txtjmlpsn.Text)
    lv1.Items(n).SubItems.Add(txtspesifikasi.Text)
    txttotal.Text = Format(CDbl(Total()), "###, ###, ###")
    ClearBarang()
    txtkdbrng.Focus()
End Sub

Function Total() As Double
    Dim ttl As Double = 0
    If Not Double.TryParse(txttotal.Text, Total) Then
        Total = 0
    End If
End Function

Private Sub btncetak_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btncetak.Click
    If txtnosph.Text = "" Or lv1.Items.Count = 0 Then
        MsgBox("Data Belum Lengkap", MsgBoxStyle.Information, "INFORMASI")
    Else
        Dim nilaikembali1, nilaikembali2 As Integer
        objsph.PNoSph = txtnosph.Text
        objsph.PTglSph = Format(dtpsph.Value, "yyy-MM-dd")
        objsph.PKdCs = txtkdcstmr.Text
        nilaikembali1 = objsph.Simpan()
        'menyimpan ke tabel Ada menggunakan perulangan
        For x As Integer = 0 To lv1.Items.Count - 1
            objada.PNoSph = txtnosph.Text
            objada.PKdBrg = lv1.Items(x).SubItems(1).Text
            objada.PKdBrg = CDbl(lv1.Items(x).SubItems(2).Text)
            objada.PKdBrg = CDbl(lv1.Items(x).SubItems(3).Text)
            nilaikembali2 = objada.Simpan()
            Dim objbarang As New ClsBarang
            objbarang.PKdBrg = lv1.Items(x).SubItems(0).Text
        Next
        If nilaikembali1 = 1 And nilaikembali2 = 1 Then
            MsgBox("Data Berhasil Disimpan", MsgBoxStyle.Information, "INFORMASI")
        End If
        ClearForm()
        ClearBarang()
        ClearCustomer()
        txtnosph.Text = objsph.AutoNumber
    End If
End Sub

A: The problem is with this code:
Function Total() As Double
    Dim ttl As Double = 0
    If Not Double.TryParse(txttotal.Text, Total) Then
        Total = 0
    End If
End Function

First off you are using the less well known VB6 style implicit return variable that matches the name of the function, instead use the declared Double in your code named ttl and return the value, like this:
Function Total() As Double
    Dim ttl As Double = 0
    If Double.TryParse(txttotal.Text, ttl) Then
        Return ttl
    Else
        ' Attempted conversion of text to Double type failed
        ' Do something here, raise error, alert user, etc.
        ' Returning zero may or may not be acceptable, if it is return zero
        Return 0
    End If
End Function

Using the Return syntax produces much clearer code, in that it does not assume the reader of your code knows the implicit variable that matches the name of the function concept. Always use Return in a Function.
Note: If a total value of zero is not indicative of a problem, then you will need to alter your function to return Nullable(Of Double) instead of just Double and then you can alter the Else portion of the TryParse() result to this:
Function Total() As Nullable(Of Double)
    Dim ttl As Double = 0
    If Double.TryParse(txttotal.Text, ttl) Then
        Return ttl
    Else
        ' Attempted conversion of text to Double type failed
        ' So return null
        Return Nothing
    End If
End Function

Now the caller of your Total function will need to account for Nothing being returned and react accordingly.

A: This means the variable being explicitly or implicitly casted/converted to double is actually an empty string and cannot be proceed.


text:
Q: Fresh install flutter in ubuntu 18.04 wont run my first app I tried to create my first app using flutter create newapp
but it wont run i always get an error
* What went wrong:
A problem occurred evaluating project ':app'.
> com/google/common/util/concurrent/SettableFuture

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to
get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
Exception: Gradle task assembleDebug failed with exit code 1

A: I just wipe all the cache in .gradle/cache and it works


text:
Q: How can I reach distant systems When I want to travel to a system very far away from my current location, so that I can't simply reach it using the planner in the galaxy map, what is the best way to do that?
Do I have to move and rotate the galaxy map so that I can figure out what reachable star system is the closest and this way make my way to the target - that way I would never know if I can reach the system at all until I end up in a place that's too far away for a jump to the next system?

A: The route planner now(since update 1.1) will path up to 1000LY away, and you don't need to wait for it to path before selecting.
Just select the star you wish to travel to and if it is within 1000LY you can click the plan route button and it will set one up for you quickly.
The automatic route planner still takes a decently long time to build a web, though.
If the line that appears is solid you can make it there in a single tank. if the path becomes a dotted line, you will need to stop and refuel or scoop some fuel to keep going.
There are some tools people use to speed up the searching, but as with any third party app. Use at your own risk/discretion.

A: I personally never bother with the 3rd party tools.  They don't contain information about every star system in the game and there is no guarantee of accuracy of the information that they do contain.
I always do as you suggest - rotating the map around the destination so that I can see the marker for my current location (if you "lock on" to the desired destination you can use the little arrow buttons next to the destination and your current location to swap between them, giving you hints to the direction).
Once the spider web of routes has expanded out to the maximum range (currently about 100Ly), I choose a point on it that appears to be going in the correct direction.  This system is clumsy, slow, and frankly not very good, but at least it doesn't involve Alt-Tabbing out to 3rd party tools.
Soon (within this month, according to their announcements), Frontier are launching an update which among other things will extend route planning out to 1000Ly, so this should alleviate the problem.  Hopefully this range extension will not be a simple adjustment of the current route planning max distance parameter - hopefully better optimised path finding code has made this extension practical.
Personally I don't understand the need for the game to plan out every possible route from your current location.  Like the original Elite, it could simply give an indication of how far you can travel in a single jump and leave it to the player to trigger the route planning - when they select a system as the destination, no matter how far away it is, the game should then plan the route to that system.  It should be a lot faster, a lot less cluttered and a lot more useful.

A: There are a number of online third-party routing tools that you can use to find your way on long voyages.
CMDR's Club is the one that I use, although Elite Dangerous Central is another one that's fairly popular. Note that these tools may not work for distant, less-frequented star systems.

A: One technique that can help a little is as follows:

*

*Click on the target system (at whatever distance), and select it to put a marker on it.

*Zoom out until you can see both your current location (blue marker) and the destination (orange marker). Your view should still be centred on the destination.

*Zoom in slowly until your current position disappears behind your viewpoint, and hover the mouse over stars in the foreground until you find one at a little under 100Ly distance.

*Wait, if necessary, for the blue route network to reach to the star you are looking at. Ask the game for a route to this star. Repeat after 100Ly.

I've found that this method is helpful for travelling up to ~500Ly. Beyond that it may get too difficult to operate. It won't help to route around large sparse areas where you may have to backtrack for more than 100Ly.


text:
Q: How to run bootRun with spring profile via gradle task I'm trying to set up gradle to launch the bootRun process with various spring profiles enabled.
My current bootRun configuration looks like:
bootRun {
    // pass command line options from gradle to bootRun
    // usage: gradlew bootRun "-Dspring.profiles.active=local,protractor"
    if (System.properties.containsKey('spring.profiles.active')) {
        systemProperty "spring.profiles.active", System.properties['spring.profiles.active']
    }
}

I'd like to set system properties with a gradle task, and then execute bootRun.
My attempt looked like this:
task bootRunDev

bootRunDev  {
    System.setProperty("spring.profiles.active", "Dev")
}

A few questions:

*

*is systemProperty a part of the spring boot bootRun configuration?

*is it possible to set a system property in another task?

*What should my next step be? I need to get bootRunDev configuration to happen before bootRun

*Is there another approach I should look into

-Eric

A: Kotlin edition: Define the following task in you build.gradle.kts file:
tasks.named<BootRun>("bootRun") {
  args("--spring.profiles.active=dev")
}

This will pass the parameter --spring.profiles.active=dev to bootRun, where the profile name is dev in this case.
Every time you run gradle bootRun the profile dev is used.

A: Environment variables can be used to set spring properties as described in the documentation. So, to set the active profiles (spring.profiles.active) you can use the following code on Unix systems:
SPRING_PROFILES_ACTIVE=test gradle clean bootRun

And on Windows you can use:
SET SPRING_PROFILES_ACTIVE=test
gradle clean bootRun

A: In your build.gradle file simply use the following snippet
bootRun {
  args = ["--spring.profiles.active=${project.properties['profile'] ?: 'prod'}"]
}

And then run following command to use dev profile:
./gradlew bootRun -Pprofile=dev

A: Simplest way would be to define default and allow it to be overridden. I am not sure what is the use of systemProperty in this case. Simple arguments will do the job.
def profiles = 'prod'

bootRun {
  args = ["--spring.profiles.active=" + profiles]
}

To run dev:
./gradlew bootRun -Pdev

To add dependencies on your task you can do something like this:
task setDevProperties(dependsOn: bootRun) << {
  doFirst {
    System.setProperty('spring.profiles.active', profiles)
  }
}

There are lots of ways achieving this in Gradle.
Edit:
Configure separate configuration files per environment.
if (project.hasProperty('prod')) {
  apply from: 'gradle/profile_prod.gradle'
} else {
  apply from: 'gradle/profile_dev.gradle'
}

Each configuration can override tasks for example:
def profiles = 'prod'
bootRun {
  systemProperty "spring.profiles.active", activeProfile
}

Run by providing prod flag in this case just like that:
./gradlew <task> -Pprod

A: I wanted it simple just to be able to call gradle bootRunDev like you without having to do any extra typing..
This worked for me - by first configuring it the bootRun in my task and then right after it running bootRun which worked fine for me :)
task bootRunDev {
    bootRun.configure {
        systemProperty "spring.profiles.active", 'Dev'
    }
}

bootRunDev.finalizedBy bootRun

A: For anyone looking how to do this in Kotlin DSL, here's a working example for build.gradle.kts:
tasks.register("bootRunDev") {
    group = "application"
    description = "Runs this project as a Spring Boot application with the dev profile"
    doFirst {
        tasks.bootRun.configure {
            systemProperty("spring.profiles.active", "dev")
        }
    }
    finalizedBy("bootRun")
}

A: For someone from internet, there was a similar question https://stackoverflow.com/a/35848666/906265 I do provide the modified answer from it here as well:
// build.gradle
<...>

bootRun {}

// make sure bootRun is executed when this task runs
task runDev(dependsOn:bootRun) {
    // TaskExecutionGraph is populated only after
    // all the projects in the build have been evaulated https://docs.gradle.org/current/javadoc/org/gradle/api/execution/TaskExecutionGraph.html#whenReady-groovy.lang.Closure-
    gradle.taskGraph.whenReady { graph ->
        logger.lifecycle('>>> Setting spring.profiles.active to dev')
        if (graph.hasTask(runDev)) {
            // configure task before it is executed
            bootRun {
                args = ["--spring.profiles.active=dev"]
            }
        }
    }
}

<...>

then in terminal:
gradle runDev

Have used gradle 3.4.1 and spring boot 1.5.10.RELEASE

A: Configuration for 4 different task with different profiles and gradle tasks dependencies:

*

*bootRunLocal and bootRunDev - run with specific profile

*bootPostgresRunLocal and bootPostgresRunDev same as prev, but executing custom task runPostgresDocker and killPostgresDocker before/after bootRun

build.gradle:
final LOCAL='local'
final DEV='dev'

void configBootTask(Task bootTask, String profile) {
    bootTask.main = bootJar.mainClassName
    bootTask.classpath = sourceSets.main.runtimeClasspath

    bootTask.args = [ "--spring.profiles.active=$profile" ]
//    systemProperty 'spring.profiles.active', profile // this approach also may be used
    bootTask.environment = postgresLocalEnvironment
}

bootRun {
    description "Run Spring boot application with \"$LOCAL\" profile"
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootRunLocal(type: BootRun, dependsOn: 'classes') {
    description "Alias to \":${bootRun.name}\" task: ${bootRun.description}"
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootRunDev(type: BootRun, dependsOn: 'classes') {
    description "Run Spring boot application with \"$DEV\" profile"
    doFirst() {
        configBootTask(it, DEV)
    }
}

task bootPostgresRunLocal(type: BootRun) {
    description "Run Spring boot application with \"$LOCAL\" profile and re-creating DB Postgres container"
    dependsOn runPostgresDocker
    finalizedBy killPostgresDocker
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootPostgresRunDev(type: BootRun) {
    description "Run Spring boot application with \"$DEV\" profile and re-creating DB Postgres container"
    dependsOn runPostgresDocker
    finalizedBy killPostgresDocker
    doFirst() {
        configBootTask(it, DEV)
    }
}

A: For the command line as of Gradle 7.5 and Spring Boot 2.7.3, I do this (if it helps anyone):
gradle bootRun --args=--spring.profiles.active=myprofile

A: For those folks using Spring Boot 2.0+, you can use the following to setup a task that will run the app with a given set of profiles.
task bootRunDev(type: org.springframework.boot.gradle.tasks.run.BootRun, dependsOn: 'build') {
    group = 'Application'

    doFirst() {
        main = bootJar.mainClassName
        classpath = sourceSets.main.runtimeClasspath
        systemProperty 'spring.profiles.active', 'dev'
    }
}

Then you can simply run ./gradlew bootRunDev or similar from your IDE.

A: Spring Boot v2 Gradle plugin docs provide an answer:

6.1. Passing arguments to your application
Like all JavaExec tasks, arguments can be passed into bootRun from the command line using --args='<arguments>' when using Gradle 4.9 or later.

To run server with active profile set to dev:
$ ./gradlew bootRun --args='--spring.profiles.active=dev'

A: Using this shell command it will work:
SPRING_PROFILES_ACTIVE=test gradle clean bootRun

Sadly this is the simplest way I have found.
It sets environment property for that call and then runs the app.

A: Add to VM options:
-Dspring.profiles.active=dev
Or you can add it to the build.gradle file to make it work: bootRun.systemProperties = System.properties.

A: my way:
in gradle.properties:
profile=profile-dev

in build.gradle add VM options -Dspring.profiles.active:
bootRun {
   jvmArgs = ["-Dspring.output.ansi.enabled=ALWAYS","-Dspring.profiles.active="+profile]
}

this will override application spring.profiles.active option

A: Working solution for Spring Boot 2.5+
tasks.register('runDev') {
   dependsOn 'bootRun'
   bootRun.systemProperty('spring.profiles.active', 'dev')
}

and to run:
./gradlew runDev


text:
Q: DevExpress (JS / HTML) Attach Events to Elements in a Popup How do you properly attach events to elements in a popup?
This is how I currently do it:
HTML

    <input id="checkbox" type="checkbox" />

JavaScript
var userDetail = $("#userDetail").dxPopup({
    width: '550',
    height: 'auto',
    showTitle: true,
    title: "Setup Import Template",
    visible: false,
    onShown: function () {
        $('#checkbox').one('click', function () {
             $('.template-view').toggle();
        });
        $("#button-confirm").dxButton({
            onClick: function (e) {
                e.jQueryEvent.preventDefault();
                templateDataPopup.hide();
            }
        });
    }
}).dxPopup('instance');

The problem with this is that:

*

*Every time the popup is shown, the jQuery attaches new click event to #checkbox element, event after I use .one().

*#button-confirm element's click event is NOT being attached twice. This is the behavior I want (although it's not what I expected, I think because it's a DevExpress instance).

*I have tried attached events to elements in the popup before I initialized the popup, but for some reason, after the popup is shown, none of the elements' events work.

So, how do you properly attach events to elements in a popup?
Thanks!

A: I got answer from DevExpress support and the suggestion is to use contentTemplate. The reply:

Use the contentTemplate property to create popup content and add the
  required events to it:

contentTemplate: function (contentElement) {
    contentElement.append('<input id="checkbox" type="checkbox" />');
    var hideButton = $("
").dxButton({
        text: "Hide popup",
        onClick: function (e) {
            popupInstance.hide();
        }
    });
    contentElement.append(hideButton);
}

So, instead of attaching the event through onShown event, it's recommended to attach in contentTemplate.
You can also load popup content from HTML tag in contentTemplate


text:
Q: Using select2 typeahead with a url outside the web root How can I get select2 to access a url outside the web root for a db query select?
I have this:
$('#payees').select2({
    minimumInputLength: 2,
    ajax: {
      url: "/connectors/search-connector.php",
      dataType: 'json',
      data: function (term, page) {
        return {
          q: term
        };
      },
      results: function (data, page) {
        return { results: data };
      }
    }
  });

I would like /connectors/search-connector.php to be actually outside the web root [not web accessible] ~ now I know I can do this with PHP, but select2 appends a querystring to the end of the url that needs to be somehow captured and passed.
Can this be done?

A: You can't access with javascript to php files if these are outside the web root or not are accessible from a public url.
Try create first a php with public URL and this file will call the private file


text:
Q: Can I program a Raspberry Pi with Node.js? I want to learn to program Raspberry Pi's and I'm pretty good with Node.js. I haven't touched C++ in almost half a decade. I understand that I can load Linux on the Pi, but how do can I do my programming in Node?
If so, how do I handle things like input / output? If I wanted to make a simple device that detected motion and emitted a beep, for example, is this doable via Node.js on the Pi?

A: I think you need some C ported modules to control the hardware, but I don't know
if there is any.
However you can take a look at Tessel which is an embedded
development hardware specialized for JavaScript, so it's possible to run Node.js
applications on your Pi to program it.

A: Haven't used it but perhaps this is what you need:  https://npmjs.org/package/pi-gpio

A: Like Dave Swersky said in a comment, yes you can, there s a complete tutorial here:
http://blog.rueedlinger.ch/2013/03/raspberry-pi-and-nodejs-basic-setup/
I would add it work well, but you ll need to use Leafpad (if GUI) or nano to edit your code, they are good text editor, but no syntax coloration.
EDIT: For thoses who don t want to see the link, here a quick resume of it:
Creating a new directory for node:
sudo mkdir /opt/node

Get the package for Raspbian: (vX.XX.X is to be replaced by latest one)
wget http://nodejs.org/dist/vX.XX.X/node-vX.XX.X-linux-arm-pi.tar.gz
tar xvzf node-vX.XX.X-linux-arm-pi.tar.gz
sudo cp -r node-vX.XX.X-linux-arm-pi/* /opt/node

Add node.js to the PATH:
nano /etc/profile

Add this before 'export'
NODE_JS_HOME="/opt/node"
PATH="$PATH:$NODE_JS_HOME/bin"
export PATH

It is a rip off of the basic installation of node.js as explained in the link, I didn t writed it, but tested it successfully on two Raspberry.
For more information about why thoses command, and how to properly configure the RPi, go to the link, the real author deserve the credit.
EDIT 3 (Inserted before EDIT2 since more related to the question)
For the hardware io with the RPi, you can use the popular socket.io package, or some speciallized module as pi-gpio.
EDIT 2:
For nano syntax coloration, copy this in a file named js.nanorc, at ~/ for this example
Then use this command:
cp /etc/nanorc ~/.nanorc
nano ~/.nanorc

To create a user nano config file and edit it.
Read all option and uncomment those you want, I reccommend to activate:
set autoindent
set tabspace 4
set tabstospace
set whitespace " °"

So you have auto indent, and tabs are made of 4spaces, and by typing alt + P, you see all whitespace replaced by ° (only visual, they aren t replaced in the file)
Then, at the end of the file, type
include "~/js.nanorc"

So you now have coloration for javascript too.

A: On Linux systems, you can do a lot of fun stuff just by interacting with the files on the procfs, sysfs and configfs filesystems, mounted at /proc, /sys and /sys/kernel/config mountpoints, respectively.
These allow you to observe your system's status and configuration and in many cases also provide mechanisms to alter that configuration by writing specific data to files. No C/C++ native addons required - the standard fs module will be quite enough.
As an example, take a look at the ledctl library that allows you to control your LEDs simply by reading and writing data to the LEDs' configuration endpoints on the sysfs mountpoint (Disclaimer: I am the author of the module).
If you would like to interact with your custom devices using the GPIO pins available on Raspberry PI, there are plenty of native addons for Node.js that provide a nice JavaScript API to send and receive signals on particular pins.
So, to create a device that detects a motion and emits a beep, you connect the motion detector and beeper to the GPIO (most likely), take control of the pins using one of your chosen GPIO modules and start listening for incoming signals. When you receive a signal, you emit another signal to the beeper.


text:
Q: the participant/reader/writer Why in paragraph below, it is used "the participant" and "the reader" and "the writer"? Can't we write them as "A participant", "A reader", "A writer"?

Talking about "one of many" is also called "indefinite reference." We use it when the noun's exact identity is unknown to one of the participants: the reader, the writer, or both. Sometimes it's not possible for the reader or the writer to identify the noun exactly; sometimes it's not important.

Reference: http://writingcenter.unc.edu/tips-and-tools/articles/

A: We use the definite article here because we're not just talking about any participant or any reader or any writer, but the specific reader or writer involved in this exact case.
The sentence wouldn't exactly be wrong with "a", but it's more correct to say "the".


text:
Q: Apache as reverse proxy: synchronous or asynchronous? I'm using Apache to serve static content, and then reverse proxy-ing to a Rails server to process dynamic content, some of which can take a long time to generate. When Apache hands off a request to a reverse proxy, is an Apache process used up just sitting there waiting for a response (im using prefork mpm), or can it go off and process other requests, and just handle the response from the Rails server when the response is ready?

A: Using Apache Prefork MPM you will have at least one process for each concurrent request. And, each process will be serving one or zero requests (idle or spare).
So the process doing the reverse proxy to Rail, will be blocked till it gets completed (or error). Anyway, another connection can be open to the same server.


text:
Q: Using methods inside a constructor I'm new to learning Java and was trying to understand OOP, but I can't seem to find anyone who has the same exact question. My question is, is it okay to use methods inside a constructor like the example here:
package ezrab.nl;

public class Calculations {

    private int number;
    private int multiplier;

    private String operator = "";

    public Calculations(int number, String operator, int multiplier) {
        this.number = number;
        this.operator = operator;
        this.multiplier = multiplier;
        switch (getOperator()) {
        case "+":
            System.out.println(getNumber() + getMultiplier());
            break;
        case "-":
            System.out.println(getNumber() - getMultiplier());
            break;
        case "*":
            System.out.println(getNumber() * getMultiplier());
            break;
        case "/":
            System.out.println(getNumber() / getMultiplier());
            break;
        case "%":
            System.out.println(getNumber() % getMultiplier());
            break;
        default:
            System.out.println("Something went wrong.");
        }
    }

    public int getNumber() {
        return this.number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public int getMultiplier() {
        return this.multiplier;
    }

    public void setMultiplier(int multiplier) {
        this.multiplier = multiplier;
    }

    public String getOperator() {
        return this.operator;
    }

    public void setOperator(String operator) {
        this.operator = operator;
    }

}

So I'd like to know, is it allowed to use the methods I've created inside the constructor.
EDIT: I'd like to point out that the program is working. I just want to know if I followed the rules to OOP correctly.

A: Put behavior of object separately with creation:
public class Calculations {

private int number;
private int multiplier;
private String operator = "";

public Calculations(int number, String operator, int multiplier) {
    this.number = number;
    this.operator = operator;
    this.multiplier = multiplier;
}

public int getNumber() {
    return this.number;
}

public void setNumber(int number) {
    this.number = number;
}

public int getMultiplier() {
    return this.multiplier;
}

public void setMultiplier(int multiplier) {
    this.multiplier = multiplier;
}

public String getOperator() {
    return this.operator;
}

public void setOperator(String operator) {
    this.operator = operator;
}

public void print() {
     switch (getOperator()) {
    case "+":
        System.out.println(getNumber() + getMultiplier());
        break;
    case "-":
        System.out.println(getNumber() - getMultiplier());
        break;
    case "*":
        System.out.println(getNumber() * getMultiplier());
        break;
    case "/":
        System.out.println(getNumber() / getMultiplier());
        break;
    case "%":
        System.out.println(getNumber() % getMultiplier());
        break;
    default:
        System.out.println("Something went wrong.");
    }
}
}

A:
is it allowed to use the methods I've created inside the constructor.

It's allowed but dangerous as you need to know if everything which should be set, has been set. It's better to use the value which was passed as a parameter.
However your switch should be in the constructor as you can change the operator or operand later. I would have a separate method for it.
NOTE: Having a field called multiplier is confusing as it's not a multiplier in most cases.

A: Yes it's allowed but better way is to separate the behavior and construction of object. Constructors are mainly used to set properties of the class.

A: To better code in OOP (Object Oriented Programming) this concept you are referring to is known as Encapsulation. You can generally code in the way you are saying to do it. However, down the line when the application gets bigger, it would make your life much easier if you follow established design patterns. Please review this link for the Encapsulation concept:
https://www.tutorialspoint.com/java/java_encapsulation.htm


text:
Q: Find the autocovariance function of the process $Y_t$ Consider the stationary process $X_t= \rho X_{t-1} + \epsilon_t$ in which {$\epsilon_t$} is a serie of random shocks with zero mean and variance $\sigma^2_{\epsilon}$. Also, consider another serie of random shocks {$W_t$} with zero mean and variance $\sigma^2_{W}$, in a way that $E[\epsilon_t W_s] = 0 \forall s,t$. Be $Y_t = X_t + W_t$, find the autocovariance of the process $Y_t$.
—-
My work, so far was first try to prove that $Y_t$ is stationary..


text:
Q: Using column count with ul I wanted to split a unordered list in to two columns so i searched for a solution and found this:
 csswizardry.com/2010/02/mutiple-column-lists-using-one-ul/
This worked fine but on certian pages you couldn't see the bullet points so i switched to using column count to balance s simple list

test 1

test 2

test 3

test 4

test 5

test 6

test 7

test 8

test 9

like here http://jsfiddle.net/jZA4y/
The problem i am having is the on some lists the column count dosen't balance the list equally?
http://i.stack.imgur.com/oRfAF.png
What is the best way to fix this problem so that both column are equal or close as possible?

A: $(".double_column ").find("li").count();
would do your work

A: I think that the example of work and that it can help you float:left;