Q: What is the best practice to use Oauth2, React, Node.js and Passport.js to authenticate user with Google sign on button? I want to have a login button in my website so when a user clicks on it, the user can use their Google credentials. I'd like to ideally perform the authentication server side using Express.js and Passport.js.
I implemented authentication server-side but the problem is that I can't make an AJAX request from the website to the server to start authentication because Google or Oauth don't support CORS. So I need to use a href element in my website which would call the server authentication endpoint. However, I can't catch server response in this way.
If I perform the authentication client-side (I'm using React) I could store login state in Redux and allow the user to access the website's resources. However, when the user logs out I need to make sure that server endpoints stop serving the same user which feels like implementing authentication twice: client-side and server-side.
In addition when authenticating client-side, Google opens a popup for the user to authenticate which I think is worse user experience then just a redirect when authenticating server-side.
I'm wondering what the best practice in terms of authenticating using Oauth2/Google. For example, stackoverflow.com also has Google button but just makes a redirect, without any popup, so I guess they figured out a way to perform server-side authentication and to bypass CORS issue.

A: I faced the same issue. This article is Gold link
1.In auth route File I had following code
 const CLIENT_HOME_PAGE_URL = "http://localhost:3000";

  // GET  /auth/google
  // called to authenticate using Google-oauth2.0
  router.get('/google', passport.authenticate('google',{scope : ['email','profile']}));

  // GET  /auth/google/callback
  // Callback route (same as from google console)
   router.get(
    '/google/callback',
    passport.authenticate("google", {
    successRedirect: CLIENT_HOME_PAGE_URL,
    failureRedirect: "/auth/login/failed"
   }));

   // GET  /auth/google/callback
  // Rest Point for React to call for user object From google APi
   router.get('/login/success', (req,res)=>{
     if (req.user) {
         res.json({
          message : "User Authenticated",
         user : req.user
        })
     }
     else res.status(400).json({
       message : "User Not Authenticated",
      user : null
    })
  });

2.On React Side After when user click on button which call the above /auth/google api
  loginWithGoogle = (ev) => {
    ev.preventDefault();
    window.open("http://localhost:5000/auth/google", "_self");
  }

3.This will redirect to Google authentication screen and redirect to /auth/google/callback which again redirect to react app home page CLIENT_HOME_PAGE_URL
4.On home page call rest end point for user object
(async () => {
  const request = await fetch("http://localhost:5000/auth/login/success", {
   method: "GET",
   credentials: "include",
   headers: {
    Accept: "application/json",
     "Content-Type": "application/json",
    "Access-Control-Allow-Credentials": true,
  },
});

const res = await request.json();
   //In my case I stored user object in redux store
   if(request.status == 200){
     //Set User in Store
    store.dispatch({
      type: LOGIN_USER,
      payload : {
        user : res.user
     }
    });
  }

})();

5.last thing add cors package and following code in server.js/index.js in node module
// Cors
app.use(
  cors({
    origin: "http://localhost:3000", // allow to server to accept request from different origin
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    credentials: true // allow session cookie from browser to pass through
   })
);

A: Your authentication should be done server side. Here is how it works.

*

*You make a fetch or axios call to your authentication route.

*Your authentication route sends a request to Google's Authentication servers. This is important to have on the backend because you will need to provide your clientSecret. If you were to store this on the frontend, it would make it really easy for someone to find that value and compromise your website.

*Google authenticates the user and then sends you a set of tokens to your callback url to use for that user (refresh, auth, etc...). Then you would use the auth token for any additional authorization until it expires.

*Once that expires, you would use the refresh token to get a new authorization token for that client. That is a whole other process though.

Here is an example of what that looks like with Passport.js: https://github.com/jaredhanson/passport-google-oauth2
EDIT #1:
Here is an example with comments of the process in use with Facebook, which is the same OAuth codebase:
https://github.com/passport/express-4.x-facebook-example/blob/master/server.js

A: Redux can really help with achieving this and this follows the same logic as Nick B already explained...

*

*You set up oauth on the server side and provide an endpoint that makes that call

*You set up the button on you react frontend and wire that through an action to the endpoint you already setup

*The endpoint supplies a token back which you can dispatch via a reducer to the central redux store.

*That token can now be used to set a user to authenticated

There you have it.


Q: Set VisualState of combobox when a item is selected in Xaml (Silverlight) When my combobox expands and I select an item, I want the combobox to change visual state(it is highlighted). This will signify something is selected. I tried various VisualStates but none of them would trigger in this scenario. How can I achieve this? Thanks.

A: The standard ComboBox simply doesn't have states to distinguish between having something selected and having nothing selected.
There are a number of ways to go about solving the underlying problem, and it depends mostly on the answer to the following question:
Do you really need to change the visual appearance of the ComboBox itself or does it suffice to style the selected item more prominently?
If it's the latter, you're best served with the rather easy way of using a custom control template for the ComboBoxItems.
If you really want to style the ComboBox itself that way, there are two options I can think of:
A) Add custom states to a ComboBox with a custom template.
Copy your ComboBox's control template and add another state group to the already present states. Both of this is typically done in Expression Blend.
After that you can update the new states in code with
VisualStateManager.GoToState(this, "Selected", true);

for example. You will have to set those states yourself when the first item is chosen. This could be done on the SelectionChanged event.
B) Derive from ComboBox
If you want to use the control in this way often, it might be worthwhile to derive from ComboBox to make your own custom control.
It would look somthing like this:
[TemplateVisualState(Name = "SelectedStates", GroupName = "Unselected")]
[TemplateVisualState(Name = "SelectedStates", GroupName = "Selected")]
// ... (more attributes copied from the ComboBox ones)
public class MyComboBox : ComboBox
{
    public MyComboBox()
    {
        SelectionChanged += HandleSelectionChanged;

        DefaultStyleKey = typeof(MyComboBox);
    }

    void HandleSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        VisualStateManager.GoToState(this, SelectedItem != null ? "Selected" : "Unselected", true);
    }
}

And you would then need a default style based on the default ComboBox style (or whatever you usually use).
Note that I didn't test this in any way.


Q: Approximating $\vartheta(x)=\sum_{p\le x} \log(p)?$ Consider the first Chebyshev function $\vartheta(x)=\sum_{p\le x} \log(p)$ where the sum runs over the primes less than or equal to $x$.
I wanted to approximate $\vartheta(x).$
My attempt was $f(x)=\sum_{n \ge 2}^x n^\frac{-1}{n}.$ It overcounts by about $2$ at $x=101$ giving a value of $90.177$ whereas $\vartheta(x)$ gives $88.344.$ I'm not sure how $f(x)$ performs as $x$ increases.

Is $f(x)\sim \vartheta(x)?$

A: Per
$$n^{-1/n} = \exp \biggl(-\frac{\log n}{n}\biggr) = 1 - \frac{\log n}{n} + O\biggl(\frac{(\log n)^2}{n^2}\biggr)$$
we have
$$f(x) = x - \frac{1}{2}(\log x)^2 + O(1)\,.$$
Thus we have $f(x) \sim \vartheta(x) \sim x$.
But $f(x)$ stays much closer to $x$ than $\vartheta(x)$. By a result of Littlewood we have
$$\vartheta(x) - x \in \Omega_{\pm}(\sqrt{x}\, \log \log \log x)$$
while $x - f(x)$ is of much smaller magnitude, and always positive.


Q: PHP array_key_exists and is not empty Following on from a previous question, I am now using the following function to check if a key exists in a multi-dimensional array...
function array_key_exists_r($needle, $haystack) {
        $result = array_key_exists($needle, $haystack);
        if ($result)
            return $result;

        foreach ($haystack as $v) {
            if (is_array($v) || is_object($v))
            $result = array_key_exists_r($needle, $v);
            if ($result)
            return $result;
        }

        return $result;
    }

I am checking like this...
if (array_key_exists_r("image",$myarray)) {
echo 'Array Key Image Exists';
}

But now I am trying to modify it or the result to check that key is not empty, can I do this inside the function or should I do something with the output of the function?
Or should I be using isset instead?

A: Whether you do this inside the function or not it's fully up to you. Personally if I did it inside the function I would change its name to something clearer since it doesn't only check if a key exists. Anyhow I found a solution within the same function:
function array_key_exists_r($needle, $haystack){

    $result = array_key_exists($needle, $haystack);

    if ($result && $haystack[$needle]){
        return $result;
    }

    foreach ($haystack as $v)
    {
        if (is_array($v) || is_object($v)){
            $result = array_key_exists_r($needle, $v);

            if ($result) {
                return $result;
            }
        }
    }

    return false;
}

So basically I added a validation on your ifs and that did it also change the default return value to false just in case. I think it can still be enhanced but this does the job.

A: Try this approach instead. Easier!
function array_key_exists_r($needle, $haystack) {
   $found = [];
   array_walk_recursive($haystack, function ($key, $value) use (&$found) {
      # Collect your data here in $found
   });
   return $found;
}


Q: Multiple Uploads Rails Paperclip not Saving I have a rails model 'Guitar' and a rails model 'Photo.' I wanted to be able to attach multiple photos so I watched the railscasts for Paperclip, read the docs, etc. I've used Paperclip in the past to attach a single photo, but I wanted to do multiples this time. I don't have a problem updating the model, and it doesn't error out when I attach sample photos, but when I rails console to Photos.all, nothing comes back. My ultimate goal is to a polymorphic association with an 'Amps' model, but I really just wanted to get 'Guitars' working first.
I have paperclip added to the Gemfile and I've bundle installed, restarted the server, etc. I think I'm missing something stupid and I'm new to rails so please be gentle...
guitar.rb
class Guitar < ActiveRecord::Base
  belongs_to :user
  has_many :photos

  accepts_nested_attributes_for :photos
end

photo.rb
class Photo < ActiveRecord::Base
  belongs_to :guitars

  has_attached_file :photo, styles: {
        thumb: '100x100>',
        square: '200x200#',
        medium: '300x300>',
        large: '600x600#' }
end

