text:
Q: Move position of text in ggplot Hopefully a pretty simply problem to solve - I have produced the boxplot pictured using the following code
ggplot(minanalysis, aes(x=MinAnaType, y=Calcium)) +
  geom_boxplot() +
  geom_point(aes(colour=Ploidy)) +
  stat_summary(fun.y=mean, colour="black", geom="point", size=2,show.legend = FALSE) +
  geom_text(data = means, vjust = -0.25, hjust=-0.3, size = 3, aes(label = round(Calcium, 2),
                                                   y = Calcium + 0.08)) +
  #add a sample size n =
  geom_text(data = minanalysis %>% group_by(MinAnaType) %>%
          summarize(Count = n(),
          Calcium=max(Calcium) + 0.05 * diff(range(minanalysis$Calcium))),
          aes(label = paste0("n = ", Count)),
          position = position_dodge(0.85), size=3, show.legend = FALSE) +
  # Add pairwise comparisons p-value and global p-value
  stat_compare_means(comparisons = my_comparisons, label = "p.signif", label.y = 9500, size = 4) +
  stat_compare_means(label.y = 10500, size = 4)

What I want is for the "n=290" and n=50" to be located underneath x axis labels 'Eviscerated' and 'WholeBody'. Having them above the boxplots themselves is too messy. Could somebody help with the code for this, I'm new to R studio.
Thanks

A: The easiest is probably to add a linebreak to your x labels. You can then add your count, either hardcoded, or programmatically.
(This would be within scale_x_...(labels = ...))
E.g.
library(tidyverse)

ggplot(filter(iris, Species %in% c('setosa','virginica')), aes(Species, Sepal.Length)) +
  geom_boxplot() +
  scale_x_discrete(labels = c(setosa = paste('setosa', '\nn = 30'),
                              virginica = paste('virginica', '\nn = 30')))


text:
Q: Paypal multiple payments I'm trying to write a PHP class for paypal express mutliple payments. All is well so far except one thing I haven't figured out.
In PayPal's docs it says that PAYMENTREQUEST_n_PAYMENTREQUESTID is a required field for multiple payments, however I have no idea where to obtain a value for it. Is it a user set value? I tried putting random values and PP returns a SUCCESS however I'm not sure if that's good or bad.

A: PAYMENTREQUESTID is a user set value. The purpose of this field is to allow you co-relate response data for each of your parallel payments with your request data - Therefore it is good enough that this field is unique amongst multiple payment data for a given API call but random numbers should work too. See the docs for more.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stop UITableView consuming touch events so sliding menu in parent view can detect horizontal swipes I am about driven to despair trying to achieve something so simple.
I have a view with a menu that, using touchEvents slides from the left when it is gestured to do so with a horizontal swipe.  I don't use gesture recognisers, I simply use the touchesBegan, touchesMoved, etc.. and track the x coordinate difference between the starting touch position, those in-between and the finishing touch position.  It works great.
But, when in the body I have a UITableView, the touch events no longer find their way up the hierarchy to the view managing the menu.  I tried to get around this by passing touches to superview/nextResponder, which sort of works, but I see a touchesBegan and 2 touchesMoved calls before it simply stops being processed further up the hierarchy.
Specifically, I have a SlideMenuView, in which there is a menu view and a body view.  Inside the body view, I have at some point the UITableView.  I see (via NSLog) that the touches* methods are called from start to finish just fine.  I pass them on to nextResponder and begin to see them in SlideMenuView also - but after 2 calls to touchesMoved, they seem to stop in SlideMenuView but continue in my UITableView.
I am overriding the UITableView to do this, but I have changed nothing more inside of it.
I know that this must be possible, as it is in the Facebook app.  You can swipe anywhere in the body, which is scrollable, horizontally and reveal the menu.  I want the same thing to naturally occur here, but it appears as though something weird is happening, and the UITableView is consuming or destroying the events.
Can anybody help me out with this?  Somebody must have achieved this in a clean way.

A: Okay, for anybody interested - I found a clean solution.
Apple know what they're doing.  Back in the day we used to override touchesBegan, ... but then they introduced GestureRecognizers. For some controls, such as the UIScrollView (and any subclasses, such as UITableView), they seem to butcher their event responder system.  I was at fault for assuming that the Gesture Recognizers don't do anything special, and simply hook in to these touchesBegan, ... methods - this is not correct.
The safest way is to use the Gesture Recognizers.  Specifically, there are some options on them that can make all the difference.  Such as .cancelsTouchesInView = YES in my case.
So what I did, is use a PanGestureRecognizer on the Menu View, set .cancelsTouchesInView to YES, and it works.  I am going to avoid touchesBegan, ... like the plague, and write custom gesture recognisers for anything complex.
I hope this helps somebody pulling their hair out like I was !


text:
Q: How to implement popup menu on a listview in android I am implementing a pop up menu on listview in android. I am getting a null pointer exception, on this line
PopupMenu popupMenu = new PopupMenu(mContext,view.findViewById(R.id.imageButton1));

**Only the pop up menu on the first row is working. When I clicked the button in the other rows the exception comes.
The reason is the anchor view is null, not the context. How to fix this issue?
Here is my complete getView method.
@Override
public View getView(int position,View convertView, ViewGroup parent) {

    ViewHolderItem viewHolder = null;

    final View view = convertView;

    if (convertView == null) {

        if (inflater == null) {
            inflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        convertView = inflater.inflate(R.layout.main_list_row, null);

        viewHolder = new ViewHolderItem();

        viewHolder.tvTitle = (TextViewPlus) convertView
                .findViewById(R.id.tvShowTitle);
        viewHolder.tvChannelName = (TextViewPlus) convertView
                .findViewById(R.id.tvChannelName);
        viewHolder.tvViews = (TextViewPlus) convertView
                .findViewById(R.id.tvViews);
        viewHolder.ivThumbImage = (ImageView) convertView
                .findViewById(R.id.ivThumbImage);
        viewHolder.tvShowId = (TextView) convertView
                .findViewById(R.id.tvShowId);
        viewHolder.btnSubscribe = (Button)convertView.findViewById(R.id.btnSubscribe);
        //viewHolder.imgButton = (ImageButton)convertView.findViewById(R.id.imageButton1);
        viewHolder.btnTest = (Button)convertView.findViewById(R.id.imageButton1);

        convertView.setTag(viewHolder);

    } else {

        viewHolder = (ViewHolderItem) convertView.getTag();
    }

    SharedPreferences SP = PreferenceManager
            .getDefaultSharedPreferences(mContext);
    String languageType = SP.getString("applicationLanguage", "2");

    final Show show = data.get(position);

    if (languageType.equals("2")) {
        viewHolder.tvTitle.setText(show.getShowNameEn());
        viewHolder.tvChannelName.setText(show.getChannelNameEn());
    } else {
        viewHolder.tvTitle.setText(show.getShowNameSi());
        viewHolder.tvChannelName.setText(show.getChannelNameSi());
    }

    viewHolder.tvViews.setText("Views :" + show.getViews());
    viewHolder.tvShowId.setText(show.getShowId());
    viewHolder.btnSubscribe.setTag(position);
    viewHolder.btnTest.setTag(position);

    if(show.getSubscribed()==0){
        viewHolder.btnSubscribe.setText("Subscribe");
    }else{
        viewHolder.btnSubscribe.setText("Unsubscribe");
    }

    viewHolder.btnSubscribe.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            int result = dbHelper.subscribeShow(Integer.parseInt(show.getShowId()));

            if(result>0){

                if(((Button)v).getText().equals("Subscribe")){
                    ((Button)v).setText("Unsubscribe");
                }else if(((Button)v).getText().equals("Unsubscribe")){
                    ((Button)v).setText("Subscribe");
                }
            }

            data = dbHelper.getShowList(Integer.parseInt(show.getCategoryId()));

        }
    });

    viewHolder.btnTest.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            PopupMenu popupMenu = new PopupMenu(mContext,view.findViewById(R.id.imageButton1));

            popupMenu.inflate(R.menu.list_menu);

            popupMenu.show();

        }
    });

A: SInce you want to use the button you clicked on, as anchorView for your PopMenu, you can change view.findViewById with v, like:
 viewHolder.btnTest.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PopupMenu popupMenu = new PopupMenu(mContext,v);
            popupMenu.inflate(R.menu.list_menu);
            popupMenu.show();
        }
    });

A: No need to manually findViewById imageButton1 in on click v is reference of imageButton1 :
PopupMenu popupMenu = new PopupMenu(mContext,v);


text:
Q: Outlook 2013, and Excel 2007 Currently when clicking on an .xls or .xlsx file it opens in Excel 2007 fine.
However when clicking on a .xlsx attachment in Outlook 2013 it opens in Excel 2013.
Is there a way to force Excel Attachments recieved in Outlook 2013 to open in Excel 2007.

A: Outlook does not establish which program to open a file with. It simply references whatever Windows has set for the default application. I would ensure that your default program is indeed the version of Excel you want.  Your computer may have changed the default to 2013 once you installed it since it is the newest.
To change the default program, right click on one of your excel files with the extension you want to change, click open with.. click choose default program.. Check "Always use the selected program to open this kind of file", select the correct Excel version, and then click ok and it should be set.


text:
Q: API design and jQuery I have often heard that jQuery has made some poor API decisions. Although jQuery is not my favourite library it's the library I've used most often and I find it hard to point out specific mistakes in the API design or how it could have been improved.
What parts of jQuery's API could have been done better, how could it have been implemented different and why would that different implementation be better?
The question extends to both low level individual details of the API and high level details of the API. We are only talking about flaws in the API rather then flaws in the high level design / purpose of the library, jQuery is still a DOM manipulation library centred around a selector engine.
Because of the necessity of API freezing in popular libraries, jQuery is stuck in it's current state and the developers are doing a great job. As can be seen by the recent .attr vs .prop change the developers do not have the flexibility to change any of their design decisions (which is a shame!).
One specific example I can think of would be
$.each(function(key, val) { })
vs
$.grep(function(val, key) { })
which is confusing enough that I have to double check what the parameters are frequently.
Please do not compare the jQuery library to full fledged frameworks like dojo and YUI and complain about lack of features.

A: The way jQuery handles collections vs single elements can be confusing.
Say if we were to update some css property on a collection of elements, we could write,
$('p').css('background-color', 'blue');

The setter will update the background color of all matching elements. The getter, however, assumes that you are only interested in retrieving the value of the first element.
$('p').css('background-color')

MooTools would return an array containing the background colors of each matching element, which seems more intuitive.
The naming conventions for jQuery promote conciseness instead of clarity. I like Apple's strategy in naming things:

It's better to be clear than brief.

And here's an example of a method name from a mutable array class (NSMutableArray) in Objective-C.
removeObjectAtIndex:(..)

It's not trying to be clever about what's getting removed or where it's getting removed from. All the information you need to know is contained in the name of the method. Contrast this with most of jQuery's methods like after and insertAfter.
If somebody can intuitively figure out what after or insertAfter does without reading the docs or the source code, then that person is a genius. Unfortunately, I'm not one - and to-date, I still have to go to the documentation to figure out what the hell gets placed where when using these two methods.

