text:
Q: When using Postman, my post method is ignored (making a Flask API) Whenever I do a post request to http://0.0.0.0:8000/api/v1/fliers it ignores it. I get a 200 OK status back and the database remains unchanged. My get request to the same comes back as its supposed to, but the post request is ignored.
Weird thing is everything was working fine just a bit ago, and now it isn't. I'm thoroughly confused. Any help would be appreciated.
from flask import jsonify, Blueprint, abort

from flask.ext.restful import (Resource, Api, reqparse,
                               inputs, fields, marshal,
                               marshal_with, url_for)

from auth import auth
import models

flier_fields = {
    'name': fields.String
}

def flier_or_404(flier_id):
    try:
        flier = models.Flier.get(models.Flier.id==flier_id)
    except models.Flier.DoesNotExist:
        abort(404)
    else:
        return flier

class FlierList(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument(
            'name',
            required=True,
            help='No name provided',
            location=['form', 'json']
        )
        super(FlierList, self).__init__()

    def get(self):
        fliers = [marshal(flier, flier_fields) for flier in     models.Flier.select()]
        return {'fliers': fliers}

    @marshal_with(flier_fields)
    @auth.login_required
    def post(self):
        args = self.reqparse.parse_args()
        flier = models.Flier.create(**args)
        return (flier, 201)

class Flier(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument(
            'name',
            required=True,
            help='No name provided',
            location=['form', 'json']
        )
        super(Flier, self).__init__()

    @marshal_with(flier_fields)
    def get(self, id):
        return flier_or_404(id)

    def put(self, id):
        return 400

    @auth.login_required
    def delete(self, id):
        query = models.Flier.delete().where(models.Flier.id==id)
        query.execute()
        return ('', 204)

fliers_api = Blueprint('resources.fliers', __name__)
api = Api(fliers_api)
api.add_resource(
    FlierList,
    '/api/v1/fliers',
    endpoint='fliers'
)
api.add_resource(
    Flier,
    '/api/v1/fliers/<int:id>',
    endpoint='flier'
)


text:
Q: I need help in changing the src of a file in a function written in javascript I want the src of the ga.js to read from my js/ folder and not from google-analytics. I have the ga.js file on my server and want to map the link to that and not from google-analytics.com. I don't know JavaScript. so any help would be much appreciated.
Below is the function. The line i need editing is the third line.
(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

A: Modify the function line the one below i don't know why do you want to do this but modify your code like the one below,replace localpath with your path where the file is stored
(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = '\localpath\ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

A: Change this line:
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
to:
ga.src = 'js/dummy.js';

A: Change your src attribute to point directly to your "ga.js" file into the /js/ folder:
ga.src = '/js/ga.js';

You can find more information about the source attribute here:
http://www.w3schools.com/tags/att_script_src.asp

redpajama_set_name: RedPajamaStackExchange


text:
Q: Format in R for point prediction of survival analysis I am befuddled by the format to perform a simple prediction using R's survival package
library(survival)
lung.surv <- survfit(Surv(time,status) ~ 1, data = lung)

So fitting a simple exponential regression (for example purposes only) is:
lung.reg <- survreg(Surv(time,status) ~ 1, data = lung, dist="exponential")

How would I predict the percent survival at time=400?
When I use the following:
myPredict400 <- predict(lung.reg, newdata=data.frame(time=400), type="response")

I get the following:
myPredict400
       1
421.7758

I was expecting something like 37% so I am missing something pretty obvious

A: The point with this survival function is to find an empirical distribution that fits the survival times. Essentially you are associating a survival time with a probability. Once you have that distribution, you can pick out the survival rate for a given time.
Try this:
library(survival)
lung.reg <- survreg(Surv(time,status) ~ 1, data = lung)  # because you want a distribution

pct <- 1:99/100  # this creates the empirical survival probabilities
myPredict400 <- predict(lung.reg, newdata=data.frame(time=400),type='quantile', p=pct)

indx = which(abs(myPredict400 - 400) == min(abs(myPredict400 - 400))) # find the closest survival time to 400
print(1 - pct[indx]) # 0.39

Straight from the help docs, here's a plot of it:
matplot(myPredict400, 1-pct, xlab="Months", ylab="Survival", type='l', lty=c(1,2,2), col=1)

Edited
You're basically fitting a regression to a distribution of probabilities (hence 1...99 out of 100). If you make it go to 100, then the last value of your prediction is inf because the survival rate in the 100th percentile is infinite. This is what the quantile and pct arguments do.
For example, setting pct = 1:999/1000 you get much more precise values for the prediction (myPredict400). Also, if you set pct to be some value that's not a proper probability (i.e. less than 0 or more than 1) you'll get an error. I suggest you play with these values and see how they impact your survival rates.


text:
Q: Discrete Mathematics proving set equality Refer to this Definition to solve the problem bolded:
If $f : X \to Y$ is a function and $A \subseteq X$ and $C \subset Y$ , then
$f (A) = \{y \in Y\, |\, y = f (x)\text{ for some }x \in A\}$
and $f^{−1}(C) = \{x \in X\, |\, f (x) \in C\}$.
$f (A)$ is called the image of $A$, and $f^{−1}(C)$ is called the inverse image of $C$.
For all subsets $A$ and $B$ of $X$, Prove or Disprove:
$F(A \cap B) = F(A) \cap F(B)$
I am completely lost and have no idea how to approach this problem.
I'm guessing I have to prove that the LHS and RHS are both proper subsets of each other to show equality. Any help is welcome to get me started.

A: It's not true. Let
$A = \{1,2\}$,
$B=\{4,5\}$,
$f(1) = 2$, $f(2) = 3$, $f(4) = 3$, $f(5) = 4$.
Then $A \cap B = \emptyset$, so $f(A \cap B) = \emptyset$. But
$f(A) = \{2,3\}$  ;   $f(B) = \{3,4\}$
So $f(A) \cap f(B) = \{3\}$, which is not empty.

A: In general, the two sides are not equal.Let A = (-1, 0 ], and B = (0, 1], X = Y = [-1, 1] and F:X --> Y as F(x) = x^2 ,then F(A and B) = empty , while F(A) intersects F(B) is not empty. In general, the LHS is a subset of the RHS.


text:
Q: NullPointer when call entity Manager I try to write some programme using Java, Hibernate and Spring. I see NullPointerException when I call the SQL query. I tried perhaps every samples of code on the internet, but I don't know how to do this. How can I solve it? This is my sample code. There is my full code of programme: https://github.com/lukasz-chojn/films_database/tree/master/src/main/java/Films
    @Controller
    public class DataFromUserController {
        private FilmDaoImpl filmDaoImpl = new FilmDaoImpl();
        private DirectorDaoImpl directorDaoImpl = new DirectorDaoImpl();
        private Locale locale = Locale.getDefault();
        private Scanner sc = new Scanner(System.in).useLocale(locale);

        public FilmDs collectData() {
            //....

            filmDaoImpl.insert(film);
            directorDaoImpl.insert(director);

            return film;
        }

        private String collectTitle() {
            System.out.print("Podaj tytuł filmu: ");
            String tytul = sc.nextLine();
            List<String> existingEntry = filmDaoImpl.existingTitle();
            if (existingEntry.contains(tytul)) {
                System.out.println("Tytuł jest już w bazie. Podaj inny");
                return collectTitle();
            }
                if (tytul.isEmpty()) {
                    System.out.println("Tytuł nie może być pusty. Podaj go");
                    return collectTitle();
                }
            return tytul;
        }//......
    }

    @Service
    @Transactional
    public class FilmDaoImpl implements FilmDAO {

        @PersistenceContext
        private EntityManager entityManager;

        //......
        @Override
        @SuppressWarnings("unchecked")
        public List<String> existingTitle() {
            List<String> titleInTheDatabase;
    // here is NPE
    return titleInTheDatabase = entityManager.createQuery("SELECT film.tytul FROM FilmDs film").getResultList();
        }

        //....
    }

A: You're creating instances on your own instead of letting spring inject it for you which is why you're losing all the dependencies like entitymanager, etc. change your DataFromUserController
@Controller
public class DataFromUserController {

@Autowired
private FilmDAO filmDao;

@Autowired
private DirectorDAO directorDao;

.....
}


text:
Q: How to call my OOP based classes and methods in PHP when buttons clicked or page loads in purely OOP style Point 1:
So I'm a beginner in PHP OOP and have been asked to complete a project for hiring at a company. They have asked in the guidelines to code in PHP OOP only, and have recently returned my project with one of the following point:
"Procedural PHP code is allowed exclusively to initialize your PHP classes. Rest logic should be placed within class methods."
Now, I am stuck since I have no clue how to call my php code without instantiating my classes in scenarios like such:

*

*Perform a save/delete function when a button is clicked

*Show all products from my phpMyadmin database on the homepage automatically
when the page loads

My frontend is made using basic HTML+ JQuery and I'm required to use php oop for all logical handling.
This is a snippet of my code where when a button is clicked I have used isset to call a function or instantiate a class and added calls to functions in the constructor, I dont know how else to call my functions, like I have to instantiate the objects somewhere and call function on the basis of some check when specific event happens.
//placed these checks in a procuctinfo.php class which is called when button save/delete(with action="productinfo.php" method = "post") is clicked

if (isset($_POST['save'])) {
    $product = new $_POST['productType'](); //goes to constructor of specific product where method is called to save data
}

if (isset($_POST['delete'])) {
    Product::delete(); // static method called since delete is not object specific
}

//here is my constructor of one of the product classes
    public function __construct(){ //contructor for one of the products
            parent::__construct();
            if (isset($_POST['save'])) {
                $this->weight =$_POST['weight'];
                **$this->setData()**; //method called within constructor which saves data in my db
            }
        }

Similarly for rendering all products on homepage I have embedded php code within my html in the following way,

                    <?php

                    $DVDs = new DVD([]);
                    $result = $DVDs->getAllData();
                    if($result){
                        foreach($result as $product){
                            $productObj = new $product['productType']([]);
                            $productResult = $productObj->getDataProductWise($product);
                            ?>

                                        <input class="form-check-input m-3 border border-dark rounded-0" type="checkbox" name = "deleteChecked[]" value="<?= $productResult['sku'] ?>" id="flexCheckDefault">

<?= $productResult['sku'] ?>

<?= $productResult['name'] ?>

<?= $productResult['price'] ?> $

<?= $productResult['attribute']?>

                        <?php
                    }
                }

                ?>

Please guide me if there is some purely OOP based way/approach to do this.
Point 2:
I provided them a website link which I created using https://www.000webhost.com/ website but they have asked me to :
"Please provide FE link."
What is this and how can I create it?

A: I do not like to see $_POST[] inside a constructor. That's purely my opinion, but I can give some reasons: It's raw user input, think about security, and classes should be created to be flexible, not rigid in that the input has to come from the user.
Your code snippets are very short. I cannot do much with those. Only the output code is long enough.
In it I see that you don't actually use objects, you convert them to arrays. Why? getAllData() and getDataProductWise() should not be used in this code. It should simply be getProducts() which should return an array with zero or more product objects.
This means that when you need to display something from an object you do:
echo '
' . $product->getPrice() . '
';

You can create a method in the DVD class called outputProductHtml($product) to output a product and then you can also do:
public function outputProductsHtml()
{
    foreach ($this->getProducts() as $product) {
        outputProductHtml($product);
    }
}

Keep methods short and simple like this. Now your DVD class can generate HTML for a single product or for all products it contains.


text:
Q: Rolled back on heroku, restored db, and now getting a ton of database errors We deployed some code tonight but had to rollback. The rollback affected the database so we restored our database to one we captured right before the deploy. Now we're getting all types of database errors, such as:
ActiveRecord::UnknownPrimaryKey: Unknown primary key for table billing_accounts in model BillingAccount.

PG::SyntaxError: ERROR: zero-length delimited identifier at or near """" LINE 1: ... "billing_accounts" ORDER BY "billing_accounts"."" ASC LIM.

PG::InternalError: ERROR: cache lookup failed for type 19005

PG::InFailedSqlTransaction: ERROR: current transaction is aborted, commands ignored until end of transaction block

I have no idea what to do about these errors, we're getting a ton of them. Help!!


text:
Q: API Manger fails to start in a Remote Server I am trying to run APIM 1.6.0 in a remote server. It gives following exception - http://pastebin.com/HTAsbpsQ. Is it a configuration fault in APIM or problem in the server configuration ?

A: If you have changed the HostName and MgtHostName properties in carbon.xml try first by giving the IP of the server. It seems the server is bound to an unresolvable host name.


text:
Q: Django - Correct method of consuming my own REST API internally in the views.py? I created a Django REST API using serializers, viewsets and routers. My end points looks something like this:
http://www.website.com/api/items
http://www.website.com/api/items/available

serializer.py (omitting imports)
class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = '__all__'

viewsets.py (omitting imports)
class ItemViewSet(viewsets.ModelViewSet):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer

    @action(methods=['GET'], detail=False)
    def most_expensive(self, request):
        query = self.get_queryset().order_by('price').last()
        serialized = self.serializer_class(query)
        return Response(serialized.data)

Now I want to able to access this API from my views.py to render the HTML with the available items:
This is the way im doing it right now:
views.py (omitting imports)
class ProductListView(View):
    template = 'store/product_list.html'

    def get(self, request):
        items = requests.get('http://127.0.0.1:8000/api/items/available')
        context = {'items': items}
        return render(request, self.template, context=context)

Using the requests modules I have a couple of concerns, after measuring I noticed there is a 0.015 second delay for that request to go through and if I ever change the API endpoint I would have to adjust it here since its hard coded.
I can get my items using:
Item.objects.filter(available=True)

Which gives me the result pretty much instantly but I'm writing all the queries twice (once in my API and once in my views.py)
Is there a better way of doing this like calling the viewset class directly and getting the data from there?
Many thanks!

A: Calling the API endpoint in the same app is not considered a good practise.
An option would be to call your viewset method directly, like in https://stackoverflow.com/a/51149806/290036
The other one that I recommend is to use the same codebase for your API and for the view.
def get_avaialble_items():
     items = Item.objects.filter(available=True)
     ...
     return items

# Use get_avaialble_items both in ItemViewSet and ProductListView


text:
Q: Multiple row in self join i have table in this format
Id  QId   ResourceId ModuleId SubProjId  Comments
1   1   1   1   2   ffdg    1   1
2   2   1   1   2   dfgfdg  1   1
3   3   1   1   2   hgjhg   1   1
4   1   2   1   2   tryty   1   0
5   5   1   1   2   sdf 1   1
6   5   2   1   2   ghgfh   1   0
7   7   2   1   2   tytry   1   0
8   3   2   1   2   rytr    1   0

and i wan result in this way
qid  ResourceId Comments   ResourceId  Comments

1   1   ffdg    2   tryty
3   1   hgjhg   2   rytr

i tried
select distinct  A.qid,A.ResourceId,A.Comments,B.ResourceId,b.Comments
from dbo.#temp A inner join #temp B on A.QId=B.QId and A.[ModuleId]=B.[ModuleId] and a.[SubProjId]=b.[SubProjId]

but did not find any luck please help

A: You want to convert vertical data to horizontal. So you need to create a pivot table. You can find more details here
How to transform vertical data into horizontal data with SQL?


text:
Q: Intro to GPU programming Everyone has this huge massively parallelized supercomputer on their desktop in the form of a graphics card GPU.

*

*What is the "hello world" equivalent of the GPU community?

*What do I do, where do I go, to get started programming the GPU for the major GPU vendors?

-Adam

A: I think the others have answered your second question. As for the first, the "Hello World" of CUDA, I don't think there is a set standard, but personally, I'd recommend a parallel adder (i.e. a programme that sums N integers).
If you look the "reduction" example in the NVIDIA SDK, the superficially simple task can be extended to demonstrate numerous CUDA considerations such as coalesced reads, memory bank conflicts and loop unrolling.
See this presentation for more info:
http://www.gpgpu.org/sc2007/SC07_CUDA_5_Optimization_Harris.pdf

A: OpenCL is an effort to make a cross-platform library capable of programming code suitable for, among other things, GPUs.  It allows one to write the code without knowing what GPU it will run on, thereby making it easier to use some of the GPU's power without targeting several types of GPU specifically.  I suspect it's not as performant as native GPU code (or as native as the GPU manufacturers will allow) but the tradeoff can be worth it for some applications.
It's still in its relatively early stages (1.1 as of this answer), but has gained some traction in the industry - for instance it is natively supported on OS X 10.5 and above.

A: Check out CUDA by NVidia, IMO it's the easiest platform to do GPU programming. There are tons of cool materials to read.
[http://www.nvidia.com/object/cuda_home.html][1]
[1]: http://www.nvidia.com/object/cuda_home.html

Hello world would be to do any kind of calculation using GPU.

A: Take a look at the ATI Stream Computing SDK. It is based on BrookGPU developed at Stanford.
In the future all GPU work will be standardized using OpenCL. It's an Apple-sponsored initiative that will be graphics card vendor neutral.

A: CUDA is an excellent framework to start with. It lets you write GPGPU kernels in C. The compiler will produce GPU microcode from your code and send everything that runs on the CPU to your regular compiler. It is NVIDIA only though and only works on 8-series cards or better. You can check out CUDA zone to see what can be done with it. There are some great demos in the CUDA SDK. The documentation that comes with the SDK is a pretty good starting point for actually writing code. It will walk you through writing a matrix multiplication kernel, which is a great place to begin.

A: Another easy way to get into GPU programming, without getting into CUDA or OpenCL, is to do it via OpenACC.
OpenACC works like OpenMP, with compiler directives (like #pragma acc kernels) to send work to the GPU. For example, if you have a big loop (only larger ones really benefit):
int i;
float a = 2.0;
float b[10000];
#pragma acc kernels
for (i = 0; i < 10000; ++i) b[i] = 1.0f;
#pragma acc kernels
for (i = 0; i < 10000; ++i) {
  b[i] = b[i] * a;
}

Edit: unfortunately, only the PGI compiler really supports OpenACC right now, for NVIDIA GPU cards.

A: Try GPU++ and libSh
LibSh link has a good description of how they bound the programming language to the graphics primitives (and obviously, the primitives themselves), and GPU++ describes what its all about, both with code examples.

A: If you use MATLAB, it becomes pretty simple to use GPU's for technical computing (matrix computations and heavy math/number crunching). I find it useful for uses of GPU cards outside of gaming. Check out the link below:
http://www.mathworks.com/discovery/matlab-gpu.html

A: *

*You get programmable vertex and
pixel shaders that allow execution
of code directly on the GPU to
manipulate the buffers that are to
be drawn. These languages (i.e.
OpenGL's GL Shader Lang and High
Level Shader Lang and DirectX's equivalents
), are C style syntax, and really
easy to use. Some examples of HLSL
can be found here for XNA game
studio and Direct X. I don't have
any decent GLSL references, but I'm
sure there are a lot around. These
shader languages give an immense
amount of power to
manipulate what gets drawn at a per-vertex
or per-pixel level, directly
on the graphics card, making things
like shadows, lighting, and bloom
really easy to implement.

*The second thing that comes to mind is using
openCL to code for the new
lines of general purpose GPU's. I'm
not sure how to use this, but my
understanding is that openCL gives
you the beginnings of being able to
access processors on both the
graphics card and normal cpu. This is not mainstream technology yet, and seems to be driven by Apple.

*CUDA seems to be a hot topic. CUDA is nVidia's way of accessing the GPU power. Here are some intros


text:
Q: NumPy PolyFit and PolyVal in Multiple Dimensions? Assume an n-dimensional array of observations that are reshaped to be a 2d-array with each row being one observation set.  Using this reshape approach, np.polyfit can compute 2nd order fit coefficients for the entire ndarray (vectorized):
fit = np.polynomial.polynomialpolyfit(X, Y, 2)

where Y is shape (304000, 21) and X is a vector.  This results in a (304000,3) array of coefficients, fit.
Using an iterator it is possible to call np.polyval(fit, X) for each row.  This is inefficient when a vectorized approach may exist.  Could the fit result be applied to the entire observation array without iterating?  If so, how?
This is along the lines of this SO question.

A: np.polynomial.polynomial.polyval takes multidimensional coefficient arrays:
>>> x = np.random.rand(100)
>>> y = np.random.rand(100, 25)
>>> fit = np.polynomial.polynomial.polyfit(x, y, 2)
>>> fit.shape # 25 columns of 3 polynomial coefficients
(3L, 25L)
>>> xx = np.random.rand(50)
>>> interpol = np.polynomial.polynomial.polyval(xx, fit)
>>> interpol.shape # 25 rows, each with 50 evaluations of the polynomial
(25L, 50L)

And of course:
>>> np.all([np.allclose(np.polynomial.polynomial.polyval(xx, fit[:, j]),
...                     interpol[j]) for j in range(25)])
True

A: np.polynomial.polynomial.polyval is a perfectly fine (and convenient) approach to efficient evaluation of polynomial fittings.
However, if 'speediest' is what you are looking for, simply constructing the polynomial inputs and using the rudimentary numpy matrix multiplication functions results in slightly faster ( roughly 4x faster) computational speeds.
Setup
Using the same setup as above, we'll create 25 different line fittings.
>>> num_samples = 100000
>>> num_lines = 100
>>> x = np.random.randint(0,100,num_samples)
>>> y = np.random.randint(0,100,(num_samples, num_lines))
>>> fit = np.polyfit(x,y,deg=2)
>>> xx = np.random.randint(0,100,num_samples*10)

Numpy's polyval Function
res1 = np.polynomial.polynomial.polyval(xx, fit)

Basic Matrix Multiplication
inputs = np.array([np.power(xx,d) for d in range(len(fit))])
res2 = fit.T.dot(inputs)

Timing the functions
Using the same parameters above...
%timeit _ = np.polynomial.polynomial.polyval(xx, fit)
1 loop, best of 3: 247 ms per loop

%timeit inputs = np.array([np.power(xx, d) for d in range(len(fit))]);_ = fit.T.dot(inputs)
10 loops, best of 3: 72.8 ms per loop

To beat a dead horse...

mean Efficiency bump of ~3.61x faster. Speed fluctuations probably come from random computer processes in background.


text:
Q: How do I know if a BigQuery query is purning partitions or not? I am issuing a query on a BigTable table and have a WHERE clause on the partition column which I'm confident is pruning the partitions (which is good).
select *
from `project_id.dataset_id.table_id`
where dateTimeCreated >= '2021-11-27' --partition column
  and emailAddress = 'thing@example.com'

I'm keen to understand more about what is going on internally though. I was hoping the query plan (shown in "Execution details" in the BigQuery console) would explicitly state that its only consuming from one partition however that information doesn't seem to be available. All I see for the READ operation of stage S00 is:
FROM project_id.dataset_id.table_id
WHERE and(greater_or_equal($6, 1637971200.000000000), equal($30, 'thing@example.com'))

I know from the number of rows output from this stage that it is only retrieving from one partition however I would have hoped to see some information about this in the query plan. For a more complicated query than this its going to be really important to know which partitions are being queried,how many partitions are being queried, or at least know whether or not partition pruning is occurring.
Is this information available anywhere?


text:
Q: Difference between a Byte, Word, Long and a Long Word? I'm aware that a Byte is 8 bits, but what do the others represent? I'm taking an assembly course which uses a Motorola 68k Architecture, and I'm confused on the vocabulary present.

A: As mentioned on the first page of the operator's manual for the 68k Architecture, in your case a word is 16 bits and a long word is 32 bits.
In an assembly language, a word is the CPU's natural working size. Each instruction, as well as addresses in memory, tend to be one word in length. Whereas a byte is always 8 bits, the size of a word depends on the architecture you're working in.


text:
Q: Known Correlation between predictors I have two predictors and an outcome, let's call them x, y and z. I know that x and y are correlated with correlation r.
I am trying to construct a linear model:
z = ax + by + c
I have an expectation of what a and b should be based on how they are generated if x and y were not correlated. However, this correlation is causing my model to give me different results. What is the best/simplest/quickest method to eliminate the correlation and/or adjust for it.
The two options I can see would be either a third variable as an adjustment term (derived from the known correlation) or a method to transform x and y to be orthogonal. What methods could I use to achieve this?

A: I think it depends on the importance of the correlation. It is difficult to avoid any correlation between two explanatory variables (e. g. blood pressure and weight are related but can be included in the same model). On the other hand, some variables can be created to avoid putting two variables that are too correlated (e. g. BMI to take into account height and weight at the same time).


text:
Q: .xcworkspace wasn't found after pod install with no error message I am a newbie in cocoapods and I would be appreciated if you help.
Today I want to use cocoapods to manager my dependencies in my project.
So my Profile is:
platform :ios, '8.0'

target 'TargetName' do
pod 'AFNetworking', '~> 3.0'
end

But after running pod install, I got the message as follow:
pod install
Analyzing dependencies
Downloading dependencies
Installing AFNetworking (3.1.0)
Generating Pods project
[1]    53417 abort      pod install

After that, I can't find the TargetName.xcworkspace and the Podfile.lock but the Pods folder is there.
That's weird because there are no more error messages here.
I installed the cocoapods exactly according to the official guides. And here are the environments:

*

*pod: 1.1.1

*ruby: 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin16]

*gem: 2.6.8

*Xcode: 8.2.1

Thank you very much!

A: Finally I upgrade cocoapods(now Version 1.2.0.beta.1) and solve my problem.


text:
Q: Grouping items into first occurances I totally can't get my head around writing a correct query for my problem this morning so here's hoping that someone out there can help me out.
I have a database table called Sessions which basically looks like this
Sessions:
  SessionID
  SessionStarted
  IPAddress
  ..other meta data..

I have a requirement where I am to show how many new Sessions (where new is defined as from a previously unseen IPAddress) arrive each day over a given period. Basically, each IPAddress should count only once in the results, namely for the day of the first session from the IPAddress. So I'm looking for a result like:
[Date]      [New]
2009-10-01 : 11
2009-10-02 : 6
2009-10-03 : 19
..and so on

...which I can plot on some nice chart and show to important people. I would very much prefer a Linq2SQL query as that is what we are currently using for data access, but if I'm out of luck I may be able to go with some raw SQL (accessed via stored procedure, but I would really, really, really prefer Linq2SQL).
(As a bonus my next step will very likely be qualifying which sessions should be included by filtering on some of the other meta data)
Hoping that someone clever will help me out here...

A: I would use something like this.
var result = data.OrderBy(x => x.SessionStarted)
    .GroupBy(x => x.IPAddress)
    .Select(x => x.First())
    .GroupBy(x => x.SessionStarted.Date)
    .Select(x => new { Date = x.Key, New = x.Count() });


text:
Q: How can I use Pymongo Aggregation to inquiry this dataset? This is my first time use MongoDB aggregation query. The dataset I have is as follow:
{ // doc 1
    "_id" : ObjectId("55f2481bc9b4cd1c0c198c9f"),
    "channels" : [
        "channel_3",
        "channel_2",
        "channel_1",
        "channel_4"
    ],
    "msd" : 25,
    "uid" : "000012bb-2e5a-8bd3-d36a-fa037973e632"
}
{ // doc 2
    "_id" : ObjectId("55f2481bc9b4cd123452345f"),
    "channels" : [
        "channel_3",
        "channel_4"
    ],
    "msd" : 50,
    "uid" : "000012bb-2e5a-8bd3-d36a-fa037973e632"
}
{ // doc 3
    "_id" : ObjectId("55f2481bc9b4cd1c0c198c9f"),
    "channels" : [
        "channel_2"
    ],
    "msd" : 100,
    "uid" : "000012bb-2e5a-8bd3-d36a-fa037973e632"
}
{ // doc 4
    "_id" : ObjectId("55f2481bc9b4cd1c0c198c9f"),
    "channels" : [
        "channel_2"
    ],
    "msd" : 80,
    "uid" : "000012bb-2e5a-8bd3-d36a-fa037973e632"
}

I have built a compound index:
userlog.create_index([('uid', ASCENDING), ('channels', ASCENDING)])

Now, given a user and an array of channels, I want to retrieve the average of msd whose at least one channel is in the query channels.
For instance, a query is:
{"uid" : "000012bb-2e5a-8bd3-d36a-fa037973e632", "channels" : ["channel_1", "channel_2"], }

The channels of doc 1 contains "channel_1" and "channel_2" and the channels of doc 3 and 4 contains "channels_2". So the expected return value is (25+100+80)/3 = 68.33
====================== TRIAL 1 =======================
CODE:
pipe=[
    {"$unwind":'$channels'},
    {"$match":{'uid':"000012bb-2e5a-8bd3-d36a-fa037973e632", 'channels':{'$in':channels}}},
    {"$group":{'_id': '$channels', 'averageMSD':{'$avg':'$msd'}}}
    ]

for res in db.aggregate(pipeline=pipe):
    print(res)

RESULT:
{'_id': 'channel_1', 'averageMSD': 25.0}
{'_id': 'channel_2', 'averageMSD': 68.33333333333333}

It seems that "$unwind" makes the doc 1 is unexpectedly counted twice. Also, "$unwind" is quite slow.
====================== TRIAL 2 =======================
CODE:
pipe=[
    {"$match":{'uid':"000012bb-2e5a-8bd3-d36a-fa037973e632", 'channels':{'$in':channels}}},
    {"$group":{'_id': '$channels', 'averageMSD':{'$avg':'$msd'}}}
    ]

for res in db.aggregate(pipeline=pipe):
    print(res)

RESULT:
{'averageMSD': 90.0, '_id': ['channel_2']}
{'averageMSD': 25.0, '_id': ['channel_3', 'channel_2', 'channel_1', 'channel_4']}

The result is still not what I want. It seems that I should not group the result by "channels". But I do not how I can fix it.
How can I use aggregation to inquire the DB efficiently?

A: I figured it out:
pipe=[
    {"$match":{'uid':"000012bb-2e5a-8bd3-d36a-fa037973e632", 'channels':{'$in':channels}}},
    {"$group":{'_id': None, 'averageMSD':{'$avg':'$msd'}}}
    ]


text:
Q: focus() not working for a select box(dropdown) On some particular event i want to focus on a particular select box. But
document.getElementById('myselect').focus()

is not working. It is working fine for a text input but not for a select box.

A: Are you sure that it isn't focusing?
I just ran a quick test on jsFiddle with the following code - jsFiddle:
<select name="dropdown" id="dropdown">
    <option value="1">One</option>
    <option value="2">two</option>
</select>

<input type="text" id="textfield" /><br />

    <button id="clickme"
         onclick="javascript: document.getElementById('dropdown').focus()">
            focus dropdown</button>
    <button id="clickme1"
         onclick="javascript: document.getElementById('textfield').focus()">
        focus textfield</button>

 Pressing the "Focus Dropdown" button does set the focus to the drop down field, but it doesn't actually appear to do anything.  The dropdown field isn't highlighted, although if I press the arrow keys, different values will be selected.

A: it should work and its working.. check the fiddle
--html--
<select id="dpk">
    <option> first </option>
    <option> second </option>
    <option> third </option>
</select>
<input type="button" value="focus Dropdown" id="btn" onclick="my_method()" />

--javscript---
function my_method()
{
    document.getElementById('dpk').focus();
}


text:
Q: How to rename package "AndroidTest" in Android Studio enter image description hereI got a ready resource and wanted to rename the AndroidTest folder just as I renamed the others, but every time I click on "refactor" and "rename" nothing happens

A: Follow the following steps to do it:

*

*In your Project pane, click the little settings icon on the right & uncheck/De-select the Compact Empty Middle Packages option like this:

*

*Select the individual directories created from the package & select refactor by performing a right-click on it & rename. Choose Rename All when required like this:

*

*Open up app-level build.gradle and change the applicationId field inside defaultConfig with your new package name and sync like I changed it to newone below in my build.gradle file:

Hope this helps!


text:
Q: The output is right but the codechef not accepting, What is wrong in my code? Is my logic wrong? #include <stdio.h>

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int app,ora,coins,rem;
        scanf("%d %d %d",&app,&ora,&coins);
        if(app!=ora)
        {
            while(coins>0)
            {
                if(app<=ora)
                {
                    app++;
                    coins--;
                }
                else if(ora<=app)
                {
                    ora++;
                    coins--;
                }
            }
            if(app>=ora)
            {
                printf("%d",app-ora);
            }
            else if(ora>=app)
            {
                printf("%d",ora-app);
            }
        }
    }
    return 0;
}

Context:
to have the minimum possible difference between the number of apples and oranges he has. To do so, he can purchase 1 apple or 1 orange by paying exactly 1 gold coin (that's some expensive fruit, eh?). Chef can purchase fruits at most K times (as he has only K gold coins in his pocket) to make the difference the minimum possible.
Input:
4
3 4 1
5 2 1
3 4 3
6 11 3
Output:
0
2
0
2


text:
Q: Webpack чанки. Как подключить только свои js и css файлы в html файлы?

const path = require('path')
const fs = require('fs')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const webpack = require('webpack')

const PATHS = {
  src: path.join(__dirname, '../src'),
  dist: path.join(__dirname, '../dist'),
  site_pages: path.join(__dirname, '../src/components/site-pages'),
  assets: 'assets/'
}

const PAGES_DIR = `${PATHS.src}/pages`
const PAGES = fs.readdirSync(PAGES_DIR).filter(filename => filename.endsWith('.pug'))

module.exports = {
  externals: {
    paths: PATHS
  },
  entry: {
    app: PATHS.src,
    "room-details": `${PATHS.site_pages}/room-details/room-details.js`,
  },
  output: {
    filename: `${PATHS.assets}js/[name].[hash].js`,
    path: PATHS.dist,
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: {
          name: 'vendors',
          test: /node_modules/,
          chunks: 'all',
          enforce: true
        }
      }
    }
  },
  module: {
    rules: [{
      test: /\.pug$/,
      loader: 'pug-loader'
    }, {
      test: /\.js$/,
      loader: 'babel-loader',
      exclude: '/node_modules/'
    }, {
      test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
      loader: 'url-loader',
      options: {
        outputPath: "assets/fonts",
        publicPath: "../fonts",
        name: '[name].[ext]',
        limit: 1000
      }
    }, {
      test: /\.(png|jpg|gif|svg)$/,
      loader: 'url-loader',
      options: {
        name: '[name].[ext]'
      }
    }, {
      test: /\.scss$/,
      use: [
        'style-loader',
        MiniCssExtractPlugin.loader,
        {
          loader: 'css-loader',
          options: {
            sourceMap: true
          }
        }, {
          loader: 'postcss-loader',
          options: {
            sourceMap: true,
            config: {
              path: `./postcss.config.js`
            }
          }
        }, {
          loader: 'sass-loader',
          options: {
            sourceMap: true
          }
        }
      ]
    }]
  },
  resolve: {
    alias: {
      '~': 'src'
    }
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      '$': 'jquery',
      jquery: 'jquery',
      jQuery: 'jquery',
      'window.jquery': 'jquery',
      'window.jQuery': 'jquery',
    }),
    new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: `${PATHS.assets}css/[name].[hash].css`,
    }),
    new CopyWebpackPlugin([{
        from: `${PATHS.src}/components/**/*.{jpg,jpeg,png,svg,gif}`,
        to: `${PATHS.assets}img`,
        flatten: true
      },
      {
        from: `${PATHS.src}/static`,
        to: ''
      },
    ]),

    ...PAGES.map(
      page =>
      new HtmlWebpackPlugin({
        template: `${PAGES_DIR}/${page}`, // .pug
        filename: `./${page.replace(/\.pug/,'.html')}` // .html
      })
    )
  ],
}
<!DOCTYPE html>
<html lang="ru">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Menu</title>
  <meta name="description" content="navigation page">
  <link href="assets/css/vendors.25026dde96cf2da3a1b5.css" rel="stylesheet">
  <link href="assets/css/app.25026dde96cf2da3a1b5.css" rel="stylesheet">
  <link href="assets/css/room-details.25026dde96cf2da3a1b5.css" rel="stylesheet">
</head>

<body>
  <!-- code -->
  <script type="text/javascript" src="assets/js/vendors.25026dde96cf2da3a1b5.js"></script>
  <script type="text/javascript" src="assets/js/app.25026dde96cf2da3a1b5.js"></script>
  <script type="text/javascript" src="assets/js/room-details.25026dde96cf2da3a1b5.js"></script>
</body>

</html>

room-details.css и room-details.js файлы добавляются в index.html и файлы всех остальных страниц тоже, но в нём не должно их быть, они должны добавляться только в room-details.html
сейчас:
//page-name.html
app
vendors
page-name
page-name2
page-name3
...
page-nameN

должно быть:
//page-name.html
app
vendors
page-name

Как это сделать?

A: Нужно добавить в HtmlWebpackPlugin ключ chunks, например:
chunks: ['page1', 'page2', 'page3'...],


text:
Q: Codeigniter not uploading image Problem
I have form for registring students. Now I am trying to insert data with uploading image however to database comes only file name. Uploads file is empty! My view form input type is 'file'.
Controller
$config['upload_path'] = APPPATH.'uploads';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '100';
    $config['max_width']  = '1024';
    $config['max_height']  = '768';
    $this->upload->do_upload('image');
    $this->load->library('upload',$config);

    if($this->form_validation->run())
    {
        $data = array(
            'student_name'=>$this->input->post('name'),
            'student_surname'=>$this->input->post('surname'),
            'student_middlename'=>$this->input->post('middlename'),
            'student_birth'=>$this->input->post('date'),
            'student_add_date' => date('Y-m-d'),
            'student_gender'=>$this->input->post('gender'),
            'student_addres'=>$this->input->post('address'),
            'student_mobile'=>$this->input->post('phone'),
            'student_email'=>$this->input->post('email'),
            'student_image'=>$this->upload->do_upload('image')

        );

        $this->member->add_student($data);
        redirect('members/student_list');
    }

A: You can do just this,
$config['upload_path'] = 'uploads/';

A: Please provide below statement instead of  $config['upload_path'] = APPPATH .'uploads';
$config['upload_path'] = './uploads/';

And also ensure that your uploads folder created in the outside of application folder

A: try this code :
if($this->form_validation->run())
{
      //configure and load upload library
        $config['upload_path'] =getcwd().'/uploads';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '10000';
        $config['max_width']  = '1024';
        $config['max_height']  = '768';

        $this->load->library('upload',$config);

   //if can't upload image exit the function
    if (!$this->upload->do_upload('image')) {
        $error = $this->upload->display_errors();
        //use var_dump only developing environment
        var_dump($this->upload->display_errors());
       // exit();
    }

    $data = array(
        'student_name'=>$this->input->post('name'),
        'student_surname'=>$this->input->post('surname'),
        'student_middlename'=>$this->input->post('middlename'),
        'student_birth'=>$this->input->post('date'),
        'student_add_date' => date('Y-m-d'),
        'student_gender'=>$this->input->post('gender'),
        'student_addres'=>$this->input->post('address'),
        'student_mobile'=>$this->input->post('phone'),
        'student_email'=>$this->input->post('email'),
        // 'student_image'=>$this->upload->do_upload('image'),

    );

    $this->member->add_student($data);
    redirect('members/student_list');
}

A: change/edit your .htaccess file to :
              <IfModule mod_rewrite.c>
                 RewriteEngine On
                 RewriteCond %{REQUEST_FILENAME} !-d
                  RewriteCond %{REQUEST_FILENAME} !-f
                  RewriteRule ^(.*)$ index.php/$1 [QSA,L]
              </IfModule>

then in your controller set:
                  $upload_dir = 'upload_folder';
                  $config['upload_path'] =  $upload_dir ;
                  $config['allowed_types'] = 'gif|jpg|jpeg|png';
    $config['max_size'] = '10000';
    $config['max_width'] = '1024';
    $config['max_height'] = '768';

    $this->load->library('upload',$config);


text:
Q: PHP forking php-fpm with pcntl_fork() I'm forking with this code:
echo "1. posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";

$pid = pcntl_fork();
var_dump($pid);
if ($pid == -1) die("could not fork");

if ($pid) {
//parent
echo "2. pid=".$pid.", posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";
} else {
//child
$sid = posix_setsid();

if ($sid < 0)
exit;

echo "3. pid=".$pid.", posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";

$fp = fopen("/tmp/testfile", "w");
fwrite($fp, '$data');
fclose($fp);

}

For some reason sometimes the else block is sent to the browser, and sometimes the if ($pid) block is displayed.
What I'm trying to achieve is to send some response, and then continue processing after the connection with the client has closed. Then finally close after the post-request processing is finished. If I sleep in the child or parent the request hangs there.
Both parts are being executed though, it's just being weird in determining which on is sent to the browser.
Thanks in advance.

A: Actually you should use fastcgi_finish_request() to send the response to the browser, then continue working in the background. Keep in mind though, that this ONLY works when using PHP-FPM.
Note: the fastcgi_finish_request() function isn't documented in the PHP manual (see bug 61449) but the usage is pretty straight forward.
As for ignore_user_abort(), some comments on php.net suggest using the Content-Length: 0 header with it, but this will cause problems when using SSL in conjunction with Internet Explorer.

A: Consider using ignore_user_abort() instead.


text:
Q: The name "MvxWindowsPage" does not exist in the namespace "using:Cirrious.MvvmCross.WindowsUWP.Views" I am starting working with MVVMCross.
I had created the View and view model.
The View.xaml look like that:
<views:MvxWindowsPage
x:Class="xxx.Client.UWP.Views.View1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:Cirrious.MvvmCross.WindowsUWP.Views"
mc:Ignorable="d">

But I get this error:
The name "MvxWindowsPage" does not exist in the namespace "using:Cirrious.MvvmCross.WindowsUWP.Views"

But in my View.xaml.cs i had inherited from it without error:
    public sealed partial class View1 : Cirrious.MvvmCross.WindowsUWP.Views.MvxWindowsPage

Do you know what the problem is?
Thanks.

A: I tested it with MvvmCross 4.0.0-beta3, and it works without any problem.
If you are using the correct version, see if you can repro the issue using the following steps. Just want to make sure we are doing the same thing.

*

*In Visual Studio 2015 RTM-> new-> project-> c#-> windows-> universal-> Blank App(Universal Windows) name it "Test.Client.UWP".

*Right click on the project node in VS solution explorer -> Manage NuGet Packages -> Check "include prerelease" and search mvvmcross -> Select the Latest prerelease 4.0.0-beta3 and install. (make sure there is no error in output window)

*Add Views folder in the project root -> Add a blank page named View1 -> do the following changes:
Change to View1.xaml.cs
namespace Test.Client.UWP.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class View1 : Cirrious.MvvmCross.WindowsUWP.Views.MvxWindowsPage
    {
        public View1()
        {
            this.InitializeComponent();
        }
    }
}

Change to View1.xaml
<views:MvxWindowsPage
    xmlns:views="using:Cirrious.MvvmCross.WindowsUWP.Views"
    x:Class="Test.Client.UWP.Views.View1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Test.Client.UWP.Views"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    </Grid>
</views:MvxWindowsPage>


text:
Q: Apache "Module mod_alias does not exist" I installed apache on Debian:
sudo apt-get install apache2 apache2-utils

and ran
a2enmod cgi alias env

I want to use ScriptAlias command. However I get the message Command is missing.
I find this answer
where suggestion was made that I should use
a2enmod mod_alias

When I use it I get the message
Module mod_alias does not exist

Do you have any suggestions how to solve this ?
I try to configure git with these instructions.

A: Under debian, you can load the mod_alias module using:
$ sudo a2enmod alias

You should see two symbolic links alias.conf and alias.load in the folder /etc/apache2/mods-enabled.
After running this command, make sure that your current httpd configuration is correct using the following command:
$ sudo apache2ctl configtest

If no error message appears, restart the httpd server in order to activate this configuration change:
$ sudo service apache2 restart


text:
Q: JVectorMap Multimap drill down has different style when drilled down, how can I change this style as well? This question was asked here as well maybe a year ago, but no answer was provided. I'd like to know how I can make the "drilled-down" map have the same style and background as my main map.
var regionStyling9 = {                  // This style is set to the main map's regionStyle
        initial: {
            fill: '#E9E9E9',
            stroke: '#505050',
            "fill-opacity": 1,
            "stroke-width": 1,
            "stroke-opacity": 1
        },
        hover: { fill: "#4DB870" }
    };

    $(function() {
        new jvm.MultiMap({
            container: $('#Chart9Map'),
            maxLevel: 1,
            main: {
                map: 'us_aea_en',
                backgroundColor: '#fff',
                regionStyle: regionStyling9,     // Here I set the top level style to the main map
                series: {
                    regions: [{ values: stateMapData, scale: ['#cce2ec', '#006593'], normalizeFunction: 'polynomial' }]
                }
            },
            mapUrlByCode: function(code, multiMap) {
                return '../Scripts/JVectorMap/jquery-jvectormap-data-' +
                    code.toLowerCase() +
                    '-' +
                    multiMap.defaultProjection +
                    '-en.js';
            }
        });
    });

How can I affect the style of the secondary chart like I did for the main chart?
According to the jVectorMap MultiMap Documentation, there is only config for the main map, no other object for the drill down maps...

A: I know what you mean, I also could not find this info. It is very strange the library doesnt handle this. Its such a well produced package, yet seems to me missing some basics.
Assuming you arent using the free version, the license says you are allowed to modify the code.
Open up the jquery-jvectormap.js file (prettify it is needed).
At the bottom you'll see the lines:
   currentMap.params.container.hide(), that.maps[name] ? that.maps[name].params.container.show() : that.addMap(name, {
        map: name,
        multiMapLevel: currentMap.params.multiMapLevel + 1
    }), that.history.push(that.maps[name]), that.backButton.show()

Change this so settings from the main map are passed down to the children (so just add the 3 extra lines):
   currentMap.params.container.hide(), that.maps[name] ? that.maps[name].params.container.show() : that.addMap(name, {
        backgroundColor: that.params.main.backgroundColor,
        series: that.params.main.series,
        onRegionTipShow: that.params.main.onRegionTipShow,
        map: name,
        multiMapLevel: currentMap.params.multiMapLevel + 1


text:
Q: How to properly wrap a Functional Component into a React HOC I am building some web pages in nextjs and I need to make sure certain pages can only be accessed if the user has been authenticated as below:
import UserManager from "../managers/user_manager";
import { useRouter } from "next/router";
import LogInPage from "../pages/auth/login";

export default function EnsureAuthenticated(OriginalComponent) {
    const router = useRouter();
    const loggedInUser = UserManager.getLoggedInUser();
    if (loggedInUser ) {
        return <OriginalComponent />;
    }
    return router.push(LogInPage.routePath);
}

And here is my dashboard page that I need to wrap with the above HOC to enforce authentication
import { useEffect } from "react";
import { useRouter } from "next/router";
import EnsureAuthenticated from "../../components/auth_hoc";

function DashboardHomePage(props) {
    const router = useRouter();
    return (

        Home Page

);
}
DashboardHomePage.routePath = "/dashboard/home";
export default EnsureAuthenticated();

Unfortunately for me I keep getting this error after compiling in NextJS
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

Please, how do I resolve this?
Thank you.

A: You aren't  passing DashboardHomepage component to HOC .
HOC code has to changed , we cannot use hooks in HOC body because we are calling HOC as a function instead of a component. When we  call a component as a function react excludes all the lifecycles from that.
There is also an issue with the usage of router in your code, as in nextjs if we use it in render it will be rendered and client side and server side.
You may have to create a component which will do routing in useEffect and use it instead of router.push(LogInPage.routePath)
import React from "react";
import UserManager from "../managers/user_manager";
import { useRouter } from "next/router";
import LogInPage from "../pages/auth/login";

export default function EnsureAuthenticated(OriginalComponent) {
  return (props) => {
    const router = useRouter();
const loggedInUser = UserManager.getLoggedInUser();
    if (loggedInUser ) {
        return <OriginalComponent />;
    }
//below code can give error as router is supposed to be called only at client side, you might have to implement it using useEffect
    return router.push(LogInPage.routePath);
  };
}

import { useRouter } from "next/router";
import EnsureAuthenticated from "../components/test/AddCount";

function DashboardHomePage(props) {
  const router = useRouter();
  return
Home Page
;
}

DashboardHomePage.routePath = "/dashboard/home";

export default EnsureAuthenticated(DashboardHomePage);


text:
Q: How to save array data from multiple select in Laravel using Eloquent i'd like to save data from multiple select to the database. So a user can choose more than one products in a multiple select. I've tried the code like below but i got this error "ErrorException Array to string conversion".
Here is my blade.php

Barang

        <select class="form-control m-select2" width="500px" id="kt_select2_1" name="id_product[]" multiple="multiple">
                <option value=""></option>
                @foreach($produk as $p)
                <option value="{{ $p->id }}">{{ $p->product }}</option>
                @endforeach
        </select>

and here is my controller
$id_promo = Promo::select('id')
   ->where('delete', 0)->orderBy('created_at', 'DESC')
   // ->take(1)
   ->pluck('id')->first();

   $id_product = [];
   $id_product[] = $request->id_product;

   // $id_products = $id_product['id_product'];

   foreach ($id_product as $i) {
           DetailPromo::create([
           'id_promo' => $id_promo,
           'id_product' => $i,
           'det_potongan' => $request->potongan,
           'det_jumlah_potongan' => $request->jumlah_potongan
       ]);
       }

Any helps will be appreciated, thank you so much

A: Try below code:
$id_promo = Promo::select('id')
    ->where('delete', 0)
    ->orderBy('created_at', 'DESC')
    // ->take(1)
    ->pluck('id')
    ->first()
;

$id_products = $request->id_product;
foreach ($id_products as $id_product) {
    DetailPromo::create([
        'id_promo' => $id_promo,
        'id_product' => $id_product,
        'det_potongan' => $request->potongan,
        'det_jumlah_potongan' => $request->jumlah_potongan
    ]);
}


text:
Q: How to hide a Div when the scroll bar is moving with jQuery? I just want the #menu to fade when the scroll bar is moving to provide a less cluttered interface. Is there code that would allow this?
I guess basically what I'm looking for is how to grab the scroll bar movement event. To slowly fade out the #menu after 1 seconds of scrolling and bring back the #menu after 2 second of scroll-bar inactivity.
Thank you so much!

A: var $menu = $("#menu");
var opacity = $menu.css("opacity");
var scrollStopped;

var fadeInCallback = function () {
    if (typeof scrollStopped != 'undefined') {
        clearInterval(scrollStopped);
    }

    scrollStopped = setTimeout(function () {
        $menu.animate({ opacity: 1 }, "slow");
    }, 2000);
};

$(window).scroll(function () {
    if (!$menu.is(":animated") && opacity == 1) {
        $menu.animate({ opacity: 0 }, "slow", fadeInCallback);
    } else {
        fadeInCallback.call(this);
    }
});

http://jsfiddle.net/zsnfb/9/
This sets the scroll event to do a few things. First it clears a timeout to fade the menu div back in. After that, if the menu isn't already faded out, it fades the menu out and sets the timeout in the callback. If the menu is already faded out, it just sets the timeout. If the user stops scrolling, the menu will fade back in after 2 seconds.
There are other solutions that use fadeOut() and fadeIn(). My only issue with those functions in this case is that setting display: none; to the menu div will affect the layout of the page, where setting visibility: hidden; or opacity: 0; shouldn't affect the layout.

A: Right using the following:
$('body').scroll(function(){
    $('#menu').fadeOut();

    var scrollA = $('body').scrollTop();

    setTimeout(function(){
        if(scrollA == $('body').scrollTop()){
            $('#menu').fadeIn();
        }
    }, 200);
})

So we record the scroll amount, wait 200 milliseconds and then see if the scroll has changed, if not we fade the menu back in.

A: I think this is what you are looking for http://jsfiddle.net/wfPB6/


text:
Q: Invoke EJB Remote Bean in Web App I have just begun reading up on EJBs.
Is it possible invoke remote bean in seperate web app (war)? if its possible how to achieve it. I tried it, web app can invoke remote bean if both in same EAR but i want invoke it in separate EJB + WAR.
ps. I use glassfish 4.0

A: For glassfish you can try this:
https://glassfish.java.net/javaee5/ejb/EJB_FAQ.html#StandaloneRemoteEJB
Below my example for weblogic.
1) in your EAR you should have @remote annotated interface and it's implementation
@Remote
public interface Calculator {

    public int add(int a, int b);

}

@Stateless(mappedName = "myCalculator")
public class CalculatorImpl implements Calculator {
    @Override
    public int add(int a, int b) {
      return a + b;
    }
}

2) you should have a Client which will call your remote calculator
private static Calculator getRemoteCalculator() {
    Hashtable<String, String> props = new Hashtable<String, String>();

    props.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
    props.put(Context.PROVIDER_URL, "t3://localhost:7001");

    try {
        InitialContext ctx = new InitialContext(props);
        return (Calculator) ctx.lookup("myCalculator#com.javaee.Calculator");
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

3) for Client you should add your remote Calculator EJB module to build pass


text:
Q: Parsing Firebase JSON F# I'm trying to convert the following Firebase JSON into something that can be parsed in F#:
{
   "listings":{
      "-L0pJmU9yj4hAocHjnrB":{
         "listing_id":"-L0pJmU9yj4hAocHjnrB",
         "location":"Edinburgh",
         "messages":{
            "SWs56OIGzMdiCjSXahzDQX8zve92":{
               "-L3ELSSzZPRdjCRcFTrb":{
                  "senderId":"SWs56OIGzMdiCjSXahzDQX8zve92",
                  "senderName":"alberto",
                  "text":"Hi"
               },
               "-L3EN1NW5hHWBTEGC9ve":{
                  "senderId":"YMM45tgFFvYB7rx9PhC2TE5eW6D2",
                  "senderName":"David",
                  "text":"Hey"
               }
            }
         }
      },
      "-L19C5OjcDSjMi4-oha-":{
         "listing_id":"-L19C5OjcDSjMi4-oha-",
         "location":"Edinburgh"
      },
      "-L19CJrzEpChO_W14YkC":{
         "listing_id":"-L19CJrzEpChO_W14YkC",
         "location":"Edinburgh",
         "messages":{
            "Rp7ytJdEvZeMFgpLqeCSzkSeTyf1":{
               "-L19V4QpPMCMwGcNaQBG":{
                  "senderId":"Rp7ytJdEvZeMFgpLqeCSzkSeTyf1",
                  "senderName":"Albert",
                  "text":"Hey there"
               },
               "-L19r0osoet4f9SjBGE7":{
                  "senderId":"YMM45tgFFvYB7rx9PhC2TE5eW6D2",
                  "senderName":"David",
                  "text":"Hi"
               },
               "-L3ELGAbcOjdJsHRtnAe":{
                  "senderId":"YMM45tgFFvYB7rx9PhC2TE5eW6D2",
                  "senderName":"David",
                  "text":"Icvjv"
               }
            }
         }
      },
      "-L19ChjPjX1DnfQb28AW":{
         "listing_id":"-L19ChjPjX1DnfQb28AW",
         "location":"Edinburgh",
         "messages":{
            "879dUqGuiXSd95QHzfhbSs05IZn2":{
               "-L1i6c7sGf3BcF2cCSCu":{
                  "senderId":"879dUqGuiXSd95QHzfhbSs05IZn2",
                  "senderName":"Alberto",
                  "text":"Hello"
               }
            },
            "Rp7ytJdEvZeMFgpLqeCSzkSeTyf1":{
               "-L19FGCMuQACjYKCFEwV":{
                  "senderId":"Rp7ytJdEvZeMFgpLqeCSzkSeTyf1",
                  "senderName":"Albert",
                  "text":"Hey"
               },
               "-L19T_v2Utxhu1mGhz7-":{
                  "senderId":"YMM45tgFFvYB7rx9PhC2TE5eW6D2",
                  "senderName":"David",
                  "text":"Hi"
               },
               "-L19TbhActGmga4f47Mz":{
                  "senderId":"Rp7ytJdEvZeMFgpLqeCSzkSeTyf1",
                  "senderName":"Albert",
                  "text":"How are you"
               }
            }
         }
      },
      "-L19Cz1abm1o-JCbiAnN":{
         "listing_id":"-L19Cz1abm1o-JCbiAnN",
         "location":"Edinburgh"
      },
      "-L19DMdFx2pXj9-EKCq2":{
         "listing_id":"-L19DMdFx2pXj9-EKCq2",
         "location":"Edinburgh"
      },
      "-L19DV67WjguozFE_4dM":{
         "listing_id":"-L19DV67WjguozFE_4dM",
         "location":"Edinburgh"
      }
   }
}

The problem here is that the entries like L0pJmU9yj4hAocHjnrB in the 2nd line and subsequent similar entries are autogenerated timestamp IDs created in Firebase, and they do not have a corresponding name, like for example: "listing_id":"-L0pJmU9yj4hAocHjnrB", therefore I do not know how to set up my F# Records to correctly parse this JSON.
My attempt can be seen below:
type MessageContent =
    { senderId: string
      senderName: string
      text: string; }

type Message =
     { timestampId : string
       chatMessages : MessageContent;}

type Chat =
    { chatPartnerId : string
      Messages : Message array option;}

type ListingContent =
    { from : string
      landlord_id : string
      listing_id : string
      location : string
      name : string
      pic_1_url : string
      pic_2_url : string
      pic_3_url : string
      pic_4_url : string
      pic_5_url : string
      messages : Chat array option
      postcode : string
      price_per_night : int
      to_date : string;
    }

type Listing =
     { timestampId : string
       listingcontent : ListingContent option;}

type City =
    { city : string
      listings : Listing array option
    }

type AllListings =
    { cities : City array;}

type SearchSettings =
    { from : string
      location : string
      max_price : decimal
      min_price : decimal
      to_date : string;}

type MatchContent =
    { id : string
      location : string;}

type Match =
    {timestampId : string
     matchContent : MatchContent;}

type DeclinedContent =
    { id : string;
      }

type Declined =
    {timestampId : string
     declinedContent : DeclinedContent;}

type ListingUserContent =
    { listing_id : string
      location : string
      messages : Chat array option;
    }

type ListingUser =
    {timestampId : string
     listingUser : ListingUserContent;}

type UserContent =
    { declined: Declined option
      matches : Match option
      search_settings : SearchSettings option
      listings : ListingUser option;
    }

I use the following code for parsing:
    let myCallbackGetChats (reader:IO.StreamReader) url =
    let html = reader.ReadToEnd()
    let reader = new JsonTextReader(reader);
    let serializer = JsonSerializer.Create(JsonSerializerSettings(Converters = [| Types.OptionConverter() |]))
    use stringReader = new StringReader(html)
    use jsonReader = new JsonTextReader(stringReader)
    let listings_json = serializer.Deserialize<Types.UserContent>(jsonReader)
    printfn "%A" listings_json

This produces the following output:
    {declined = null;
 matches = null;
 search_settings = null;
 listings = Some {listing_id = null;
                  location = null;
                  messages = null;};}

As we can see the first listings tag is properly deserialized, however as soon as it sees L0pJmU9yj4hAocHjnrB it doesn't know what that is and the rest of the parsing fails. How can I fix this issue?

A: You can deserialize your JSON with the following F# types:
type MessageContent =
    { senderId: string
      senderName: string
      text: string;
    }

type ListingContent =
    { listing_id : string
      location : string
      messages : Map<string, Map<string, MessageContent>>
      // Add other members as required
    }

type UserContent =
    { listings: Map<string, ListingContent>
      // Add other members as required
    }

And the following line of code:
let listings_json = JsonConvert.DeserializeObject<UserContent>(inputJson)

Notes:

*

*The "listing" object consists of variable property names with a fixed schema for their values.  As explained in Serialization Guide: Dictionaries and Hashtables such objects can be mapped to a .Net dictionary.  In this case I chose the F# Collections.Map<'Key,'Value> class, specifically a Map<string, ListingContent>.

*Similarly, the "messages" object consists of variable property names whose values are a nested level of objects with variable property names, and so can be represented with a Map<string, Map<string, MessageContent>>.

*I simplified the UserContent and ListingContent types by removing members not actually present in the sample JSON.  You can add them back as required.

*Since Json.NET has built-in support for dictionaries, a custom JsonConverter is not required for this solution.
Example working F# fiddle.


text:
Q: CGridView in yii 1.1 sorts date as number rather than date Well Im new to YII 1.1 framework and  I have to debug a code.Here the widget CGridView sorts date as number rather than date. That is 01-02-2017,10-01-2017,15-01-2017,21-12-2016.
It should sort with month and year that is 21-12-2016,10-01-2017,15-01-2017,01-02-2017.
My code for view is following :-
<article class="listBox list-view">
                    <?php
                    $this->widget('zii.widgets.grid.CGridView', array(
                        'id' => 'child-invoice-payments-grid',
                        'htmlOptions' => array('class' => 'table-responsive'),
                        'itemsCssClass' => 'table invoiceTable',
                        'summaryText' => '',
                        'dataProvider' => new CArrayDataProvider($response, array(
                           'id' => 'id',
                            'sort' => array(
                                //'defaultOrder'=>'date_of_payment ASC',
                                'attributes' => array(
                                    'date_of_payment','id', 'payment_mode','type','amount'
                                )
                            ),
                            'pagination' => array(
                                'pageSize' => 10
                            )
                        )),
                        'enablePagination' => true,
                        'pagerCssClass' => 'text-center',
                        'pager' => array(
                            'header' => '',
                            'maxButtonCount' => 4,
                            'firstPageLabel' => '<<',
                            'prevPageLabel' => '<',
                            'nextPageLabel' => '>',
                            'lastPageLabel' => '>>',
                            'pageSize' => 5,
                            'htmlOptions' => array(
                                'class' => 'pagination',
                            )
                        ),
                        'columns' => array(
                            array(
                                'name' => 'id',
                                'type' => 'raw',
                                'header' => 'Transaction ID',
                                'value' => 'CHtml::link($data["id"], $data["url"])'
                            ),
                            **array(
                                'name' => 'date_of_payment',
                                'type' => 'raw',
                                'header' => 'Payment Date',
                                'value' => 'CHtml::link($data["date_of_payment"], $data["url"])'
                            )**,
                            array(
                                'name' => 'payment_mode',
                                'type' => 'raw',
                                'header' => 'Payment Mode',
                                'value' => 'CHtml::link($data["payment_mode"], $data["url"])'
                            ),
                            array(
                                'name' => 'type',
                                'type' => 'raw',
                                'header' => 'Payment Type',
                                'value' => 'CHtml::link($data["type"], $data["url"])'
                            ),
                            array(
                                'name' => 'amount',
                                'type' => 'raw',
                                'header' => 'Amount',
                                'value' => 'CHtml::link($data["amount"], $data["url"])'
                            )
                        )
                    ));
                    ?>
                </article>

and the code for the controller is as follows :-
public function actionPayments($child_id) {
    $response = array();
    $criteria = new CDbCriteria();
    $criteria->condition = "child_id = :child_id AND (invoice_type = 0 OR invoice_type = 1)";
    $criteria->params = array(':child_id' => $child_id);
    $invoiceModel = ChildInvoice::model()->findAll($criteria);
    if (!empty($invoiceModel)) {
        foreach ($invoiceModel as $invoice) {
            $transactionModel = ChildInvoiceTransactions::model()->findAllByAttributes(array(
                'invoice_id' => $invoice->id, 'credit_note_id' => NULL, 'payment_id' => NULL));
            if (!empty($transactionModel)) {
                foreach ($transactionModel as $transaction) {
                    $temp = array();
                    $temp['id'] = "Invoice Payment-" . $transaction->id;
                    $temp['amount'] = $transaction->paid_amount;
                    $temp['date_of_payment'] = $transaction->date_of_payment;
                    $temp['payment_mode'] = customFunctions::getPaymentOptionName($transaction->payment_mode);
                    $temp['type'] = "Invoice Payment";
                    $temp['url'] = Yii::app()->createUrl('childInvoice/view', array('child_id' => $invoice->child_id,
                        'invoice_id' => $invoice->id));
                    $response[] = $temp;
                }
            }
        }
    }
    $creditNotesModel = ChildInvoice::model()->findAllByAttributes(array('child_id' => $child_id,
        'invoice_type' => 3, 'is_deposit' => 1), array('order' => 'invoice_date'));
    if (!empty($creditNotesModel)) {
        foreach ($creditNotesModel as $creditNote) {
            $temp = array();
            $temp['id'] = "Credit Note-" . $creditNote->invoiceUrn;
            $temp['amount'] = sprintf("%0.2f", -$creditNote->total);
            $temp['date_of_payment'] = $creditNote->invoice_date;
            $temp['payment_mode'] = $creditNote->description;
            $temp['type'] = "Deposit";
            $temp['url'] = Yii::app()->createUrl('childInvoice/updateCreditNote', array(
                'id' => $creditNote->id, 'child_id' => $creditNote->child_id));
            $response[] = $temp;
        }
    }
    $paymentsModel = Payments::model()->findAllByAttributes(array('branch_id' => Yii::app()->session['branch_id']), array(
        'order' => 'date_of_payment'));
    if (!empty($paymentsModel)) {
        foreach ($paymentsModel as $payments) {
            if (in_array($child_id, explode(",", $payments->child_id))) {
                $temp = array();
                $temp['id'] = "Payment-" . $payments->id;
                $temp['amount'] = sprintf("%0.2f", $payments->amount);
                $temp['date_of_payment'] = $payments->date_of_payment;
                $temp['payment_mode'] = customFunctions::getPaymentOptionName($payments->payment_mode);
                $temp['type'] = "Payments";
                $temp['url'] = Yii::app()->createUrl('payments/view', array('id' => $payments->id));
                $response[] = $temp;
            }
        }
    }
    usort($response, function($i, $j) {
        $a = strtotime(date("Y-m-d", strtotime($i['date_of_payment'])));
        $b = strtotime(date("Y-m-d", strtotime($j['date_of_payment'])));
        if ($a == $b)
            return 0;
        elseif ($a > $b)
            return 1;
        else
            return -1;
    });
    $this->render('payments', array(
        '**response**' => $response,
    ));
}

So the response array which looks like this will have to be formated :-
[0] => Array
    (
        [id] => Payment-8
        [amount] => 100.00
        [date_of_payment] => 06-03-2017
        [payment_mode] => Cash
        [type] => Payments
        [url] => /new_management/index.php/payments/8
    )

[1] => Array
    (
        [id] => Payment-12
        [amount] => 1500.00
        [date_of_payment] => 22-03-2017
        [payment_mode] => Bank/Standing Order
        [type] => Payments
        [url] => /new_management/index.php/payments/12
    )

[2] => Array
    (
        [id] => Payment-14
        [amount] => 150.00
        [date_of_payment] => 27-03-2017
        [payment_mode] => Cheque
        [type] => Payments
        [url] => /new_management/index.php/payments/14
    )

Below is screenshot of the page and the problem :-
enter image description here


text:
Q: Multi language in parse i'm using parse to push notification and I want to sent notification depend on the device language
the question is How can I send notification in multi language ? there is any way to do this ..!!
please help

A: You can store the users language selection on the Installation object.
Using iOS examples:
PFInstallation *current = [PFInstallation currentInstallation];
[current setObject:@"english" forKey:@"language"];
[current saveEventually];

Then you can push to a query based on language:
PFQuery *query = [PFInstallation query];
[query whereKey:@"language" equalTo:@"english"];

NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
  @"Yo", @"alert", @"yo.caf", @"sound", nil];

PFPush *push = [[PFPush alloc] init];
[push setQuery:query];
[push setData:data];
[push sendPushInBackground];


text:
Q: BIML calling a stored procedure in C# using SSIS project parameter I am new to BIML. I am stuck at the point where I want to call a SQL Server stored procedure in C# and want to pass SSIS project parameter in the stored procedure as a parameter.
For example -
<# string sSQL1 = "Exec dbo.USP_ProcName 'p1'";#>

<# DataTable tbl1 = ExternalDataAccess.GetDataTable(DBConnectionStr,sSQL1); #>

<# foreach (DataRow row in tbl1.Rows){ #>
<Package PackageName="<#=row["PackageName"]#>" />
...
<# } #>

In the above example I want to use SSIS project parameter say, @[Project::Param1] rather than the constant value p1, but I am not getting it right and keep getting syntax errors all the time.
Could someone please help? Thanks in advance

A: It looks like you are using the results of your stored procedure to build a DataTable that is then used to create your SSIS packages via Biml.  As far as I am aware, this is not possible.
If you want to have a dynamic element within your actual Biml script, you need to have those values available to reference either in a metadata file or a database somewhere you can connect to and retrieve.

A: I know I'm a bit late to the party but if anyone else wonders this is actually possible. The following code should work fine:
<#
    string _queryString;
    DataTable _sprocResultSetDT;
    _queryString = string.Format("Exec dbo.MySproc {0}", "InsertParamValueHere");

    _sprocResultSetDT = ExternalDataAccess.GetDataTable (_myConnectionString,_queryString);

    foreach (DataRow row in _sprocResultSetDT.Rows)
    {
#>
    <Package PackageName="<#=row["PackageName"]#>" />

<#  } #> <!-- end of foreach loop -->

Don't forget to set NOCOUNT on inside the sproc if it's returning multiple messages as it won't work otherwise.


text:
Q: Why isn't my code working as intended? I think there is a problem with a null pointer exception. (Java) My code is relatively simple. I have to create a program that takes the input of a string, and tracks the frequency of each string. As well as the user should be able to type in a line, click enter and be able to enter the next line, etc. until the user clicks enter twice in a row. Here is my code so far:
package javaapplication8;

import java.util.Scanner;

public class JavaApplication8 {

static Scanner sc = new Scanner (System.in);

public static void main(String[] args) {
    System.out.print("Enter a sentence: ");
    String input = sc.nextLine() ;
    while (input!=null) {
        if (input.isEmpty()){
            System.out.println("Read Enter Key.");
            break;
        } else if (sc.hasNextLine()){
            input = sc.nextLine();
        } else {
            input = null;
        }
    }
    String sentence = input.replaceAll("\\W", "");
    sentence = sentence.toUpperCase();
    int [] frequencies = new int [26];
    int value = 65;
    double valuecount = 0;

    for (int i = 0; i < 26 ; i++) {
        for (int i2 = 0; i2 < sentence.length(); i2++){
            if (sentence.charAt(i2) == value){
                valuecount += 1 ;
            }
        }
        double percent = (valuecount / sentence.length() ) * 100;
        char val = (char) value;
        System.out.format (val + " occured %.2f percent of the time. \n", + percent);
        value += 1;
        valuecount =0 ;
    }
}
}

Netbeans isn't giving me any syntax errors meaning there isn't any exception stack trace. I'm guessing the issue is between the replaceAll line and the null statements in my while loop (that allows the user to click the enter key twice before the program runs.
I'm very new to Java, so sorry for any 'rookie mistakes'
Thanks!
Edit: My apologies, I thought the exception stack trace was the red text you get when you run your program with syntax errors (missing a semicolon, etc.)
I mean that my program runs, but it gives me NaN instead of the percentage amount, but when I remove the whole while loop, the program works perfectly without the next line feature.

A: The issue appears to be your loop for reading input. Your while loop won't exit until you set your string to null, which only happens when piping input to stdin. I believe if you want to only continue when the string is both not null and not empty, an example solution would be:
while(true){
    if(input != null){
        if(!input.isEmpty()){
            break;
        }
    }
    input = sc.nextLine();
}

Edit:
Apologies did not fully understand what you were trying to achieve and instead assumed.
replacing the snippet above with:
StringBuilder inputBuilder = new StringBuilder();
String nextInput = sc.nextLine();
while(true){
    if(nextInput != null){
        if(nextInput.isEmpty()){
            break;
        }
        inputBuilder.append(nextInput);
    }
    nextInput = sc.nextLine();
}
String input = inputBuilder.toString();

should get the behaviour you were after


text:
Q: Determine record count grouped as year-month for each user including 0 counts I have table with following schema:
article(id,title, content, created_at, created_by)
I want to find all the records created by each user in each month. If the user did not create the the count should show 0. The date range should start from oldest record and end at most recent record. I want to group records by month-year, meaning I want to check records created by each user in each month, if a user did not create any record then it should NOT be skipped in result set rather it should show count for that month as 0.
Assume I have 5 records as follows:
id, title,      content,          created_at, created_by

1,  Some title, some description, 2017-04-21, 2

2,  Some title, some description, 2017-04-10, 2

3,  Some title, some description, 2017-07-15, 2

4,  Some title, some description, 2017-08-21, 2

5,  Some title, some description, 2017-10-04, 2

The result should be like this:
date,    count, created_by
2017-04,  2,     2
2017-05,  0,     2
2017-06,  0,     2
2017-07,  1,     2
2017-08,  1,     2
2017-09,  0,     2
2017-10,  1,     2

Please note that even if the user did not create any record in a specific month still that month-year was included, that is exactly what I want.
I want to do that in MySQL.
Thank You.
And please don't ask what I have tried, I am not good at such complex queries.

A: I don't have a MySQL instance handy to test and confirm that this works for you, but this should work.  It assumes that you have at least one entry for every month in the table.
SELECT DateTable.MonthDay
    , RecordCount.Records
    , RecordCount.created_by
FROM (
    SELECT DISTINCT DATE_ADD(LAST_DAY(DATE_SUB(created_at, interval 30 day), interval 1 day) AS MonthDay
    FROM article
    ) AS DateTable
    LEFT OUTER JOIN (SELECT DATE_ADD(LAST_DAY(DATE_SUB(created_at, interval 30 day), interval 1 day) AS MonthDay
                        , created_by
                        , COUNT(id) AS Records
                    FROM article
                    ) AS RecordCount ON RecordCount.MonthDay = DateTable.MonthDay
WHERE DateTable.MonthDay >= '4/1/2017' AND DateTable.MonthDay <= '10/1/2017'


text:
Q: In TypeScript, how can you confirm that an array contains all the possible values of a string literal union type? I have a string literal union type inherited from a library, and it has hundreds of members (the IconName type from @fortawesome/fontawesome-common-types, if you're curious). I am not able to redefine this type or use an enum instead.
I know that you can't convert a string literal union to an Array. But is there some way to use types to ensure that an array contains all the possible values of a string literal union?
I can do something like
const iconNames: IconName[] = [
  ...
]

but that only guarantees that all members of the array are valid IconName, it doesn't guarantee that the list is exhaustive.
Is there a way to exhaustively confirm that all members of an array conform to a type, and that the array lists all possible values of the type?
As I said, I don't control this type so I can't just rewrite it as an enum, or rewrite it as an array then derive the union type from the array.  The intended use case here is to give users a dropdown to choose an icon from the list of possible valid values.


text:
Q: Wrong query order in Node.js script using SQLite3 package I'm playing with the node-sqlite3 package and ran into a strange situation.
This simple script has a simple logic: find if a table exists, if it does empty it, if not - create it.
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('guy.sqlite');    //':memory:'

var tableExists = false;
db.serialize(function() {
    db.get("SELECT name FROM sqlite_master WHERE type='table' AND name='lorem'", function(error, row) {
        tableExists = (row != undefined);
        console.log("xxxxx " +tableExists);
    });

    console.log("yyyyy " +tableExists);

    if (tableExists) {
        console.log("table exists. cleaning existing records");
        db.run("DELETE FROM lorem", function(error) {
            if (error)
                console.log(error);
        });
    }
    else {
        console.log("creating table")
        db.run("CREATE TABLE lorem (info TEXT)", function(error) {
            if (error.message.indexOf("already exists") != -1) {
                console.log(error);
            }
        });
    }
});

db.close();

But the result I get is:
yyyyy false
creating table
xxxxx true
{ stack: [Getter/Setter],
  arguments: undefined,
  type: undefined,
  message: 'SQLITE_ERROR: table lorem already exists',
  errno: 1,
  code: 'SQLITE_ERROR' }

According to the serialize command documentation, these queries are supposed to run sequentially. Yet clearly the evaluation of tableExists (marked with 'yyy') occurs before a value is set (marked with 'xxx'), causing an attempt to recreate an existing table.
I can handle the error, but I was wondering what's causing this and how to avoid such behavior in the future.
As always, thanks for your time.
Guy

A: node.js works in an asynchronous mode, but your code is some strange form form of mixxed synchronous and asynchronous form.
the complete code after the select should be in the callback whie your actual code does not do what you want, tableexists will not have the values you like.
learn loving the asynchronous model of node.js ;)

A: Example 2 in the documentation explains your problem directly. The tableExists variable will be false in the first run-through while the SELECT function is only queued on the event loop, and won't get run until after the code in serialize() is finished. The solution would be to place the if(tableExists) code inside the callback to SELECT. This defeats the purpose of using serialize, but that's how it works. Writing values are fine because they will get queued up in the order they were called, but something that requires a response via I/O will need a callback and thus run asynchronously.
Also, the  SQLITE_MISUSE error comes from the fact that you call db.close() at the end of the script, but outside of the asynchronous callbacks. Even though it's at the end of the script, any asynchronous stuff guts put into a queue that isn't called until after the current function has finished.


text:
Q: Amazon EC2 (Linux) + RDS (MySQL) + PHP + pdflatex = LaTeX to PDF online I would like to have a website capable of converting LaTeX documents to PDF online. So for example user types in some raw LaTeX (document), I'm saving it into my MySQL database and I'm able to convert that LaTeX to PDF docuement available for preview and download.
As I understand, I need to have my own Linux powered server with pdflatex installed on the machine. I have in mind buying EC2 instance on Amazon (+ RDS for MySQL, or MySQL on EC2, doesn't matter much in this case) powering some Linux distribution, installing pdflatex on it and putting some PHP script (Apache, LAMP installed) which could do converting LaTeX to PDF and representing it onto my webpage.
Is this a good way to do it, and if it is could you provide me some more detailed steps - especially installing pdflatex on the machine and connecting it with PHP script?

A: It sounds like you're looking for scribtex.com. Go give them a shot! I really like it.
As a bonus beyond what you described, they support Git access, so you can do real version control of your documents.


text:
Q: What is the difference between block coverage and branch coverage? Is block coverage the same as branch coverage, similar to it or completely different?
The top Google link explaining branch coverage: http://www.tutorialspoint.com/software_testing_dictionary/branch_testing.htm

A: Block coverage (or "basic block coverage") and branch coverage are two different measures of code coverage. Block coverage counts blocks bounded by branches. Branch coverage counts the actual branches.
This code fragment
puts "I'm block 1"
if condition
  puts "I'm block 2"
else
  puts "I'm block 3"
end
puts "I'm block 4"

has four blocks but only two branches, the two sides of the if/else. If this code is tested by only one test and condition is true in that test,

*

*blocks 1, 2 and 4 will be covered, so block coverage will be 75%

*the true branch of the if will be covered but not the false branch of the if, so branch coverage will be 50%


text:
Q: Accessing the variable of parent class shows subclass variable I encountered an example which is not at all clear to me.
In this example result is :
feline cougar c c
But we call in method super.type.
class Feline {
   public String type = "f ";
   public Feline() {
   System.out.print("feline ");
   }
 }
 public class Cougar extends Feline {
   public Cougar() {
     System.out.print("cougar ");
      }
      void go() {
       type = "c ";
        System.out.print(this.type + super.type);
     }
      public static void main(String[] args) {
        new Cougar().go();
         }
        }

I expected feline cougar c f.

A: There is only one variable. However you access that variable, it will give the same value.


text:
Q: Sentences starting with the preposition "Of" I often see sentences starting with the prepositions "In", "With", "To", and "For".
However, a sentence starting with "Of" seems to be quite rare.
Is that grammatically correct? For example, what about the following complicated sentence?
Of our shelves A, B, C, and D, for B and C, you can take any book from there; for A and D, you cannot.

A: Of the comments on the question, one is yours and the rest are by other people.
Note that valid sentences of this form can be rearranged:

Of the comments on the question, one is yours and the rest are by other people.
One of the comments on the question is yours and the rest of the comments on the question are by other people.

Because "of the comments on the question" occurs twice, you can bring it to the front. This is rather like factorisation in algebra: ax+bx → x(a+b).
However, to start a sentence with of, that preposition must make sense. In your example sentence, you have also included the prepositions for and from. You have too many prepositions. Any sentence is awkward.

✗ Of our shelves A, B, C, and D, for B and C, you can take any book from there; for A and D, you cannot.
✗ Of our shelves A, B, C and D, you can take any book from B and C; you cannot from A and D.
✓ From our shelves B and C, you can take any book; from shelves A and D, you cannot.


text:
Q: A north country question: is Varmint the root of Warm 'un? I would like to examine the proposition that the Yorkshire and north country term warm 'un may derive from the word varmint.
I was brought up in south Yorkshire and often heard children referred to as a warm 'un. The phrase usually applied to lively, mischievous or otherwise exceptionally active children who entertained or irritated adults. "Ee – ee's a warm 'un!"
Un is not difficult:

Yorkshire Express
Un – one

Warm poses more interest. In my childlike naivety I assumed it meant "A warm one", drawing some sort of parallel with a hot and active fire (of which there were many in a coalfield area).
Later I thought it to relate to the adult use of hot, referring to a sexually active and attractive person:

Cambridge
Hot:
sexually attractive, or feeling sexually excited:
She's really hot!
I'm hot for you, baby.
I've got a hot date tonight.

Being slang, there are only limited quotations available. We have:

Milly Johnson
Warm un:
Witty
bit of a slapper (female).
Elsie down the road is a warm un.

Yorkshire Post
He's a warm (rhymes with harm) un" (has a bob or two, nicely off)

BBC
Amt Tyke (a contributor to the BBC):
Anyone know this one: "tha's a warm un"? {= "You are a warm one"}

while over the border in Lancashire is:

Lancashire Songs; Edwin Waugh
"A needle would keep th' body wake, An' th' soul met still be dozin'; But this receipt would set it reet, Iv th' mixture wur a warm un — Yo'm get some stingin' gospel-snuff, An' put it into th' sarmon."

In summary, warm seems to be associated with childhood precocity and naughtiness, spiciness, wealth, sexual attraction and – more generally – with types of egregiousness.
However, more recently I have had the suspicion that some of these uses derive from a simple spoken corruption of Varmint

Merriam Webster
a contemptible person : rascal broadly : person, fellow

Cambridge
an annoying child:
The little varmints stole my wallet!

I add the aural aspect of this question: the pronunciation I knew - and it is exemplified by the Yorkshire Post quotation - was Warm rhyming with Arm.
Add to this the sort of sound shifts we see between Scando-German "warm" (initial "V" sound in German, Swedish and others), the Scandinavian-Viking influence in northern England, all contrasting with the usual English "warm" (initial "w" sound), and you may see the reasons for my notion.
Do you agree with this suspicion?

A: warm'un reminds me of wane/we'an/wean widely used in Ulster/Scotland.

Weans
Derived from wee, meaning little, and ane meaning one, wean is a word most commonly used in the West of Scotland to refer to a young child, and is sometimes also spoken as wee yin or 'little one'.
The Scotsman

I think OP's original idea re. warm one is a very promising avenue, and to my ears, it simply implies an alive/lively/living/warm-blooded one as opposed to a dead/cold/cold-hearted one.

A: Based on the following entry, it seems warm 'un has nothing to do with varmints.
Under warm, in Slang and Its Analogues Past and Present — A Dictionary, Historical and Comparative, of the Heterodox Speech of All Classes of Society for More Than Three Hundred Years. With Synonyms in English, French, German, Italian, Etc · Volume 7 (1890) we find:

WARM (= wanton) DESIRE: a WARM (= lecherous) MEMBER (or WARM-'UN): a
harlot or whoremonger : cf. HOT-UN, SCHORCHER (q.v.);

And this quote:

c. 1889. Music Hall Song, 'Salvation Sarah.' They call me Salvation Sarah, a warm-'un I have been; but now I am converted, I'll
never go wrong again.

You can find there other meanings for warm (albeit without 'un) more suitable for children.
Here are some definitions of warm from the OED:

warm, adj. and n.2
10. b. Of the passions or disposition in general: Prone to excitement, ardent, impulsive; apt to disregard the voice of cool
reason.
11. Hot-tempered, angry.
13. Characterized by, of the nature of, prone to, sexual desire; amorous.
14. b. Of imaginative composition: Indelicate in its appeal to sexual emotion.
Source: Oxford English Dictionary (login
required)

However you want to spin it, there's no need to get varmints involved.


text:
Q: IMG tag does not bring image I have a web application, where i am storing all the images in a folder which is totally outside WEB-INF folder or webroot folder. When the jsp to display the image is called, before displaying it, i am moving the concerned image files to WEB-INF/images folder and then setting the path in the html IMG tag. My question is
Is this good design?
Also even though the image is moved to WEB-INF/images folder, the page does not display the image always, it displays sometimes and sometimes it doesnt. I dont know how to debug this problem.
I am using springs and spring security.

A: This is not a very good design. In many cases, server will cache web application data so if the image was not there it will never find out that it appeared in place. That's, probably, causing the inconsistency that you observe as there may be other factors affecting caching.
The right choice would be to provide a servlet that serves your image data upon request from the file.