guitars_controller.rb
class GuitarsController < ApplicationController
  before_action :set_guitar, only: [:show, :edit, :update, :destroy]

  # GET /guitars
  # GET /guitars.json
  def index
    @guitars = Guitar.all
  end

  # GET /guitars/1
  # GET /guitars/1.json
  def show
  end

  # GET /guitars/new
  def new
    @guitar = Guitar.new
    3.times { @guitar.photos.build }
  end

  # GET /guitars/1/edit
  def edit
    @guitar = Guitar.find(params[:id])
    3.times { @guitar.photos.build }
  end

  # POST /guitars
  # POST /guitars.json
  def create
    @guitar = Guitar.new(guitar_params)
    @guitar.user_id = current_user.id if current_user

    respond_to do |format|
      if @guitar.save
    format.html { redirect_to @guitar, notice: 'Guitar was successfully created.' }
    format.json { render action: 'show', status: :created, location: @guitar }
      else
    format.html { render action: 'new' }
    format.json { render json: @guitar.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /guitars/1
  # PATCH/PUT /guitars/1.json
  def update
    respond_to do |format|
      if @guitar.update(guitar_params)
    format.html { redirect_to @guitar, notice: 'Guitar was successfully updated.' }
    format.json { head :no_content }
      else
    format.html { render action: 'edit' }
    format.json { render json: @guitar.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /guitars/1
  # DELETE /guitars/1.json
  def destroy
    @guitar.destroy
    respond_to do |format|
      format.html { redirect_to guitars_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_guitar
      @guitar = Guitar.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def guitar_params
      params.require(:guitar).permit(:make, :model, :year, :color, :serial, :price, :condition, :kind, :bodykind, :frets, :one_owner, :user_id)
    end
end

guitars show.html.erb

  Make:
  <%= @guitar.make %>

  Model:
  <%= @guitar.model %>

  Year:
  <%= @guitar.year %>

  Color:
  <%= @guitar.color %>

  Serial:
  <%= @guitar.serial %>

  Price:
  <%= @guitar.price %>

  Condition:
  <%= @guitar.condition %>

  Kind:
  <%= @guitar.kind %>

  Bodykind:
  <%= @guitar.bodykind %>

  Frets:
  <%= @guitar.frets %>

  One owner:
  <%= @guitar.one_owner %>

  User:
  <%= @guitar.user_id %>

    <% for asset in @guitar.photos %>
      <%= link_to image_tag(photo.photos.url(:thumb)), photo.photo.url(:original) %>
    <% end %>

<%= link_to 'Edit', edit_guitar_path(@guitar) %> |
<%= link_to 'Back', guitars_path %>

guitars _form.html.erb
<%= simple_form_for(@guitar, html: { class: 'form-horizontal', :multipart => true}) do |f| %>
  <% if @guitar.errors.any? %>

<%= pluralize(@guitar.errors.count, "error") %> prohibited this guitar from being saved:

      <% @guitar.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

  <%= f.input :make, label: 'Make of the Guitar', placeholder: 'Gibson' %>
  <%= f.input :model, label: 'Model of the Guitar', placeholder: 'Les Paul' %>
  <%= f.input :year, label: 'Year Made', placeholder: '1957' %>
  <%= f.input :color, label: 'Color', placeholder: 'GoldTop' %>
  <%= f.input :serial, label: 'Serial', placeholder: '#7-8789' %>
  <%= f.input :price, label: 'Price' %>
  <%= f.input :condition, label: 'Condition, 1-10' %>
  <%= f.input :kind, label: 'Kind of Guitar', placeholder: '6-String-Electric' %>
  <%= f.input :bodykind, label: 'Body Type', placeholder: 'Solid String Electric' %>
  <%= f.input :frets, label: 'Number of Frets', placeholder: '22' %>
  <%= f.input :one_owner, label: 'Original Owner' %>

  <%= f.fields_for :photos do |photo| %>
    <% if photo.object.new_record? %>
      <%= photo.file_field :photo %>
    <% end %>
  <% end %>

    <%= f.submit %>

<% end %>

A:  def guitar_params
  params.require(:guitar).permit(:make, :model, :year, :color, :serial, :price, :condition, :kind, :bodykind, :frets, :one_owner, :user_id, photos_attributes: [:photo])
end

A: You're running into mass assignment protection which is preventing the photos from being saved.  Add this line to your Guitar model:
attr_accessible :photos_attributes

A: in my case I need create a document.
# config/initializer/paperclip.rb
require 'paperclip/media_type_spoof_detector'
module Paperclip
  class MediaTypeSpoofDetector
    def spoofed?
      false
    end
  end
end

This document is necessary create in config > initializers. If your SO is windows, you need add this line in config/environments/development.rb:

Paperclip.options[:comand_path] = "/ImageMagick-6.8.9-Q16/"


Q: Android service fails after onRebind() with a DeadObjectException I am having a problem with my Android service and client apps who rebind to it. Everything works fine when a client app initially binds to my service, after which messages can be sent from service to client. However, if the client app is killed and then binds agains, onRebind() is correctly called in the service, but my messenger in the intent is invalid, causing a DeadObjectException, as noted in the code below. Any ideas?
Here is my code for the service:
@Override
public IBinder onBind(Intent intent)
{
    getMessenger(intent);

    return _inputMessenger.getBinder();
}

@Override
public void onRebind(Intent intent)
{
    getMessenger(intent);
}

@Override
public boolean onUnbind(Intent intent)
{
    return true;
}

private void getMessenger(Intent intent)
{
    Bundle extras = intent.getExtras();

    if (extras != null)
    {
        // Get the messenger sent from the app.
        // This is handled correctly after onBind() and onRebind().
        _outputMessenger = (Messenger) extras.get("MESSENGER");
        Log.i(TAG, "Got messenger from app: " + _outputMessenger);
    }
}

private void sendMessageToClient(String key, String value)
{
    Message message = Message.obtain();
    Bundle bundle = new Bundle();
    bundle.putString(key, value);
    message.setData(bundle);

    try
    {
        _outputMessenger.send(message); // EXCEPTION OCCURS HERE AFTER onRebind()
    }
    catch (Exception ex)
    {
        Log.e(TAG, "_outputMessenger.send() failed: " + ex);
    }
}

And here is the code for the application:
     Intent intent = new Intent("com.foobar.service");

    // Create a new messenger for the communication from service to app.
    _messenger = new Messenger(new ServiceToActivityHandler());
    intent.putExtra("MESSENGER", _messenger);

    _serviceConnection = new MyServiceConnection();

    _isBoundToService = _context.bindService(intent,
                                           _serviceConnection,
                                           Context.BIND_AUTO_CREATE);

A: There is a note on bound services... The part under additional notes should be useful. I think trapping the exception is probably what you should do...
try {
    // Do stuff
} catch(DeadObjectException e){
    // Dead object
}

I read that object lifetimes should be reference counted by android across processes, so you should be OK, when the client dies I wonder if
 _outputMessenger // needs to be unassigned in your service...?

I assume what is happening is that your binding to the service, it's pumping some data back to your client, your client goes away, the service continues running but then needs to pump some data to the client which has gone by this point?
Also this link


Q: postman only showing "This field is required" to ManyToMany field in django I have 2 models - Module and Room. A module can have zero or multiple rooms and a room can be added into multiple modules. So, there is a simple many-to-many relationship between them.
When I use post request, raw-data works, but not form-data.
module/models.py -
class Module(models.Model):
    module_id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=100)
    desc = models.TextField()
    room_list = models.CharField(max_length = 100, blank=True)
    rooms = models.ManyToManyField(Rooms, blank=True)

rooms/models.py -
class Rooms(models.Model):
    room_id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=100)
    level = models.CharField(max_length=100)
    desc = models.TextField()

module/serializers.py -
class ModuleSerializer(serializers.ModelSerializer):
    rooms = RoomSerializer(many=True)

    class Meta:
        model = Module
        fields = '__all__'

    def create(self, validated_data):
        rooms_data = validated_data.pop('rooms')
        module = Module.objects.create(**validated_data)
        for data in rooms_data:
            room = Rooms.objects.get(**data)
            module.rooms.add(room)
        return module

    def update(self, instance, validated_data):

        # Updating rooms
        rooms_data = validated_data.get('rooms')
        instance.rooms.clear()

        for room_data in rooms_data:
            room = Rooms.objects.get(**room_data)
            instance.rooms.add(room)

        # Updating other fields
        fields = [
            'title',
            'desc',
            'thumbnail',
            'is_deleted',
        ]
        for field in fields:
            setattr(instance, field, validated_data[field])
        instance.save()
        return instance

rooms/serialier.py -
class RoomSerialize(serializers.ModelSerializer):
    room_id = serializers.IntegerField()
    class Meta:
        model = Rooms
        fields = "__all__"

module/views.py -
class add_module(APIView):
    def post(self, request, format=None):

        # Adding the rooms to module from room_list
        new_request = request.data.copy()
        room_list=[]
        if 'room_list' in new_request:
            room_list_data = list(new_request['room_list'].split(" "))
            for room in room_list_data:
                room_object = Rooms.objects.get(room_id=room)
                room_serializer = RoomSerializer(room_object)
                room_list.append(room_serializer.data)
        new_request.update({'rooms':room_list})

        # creating the module
        module_serializer = ModuleSerializer(data=new_request)
        if module_serializer.is_valid():
            module_serializer.save()
            return Response(module_serializer.data['module_id'])
        return Response(module_serializer.errors)

POST request body for updating a module in POSTMAN -
{
    "module_id": 2,
    "room_list": "1 2",
    "title": "4",
    "desc": "22",
}

Pls notice that while taking input of ManyToMany field - "rooms", I'm taking a string "room_list" as input that contains all the room_ids to be included. This works perfectly fine when I take input as raw-data in postman, but when I use form-data, it shows
{
    "rooms": [
        "This field is required."
    ]
}

What to do?

A: First of all, serializer fields with (many=True) create nested objects.
If you input data with Rooms as already serialized, then it means that you create other Rooms instances. It will be shown with if module_serializer.is_valid(): part. Therefore, if you intended to implement as just link already instantiated Rooms to Module, it's better to make it as primary key list.
Here are my example codes.
class ModuleSerializer(serializers.ModelSerializer):
    rooms = RoomSerializer(many=True, read_only=True)

    def create(self, validated_data):
        rooms_data = validated_data['room_list']
        module = Module.objects.create(**validated_data)
        for data in rooms_data.split(' '):
            room = Rooms.objects.get(room_id=data)
            module.rooms.add(room)
        return module

    def update(self, instance, validated_data):

        # Updating rooms
        rooms_data = validated_data.get('rooms')
        instance.rooms.clear()

        for room_data in rooms_data:
            room = Rooms.objects.get(**room_data)
            instance.rooms.add(room)

        # Updating other fields
        fields = [
            'title',
            'desc',
            'thumbnail',
            'is_deleted',
        ]
        for field in fields:
            setattr(instance, field, validated_data[field])
        instance.save()
        return instance

    class Meta:
        model = Module
        fields = '__all__'

class AddModule(APIView):
    def post(self, request, format=None):
        # creating the module
        module_serializer = ModuleSerializer(data=request.data)
        if module_serializer.is_valid():
            module_serializer.save()
            return Response(module_serializer.data['module_id'])
        return Response(module_serializer.errors)

Any other parts are same as yours. Regardless of whether data are sent by form-data or json raw data, results are same as below.


Q: Chrome Devs tools - where's size and content? According to Chrome Dev Tools - "Size" vs "Content", I should be able to see Size (bytes on the wire) and Content (uncompressed size).
I remember seeing this at one time.
But now (Chrome 38), I only see one measurement, and I'm not sure which one it is.

Can I see the compressed and uncompressed sizes with the Chrome Dev Tools?

A: You should press "Use large resource rows." to see more data.

A: If you are using the latest version of Chrome (like 78+), you can check "Use large request rows" under the settings icon.
Doc: https://developer.chrome.com/docs/devtools/network/reference/#uncompressed

A: I was stuck because only the name of the file was showing up (no other columns), but I realized that you must close the "details" view that shows on the right side when you click a row to see any other columns. Posting the answer here since search brought me here, though it wasn't the OP's actual issue.


Q: format of returned result for .objects.filter(name__containe=data) without quotes sign I have written a code by django in which a user can search for a word in a table of database. My problem here is when I print the returned results, they contain quotations. How can I omit them?
def My_data_filed(request):
    form = data_filed_Form(request.POST or None)
    data = None
    download_form = None

    if request.method == 'POST':
        if form.is_valid():
            data_g = form.cleaned_data.get('g')
            data = list(data_filed.objects.filter(g__contains=data_g).values())
            print(data_filed.objects.all().values())
            download_form = data_filed_DownloadForm(initial={
                'g': data_g,
            })

    return render(request, 'search_report.html',
                  {
                      'form': form,
                      'data': data,
                      'download_form': download_form
                  })

The output of this code is like:
 'Creator': 'Davide'

But I just want to have:
Davide

Whats wrong in my effort?

My code for writing the fetched result into a csv file: (Since from the comments I understood this part is related too)
def resultDownload(request):
    try:
        assert request.method == 'POST'
        form = data_DownloadForm(request.POST)
        assert form.is_valid()
        data_g = form.cleaned_data.get('g')
        data = list(data_filed.objects.filter(data__contains=g).values_list())
    except AssertionError:
        error = 'Your request has some problems.'
        data = error

    attachment = 'SearchedReport.csv'
    response = HttpResponse(content_type='text/csv')

    response['Content-Disposition'] = 'attachment;filename="{}"'.format(attachment)
    response.write(data)
    return response

A: Whenever you run a queryset like data_filed.objects.filter(g__contains=data_g).values() it always returns a dictionary kind of output with keys and values. And when you passed that result to your template file using:
return render(request, 'search_report.html',
                  {
                      'form': form,
                      'data': data,
                      'download_form': download_form
                  })

It is still in that format. If you want to output only the value, you need to output it as such
{{ data.Creator }}

That will give you the output "Davide" without the quotes


Q: magento2 add credit memo for invoice with items I am trying to add partial credit memo programatically but it is consuming whole quantity in first credit memo, How can I pass specific items to credit memo?
public function createCreditMemo ($entityId,$invId,$shipping,$subtotal,$grandtotal,$tax) {

        $post_data = json_decode(file_get_contents('php://input'), true);
    $itemsArray = array();

        foreach($post_data['items'] as $index => $details){
                 $quantity = $details['qty'];
         $order_item_id = $details['order_item_id'];
                 $itemsArray[$order_item_id]=$quantity;
            }

        $orderId = $entityId;
        $order = $this->_orderRepository->get($orderId);
        $shippingAmount = $shipping;
        $subTotal = $subtotal;
        $taxAmount = $tax;
        $grandTotal = $grandtotal;
        $invoiceId = $invId;

        $invoiceobj =  $this->invoice->load($invId);
        $creditmemo = $this->creditmemoFactory->createByInvoice($invoiceobj,$itemsArray);

        $creditmemo->setShippingAmount($shippingAmount);
        $creditmemo->setTaxAmount($taxAmount);
        $creditmemo->setBaseTaxAmount($taxAmount);
        $creditmemo->setSubtotal($subTotal);
        $creditmemo->setBaseSubtotal($subTotal);
        $creditmemo->setGrandTotal($grandTotal);
        $creditmemo->setBaseGrandTotal($grandTotal);

        $this->creditmemoService->refund($creditmemo);

       return $creditmemo->getId();

    }
}