A: patrick dw hit most of the points in his (fantastic) answer. Just to add to his collection with a few other examples.
An API is supposed to be consistent; and jQuery succeeds in a lot of areas (being very consistent for returning a jQuery object/ get value, as expected in a lot of cases). In other situations however, it doesn't do so well.
Method Names
As already pointed out by patrick; closest() is a crap method name. prev(), and next() appear to most as if they do the job prevAll() and nextAll() actually provide.
delay() confuses a lot of people: In the following example, which do you expect to happen? (what actually happens?)
$('#foo').hide().delay(2000).slideDown().text('Hello!').delay(2000).hide();

Method Arguments
A lot of the tree traversal functions are inconsistent with what they accept; they all accept a mixture of selectors, jQuery objects and elements, but none are consistent; which is bad considering they all do similar jobs. Check out closest(), find(), siblings(), parents(), parent() and compare the differences!
Internally, the "core" of jQuery originally contained lots of intertwined methods, that the dev team have struggled to split up (and done really well to), over the past releases. Internal modules such as css, attributes, manipulation and traversing all used to be bundled in the same big package.

A: *

*.load() is overloaded with entirely different behavior depending on the arguments passed

*.toggle() is overloaded with entirely different behavior depending on the arguments passed

*too much overloading of the jQuery() function perhaps.

*the .attr() you mentioned. The distinction from properties should have been immediate IMO.

*.map( key,val ) but $.map( val,key ), and the this values are different.

*non-standard selectors ought to have been kept out of Sizzle IMO. Javascript based selector engines should become obsolete in a number of years, and people hooked on the proprietary selectors will have a more difficult transition

*poor method naming of methods like .closest() or .live(). What exactly do they do?

*I recently discovered that you can't set the standard width and height attributes via the props argument when creating a new element. jQuery runs its own width and height methods instead. IMO, the spec attributes should have been given priority, especially since width and height can be set via css.
$('<img/>', {
    css:{width:100, height:100},
    width:100, // <-- calls method, why?
    height:100, // <-- calls method, why?
});

*

*$.get() and .get() are entirely different.

*.get() and .toArray() are identical when passing no arguments

*toArray() and $.makeArray() do effectively the same thing. Why didn't they give them the same name like .each() and $.each()?

*two different event delegation methods. .delegate() the sensible one, and .live() the magical "wow, it just works!" one.

*.index() is overloaded with 3 behaviors, but their differences can be confusing
 // v---get index   v---from collection (siblings is implied)
$('selector').index();
 // v---from collection   v---get index
$('selector').index(element);
 // v---get index      v---from collection
$('selector').index('selector');

The first one is understandable if you remember that it only operates on the first element
The second one makes the most sense since jQuery methods usually operate on an entire collection.
The third one is entirely confusing. The method gives no indication of which selector is the collection and which selector represents the element whose index you want from the collection.
Why not just eliminate the third one, and have people use the second one like this:
 // v---from collection      v---get index
$('selector').index( $('selector') );

This way it fits more closely with the rest of jQuery where .index() operates on the entire collection.
Or at least reverse the meaning of the selectors to fit in better:
 // v---from collection   v---get index
$('selector').index('selector');

Here's another to think about anyway.
I have some concerns with jQuery's event handling/data storage system. It is praised because it doesn't add functions to on[event] properties that can close around other elements, creating memory leaks in IE. Instead it places a lightweight expando property, which maps to an entry in jQuery.cache, which holds handlers and other data.
I believe it then attaches a handler with in turn invokes the handler that you assigned. Or something like that.
Whatever the system is doesn't really matter. The point is that the connection between the element(s) and the jQuery.cache is that expando.
Why is that a big deal? Well philosophically jQuery is not a framework; it is a library. It would seem that as a library you should be able to use or not use the jQuery functions without concern for negative effects. Yet if you go outside jQuery when removing elements from the DOM, you've orphaned any handlers and other data associated with those elements via the expando, creating a nice and fully cross-browser memory leak.
So for example, something as simple as el.innerHTML = '' could be very dangerous.
Couple this with the jQuery.noConflict() feature. This enables developers to use jQuery with other libraries that utilize the $ global namespace. Well what if one of those libraries deletes some elements? Same problem. I have a feeling that the developer that needs to use a library like Prototypejs along side jQuery probably doesn't know enough JavaScript to make good design decisions, and will be subject to such a problem as I've described.

In terms of improvements within the intended philosophy of the library, as far as I know, their philosophy is "Do more, write less" or something. I think they accomplish that very well. You can write some very concise yet expressive code that will do an enormous amount of work.
While this is very good, in a way I think of it as something of a negative. You can do so much, so easily, it is very easy for beginners to write some very bad code. It would be good I think if there was a "developer build" that logged warnings of misuse of the library.
A common example is running a selector in a loop. DOM selection is very easy to do, that it seems like you can just run a selector every time you need an element, even if you just ran that selector. An improvement I think would be for the jQuery() function to log repeated uses of a selector, and give a console note that a selector can be cached.
Because jQuery is so dominant, I think it would be good if they not only made it easy to be a JavaScript/DOM programmer, but also helped you be a better one.

A: Included in jquery:
.post()
.get()
.getScript()
.getJSON()
.load()

Not in jQuery:
$.getXML();
$.headXML();
$.postXML();
$.putXML();
$.traceXML();
$.deleteXML();
$.connectXML();
$.getJSON();
$.headJSON();
$.postJSON();
$.putJSON();
$.traceJSON();
$.deleteJSON();
$.connectJSON();
$.headScript();
$.postScript();
$.putScript();
$.traceScript();
$.deleteScript();
$.connectScript();
$.getHTML();
$.headHTML();
$.postHTML();
$.putHTML();
$.traceHTML();
$.deleteHTML();
$.connectHTML();
$.getText();
$.headText();
$.postText();
$.putText();
$.traceText();
$.deleteText();
$.connectText();
$.head();
$.put();
$.trace();
$.delete();
$.connect();

Why does this bother me? Not because we don't have the above methods in the library, that's just dumb and I'd hate if we ever did (plus, most won't work with browsers), but what I hate is these short-hand methods all over the place: $.post(); Sends an ajax request via post.
Know what covers off everything in this list? The one function that isn't short-hand, $.ajax, it's full featured and covers off everything, you can even configure it to store defaults and in essence create all of these short-hands. You can create your own methods if you wish to call that call to ajax (which is what these all do).
Here's where it's really REALLY annoying.
Somebody writes all their code using shorthand:
$.getJSON(
  'ajax/test.html',
   function(data) {
     $('.result').html(data);
   }
);

Okay, oh wait, we want to change that to an XML feed we get from a post, also we need to make something happen before and after post. Oh, lets just switch to the non-short-hand method
$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success
  dataType: dataType
});

Oh wait, I can't just replace the word, the whole structure is all over the place.
This, and especially for things like $.load(), cross lines into why PHP has such a hated API, they're trying to do things they shouldn't do.
To extend this beyond AJAX calls, look at the animation portion. We have calls to slideUp, slideDown, fadeIn, fadeOut, fadeToggle, show, and hide. Why? Where's my slide left, slide right, slide in, slide out, teleport, and every other thing we can think up? Why not just stick to $.animate() and let someone write a plugin if we want those effects. Infact, someone did write a plugin, jQueryUI extends animations. This is just crazy, and leads to people not knowing that some effects create CSS rules on their divs that end up goofing up what they want to do later on.
Keep it pure, keep it simple.


text:
Q: Change size of spinner by css i'm working on a webpage and i put a spinner like this below:
<p:spinner id="mySpinner" .. size="3">...</p:spinner>

How can i use css to change the size to make it responsive?

A: You need to override spinner-border class width and height:

.spinner-border {
    width: 100px;
    height: 100px;
}

A: I found an answer for you here in another Stack Overflow post:
The "size" element is set to 20 by default, use this class to change it:

.ui-spinner-input {
  width: 50px;
  /* Enter your own width above */
 }


text:
Q: To create a vector of x in the form: $x_0 = 0$ and $x_n=1$ , $x_k=x_{k-1}+2^{-k}$ Here is my code, the output I get is when use N=4 is [0,0,0,1], does anyone knows where the problem is?
Thanks
function xg = GenMesh(N)
    xg=[];
    xg(1) = 0;
    for i=2:length(N)-1
        xg(i)=xg(i-1)+2.^(-i);
    end
    xg(N)=1;
end

A: The error lies in the upper limit of your for loop: you assign length(N) to it, but N is a scalar, so its length=1. You have to directly set N as upper limit.
Also, you should initialise the size of xg to N before operating on it, otherwise the MATLAB interpreter will have to keep expanding its size throughout the loop.
Here below is a working version of your function:
function xg = GenMesh(N)
    xg = zeros(1,N);                % set dimension and initialise to 0

    for i = 2:N-1                   % N not length(N)
        xg(i) = xg(i-1) + 2^(-i);   % normal ^, not .^
    end

    xg(N)=1;
end


text:
Q: Java best practice: optimum number of calls in the Controller We have an internal website with dozens of reports for the user to choose from.  These go to a Reports Servlet with is the controller.  It contains code such as:
if (report.equals('reportOne')){
   bo.runReportOne(requestObjectData);
} else if(report.equals('reportTwo')){
   bo.runReportTwo(requestObjectData);
}

How many of these if/else are optimal before breaking things apart.  For example having multiple servlets based on function.  For example ProcessReportsServlet, ResultReportsServlet, BillingReportServlet, etc.
Thanks,
Brita

A: Typically, if you know you are going to be adding to this list eventually you should plan to clean up the if-else chain you'll create, or clean it up right now. You probably also want to figure out a different approach than having a new method for each type of report you can possibly create. I think anything less than 5 if-else statements is fine.


text:
Q: How to add an instance of a model to an instance of another in Rails The model Patient belongs_to FeedList, which has_many patients. I'm attempting, upon the creation of a new FeedList I want to add all patients that are currently in the DB to the FeedList. I'm currently attempting to do it within create of feed_lists_controller.rb.
def create
    @feed_list = FeedList.new(feed_list_params)

    Patients.all.each do |p|
      @feed_list.patients << p
    end

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

however, it doesn't seem to be registering when I create a new FeedList
[8] pry(main)> FeedList.create
=> #<FeedList:0xbaf7bdd0
 id: 3,
 created_at: Sun, 29 Nov 2015 01:11:54 UTC +00:00,
 updated_at: Sun, 29 Nov 2015 01:11:54 UTC +00:00,
 date: nil,
 integer: nil>
[9] pry(main)> FeedList.last.patients
=> #<Patient::ActiveRecord_Associations_CollectionProxy:0x-2284f570>

FeedList.rb:
class FeedList < ActiveRecord::Base
    has_many :patients

after_create :add_patients
  private
    def add_patients
      ::Patients.all.each do |p|
        self.patients << p
      end
    end

end

Am I on the right track?

A: Try using a callback in your FeedList model file:
after_create :add_patients

  private
    def add_patients
      Patient.all.each do |p|
        self.patients << p
      end
    end

