text:
Q: No Activity found to handle Intent (android.intent.action.VIEW) In my application am having a pdf which is to be printed by selecting the installed apps in the device. When I tried to open the application it throws "No Activity found to handle Intent". I have also added  in my manifest file but it's not helping. I have installed printshare in my emulator which used to print the pdf. Below is my code.
handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Uri uri = FileProvider.getUriForFile(InventoryPDFCreate.this,getPackageName(), pdfFile);
                                Intent intent = ShareCompat.IntentBuilder.from(InventoryPDFCreate.this)
                                        .setStream(uri) // uri from FileProvider
                                        .getIntent()
                                        .setAction(Intent.ACTION_VIEW) //Change if needed
                                        .setDataAndType(uri, "pdf/*")
                                        .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                        startActivity(intent);

                            } catch (ActivityNotFoundException e) {
                                e.printStackTrace();
                                toastMsg.showToast(InventoryPDFCreate.this, "No Application match to Open Print File"+e);
                            }
                        }
                    }, 100);

Manifest file
<queries>
        <!-- WebView -->
        <intent>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="http" />
        </intent>
        <intent>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="https" />
        </intent>

        <!-- Camera -->
        <intent>
            <action android:name="android.media.action.IMAGE_CAPTURE" />
        </intent>

        <!-- Gallery -->
        <intent>
            <action android:name="android.intent.action.GET_CONTENT" />
        </intent>
    </queries>

Am getting the below exception:
No Activity found to handle Intent { act=android.intent.action.VIEW dat=content://com.mobilesalesperson.controller/external/Android/AMSP/PrintReport/msp.pdf typ=pdf/* flg=0x80001 (has extras) }

A: The probem was that the OP was using an incorrect mime-type as the parameter. Android does not support all types of mimes but this can be checked by using MimeTypeMap.

Return the MIME type for the given extension if supported, null otherwise.

final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");


text:
Q: how to show table columns based on radio button input values? Radio button generated dynamically based on selected option. Next if a user selects a radio button, based on the radio button value, certain number of table columns need to show. Example:

*

*If a user selects radio button 3 that contain value 3 then I need to show three columns in table.

*If a user selects radio button 2 that contain value 2 then I need to show 2 columns in table.

*If user selects radio button then I need to show one column in table.

How can I do this, please help me.
I tried this code:

<input id="col1" name="radiogrp4" type="radio" class="ibm-styled-radio" value="1" ng-click="generateQuestionSection($event)"/>
col1

  <input id="col2" name="radiogrp1" type="radio" value="2" ng-click="generateQuestionSection($event)"/>
  col2

  <input id="col3" name="radiogrp1" type="radio" value="3" ng-click="generateQuestionSection($event)"/>
  col3

    <buton ng-click="showOverlay(btn.create);" style="background:#3de;padding:0px 2px;;margin:25px;">clickme</buton>

     <button ng-show="name.length > 0" ng-click='getUserDetails(name)'> {{name}}</button>

  <form>
     <input type="text" ng-model="user.name" />
     <input type="button" ng-click="sayName(user.name);" value="sayName"/>
  </form>

Script:
var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    //collection data
    $scope.data = {};
    $scope.sayName = function(data) {
        $scope.data[$scope.selected] = $scope.data[$scope.selected] || [];
        $scope.data[$scope.selected].push(data);
    };
    // get the data
    $scope.getUserDetails = function(data) {
        alert(data)
    };
    //creating buttons
    $scope.createQueBtns = [{
            "create": "createQueBtn1"
        },
        {
            "create": "createQueBtn2"
        },
        {
            "create": "createQueBtn3"
        }
    ];
    $scope.showOverlay = function(btn) {
        $scope.selected = btn;
        $scope.overlay = true;
    }
    $scope.generateQuestionSection = function(item) {
        debugger;
        var radioSelectedVal = item.currentTarget.getAttribute("value");
        $scope.radioSelectedVal = parseInt(radioSelectedVal);
    };
}

jsfiddle link:http://jsfiddle.net/wboxqqu0/10/

A: You can use ng-repeat limitto filter to achieve what you want please find below snippet for more information as well as you can find this updated fiddle
For more information about limitTo please find this documentation

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
//collection data
$scope.data = {};
$scope.sayName = function(data){
$scope.data[$scope.selected] = $scope.data[$scope.selected] || [];
$scope.data[$scope.selected].push(data);
};
// get the data
$scope.getUserDetails = function(data){
alert(data)
};
//creating buttons
$scope.createQueBtns = [
 { "create":"createQueBtn1"},
  {"create":"createQueBtn2"},
   {"create":"createQueBtn3"}
];
$scope.showOverlay = function(btn){
$scope.selected = btn;
$scope.overlay = true;
}
$scope.generateQuestionSection = function(item) {debugger;
        var radioSelectedVal = item.currentTarget.getAttribute("value");
        $scope.radioSelectedVal = parseInt(radioSelectedVal);

    };
}
.liked {
  color: green;
}
.overlay{
  box-shadow:1px 1px 10px 10px #cd4;
  padding:10px;
  magin:10px;
}
.disliked {
  color: red;
}
table tr td{
border:1px solid #ccc;padding:5px;margin:5px;
}

<input id="col1" name="radiogrp1" type="radio" class="ibm-styled-radio" value="1" ng-click="generateQuestionSection($event)"/>
col1

  <input id="col2" name="radiogrp1" type="radio" value="2" ng-click="generateQuestionSection($event)"/>
  col2

  <input id="col3" name="radiogrp1" type="radio" value="3" ng-click="generateQuestionSection($event)"/>
  col3

    <buton ng-click="showOverlay(btn.create);" style="background:#3de;padding:0px 2px;;margin:25px;">clickme</buton>

     <button ng-show="name.length > 0" ng-click='getUserDetails(name)'> {{name}}</button>

  <form>
     <input type="text" ng-model="user.name" />
     <input type="button" ng-click="sayName(user.name);" value="sayName"/>
  </form>

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the probability that the sum of six rolls of a fair die is divisible by $7$? $$P(E)=\frac{\text{Favourable outcomes}}{\text{Total outcomes}}$$
Total outcomes $=6^6$
Favourable outcomes means the sum must be $7$, $14$, $21,28$ or $35$
Assume $a_1$, $a_2$, $a_3$, $a_4$, $a_5$, $a_6$ to be the numbers on the top faces of the dice
In case of $7$ and $35$ the number of cases should be $6$ as $0<a_i<7$.
When the sum is $14$, favourable outcomes are: $${14 \choose 6}-6\left({7 \choose5}+{6 \choose 5}+1\right).$$ I tried this by a variation of beggars method. Let's assume there are $14$ coins, and $6$ beggars. There are $14$ places for the beggars to choose, such that there are $13$ places between two coins and one to the left of the first coin. Each beggar gets all the coins between himself and the beggar just to the right of him. This way we ensure that each beggar at least gets one coin. After this I subtracted the number of cases where one beggar gets more than one coin.
Now this is solvable up to this point, but I'm getting a very large equation when I do this for $21$ and $28$. Is there a better method, since I will most probably only have $5$ min in the upcoming exam on $3^d$ October.

A: The number of outcomes with sum $14$ is the number of solutions of the equation
$$a_1 + a_2 + a_3 + a_4 + a_5 + a_6 = 14 \tag{1}$$
in the positive integers subject to the restrictions that $a_i \leq 6$, $1 \leq i \leq 6$.
A particular solution Equation 1 in the positive integers corresponds to the placement of $6 - 1 = 5$ addition signs in the $13$ spaces between successive ones in a row of $14$ ones.
$$1 \square 1 \square 1 \square 1 \square 1 \square 1 \square 1 \square 1 \square 1 \square 1 \square 1 \square 1 \square 1 \square 1$$
For instance, if we select the second, fifth, seventh, tenth, and twelfth spaces, we get
$$1 1 + 1 1 1 + 1 1 + 1 1 1 + 1 1 + 1 1$$
which corresponds to the solution $a_1 = 2, a_2 = 3, a_3 = 2, a_4 = 3, a_5 = a_6 = 2$.  The number of such solutions is the number of ways we can select which $6 - 1 = 5$ of the $14 - 1 = 13$ spaces can be filled with an addition sign, which is
$$\binom{14 - 1}{6 - 1} = \binom{13}{5}$$
In general, the number of solutions of the equation
$$x_1 + x_2 + \cdots + x_k = n$$
in the positive integers is
$$\binom{n - 1}{k - 1}$$
since we must select which $k - 1$ of the $n - 1$ spaces between successive ones in a row with $n$ ones will be filled with addition signs.
From these $\binom{13}{5}$ solutions in the positive integers, we must subtract those solutions in which one or more of the variables exceeds $6$.  At most one variable can exceed $6$ since $7 + 7 + 1 + 1 + 1 + 1 = 16 > 14$.
Suppose $a_1 > 6$.  Then $a_1' = a_1 - 6$ is a positive integer.  Substituting $a_1' + 6$ for $a_1$ in equation 1 yields
\begin{align*}
a_1' + 6 + a_2 + a_3 + a_4 + a_5 + a_6 & = 14\\
a_1' + a_2 + a_3 + a_4 + a_5 + a_6 & = 8 \tag{2}
\end{align*}
Equation 2 is an equation in the positive integers with
$$\binom{8 - 1}{6 - 1} = \binom{7}{5}$$
solutions.
By symmetry, there are an equal number of cases for each $a_i$ which violates the restriction that $a_i \leq 6$.  Hence, the number of admissible solutions of Equation 1 is
$$\binom{13}{5} - \binom{6}{1}\binom{7}{5}$$
To find the number of outcomes with sum $21$, we can use the Inclusion-Exclusion Principle.  We find the number of solutions of the equation
$$a_1 + a_2 + a_3 + a_4 + a_5 + a_6 = 21 \tag{3}$$
in the positive integers subject to the restrictions that $a_i \leq 6$, $1 \leq i \leq 6$, by first counting the number of solutions of Equation 3 in the positive integers, then subtracting the number of solutions which violate at least one of the restrictions.  Note that at most two restrictions may be violated simultaneously since $7 + 7 + 7 + 1 + 1 + 1 = 24 > 21$.
If we subtract those cases which violate a restriction, we end up subtracting each case which violates two of the restrictions twice, once for each way of designating one of the violated restrictions as the restriction that has been violated.  Therefore, we must add those cases in which two of the restrictions have been violated to the difference of the total number of solutions and the number which violate one of the restrictions.

  As you should check, the number of solutions of equation 3 in the positive integers is $$\binom{21 - 1}{6 - 1} = \binom{20}{5}$$  As you should check, the number of solutions which violate one of the restrictions is $$\binom{6}{1}\binom{15 - 1}{6 - 1} = \binom{6}{1}\binom{14}{5}$$ and the number of solutions which violate two of the restrictions is $$\binom{6}{2}\binom{9 - 1}{6 - 1} = \binom{6}{2}\binom{8}{5}$$  Hence, by the Inclusion-Exclusion Principle, the number of ways to obtain a sum of $21$ with six dice is $$\binom{20}{5} - \binom{6}{1}\binom{14}{5} + \binom{6}{2}\binom{8}{5}$$