I am passing item array still it is taking all the items of invoice.

A: replace of your code line from :
$creditmemo = $this->creditmemoFactory->createByInvoice($invoiceobj,$itemsArray);

to
$creditmemo = $this->creditmemoFactory->createByOrder($order,$itemsArray);


Q: I'm trying to set up a new SharePoint production server and getting an error creating an Open XML 2.5 document I have a SharePoint application written in Visual Basic that works fine and creates Word Documents using Open XML 2.5 on my development machine. We recently set up a new Production server and I published the .wsp file and deployed it on the new server. The application all works fine except the code that generates reports in Word format. It fails on the following line of code.
Dim wpd As WordprocessingDocument = WordprocessingDocument.Create(MemStream, WordprocessingDocumentType.Document, True)
This is what the code looks like in the function that is failing.
''' \<summary\>
'''
''' \</summary\>
''' \<param name="MemStream"\>\</param\>
''' \<returns\>\</returns\>
Public Function WPDCreateFromStream(MemStream As MemoryStream) As WordprocessingDocument
   Try
      Dim wpd As WordprocessingDocument = WordprocessingDocument.Create(MemStream, WordprocessingDocumentType.Document, True)
      Dim MainPart As MainDocumentPart = wpd.AddMainDocumentPart()
      MainPart.Document = New Document()
      Dim DocBody As New Body()
      Return wpd
   Catch ex As Exception
      WriteErrorToEventLog("OpenXML", "WPDCreateFromStream", "", ex)
      Return Nothing
   End Try
End Function

Here is the exception detail I get when trying to make the WordProcessingDocument.Create call above.
ERROR: Source: OpenXML Routine: WPDCreateFromStream User:
Message: The type initializer for 'MS.Utility.EventTrace' threw an exception.
StackTrace:    at MS.Utility.EventTrace.EasyTraceEvent(Keyword keywords, Event eventID)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateCore(Stream stream)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(Stream stream, WordprocessingDocumentType type, Boolean autoSave)
at FIS.SP.PSTARProjectTracker.PSTAR.Core.BusinessLogic.OpenXML.WPDCreateFromStream(MemoryStream MemStream)
Source: WindowsBase
Data: System.Collections.ListDictionaryInternal
InnerException: System.Security.SecurityException: Requested registry access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.Registry.GetValue(String keyName, String valueName, Object defaultValue)
at MS.Utility.EventTrace.IsClassicETWRegistryEnabled()
at MS.Utility.EventTrace..cctor()
The Zone of the assembly that failed was:
MyComputer
ToString: System.TypeInitializationException: The type initializer for 'MS.Utility.EventTrace' threw an exception. ---> System.Security.SecurityException: Requested registry access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.Registry.GetValue(String keyName, String valueName, Object defaultValue)
at MS.Utility.EventTrace.IsClassicETWRegistryEnabled()
at MS.Utility.EventTrace..cctor()
--- End of inner exception stack trace ---
at MS.Utility.EventTrace.EasyTraceEvent(Keyword keywords, Event eventID)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateCore(Stream stream)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(Stream stream, WordprocessingDocumentType type, Boolean autoSave)
at FIS.SP.PSTARProjectTracker.PSTAR.Core.BusinessLogic.OpenXML.WPDCreateFromStream(MemoryStream MemStream)
TargetSite: Void EasyTraceEvent(Keyword, Event)
I know this is not an issue with the code as the same code works in development. I assume it has to do with  permissions, or getting the DocumentFormat.OpenXML.dll installed / registered correctly on the new server, but I've had no luck searching for a solution.
I tried installing OpenXML and the Productivity tool on the server. The productivity tool works and can open a word document, but the Application has the same issue.
If anyone has run into this and can point me to a solution, I would appreciate it.

The MemoryStream is created and passed in to be used by this function. The WordProcessingDocument is returned to the calling function. I could explicitly call ByVal, but in this case it would not change anything.
I am creating a new document, that is why it is coded using WordProcessingDocument.Create
Remember, this code all functions perfectly on the development SharePoint server. It has been used heavily for about a year. I'm just trying to get this to work on a new production server we recently stood up. I have to believe this is related to some permission issue, or a component that is not installed or registered correctly. For Open XML, I believe there is just the one DLL (DocumentFormat.OpenXML.DLL) and it does not register. It is on the server from installing the .wsp package. I also tried installing Open XML 2.5 on the server along with the productivity tool and they all work fine.
The more I think about it, it just feels like a permission issue.


Q: limsup definition in Alexandroff compactification of C In the Alexandroff, or one-point compactification of $\mathbb{C}$ (by adding a point $\infty$), consider a function $f:\Omega (\subset \mathbb{C}) \to \mathbb{R}$. I was asked to justify the following definition of $\limsup$ by somebody:

$\displaystyle\limsup_{z \to p} f(z) = \displaystyle\lim_{r \to 0^+} (\sup\{ f(z) : z \in \Omega\ \cap\ U(p;r)\})$

Where $U(p;r)$ is defined as $D(p;r)^*$ (punctured disc around $p$ of radius $r$) if $p \in \mathbb{C}$,and as the annulus centered at $0$ and going from radius $\dfrac{1}{r}$ to $\infty$ if $p \notin \mathbb{C}$. The set of annuli, with $\infty$ added, form basic open sets in the one-point compactification.
I have to justify the following definition by showing that the limit on the right side exists. However, I need a clue on how to start, because in  many limit existence problems we have shown the underlying subsequence as Cauchy and used completeness to establish a limit, or figured out a candidate limit by hook or crook. I am not able to do either here.
Thanking all in advance.


Q: Reporting Services: How To Fit PDF Export On One Page? I've built a report in Reporting Services and when we browse to the report in Internet Explorer we want to be able to export the report in PDF format.  It works, but it was cutting off the columns to the right and displaying them on the next page (in PDF) because the page was too wide.  I changed the orientation to landscape and it still cut off the columns on the right.  Then I changed the page size to legal paper and it fits on one page, but we want the report on letter size paper.  Is there a way to compress the report to fit on letter size landscape?

A: Here is how to get a report to fit on a letter page:

*

*Click on the blank space outside of your report

*Look at the properties and find interactive size. Set it to 11,8.5in.  Set your Margins to 0.5in, 0.5in, 0.5in, 0.5in

*Click on the body and select properties.  Set the width to 10in and something less than 7.5 for the height.

A: I was having this issue too. I set my margins to zero, which allowed me to print on 1 pdf page instead of 2.

A: When you develop report from SpagoBI Studio
change setting of Master Page (next to Layout).
No need to change orientation but you need to
increase the width of report according to your number of columns and column with.
make sure it is greater than sum of all column's width (table width)
This will solve the issues


Q: Where do I find aux files in Overleaf? Currently I am working in a template on Overleaf. I decided I wanted to use a different citation style, so I turned this:
\bibliography{report}

into this:
\bibliographystyle{ieeetr}
\bibliography{report}

That gave the following warning:
./report.tex:
LaTeX Warning: Unused global option(s):
    [largelogo].
(no line number):
This is BibTeX, Version 0.99d (TeX Live 2016/Debian)
Capacity: max_strings=100000, hash_size=100000, hash_prime=85009
The top-level auxiliary file: report.aux
The style file: my-report.bst
Illegal, another \bibstyle command---line 46 of file report.aux
 : \bibstyle
 :          {ieeetr}
I'm skipping whatever remains of this command
Database file #1: report.bib
You've used 5 entries,
            2773 wiz_defined-function locations,
            635 strings with 6341 characters,
and the built_in function-call counts, 2901 in all, are:
= -- 265
> -- 195
< -- 2
+ -- 65

Now it seems the template already defines a citation style. The programmer in me now wants to go to line 46 in report.aux to look what happens there.
However there is no such file in my entire project. According to this FAQ answer on Overleaf, I need to download an extensive zip-version of the project to see these files. However when I do that, the zip-file again doesn't contain a report.aux file.
So my question is: does this file exist (at any point)? If yes, where do I find this file? If not, where does the warning refer to?
Note: in this question I am not directly interested in the original problem, but specifically in the report.aux file referenced in the warning.

A: This post is valid only for Overleaf version 1 (I do not know if it is still used). For Overleaf v2, see the other answer.
As far as I know, the only way to get all the auxliary files is to select
Project (if not already displayed) and then DOWNLOAD AS ZIP --> Input and Output Files.
In this way you can download a .zip with all your auxilary files.
Note that you have to use Input and Output Files, not Input Files Only, which is the default if you only click on DOWNLOAD AS ZIP.

A: Update for Overleaf version 2: the menu has changed.
If you need any additional files, you can find them in the compiler panel under "Logs and output files" and "other logs & files".


Q: Why was Thor worthy to lift Mjolnir? Especially in the beginning of the first movie, Thor is brash and often petulant. He seeks the glory of king-hood without understanding or accepting the self-sacrifice and responsibility that such a role requires. He is brave, yet selfish.
My question is Why was Thor worthy? I would think that some nice, selfless guy should be able to lift Mjolnir, but it is portrayed as some rare trait of extreme virtue that only Thor and perhaps a couple others possess.
Because Thor himself doesn't appear to be excessively virtuous, it seems like the power to lift Mjolnir was endowed on him, not earned by him, so why all this pretense about worthiness?

A: Odin fully believed Thor was worthy to take his place on the throne as King. It was only once Odin deemed Thor unworthy of being King that he lost the ability to wield Mjolnir.

Previously, both myself and KutuluMike argued that Thor's hammer hadn't been enchanted at the beginning of Thor. However, Valorum found this quote from Odin before Thor loses his hammer.

ODIN (CONT'D): So long entrusted with this mighty hammer, Mjolnir.
  Forged in the heart of a dying star, from the sacred metal of Uru.
  Only one may lift it. Only one is worthy. Who wields this hammer
  commands the lightning and the storm. Its power has no equal -- as a
  weapon, to destroy, or as a tool, to build. It is a fit companion for
  a King.
Thor Transcript via The Internet Movie Script Database

This implies that Odin believed his son was worthy to wield Mjolnir at the start of Thor. We see Odin define what he believes are the essential virtues for a ruler as he prepared to crown Thor King of Asgard.

ODIN: Today I entrust you with the greatest honor in all the Nine
  Realms. The sacred throne of Asgard. I have sacrificed much to
  achieve peace. So, too, must a new generation sacrifice to maintain
  that peace. Responsibility, duty, honor. These are not merely
  virtues to which we must aspire. They are essential to every soldier
  and to every King.
Thor turns back to face his father. Odin looks upon his son with pride.

You see these beliefs again when Odin has Thor take his vows, emphasizing the preservation of peace between worlds.

ODIN (CONT'D): Thor Odinson, do you swear to guard the Nine Realms?
THOR: I swear.
ODIN: Do you swear to preserve the peace?
THOR: I swear.
ODIN: Do you swear to cast aside all selfish ambition and pledge
  yourself only to the good of all the Realms?
THOR: I swear.

After Thor betrayed his father's trust by disobeying a direct order and attacking the frost giants, his father deemed Thor unworthy of wielding Mjolnir.

ODIN: Thor Odinson... You have disobeyed the express command of your
  King. Through your arrogance and stupidity, you have opened these
  peaceful Realms and innocent lives to the horrors of war.
You are unworthy of this Realm... unworthy of your title... unworthy
  of the loved ones you've betrayed. I hereby take from you your powers.
Odin extends his hand towards his son. Mjolnir goes flying from Thor's grasp into Odin's hand.

A: At the beginning of the movie Thor, Mjolnir is not enchanted. It's just Thor's war hammer, built for him by whoever makes Asgardian weapons. He uses it because it's his, with no other particular requirements.
After the fiasco with the Frost Giants, Odin places an enchantment on the weapon -- this is what he's doing when he whispers into the hammer, just before sending both it and Thor to Earth. You can see this in the Thor Transcript.
      Odin holds Mjolnir in his hand, stares at it bitterly. He
      closes his eyes, lost in contemplation, whispers something
      quietly.

      ODIN (CONT'D)

                     (WHISPERING)
      Whosoever holds this hammer, if he
      be worthy, shall possess the power
      of Thor.
      RUNES appear on the side of the hammer, as if carved into its
      smooth surface. The runes linger for but a moment, then
      disappear. Suddenly, Odin turns and hurls the hammer into
      the Bifrost.

At this point, Thor isn't worthy of the weapon, as we can see when he tries to lift it and fails.
By the end of the movie, his character has grown more humble and more worthy by nature of having to confront his own flaws. When he finally

 sacrifices his life to save the town

he becomes worthy of the hammer, and remains so from then on.

It's important to note that the definition of "worthy" here is the Asgardian definition. There are likely things about it that may seem unusual to us, but imagine as a rough estimate what a Viking might think of as worthy. Being brave in battle, being able to defeat enemies, defending the weak and helpless, putting yourself in harms way for the sake of others, etc. These are the things that appear to qualify as worthy.
Being obnoxious, or a braggart, or a drunk, or promiscuous -- none of these things really detract from someone's "worthiness" to wield a weapon of battle. They may be things that we see as detrimental to someone's personality, but in the eyes of Odin's enchantment, as long as that person continues to exhibit the virutes it cares about, everything else is irrelevant.
Also note that, at least in the source material, many other people are equally as worthy as Thor to wield Mjolnir. Besides Vision, we haven't seen that happen in the MCU yet, but there was a hint of it in Age of Ultron -- Steve Rogers did move Mjolnir ever so slightly from its resting place. This wasn't a mistake either -- the camera cuts to Thor who clearly noticed and was worried, before relaxing when Rogers fails to lift it. Whether this was just an Easter Egg for comics fans, or it was a hook for future development, remains to be seen.

A: Despite Thor's brash personality he has fought for justice and saved many people from foreign worlds and defended Asgard and Earth. He is worthy to be king but realize his time is spent answering the call to protect vulnerable populations throughout the nine world and other galaxies thereby being absent from Asgard. Odin All Father has gifted him with Mjolnir to use as a weapon to build or to destroy. Mjolnir is made from the powered essence of a dying star. It can only be lifted by those that are worthy. Thor is extremely worthy by his very nature and by his great deeds.

A: From what the MCU has shown us, it seems that Mjolnir's main qualification for worthiness is that the one who wields it must have peace and safety as the overall goal of their life, making great sacrifices in the name of it, including the sacrifice of their own life.
The moment that Thor once again became worthy in Thor was the moment that he was willing to lay his own life down for Earth, a planet which he had hardly any connection to at the time.
He wanted to save not only Jane, but as he stated to Coulson, the entirety of Earth, even though earth was an unfamiliar place. That shows serious devotion to peace for its own sake.
Odin is worthy of wielding the hammer as well, as his conversations with Thor have shown that he desires peace and coexistence above anything else.
Mjolnir chooses people who inherently want to see peace and will do anything they must to find peace in every situation. Mjolnir presents itself as a tool for this peace.

A: From the original transcript Odin says "only one is worthy, only one can lift it". He does not explicitly say "anyone can be worthy, anyone can lift it". When Thor is deemed unworthy, Odin strips him of his power and enchants it to Mjolnir. When he is worthy again he will lift the hammer and gain his power back. We do not know that the enchantment is everlasting. We do know that Thor has his godly powers when he isn't wielding the hammer after he is deemed worthy again. Do you really think Odin would allow for the power of a god to be stumbled across by any one else other than the one he intended? No. Thor is the only one who is worthy. Odin handed it down to him in that way.


Q: Because the plugin below does not work when used in the response of a getJSON (function ($) {
    $.fn.reverse = function(fn) {
       var i = this.length;
       while(i--) {
           fn.call(this[i], i, this[i])
       }
    };
}(jQuery));

Below the use of jquery code with alphabetical data
$.fn.reverse ($response, function (k, v) {
    $("#selector").append('
' + v.name + '
');
});

A: You need to apply the plugin to any jQuery object, so you need to do something like this to use the plugin.
$($response).reverse(function (k, v) { /*.. code here ...*/ });
//-^^^- wrap using jQuery if it's not a jQuery object

Refer : How to Create a Basic Plugin


Q: Remove layers and objects in FabricJS My question is, how to remove object and layer in same time using fabricJS delete function?
Here is my jQuery for deleting objects:
$('#remove').on('click', function () {
    deleteObjects();
    $(".deleteBtn").remove();
});

Here is my FabricJS example with layer control https://jsfiddle.net/peLcju2h/15/
Thank you :)

A: If you take a look through the Fabric JS documentation you'll notice that every object extends the Fabric.Object.
The Fabric.Object has a remove() method that you can call to remove any Fabric.Object or class that extends Fabric.Object, which is just about every class that can be rendered onto a canvas, with the exception of a handful of less commonly used classes.
Take a look at the documentation of the remove() function here:
http://fabricjs.com/docs/fabric.Object.html#remove
Also there is a hierarchy of classes on the main page of their documentation which can be found here:
http://fabricjs.com/docs/


Q: Refresh UltraCombo Content I have to do some maintenance on an old VB.NET application (Visual Studio 2003) that uses Infragistics NetAdvantage 2006. I have a UltraCombo control binded to a DataView.
How can I refresh the content displayed after a change in the database?

A: It sounds like you'll need to repopulate the DataView from the database and refresh your databinding on the UltraCombo; probably pretty close to the same code you use to initially populate the DataView and set the UltraCombo databinding.
You may get a more complete answer if you post some code.


Q: LINQ-to-SQL not submitting changes to local database I have a local, SQL Server Compact database in an application I am creating. I generated a .dbml file I can use for LINQ-to-SQL purposes using the SqlMetal.exe tool, which worked fine - I now have the table objects for use in my application.
I have a strange issue though. Even after calling SubmitChanges() on my DataContext, the data never commits. But strangely, after adding the rows, these rows do appear in the table object on the datacontext, but not in the table. What shocked me is even after stopping and starting my application, these rows still existed in the DataContext - but after a few minutes they seem to disappear.
Have I configured this correctly? Are there any more steps I need to do after using SqlMetal to allow the LINQ to commit changes?

A: I am assuming that you linked to the dbml file using the default properties.  This means that, each time you start a debug session, the file will be copied into your output directory and changes made to it will only be seen for that session (i.e., "Copy -> Always").
If you want the changes to persist then right click the file -> properties -> Copy Never.  By default the IDE assumes that you don't want to modify the original database, only a copy for debugging purposes.


Q: Not getting Form value, in java I have a form and bean. From bean I am retreiving values and setting in DTO. That is also setting in FORM. But getter property value is null. I don't know what is the problem here. Can anybody suggest on this?
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

public class LoginForm extends XFormBase {
    private String title;

    public void setTitle(String title) {
       this.titleValue = title;
       System.out.println(" Form set"+titleValue);
    }

    public String getTitle() {
       this.title = titleValue;
       System.out.println(" Form get"+titleValue);
       return title;
   }
}

A: It looks like there is an bug:
the setTitle method, does not set the title but the titleValue!
I would guess the correct implementation is:
public void setTitle(String title) {
   this.title = title;
   System.out.println(" Form set"+title);
}

A: Try using this. I suspect a mistake in your getter and setter implementation
public class LoginForm extends XFormBase {
    private String title;

    public void setTitle(String titleValue ) {
       this.title= titleValue;
       System.out.println(" Form set"+this.title);
    }

    public String getTitle() {
       System.out.println(" Form get"+this.title);
       return this.title;
   }
}


Q: Unexpected result at summing numbers using a while loops in console application I am trying to make a program to sum numbers until the user enter OK.
The program make the sum, but return a bad result.
i'm not sure where is my error...
int sum = 0;
Console.WriteLine("Enter number:");
int num = Convert.ToInt32(Console.ReadLine());
while (Console.ReadLine() != "OK")
    {
       sum += num;
    }
Console.WriteLine(sum);

A: you don't keep the number the use enter in the while loop.
you need to input the readline to a variable.
var num = Console.Readline();
sum += num; //parse first

A: Inside your while loop you need to update num:
int num = Convert.ToInt32(Console.ReadLine());
while (Console.ReadLine() != "OK")
{
    num = Int32.Parse(Console.ReadLine());
    sum += num;
}

Also just as a note, if you need your program to be a little safer, you can you use the following:
int num;
if(Int32.TryParse(Console.ReadLine(), out num)) {
    //do something..
}
else {
    //do something else.. like end program, throw exception etc.
}

Int32.TryParse:

Converts the string representation of a number to its 32-bit signed
  integer equivalent. A return value indicates whether the conversion
  succeeded

This way you can do something in the instance that the input string was not a valid conversion.  Example: if someone input cat, which can not be converted to an int, it would crash your program without the TryParse.

A: You need to input the number once per iteration, and store it each time. So each value retrieved from Console.ReadLine() needs to be captured in an assignment statement, then converted to a number if it is not "OK".
I think you're after this:
int sum = 0;
string input;

Console.WriteLine("Enter number: ");
while ((input = Console.ReadLine()) != "OK")
{
    int inputNum = Convert.ToInt32(input);
    sum += num;

    Console.WriteLine("Enter number: ");
}

The statement (input = Console.ReadLine() assigns the user input to the input variable, then the assignment statement returns the value of input. Then that value is compared against OK.
An alternative way to get input, then check it is:
Console.WriteLine("Enter number: ");
input = Console.ReadLine()
while (input != "OK")
{
    ...
    Console.WriteLine("Enter number: ");
    input = Console.ReadLine()
}

A: int sum = 0;
Console.WriteLine("Enter number:");
int num = int.Parse(Console.ReadLine());
while (sum< num)
{
     sum++;
}
Console.WriteLine(sum);


Q: Is it possible to capture Android Screen multiple times simultaneously? Is it possible to capture Android screen multiple times with different settings on Android 13? I've tried two approaches:

*

*Create two media projections using the same Activity.RESULT_OK and intent

*Create one media projection and two virtual displays by invoking the createVirtualDisplay method twice with the different parameters.

I need this because I need to cast one screen (virtual display, technically speaking) via the WebRTC with the ScreenCapturerAndroid and record on the device the second using the MediaRecorder API.
On devices with the API Level prior to 33 (Android 11), the approach #1 works fine, but not on devices with API Level 33.
Are there any ways to overcome this?


Q: Git : Unable to unlink / cannot create directory, on ignored folder I'm using SourceTree, and when I try to checkout from one branch to another, I've got the following error message :
warning: unable to unlink sf2/web/bundles/mybundle: Permission denied
fatal: cannot create directory at 'sf2/web/bundles/mybundle': Permission denied

Though, on both branches, the folders in sf2/web/bundles/ are ignored, since many commits, as you can see in my .gitignore :
/sf2/web/bundles/*

That's pretty normal I guess, I'm on Windows, symlinks are sh*t.
As a workaround, I can remove the folder and then checkout, but that's not so great.
It seems that, because I commited this folder/symlink some times at the begining, it now has to redo all the modifications step by step, including the ignored folders ?!
EDIT : I confirm it's creating this folder, an old version of it, even if it's supposed to be ignored now. And if I remove this folder, it's showing the few old files inside as working copy changes...

A: Finally found the solution here :
Applying .gitignore to committed files
It's apparently because some files inside has been commited one time, so they are in the repo.
If I understand it right, that means it's very important to modify the .gitignore before commiting any file inside, otherwise it can be a mess !


Q: Failed to create maven project with maven-archetype-webapp When I tried to create a Maven project with maven-archetype-webapp, some problems came out.
An internal error occurred during: "Creating maven-archetype-webapp".
org/apache/maven/shared/filtering/MavenFilteringException

An internal error occurred during: "Updating Maven Dependencies".
org/apache/maven/shared/filtering/MavenFilteringException

I have tried a lot of solutions related to this, nothing worked.
How can I solve this?Thanks!
ps:I was using eclipse 4.4.1 and m2e 1.5.0


Q: "Invalid host in redirect target" using ACME on pfsense I've set up pfsense to manage my network, and I have the ACME plug in installed. I'm to correctly direct traffic to my secure webservers, but first I need to get the certificates onto PFSense.
At the moment, my certificates are using certbot on the webservers, but I want pfsense to manage all the certs.
When I use the stand alone method for the ACME plugin, I get this error, and I'm not sure where I went wrong in setting up pfsense. If someone could help me out, it would be great, thanks.
Renewing certificate
account: myaccount
server: letsencrypt-production-2
/usr/local/pkg/acme/acme.sh  --issue  -d 'domain.ca' --standalone --listen-v4 --httpport '80' --home '/tmp/acme/myaccount/' --accountconf '/tmp/acme/myaccount/accountconf.conf' --force --reloadCmd '/tmp/acme/myaccount/reloadcmd.sh' --log-level 3 --log '/tmp/acme/myaccount/acme_issuecert.log'
Array
(
    [path] => /etc:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin/
    [PATH] => /etc:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin/
    [port] => 80
    [ipv6] =>
)
[Fri Jul 10 10:53:49 MDT 2020] Standalone mode.
[Fri Jul 10 10:53:49 MDT 2020] Single domain='domain.ca'
[Fri Jul 10 10:53:49 MDT 2020] Getting domain auth token for each domain
[Fri Jul 10 10:53:51 MDT 2020] Getting webroot for domain='domain.ca'
[Fri Jul 10 10:53:51 MDT 2020] Verifying: domain.ca
[Fri Jul 10 10:53:51 MDT 2020] Standalone mode server
[Fri Jul 10 10:53:55 MDT 2020] domain.ca:Verify error:Fetching https://domain.ca.well-known/acme-challenge/VBYshVeuP8BQXWnuUMggKU3Rn_cD4k5Tg9FD0gS_-7k: **Invalid host in redirect target**

A: My problem was with AAAA DNS record. Ipv6 record pointed to another host.


Q: php createimage does not output an image to browser can you help?
Using XAMPP I have localhost/drawrectangle.php containing the following code which does not render an image, ll I get is an image placeholder, can you help?
<?php

// Create a 200 x 200 image
$canvas = imagecreatetruecolor(200, 200);

// Allocate colors
$pink = imagecolorallocate($canvas, 255, 105, 180);
$white = imagecolorallocate($canvas, 255, 255, 255);
$green = imagecolorallocate($canvas, 132, 135, 28);

// Draw three rectangles each with its own color
imagerectangle($canvas, 50, 50, 150, 150, $pink);
imagerectangle($canvas, 45, 60, 120, 100, $white);
imagerectangle($canvas, 100, 120, 75, 160, $green);

// Output and free from memory
header('Content-Type: image/jpeg');

imagejpeg($canvas);
imagedestroy($canvas);

?>


Q: C# Dates - Databases, Display and Localization What are some Date (& Time) format best practices when wanting to adhere to localization in a new application.
For example, what format do you use to write dates to the database.
How do you display the following to the user using their own locale settings once the date has been obtained from the database.
ShortDate
LongDate
DateTime
Any tips for punters appreciated.

A: Always store dates in UTC and when displaying them, calculate the local time based on the user's time zone (which you will have to ask for at some point and store).

A: DateTime2 (aka long date in MS SQL) is only going to be useful if you need that level of granularity or 10,000 year range. DateTime seems to be the norm. If you only need the date portion and can ignore the time, use the new Date datatype in SQL 2008. Ask your clients what granularity is necessary for the project.
UTC is the best way to store the date since your server or your client can be anywhere in the world (assuming a web-based deployment). Also, if you move your server or have a new co-located server you won't need to adjust for timezone since everyone is already running on UTC.
You should only convert from UTC to local time in the presentation later. If your client is using a web browser you can get the timezone offset from javascript. Then if you need that value on the server-side, either store the value in a cookie or in a hidden HTML field for easy access.
I've used a tweaked version of this javascript sample from CodeProject to do the same.


Q: Nginx + Django + Gunicorn: 502 Bad Gateway upstream prematurely closed connection while reading response header from upstream I am creating (for the first time) a website.
More specifically, the user uploads an image and after some computations the website displays some result.
However, sometimes (not always, sometimes just retrying or changing image it works) during this process I get "502 Bad Gateway nginx/1.10.3 (Ubuntu)"
Looking at the error I get:
[error] 7836#7836: *16 upstream prematurely closed connection while reading response header from upstream, client: 131.175.147.1, server: _, request: "POST / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "165.227.170.231", referrer: "http://165.227.170.231/"

I tried this but it did not help much, while I think this is not my case.
The settings are:
/etc/nginx/sites-available/django :
upstream app_server {
server unix:/home/django/gunicorn.socket fail_timeout=0;
}

server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;

root /usr/share/nginx/html;
index index.html index.htm;

client_max_body_size 4G;
server_name _;

keepalive_timeout 5;

# Your Django project's media files - amend as required
location /media  {
    alias /home/django/django_project/django_project/media;
}

# your Django project's static files - amend as required
location /static {
    alias /home/django/django_project/django_project/static;
}

# Proxy the static assests for the Django Admin panel
location /static/admin {
   alias /usr/lib/python2.7/dist-packages/django/contrib/admin/static/admin/;
}

location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
        proxy_buffering off;

        proxy_connect_timeout 75s;
        proxy_read_timeout 300s;

        proxy_pass http://app_server;
        }
}

The /etc/nginx/nginx.conf:
user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
   ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;

    proxy_connect_timeout 75s;
    proxy_read_timeout 300s;
  }

  #mail {
  #       # See sample authentication script at:
  #       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
  #
  #       # auth_http localhost/auth.php;
  #       # pop3_capabilities "TOP" "USER";
  #       # imap_capabilities "IMAP4rev1" "UIDPLUS";
  #
  #       server {
  #               listen     localhost:110;
  #               protocol   pop3;
  #               proxy      on;

  #       }
  #}

The /ect/gunicorn.d/gunicorn.py:
"""gunicorn WSGI server configuration."""
from multiprocessing import cpu_count
from os import environ

def max_workers():
    return cpu_count() * 2 + 1

    max_requests = 1000
    worker_class = 'gevent'
    workers = max_workers()
    TIMEOUT=120

And I start gunicorn in this way:
service gunicorn start --timeout 300

Basically, I tried everywhere to avoid timing out, but still encounter the same problem.


Q: Optimising the query which has joins and unions in mysql I am using the laravel to build my web app. In that for listing all orders I have an query but it takes upto 40s in my localhost whereas in goddady shared hosting it takes upto 95s. Although I implemented the server side datatable yet the query takes bit long to execute. I need someone to suggest or help to make the query to excute more efficient. There are majorly two sets and I make that union.
select * from ((
select `subscription`.`id`,
`subscription`.`order_id`,
`users`.`name` as `user_name`,
`subscription`.`new_dated`,
`subscription`.`rescheduling_delivery_date` as expected_date,
COUNT(`subscription_items`.`product_id`) as items,
`subscription`.`od_dis_total` as `total`,
`subscription`.`order_discount`,
`area`.`area_name`,
`subscribe_orders`.`action` as ordertype,
driver.name as driver_name,
'NA' as payment_mode,
`payment_status`.`status_name` as payment_status,
`subscription_status`.`status_name` as order_status,
`subscription`.`od_payment_method`,
`subscription_items`.`product_id`,
subscription.delivered_dated
from `subscription`
left join `subscription_items` on `subscription`.`id` = `subscription_items`.`subscription_id`
left join `users` on `subscription`.`user_id` = `users`.`id`
left join `users` as `driver` on `subscription`.`driver_id` = `driver`.`id`
left join `ycias_address` on `subscription`.`add_id` = `ycias_address`.`id`
left join `area` on `ycias_address`.`area_id` = `area`.`id`
left join `subscribe_order_items` on `subscription`.`subscribe_order_id` = `subscribe_order_items`.`subscribe_order_id`
left join `subscribe_orders` on `subscription`.`subscribe_order_id` = `subscribe_orders`.`id`
left join `payment_status` on `subscription`.`payment_status` = `payment_status`.`id`
left join `subscription_status` on `subscription`.`od_status` = `subscription_status`.`id`
group by `subscription_items`.`subscription_id`)
union (
select `orders`.`id`,
`orders`.`order_id`,
`users`.`name` as `user_name`,
`orders`.`new_dated`,
`orders`.`expected_delivery_date` as expected_date,
COUNT(order_items.product_id) as items,
`orders`.`od_dis_total` as `total`,
`orders`.`order_discount`,
`area`.`area_name`,
'Instant Order' as ordertype,
driver.name as driver_name,
orders.payment_mode,
`payment_status`.`status_name` as payment_status,
`order_status`.`status_name` as order_status,
`orders`.`od_payment_method`,
`order_items`.`product_id`,
`orders`.`delivered_dated`
from `orders`
left join `order_items` on `orders`.`id` = `order_items`.`order_id`
left join `users` on `users`.`id` = `orders`.`user_id`
left join `users` as `driver` on `driver`.`id` = `orders`.`driver_id`
left join `ycias_address` on `orders`.`add_id` = `ycias_address`.`id`
left join `area` on `ycias_address`.`area_id` = `area`.`id`
left join `payment_status` on `orders`.`payment_status` = `payment_status`.`id`
left join `order_status` on `orders`.`od_status` = `order_status`.`id`
group by `order_items`.`order_id`)) as all_orders limit 10 offset 0

A: As per the suggestion given by Andy Lester I have added the index for the necessary columns. So the execution time is reduced to half that is 18 secs in localhost. I further investigated that the index columns are of datatype VARCHAR. So I changed that to INT and then executed, got results within 0.9 secs. Thanks to Andy Lester.


Q: How do I place a Google recaptcha in my website successfully? I am having real trouble putting a Google recaptcha into my website. There seems to be no easy to follow tutorial. I am brand new to JavaScript, but am building a website which receives a huge amount of spam from the contact form. I'd like a Google recaptcha form, possibly v2 as that seems the 'easiest' but I am still having issues.
I have PHP, JS and HTML and I am not understanding how any of it links, and it is not working. The form submits successfully, however, there is no way of telling the form has submitted, nothing happens on the page. I would like a Bootstrap success alert to take place when I press submit.
Here is the PHP:
<?php

    $Fname = $_POST['Fname'];
    $Lname = $_POST['Lname'];
    $email = $_POST['email'];
    $number = $_POST['number'];
    $company = $_POST['company'];
    $message = $_POST['message'];

    $email_from = "Your website";
    $email_subject = "You have a new submission form from Your website";
    $email_body = "First Name: $Fname.\n".
                    "Last Name: $Lname.\n".
                    "Email Address: $email.\n".
                    "Telephone Number: $number.\n".
                    "Company Name: $company.\n".
                    "Message: $message.\n";

    $to = "howdy@yourwebsite.co.uk";
    $headers = "From: $email_from \r\n";
    $headers .= "Reply-To: $email \r\n";

    $captcha;
    if(isset($_POST['email'])){
        $email=$_POST['email'];
    }
    if(isset($_POST['message'])){
        $message=$_POST['message'];
    }
    if(isset($_POST['g-recaptcha-response'])){
        $captcha=$_POST['g-recaptcha-response'];
    }
    if(!$captcha){
        echo '
Please check the "I am not a robot" checkbox"
';
        exit;
    }
    $secretKey = 'acombinationoflettersandnumbers';
    $ip = $_SERVER['REMOTE_ADDR'];
    // post request to the server
    $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
    $response = file_get_contents($url);
    $responseKeys = json_decode($response, true);
    // should return JSON with success as true
    if($responseKeys["success"]) {

        mail($to,$email_subject,$email_body,$headers);

    } else {
        echo '
This has been unsuccessful according to our security checks
';
    }
?>

Here is the HTML form:
<form action="contact.php" id="contact-form" method="POST" role="form">

                    First Name*
                    <input id="form_name" type="text" class="form-control" name="Fname" placeholder="David" required data-error='Please fill in your first name'>

                    Last name*
                    <input id="form_lastname" type="text" class="form-control" name="Lname" placeholder="Beckham" required data-error="Please fill in your last name">

                    Email address*
                    <input id="form_email" type="email" class="form-control" name="email" placeholder="becks@example.com" required data-error="Please provide your email address">

                    Contact number*
                    <input id="form_number" type="number" class="form-control" name="number" placeholder="01234567890" required data-error="Please provide a contact number">

                    Your company name
                    <input id="form_company" type="text" class="form-control" name="company" placeholder="Ex-footballers r us">

                    Your message*
                    <textarea id="form_message" class="form-control" name="message" cols="30" rows="10" placeholder="I need the world's best website...HELP!" required></textarea>

                  <input type="submit" class="btn btn-outline-brand btn-block" name="submit" value="Send enquiry">

            </form>

Here is the JavaScript:
var onloadCallback = function() {
        grecaptcha.render('html_element', {
        'sitekey' : 'acombinationoflettersandnumbers'
      });
      };
      onloadCallback();

    $('form').on('submit', function(e) {
      if(grecaptcha.getResponse() == "") {
      e.preventDefault();
      alert("You can't proceed!");
    } else {
      alert("Thank you");
    }
    });

I have only got this far by following steps from lots of different tutorials and am not sure if any of it is correct. Hope someone is able to assist with a step by step process that allows me submit a contact form, with a success Bootstrap alert and form refresh once it has been submitted.
Thank you!

A: You could try something like this:
front-end

back-end
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey";
$response = file_get_contents($url);
$response = json_decode($response);
if ($response->success) {
 // not a robot
} else {
 // robot
}

The Recaptcha response will be placed in your g-recaptcha input tag. This value will be sent to the back-end (PHP) of the application. There you can validate the Recaptcha response and show a result based on the outcome of the Recaptcha.


Q: CanvasJS, issues with setting a user input Title for chart I am currently facing an issue with creating a user input title for a canvasJS chart. I am currently running through the tutorial over at canvasJS, and I thought it would make a neat small project to create a user input oriented pie chart.
The current issue I am facing is trying to get the text inputted from HTML to show up correctly.
[JSFiddle]https://jsfiddle.net/n3n0pssc/
var chart = new CanvasJS.Chart("chartContainer",{
               title:{
document.getElementById("chartTitle").setAttribute("text")
}`

I understand that the title must be set by tying it together with the addDataPointsAndRender function, but I am confused as canvasJS only displays set text by title: {text : "title"} and I am trying to figure out how it would go together by fetching input text.
Thank you for any assistance.

A: You can set the user inputs to the chart by either using chart options or by using the set() methods of the CanvasJS API.
I have modified your jsfiddle, and its working now.
function addDataPointsAndRender(){
    chart.options.title.text =document.getElementById("chartTitle").value;
    chart.options.data[0].dataPoints.push({
        y: parseFloat(document.getElementById("yValue1").value),
        indexLabel: document.getElementById("indexLabel1").value
    });
    chart.render();
}

Also have a look at :

*

*Tutorial on Rendering chart from user Input

*Updating Chart Options

*CanvasJS Methods & Properties Documentation


Q: Java: Creating New Strings During Runtime to Edit I'm creating a Mad Lib generator in Java. If you know what a Mad Lib is, this will be easier to understand. Also, I'm new to Java, so bear with me here. I want to make it so that each Mad Lib only asks for the number of adjectives, nouns, etc. that are in that specific one. For example, Mad Lib 1 may have 3 nouns, while Mad Lib 2 has 5 nouns. Is there a way to write a separate method to be run X times, creating X new strings (for the player to enter X nouns), and giving each string a different name? Just giving the strings names like nounA, nounB, nounC, or noun1, noun2, noun3 would be perfect. I need the final story to be able to differentiate between them. It will be really nice if each time I decide to add another Mad Lib to my program to just be able to loop an addNoun() method 8 times instead of writing
String nounA = scan.next();
System.out.print("\f");
String nounB = scan.next();
System.out.print("\f");

...and so on every time for each part of speech. I have not yet learned about arrays, and I think this may have a solution involving that. Like I said, I'm new to Java, so if you try to show me anything advanced, please explain it in a way that I can understand it or find a simpler way to do it.

A: If I understand your problem correct then you need to use ArrayList and HashMap to achieve this:
First you can create ArrayList of String to store X nouns. An ex: of Arraylist is:
  List<String> nouns = new ArrayList<String>();
  nouns.add('nounA'); // add related noun
  //or
  String nounStr = 'new Noun'
  nouns.add(nounStr);

Then you can categorise particular nouns by HashMap
HashMap<String, List<String> > nounCategory = new HashMap<String, List<String> >();
nounCategory.put('madLib1', 'nouns'); // add all list with a unique key madLib1 ...

To learn more about using List and HashMap read reference List:here and HashMap:here

A: If you have the count of nouns, say, in int nounCount, use arrays like this:
String[] nouns = new String[nounCount]; // Create an array
for (int i = 0; i < nouns.length; i++) {
    nouns[i] = scan.next(); // Set each item
}

Then you would be able to access different words as noun[0], noun[1], etc. You're likely to use loops and store index of selected noun somewhere though.
See also: Java arrays tutorial


Q: How to create custom component using JSF 1.2? I am new in the JSF world, please tell me step by step answer of how to create JSF custom component i search on the net but i didn't get any proper answer or give me some link which shows how to create custom component.
Thanks
Vinod

A: Googling for "extend UIComponentELTag" or "extends UIComponentELTag" should yield enough hints.
This is one of my favourites: http://blogs.steeplesoft.com/2006/12/jsf-component-writing-check-list/

A: RichFaces includes CDK (component development kit) that can be used for components development.
Here is the link to the guide: RichFaces CDK Developer Guide


Q: When validation fails, associated record count still changes Here's a problem.   I have my models:
class Collection < ActiveRecord::Base

    has_many    :collection_ownerships
    has_many    :items
    has_many    :users, :through => :collection_ownerships

    validates :title, presence: true, length: { maximum: 25 }
    validates :description, length: { maximum: 100 }
end

class Item < ActiveRecord::Base

    belongs_to :collection
    has_many :item_ownerships, :dependent => :destroy
    accepts_nested_attributes_for :item_ownerships

    validates :name, :presence => true, length: { maximum: 50 }
    validates :collection, :presence => true

end

class ItemOwnership < ActiveRecord::Base

    belongs_to  :item
    belongs_to  :user

    validates :user, :presence => true
    validates :item, :presence => true
end

Here is my controller code:
before_filter(:except => :toggle_item_owned_state) do
    @collection = current_user.collections.find(params[:collection_id])
end

def new
    @item = @collection.items.new
    @item_ownership = @item.item_ownerships.build(:owned => true, :user => current_user, :item => @item)
end

def create
    @item = @collection.items.new(item_params)
    @item_ownership = @item.item_ownerships.build(:owned => false, :user => current_user, :item => @item)

    if @item.save
        redirect_to collection_items_path(@collection)
    else
        flash.now[:alert] = "There was a problem saving this item."
        render "new"
    end
end

I have a couple of controller tests:
describe 'POST#create' do

            context "with bad data" do
                it "should not create a new record for 'items'" do
                    expect { post :create, :collection_id => batman_collection.id,
                                       :item => { :name => '',
                                                :item_ownership_attributes => { :owned => '1'} }
                            }.to change(Item,:count).by(0)
                end

                it "should not create new record 'item_ownerships'" do
                    expect { post :create, :collection_id => batman_collection.id,
                   :item => { :name => 'item_name',
                            :item_ownership_attributes => { :owned => '1'} }
                            }.to change(ItemOwnership,:count).by(0)
                end
            end
        end

When I run my tests, the second one fails:
  1) ItemsController authenticated user POST#create with bad data should not create new record 'item_ownerships'
     Failure/Error: expect { post :create, :collection_id => batman_collection.id,
       expected #count to have changed by 0, but was changed by 1
     # ./spec/controllers/items_controller_spec.rb:62:in `block (5 levels) in <top (required)>'

And ultimately this reflects in the view as well.   Now, when I look in the db, I don't see the record created.   I assume this his happening because somehow Count is reflecting the count of objects in memory, not in the db.
How can I get a handle on the situation.   The problem manifests itself in that when the form is submitted for populating the validation fails for Item, however, multiple instances of ItemOwnership end up showing up on form.
Thanks

A: I found the problem.  My second test is wrong as it's actually submitting a valid request to the server in that 'name' is not blank.
I removed it and now the test passes.

A: Rails will by default save records created from nested attributes even if the validations of the parent record fails. Thats why Item.count increases. .count unlike collection#size always queries the database.
What you need to do is create a validation on Item that tells Rails that an Item is not valid unless the parent collection is valid.
class Item < ActiveRecord::Base

    belongs_to :collection
    has_many :item_ownerships, :dependent => :destroy
    accepts_nested_attributes_for :item_ownerships

    validates :name, :presence => true, length: { maximum: 50 }
    validates :collection, :presence => true
    validates_associated :collection #!

end

http://guides.rubyonrails.org/active_record_validations.html#validates-associated


Q: How do I determine the physical inode limit? How do I determine the maximum number of inodes physically possible?  Or is this a software limit?
I work on a GPFS file system.  According to /usr/lpp/mmfs/bin/mmlsfileset gpfs0 -i I have a MaxInodes = 134217728. This is the value of a 27 bit unsigned integer, which is unconvincing. It seems like a software set limit. Is it?

A: Inodes do not have a physical relationship to disk characteristics, except as is a side-effect of the particular file system's design.
inodes are a filesystem metadata concept, and are used to attach metadata to on-disk structures or meta-structures (like directories, which are an inode that lists inodes reflecting its contents). As such, the any limitation on inodes is based on structures created when the disk is formatted for a given filesystem type.
From the link above:

Space for inodes must be set aside when an operating system (or a new
  filesystem) is installed and that system does its initial structuring
  of the filesystem. Within any filesystem, the maximum number of
  inodes, and hence the maximum number of files, is set when the
  filesystem is created.

So, yes, the limit is based on software either in the OS or the file system drivers. Linux file systems generally allow the OS to play a role in determining the number of inodes when formatting a disk.

The default setting creates an inode for every 2K bytes contained in
  the filesystem, but the number can be adjusted by the user when
  creating the filesystem. For example, it can be wise to create fewer
  inodes when setting up a filesystem that will contain just a few large
  files. Similarly, for a filesystem intended for mostly small files, it
  is advisable to allocate more space to inodes and less to file
  contents.

So by default most linuxes will allocate
ceil(formattedSizeInBytes/(2 * 1024)) => initialInodes.
This indicates (among other things) that the count of inodes will always be an exact power of two (as both the divisor and the dividend are intrinsically powers of 2).
Now, all that said, many older file systems were designed to store a single file per sector or block, so in those cases, the number of inodes is a function of the number of sectors the disk provides (plus whatever the file system creators deemed appropriate for links and directories, etc).
GPFS is an older filesystem, but it is designed for parallel access by mainframes and supercomputers, using techniques like multi-disk striping, so it is already going to great extents to divorce its operation from the physical characteristics of individual physical disks.


Q: Best practice for keeping denormalized schema up to date? I'm creating a game with points for doing little things, so I have a schema as such:
create table points (
  id int,
  points int,
  reason varchar(10)
)

and to get the number of points a user has is trivial:
select sum(points) as total from points where id = ?

however, performance has become more and more of an issue as the points table expand.  I want to do something like:
create table pointtotal (
  id int,
  totalpoints int
)

what is the best practice for keeping them in sync?  Do I try to update pointtotal on every change?  Do I run a daily script?
(Assume I have the right keys - they were left out for conciseness)
Edit:
Here are some characteristics that I left out but should be helpful:
Inserts/Updates to Points are not all that frequent
There are a large number of entries, and there are a large number of requests - the keys were pretty trivial, as you can see.

A: The best practice is to use a normalized database schema.  Then the DBMS keeps it up to date, so you don't have to.
But I understand the tradeoff that makes a denormalized design attractive.  In that case, the best practice is to update the total on every change.  Investigate triggers.  The advantage of this practice is that you can make the total keep in sync with the changes so you never have to think about whether it's out of date or not.  If one change is committed, then the updated total is committed too.
However, this has some weaknesses with respect to concurrent changes.  If you need to accommodate concurrent changes to the same totals, and you can tolerate the totals being "eventually consistent," then use periodic recalculation of the total, so you can be sure only one process at a time is changing the total.
Another good practice is to cache aggregate totals outside the database, e.g. memcached or in application variables, so you don't have to hit the database every time you need to display the value.

The query "select sum(points) as total from points where id = ?" should not take 2 seconds, even if you have a huge number of rows and a lot of requests.
If you have a covering index defined over (id, points) then the query can produce the result without reading data from the table at all; it can calculate the total by reading values from the index itself.  Use EXPLAIN to analyze your query and look for the "Using index" note in the Extra column.
CREATE TABLE Points (
  id     INT,
  points INT,
  reason VARCHAR(10),
  KEY    id (id,points)
);

EXPLAIN SELECT SUM(points) AS total FROM Points WHERE id = 1;

+----+-------------+--------+------+---------------+------+---------+-------+------+--------------------------+
| id | select_type | table  | type | possible_keys | key  | key_len | ref   | rows | Extra                    |
+----+-------------+--------+------+---------------+------+---------+-------+------+--------------------------+
|  1 | SIMPLE      | points | ref  | id            | id   | 5       | const |    9 | Using where; Using index |
+----+-------------+--------+------+---------------+------+---------+-------+------+--------------------------+

A: By all means keep the underlying table normalized. If you can deal with data potentially being one day old, run a script each nigh (you can schedule it), to do the roll up and populate the new table. Best to just re-create the thing each night from the source table to prevent any inconsistencies between the two.
That said, with the size of your record, you must either have very slow server, or very large # of records, because a record that small, with an indexed field on id should sum very quickly for you - however, I am of the mindset that if you can improve user response time by even a few seconds, there is no reason not to use rollup tables - even if DB purists object.

A: Have the extra totalpoints column on the same table, and create/update the value of totalpoints for every row creation/update.
If you need totalpoints for a certain record, you can lookup the value without computing totalpoints. For example if you need the last value of totalpoint, you can get it like this:
SELECT totalpoint FROM point ORDER BY id DESC LIMIT 1;

A: There is another approach: caching. Even if it's cached for only a few seconds or minutes, that is a win on a frequently accessed value. And it's possible to dissociate the cache-fetch with the cache-update. That way, a reasonably current value is always returned in constant time. The tricky bit is having the fetch spawning a new process to do the update.

A: I'd suggest to create a layer that you use to access and modify the data. You can use these DB access functions to encapsulate the data maintenance in all tables to keep the redundant data in sync.

A: You could go either way in this case, because it's not very complicated.
I prefer, as a general rule, to allow the data to be temporarily inconsistent, by having just enough redundancy, and have a periodic process resolve the inconsistencies. However, there is no harm in having a trigger mechanism to encourage early execution of the periodic process.
I feel this way because relying on event-based notification-style code to keep things consistent can, in more complex cases, greatly complicate the code and make verification difficult.

A: You could also create another reporting schema and have it reload at fixed intervals via some process that does the calculations.  This is not applicable to realtime information - but is very standard way of doing things.

A: Keeping Denormalized Values Correct


Q: Why aren't composed self-recursive functions with same data structure (same dims) on in and out inlined together with other recursions? In tutorial https://markkarpov.com/tutorial/ghc-optimization-and-fusion.html#fusion-without-rewrite-rules is a code example, which will not be optimized by fusion.
map0 :: (a -> b) -> [a] -> [b]
map0 _ []     = []
map0 f (x:xs) = f x : map0 f xs

foldr0 :: (a -> b -> b) -> b -> [a] -> b
foldr0 _ b []     = b
foldr0 f b (a:as) = foldr0 f (f a b) as

nofusion0 :: [Int] -> Int
nofusion0 = foldr0 (+) 0 . map0 sqr

sqr :: Int -> Int
sqr x = x * x

My question is: Why isn't function foldr0 (+) 0 . map0 sqr automatically inlined together into one recursion if the compiler can easily prove, that map0 doesn't change data structure dimension and deduce everything on run from the up of structure to the down of structure? I can't still find out, why this kind of code can't be automatically optimized without rewritting rules.
Do you know any specific reason, why this optimization isn't used please?
Thanks.

A: I think the most promising approach that could optimize your example is called supercompilation. There is a paper about supercompilation for lazy functional languages: https://www.microsoft.com/en-us/research/publication/supercompilation-by-evaluation/.
In the future work section of the paper the authors state:

The major barriers to the use of supercompilation in practice are code bloat and compilation time.

There has been work on trying to integrate supercompilation into GHC, but it has not yet been successful. I don't know all the details, but there is a very technical GHC wiki page about it: https://gitlab.haskell.org/ghc/ghc/-/wikis/supercompilation.


Q: Effects on Input Variable after Failed Input Stream I was working on the following code.
#include <iostream>

int main()
{
  std::cout << "Enter numbers separated by whitespace (use -1 to quit): ";
  int i = 0;
  while (i != -1) {
    std::cin >> i;
    std::cout << "You entered " << i << '\n';
  }
}

I know that using while (std::cin >> i) would have been better but I don't understand a specific occurrence.
If I provide an invalid input, the loop becomes infinite because the Input Stream enters a failbit state. My question is that what happens to the input variable i? In my case, it becomes 0 regardless of the previous value entered. Why does it change to 0 after an invalid input? Is this a predefined behaviour?

A: You get zero because you have a pre-C++11 compiler.  Leaving the input value unchanged on failure is new in the latest standard.  The old standard required the following:

If extraction fails, zero is written to value and failbit is set. If
  extraction results in the value too large or too small to fit in
  value, std::numeric_limits::max() or std::numeric_limits::min()
  is written and failbit flag is set.

(source)
For gcc, you need to pass -std=c++11 to the compiler to use the new behavior.


Q: Restlet ServerResource method parameters? This is probably a really stupid/simple question with such an obvious answer that it seems not worth stating in restlet documentation. Where and how (if at all) can Restlet pass parameters to methods in ServerResource classes?
Given this class:
public class FooServerResource extends ServerResource {
    @Get
    public String foo(String f) {
        return f;
    }
}

and a Router attachment router.attach("/foo", FooServerResource.class);
I know that if I use a Restlet client connector I could create a proxy for this class and invoke methods directly, but what if I am making calls to this ServerResource from some other non-java language, e.g. PHP?

A: You can access the query parameters using from the resource reference. Typically, something like this:
@Get
public String foo() {
    Form queryParams = getReference().getQueryAsForm();
    String f = queryParams.getFirstValue("f");
    return f;
}

Generally speaking (and this would work for other methods that GET), you can access whatever is passed to the request (including the entity, when appropriate) using getRequest() within the ServerResource.

A: hithe question is about one year old, but I just started with Restlet and stumbled into the "same" problem. I am talking about the server, not the client (as Bruno marked it, the original question is mixing server and client part)
I think the question is not completely answered. If you, for instance, prefer to separate the Restlet resource from semantic handling of the request (separating business logics from infrastructure) it is quite likely that you need some parameters, like an Observer, or a callback, or sth. else. So, as I fas as I see, no parameter could be transmitted into this instantiation process. The resource is instantiated by Restlet engine per request. Thus I found no way to pass a parameter directly (is there one?)
Fortunately it is possible to access the Application object of the Restlet engine from within the resource class, and thus also to the class that creates the component, the server, etc.
In the resource class I have sth. like this
protected Application initObjLinkage(){

    Context cx = this.getContext();
    Client cli = cx.getClientDispatcher();
    Application app = cli.getApplication() ;
    return app;
}

Subsequently you may use reflection and an interface to access a method in the Application class (still within the resource class), check reflection about this...
Method cbMethod = app.getClass().getMethod("getFoo", parameterTypes) ;
CallbackIntf getmethodFoo = ( CallbackIntf )cbMethod.invoke( app, arguments );
String str = getmethodFoo()

In my application I use this mechanism to get access to an observer that supplies the received data to the classes for the business logics. This approach is a standard for all my resource classes which renders them quite uniform, standardized and small.
So... I just hope this is being helpful and that there is {no/some} way to do it in a  much more simple way :)


Q: How do I get the color of a specific pixel from a picture box? I have a picture box in one of my programs which displays my images just fine. What's displayed consists of a chosen "BackColor" and some filled rectangles using a brush and some lines using a pen. I have no imported images. I need to retrieve the color value of a specified pixel on the picture box. I've tried the following:
Bitmap b = new Bitmap(pictureBox1.Image);
                Color colour = b.GetPixel(X,Y)

But pictureBox1.Image always returns null. Does .Image only work with imported images? If not how can  I get this to work? Are there any alternatives?

A: Yes you can, but should you?
Here is the change your code needs:
Bitmap b = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height);
pictureBox1.DrawToBitmap(b, pictureBox1.ClientRectangle);
Color colour = b.GetPixel(X, Y);
b.Dispose();

But there is really no way around giving the PictureBox a real Image to work with somewhere if you want to do real work with it, meaning if you want to use its possibilities e.g. its SizeMode.
Simply drawing on its background is just not the same.  Here is a minimal code to get a real Bitmap assigned:
public Form1()
{
   InitializeComponent();
   pictureBox1.Image = new Bitmap(pictureBox1.ClientSize.Width,
                                  pictureBox1.ClientSize.Height);
   using (Graphics graphics = Graphics.FromImage(pictureBox1.Image))
   {
     graphics.FillRectangle(Brushes.CadetBlue, 0, 0, 99, 99);
     graphics.FillRectangle(Brushes.Beige, 66, 55, 66, 66);
     graphics.FillRectangle(Brushes.Orange, 33, 44, 55, 66);
   }
}

However if you really don't want to assign an Image you can make the PictureBox draw itself onto a real Bitmap. Note that you must draw the Rectangles etc in the Paint event for this to work! (Actually you must use the Paint event for other reasons as well!)
Now you can test either way e.g. with a Label and your mouse:
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if (pictureBox1.Image != null)
    {   // the 'real thing':
        Bitmap bmp = new Bitmap(pictureBox1.Image);
        Color colour = bmp.GetPixel(e.X, e.Y);
        label1.Text = colour.ToString();
        bmp.Dispose();
    }
    else
    {   // just the background:
        Bitmap bmp = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height);
        pictureBox1.DrawToBitmap(bmp, pictureBox1.ClientRectangle);
        Color colour = bmp.GetPixel(e.X, e.Y);
        label1.Text += "ARGB :" + colour.ToString();
        bmp.Dispose();
    }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.FillRectangle(Brushes.DarkCyan, 0, 0, 99, 99);
    e.Graphics.FillRectangle(Brushes.DarkKhaki, 66, 55, 66, 66);
    e.Graphics.FillRectangle(Brushes.Wheat, 33, 44, 55, 66);
}