As Jason mentioned above "create action [that is in your controller] isn't a callback that gets invoked every time you create an instance of a model". See What is a callback function? for information on what is a callback. The after_create callback essentially says to invoke add_patients right after you call FeedList.create


text:
Q: Can anyone recommend a simple screenshot tool that can be installed as a portable app? The printscreen button doesn't work on our university computers, so I'm looking for a simple free screenshot tool that can be installed on a USB drive.
this question is similar:
https://superuser.com/questions/254/screenshot-utilities-for-windows
though I'm looking for something specifically portable.

A: FastStone Capture fits the bill quite well.

A: Lightscreen Portable is another alternative.

A: One more to the list which I have used extensively is Cropper which uses Print screen and Alt+Print screen as shortcuts.

A: Bit late to this part but many consider PicPick the best screen captured program and it comes in a portable version too


text:
Q: Is a principal bundle over a discrete base space necessarily trivial? Let $X$ be a topological space with discrete topology. More concretely, one can think of the lattice $\mathbb{Z}^n$.
Then, is it true that any principal $G-$bundle over $X$ is trivial? Here $G$ is an arbitrary Lie group.
I feel this way because every one-point set is open in $X$ but cannot prove rigorously myself.. Could anyone please help me?

A: A bundle is trivial if and only if it has a global section. Take any set theoretic section of the bundle. Since the base is discrete, it will be continuous. So we have
$$s\colon X \to P$$
continuous, such that
$$p\circ s = \mathbb{1}_X$$
The isomorphism of the trivial bundle with the our bundle is given by the map
$$(x,g) \mapsto (x, s(x) \cdot g)$$

A: Consider an extension of groups $1\rightarrow H\rightarrow G\rightarrow K\rightarrow 1$. where $H,G,K$ are finite. It is a principal bundle over $K$ with typical fiber $H$. If the extension is not trivial the bundle is not trivial.


text:
Q: Using reserved word with ejs if I try to compile an EJS template like below:
var data = { case: 'Something' };
var html = ejs.render('Case <%= case %>', data);

I get the error:
ejs.js:550 Uncaught SyntaxError: Unexpected token case while compiling ejs

If the above error is not helpful, you may want to try EJS-Lint:
https://github.com/RyanZim/EJS-Lint
    at new Function (<anonymous>)
    at Template.compile (ejs.js:550)
    at Object.compile (ejs.js:359)
    at handleCache (ejs.js:202)
    at Object.exports.render (ejs.js:385)
    at VM546 script.js:2

It's because case is a reserved word. Is there a way around it, given that I cannot change the JSON I'm feeding into EJS?
Edit: here's a link to an online Plunker - https://plnkr.co/edit/WBpjom

A: It looks like EJS, also set's a context called locals that is passed..
So..
  var html = ejs.render('Case <%= locals.case %>', data)


text:
Q: insertion sort lower bound and why it compare to `1/(2^n)`?
I have one question:

*

*we know n!*(1/(2^n))  compared to 2^n, but what about insertion sort why it compare to 1/(2^n)?

I means why unlike the example for insertion sort reverse of 2^nwas used?

A: To use at most c(n) comparisons (with two possible outcomes) on an f(n) fraction of the inputs, we need f(n) n! ≤ 2^c(n). In the display formula they're using c(n) = n (which is a little too simple because they need to consider the asymptotic constant, but whatever) and f(n) = 1/2^n, yielding the desired formula n!/2^n ≤ 2^n <=> n! ≤ 4^n, which fails for large n.
Presumably the referenced part of the textbook goes over this, but f(n) n! is the number of inputs we need to distinguish, and 2^c(n) is the number of inputs we can distinguish with c(n) comparisons.


text:
Q: I have a square, and place three dots along the 4 edges at random. What is the probability that the dots lie on distinct edges? The correct answer is listed as (3/4) * (1/2) = 3/8. The reasoning is because it doesn't matter where you put the first dot, but after you put the first dot, it is 3/4 chance of a different edge, and then 1/2 chance of another different edge.
However, if I think about it from a purely combinatorics way, there are "4" ways that three dots can be arranged on the square in which all dots are on distinct edges. There are then 12 ways that two dots can be on one edge and the third dot is on another edge (4 edges to put two dots, multiplied by 3 possible edges to put the third dot). Finally, there are 4 ways to put all three dots onto a single edge. This gives us (4/20) probability where the three dots are on distinct edges. This should work since each dot is independent of the previous dot and we can assume a uniform probability distribution.
Why are these two values different?


text:
Q: Finding the curvature from a set of datapoints I have a set of

*

*1-d

*2-d

data. I want to find the curvature at each single point. Until now I was using difference technique to find out the curvature, i.e, central difference at middle and forward and backward difference at the ends. I am writing the code in Matlab.
The problem is curvature is supposed to bring out a sudden change in dataset at a particular location. What happens is it only shows abrupt change in curvature at the starting and end of the region. But within the region it shows smooth transition?
Any ideas?


text:
Q: django type object Http404 has no attribute get I have this code:
if not selected_organization in request.user.organizations.all():
        return Http404

while returning the http 404 I got this :
type object 'Http404' has no attribute 'get'

A: Took me a while to figure out,
Eventually I had to raise the Http404 and not return it!

A: return Http404() ==> is a wrong
raise Http404()  ==> is a correct
((under _ example code))
def room_detail(request, pk):
    try:
        room = models.Room.objects.get(pk=pk)
        return render(request, "rooms/detail.html", {"room": room})
    except models.Room.DoesNotExist:
        raiseHttp404()


text:
Q: Estructura de control en Javascript Soy nueva en programacion web y tengo un archivo .html donde quiero utilizar javascrip con la estructura de control if else y otras estructuras como while, switch, do while, do y for  pero hasta el momento tengo esto pero no se como hacer la estructura para que me funcione, alguien me podría ayudar
<!DOCTYPE html>

    <title></title>

<form action="#" name="numero">
     <input type="text" name="numero"> Escibe un número

 <input type="button" onclick="var()" value="Pulsar" />
 </form>

A: No puedes usar la palabre clave var como nombre de funcion. Puedes usar alguna otra palabra para que funcione.
Revisa otras palabras reservadas: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords

<!DOCTYPE html>

    <title></title>

<form action="#" name="numero">
     <input type="text" name="numero"> Escibe un número

 <input type="button" onclick="calc()" value="Pulsar" />
 </form>

Por otro lado, la variable numero no se carga automaticamente del formulario, se debe obtener del control como en el ejemplo:
var numero=document.forms['numero'].numero.value;

A: Siendo que estás empezando en programación web, aparte sobre lo que ya te ha señalado @F.Igor sobre el uso de una palabra reservada (var) para nombrar una función, me permito advertirte sobre algunas malas prácticas en tu código.
En Javascript hay un paradigma conocido como Unobtrusive JavaScript, el cual recomienda, entre otras cosas, que haya separación de responsabilidades en el código, de modo que el código del DOM (HTML) no sea dependiente del código Javascript. Según ese paradigma, el uso de funciones in line es una mala práctica. Por funciones in line se entiende aquellas funciones que colocas dentro de los elementos HTML, como ocurre con onclick="var()" aquí: <input type="button" onclick="var()" value="Pulsar" />
¿Qué problemas trae esto? Imaginemos un programa con cientos o miles de archivos html donde has puesto varios miles de funciones in line como esta. Y al cabo de un año el programa evoluciona y te dicen que ahora la función tal que pusiste in line en 12,546 archivos tiene que cambiar, que ahora esa función va a recibir un parámetro nuevo, etc. Pues eso, a rebuscar, a ver, a adivinar, donde rayos pusiste esa función 12,546 veces para modificar la función y el archivo javascript que debiste poner in situ en ese contexto.
Pero, si haces caso a uno de los principios de Unobtrusive JavaScript, tu código será independiente del DOM. Para lograr eso, eh Javascript existe lo que se conocen como listeners o escuchadores de eventos. En este caso, puedes asignar un listener, el cual escuchará el evento onclick del botón. Es lo mismo que haría el onclick que tienes in line, sólo que aquí el código es independiente. Y además tienes la ventaja de reutilizar código. Imaginemos que necesitas usar esta función en 12,546 archivos o contextos. Pues simplemente vas a incluir un solo archivo en esos contextos y cualquier cambio se hará en ese sólo archivo.
Este es un ejemplo funcional de tu código, aplicando ese principio. Te aconsejo que lo tengas en cuenta para tus programas. El código quedará más limpio y será más fácil de mantener. Para hacer la escucha, ha dado un id al botón que envía los datos.

var btnSend = document.getElementById('btnSend');
btnSend.onclick = function() {
  /*Aquí se obtiene el valor del 1er input que haya en el DOM*/
  var mNumber = document.getElementsByTagName('input')[0].value;
  /*Para mostrar la respuesta*/
  var mText = document.getElementById("respuesta");
  if (mNumber >= 100) {
    var mStatus = "Mayor o igual de 100";
    /*En este caso no haría falta comparar más*/
  } else {
    var mStatus = "Menor de 100";
  }
  alert(mStatus);
  mText.textContent = mStatus;
}
<form action="#">
  <input type="text" name="numero"> Escibe un número

  <input type="button" id="btnSend" value="Pulsar" />
</form>


text:
Q: 5 dimensional plot in r I am trying to plot a 5 dimensional plot in R. I am currently using the rgl package to plot my data in 4 dimensions, using 3 variables as the x,y,z, coordinates, another variable as the color. I am wondering if I can add a fifth variable using this package, like for example the size or the shape of the points in the space. Here's an example of my data, and my current code:
set.seed(1)
df <- data.frame(replicate(4,sample(1:200,1000,rep=TRUE)))
addme <- data.frame(replicate(1,sample(0:1,1000,rep=TRUE)))
df <- cbind(df,addme)
colnames(df) <- c("var1","var2","var3","var4","var5")
require(rgl)
plot3d(df$var1, df$var2, df$var3, col=as.numeric(df$var4), size=0.5, type='s',xlab="var1",ylab="var2",zlab="var3")

I hope it is possible to do the 5th dimension.
Many thanks,

A: Here is a ggplot2 option.  I usually shy away from 3D plots as they are hard to interpret properly.  I also almost never put in 5 continuous variables in the same plot as I have here...
ggplot(df, aes(x=var1, y=var2, fill=var3, color=var4, size=var5^2)) +
  geom_point(shape=21) +
  scale_color_gradient(low="red", high="green") +
  scale_size_continuous(range=c(1,12))