The Inclusion-Exclusion Principle can also be used to solve for the number of solutions of the equation
$$a_1 + a_2 + a_3 + a_4 + a_5 + a_6 = 28 \tag{4}$$
in the positive integers subject to the restrictions that $a_i \leq 6$, $1 \leq i \leq 6$.  However, we can use symmetry to avoid that calculation.
Notice that if $1 \leq a_i \leq 6$, then $b_i = 7 - a_i$ also satisfies the condition that $1 \leq b_i \leq 6$.  Substituting $7 - b_i$ for $a_i$, $1 \leq i \leq 6$, in Equation 4 yields
\begin{align*}
7 - b_1 + 7 - b_2 + 7 - b_3 + 7 - b_4 + 7 - b_5 + 7 - b_6 & = 28\\
-b_1 - b_2 - b_3 - b_4 - b_5 - b_6 & = -14\\
b_1 + b_2 + b_3 + b_4 + b_5 + b_6 & = 14 \tag{5}
\end{align*}
However, we already calculated the number of solutions of Equation 5 that satisfy the restrictions $b_i \leq 6$, $1 \leq i \leq 6$ above.
More generally, by symmetry the number of solutions of the equation
$$a_1 + a_2 + a_3 + a_4 + a_5 + a_6 = S \tag{6}$$
in the positive integers subject to the restrictions that $a_i \leq 6$, $1 \leq i \leq 6$, is equal to the number of solutions of the equation
$$b_1 + b_2 + b_3 + b_4 + b_5 + b_6 = 42 - S \tag{7}$$
in the positive integers subject to the restrictions that $b_i \leq 6$, $1 \leq i \leq 6$, which is why you obtained the same number of solutions for the sums $7$ and $35$.

A: For a second way , you can use generating functions. Lets say that the numbers appears in throwing represented by $x_1,x_2,x_3,x_4,x_5,x_6$. So , we are looking for $7,14,21,28,35$ as the summation.
Then ,we can say that we are looking for the coefficents for $[x^n]$ where $n$ is $7,14,21,28,35$ , respectively.
It can be seen that the generating function of $x_1,...,x_6$ are the same and it is equal to $$\bigg(x\times \frac{1-x^6}{1-x}=\frac{x -x^7}{1-x}\bigg)$$
Then , as all of the generating functions are equal

*

*Find   $$[x^7] \bigg(\frac{x -x^7}{1-x}\bigg)^6$$

*Find   $$[x^{14}] \bigg(\frac{x -x^7}{1-x}\bigg)^6$$

*Find   $$[x^{21}] \bigg(\frac{x -x^7}{1-x}\bigg)^6$$

*Find   $$[x^{28}] \bigg(\frac{x -x^7}{1-x}\bigg)^6$$

*Find   $$[x^{35}] \bigg(\frac{x -x^7}{1-x}\bigg)^6$$
We stoped at $35$ because it is the maximum value of summation that divided by $7$
CALCULATION VIA WOLFRAM-ALPHA
Then , $$\frac{[x^7]+[x^{14}]+[x^{21}]+[x^{28}] +[x^{35}]}{6^6}=\frac{6+1161+4332+1161+6}{6^6}= \frac{6666}{46656}=0,1428755...$$

A: You can encapsulate the stars-and-bars cum inclusion-exclusion for a desired sum $s$ rolling a six-sided die six times, using the formula
$$\text{Number of ways}\;W(s) = \sum_{i=0}^{\lfloor\frac{s-6}{6}\rfloor}(-1)^i\binom{6}{i}\binom{s-1-6i}5$$


text:
Q: mocha test with redis sinon stub throwing uncaught error outside suite I'm having trouble getting Sinon to mock redis correctly for unit testing. The test cases are passing but Mocha is still crashing with a redis connection error every time, and I can't get to the bottom of it. After several days of working on this and combing through Stackoverflow I still haven't been able to solve it, so it's time to ask better minds than mine.
I started with a server.ts file that will export the app, so it can be loaded for final runtime configuration externally or loaded into a test suite:
import express, { Application } from "express";
import bodyParser from "body-parser";
import auth from "./routes/authRoutes";

const createServer = () => {
  const app: Application = express();

  app.use(bodyParser.json());

  app.get("/", (_req, res: Response, _next) => {
    res.json({
      message: "Hello World",
    });
  });

  app.use("/auth", auth);

  return app;
};

export default createServer;

The authRoutes.ts file is fairly simple and I merged the validation middleware and endpoint logic for brevity:
import { Router, Request, Response, NextFunction } from "express";
import { check, validationResult } from "express-validator";
import redisCache from "../data/redis-cache";

const router = Router();

const postAuth = async (req: Request, res: Response, _next: NextFunction) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json(errors.array());
  }
  const sessionId = Math.random().toString();
  await redisCache.setAsync(sessionId, "session1");
  return res.status(200).json({ sessionId: sessionId });
};

router.post(
  "/login",
  [
    check("body").exists().withMessage("No Post Body"),
  ],
  postAuth
);

export default router;

I also set up a redis-cache.ts file to promisify and export just the redis functions that I need:
import redis from "redis";

import { promisify } from "util";

const client = redis.createClient({
  host: process.env.REDIS_HOST || "localhost",
  port: process.env.REDIS_PORT ? +process.env.REDIS_PORT : 6379,
});

const getAsync = promisify(client.get).bind(client);
const setAsync = promisify(client.set).bind(client);

export default {
  getAsync,
  setAsync,
};

The test suite index.spec.ts is simple and sets up 3 tests:
import chai, { expect } from "chai";
import chaiHttp from "chai-http";
import * as sinon from "sinon";
import createServer from "../src/server";
import redis from "redis";

chai.use(chaiHttp);
chai.should();

describe("auth routes", function () {
  const mock = sinon.createSandbox();

  before(function () {
    mock.stub(redis, "createClient").returns({
      set: (key: string, value: string, cb: (e: Error | null) => void) => {
        console.log(`mocked set, request: ${key} -> ${value}`);
        return cb(null);
      },
      get: (key: string, cb: (e: Error | null) => void) => {
        console.log(`mocked get, request: ${key} `);
        return cb(null);
      },
      quit: (_cb: () => void) => {
        console.log(`mocked quit method`);
      },
    } as any);
  });

  after(function () {
    mock.restore();
  });

  describe("#GET/login", function () {
    it("responds with 404", function (done) {
      const app = createServer();
      chai
        .request(app)
        .get("/auth/login")
        .end((err: any, res: any) => {
          expect(err).to.be.null;
          expect(res.status).to.equal(404);
          done();
        });
    });
  });

  describe("#POST/login", function () {
    const app = createServer();
    function requestSend() {
      return chai.request(app).post("/auth/login");
    }

    describe("without body", function () {
      it("responds with 422", function (done) {
        requestSend().end(function (err: any, res: any) {
          if (err) return done(err);
          expect(res.status).to.equal(422);
          done();
        });
      });

      it("returns error when no post body sent", function (done) {
        requestSend().end(function (err: any, res: any) {
          if (err) return done(err);
          expect(res.body).to.be.a("array");
          const body = res.body as { msg: string }[];
          const messageIndex = body.findIndex(
            (el) => el.msg === "No Post Body"
          );
          expect(messageIndex).to.not.equal(-1);
          done();
        });
      });
    });
  });
});

Now I run the tests with Mocha and get the following:
auth routes
    Uncaught error outside test suite
    #GET/login
      ✔ responds with 404
    #POST/login
      without body
        ✔ responds with 422 (45ms)
        ✔ returns error when no post body sent

  3 passing (217ms)
  1 failing

  1) auth routes
       Uncaught error outside test suite:
     Uncaught Redis connection to localhost:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
  Error: connect ECONNREFUSED 127.0.0.1:6379

As you can see, all the tests are passing but redis is still trying to connect outside of the test suite, and I can't figure out how to get around it. If I comment out the call to await redisCache.setAsync in my authRoutes.ts file and run the tests, all green and no errors.
I've spent hours googling and trying things with no luck and I'm pretty sure I'm missing something but I can't find it. Any help would be appreciated.
I followed this blog post to create a similar setup and it works, which leads me to believe this can be done and the error is on my part.

A: I was able to answer my own question with this one (finally!) It appears that I needed to scope the creation of the redis client per request and make sure it quit in the callback when the request finished. I borrowed from the blog post above and rebuilt the redis-cache.ts file to turn the redis calls into promises another way. My new redis-cache.ts looks like this:
import * as redis from "redis";
import {
  SuccessfulSetResponse,
  FailResponse,
  SuccessfulGetResponse,
} from "../types";

const url = `${process.env.REDIS_HOST || "localhost"}:${
  process.env.REDIS_PORT ? +process.env.REDIS_PORT : 6379
}`;

const getAsync = async (
  key: string
): Promise<SuccessfulGetResponse | FailResponse> => {
  return new Promise((resolve, _reject) => {
    const client = redis.createClient({ url });

    client.get(key, (error, value) => {
      // note the client quits in the callback
      client.quit();

      if (error) {
        resolve({
          reason: error.message,
          ...error,
        } as FailResponse);
      }
      if (value === null) {
        resolve({
          success: false,
        } as SuccessfulGetResponse);
      }

      resolve({
        success: true,
        value: value,
      } as SuccessfulGetResponse);
    });
  });
};

const setAsync = async (
  key: string,
  value: string
): Promise<SuccessfulSetResponse | FailResponse> => {
  return new Promise((resolve, _reject) => {
    const client = redis.createClient({ url });

    client.set(key, value, (error) => {
      // note the client quits in the callback
      client.quit();

      if (error) {
        resolve({
          reason: error.message,
          ...error,
        } as FailResponse);
      }

      resolve({
        success: true,
      } as SuccessfulSetResponse);
    });
  });
};

export default {
  getAsync,
  setAsync,
};

I also added a few type definitions the src/types.d.ts file:
export interface SuccessfulSetResponse {
  success: boolean;
}

export interface SuccessfulGetResponse {
  success: boolean;
  value?: string;
}

export interface FailResponse {
  reason: string;
  [key: string]: string;
}

With these changes, I just had to chase a couple places where this is used (in an auth middleware for caching session tokens is the only thing so far) and all tests are green, and running the app manually and using postman also works as expected.
I would still love to know exactly what is going on, please comment if anybody knows and / or edit this answer to provide insight as to why this worked this way.


text:
Q: How can I find CRLB for an integer valued Maximum Likelihood Estimator? Reference: How to find Maximum Likelihood estimates of an *integer* parameter?
Extending the above question, how to find the Fisher information and hence CRLB for the integer-valued Estimator using second forward difference operator.


text:
Q: use two ASIHTTPRequest in the same class if i use ASIHTTPRequest the first time , with asynchroun mode , i recive result and error in

*

*(void)requestFinished:(ASIHTTPRequest *)request
  and the error in

*(void)requestFailed:(ASIHTTPRequest *)request

but what if I make another query asynchronously? I will receive the result in the same method? how to know if this is the result of the first query or second? I tryed to change the delegate but it don't work
-(void)getCities
{
    NSString * myURLString = [NSString stringWithFormat:@"http://localhost:8080/Data/resources/converter.city/CountryCode/%@",choosedCodeCity];

    NSURL *url =[NSURL URLWithString:myURLString];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:resultCities];
    [request startAsynchronous];

}

-(void)resultCities :(ASIHTTPRequest *)request
{

}

A: ASIHttpRequest has a NSDictionary* userInfo property that you can use to store whatever you like.  You can simply add a flag to this dictionary in order to tell the two requests apart.
Another approach would be to use the ASIHttpRequest methods that take blocks instead of using a delegate.
EDIT:
To use the flag approach, when you create the request object, do something like
[request.userInfo setObject:[NSNumber numberWithInt:1] forKey:@"flag"];

Then in the response methods you can ask the request for the flag to determine which request it is.
int flag = [[request.userInfo objectForKey:@"flag"] intValue];

A: you can do:
request.didFinishSelector = @selector(yourFinishMethodHere:);
request.didFailSelector = @selector(yourFailMethodHere:);

in other words, you do not have to use the default "requestFinished:" and "requestFailed:" methods on the delegate.


text:
Q: Show that the $G_f$ of $f$ is connected on $\mathbb{R}^2$. Let $f: [a, b] \rightarrow \mathbb{R}$ be a continuous function. Define the graph of $f$ as $G_f:= \{(x, f (x)) \in \mathbb{R}^2: x \in [a,b]\}$. Show that the $G_f$ of $f$ is connected on $\mathbb{R}^2$.
Let's define $F: [a, b] \rightarrow \mathbb{R}^2$ such as $F(x):= (x, f(x)); \forall x \in [a,b]$.
I already proof that $F$ is continuous in $[a, b]$.
How [a,b] is compact on $\mathbb{R}$, I know that the $F([a,b])=G_f$ is compact.

A: Consider $g: [a,b] \to G_f$ given by $g(x) = (x, f(x)).$ Show that $g$ is continuous, then assume $A \cup B = G_f$ for non-empty open sets $A, B.$ Do you see what to do next?


text:
Q: Symfony rendering form only in first row of collection perhaps somebody can help me because I'm digging forums and documentation since a week how to render a table where I have a form in 3rd column.
I have a class CollectionController with following snippet:
return $this->render(
        'vollmachtapp/pages/collections/list2.html.twig',
        [
            'attachmentForm' => $attachmentForm->createView(),
            'list' => $apiClient->listAllVollmachten()
        ]
    );

The attachmentForm looks like this:
$attachmentForm = $this->createForm( SimpleAttachmentType::class, $attachment );

Here is my SimpleAttachmentType:
class SimpleAttachmentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $builder
        ->add('file', FileType::class)
        ->add('vollmachtId', HiddenType::class)
        ->add('save', SubmitType::class, ['label' => 'Vollmacht hochladen']);
  }
}

Now I'm using a twig which looks like:

                        Vollmacht ID
                        Users
                        Upload/Download

                        {% for collection in list.items %}

                                {{ collection.id }}

                                    {% for user in collection.users %}

                                            {{ user.name }}

                                    {% endfor %}

                                    <button type="button" class="btn btn-sm btn-primary">Download Vollmacht</button>
                                    {% if(app.user.role == "admin") %}

                                        {{ form_start(attachmentForm, {method: 'POST'}) }}
                                            {% if not attachmentForm.vars.valid %}

                                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                                                    {{ form_errors(attachmentForm.file) }}

                                            {% endif %}
                                            {{ form_widget(attachmentForm.vollmachtId, {'name': vollmachtId, 'value': collection.id}) }}
                                            {{ form_widget(attachmentForm.file) }}

                                            {{ form_widget(attachmentForm.save, {attr: {'class': 'btn-left btn btn-sm btn-primary'}}) }}
                                        {{ form_end(attachmentForm) }}

                                    {% endif %}

                        {% endfor %}

The problem I have, the form is only rendered in the 1st row of the table. Can anybody tell me what I'm doing wrong and have to change to get it work?
Thanks and best regards,
Michael Obster

A: Your Main Problem is, that you cant seperate this form_snippet multiple times
{{ form_start(attachmentForm, {method: 'POST'}) }}

Your form Start and form End have to be wrapping the hole form. if your want that form also in all  tags you cant write the start form twig snippet only in one . You have to write some code like that:

                    Vollmacht ID
                    Users
                    Upload/Download

                        {% for collection in list.items %}

                                {{ form_start(attachmentForm, {method: 'POST'}) }}
                                {{ collection.id }}

                                    {% for user in collection.users %}

                                            {{ user.name }}

                                    {% endfor %}

                                    <button type="button" class="btn btn-sm btn-primary">Download Vollmacht</button>
                                    {% if(app.user.role == "admin") %}

                                            {% if not attachmentForm.vars.valid %}

                                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
                                                    {{ form_errors(attachmentForm.file) }}

                                            {% endif %}
                                            {{ form_widget(attachmentForm.vollmachtId, {'name': vollmachtId, 'value': collection.id}) }}
                                            {{ form_widget(attachmentForm.file) }}

                                            {{ form_widget(attachmentForm.save, {attr: {'class': 'btn-left btn btn-sm btn-primary'}}) }}

                                    {% endif %}

                                {{ form_end(attachmentForm) }}

                        {% endfor %}

But maybe its reconstruct your HTML markup a lil bit.

A: You should take a look at how to work with a collection of forms in symfony Documentation :
https://symfony.com/doc/current/reference/forms/types/collection.html


text:
Q: Spring Profiles application properties order We have many environments that have multiple active Spring profiles, but what is the precedence of the application-{profile}.yml files?
If I have spring.profiles.active=test-us-west-2-p1, test-us-west-2, test
In what order do the files application-test.yml, application-test-us-west-2.yml, application-test-us-west-2-p1.yml get loaded?  If I have the same property in each file, which "wins"?
Also, has this changed from Spring-Boot 1.5.x to 2.x?  It seems like it may have.

A: The profile's properties are loaded in the same order as you specify them, and if the same property is defined in different profiles the last one wins.
This behavior applies to both Spring Boot versions 1.5.x and 2.x, and if I recall correctly, it applies to all versions of Spring.
Spring always loads appication.yml. And afterwards, if some profile is specified, it will load that profile's property file. And if after that profile another profile is specified, it will load that profile's propperty file. Always overriding current properties's value with the new one.
So, let's say you have profile1 and profile2. And you have these property files:
application.yml:
property1: bob
property2: alice
property3: eve

application-profile1.yml:
property2: alice1
property3: eve1

application-profile2.yml:
property3: eve2

And you start your application with: spring.profiles.active=profile1, profile2
Your will get:
property1: bob
property2: alice1
property3: eve2

A: First of all, we need to find out the final set of all active profiles. There are ways of setting/replacing active profiles and adding active profiles on top of existing active ones. For instance, active profiles set with the spring.profiles.active property are replaced with the -Dspring.profiles.active command line option. (And this can get really complex.)
On the other hand, the SpringApplicationBuilder's profiles method adds to the existing active profiles. We can use the following code to figure out the final set of active profiles:
@Autowired
private Environment environment;

...

System.out.println("Active profiles: " +
        Arrays.toString(environment.getActiveProfiles()));

Now we have to consider what Spring documentation calls last-wins strategy.

If several profiles are specified, a last-wins strategy applies.

So, if we have the following code and all other options excluded:
new SpringApplicationBuilder(Application.class)
        .profiles("dev", "prod")
        .run(args);

both application-dev.properties and application-prod.properties files are loaded and the keys with the same name in the latter one (the production) override the former one.

A: I posted important notice on profiles order handling. See how jar resources files are handled in this process here.


text:
Q: MySQL Restoring data from .dat file I deleted my database and customer service sent me back a .dat file but their instructions what to do with it were bad.
They said to put the (db_backup.dat) file in mysql/data folder and then do an export to sql to restore data. Can anyone help out here how to do this the file is not a text file with sql commands in it just lots of things that are not readable.

A: I'm assuming the .dat file is a text file.
mysql -u root -p password < db_backup.dat

A: Looks like they could've sent you bare data file, which you should put into mysql folder and restart mysql server.
In case they sent you bare DB file, you should ask customer service which format is that. It could be a MyISAM or InnoDB file. In case they tell you format you should crate a new database of that format titled db_backup, then find where you mySQL instance keep files, stop server, put the file you get from CS into that folder, replacing existing one and start server again.
Finally, can you post few first lines of the file or screenshot from Notepad++ ?
P.S. All above are guesses until you post head of the file or which format it is.


text:
Q: java.lang.ExceptionInInitializerError error when parsing json For this class
case class AnswerOfAPracticeQuestion (question_id: UUID,
                                      image: Option[List[String]],
                                      notes: Option[String],
                                      answer:List[AnswerSection],
                                      answer_id:Option[UUID],
                                      answeredBy: Option[Answerer],
                                      creationYear:Option[Long],
                                      creationMonth:Option[Long],
                                     ){
}

the Reads method fails when I send this json to it
{
   "new-answer":{
      "images":[
         "image 1",
         "image 2"
      ],
      "notes":"some notes",
      "answer":[
         {
            "filename":"f1",
            "answer":"a1"
         },
         {
            "filename":"f2",
            "answer":"a2"
         }
      ],
      "answer-id":"11111111-1111-1111-1111-111111111112",
      "question-id":"11111111-1111-1111-1111-111111111111",
      "creator-id":"11111111-1111-1111-1111-111111111113"
   }
}

Reads method is
  implicit val answerOfAPracticeQuestionReads: Reads[AnswerOfAPracticeQuestion] = (
      (JsPath \ "question-id").read[UUID] and
      (JsPath \ "images").readNullable[List[String]] and
      (JsPath \ "notes").readNullable[String] and
      (JsPath \ "answer").read[List[AnswerSection]] and //FAILS FOR THIS LINE
      (JsPath \ "answer-id").readNullable[UUID] and
      (JsPath \ "answerer").readNullable[Answerer] and
      (JsPath \ "creation-year").readNullable[Long] and //year/month are for internal consumption so not worried about receiving it from a client
      (JsPath \ "creation-month").readNullable[Long]
    )(AnswerOfAPracticeQuestion.apply _)

Reads for AnswerSection is
implicit val answerSectionReads:Reads[AnswerSection] = (
    (JsPath \ "filename").read[String] and
      (JsPath \ "answer").read[String]
    )(AnswerSection.apply _)

The error is
java.lang.ExceptionInInitializerError
    at models.AnswerImplicits$.<init>(Answers.scala:92)
    at models.AnswerImplicits$.<clinit>(Answers.scala)
    at models.AnswerImplicits$AnswerAPIReads$.reads(Answers.scala:108)
    at play.api.libs.json.ConstraintReads.$anonfun$optionWithNull$1(JsConstraints.scala:110)
    at play.api.libs.json.Reads$$anon$8.reads(Reads.scala:132)
    at play.api.libs.json.JsLookupResult.validateOpt(JsLookup.scala:164)
    at play.api.libs.json.JsLookupResult.validateOpt$(JsLookup.scala:162)
    at play.api.libs.json.JsDefined.validateOpt(JsLookup.scala:176)
    at play.api.libs.json.JsValue.validateOpt(JsValue.scala:20)
    at play.api.libs.json.JsValue.validateOpt$(JsValue.scala:19)
    at play.api.libs.json.JsObject.validateOpt(JsValue.scala:124)
    at controllers.AnswerController.$anonfun$newAnswer$1(AnswerController.scala:399)
    at com.mohiva.play.silhouette.api.actions.SecuredActionBuilder.$anonfun$invokeBlock$8(SecuredAction.scala:216)
    at com.mohiva.play.silhouette.api.actions.SecuredRequestHandlerBuilder.$anonfun$invokeBlock$2(SecuredAction.scala:93)
    at com.mohiva.play.silhouette.api.RequestHandlerBuilder.handleInitializedAuthenticator(RequestHandler.scala:169)
    at com.mohiva.play.silhouette.api.RequestHandlerBuilder.handleBlock(RequestHandler.scala:119)
    at com.mohiva.play.silhouette.api.RequestHandlerBuilder.handleBlock$(RequestHandler.scala:117)
    at com.mohiva.play.silhouette.api.actions.SecuredRequestHandlerBuilder.handleBlock(SecuredAction.scala:52)
    at com.mohiva.play.silhouette.api.actions.SecuredRequestHandlerBuilder.$anonfun$invokeBlock$1(SecuredAction.scala:93)
    at scala.concurrent.Future.$anonfun$flatMap$1(Future.scala:302)
    at scala.concurrent.impl.Promise.$anonfun$transformWith$1(Promise.scala:37)
    at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)
    at scala.concurrent.impl.ExecutionContextImpl$AdaptedForkJoinTask.exec(ExecutionContextImpl.scala:140)
    at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
    at java.util.concurrent.ForkJoinPool$WorkQueue.pollAndExecAll(ForkJoinPool.java:1021)
    at java.util.concurrent.ForkJoinPool$WorkQueue.execLocalTasks(ForkJoinPool.java:1046)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1058)
    at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
    at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Caused by: scala.UninitializedFieldError: Uninitialized field: C:\Users\manuc\Documents\manu\codingjedi\code_related\code\frontend\web\app\models\Answers.scala: 196
    at models.AnswerImplicits$.answerOfAPracticeQuestionWrites(Answers.scala:196)
    at models.PracticeQuestionImplicits$.<init>(PracticeQuestion.scala:139)
    at models.PracticeQuestionImplicits$.<clinit>(PracticeQuestion.scala)
    ... 29 more