While this is a bit messy, you can actually reasonably read all 5 dimensions for most points.
A better approach to multi-dimensional plotting opens up if some of your variables are categorical.  If all your variables are continuous, you can turn some of them to categorical with cut and then use facet_wrap or facet_grid to plot those.
For example, here I break up var3 and var4 into quintiles and use facet_grid on them.  Note that I also keep the color aesthetics as well to highlight that most of the time turning a continuous variable to categorical in high dimensional plots is good enough to get the key points across (here you'll notice that the fill and border colors are pretty uniform within any given grid cell):
df$var4.cat <- cut(df$var4, quantile(df$var4, (0:5)/5), include.lowest=T)
df$var3.cat <- cut(df$var3, quantile(df$var3, (0:5)/5), include.lowest=T)

ggplot(df, aes(x=var1, y=var2, fill=var3, color=var4, size=var5^2)) +
  geom_point(shape=21) +
  scale_color_gradient(low="red", high="green") +
  scale_size_continuous(range=c(1,12)) +
  facet_grid(var3.cat ~ var4.cat)


text:
Q: What is a pre-revprop-change hook in SVN, and how do I create it? I wanted to edit a log comment in the repository browser and received an error message that no pre-revprop-change hook exists for the repository. Besides having a scary name, what is a pre-revprop-change hook, and how do I create it?

A: Thanks #patmortech
And I added your code which "only the same user can change his code".
:: Only allow editing of the same user.
for /f "tokens=*" %%a in (
'"%VISUALSVN_SERVER%\bin\svnlook.exe" author -r %revision% %repository%') do (
set orgAuthor=%%a
)
if /I not "%userName%" == "%orgAuthor%" goto ERROR_SAME_USER

A: The name of the hook script is not so scary if you manage decipher it: it's pre revision property change hook. In short, the purpose of pre-revprop-change hook script is to control changes of unversioned (revision) properties and to send notifications (e.g. to send an email when revision property is changed).
There are 2 types of properties in Subversion:

*

*versioned properties (e.g svn:needs-lock and svn:mime-type) that can be set on files and directories,

*unversioned (revision) properties (e.g. svn:log and svn:date) that are set on repository revisions.

Versioned properties have history and can be manipulated by ordinary users who have Read / Write access to a repository. On the other hand, unversioned properties do not have any history and serve mostly maintenance purpose. For example, if you commit a revision it immediately gets svn:date with UTC time of your commit, svn:author with your username and svn:log with your commit log message (if you specified any).
As I already specified, the purpose of pre-revprop-change hook script is to control changes of revision properties. You don't want everyone who has access to a repository to be able to modify all revision properties, so changing revision properties is forbidden by default. To allow users to change properties, you have to create pre-revprop-change hook.
The simplest hook can contain just one line: exit 0. It will allow any authenticated user to change any revision property and it should not be used in real environment. On Windows, you can use batch script or PowerShell-based script to implement some logic within pre-revprop-change hook.
This PowerShell script allows to change svn:log property only and denies empty log messages.
# Store hook arguments into variables with mnemonic names
$repos    = $args[0]
$rev      = $args[1]
$user     = $args[2]
$propname = $args[3]
$action   = $args[4]

# Only allow changes to svn:log. The author, date and other revision
# properties cannot be changed
if ($propname -ne "svn:log")
{
  [Console]::Error.WriteLine("Only changes to 'svn:log' revision properties are allowed.")
  exit 1
}

# Only allow modifications to svn:log (no addition/overwrite or deletion)
if ($action -ne "M")
{
  [Console]::Error.WriteLine("Only modifications to 'svn:log' revision properties are allowed.")
  exit 2
}

# Read from the standard input while the first non-white-space characters
$datalines = ($input | where {$_.trim() -ne ""})
if ($datalines.length -lt 25)
{
  # Log message is empty. Show the error.
  [Console]::Error.WriteLine("Empty 'svn:log' properties are not allowed.")
  exit 3
}

exit 0

This batch script allows only "svnmgr" user to change revision properties:
IF "%3" == "svnmgr" (goto :label1) else (echo "Only the svnmgr user may change revision properties" >&2 )

exit 1
goto :eof

:label1
exit 0

A: Basically it's a script that is launched before unversioned property is modified on the repository, so that you can manage more precisely what's happening on your repository.
There are templates in the SVN distrib for different hooks, located in the /hooks subdirectory (*.tmpl that you have to edit and rename depending on your OS, to activate).

A: For Linux to allow the edition of a log comment,

*

*locate the file pre-revprop-change.tmpl in the hooks directory of your repository

*copy the file to the same directory, renaming it to pre-revprop-change

*give execute permission to the file (for the server user, e.g. www-data)

Edited: (thanks to lindes)

*

*after that you might have to edit the script to return an exit value of 0 for the kind of edits, that you want to allow.

A: For Windows, here's a link to an example batch file that only allows changes to the log message (not other properties):
http://ayria.livejournal.com/33438.html
Basically copy the code below into a text file and name it pre-revprop-change.bat and save it in the \hooks subdirectory for your repository.
@ECHO OFF
:: Set all parameters. Even though most are not used, in case you want to add
:: changes that allow, for example, editing of the author or addition of log messages.
set repository=%1
set revision=%2
set userName=%3
set propertyName=%4
set action=%5

:: Only allow the log message to be changed, but not author, etc.
if /I not "%propertyName%" == "svn:log" goto ERROR_PROPNAME

:: Only allow modification of a log message, not addition or deletion.
if /I not "%action%" == "M" goto ERROR_ACTION

:: Make sure that the new svn:log message is not empty.
set bIsEmpty=true
for /f "tokens=*" %%g in ('find /V ""') do (
set bIsEmpty=false
)
if "%bIsEmpty%" == "true" goto ERROR_EMPTY

goto :eof

:ERROR_EMPTY
echo Empty svn:log messages are not allowed. >&2
goto ERROR_EXIT

:ERROR_PROPNAME
echo Only changes to svn:log messages are allowed. >&2
goto ERROR_EXIT

:ERROR_ACTION
echo Only modifications to svn:log revision properties are allowed. >&2
goto ERROR_EXIT

:ERROR_EXIT
exit /b 1

A: For PC users:
The .bat extension did not work for me when used on Windows Server maching. I used VisualSvn as Django Reinhardt suggested, and it created a hook with a .cmd extension.

A: This was the easiest for me on a Windows Server:
In VisualSVN right-click your repository, then select Properties... and then the  Hooks tab.
Select Pre-revision property change hook, click Edit.
I needed to be able to change the Author - it often happens on remote computers used by multiple people, that by mistake we check-in using someone else's stored credentials.
Here is the modified community wiki script to paste:
@ECHO OFF
:: Set all parameters. Even though most are not used, in case you want to add
:: changes that allow, for example, editing of the author or addition of log messages.
set repository=%1
set revision=%2
set userName=%3
set propertyName=%4
set action=%5

:: Only allow the author to be changed, but not message ("svn:log"), etc.
if /I not "%propertyName%" == "svn:author" goto ERROR_PROPNAME

:: Only allow modification of a log message, not addition or deletion.
if /I not "%action%" == "M" goto ERROR_ACTION

:: Make sure that the new svn:log message is not empty.
set bIsEmpty=true
for /f "tokens=*" %%g in ('find /V ""') do (
set bIsEmpty=false
)
if "%bIsEmpty%" == "true" goto ERROR_EMPTY

goto :eof

:ERROR_EMPTY
echo Empty svn:author messages are not allowed. >&2
goto ERROR_EXIT

:ERROR_PROPNAME
echo Only changes to svn:author messages are allowed. >&2
goto ERROR_EXIT

:ERROR_ACTION
echo Only modifications to svn:author revision properties are allowed. >&2
goto ERROR_EXIT

:ERROR_EXIT
exit /b 1

A: If you want to save the changes on the log messages, use the batch script from the answer above from @patmortech (https://stackoverflow.com/a/468475),
who copied the script from https://stackoverflow.com/a/68850,
and add these lines between if "%bIsEmpty%" == "true" goto ERROR_EMPTY and goto :eofbefore:
set outputFile=%repos%\log-change-history.txt

echo User '%user%' changes log message in rev %rev% on %date% %time%.>>%outputFile%
echo ----- Old message: ----->>%outputFile%
svnlook propget --revprop %repos% svn:log -r %rev% >>%outputFile%
echo.>>%outputFile%
echo ----- New message: ----->>%outputFile%
for /f "tokens=*" %%g in ('find /V ""') do (echo %%g >>%outputFile%)
echo ---------->>%outputFile%
echo.>>%outputFile%

It will create a text file log-change-history.txt in the repo folder on the server and append each log change notification.

A: Here is the link to the stack overflow question with many common hooks Common Types of Subversion Hooks, including the original source of the pre-revprop-change hook for Windows cross-posted here.
You should refer there as they may get improved over time.

A: *

*Go to SVN repo directory into the subfolder "hooks", e.g. "D:\SVN\hooks\"

*create the empty file "pre-revprop-change.bat" there

*in the file write "exit 0" (without "") and save it

*enjoy :)

(This solution surely has drawbacks, as nothing is checked/prohibited. But for my case - a local repo that only I am using - it seems to work.)

A: As Alois Helmer answered before, you need to locate the file pre-revprop-change.tmpl in the hooks directory inside the SVN repository you want to allow revision comments edition.
For me, to create a copy with pre-revprop-change name was sufficient, though you could edit it to allow only certain users to modify the comments or some other needs you have.
And then you must grant regular read and execution permissions using chmod 755 pre-revprop-change
But regular execution permissions are not enough.  You need to give Apache/HTTPD execution grants in SELinux for that script like this.
chcon -t httpd_exec_t pre-revprop-change

If you not, you'll get the following error that gives little information and it's hard to relate to a SELinux conf.
svnrdump: E175008: Revprop change blocked by pre-revprop-change hook (exit code 255) with no output.


text:
Q: How to insert json object to a column in postgres table using pyspark I have a json variable as below, i need to insert that to a particular column in a table in postgres. How do i go about it
JSON variable is man_j which is below format
     {"a_type":"Res", "display_type":"Res", "data_type":"AAA",
     "source_name":"na", "li_details":{"li_value":"na", "li_column":"na"},
       "additional_info": {"d_name":"na",
      "description":"na", "program":"program2",
        "Author":"author2", "email":"na", "sum":"na",
         "file_name":"na","additional_files":"na", "notify_email":"na"}}

I have a column in postgres table called man_de for which i need to insert the value

A: Spark does not provide single columns updates directly.Your solution might get complicated using a staging area (in the db level) and updating the json columns alone (which is bit complicated than your actual problem in hand).
As you own the data for other columns too, convert the JSON variable to a DF.
Combine it with the DF of other columns.Now you have something that you can directly append.

*

*DF1 --> All other columns

*DF2 --> JSON variable

Join DF1 AND DF2 (hope you have some sort of PK's to join)
Rearrange the columns to the order in your RDBMS table.
Write/Append it using df.write based on your needs

A: I am not sure if this is something you are looking for , assuming that you have your connection is configured with PostGre , then you can simply call below to perform any sql operation
df = df.withColumn("new_json_column", json_variable) // I am assuming here you have the correct schema or else you can create null column to ensure there is no schema mismatch
//to send only 1 transaction
df = df.show(1)

df.write.mode("append").jdbc(jdbcUrl, "db.table_name", connectionProperties)


text:
Q: How to specify a pre-release package dependency in Xcode? How do you configure Xcode (13.2) to add a dependency on a pre-release version of a package?
For example, right now Sparkle has a 2.1.0-beta.2 release which I would like to test in my app.
More accurately stated, I would like to accept 2.1.0-beta.x up to and including the full release of 2.1.0 and I'd like Xcode's "Update to latest package versions" to find the new releases for me without me changing anything in the configuration (eg like you can do with npm).
I can't find any obvious way to achieve this using the Xcode UI. If indeed you can't, is there a way to specify this version range by editing a config directly?

As mentioned here, 2.1.0-beta.2 < 2.1.0, which is why I have tried 2.0.0 in the screenshot.


text:
Q: How to avoid Typeerror when sorting dates and grouping them I have a sample dataframe like as shown below
df=pd.DataFrame({'Adm DateTime':['02/25/2012 09:40:00','03/05/1996 09:41:00','11/12/2010 10:21:21','31/05/2012 04:21:31','21/07/2019 13:15:02','31/10/2020 08:21:00'],
                 's_id':[1,1,1,1,2,2],
                't_id':['t1','t2','t3','t3','t4','t5']})
df['Adm DateTime'] = pd.to_datetime(df['Adm DateTime'])

I would like to generate row number based for each group (of s_id)
I tried the below
df['R_N'] = df.sort_values(['Adm DateTime'], ascending=True).groupby(['s_id']).cumcount() + 1

While this works in sample data, it throws below error in original data.

TypeError: '<' not supported between instances of 'datetime.datetime'
and 'str'

But there is no NA in my original Adm DateTime column and the data type of the column itself is datetime64[ns]. I don't explicitly perform any comparison between dates (except sorting which may be done internally)
May I know why does this error happen and how can I identify the records which cause this issue?

A: You can try split solution because in your solution if chain sorting and creating new column pandas have to internally reorder rows by original index, I guess it should be problem here (and output has no sorted rows).
df['R_N'] = (df.sort_values(['Adm DateTime'], ascending=True)
               .groupby(['s_id']).cumcount() + 1)
print (df)
         Adm DateTime  s_id t_id  R_N
0 2012-02-25 09:40:00     1   t1    3
1 1996-03-05 09:41:00     1   t2    1
2 2010-11-12 10:21:21     1   t3    2
3 2012-05-31 04:21:31     1   t3    4
4 2019-07-21 13:15:02     2   t4    1
5 2020-10-31 08:21:00     2   t5    2

If need this output possible idea should be creating unique index values:
df = df.reset_index(drop=True)
df['R_N'] = (df.sort_values(['Adm DateTime'], ascending=True)
               .groupby(['s_id']).cumcount() + 1)

My solution after sort create new DataFrame, so no reorder or rows is necessary (and output has sorted rows)
df['Adm DateTime'] = pd.to_datetime(df['Adm DateTime'])

df = df.sort_values(['Adm DateTime'])
df['R_N'] = df.groupby(['s_id']).cumcount() + 1
print (df)
         Adm DateTime  s_id t_id  R_N
1 1996-03-05 09:41:00     1   t2    1
2 2010-11-12 10:21:21     1   t3    2
0 2012-02-25 09:40:00     1   t1    3
3 2012-05-31 04:21:31     1   t3    4
4 2019-07-21 13:15:02     2   t4    1
5 2020-10-31 08:21:00     2   t5    2


text:
Q: In android how to unit test for a class is equal to another class where both classes are wrapped around by a wrapper class I am using a wrapper class GenericApiResponse for api response:
sealed class GenericApiResponse<T> {

    companion object {
     fun <T> create(error: Throwable): ApiErrorResponse<T> {
        return ApiErrorResponse(error.message ?: "unknown error") }

    fun <T> create(response: Response<T>): GenericApiResponse<T> {

           if(response.isSuccessful){
               val body = response.body()
               if (body == null || response.code() == 204) {
               return ApiEmptyResponse()    }
           else if(response.code() == 401){  return ApiErrorResponse("401 Unauthorized. Token may be invalid.")     }
           else {   return ApiSuccessResponse(body = body)}
        }
        else{
          val msg = response.errorBody()?.string()
          val errorMsg = if (msg.isNullOrEmpty()) {
            response.message()
           } else {
            msg     }
         return ApiErrorResponse(errorMsg ?: "unknown error")
        }
    }   }
}

class ApiEmptyResponse<T> : GenericApiResponse<T>()

data class ApiSuccessResponse<T>(val body: T) : GenericApiResponse<T>() {}

data class ApiErrorResponse<T>(val errorMessage: String) : GenericApiResponse<T>()

and from my ViewModel MainViewModel I am calling a function from my MainRepository class:
 class MainViewModel @Inject constructor(val mainRepository: MainRepository) : ViewModel() {
.....
val source: LiveData<GenericApiResponse<GitResult>> = mainRepository.fetchApiresultFromClient(str_query)
}

so in MainRepository it calls:
class MainRepository @Inject constructor(val mainApiClient: MainApiClient) {
    ....
    fun fetchApiresultFromClient(strQuery: String)
         : LiveData<GenericApiResponse<GitResult>> {

          var returnedData =    mainApiClient.getApiResultFromServer(strQuery)
          return returnedData
     }

MainApiClient:
class MainApiClient  @Inject constructor(val mainApi: MainApi) {
   fun getApiResultFromServer(query :String )
        : LiveData<GenericApiResponse<GitResult>> {

    var apiResult =   mainApi.getAllRepo(query)
       return apiResult
    }
}

MainApi: is the interface used for retrofit
Everything is working fine but I am having some problem when trying to implement some unit testing code for the app. I want to assert that when method is called from viewModel then the returned data is:

*

*is of type GenericApiResponse

*is ApiSuccessResponse

*value is same as i defined in test class; which is ApiSuccessResponse(TestUtil.obj_gitresult)

So far I have tried:
  @ExtendWith(InstantExecutorExtension::class)
  class MainViewModelTest {

    lateinit var  mainViewModel: MainViewModel

    @Mock
     lateinit var  mainRepository: MainRepository

    @Mock
    lateinit var  mainApiClient: MainApiClient

    @BeforeEach
    fun init()
    {
    MockitoAnnotations.initMocks(this)
    mainViewModel = MainViewModel(mainRepository)
    }

    @Test
    fun setSearchQuery_callsRepositoryMethod_returnSuccess() {

           //arrange
         mainViewModel.liveResult.value = ApiSuccessResponse(TestUtil.obj_gitresult) as GenericApiResponse<GitResult>

        Mockito.`when`(mainApiClient.getApiResultFromServer(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt()))
            .thenReturn(mainViewModel.liveResult)

           //act

        var repo_response = mainRepository.fetchApiresultFromClient("java")

        //assert
           // assertTrue(repo_response.value is  GenericApiResponse<GitResult> ) //for asserting return type is of type GenericResponse //--TestResult- java.lang.NullPointerException
           // assertTrue(repo_response.value is  ApiSuccessResponse<GitResult> ) //for asserting return type is of type ApiSuccessResponse //--TestResult- java.lang.NullPointerException
           //  assertEquals(mainViewModel.liveResult.value , repo_response.value ) //for asserting 2 generic types are equal //--TestResult- java.lang.NullPointerException
        }

}

but all of the 3 cases i used for testing fails and shows result java.lang.NullPointerException.
What am I doing wrong? how to solve it? How do I write the function for testing all of the above mentioned cases?


text:
Q: How to set a ratio to select the payment method from multiple payment methods in laravel Consider we have an "orders" table and have multiple payment gateways.
We now have a need where we will be setting ratio for each payment gateway.
For example if we have a ratio set to 2:1, every 2 orders should be given gateway "x" and 1 order should be assigned to gateway "y".
I need to develop a mechanism, in which user can set the ratio against each payment gateway. This ratio should become functional as soon as the user sets it.
PaymentGateway and Orders table is in a one-to-one relationship.


text:
Q: Esconder o cerrar un formulario MDI Children Buenas , tengo un formulario MDI (frmPrincipal) donde abro un formulario MDI Children (frmListadoClientes).
Dentro de este mdi children al cerrar el formulario lanzo un formulario (frmOpciones) que permite hacer un par de gestiones rápidas que bien se puede pulsar una de ellas o cancelar el formulario.

*

*Si se cancela el frmOpciones se nos queda en modal el frmListadoClientes

*Si se acciona uno de los botones de frmOpciones se abre un 4º formulario (frmTPV) , por lo que intento esconder el tercer formulario (frmOpciones) y mostrar en forma modal este último formulario abierto , para ello uso este código
Código para abrir el formulario de Opciones
frmOpciones frm = new frmOpciones (param1 , param2);
frm.ShowDialog();

Desde el formulario frmOpciones (3º formulario) abro la opción correspondiente para ello se abre  el 4º formulario que lo lanzo con este código
private void btnStock_Click(object sender, EventArgs e)
{
    this.Close();
    Form f2 = new frmTPV(param1 , param2 , param3);
    f2.MdiParent = this.ParentForm;
    f2.ShowDialog();
}

Aquí lo que intento hacer es que antes de lanzar este 4º form cierre el tercero pero no lo consigo , también he probado con un this.Hide() sin éxito.
El problema que tengo es este como hacer que no se muestre o quede escondido este formulario.
Gracias

A: Buenas, a mí me ha funcionado lo siguiente:
private void btnStock_Click(object sender, EventArgs e)
{
    //this.Close();
    Form f2 = new frmTPV(param1 , param2 , param3);
    f2.MdiParent = this.ParentForm;
    f2.ShowDialog();
    this.Hide();
}

Ya me dices si te ha funcionado.
Saludos!!

A: Buenas,
Lo que estas intentando hacer es como una ventana de menú dónde eliges que acción realizar y abrir una ventana u otra dependiendo del botón que se haga clic.
La forma mas sencilla de realizar esta acción es llamando al formulario frmOpciones des del frmPrincipal y dependiendo del botón que se haga clic, el mismo formulario devuelva una variable para que frmPrincipal la interprete y abra el formulario que se desea, y de ésta manera te aseguras que se va a abrir con ése MDI y frmOpciones estará cerrado:
Código para frmOpciones:
public int OpcionMenu { get; set; } //Declaramos una variable como property para recogerla en frmPrincipal.

Evento del click de TPV:
private void TPVbutton_Click(object sender, EventArgs e)
{
    OpcionMenu = 1; //Número que asociarás al formulario que deseas abrir
    this.DialogResult = System.Windows.Forms.DialogResult.Yes;
}

Código para frmPrincipal:
int opcionMenu;
frmOpciones frm = new frmOpciones (param1 , param2);
frm.ShowDialog();
if (frm.DialogResult = System.Windows.Forms.DialogResult.Yes)
{
   opcionMenu = frm.OpcionMenu; //Recogemos el valor de frmOpciones
   if (opcionMenu == 1)
   {
       //Abrimos el frmTPV
   }
}

Espero que te sirva de ayuda.


text:
Q: spring boot multiple tests classes but only is executed when mvn package the app I have fresh spring boot application generated from https://start.spring.io/
My problem is the generated already Test class is the only one is executed even when I have added different test classes with the same annotaions as the generated one and located in the same package.
spring boot version is : 2.2.4

A: I think that the problem could be because of the name of the test classes.
By default maven only executes test in the clasees which follows this name convention: (In short the test class must starts or ends with Test word)
By default, the Surefire Plugin will automatically include all test classes with the following wildcard patterns:

"/Test*.java" - includes all of its subdirectories and all Java
  filenames that start with "Test". "/*Test.java" - includes all of
  its subdirectories and all Java filenames that end with "Test".
  "/*Tests.java" - includes all of its subdirectories and all Java
  filenames that end with "Tests". "/*TestCase.java" - includes all of
  its subdirectories and all Java filenames that end with "TestCase".

As you can see in
https://maven.apache.org/surefire/maven-surefire-plugin/examples/inclusion-exclusion.html


text:
Q: Elasticsearch datastreams integration with spring data We have time series data & there by moving to use elasticsearch datastreams
I am using springboot, having following dependency
<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-elasticsearch</artifactId>
  <version>4.4.1</version>
</dependency>

Seems Spring Data stopped working with following error:
Error Message: cannot create index with name [my_datastream_index_test], because it matches with template [my-datastream-index-template] that creates data streams only, use create data stream api instead

Caused by: ElasticsearchStatusException[Elasticsearch exception [type=illegal_argument_exception, reason=cannot create index with name [my_datastream_index_test], because it matches with template [my-datastream-index-template] that creates data streams only, use create data stream api instead]]
    at org.elasticsearch.rest.BytesRestResponse.errorFromXContent(BytesRestResponse.java:178)
    at org.elasticsearch.client.RestHighLevelClient.parseEntity(RestHighLevelClient.java:2484)
    at org.elasticsearch.client.RestHighLevelClient.parseResponseException(RestHighLevelClient.java:2461)
    at org.elasticsearch.client.RestHighLevelClient.internalPerformRequest(RestHighLevelClient.java:2184)
    at org.elasticsearch.client.RestHighLevelClient.performRequest(RestHighLevelClient.java:2154)
    at org.elasticsearch.client.RestHighLevelClient.performRequestAndParseEntity(RestHighLevelClient.java:2118)
    at org.elasticsearch.client.IndicesClient.create(IndicesClient.java:152)
    at org.springframework.data.elasticsearch.core.RestIndexTemplate.lambda$doCreate$0(RestIndexTemplate.java:86)
    at org.springf

Does elastic spring-data work with data streams? I expected it to be seamless transition. Am I missing on anything?
The repository bean itself is not getting created:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is RestStatusException{status=400} org.springframework.data.elasticsearch.RestStatusException: Elasticsearch exception [type=illegal_argument_exception, reason=cannot create index with name [my_datastream_index_test], because it matches with template [my-datastream-index-template] that creates data streams only, use create data stream api instead]; nested exception is ElasticsearchStatusException[Elasticsearch exception [type=illegal_argument_exception, reason=cannot create index with name [my_datastream_index_test], because it matches with template [my-datastream-index-template] that creates data streams only, use create data stream api instead]]
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:224)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.lambda$instantiateClass$5(RepositoryFactorySupport.java:579)
    at java.util.Optional.map(Optional.java:215)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.instantiateClass(RepositoryFactorySupport.java:579)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getTargetRepositoryViaReflection(RepositoryFactorySupport.java:544)
    at org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactory.getTargetRepository(ElasticsearchRepositoryFactory.java:74)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:325)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:323)
    at org.springframework.data.util.Lazy.getNullable(Lazy.java:231)
    at org.springframework.data.util.Lazy.get(Lazy.java:115)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:329)
    at org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactoryBean.afterPropertiesSet(ElasticsearchRepositoryFactoryBean.java:69)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800)
    ... 161 more