Futures timed out after [5000 milliseconds]
java.util.concurrent.TimeoutException: Futures timed out after [5000 milliseconds]
...

If I compare the implicit methods, in the pics below, you'll notice that the reads, there is an additional canBuildForm while there is nothing like it in writes
Reads

Writes


text:
Q: Proving there exists $V$ so that $\{x_0\}\times I\subset V\times I\subset U$ Let $X$ be a topological space, and $I=[0,1]$. Consider $X \times I$ with the product topology. Now fix $x_0\in X$ and $U\subset X\times I$ an open that contains $\{x_0\}\times I$. Prove that there exists an open $V\subset X$ so that $\{x_0\}\times I\subset V\times I\subset U$
My attempt:
Since U is an open set in the product topology, $U=\bigcup( U_{x_0}\times I_i)$ where $I_i$ are open sets of I and $U_{x_0}$ is an open set of $X$ that contains $x_0$. Since I is compact $W$ is the finite union $W=\bigcup( U_{x_0}\times I_i)\subset U$.
Now I would need to find a subset of $U_{x_0}$ that also contained $x_0$, how?

A: We suppose here that the topology used on $I$ is the stadard one
As $U$ is an open that contains $\{x_0\}\times I$, for all $i \in I$, there is an open $U_i \subseteq X$ that contains $x_0$ and an open $J_i \subseteq [0,1]$ that contains $i$ such that $(x_0,i) \in U_i \times J_i$.
$\mathcal J = \{J_i \mid i \in I\}$ is an open cover of $I$. Using the introduction remark, $I$ is compact and we can extract from $\mathcal J$ a finite subcover $\{J_{i_1}, \dots ,J_{i_n}\}$.
$V=\cap_{j=1}^n U_{i_j}$ is an open subset of $X$ that satisfies the conditions we're looking for.


text:
Q: Some Woocommerce scheduled actions are not running I noticed that in Woocommerce -> Status -> Scheduled Actions a bunch of tasks were created related to the new orders and left as Pending. The task is called wc-admin_import_orders and has an argument like 0 => xxx (the xxx is the order id).
As a consequence of this issue, the data about the costumers from the Woocommerce -> Customers does not get updated.
I can run them manually, but I would like it to happen automatically, as it is supposed to. What could be the issue?
I am running Wordpress in a Docker container on my local machine.


text:
Q: Two linearLayout inside relative layout in order to show each content in new line i'm trying to show each content ( imageview and text view ) in new line but i coudn't succeed.
i'm doing that programmatically , here is my code.
RelativeLayout grp=new RelativeLayout(this);
            grp.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));

            grp.setPadding(10, 10, 10, 10);

            TextView test=new TextView(this);
            test.setPadding(15, 15, 15, 15);
            test.setText(Html.fromHtml("
text here
"));
            LinearLayout ln=new LinearLayout(this);
            ImageView img=new ImageView(this);
            img.setImageResource(R.drawable.imageA);
            img.setFadingEdgeLength(10);
            ln.addView(img);

            ln.addView(test);
            ln.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT));

            LinearLayout ln0=new LinearLayout(this);
            grp.addView(ln);

            TextView test1=new TextView(this);
            test1.setPadding(15, 15, 15, 15);
            test1.setText(Html.fromHtml("
text here
"));
            LinearLayout ln1=new LinearLayout(this);
            ImageView img1=new ImageView(this);
            img1.setImageResource(R.drawable.imageB);
            img1.setFadingEdgeLength(10);
            ln1.addView(img1);
            //ln1.setPadding(10, 10, 10, 10);
            ln1.addView(test1);
            ln1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT));

            grp.addView(ln1);

            setContentView(grp);

what sould i do ?

A: Use LinearLayout instead of RelativeLayout and set the linearlayout's orientation to vertical with setOrientation(LinearLayout.VERTICAL);


text: Q: Why is frame dragging possible for perfectly spherical spinning blackhole? Even factoring the bulging as it spin very fast, I imagine no fluctuations in the density of gravitons emitting along the equator so how can frame dragging occurs? I know a gravitational wave depends on mass and frame dragging depends on spin instead, does it means the faster a black hole spins the event horizon actually shrinks and so frame dragging occurs?


text:
Q: Why am I getting " java.net.ConnectException: Connection refused: connect"? I am trying to make a simple socket to my loopback address -
Socket socket = new Socket("127.0.0.1", 4424);

when i get this exception. How do i resolve it?

A: Have you a socket server listening on port 4424?
You are creating a socket client. It can communicate only with a running socket server on the same port.
If you like you can create a server in java using the ServerSocket class.

A: Your socket server is not listening to localhost.Make sure that u have socket server on ur machine nd if not please download it .


text:
Q: Clearing a single cookie with a set value for ALL users on a domain So I finally got this fantastic cookie script working for my site www.dynamicdrive.com/forums/showthread.php?69591-Looking-for-a-quot-do-not-show-this-page-again-quot-checkbox-script :
// Skip this Page Script (c)2012 John Davenport Scheuer
        // as first seen in http://www.dynamicdrive.com/forums/
        // username: jscheuer1 - This Notice Must Remain for Legal Use
        ;(function(setting){
            var cook = {
                set: function(n, v, d){ // cook.set takes (name, value, optional_persist_days) - defaults to session if no days specified
                    if(d){var dt = new Date();
                        dt.setDate(dt.getDate() + d);
                    d = '; expires=' + dt.toGMTString();}
                    document.cookie = n + '=' + escape(v) + (d || '') + '; path=/';
                },
                get: function(n){ // cook.get takes (name)
                    var c = document.cookie.match('(^|;)\x20*' + n + '=([^;]*)');
                    return c? unescape(c[2]) : null;
                }
            };
            if(cook.get('skipthispage')){
                //Hide element when cookie exists
            }
            else {
                //Show element when cookie does not exist
            }
            if(!document.cookie){cook.set('temp', 1);}
            if(document.cookie){
                jQuery(function($){
                    $('#optout').css({display: ''}).append(setting.optoutHTML).find('input').click(function(){
                        this.checked? cook.set('skipthispage', '1', setting.days) : cook.set('skipthispage', '', -1);
                        this.checked && setting.gowhenchecked && location.replace(setting.page);
                    });
                });
            }
        })({
            days: 1, // days cookie will persist
            page: '',
            gowhenchecked: true, // true/false - should page switch when the box is checked?
            optoutHTML: '<label for="optoutcheckbox">Don\'t show this again: <input type="checkbox" id="optoutcheckbox" value=""></label>'
        });

However;
I am using this to hide a splash page that pops up when people initially visit my site, and it gives them the option to hide this splash page using a 1day long cookie.
This splash page contains information about the site I'm working on, and it's ever changing. So I need a quick and efficient way of clearing all cookies whenever the information changes.
So what I need is a button that I can click in my ACP, that clears these cookies and once again displays the splash page for people visiting my site.
I've been trying to get this to work using a lot of different methods, but none seem to work.
Thanks to jscheuer1 for this lovely script.
Regards,
Fredric T

EDIT:
I should add: the ACP is located in a subdirectory from where the script is.
http://example.com/index.php // This is where the script is loaded
http://example.com/admin/index.php // This is where I need the button to be.
If the above is not possible, I guess I can use PHP to only allow display if the session user is set as an admin. But I would like to avoid this.

A: Solved this by generating a 64 byte string in my database, to replace the old value whenever changes are made, which I want people to be able to see.
Bound that to a string and inserted it into the Javascript.


text:
Q: Laravel Binary String Issue When DB:raw and Pluck() or toArray() So when i use retrieve an object using get, i got a normal result
Code:
Contact::select(\DB::raw("CONCAT(COALESCE(`name`,''),' ',COALESCE(`last_name`,'')) AS display_name"),'id','name','last_name')->where('id',2382)->get()

Result:
[
        "display_name" => "OFNA • CASA "
        "id" => 2382
        "name" => "OFNA • CASA"
        "last_name" => null
      ]

but if i do a ->pluck() or ->toArray() i got this result:
[
    "display_name" => b"Ofna €¢ Casa "
    "id" => 2382
    "name" => "OFNA • CASA"
    "last_name" => null
  ]

For some reason the display_name is encoding incorrectly when converting to an Array. is there a way to fix this? or is a Laravel issue?
Thanks
My Laravel version is 6.8

A: I made a workaround, but im sure there should be a fix to this issue
This is my work around, map the get and then use the pluck on the collection after the map
                 get()->
                 map(function($object){
                    return [
                        'name'=>$object->name.' '.$object->last_name,
                        'id'=>$object->id
                    ];
                })->pluck('name','id');

It does work but im sure there should be a better way or maybe report it to Laravel.
Hope someone knows better about this.
THanks


text:
Q: Why I'm getting recyclerview's item position as "-1"? I'm having a very strange error . Basically I'm trying to delete recyclerview items on LongClick but in some cases I'm getting adapter position as -1.
My Code:
 @Override
 public void onBindViewHolder(ViewHolder holder, int position) {

 Message message = mMessages.get(position);
 holder.setMessage(message.getMessage());

  holder.msgContainer.setOnLongClickListener(view -> {
  int position = holder.getAdapterPosition();

  mMessages.remove(position);
 notifyItemRemoved(position);
 notifyItemRangeChanged(position, mMessages.size());

    return false;
   });

 }

 }
  }

A: From the docs: RecyclerView does not handle any adapter updates until the next layout traversal. This may create temporary inconsistencies between what user sees on the screen and what adapter contents have.
This is a common issue, just wrap your call in an if statement checking if the position isn't -1.
if (getAdapterPosition() != - 1)

A: getAdapterPosition() return -1.It means Adapter gets a NO_POSITION,and it always happened when you call method like notifyDataSetChanged(). we always use position like this
@Override
 public void onBindViewHolder(ViewHolder holder, final int position) {

  Message message = mMessages.get(position);
  holder.setMessage(message.getMessage());

  holder.msgContainer.setOnLongClickListener(view -> {
 //you can use the position  parameter directly,just set it as final
  mMessages.remove(position);
  notifyItemRemoved(position);
  notifyItemRangeChanged(position, mMessages.size());
     return false;
   });
}


text:
Q: Laravel: dynamic configuration for Pusher I am trying to make the configuration for Pusher in my Laravel app (SaaS) dynamic.
Basically I want to store different Pusher configs for different accounts. And call the corresponding config based on the user.
I have tries to change the config in runtime using config()->set('services.pusher.xxx', 'yyyy'), but this doesn't work at any level of the framework, event in a custom ServiceProvider.
I found Laravel's BroadcastManager and tried to override the createPusherDriver() so that I could create a custom instance of PusherBroadcaster with the user's config, but I am not sure how to do that or where to put it!
What is the best-practice/standard way to do that?

A: I've been using a setup like this in one of my own projects, to set a custom mail config:

NOTE: Your mileage may vary due to the order in which service providers are loaded in your app.

Create a serviceprovider like app\Providers\ConfigProvider.php
public function boot()
{
    $this->app->booted(function () {
        $shouldSetCustomConfig = true;
        // Set config values from database.
        if($shouldSetCustomConfig) {
            config([
                'mail.host' => Config::get('mail.host'),
                'mail.port' => Config::get('mail.port'),
            ]);
        }
    });
}

*

*The $this->app->booted() is a simple callback that gets called after the application has been booted. This might not always work correctly because I've seen various packages that use this callback too to do various stuff. When this is the case, the order of registration matters. Note that it is not required to use this callback. One might simply call the config(['key' => 'newval']) directly and it could work as intended.

*The service provider above should be loaded BEFORE the provider you are setting configuration for. In the example above it would be the Illuminate\Mail\MailServiceProvider::class. This should make sure the correct config is loaded.


text:
Q: Microsoft Arc mouse on Ubuntu 18.04 I have ubuntu
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.1 LTS
Release:    18.04
Codename:   bionic

and bluetooth:
hciconfig -a
hci0:   Type: Primary  Bus: USB
    BD Address: 74:2F:68:D4:6F:6A  ACL MTU: 1022:8  SCO MTU: 121:3
    UP RUNNING PSCAN ISCAN INQUIRY
    RX bytes:8216 acl:0 sco:0 events:267 errors:0
    TX bytes:5769 acl:0 sco:0 commands:125 errors:0
    Features: 0xff 0xfe 0x0d 0xfe 0x98 0x7f 0x79 0x87
    Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
    Link policy: RSWITCH HOLD SNIFF
    Link mode: SLAVE ACCEPT
    Name: 'kamil-K53SV'
    Class: 0x1c010c
    Service Classes: Rendering, Capturing, Object Transfer
    Device Class: Computer, Laptop
    HCI Version: 3.0 (0x5)  Revision: 0x9999
    LMP Version: 3.0 (0x5)  Subversion: 0x9999
    Manufacturer: Atheros Communications, Inc. (69)