A: First, as Val commented, Spring Data Elasticsearch currently creates indexes and no data streams.
But second, according to the error message, the data stream would be created by an index template, I assume. You need to keep Spring Data Elasticsearch from creating the index automatically, you do this by adding the createIndex value to the @Document annotation of your entity class:
@Document(indexName = "my_datastream_index_test", createIndex = false)


text:
Q: rebind-as-user in slapd-meta not running (OpenLDAP) I'm trying to configure a LDAP proxy with slapd-meta.
I have several suffixs over several instances that shares the same user accounts. It's posible that one user had access to several targets.
The targets are:

*

*Users: ou=users, dc=test, dc=com (here resides all accounts)

*Target1: ou=target1, dc=test, dc=com

*Target2: ou=target2, dc=test, dc=com
These 3 suffix are on 3 differents instances.
The instances where target1 and target2 are also have another suffix: ou=users, dc=test, dc=com. This suffix is replicated from the first instance (Users)
Normally, the users connect throught the proxy, but sometimes will connect directly to the others instances.
Basically this is the slapd.conf of the proxy:
database meta
chase-referrals yes
rebind-as-user  yes

suffix   "ou=users,dc=test,dc=com"
uri      "ldap://192.168.1.34:3891/ou=users,dc=test,dc=com"