but Ubuntu does not find my mouse in the Settings Bluetooth tab.
I was trying to hold the bluetooth button on the mouse for 5 seconds - but that did not help me find my mouse on my laptop (asus K53SV https://www.asus.com/Laptops/K53SV/specifications/).


text:
Q: How to position a bootstrap modal to open from where the button is I am new to bootstrap and AngularJs.
I am trying to use bootstrap modal dialog box to display additional details in a column of a table. I want the bootstrap modal to popup from where the details button in every row is but I can't seem to change the default position of the modal. It always pops up at the top and not where the mouse was clicked. Is there any way to re position it so that it pops up from right where the button is so that it looks more relevant to a particular element and less like an alert box.
Thanks.

A: use tooltip with html template and you can change the trigger to click so it will resolve your problem


text:
Q: React-Native-Element icon shows up as cross in search bar How do I change the icon of search bar in react-native-element.
<Icon type='font-awesome' name="share-alt" size={33} color="red" />

The above code does render the icon properly.
But the same icon shows up as a cross in the following code
<SearchBar
    lightTheme
    icon = {"share-alt", "red"}
    inputStyle={{margin: 0, padding:3, flex:1}}
    containerStyle={{flex:1, height:undefined}}
    onChangeText={() => {}}
    placeholder='ABC' />

A: You can only change native icon only. It's list in here https://material.io/icons/.
icon prop does not accept type . It is specify here react-native-elements/API/searchbar/
 object {name (string), color (string), style (object)}

A: According to your screen shots, react-native-vector-icons is not installed properly.
1. Install react-native-vector-icons correctly.
2. And then you can see search icon. At that time, you can change the icon of search bar. You can use Material icon names

A: Make sure you have linked the vector icons after installing them
npx react-native link react-native-vector-icons

Then make sure you stop your packager and recompile the app again. now the icons should show up. The icons are not usually loaded up after installing and linking, you must recompile the app again.


text:
Q: Check if string begins with something? I know that I can do like ^= to see if an id starts with something, and I tried using that for this, but it didn't work. Basically, I'm retrieving a URL and I want to set a class for an element for path names that start in a certain way.
Example:
var pathname = window.location.pathname;  //gives me /sub/1/train/yonks/459087

I want to make sure that for every path that starts with /sub/1, I can set a class for an element:
if (pathname ^= '/sub/1') {  //this didn't work...
        ...

A: You can use string.match() and a regular expression for this too:
if(pathname.match(/^\/sub\/1/)) { // you need to escape the slashes

string.match() will return an array of matching substrings if found, otherwise null.

A: A little more reusable function:
beginsWith = function(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}

A: Use stringObject.substring
if (pathname.substring(0, 6) == "/sub/1") {
    // ...
}

A: First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.
String.prototype.beginsWith = function (string) {
    return(this.indexOf(string) === 0);
};

Then you use it like this. Caution! Makes the code extremely readable.
var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
    // Do stuff here
}

A: Have a look at JavaScript substring() method.

A: String.prototype.startsWith = function(needle)
{
    return this.indexOf(needle) === 0;
};


text:
Q: How to iterate through all files in sftp folder in Microsoft Azure Logic App steps i already did using SFTP connector (how can i access files while looping through list files in folder in azure logic app):

*

*I added foreach loop

*I added list files in folder

*I passed Body as parameter in foreach loop

*then i added action to create new file with new name for all files.

*but i am not able to get file name and content while iterating sftp folder using foreach loop?

A: Please see example image, showing the logic app design. I am iterating sftp folder posting file content to http end point:


text:
Q: Submit form and file to controller codeigniter I am newbie in codeigniter and MVC model
i want to know how i passing my form and file upload to controller and upload it using curl
and return the confirmation result to view
this is my view :

            Edit Issue

            <form class="editissueform">
            <h7>Name : </h7>
            <input type="text" name="issue_name">

            <h7>Tagline:</h7>
            <input type="text" name="issue_tagline">

            <h7>Description:</h7>
            <input type="text" name="issue_description">

            <h7>Publish Date:</h7>
            <input type="text" name="issue_publish_on">

            </form>

Upload Publication

            <form class="editissueform">
            <input type="file" name="issue_file" size="40" />
            <h7>Please Upload using pdf file format</h7>
            </form>

        <input type="submit" name="submit" value="upload">
        <?php echo form_close(); ?>

and this is my controller:
$issue_name = $this->input->post('issue_name');
  $issue_tagline = $this->input->post('issue_tagline');
  $issue_description = $this->input->post('issue_description');
  $issue_publish_on = $this->input->post('issue_publish_on');
  $issue_file = $this->input->post('issue_file');

$data2=array(
  'issue_name' => $issue_name,
  'issue_tagline' => $issue_tagline,
  'issue_description' => $issue_description,
  'issue_file' => $issue_file
  );

$this->load->helper('form');
$this->load->view('issue_detail',$data2);

  echo $issue_name;

  $target_url = 'https://platform.twixlmedia.com/admin-api/1/upload';

  $file_name_with_full_path = realpath($issue_file);
  $post3 = array(
'admin_api_key'    => 'da06751194bc1xxxxxxxxxxxx',
'app_key'          => 'bd7cf04226c587xxxxxxxxxxx',
'issue_identifier' => $productid,
'issue_file'       =>'@' . realpath($issue_file),
'issue_name'       => $issue_name
  );

$ch3 = curl_init();
curl_setopt($ch3, CURLOPT_URL, 'https://platform.twixlmedia.com/admin-api/1/upload');
curl_setopt($ch3, CURLOPT_POST, 1);
curl_setopt($ch3, CURLOPT_POSTFIELDS, $post3);
curl_setopt($ch3, CURLOPT_RETURNTRANSFER, 1);
$result3 = curl_exec($ch3);
curl_close ($ch3);
echo $result3;

how i can passing my form input to controller and upload them to server api?
thanks

A: Your HTML <form> tag is missing attributes:
<form class="editissueform" action="upload.php" method="post" enctype="multipart/form-data">

*

*action

*method

*enctype

Debugging update
Your HTML form
<form class="editissueform" action="www.example.com/process/curl" method="post" enctype="multipart/form-data">

</form>

process.php controller
<?php

class Process extends CI_controller
{
    public function curl()
    {
        /**
         *
         * Does this output what you expect?
         *
         */

        echo '
'.print_r($this->input->post(), true).'
'

        die();

        // All of your curl code
    }
}


text:
Q: retrieve the fields we are interested in and write to a result file the fields + count result using scala spark I need to import a CSV file that contains several fields, I must later loop on some fields that interest us to recover the data contained in it.
In the file there is a field named query that contains SQL queries that must be executed and store in another CSV file that will contain the fields to retrieve as well as the results of each query.
Below is my code so far:
// step1:read the file
val table_requete = spark.read.format("com.databricks.spark.csv").option("header","true").option("delimiter", ";").load("/user/swychowski/ClientAnlytics_Controle/00_Params/filtre.csv")
req.registerTempTable("req")
// step2:read the file

However, I dont know how to loop and store on another file at the same time.


text:
Q: Multi-select / modify event Openlayers 3 I'm trying to incorporate a modify feature where the user will move a point and any underlying geometry is also modified. Currently to draw a route on a map I'm taking points from a database and creating a Feature for each(ol.geom.Point) and then pushing the same coordinates into an array for the underlying linestring. All of these are added to a Feature Collection so if there were 28 points in the database, there will be a feature collection with 29 items(28 points and a linestring).
The Select and Modify interactions are set to multi:true and this seems to occasionally allow me to select both the waypoint and the vertex point beneath but it's really hit and miss.
These are sample Modify Start/End functions:
session.interactions.modify.on('modifystart', function (e) {
        session.selectedFeatures = session.activeRoute.Layers[0].getSource().getFeatures();
        session.testArray = e.features.getArray();
        for (var p = 0; p < session.testArray.length; p++) {
             session.modifiedGuid = session.testArray[p].get('Guid');
             session.originalCoordinates = session.testArray[p].getGeometry().getCoordinates();
                }
  });

  session.interactions.modify.on('modifyend', function (e) {
         session.selectedFeatures = session.activeRoute.Layers[0].getSource().getFeatures();
         var lsRoute = session.selectedFeatures[session.selectedFeatures.length - 1];
         console.log(lsRoute);
         console.log(lsRoute.getGeometry().getCoordinates());
         console.log(session.testArray);
                for (var p = 0; p < session.testArray.length; p++) {
                    console.log(session.testArray[p].get('Guid'));
             console.log(session.testArray[p].getGeometry().getCoordinates());
                    session.modifiedCoordinates = session.testArray[p].getGeometry().getCoordinates();
                    updateModifiedGeom(session.modifiedGuid, session.originalCoordinates, session.modifiedCoordinates);
                }
            });

The updateModifiedGeom function was logging to the console the Guid, original, and modified coordinates but since I specified multi: true on the modify interaction it's no longer picking up these details, only the linestring array beneath.
I'm sorry if this seems a little garbled but I've been struggling for months to be able to display rich data points on a linestring and this is the only way I've been able to resolve it to any degree.
I'd previously posted this question which received no responses and I've managed to get this far but hopefully someone can tell me where I'm going wrong. I can't post a fiddle as it would take far too long to adapt the code to work in a stand-alone way.


text:
Q: Description and counting non-crystallographic discrete subgroups of Euclidean isometries I am not sure if this question is more suited for mathOverflow, I will give it a chance here first.
An n-dimensional crystallographic group is a discrete co-compact subgroup of the group of isometries of $\mathbb R^n$.
The cornerstone of n-dimensional crystallographic group theory is based on a series of three theorems by  L. Bieberbach (1911  and 1912 ) together with the work of H. Zassenhaus (1948).
In addition to the algebraic understanding provided by these theorems, many works went to explicitly count crystallographic groups, at least in low dimensions, which is relevant not only to math but also to physics.

See for example
Plesken, W. and Schulz, T., (2000). "Counting
  crystallographic groups in low dimensions.",pdf
Fischer, M., Ratz, M., Torrado, J. and Vaudrevange, P.K., (2013).  "Classification of symmetric toroidal orbifolds.",
  ArXiv

Contrastly, in my experience, it is difficult to find such theoretical and computational studies for non-cocompact discrete subgroups of Euclidean isometries in dimensions greater than $2$. In the case dimension $2$, I am aware of Rosette and Frieze groups. I want to know what we know about those non-crystallographic discrete subgroups in dimensions greater than $2$.

A: If $\Gamma$ is a discrete subgroup of $\mathrm{Isom}(E)$, $E$ a Euclidean space, then there exists a unique minimal $\Gamma$-invariant affine subspace $V$ in $E$. Then $\Gamma$ acts cocompactly and properly on $V$ (hence with finite kernel); it acts as a finite group on $E/V$; $\Gamma$ has a finite index subgroup isomorphic to $\mathbf{Z}^{\dim(V)}$, and is cocompact iff $V=E$.
This is essentially (but not completely) a reduction to the cocompact case.
It is possible that you get more complete information on MO (think of tagging your question, in addition to gr.group-theory, also gt.geometric-topology and lie-groups).


text:
Q: Understanding what is meant by "Integrability" with regards to the Euler Top I am reading Discrete Systems and Integrability by F.W. Nijhoff, J. Hietarinta, and N. Joshi. Currently, I am investigating Chapter 6 and in particular the Euler Top. The book says the following:

There are several properties associated with integrability of maps,
  for example, the existence of a sifficient number of conserved
  quantities, symmetries, Lax pair and the behavior around
  singularities.

The book then defines a type of Integrability

A system with $2N$-dimension phase space is called Louiville
  Integrable if there are $N$ conserved quantities

The Euler Top is  given by
$$
\begin{cases}
\overset{\cdot}{x}_1 = \alpha_1 x_2 x_3, \\
\overset{\cdot}{x}_2 = \alpha_2 x_{3}x_{1}, \\
\overset{\cdot}{x}_3 = \alpha_3 x_{1}x_{2}.
\end{cases}
$$
where $\alpha_{1,2,3}$ are real parameters. This is one of the most famous integrable systems of classicaly mechanics. The function $H(x) = \gamma_1 x_1^2 + \gamma_2 x_2^2 + \gamma_3 x_3^2$ is an integral (conserved quantity?) for the above system $\iff \gamma \perp \alpha$.
In particular, there are $3$ integrals of motion (conserved quantities) of the system where only two of them are independent:
$$H_1 = \alpha_2 x_3^2 - \alpha_3 x_2^2, \; H_2 = \alpha_3 x_1^2 - \alpha_1 x_3^2 , \; H_3 = \alpha_1 x_2^2 - \alpha_2 x_1^2$$
So, here is what I know. The dimension of the Euler Top is $3$ because there are three independent variables $x_1, x_2, x_3$. We have found $2$ independent conserved quantities. Since the dimension of the system is $3$, then this doesn't fit the definition of the Louiville Integrability.
So, by what definition is the Euler Top called Integrable?

A: Hamiltonian systems can be defined on any manifold where there is a Poisson bracket (something satsifying the axioms given in section 6.1.1 of the book you referred to). It doesn't have to be a $2N$-dimensional space, and the Poisson bracket doesn't have to be given by the classical formula
$$
\{ F,G \} = \sum \left( \frac{\partial F}{\partial q_j} \frac{\partial G}{\partial p_j} - \frac{\partial F}{\partial p_j} \frac{\partial G}{\partial q_j} \right)
.
$$
In the case of the Euler rigid body equations with no external forces, which are usually written
$$
\begin{aligned}
  \dot x_1 = \left( \frac{1}{I_3} - \frac{1}{I_2} \right) x_2 x_3, \\
  \dot x_2 = \left( \frac{1}{I_1} - \frac{1}{I_3} \right) x_1 x_3, \\
  \dot x_3 = \left( \frac{1}{I_2} - \frac{1}{I_1} \right) x_1 x_2,
\end{aligned}
$$
where $(x_1,x_2,x_3)=(I_1 \omega_1,I_2 \omega_2,I_3 \omega_3)$,
the phase space is $\mathbf{R}^3$ and the Poisson bracket is
$$
\{ F,G \} =
\begin{pmatrix}
  \dfrac{\partial F}{\partial x_1} &
  \dfrac{\partial F}{\partial x_2} &
  \dfrac{\partial F}{\partial x_3}
\end{pmatrix}
\begin{pmatrix}
  0 & -x_3 & x_2 \\
  x_3 & 0 & -x_1 \\
  -x_2 & x_1 & 0
\end{pmatrix}
\begin{pmatrix}
  \partial G / \partial x_1 \\
  \partial G / \partial x_2 \\
  \partial G / \partial x_3
\end{pmatrix}
.
$$
The matrix in the middle is called a Poisson matrix, and the fact that this really is a Poisson bracket (in particular that the Jacobi identity is satisfied) has to do with the Lie algebra $\mathfrak{so}(3)$.
The Euler top is a Hamiltonian system (with respect to this Poisson structure) since it can be written as
$$
\frac{d}{dt}
\begin{pmatrix}
  x_1 \\ x_2 \\ x_3
\end{pmatrix}
=
\begin{pmatrix}
  0 & -x_3 & x_2 \\
  x_3 & 0 & -x_1 \\
  -x_2 & x_1 & 0
\end{pmatrix}
\begin{pmatrix}
  \partial H / \partial x_1 \\
  \partial H / \partial x_2 \\
  \partial H / \partial x_3
\end{pmatrix}
,
$$
with the Hamiltonian function
$$
H(x_1,x_2,x_3) = \frac12 \left( \frac{x_1^2}{I_1} + \frac{x_2^2}{I_2} + \frac{x_3^2}{I_3} \right)
.
$$
This automatically makes $H$ a constant of motion.
And moreover, $C=x_1^2+x_2^2+x_3^2$ is another constant of motion. It's a so-called Casimir function, which means that it's constant for any system of the above Hamiltonian form, no matter what the Hamiltonian function $H$ is (so it's something that's only related to the particular Poisson structure that we have here). And it turns out that you can restrict the Poisson structure to each level set of $C$ (in this case spheres around the origin, and let's exclude the exceptional level set consisting of only the origin), so that each sphere becomes a symplectic manifold, which is the setting for classical Hamiltonian systems. And the system can be restricted to a system on any particular such "symplectic leaf", as these spheres are called, and you can introduce coordinates $(q,p)$ such that the system looks just like a classical Hamiltonian system (in this case $2N$-dimensional with $N=1$). And any such system is Liouville integrable, since it has the right number of constants of motion: one (namely the Hamiltonian function, the restriction of $H$ to the sphere).
This was of course only a very brief outline. A more thorough description of how it works in general can be found in Chapter 6 of Peter Olver's Applications of Lie Groups to Differential Equations.


text:
Q: CodeDeploy getcwd: cannot access parent directories: No such file or directory We have a repeating problem where CodeDeploy just loses access.
This problem is bugging me and out Amazon AWS reseller support team for a few months now.
After fresh instance ec2 creation our deploy works fine.
After few days 7-14 days (10-30 deploys) codeDeploy just throws an error.
We already upgraded codeDeploy to the newest version.
The directory exists and has good privileges.
We had this problem on rsync. then we stopped using rsync and we now have it on first script that does anything in directory which is application stop.
Disk space is ok, nothing more is on logs than those below.
At some point the codedeploy just does not see anything and cannot do anything.
At the same time on the same ec2 other software deployments work fine, just the one has problems. This app is React js dashboard with nodejs server that stops and starts.
Also, application works fine, all files are there but only new deployments does not work.
We were using before rsync to swap files in file to lower downtime and we thought that maybe this is causing some problems but it is happening regardless if we use rsync or deployment in place. It seems like CodeDeploy bug...
Also manually executing all commands in CodeDeploy scripts work fine. Only CodeDeploy can't do that anymore on its own.
ApplicationStop script:
#!/bin/bash

#/usr/local/lib/npm/bin/pm2
export PATH="/usr/local/lib/npm/bin/:$PATH"
cd /home/koza/dashboard/ && npm run start:prod

2021-01-27 22:18:29 [stdout]### Rsync z temp do glownego ###
2021-01-27 22:18:29 [stderr]rsync: getcwd(): No such file or directory (2)
2021-01-27 22:18:29 [stderr]rsync error: errors selecting input/output files, dirs (code 3) at util.c(1185) [Receiver=3.1.2]
2021-01-27 22:18:29 [stdout]ownership of '/home/koza/dashboard' retained as koza:koza
2021-01-27 22:18:29 [stdout]### REMOVING UNNECESSARY FILES ###
2021-01-27 22:18:29 [stdout]### PURGING TEMPORARY DIR ###
2021-01-27 22:18:31 Script - aws/startApp.sh
2021-01-27 22:18:31 [stderr]shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
2021-01-27 22:18:31 [stderr]shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
2021-01-27 22:18:31 [stderr]internal/bootstrap/switches/does_own_process_state.js:128
2021-01-27 22:18:31 [stderr]  cachedCwd = rawMethods.cwd();
2021-01-27 22:18:31 [stderr]                         ^
2021-01-27 22:18:31 [stderr]
2021-01-27 22:18:31 [stderr]Error: ENOENT: no such file or directory, uv_cwd
2021-01-27 22:18:31 [stderr]    at process.wrappedCwd [as cwd] (internal/bootstrap/switches/does_own_process_state.js:128:26)
2021-01-27 22:18:31 [stderr]    at new API (/usr/local/lib/npm/lib/node_modules/pm2/lib/API.js:70:24)
2021-01-27 22:18:31 [stderr]    at Object.<anonymous> (/usr/local/lib/npm/lib/node_modules/pm2/lib/binaries/CLI.js:22:11)
2021-01-27 22:18:31 [stderr]    at Module._compile (internal/modules/cjs/loader.js:999:30)
2021-01-27 22:18:31 [stderr]    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
2021-01-27 22:18:31 [stderr]    at Module.load (internal/modules/cjs/loader.js:863:32)
2021-01-27 22:18:31 [stderr]    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
2021-01-27 22:18:31 [stderr]    at Module.require (internal/modules/cjs/loader.js:887:19)
2021-01-27 22:18:31 [stderr]    at require (internal/modules/cjs/helpers.js:74:18)
2021-01-27 22:18:31 [stderr]    at Object.<anonymous> (/usr/local/lib/npm/lib/node_modules/pm2/bin/pm2:3:1) {
2021-01-27 22:18:31 [stderr]  errno: -2,
2021-01-27 22:18:31 [stderr]  code: 'ENOENT',
2021-01-27 22:18:31 [stderr]  syscall: 'uv_cwd'
2021-01-27 22:18:31 [stderr]}
2021-01-27 22:18:31 [stderr]chdir: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
2021-01-27 22:18:31 [stdout]
2021-01-27 22:18:31 [stdout]> koza-dashboard@3.0.0 start:prod /home/koza/dashboard
2021-01-27 22:18:31 [stdout]> pm2 start ecosystem.config.js --env production
2021-01-27 22:18:31 [stdout]
2021-01-27 22:18:32 [stdout][PM2][WARN] Environment [production] is not defined in process file
2021-01-27 22:18:32 [stdout][PM2] Applying action restartProcessId on app [sm-dashboard](ids: [ 0 ])
2021-01-27 22:18:32 [stdout][PM2] [sm-dashboard](0) ✓

2021-01-11 23:15:56 [stdout]### REMOVING UNNECESSARY FILES ###
2021-01-11 23:15:56 [stdout]### PURGING TEMPORARY DIR ###
2021-01-11 23:15:57 Script - aws/startApp.sh
2021-01-11 23:15:57 [stderr]shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
2021-01-11 23:15:57 [stderr]shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
2021-01-11 23:15:57 [stderr]chdir: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory

2021-01-12 15:31:54 [stdout]changed ownership of '/home/koza/temp_dashboard' from root:root to koza:koza
2021-01-12 15:31:54 [stderr]rsync: getcwd(): No such file or directory (2)
2021-01-12 15:31:54 [stderr]rsync error: errors selecting input/output files, dirs (code 3) at util.c(1185) [Receiver=3.1.2]
2021-01-12 15:31:54 [stdout]### Rsync z temp do glownego ###
2021-01-12 15:31:54 [stdout]ownership of '/home/koza/dashboard' retained as koza:koza
2021-01-12 15:31:54 [stdout]### REMOVING UNNECESSARY FILES ###
2021-01-12 15:31:54 [stdout]### PURGING TEMPORARY DIR ###
2021-01-12 15:31:54 Script - aws/startApp.sh
2021-01-12 15:31:54 [stderr]shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
2021-01-12 15:31:54 [stderr]shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
2021-01-12 15:31:54 [stderr]/opt/codedeploy-agent/deployment-root/ccbab8f8-3a6a-4efd-8e71-753c33d93659/d-25VXE5DF8/deployment-archive/aws/startApp.sh: line 4: pm2: command not found
2021-01-12 15:31:54 [stderr]chdir: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory

LifecycleEvent - ApplicationStop
Script - aws/ApplicationStop.sh
[stderr]shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
[stderr]shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
[stderr]internal/bootstrap/switches/does_own_process_state.js:128
[stderr] cachedCwd = rawMethods.cwd();
[stderr] ^
[stderr]
[stderr]Error: ENOENT: no such file or directory, uv_cwd
[stderr] at process.wrappedCwd [as cwd] (internal/bootstrap/switches/does_own_process_state.js:128:26)
[stderr] at new API (/usr/local/lib/npm/lib/node_modules/pm2/lib/API.js:70:24)
[stderr] at Object.<anonymous> (/usr/local/lib/npm/lib/node_modules/pm2/lib/binaries/CLI.js:22:11)
[stderr] at Module._compile (internal/modules/cjs/loader.js:999:30)
[stderr] at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
[stderr] at Module.load (internal/modules/cjs/loader.js:863:32)
[stderr] at Function.Module._load (internal/modules/cjs/loader.js:708:14)
[stderr] at Module.require (internal/modules/cjs/loader.js:887:19)
[stderr] at require (internal/modules/cjs/helpers.js:74:18)
[stderr] at Object.<anonymous> (/usr/local/lib/npm/lib/node_modules/pm2/bin/pm2:3:1)

{ [stderr] errno: -2, [stderr] code: 'ENOENT', [stderr] syscall: 'uv_cwd' [stderr]}
CLOSED

LifecycleEvent - ApplicationStop
Script - aws/ApplicationStop.sh
[stderr]shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
[stderr]shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
[stdout]/
[stderr]internal/bootstrap/switches/does_own_process_state.js:129
[stderr] cachedCwd = rawMethods.cwd();
[stderr] ^
[stderr]
[stderr]Error: ENOENT: no such file or directory, uv_cwd
[stderr] at process.wrappedCwd [as cwd] (internal/bootstrap/switches/does_own_process_state.js:129:28)
[stderr] at new API (/usr/local/lib/npm/lib/node_modules/pm2/lib/API.js:70:24)
[stderr] at Object.<anonymous> (/usr/local/lib/npm/lib/node_modules/pm2/lib/binaries/CLI.js:22:11)
[stderr] at Module._compile (internal/modules/cjs/loader.js:1063:30)
[stderr] at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
[stderr] at Module.load (internal/modules/cjs/loader.js:928:32)
[stderr] at Function.Module._load (internal/modules/cjs/loader.js:769:14)
[stderr] at Module.require (internal/modules/cjs/loader.js:952:19)
[stderr] at require (internal/modules/cjs/helpers.js:88:18)
[stderr] at Object.<anonymous> (/usr/local/lib/npm/lib/node_modules/pm2/bin/pm2:3:1)

{ [stderr] errno: -2, [stderr] code: 'ENOENT', [stderr] syscall: 'uv_cwd' [stderr]}

A: After some time trying to find an answer for this I decided to just go and restart the codedeploy-agent service.
Well it worked (on ubuntu):
sudo service codedeploy-agent restart


text:
Q: how to include a page in WEB_INF from a different directory
This is my folder Structure I want to include the page "common/tray.jsp" form "plan/add_edit.jsp" page
I have done <!-- Tray -->
        <%@ include file="/common/tray.jsp" %>
        <!--  END Tray -->
 in  plan/add_edit.jsp page But giving me
org.apache.jasper.JasperException: /plan/add_edit.jsp (line: 47, column: 9) File "/plan/common/tray.jsp" not found

A: <%@ include file="../common/tray.jsp" %>


text:
Q: How to specify path that CSV is saved in python the default path appears to be the project folder I am working in, but I cannot find any documentation that shows how to specify where the csv is saved to on the machine, I am currently using shutil to move the file to my desired path but this is not a robust solution because this application will be used by many users and this may cause problems.
length = len(list1)

#convert job name to csv name
jobname = jobname + ".csv"

with open (jobname, 'w', newline='') as f:
    thewriter = csv.writer(f)

    thewriter.writerow(column_header_list)

    i = 0
    for x in range(length):
        thewriter.writerow([list1[i],0,0,0,0,0,0,0,0,0,0])
        i += 1

#create a path for the newly made file
original_path = r'C:\Users\Scott\OneDrive\Documents\DL\Main Application MRL'
original_path = (original_path + '\\') #concat to add backslash to path
original_path = original_path + jobname #add jobname to path

target_path = r'C:\Users\Scott\OneDrive\Documents\DL\JobData'

shutil.move(original_path,target_path)


text:
Q: Unexpected token error on my for loop function count(num){
    var nums=[];

    for(i=1;i<num){
        var n=Integer.toString(i);
        nums.add(n);
        i++;
    }
    return nums;
}

I'm getting an error on my for loop

A: You need to do this:
for (i = 0; i < num;)
for-loops take in 3 parameters.

A: You need do this in javascript:
function count(num){
    var nums=[];
    for(var i=1;i<num;i++){
        nums.push(i);
    }
    return nums;
}


text:
Q: Foreign key -- id or just UNIQUE column Suppose that I have a table with the following columns:
CREATE TABLE users
{
  id INTEGER PRIMARY KEY,
  login VARCHAR(50) UNIQUE,
  password VARCHAR(50)
}

And I need to create a table which will store one cookie for each account. What's better -- to create a foreign key that refers to the login column from the first table
CREATE TABLE cookies
{
  id INTEGER PRIMARY KEY,
  cookie VARCHAR(50),
  login VARCHAR(50) FOREIGN KEY REFERENCES users(login)
}

or to create a foreign key that refers to the id column?
CREATE TABLE cookies
{
  id INTEGER PRIMARY KEY,
  cookie VARCHAR(50),
  expires DATETIME,
  id_user INTEGER FOREIGN KEY REFERENCES users(id)
}

And why?

A: Ok as you have several columns in cookie table and since that is a seperate entity I agree and it makes sense to take those additional columns in seperate table. What about pks and fks? Since you have only one row per user I would make userid a primary key and foreign key simultaneously:
cookies
{
  id_user(pk, fk),
  cookie,
  expires
}

A: CREATE TABLE cookies
{
  id INTEGER PRIMARY KEY,
  cookie VARCHAR(50),
  login VARCHAR(50) FOREIGN KEY REFERENCES users(login)
}

I think this is better option, as you need to communicate with login.

A: Use a foreign key that relates to the primary key of the users table:
create a foreign key that refers to the id column?

CREATE TABLE cookies
(
    id INTEGER PRIMARY KEY,
    cookie VARCHAR(50),
    expires DATETIME,
    user_id INTEGER,
    FOREIGN KEY (user_id) REFERENCES users(id)
)

The reason for doing this as a general convention is that the users(id) primary key is an immutable value. The 'login' column or any other which represents meta data about an object external to the database may change over time and is therefore less suitable for use in foreign key references.


text:
Q: How to generate program dependence graph for C program? I want to generate a Program Dependence Graph (PDG) from C source code. I found papers that explain how do it, but all used the commercial CodeSurfer tool.
Are there any free tools that do this?

A: Frama-C is an open-source static analysis framework that can compute a sound Program Dependency Graph for C programs. Its slicing plug-in uses the resulting PDG. The slicing and PDG computation were discussed in February 2010 on the mailing list (messages from jung, myung-jin and their answers).
You may also look at NIST's Unravel, or Georgia Tech's Aristotle. Both Valsoft at Karlsruhe University, and Loyola's Surgeon's Assistant, might also be worth looking into.

A: Doxygen can generate function caller and callee graphs, as well as all the functions used in your program.  This may not be exactly what you are looking for, but it could provide some useful data.
SourceMonitor is a metrics tool that can show function and program complexity as well as complexity diagrams.
Both tools are free.

A: There's a promising new tool called cpp-depenencies.
It can generate component dependency diagrams (like below) as well as class hierarchy diagrams (by passing an option to treat each source file as a component).

A: If you use llvm to generate pdg, you can use this:
https://bitbucket.org/psu_soslab/program-dependence-graph-in-llvm/src/master/


text:
Q: Drupal href is not working

        image tag

title

Welcome

I click on image or text is it not opening to the href link, but if open new tab is working, also I tried with href full path but its not working

A: You can define
 l(t('Link text'), 'about-us');
inside your php tag it will help you better.

A: Plz check ur javascript whether onclick event is disable or not
Example:
el.onclick = function (e) {
e.stopPropagation()
e.preventDefault()
}

This is disable the click event.

A: It may be your css/javascript issue.
If you want to validate your html check it in https://jsfiddle.net.
I copy/pasted your above-mentioned code into HTML section the clicked on run button. The link [] is working fine.
You can check z-index or another thing.


text:
Q: What's the best library for parsing RSS/Atom in Perl? I notice that XML::RSS::Parser hasn't been updated since 2005. Is this still the recommended library for parsing RSS or Atom? Is there a better one or a better way?

A: I actually like to avoid domain-specific XML parsers these days and just use XPath for everything. That way I only have to remember one API. (Unless it's a huge XML, then I'll use an event-based parser like XML::Parser.)
So using  XML::XPath, I can grab a bunch of stuff from an RSS file like this:
my $rss = get_rss();
my $xp = XML::XPath->new( xml => $rss );

my $stories = $xp->find( '/rss/channel/item' );

foreach my $story( $stories->get_nodelist ) {
    my $url   = $xp->find( 'link',  $story )->string_value;
    my $title = $xp->find( 'title', $story )->string_value;
    ...
}

Not the prettiest code in the world, but it works.

A: If XML::RSS::Parser works for you then use it. I've used XML::Parser to deal with RSS but I had narrow requirements and XML::Parser was already installed.
Just because something has been updated in a few years doesn't mean that it doesn't work anymore; I don't think the various RSS/Atom specs have changed recently so there's no need for the parser to change.

A: There is also a very nice module called XML::FeedPP (see http://search.cpan.org/dist/XML-FeedPP/lib/XML/FeedPP.pm). FeedPP is no so fast but it writen in almost pure Perl and has minimalistic dependencies.

A: I'm not sure it's ever been the "recommended library". If I know which kind of feed I need to parse, I use XML::RSS or XML::Atom as appropriate, but if (as is more likely) I just know it's a web feed, I use XML::Feed.
Adding an example of using XML::Feed as requested..
use XML::Feed;

my $feed = XML::Feed->parse(\$string_containing_feed);

foreach ($feed->entries) {
  print $_->title, "\n";
  print $_->content->body, "\n";
}

This is all pretty much copied from the module documentation.


text:
Q: Hover image - display div over it On hover I want a link apear at the top-right of the image. Just like on your profile picture on Facebook, where it says "Change Picture".
I have tried to to get it working with a bit of jquery but had no luck, as it doesn't go t the right of the image. The images are going to be different sizes as they are profile pictures. So whatever the size, it needs to stay at the top-right of the image.
JQuery:
$(".imgHover").hover(function() {
    $(this).children("img").fadeTo(200, 0.25)
           .end().children(".hover").show();
}, function() {
    $(this).children("img").fadeTo(200, 1)
           .end().children(".hover").hide();
});

HTML:

Edit

CSS:
.imgHover .hover {
    display: none;
    position:absolute;
    z-index: 2;

}

Thanks!

A: Try <!doctype html>

    <meta charset="utf-8">
    <title>Test</title>

Edit

A: If the imgHover is made to match its contents, then it should just have position:relative and the hover class have position:absolute and top:0;right:0
Example at http://www.jsfiddle.net/FvBqA/

A: This is the way I done it:
CSS:
.imgHover {
    display: inline;
    position: relative;
}
.imgHover .hover {
    display: none;
    position: absolute;
    right:0;
    z-index: 2;
}

HTML:

Edit

JQuery:
$(function() {
    $(".imgHover").hover(
        function() {
            $(this).children("img").fadeTo(200, 0.85).end().children(".hover").show();
        },
        function() {
            $(this).children("img").fadeTo(200, 1).end().children(".hover").hide();
        });
});

Test this on jsfiddle.

A: make your image a background for div with relative positioning
and add inner div to it with the overlay content
style it with display:none
then
    imgdiv:hover innerdiv{display:block}
will do the trick

A: You need to absolute position the link in a container that has position different than the normal flow. In this example I use relative for that on the container. Try this:
HTML

    Edit

CSS
.imgHover { float: left; }
.imgContainer { position: relative; }
.imgContainer a { display: block; position: absolute; top: 0; right: 0; background: Green;}


text:
Q: How to set different dates to different Users in Windows7 I want to set different date for each user on my Windows 7,
is there any option? or third party software?
Want to change system date/time when particular user login windows.
thank you

A: The system time is exactly that, the time of the system. There is no reason to have "user times" as the time should always be accurate and reflect the current time zone of the machine.

A: 1) Create a batch file that uses the inbuilt command-line time and date commands to set the time to the time/date you want.
2) Setup Windows' Task Scheduler to run the batch file, with the Trigger set to when the user logs in, with "run with highest privileges" set in the task.
3) There is no 3. :)


text:
Q: How to output array with new line separated values using Laravel Storage:put How to output an each array element in a new line with Laravel Storage:put?
I have an array like below that I want to put into a file, array_test.txt, where each element goes on a new line.
$arrTest
array:2 [
  0 => "Val 1"
  1 => "Val 2"
]

Using Laravel's Storage, it goes like Storage:put($fileName, $arrTest); However the output is on a single line. Storage as an $options tag, but that seems to just be for setting files as public or private.
If you had a link to what $options could be inputted, I'd like that, I can't find any documentation for what all the $options are for Storage:put!
Another option seems to be using Storage:append($fileName, $arrTest[0]) and then loop over all results.
Is there some easy way to output an entire array's elements on new lines with Storage:put instead of just a single line?

A: Quick answer. You can use implode :
$arrTest = [
  0 => "Val 1",
  1 => "Val 2"
];
$arrTest = implode("\n", $arrTest);

Storage::put('test.log', $arrTest);

A: Try this method. Hope is helpful.
foreach ($arrTest as $index => $arr) {
    Storage:put($fileName, $arr[$index] + "\n")
}


text:
Q: How to limit the amount of characters returned from a field in a Mongo query I'm trying to make a post list page for a blog i am working on and as usual on this page i want to show a piece of the blog content (first 100 characters or so) with a "Read More" button to go to the post detail. I iterate over a cursor that is the result of this query
db.posts.find();