suffix   "ou=target1,dc=test,dc=com"
uri      "ldap://192.168.1.34:3892/ou=target1,dc=test,dc=com"

suffix   "ou=target2,dc=test,dc=com"
uri      "ldap://192.168.1.34:3893/ou=target2,dc=test,dc=com"

When a user connects to the proxy with cn=user1,ou=users,dc=test,dc=com, the user is validated against the first target (ou=users) and can search over this suffix, but if this user try to search something over other target (for example ou=target1) the proxy does not use the credentials of the user and do an anonymous bind to target1, so the search doesn't run.
I thought that rebind-as-user resolve this but doesn't run.
I've tried using idassert-bind mode=self bindmethod=simple binddn="cn=adminuser,ou=users,dc=test,dc=com" credentials="password" and runs ok, but I prefer not to use an administrative account to connect the proxy with the targets.
Is there something I'm missing?
Thanks


text:
Q: EntityFramework.sqlServer dll not found We have ASP.NET WebSite and it refers project (dll) which refer EntityFramework dll. We have added EntityFramework.dll and EntityFramework.SqlServer.dll reference to bin folder manually(not through Nuget). We are using Octopus to deploy our websites. While deploying  we dont have EntityFramework.SqlServer dll in bin folder. I have gone through various answers but couldn't get it.
Anybody know the answer on the same? I have tried publishing through VS and I see SqlServer of EF in bin folder. Surprisingly we dont have any reference entry in our web.config for EF dll version.
Not sure about adding below code which some of them suggested -
 var ensureDLLIsCopied = System.Data.Entity.SqlServer.SqlProviderServices.Instance;

Error Message-
ERROR occurred in LockAutomationNotification.NotifyEmail
System.Data.Entity.Core.MetadataException: Schema specified is not valid. Errors:
OLIEDataModel.ssdl(2,2) : error 0152: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See

A: Answer to your first question is here. It is happening as EntityFramework.SqlServer.dll is referenced internally by EntityFramework.dll but not your project code.
The new error you're getting is because of your missing configurations. Please add below settings in web.config file of your website:
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>


text:
Q: error warning message when i try to log on to a page using php and mysql $result = mysql_query($db, $query);
if (mysqli_num_rows($result) ==1)

Error message: "mysql_query() expects parameter 1 to be string, object
  given in C:\xampp\htdocs\registration\server.php on line 65"
"mysqli_num_rows() expects parameter 1 to be mysqli_result, null given
  in C:\xampp\htdocs\registration\server.php on line 66"

Can anyone please help me not getting those two errors, I'm trying to log on to a page but I'm really not familiar with the errors above

A: Change it to
syntax mysql_query(query, connection)
$result = mysql_query( $query,$db);

A: mysql  pass connection object second
write mysql_query($query,$db); instead of mysql_query($db, $query);
and you write mysqli_query for count row and use mysql_query for get result
so change mysqli_fetch_rows to mysql_fetch_rows
so its work
code like below
$result = mysql_query($query,$db);
if (mysql_num_rows($result) ==1)

or using mysqli
$result = mysqli_query($db,$query);
if (mysqli_num_rows($result) ==1)

A: The mysql_query($query, [$link]); documentation can be found here.
So you would need mysql_query($query, $db);
Part of your issue is that you're also using mysql_query with mysqli_num_rows, and you need to be consistent.
That being said, mysql_* functions are deprecated and should not be used in new code (and replaced in old). If you want a simple transition, mysqli_* is an acceptable replacement, which supports parameter binding and other more secure and conventional methods. That documentation can be found here.
A tutorial for mysqli_* or PDO (preferred) can be found all of the place, but a decent one is here.


text:
Q: Remove /web/index.html#!/ from Plex server URL My currently Nginx config (below) will successfully take me to Plex Media Server's web interface when typing:  https://plex.mydomain.com in a web browser address bar from anywhere.
However, immediately after displaying the web interface, the URL is automatically forwarded (persistently) to:
https://plex.mydomain.com/web/index.html#!/
How can I use the rewrite directive to persistently display: https://plex.mydomain.com instead of https://plex.mydomain.com/web/index.html#!/ in my web browser's address bar?

    server {
            listen 443 ssl http2;
            listen [::]:443 ssl http2;
            ssl_certificate     ./ssl/fullchain.cer;
            ssl_certificate_key ./ssl/cert.key;
            server_name  plex.mydomain.com;
            location / {
                proxy_pass http://localhost:32400;
                proxy_set_header Accept-Encoding "";
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection $http_connection;                }
    }

I tried adding the below line to the config above, but it didn't make any difference.
rewrite /web/index.html#!/(.*) /$1 break;

I also tried the below line; which didn't make any difference either:
rewrite /web/index.html/(.*) /$1 break;


text:
Q: is ther way to expose aws public alb without putting 0.0.0.0 in ingress rule I have aws application load balancer which is of type external and in public subnet. The targets ec2 are in private subnets.
The ALB subnets are whitelisted in palo alto firewall software. We have 0.0.0.0 in ngress rule of the ALB security group.
Is there a way to allow all public internet traffic without providing  0.0.0.0/0 in the ingress rule of alb ?  any additional servers or provide only palo alto subnets in sSG groups ?

A:
Is there a way to allow all public internet traffic without providing 0.0.0.0/0 in the ingress rule of the ALB?

No, to allow public internet traffic, you need to give public access.
You don't know anyone's IP on the internet so you need to specify all IPs using 0.0.0.0/0.


text:
Q: System.Configuration.ConfigurationManager.AppSettings duplicates \ I am using System.Configuration.ConfigurationManager.AppSettings["path"] to retreive the path where a file is, the value of "path" in App.config is C:\Temp\Config.ini but it returns the \ duplicateC:\\Temp\\Config.ini
I assume this is very easy to solve, but it's getting hard for me to find a solution.

A: In C#, the backslash character is the escape character. This character is used to include special characters in a string, e.g. newline (\n), tab (\t).
In order to include a backslash in your string, you need to also add the escape character in front of the backslash, so that you need to type \\. If you want to assign the value "C:\Temp\Config.ini" to a variable, you need to type it like this:
var path = "C:\\Temp\\Config.ini";

The value that is shown to you in the debugger also shows the double backslash, but C# will handle this correctly.
For details on escape characters in C#, see this link.