which gives me the title and body of each post. I was wondering if there was a way to change my mongo query to pull the title and only the first 100 characters of the body field. Thank you.

A: You could use the aggregation pipeline operators $project and $substr
db.posts.aggregate(
[
  {
    $project:
      {
        intro: { $substr: [ "$fullText", 0, 100 ] },
        // ...
      }
  } ] )

However, I don't know whether this will have good performance characteristics. If not, using a separate field (e.g., teaser) that contains an intro snippet might be a better idea because you can simply ask MongoDB to not populate the actual text field at all:
db.posts.find({}, { "fullText" : 0 });

And posts then looks like
posts  {
  fullText : "Lorem Ipsum dolor sit amet .... ",
  teaser: "Lorem Ipsum!"
}

Whether or not the user should be able to modify intro or not is then a matter of product design, but it's possible from a tech perspective, at least, and the query is fast.


text:
Q: How to set background color of console in python? My question is clear. How can I set background color of console with python ?
I know that we can set background color of console in C#.
So I thought that python can do it, too.
But how ?
I'm on Windows and I use python 2.7.3.
Thanks...

A: You can set the Windows cmd console color with the color command, passing it from Python via os.system:
>>> import os
>>> os.system('color 1f') # sets the background to blue

For Linux terminals, use the setterm command:
>>> import os
>>> os.system('setterm -background white -foreground white -store')

A: Depends on  the shell and terminal emulator you are working running on. For bash this should work on ubuntu's terminal.
import os
color = 'blue'
os.system('setterm -term linux -back $'+color+' -fore white -clear')


text:
Q: Read Properties of devices on a BACNET IP router I'm having issues reading properties from devices on a BACNET IP router. For this I'm using .net library https://github.com/ela-compil/BACnet
If I'm interacting with multiple devices, each with its own ip and id (no router configuration), communication works and I'm able to read properties. But once a device in router mode is implemented and all other devices communicate throu this main router, I'm no longer able to read properties.
Main Bacnet router IP 192.168.2.222
Device 1, Ip: 192.168.1.1, ID: 10
Device 2, Ip: 192.168.1.2, ID: 11
My software is on IP 192.168.2.220

To read properties I'm using:
var targetObjId = new BacnetObjectId(BacnetObjectTypes.OBJECT_DEVICE, (uint)10);
var targetBacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, "192.168.1.1");
var rez = await Bacnet_client.ReadPropertyAsync(targetBacnetAddress, targetObjId, BacnetPropertyIds.PROP_OBJECT_LIST);

This returns: "Error from device: ERROR_CLASS_SERVICES - ERROR_CODE_SERVICE_REQUEST_DENIED".
If no router is used on the network, this code works and produces results. So I must be doing something wrong, while addressing the bacnet device?
Using Yabe browser all this works. So device configuration is setup corretly. Actualy devices behind router are discovered when I register foregin device throu Functions / IP Services / Foreign Device Registration.

A: Your devices, from the IP addresses, seem to be on different IP addresses. This is the first thing to confirm. ( 192.168.1.0 and 192.168.2.0 are normally different subnets, but this depends on your netmask settings).
As such, to 'reach across' and discover devices on other subnets, one would use a BBMD, and register with it, just as you mention with YABE, and the BBMD would distribute the discovery broadcasts (Who-Is) on the far subnet. So far, so good.
You are mixing up the concepts of "BACnet Router" and BBMD (BACnet Broadcast Management Device). In this case you should (are) using BBMD functionality, not BACnet Router functionality.
None of the above addresses your direct issue however. You seem to be creating a direct message (Using a known IP address, discovery not needed, therefore no Foreign Device registration with a BBMD required) and yet you get an error message. This seems to be an issue in the .Net implementation. What does Wireshark say was sent/received on port 47808?

A: I'm guessing that once you activate a router it might be the case that the devices have to be routed to via the router's IP(v4) address (& not the devices' IP address) - but with the addition of a combo of the appropriate DNET (Destination Network #) value & DADR (Destination Address) value to identity the device that you're targeting / e.g. trying to read properties from.
I.e.  The IP address identifies the router / the device that communicates to the (Modbus?) devices, and pairing of a DNET & DADR value identifies the device that the router will assist in the communication with (- as Steven has commented).
YABE confusingly seems to display the DADR value as an IP address (rather than as a MAC address aka EUI-48/MAC-48 format); you'd have to modify YABE's source code to fix this; but if you went that route, it would also be good to trace/output the I-Am info to it's 'Log' window too - to make it easier to see/refer back to.
E.g.  After the call to 'NPDU.Decode()' - having added a new 'IP_MAC' value to 'BacnetAddressTypes' (- overriding/replacing the default set value for routed-sources of "None"):

    if (source != null &&
        sender.Type == BacnetAddressTypes.IP)
    {
        source.type = BacnetAddressTypes.IP_MAC;
    }

You could then add a handling 'case' statement to the 'BacnetAddress.ToString()' method, to output a more appropriate display.
When you say "communication works and I'm able to read properties" - I assume you mean when you directly plug into the devices' (MS-TP?) network; otherwise it would sound like you don't need a router (/are maybe dealing with only BACnet/IP devices).
The 'RoutedSource' is the member/property that hangs off a 'BacnetAddress' that contains the DNET & DADR values (- set within the 'NPDU.Decode()' method).
Just in case you don't know, YABE displays all the routed-to devices underneath the (relevant/parent) router device tree node, as child nodes of the router.

"DADR = ultimate destination MAC layer address"

"DLEN = 1-octet length of ultimate destination MAC layer address"

"DNET = 2-octet ultimate destination network number"