A: How can you tell that the value has double slash?
Probably what is happening is that the string does have double slash but your viewer is escaping it.
As @Jon Skeet suggested here: Replace "\\" with "\" in a string in C# maybe try to see path.length and count the chars.


text:
Q: How to update QTableView when database updated? I use QSqlRelationalTableModel to extract data from database, and use tableView to show it. Now, when I update my database, how to update tableView automatically to show it? I know i need to use function dataChanged() to make this automatically, but i do not know how to use it? Any suggestion will be appreciated.
The main code is as follows:
QSqlRelationalTableModel *model = new QSqlRelationalTableModel(NULL, db);
model->setTable(tableName);
model->select();
tableView->setModel(model);
tableView->show();

A: No, there is no need to use dataChanged().
You just need to call QSqlRelationalTableModel::select() whenever the database gets updated. This will re-populate the model from the database, and update the views that are using it automatically.

*

*If the database is updated from within you application, you can just call model->select() after the update queries get executed in your application.

*If the database is updated from another application, you'll have to use something like PostgreSQL's event notification system, subscribe to the notification from your application using QSqlDriver::subscribeToNotification() and call model->select() in a slot connected to the notification() signal.
You can use QSqlDriver::hasFeature(QSqlDriver::EventNotifications) to check if notifications from your database are supported.


text:
Q: VoIP Implementation using Java SIP Library I want to Implement simple VoIP application using any of the Java SIP Libraries and APIs.can  you give me a simple example of VOIP application. i have not get any resources or tutor that contains
java Voice over IP.

A: This article covers this domain very widely.

A: For code samples, you can look at Jitsi's source code - it supports VoIP/SIP, along with a number of IM protocols.


text:
Q: Is MAX232 is needed? I'm planning to send data from my laptop via Hyperterminal to Arduino's TX RX pins.
Normally RS232 is around +12V -12V; but I will use a USB to RS232 converter as in the figure below:

And from a DB9 female end I will wire to Arduino TX RX pins. Eventhough the voltages at DB9 pins
might be exceeding 5v, why cant I just use a Voltage divider and feed it to TX RX pins of Arduino?

A: Level translation needs to work in both directions.  Think about the inputs and outputs you are dealing with.
Arduino --> PC
Bin   Ard. V   PC V   Notes
 0      0V     >+3V   Can't be done with a divider
 1      5V     <-3V   Can't be done with a divider

PC --> Arduino
Bin   PC V   Ard. V   Notes
 0    +12V     0V     Can't be done with a divider
 1    -12V     5V     Can't be done with a divider

You may find some one off way of doing this without a RS-232 level translator IC using discretes, but you won't accomplish this with simple resistive dividers.

A: I have done this (not with an Arduino, but with something similar) recently. The voltage levels that RS232 uses (+12V, -12V) will break the Arduino. You need a MAX232.
The much better alternative is to skip the RS232 serial port and go straight to Arduino voltage levels with a USB-to-TTL cable:

You can get these on Digikey, Adafruit, Sparkfun, etc... for roughly the same price as a USB-to-Serial cable, and then you don't need a 2-way converter. Much simpler if you don't really need the serial cable in the first place.

A: From the figure i can see you are using arduino uno. It has a inbuilt usb to serial converter so no need to use a rs232 converter just connect the arduino to your pc through its usb port. It will be detected as a serial port in your PC (I assume that you have the necessary drivers in your pc since you are burning program into the arduino with the same pc) .


text:
Q: Excel Macro to be run till the values are there I recorded a Macro for the below excel:-

Macro Code:-
Sub Macro4()
'
' Macro4 Macro
'
' Keyboard Shortcut: Ctrl+Shift+D
'
    Columns("B:B").Select
    Selection.Insert Shift:=xlToRight
    Range("B1").Select
    ActiveCell.FormulaR1C1 = "P"
    Range("B1").Select
    Selection.AutoFilter
    ActiveSheet.Range("$A$1:$C$13").AutoFilter Field:=3, Criteria1:="Credit"
    Range("B3").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = "=-RC[-1]"
    Range("B3").Select
    Selection.Copy
    Range("A3").Select
    Selection.End(xlDown).Select
    Range("B12").Select
    Range(Selection, Selection.End(xlUp)).Select
    ActiveSheet.Paste
    Application.CutCopyMode = False
    Range("B11").Select
    ActiveSheet.Range("$A$1:$C$13").AutoFilter Field:=3, Criteria1:="Debit"
    Range("B2").Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = "=RC[-1]"
    Range("B2").Select
    Selection.Copy
    Range("A2").Select
    Selection.End(xlDown).Select
    Range("B13").Select
    Range(Selection, Selection.End(xlUp)).Select
    ActiveSheet.Paste
    Application.CutCopyMode = False
    Selection.End(xlUp).Select
    ActiveSheet.ShowAllData
    Columns("B:B").Select
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Range("B2").Select
    Application.CutCopyMode = False
    Columns("A:B").Select
    Selection.NumberFormat = "#,##0.00_ ;[Red]-#,##0.00 "
    Range("B1").Select
    Selection.AutoFilter
End Sub

This gives the result:-

When I try the same Macro on the below excel:-

This gives the below result.

In reality, I don't know how many prices be there so how can edit my Macro in such a way that it selects all the range till the last row

A: You can also use a formule for this?
B2=IFERROR(IF(C2="credit",A2*(-1),(IF(C2="Debit"),A2,""),""),"")

Then just use conditional formatting on the column to get the colors.
If you insist on a macro, you can add find last row and loop through all rows to check the value of column C.
Should be easy to find and copy from google, there are a lot of simular examples.
Double check the formula, I've written it om my sellphone but it should be ok

A: Please try this code. It takes a different approach.
Sub BookToLedger()

    Dim Rng As Range
    Dim Cell As Range
    Dim R As Long

    Application.ScreenUpdating = False

    With Worksheets("Sheet1")       ' change tab name to suit
        Set Rng = .Range(.Cells(2, "A"), .Cells(.Rows.Count, "A").End(xlUp))
        .Columns(2).Insert Shift:=xlToRight
        .Cells(1, 2).Value = "Amount"
    End With

    With Rng
        .NumberFormat = "#,##0.00_ ;[Red]-#,##0.00 "
        .Copy Destination:=.Offset(0, 1)
        Set Rng = .Offset(0, 1)
    End With

    For Each Cell In Rng.Cells
        With Cell
            If Left(.Offset(0, 1).Value, 2) = "Cr" Then
                .Value = .Value * -1
            End If
        End With
    Next Cell
    Application.ScreenUpdating = True
End Sub

The code first sets the number format in column A. Then it inserts a copy of column A, including the new number format, in a new column B. Finally it loops through all entries in column B and makes the credit values negative.

A: This macro will run in activesheet. So select the sheet before you run this macro. or add first line to mention the sheet.
Sub Macro4()
' Keyboard Shortcut: Ctrl+Shift+D
Range("A1").Select
Dim tblRng As Range, cl As Range

Columns("B:B").Insert Shift:=xlToRight
Range("B1").FormulaR1C1 = "P"

Set tblRng = Range("A2", Range("C" & Rows.Count).End(xlUp))

For Each cl In Range(tblRng.Cells(1, 2), tblRng.Cells(tblRng.Rows.Count, 2))
If cl.Offset(0, 1) = "Credit" Then cl = -cl.Offset(0, -1)
If cl.Offset(0, 1) = "Debit" Then cl = cl.Offset(0, -1)
Next

Range(tblRng.Cells(1, 1), tblRng.Cells(tblRng.Rows.Count, 2)).NumberFormat = "#,##0.00_ ;[Red]-#,##0.00 "

End Sub


text:
Q: Protection against accidental object incompatibility? TL;DR
Protection against binary incompatibility resulting from compiler argument typos in shared, possibly templated headers' preprocessor directives, which control conditional compilation, in different compilation units?
Ex.
g++ ... -DYOUR_NORMAl_FLAG ... -o libA.so
/**Another compilation unit, or even project. **/
g++ ... -DYOUR_NORMA1_FLAG ... -o libB.so
/**Another compilation unit, or even project. **/
g++ ... -DYOUR_NORMAI_FLAG ... main.cpp libA.so //The possibilities!

The Basic Story
Recently, I ran into a strange bug: the symptom was a single SIGSEGV, which always seemed to occur at the same location after recompling. This led me to believe there was some kind of memory corruption going on, and the actual underlying pointer is not a pointer at all, but some data section.
I save you from the long and strenuous journey taking almost two otherwise perfectly good work days to track down the problem. Sufficient to say, Valgrind, GDB, nm, readelf, electric fence, GCC's stack smashing protection, and then some more measures/methods/approaches failed.
In utter devastation, my attention turned to the finest details in the build process, which was analogous to:

*

*Build one small library.

*Build one large library, which uses the small one.

*Build the test suite of the large library.

Only in case when the large library was used as a static, or a dynamic library dependency (ie. the dynamic linker loaded it automatically, no dlopen)
was there a problem. The test case where all the code of the library was simply included in the tests, everything worked: this was the most important clue.
The "Solution"
In the end, it turned out to be the simplest thing: a single (!) typo.
Turns out, the compilation flags differed by a single char in the test suite, and the large library: a define, which was controlling the behavior of the small library, was misspelled.
Critical information morsel: the small library had some templates. These were used directly in every case, without explicit instantiation in advance. The contents of one of the templated classes changed when the flag was toggled: some data fields were simply not present in case the flag was defined!
The linker noticed nothing of this. (Since the class was templated, the resultant symbols were weak.)
The code used dynamic casts, and the class affected by this problem was inheriting from the mangled class -> things went south.
My question is as follows: how would you protect against this kind of problem? Are there any tools or solutions which address this specific issue?
Future Proofing
I've thought of two things, and believe no protection can be built on the object file level:

*

*1: Save options implemented as preprocessor symbols in some well defined place, preferably extracted by a separate build step. Provide check script which uses this to check all compiler defines, and defines in user code. Integrate this check into the build process. Possibly use Levenshtein distance or similar to check for misspellings. Expensive, and the script / solution can get complicated. Possible problem with similar flags (but why have them?), additional files must accompany compiled library code. (Well, maybe with DWARF 2, this is untrue, but let's assume we don't want that.)

*2: Centralize build options: cheap, customization option left open (think makefile.local), but makes monolithic monstrosities, strong project couplings.

I'd like to go ahead and quench a few likely flame inducing embers possibly flaring up in some readers: "do not use preprocessor symbols" is not an option here.

*

*Conditional compilation does have it's place in high performance code, and doing everything with templates and enable_if-s would needlessly overcomplicate things. While the above solution is usually not desirable it can arise form the development process.

*Please assume you have no control over the situation, assume you have legacy code, assume everything you can to force yourself to avoid side-stepping.

*If those won't do, generalize into ABI incompatibility detection, though this might escalate the scope of the question too much for SO.

I'm aware of:

*

*http://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html

*

*DT_SONAME is not applicable.

*Other version schemes therein are not applicable either - they were designed to protect a package which is in itself not faulty.

*Mixing C++ ABIs to build against legacy libraries

*Static analysis tool to detect ABI breaks in C++

A: If it matters, don't have a default case.
#ifdef YOUR_NORMAL_FLAG
  // some code
#elsif YOUR_SPECIAL_FLAG
  // some other code
#else
  // in case of a typo, this is a compilation error
#  error "No flag specified"
#endif

This may lead to a large list of compiler options if conditional compilation is overused, but there are ways around this like defining config-files
flag=normal
flag2=special

which get parsed by build scripts and generate the options and can possibly check for typos or could be parsed directly from the Makefile.


text:
Q: Oracle - SQL, pulling time rages from within a date range I'm trying to write a select statement to return average values over a specific time range over a specific date range. For example I'd like to know the avg(max_percent_util) over the past 7 days during the time frames 4pm-11pm, all day, and 8am-6pm. This is what I have so far and I'm not sure the query will ever end at this point.
select
sdpt.DOWN_DESC,
avg(sdpt.max_percent_util) seven_day_prime,
avg(sday.max_percent_util) seven_day,
avg(sdb.max_percent_util) seven_day_business

from

(select down_desc, hour_stamp, max_percent_util from downstream_hour_facts
where ((hour_stamp >= sysdate-8 AND to_char(hour_stamp, 'HH24:MI') >= '16:00' AND to_char(hour_stamp, 'HH24:MI') <= '23:00')
or (hour_stamp >= sysdate-7 AND to_char(hour_stamp, 'HH24:MI') >= '16:00' AND to_char(hour_stamp, 'HH24:MI') <= '23:00')
or (hour_stamp >= sysdate-6 AND to_char(hour_stamp, 'HH24:MI') >= '16:00' AND to_char(hour_stamp, 'HH24:MI') <= '23:00')
or (hour_stamp >= sysdate-5 AND to_char(hour_stamp, 'HH24:MI') >= '16:00' AND to_char(hour_stamp, 'HH24:MI') <= '23:00')
or (hour_stamp >= sysdate-4 AND to_char(hour_stamp, 'HH24:MI') >= '16:00' AND to_char(hour_stamp, 'HH24:MI') <= '23:00')
or (hour_stamp >= sysdate-3 AND to_char(hour_stamp, 'HH24:MI') >= '16:00' AND to_char(hour_stamp, 'HH24:MI') <= '23:00')
or (hour_stamp >= sysdate-2 AND to_char(hour_stamp, 'HH24:MI') >= '16:00' AND to_char(hour_stamp, 'HH24:MI') <= '23:00')
or (hour_stamp >= sysdate-1 AND to_char(hour_stamp, 'HH24:MI') >= '16:00' AND to_char(hour_stamp, 'HH24:MI') <= '23:00'))) sdpt,

(select down_desc, hour_stamp, max_percent_util from downstream_hour_facts
where ((hour_stamp >= sysdate-8) or (hour_stamp >= sysdate-7) or (hour_stamp >= sysdate-6)
or (hour_stamp >= sysdate-5) or (hour_stamp >= sysdate-4) or (hour_stamp >= sysdate-3)
or (hour_stamp >= sysdate-2) or (hour_stamp >= sysdate-1))) sday,

(select down_desc, hour_stamp, max_percent_util from downstream_hour_facts
where ((hour_stamp >= sysdate-8 AND to_char(hour_stamp, 'HH24:MI') >= '8:00' AND to_char(hour_stamp, 'HH24:MI') <= '18:00')
or (hour_stamp >= sysdate-7 AND to_char(hour_stamp, 'HH24:MI') >= '08:00' AND to_char(hour_stamp, 'HH24:MI') <= '18:00')
or (hour_stamp >= sysdate-6 AND to_char(hour_stamp, 'HH24:MI') >= '08:00' AND to_char(hour_stamp, 'HH24:MI') <= '18:00')
or (hour_stamp >= sysdate-5 AND to_char(hour_stamp, 'HH24:MI') >= '08:00' AND to_char(hour_stamp, 'HH24:MI') <= '18:00')
or (hour_stamp >= sysdate-4 AND to_char(hour_stamp, 'HH24:MI') >= '08:00' AND to_char(hour_stamp, 'HH24:MI') <= '18:00')
or (hour_stamp >= sysdate-3 AND to_char(hour_stamp, 'HH24:MI') >= '08:00' AND to_char(hour_stamp, 'HH24:MI') <= '18:00')
or (hour_stamp >= sysdate-2 AND to_char(hour_stamp, 'HH24:MI') >= '08:00' AND to_char(hour_stamp, 'HH24:MI') <= '18:00')
or (hour_stamp >= sysdate-1 AND to_char(hour_stamp, 'HH24:MI') >= '08:00' AND to_char(hour_stamp, 'HH24:MI') <= '18:00'))) sdb
where sdpt.down_desc = sday.down_desc and sday.down_desc = sdb.down_desc
group by sdpt.DOWN_DESC
order by sdpt.down_desc

Example output that i'm looking to re-create:

*

*Metric:                       Utilization Data

*Previous 24 Hours:            7.15%

*7 Day Rolling (all hours):        7.12%

*7 Day Rolling Prime Time (4-12):  7.12%

*7 Day Rolling Business Hours (9-5):   7.12%

A: One reason that your query isso slow is that you're not camparing dates, you're comparing strings; using TO_CHAR().  You're also doing a lot of redundant work.
Here is an example that parses the data once (not three times), avoids string comparisons, and so should quickly filter the data down to the 8 and a bit days you want.
WITH
  filtered_data AS
(
  SELECT
    down_desc,
    hour_stamp,
    TRUNC(hour_stamp)                date_stamp,
    hour_stamp - TRUNC(hour_stamp)   time_stamp
  FROM
    downstream_hour_facts
  WHERE
    hour_stamp >= TRUNC(sysdate) - 8
)
SELECT
  down_desc,
  AVG(CASE WHEN date_stamp >= TRUNC(sysdate)
           THEN max_percent ELSE NULL END)          today,
  AVG(CASE WHEN date_stamp <  TRUNC(sysdate)
           THEN max_percent ELSE NULL END)          seven_day_all,
  AVG(CASE WHEN date_stamp <  TRUNC(sysdate)
            AND time_stamp >= TO_TIMESTAMP('16:00', 'HH24:MI')
            AND time_stamp <  TO_TIMESTAMP('23:00', 'HH24:MI')
           THEN max_percent ELSE NULL END)          seven_day_prime,
  AVG(CASE WHEN date_stamp <  TRUNC(sysdate)
            AND time_stamp >= TO_TIMESTAMP('08:00', 'HH24:MI')
            AND time_stamp <  TO_TIMESTAMP('16:00', 'HH24:MI')
           THEN max_percent ELSE NULL END)          seven_day_business
FROM
  filtered_data
GROUP BY
  down_desc
ORDER BY
  down_desc

EDIT
I've also noticed that you're joinging the data in a 'dangerously' incorrect way...
Sub Query 1 may return 9 records for a metric.
Sub Query 2 may return 3 records for that metric.
Sub Query 3 may return 4 records for that metric.
But then you join them only by the metric.  All 9 records from SQ1 match all 3 from SQ2 (27 records now), and all of them match all 4 from SQ3 (108 records now).
When joining sets of data be very careful that each record joins to where it's needed, and only where it's needed.
(The single parse version above should totally avoid that problem anyway.)


text:
Q: Как при помощи CallbackQuery перейти на следующий state aiogram Я запускаю state.
async def user_form_start(message : types.Message):
    try:
        query = "SELECT EXISTS(SELECT tg_id FROM bot WHERE tg_id = '" + str(message.from_user.id) + "' AND status = 1)"
        if (check_username(message.from_user.id, db_name, query)[0][0] == 1):
            await message.answer('Ваша заявка обрабатывается, дождитесь ответа')
        else:
            await Form.uni.set()
            await message.answer('Выберите из списка университет', reply_markup=btn_uni_select_kb)
    except:
        await message.answer('Что-то пошло не так, сообщения об ошибках обрабатываются мной максимально быстро')

Здесь обработчик, он находится в другом файле.
async def uni_button_select(query: types.CallbackQuery, state: FSMContext):
    if (len(get_arr_uni("uni.txt")) > parse_digit(query.data)):
        await state.update_data(uni=get_arr_uni("uni.txt")[parse_digit(query.data)])
        print(get_arr_uni("uni.txt")[parse_digit(query.data)])

В нем я обрабатываю и обновляю значение, как сделать так что при его срабатывании у меня state переходит на следующий. То есть при начале state отправляет inline кнопку, по нажатию на которую state сменяется на следующий. Подскажите пожалуйста

A: Если я правильно понял, то uni_button_select не ловит следующие состояние.
Всё потому что по дефолту там не установлено никакое состояние
@dp.callback_query_handler(state='*')
async def uni_button_select(query: types.CallbackQuery, state: FSMContext):
    if (len(get_arr_uni("uni.txt")) > parse_digit(query.data)):
        await state.update_data(uni=get_arr_uni("uni.txt")[parse_digit(query.data)])
        print(get_arr_uni("uni.txt")[parse_digit(query.data)])

@dp.callback_query_handler(state=Form.uni) - можно так же сделать


text:
Q: Show that $G$ is differentiable on $R$ and calculate its derivative. Let $f$ be a continuous function on $\mathbb R$ and define $$G(x) = \int _0 ^{\sin x}f(t)dt$$ for $x \in \mathbb R$. Show that $G$ is differentiable on $\mathbb R$ and calculate its derivative.
Attempt:
Let $h >0$. Then, $$\frac {G(x+h) - G(x)}{h} = \frac {\int_{\sin(x)}^{\sin(x+h)}f(t) dt}{h}.$$
Let $c,t \in \mathbb R$. Then, $\forall\varepsilon, \exists\delta>0$ s.t. if $|t-c|<\delta, |f(t)-f(c)|<\varepsilon.$
This implies that $f(c) - \varepsilon < f(t) < f(c) + \varepsilon.$
Take integral on each side and divide by $h$. Then, we have $$\frac{\int_{\sin (x)}^{\sin(x+h)}(f(c)-\varepsilon) dt}{h} \le \frac{\int_{\sin (x)}^{\sin(x+h)}f(t)dt}{h} \le \frac{\int_{\sin (x)}^{\sin(x+h)}(f(c)+\varepsilon)dt}{h}.$$
This implies : $(\sin(x+h)-\sin(x))(f(c) -\varepsilon)/h \le \frac{\int_{\sin (x)}^{\sin(x+h)}f(t)dt}{h}\le (\sin(x+h)-\sin(x))(f(c) +\varepsilon)/h.$
I am stuck here. I was planning to show $|\frac{\int_{\sin (x)}^{\sin(x+h)}f(t)dt}{h}- \cdot| < \varepsilon.$ But, I don't know what to do here. Could you give some help?

A: If $F(x)=\int_0^xf(t)\,\mathrm dt$, then $G(x)=F\bigl(\sin(x)\bigr)$. Now, use the chain rule and the fundamental theorem of Calculus.