Unable to access directory inside workspace in jenkins

Question: So I have a Jenkins job wherein as part of the build.
I run one script which creates a folder in the workspace say "test"
so the script runs fine and creates the folder test.
After this, I have a maven command wherein I want  to access this test folder(as an argument) I am trying it as $workspace/test
but it's not working.
Can anyone guide if i am missing anything here
Answer: Can you give us more information - maybe code snippets?
I'm not sure what you mean with 'maven command' and '$workspace/test'
If you want use a variable in a pom.xml like:
<path>${workspace}</path>

you will have to assign it in the properties:
<workspace>...location...</workspace>

Otherwise you can use maven preassigned variables like
${basedir}/

Comment: Thanks for the info @krysztokowski  No, I don't want to use inside pom file.  In the workspace as part of the first build step  the test directory is created via a python script ... Later as part of 2nd build step I am using a maven command wherein I want to pass this directory which is created by the above build step as an argument.  basically, I want to know how can I pass the path of "subdirectory inside the workspace" as an argument to a maven build command
Comment: @Shell_Magic
Sounds like it would be the best to use a variable (for the subdirectory) in your build environment (level above maven). I'm not sure how you build (shell script, jenkins, gitlab) but i would create the variable there and use it from there in the lower levels (maven etc.) Otherwise or furthermore these links could help:
https://stackoverflow.com/questions/7513319/passing-command-line-arguments-from-maven-as-properties-in-pom-xml
https://stackoverflow.com/questions/10463077/how-to-refer-environment-variable-in-pom-xml


Menu mobile, problema com delegação de evento

Question: Estou criando um menu desktop/mobile que será replicado algumas vezes na pagina, no entanto meu código apresenta um bug que ao clicar em abrir um acaba abrindo todos. Segue o codigo

Mobile Menu

Item 1

Item 2

Item 3

A classe "active-menu" possui apenas um visibility:hidden; para abrir e fechar o menu, o script feito consegue delegar e identificar em qual botão está clicando, no entanto não identifica qual o menu que está trocando a classe tendo em vista que esse html vai ser replicado algumas vezes
$(document).on('click', '.menu-button-section', function () {
 if( $('.menu-section').hasClass('active-menu')){
    $('.menu-section').removeClass('active-menu');
  } else {
     $('.menu-section').addClass('active-menu');
  }   });

O bug acontece nessa linha, aonde ja tentei de algumas formas transformar esse ".menu-section" em um target delegado, mas sem sucesso
$('.menu-section').removeClass('active-menu');

Comment: Conhece o objeto `this` do Javascript?
Comment: foi, conseguir resolver ontem, só não publiquei, vou postar a resposta
Answer: Conseguir resolver o problema, mudando a hierarquia do html, deixando o botão dentro do ul e utilizando o método this
O script ficou assim :
$(document).on('click', '.menu-button', function () {
 if( $(this).children('.menu').hasClass('active-menu')){
     $(this).children('.menu').removeClass('active-menu');
   } else {
     $(this).children('.menu').addClass('active-menu');
   }  });

Comment: Leia também sobre a função [`toggleClass`](http://api.jquery.com/toggleclass/)
Comment: Então tem mais coisa errada no seu layout/script.
Comment: Na verdade confundi o metodo com slidetoggle rsrsrs
Comment: Toggle class buga meu layout na hora de voltar a versão desktop


getLimit () returns null

Question: I am developing an app using google drive api.
However, getLimit() may return null from a specific account.
Why does getLimit() return null?
[OAuthGoogleDrive.java:updateAccountInfo:getLimit : null
[OAuthGoogleDrive.java:updateAccountInfo:getUsage : 7592740408804
https://developers.google.com/resources/api-libraries/documentation/drive/v3/java/latest/com/google/api/services/drive/model/About.StorageQuota.html#getLimit--
Answer: Docs says that it will not always return a valid number, only "if applicable".

The usage limit, if applicable. This will not be present if the user
  has unlimited storage.
Returns: value or null for none

getLimit () returns null


remove J and K key events on twitter.com

Question: I built a browser extension that extends twitter.com. It opens a jQuery UI modal window, and has some text inputs. When I type in those inputs, it works, except for the J and K keys. Those keys are part of some custom Twitter event (scrolling between tweets). I can get all the keys to actually type the letter into the box except for those two.
I want to know how to unbind the keypress stuff for those two keys so that I can get those two letters to type. Any ideas on how to unbind them? I have tried catching the event and preventing the default on it...didn't help. I have caught it and returned true/false, also no help. Please let me know.
Comment: Check out `phoenix.bundle.js`, it appears to do the binding you're talking about. Maybe find out what functions it's binding and either overwrite them or reference them to detach the triggers.
Answer: This sounds very similar to a problem I had where google would alter the up and down arrow keys. Here is where I solved it on SO after some help. Basically I stopped the event like so (for me its up and down, find the keycodes for your j and k):
if (event.keyCode == 40 || event.keyCode == 38)  {
    event.cancelBubble = true;
    event.stopPropagation();
    return false;
}

Answer: Twitter appears to use jQuery for event binding.  From the JavaScript console, we can inspect these events:
$(document).data('events').keydown;
$(document).data('events').keypress;
$(document).data('events').keyup;

Through basic trial and error, we can narrow our scope to the keypress event by removing these events and testing for the missing functionality.
// Results in j/k keys no longer moving up/down
$(document).data('events').keypress = [];

This of course is sort of a hack-and-slash approach, but useful for narrowing things down.
Comment: SO this keypress array has three events in it. Setting any of them to null fixes the page.
Comment: @aaronfrost I imagine that not all three are involved in this behavior, but that by setting one to null you are creating an exception in the event handling code that results in most/all of them not firing (and therefore the one of interest not firing)
Answer: I ran into the same issue with textareas and input fields on Twitter.com when I built a browser extension to enhance the page. I was able to get everything to work as expected by targeting the specific input and textareas that my extension created and then stoping the propagation of the keypress event.
$("selector-for-inputs-created-by-extension")
    .bind("keypress", function(e) {
        e.stopPropagation();
    });

Hope that helps clarify things.


Default Initialization of Private Fields in Java

Question: Say I have a class called Person:
class Person{
    private int num = 1;
}

When calling the empty constructor for class Person, will Java first initialize num to a default value of zero, and then assign num to 1? Or will Java initialize num to 1 straight away? Doesn't C++ do the former unless you use initializer syntax?
Thank You!
Comment: How would you tell the difference?
Comment: I'm not sure. I figure it would be best to initialize fields to the value you specified and not spend time initializing them to a default value.
Comment: initializing all the class variables to their default value is really easy: just set a contiguous block of memory to all zeros. This strategy is fast and easy to implement - a lot easier than trying to work out what isn't initialized (say, if variables are set conditionally), and so is obviously less vulnerable to problems with using uninitialized memory, making it secure. Don't try to second guess the performance, but also don't discount benefits beyond performance.
Answer: It would assign the value zero first.
If you put something before the field declaration like so, you could see this:
class Person{
    { print(); }
    private int num = 1;
    { print(); }

    void print() {
      System.out.println(num);
    }
}

This would print:
0
1

This is described in JLS Sec 4.12.5:

Each class variable, instance variable, or array component is initialized with a default value when it is created

And Sec 15.9.4 (emphasis added and some parts omitted):

The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its default value (§4.12.5).
...
Next, the selected constructor of the specified class type is invoked ...

In other words, object creation and constructor invocation are distinct operations, and the fields are initialized to their default values prior to the invocation of the constructor.
The actual field initialization occurs in the constructor: field initializes are inlined into every constructor that invokes super(...), immediately after the call to super(...). The following is exactly equivalent to the above:
 class Person{
   private int num;

   Person() {
     super();
     print();
     num = 1;
     print();
   }

   void print() {
     System.out.println(num);
   }
}

One subtle point to make it that although declaring the field final would make the output of this code:
1
1

This does not mean that final variables are initialized sooner. All that has changed in that case is that num has become a compile-time constant expression, and thus is inlined. As such, print() would actually be executing:
System.out.println(1);

In other words, it does not read the field at all.
Answer: Regarding the Java Docs:
Fields that are declared but not initialized will be set to a reasonable default by the compiler.
Considering this enunciation, I would say that Java will assign the value straight away.
Answer: boolean false
byte    (byte) 0
short   (short) 0
int 0
long    0L
char    \u0000
float   0.0f
double  0.0d
object reference    null

Here are all the default values of Java. It will be init by this by default any variable with this. So with answer of Andy I can conclude that it will be always first 0 then it will go by the value you give to the variable.


How to define & init Matrix in Scala

Question: I have a class which has two dimensional array as a private member - k rows and n columns (the size is not known when defining the Matrix).
I want init the Matrix using a special method: initMatrix, which will set the number of rows and cols in the matrix, and init all the data to 0.
I saw a way to init a multi-dimensional array in the following way:
  private var relationMatrix = Array.ofDim[Float](numOfRows,numOfCols)

but how can I define it without any size, and init it later?
Comment: If you're delaying initialization for efficiency reasons (e.g. might not always use it) then consider defining it as a `lazy val`. In Scala it's preferable to make your classes immutable, so late initialization of members is discouraged.
Answer: Did you consider using an Option?
class MyClass() {
  private var relationMatrix: Option[Array[Array[Float]]] = None

  def initMatrix(numOfRows:Int, numOfCols:Int): Unit = {
    relationMatrix = Some(/* Your initialization code here */)
  }
}

The pros of this approach is that in any time you can know whether your matrix is initialized or not, by using relationMatrix.isDefined, or by doing pattern matching,
def matrixOperation: Float = relationMatrix match {
  case Some(matrix) =>
    // Matrix is initialized
  case None =>
    0 // Matrix is not initialized
}

or map on it, like this:
def matrixOperation: Option[Float] = relationMatrix.map {
  matrix: Array[Array[Float]] =>
  // Operation logic here, executes only if the matrix is initialized
}

Answer: For declaring a mutable 2D array of floats without setting dimensions and values, consider
var a: Array[Array[Float]] = _
a: Array[Array[Float]] = null

For initialising it consider the use of Array.tabulate like this
def init (nRows: Int, nCols: Int) = Array.tabulate(nRows,nCols)( (x,y) => 0f )

Thus for instance,
a = init(2,3)

delivers
Array[Array[Float]] = Array(Array(0.0, 0.0, 0.0), Array(0.0, 0.0, 0.0))

Update the use of Option (already suggested by @Radian) proves type-safe and more robust at run-time, in contrast with null initialisation; hence, consider also Option(Array.tabulate).
Answer: var matrix: Array[Array[Float]] = null — this declares a variable of the same type as yours
Comment: `null` is only in Scala for Java compatibility, and you shouldn't use it unless forced to by Java
Answer: You can make your initMatrix method part of the companion object.
class Matrix(numOfRows:Int, numOfCols:Int) {
    private var relationMatrix = Array.ofDim[Float](numOfRows, numOfCols)
// your code there

}

object Matrix {
    def initMatrix(numOfRows:Int, numOfCols:Int) = Matrix(numOfRows, numOfCols)
}

var myMatrix = Matrix.initMatrix(3,5)

How to define & init Matrix in Scala


How to not split select list by content type

Question: This is about the regular select widget that you can choose in the Manage form display page.
If this widget is linked to an entity_reference field allowing several bundles to be selected; then you end up with an #options populated as follow:
_none -> "None"
Bundle label 1 ->
  id1 -> "label of ID 1"
  id3 -> "label of ID 3"
  id4 -> "label of ID 4"
Bundle label 1 ->
  id5 -> "label of ID 5"
  id6 -> "label of ID 6"

I would like to have
_none -> "None"
id1 -> "label of ID 1"
id3 -> "label of ID 3"
id4 -> "label of ID 4"
id5 -> "label of ID 5"
id6 -> "label of ID 6"

Is there any option to change? or should I hook something?
Answer: It would be nice if this were optional, but ...
You will have to write a hook_form_alter or similar to rewrite/reorganize the options in the field: They're organized in logically obvious subarrays matching what you see on screen. You can "flatten" them into a single array and re-order the options as you please.
Comment: Thanks you, I accepted your answer because you explain that there are no simple way except flattening manually. Note that using a view to populate the options doesn't solve the problem... [maybe you can update your answer for this point]


How to tell if datagridview column is an image or checkbox column?

Question: I'm trying to create a custom function that saves the content of a datagridview to a file. I'm doing this instead of serializing because my custom function is designed to be as easy and quick to implement as possible to save and load the winform's state, and creating custom classes every time I want to serialize an object is not as easy and quick as possible.
To do this, I need to programmatically detect which columns in a datagridview are either image columns or checkbox columns so I know how to handle them appropriately when loading. I looked online and it appears that there is no one else who's mentioned it yet (as far as my Google searches would've suggested), but I'm absolutely sure that there is some way to tell what kind of cell/column some cell/column is. Does anyone know?
Answer: You can do something like this -
        foreach (var col in dataGridView1.Columns)
        {
            if (col is DataGridViewImageColumn)
            {
                // Image Column
            }

            if (col is DataGridViewCheckBoxColumn)
            {
                // CheckBox Column
            }
        }

Answer: Just compare to type:
        DataGridView dgv = new DataGridView();

        foreach (DataGridViewColumn col in dgv.Columns)
        {
            if (col.GetType() == typeof(DataGridViewCheckBoxColumn))
            {
                // do something
            }
            else if (col.GetType() == typeof(DataGridViewImageColumn))
            {
                // do something else
            }
        }

Comment: Can you validate? This won't compile in C#
Answer: foreach (DataGridViewRow dr in dataGridView1.Rows) {
  foreach (DataGridViewCell dc in dr.Cells) {
    if (dc.GetType() == typeof(DataGridViewImageCell)) {

    }
  }
}

This should work... including the cells!!!
Answer: This should work.
 For each col in datagridview.columns
   If col.CellType.Name = "DataGridViewImageColumn" Then
   'do something
   End If
 Next

Answer: You might also want to look into
column.ValueType

Answer: This one is what I'm using:
Dim colType As Type = DataGridView1.Columns(0).GetType
If colType.Name = "DataGridViewImageColumn" Then
'code for image column type
End If

Credits:
Link to VB forums


suspend a deployment/replicaset to stop a CrashLooping Pod from looping

Question: i have a pod that is in CrashLoopBackOff. the reason is clear, i will have to migrate a database-schema to fix that before the container may retry looping.
i understand that the pod is supposed to crash-loop but i need to pause this. if kubectl rollout pause and then kubectl delete pod, the pod is terminating and still the deployment's replicaset seems to start a new one.
is there any way to just "suspend the deployment or replicaset" to have a chance to repair infrastructure without the pods constantly loop-crashing and/or getting recreated?
Answer: i just found out i have to scale the deployment's pod to 0 replicas:
kubectl scale --replicas=0 deployment/<your-pod>

https://stackoverflow.com/questions/54821044/how-to-stop-pause-a-pod-in-kubernetes


Did grub updating bring my server down?

Question: I have an Ubuntu 12.04 server. Last night I installed a few updates using apt-get dist-upgrade, including grub, and rebooted. After rebooting, I couldn't boot into Ubuntu. I just get a big flashing prompt, but nothing comes out when I type in it. If I try to press Del on boot for Setup, or Tab for BIOS, the boot screen just freezes.
The server is remote, so I had a technician boot from a live CD and try to run Boot Repair using the 2nd option, but that didn't fix it.
Here's the apt-get history. You may notice entries for removing kernels; I don't think they're related, and I definitely didn't remove the current kernel (that's linux-image-3.2.0-65-generic), but maybe I just don't know better, so I'm leaving those entries in. I also converted commas to newlines for readability.
Is it possible a routine software update could have caused my server to break like this? Is there any other option than Boot-Repair to fix it? The server is heavily configured, so I'm rather reluctant to reinstall.
Thanks in advance!
Start-Date: 2014-07-07  17:25:08
Commandline: apt-get dist-upgrade
Upgrade: grub-efi-amd64:amd64 (1.99-21ubuntu3.14, 1.99-21ubuntu3.15)
libdrm-radeon1:amd64 (2.4.46-1ubuntu0.0.0.1, 2.4.52-1~precise1)
libdrm2:amd64 (2.4.46-1ubuntu0.0.0.1, 2.4.52-1~precise1)
libdrm-nouveau1a:amd64 (2.4.46-1ubuntu0.0.0.1, 2.4.52-1~precise1)
libdrm-intel1:amd64 (2.4.46-1ubuntu0.0.0.1, 2.4.52-1~precise1)
grub-efi-amd64-bin:amd64 (1.99-21ubuntu3.14, 1.99-21ubuntu3.15)
grub-efi:amd64 (1.99-21ubuntu3.14, 1.99-21ubuntu3.15)
linux-libc-dev:amd64 (3.2.0-65.98, 3.2.0-65.99)
grub-common:amd64 (1.99-21ubuntu3.14, 1.99-21ubuntu3.15)
grub2-common:amd64 (1.99-21ubuntu3.14, 1.99-21ubuntu3.15)
linux-image-3.2.0-65-generic:amd64 (3.2.0-65.98, 3.2.0-65.99)
End-Date: 2014-07-07  17:25:45

Start-Date: 2014-07-07  17:29:54
Commandline: apt-get remove linux-image-3.2.0-57-generic
Remove: linux-image-3.2.0-57-generic:amd64 (3.2.0-57.87)
End-Date: 2014-07-07  17:30:00

Start-Date: 2014-07-07  17:30:15
Commandline: apt-get remove linux-image-3.2.0-58-generic
Remove: linux-image-3.2.0-58-generic:amd64 (3.2.0-58.88)
End-Date: 2014-07-07  17:30:21

Start-Date: 2014-07-07  17:30:35
Commandline: apt-get remove linux-image-3.2.0-59-generic linux-image-3.2.0-60-generic
Remove: linux-image-3.2.0-60-generic:amd64 (3.2.0-60.91)
linux-image-3.2.0-59-generic:amd64 (3.2.0-59.90)
End-Date: 2014-07-07  17:30:44

Start-Date: 2014-07-07  17:31:04
Commandline: apt-get remove linux-image-3.2.0-61-generic linux-image-3.2.0-63-generic
Remove: linux-image-3.2.0-63-generic:amd64 (3.2.0-63.95)
linux-image-3.2.0-61-generic:amd64 (3.2.0-61.93)
End-Date: 2014-07-07  17:31:13

Start-Date: 2014-07-09  12:26:23
Commandline: apt-get install -y --force-yes dmraid
Install: libdmraid1.0.0.rc16:amd64 (1.0.0.rc16-4.1ubuntu8, automatic)
kpartx-boot:amd64 (0.4.9-3ubuntu5.1, automatic)
kpartx:amd64 (0.4.9-3ubuntu5.1, automatic)
dmraid:amd64 (1.0.0.rc16-4.1ubuntu8)
End-Date: 2014-07-09  12:26:31

Start-Date: 2014-07-09  12:27:16
Commandline: apt-get purge -y --force-yes grub* shim-signed
Purge: grub-efi-amd64:amd64 (1.99-21ubuntu3.15)
grub-efi-amd64-bin:amd64 (1.99-21ubuntu3.15)
grub-efi:amd64 (1.99-21ubuntu3.15)
grub-common:amd64 (1.99-21ubuntu3.15)
grub2-common:amd64 (1.99-21ubuntu3.15)
End-Date: 2014-07-09  12:27:18

Start-Date: 2014-07-09  12:27:46
Commandline: apt-get install -y --force-yes grub-efi-amd64-signed shim-signed
Install: sbsigntool:amd64 (0.6-0ubuntu4~12.04.1, automatic)
grub-efi-amd64:amd64 (1.99-21ubuntu3.15, automatic)
secureboot-db:amd64 (1.1~ubuntu0.12.04.1, automatic)
shim:amd64 (0.4-0ubuntu4, automatic)
grub-efi-amd64-bin:amd64 (1.99-21ubuntu3.15, automatic)
grub-common:amd64 (1.99-21ubuntu3.15, automatic)
grub2-common:amd64 (1.99-21ubuntu3.15, automatic)
shim-signed:amd64 (1.5~12.04.2+0.4-0ubuntu4)
grub-efi-amd64-signed:amd64 (1.9~ubuntu12.04.6+1.99-21ubuntu3.14)
End-Date: 2014-07-09  12:27:54

Comment: > The server is heavily configured, so I'm rather reluctant to reinstall. and that is why configuration management is your best friend. TBH I can't tell from that but you always have to be very careful with dist-upgrades. Usually I bring up another box instead.
Answer: Try booting into live cd and running a grub update on the hard drive.  If the person on the other end isn't to savvy try a live cd like rescatux.
Comment: Did that end up fixing your problem?
Comment: It did, in a sense. I had to create a new boot partition and install a new kernel there using Boot Repair. So I guess that's not quite what you had in mind.

Did grub updating bring my server down?


Truss rod adjustments and tuning

Question: I'm setting up my guitar and I am about to adjust my truss rod. I heard to tune the guitar first but what tuning? I typically play tuned down a step and a half. Should I tune my guitar to that setting or standard E?
Answer: Assuming you will only play that guitar with that gauge of strings in that tuning, then that's what you do.Tune up to standard, and adjust,and the truss rod will wonder what the heck's happened when you tune down!

Truss rod adjustments and tuning


Highlight active (opened) link

Question: I want to highlight active (opened) link . This color must be maintained for all time when link is open. Not only on mouse click or hover.
Here is JS way what i tried:

html links:

Home

Football

Hockey</a

It work but the problem is with refresh and back button. It does not change this color to previous link.
With other JS ways i got same problem.
Only with css it does not work. For example:

Home

Football

Hockey</a

and CSS
#home .nav1 {
    color: #000;
    background-image:url(farba3.png);
 }
#football .nav1 {
    color: #000;
    background-image:url(farba3.png);
 }
#hockey .nav1 {
    color: #000;
    background-image:url(farba3.png);
 }

Comment: why dont you use the `a:visited` pseudo? this stays even after page-refresh, as far as I know.
Comment: @Homungus: how would that help the OP?
Comment: @LéoLam: I thought he wants to highlight a visited/opened link, doesnt he? thats what the style-pseudo `a:visited` does.
Comment: `a:visited` would end up highlighting all links, if the user clicked (that means visited) all links.
Comment: no it is not what i want. a:visited change color visited link but i want change color opened link (specific color must stay while link is open)
Comment: So what about `.nav1.active { //css color change }`?
Comment: gbishop3: it is not working without JS and with JS is problem with back/ refresh button.
Comment: ah ok you just want to highlight LAST clicked anchor. ok. Does the document-ready event occur if user hits back-button? anyone knows that?
Answer: You'll want to listen for hash change events (window.onhashchange), and change the active link accordingly.
Here's an example:
function locationHashChanged() {
    $('.nav1').removeClass('active'); // remove the active class from all elements
    $('.nav1[href="' + location.hash + '"]').addClass('active'); // add the active class to the element whose href equals the new fragment identifier ("hashtag")
}

window.onhashchange = locationHashChanged; // listen for hash change event
locationHashChanged(); // add the active class to the appropriate link on initial page load

Then, in your CSS, you'll add a rule for the list items who have the .active class.
Want to try it? There you go.
Note that the history API is available and allows for clean, nice URLs. Why not use it? Using fragment identifiers is outdated and not nice for those who happen to have JS disabled.
If you really want to use the history API and are worried about browser support, you can use history.js, which makes using the history API possible even with browsers that don't support it. For more info, please see the repository.
Comment: @Fakt7: has this helped you? Just wanted to know if this helped you or not, and if not, I'll try to improve the answer.
Comment: @Fakt7: I've edited the code, so it now adds the active class to the appropriate link on initial page load. I've also added a live example.
Answer: Try cookies or localStorage, where you can write the link on click and read it on page load. There are several jQuery plugins for this, like Storage API.
Comment: local storage/ session storage resolve refresh button problem.HistoryAPI  resolve back button problem  but it is not good idea. There is bad browsers support.
Comment: Because HTTP is state-less, I'm affraid for refresh some kind of storage you will need no matter what. And for Back I'm having some obscure ideas, like set a timer and check some attribs, like scroll position or visibility/display (to figure out what link should be highlighted)... - but of course it's a nasty and quite inefficient approach.
Comment: OK i found another one problem so i must use HistoryAPI. but how to do it. I tried window.history.back(); but without result
Comment: Invoke it by history.pushState(state_data_JSON, pageTitle, pageURL); and catch by window.addEventListener("popstate", function(e) {}); For "back" it should be possible to use window.history.back(); or window.history.go(-1); You can find an example on http://diveintohtml5.info/history.html
Comment: @Fakt7: I've updated my answer to mention a solution based on the history API for browsers that don't support it.
Comment: @Fakt7: If you want to use the history API but are having with it, it would be better to ask another question.
Comment: i created new question here http://stackoverflow.com/questions/23252490/how-to-use-historyapi-or-history-js-to-remain-previous-active-link-color-on-refr

Highlight active (opened) link


How to overwrite the css properties inherited by parent tag in child tag

Question: I have  a bootstrap element card and I have divided that card body into 3 parts(divs). Now in the last div I want the area to be covered with background -color. But I am unable to do it because of card-body class which has inbuilt feature of padding:1.25rem;
Code is as follows.

This is some text within a card body.

€7890

Comment: your last div is empty so background color can't set
Answer:

This is some text within a card body.

€7890

test

look this


Getting error EPERM: operation not permitted, symlink ... in nodejs amplify pull

Question: I've got this error while running amplify env pull <my_env_name>
A workaround with run command with admin rights works, but I want to run commands without admin rights.
Answer: We need to add permissions to create links for the concrete user or for all authenticated users and reboot the machine (maybe logoff/logon enough)example
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Is Every Sequentially Compact, First Countable Space Also Compact?

Question: I want to know if sequential compactness in first countable space implies compactness. I know the implication is correct in metric space (a proof that uses Lebesgue number), but I cannot mimic a proof in a general first countable space.
Or perhaps we cannot get compactness when we only have sequential compactness, but only countable compactness or Lindelof?
Answer: Firstly, sequential compactness is stronger than countable compactness, and spaces like $[0,1]^\mathbb{R}$ (in the product topology) are compact (so countably compact as well) but not sequentially compact. And certainly sequences behave better in first countable spaces, because closures and continuity can be characterised using sequences, just as in the metric case.
But the hypothesis is false: the classical example is to take the $[0,\omega_1)$, all ordinals below the first uncountable ordinal $\omega_1$, in the order topology. This is first countable (it's locally metrisable, even), sequentially compact and countably compact, but not compact. This settles the sequentially compact (and countably compact) case.
Lindelöf doesn't help at all to get compactness, even in metric spaces (reals, etc.), so I don't understand the last remark.
What is true, is that for first countable spaces, $X$ sequentially compact iff $X$ countably compact (see e.g. here) but we cannot go beyond countably compact. The Lindelöf part of compactness has to be assumed as well, one could say.
It can be interesting to find weaker conditions than Lindelöf, so find conditions "P" such that for $X$ that are first countable and sequentially compact: $X$ has "P" iff $X$ is compact. Of course, taking "P" as Lindelöf works, but maybe weaker ones will also work? Maybe weaker covering properties?
Comment: This one works: $T_1$ plus every well-ordered, increasing open cover $\mathscr{U}$ of $X$ of regular uncountable cofinality has an open refinement $\mathscr{R}=\bigcup_{\xi<\lambda}\mathscr{R}_\xi$ for some $\lambda<|\mathscr{U}|$ such that for each $x\in X$ there are a $\xi\in\lambda$ and a $\mathscr{V}\in[\mathscr{U}]^{<|\mathscr{U}|}$ such that $\varnothing\ne\operatorname{st}(x,\mathscr{R}_\xi)\subseteq\bigcup\mathscr{V}$; see [this PDF](http://www.ams.org/proc/1981-081-02/S0002-9939-1981-0593480-0/S0002-9939-1981-0593480-0.pdf). I'm pretty sure that there are weaker ones as well.
Answer: Sequential compactness by itself implies countable compactness, as proven on ProofWiki.
$\pi$-Base suggests that the Open Ordinal Space $[0, \Omega)$ and the Long Line are both sequentially compact and first countable, yet neither is compact or even Lindelof.


Adding a new NOT NULL field to a table causes an error

Question: When attempting to add a new column to a table within an update hook, the error Null value not allowed: 1138 Invalid use of NULL value occurred, the definition was changed to allow NULL, and the value for existing rows was set to NULL.
function MYMODULE_update_8101() {
  Drupal::database()->schema()->addField(
    'MYMODULE_table',
    'created',
    [
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ]
  );
}

When adding the column to the database with an SQL query, using the NOT NULL restriction causes the field to have a default value of 0, and no error happens.
How can the error be fixed, and the proper schema set?
Comment: have you tried `'null' => FALSE,` by removing `'not null' => TRUE,`
Comment: Having the `'not null'` restriction is a valuable and required attribute of the column and simply removing it does not actually fix the problem, it just masks the error.  There's a similar reason for not providing a `'default'` attribute.  Using `'initial'` is the correct approach, but unfortunately not very discoverable from searching based on the error message.
Answer: If the field spec sets 'not null' => TRUE but does not define a default value, the column is created allowing null values and later altered to disallow them (see the mysql driver Schema::addField(), and the $fixnull variable).  The second query attempting add the restriction fails, causing the error.
To fix the error, either

An 'initial' value needs to be added to the spec provided to addField()
Drupal::database()->schema()->addField(
  'MYMODULE_table',
  'created',
  [
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
    'initial' => 0,
  ]
)

Or a 'default' value needs to be added to the spec provided to addField().
When providing a default value, the spec in hook_schema() should also be changed to match.
Comment: I think what I suggested it is worked :)


How can I create a custom calculator on a drupal site?

Question: What I want to do is have a page that collects a few pieces of information from the user and then calculates a result of a formula.
I do not want to store the information at all, and was thinking I may need to use the PHP Input type.
Comment: I would more look into Drupal's Form API.  A quickstart guide can be found here:  http://drupal.org/node/751826
Comment: Why PHP ? Use JS to do all the math if you are not storing any of the results.
Answer: I see you've tagged this question with JavaScript, so it looks like you want to make a calculator using JavaScript.
To do this, you could make a custom module.
Create a module called calcform.
Create calcform.js
In your calcform.module you could create a custom block that has the calcform form.
You'll need to checkout: Creating modules | Block examples
<code>function calcform_form(&$form, &$form_state){
  $form['number1'] = array(
    '#type'=>'textfield',
  );
  $form['number2'] = array(
    '#type'=>'textfield',
  );
  $form['calc_button'] = array(
    '#type'=>'button',
    '#value'=>'Calculate',
  );
  return $form;
}
</code>
Then in your JavaScript:
<code>(function($){

  Drupal.calcform = {}

  Drupal.behaviors.calcform = {
    attach:function(){
      Drupal.calcform.bindEvents();
    }
  }

  Drupal.calcform.bindEvents = function(){

    $('#calc-button').click(function(e){
      // Prevent default button from submitting the form.
      e.preventDefault();
      // Do your magic here.
    });

  }

}(jQuery));
</code>
This is all very pseudo-cody, but it's the general idea.
You actually don't need to write ANY JavaScript. You could create a form submit function that does the calculations and prints out the result to the form. You can then use the $form['#ajax'] capabilities to do all the magic for you.
Drupal is amazing like that.
Comment: This is the type of information I was looking for! I assumed there would be some javascript involved, but I wasn't sure, and I had no idea how else to tag the question. Thank you.
Answer: You can do this online calculator in Drupal in several ways:
Write from scratch
For this we use plain JavaScript and, if necessary, the Drupal API itself. We add the usual form with the required fields and then, using the data entered into them by the user, we calculate using JavaScript using the given formula. If you need to send calculations to email, then you need to use PHP with the standard function mail () or SMTP or any modules to send data to email. As you know, this method requires considerable knowledge in programming.
Ready Modules
Perhaps there are several ready-made modules that allow you to make a calculation on Drupal, for example, Web Form Calculator and the like. However, they will have to be considerably refined for a specific calculator to use on your website. Obviously, this refinement will require a significant amount of time and skill.
Online services
You can choose a ready-made online designer to create a calculator and add it to the pages of the site. For example, JsCalc or uCalc. JsCalc will require some development skills to use the code. But uCalc can be used by people who do not own programming at all or do not want to waste time on development.
Order the development of a calculator
And the simplest but not cheap way, of course, is a simple calculator order from web studios and freelancers. This method is for those who have a budget for it.
In any case, I hope these lines will help novice developers to figure out which tool to create a calculator for them to choose :)


Alternatives to attrdict library for nested AttrDict

Question: My program contains a lot of configuration parameters so I was looking for a way to have them all in one place, accessible from every file in the project.
I thought about a config module which would act as an interface to a yaml file that contains the configuration parameters. One requirement I want is to be able to access the config object with attribute (dot) notation. I found the AttrDict library and wrote the following code:
import yaml
from attrdict import AttrDict

def get_cfg():
    return cfg_node

def dump(out_filepath):
    with open(out_filepath, 'w') as file:
        yaml.dump(attrdict_to_dict(cfg_node), file)

def load_yaml(filepath):
    global cfg_node
    with open(filepath, 'r') as file:
        cfg_node = dict_to_attrdict(yaml.safe_load(file))

def attrdict_to_dict(myAttrdict):
    dictionary = dict(myAttrdict)
    for k in myAttrdict:
        value = dictionary[k]
        if isinstance(value, AttrDict):
            dictionary[k] = attrdict_to_dict(value)
    return dictionary

def dict_to_attrdict(dictionary):
    myAttrdict = AttrDict()
    for k in dictionary:
        value = dictionary[k]
        if isinstance(value, dict):
            myAttrdict.__setattr__(k, attrdict_to_dict(value))
    return myAttrdict

cfg_node = AttrDict()
cfg_node.b = "value_b"
cfg_node.a = AttrDict()
cfg_node.a.b = AttrDict()
cfg_node.a.c = "nested_c"
cfg_node.a.b.e= "double_nested_e"

The problem is that this library does not allow nested AttrDict().
print(cfg_node)
 >>> {'b': 'value_b', 'a': AttrDict({})}

However if I do the following, nested assignment works but I'm forced to explicitly use the nested object which is not useful for my purpose:
cfg_node = AttrDict()
cfg_node.b = "value_b"
a =  AttrDict()
a.c = "nested_value_c"
cfg_node.a = a
print(cfg_node)
 >>> {'b': 'value_b', 'a': AttrDict({'c':'nested_value_c'})}

Answer: I've looked into the documentation of AttrDict and I'm afraid that recursive attribute access is not possible. See here:

Recursive attribute access results in a shallow copy, so recursive
assignment will fail (as you will be writing to a copy of that
dictionary):
> attr = AttrDict('foo': {})
> attr.foo.bar = 'baz'
> attr.foo
{}

They suggest using an AttrMap instead. However I've tried using it and I was getting an error right from the import. I'll look into it. *update below
For now, what you can do is define instead your custom AttrDict.
class AttrDict(dict):

    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self

if __name__ == '__main__':
    cfg_node = AttrDict()
    cfg_node.b = "value_b"
    cfg_node.a = AttrDict()
    cfg_node.a.b = AttrDict()
    cfg_node.a.c = "nested_c"
    cfg_node.a.b.e = "double_nested_e"
    print(cfg_node)
    print(cfg_node.a.b.e)

The output here is, as you needed:
{'b': 'value_b', 'a': {'b': {'e': 'double_nested_e'}, 'c': 'nested_c'}}
double_nested_e

If you are using an IDE you will also get code completion while you access the keys of AttrDict.
See also here, there are additional methods you can add to the custom class that can enhance its functionalities.
Hope this helps!
Update on the AttrMap library. I've asked about it here, I was using python 3.8 but the library contains a list[str], which is available only on python >= 3.9.
Second update on AttrMap. The creator has fixed the issue in the new version, now it supports python 3.6
Answer: Representing Configuration in Code
I like pydantic and dataclasses for such use-cases. I feel like pydantic makes it incredible clean and easy.
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel

class User(BaseModel):
    id: int
    name = 'John Doe'
    signup_ts: Optional[datetime] = None
    friends: List[int] = []

You can create the objects just like normal objects, parse it from a JSON / YAML (or anything that creates a dict). You can have validation logic and data transformations.
Attribute-like access
If it's just about making quick objects: types.SimpleNamespace:
from types import SimpleNamespace

sn = SimpleNamespace(param_a='1')
print(sn.param_a)

Answer: Checkout the module attridict, if offers what you are looking for.
It 100% allows for nested dicts.
It basically works the same
> att = attridict({'foo': {}})
> att.foo.bar = 'baz'
> att.foo
{'bar':'baz'}


How to calculate the line integral when the vector field is conservative?

Question: Calculate
$$\int_{\gamma} x^3 dx + (x^3 + y^3)dy$$
where $\gamma$ is the line $y=2-x$ from $(0, 2)$ to $(2, 0)$.
It was my understanding that if the vector field was conservative then the path doesn't matter so what I did was check if the vector field was conservative and yes it was conservative since I found a potential function to it which was:
$$f = \frac{x^4}4 + \frac{y^4}4$$
then
$$\int_{\gamma} x^3 dx + (x^3 + y^3)dy = f(2,0) - f(0, 2) = 0$$
This is wrong and the correct answer is -4.
Comment: how did you find it is conservative?
Comment: If there exists a function $f$ such that $\nabla f = \vec{F}$, then the vector field is conservative. And then I found a function $f$ which means that the vector field is conservative. Isn't that right?
Comment: what's the partial derivative of $f$with  respect to $y$?
Answer: Parametrizing the curve you get:
$$ \gamma(t)=(t,2-t) \quad \text{with} \quad t\in[0,2] \quad\text{and} \quad\,\gamma'(t)=(1,-1)$$
$$\int_{\gamma} x^3dx+(x^3+y^3)dy=\int_0^2(t^3-t^3-(2-t)^3)dt=-\int_0^2 u^3 du=-4 $$
In this case, since $ \dfrac{\partial }{\partial y}x^3\neq \dfrac{\partial }{\partial x}(x^3+y^3) $ the vector field is not conservative.
Answer: The potential $f = \frac{x^4}4 + \frac{y^4}4$ gives just a part of the given field $\mathbf{F}=(x^3,x^3+y^3)$. Indeed $\nabla f (x,y)=(x^3,y^3)$ and the remaining part
$\mathbf{F}-\nabla f (x,y)=(0,x^3)$ is not conservative because it is not irrotational: $ \frac{\partial }{\partial x}(x^3)-\frac{\partial }{\partial y}(0)\not=0$.
Hence, we may evaluate the line integral by splitting $\mathbf{F}$ in two,
$$\begin{align}\int_{\gamma} (x^3,x^3+y^3)\cdot d\mathbf{s}&=\int_{\gamma} (x^3,y^3)\cdot d\mathbf{s}+\int_{\gamma} (0,x^3)\cdot d\mathbf{s}\\
&=f(2,0) - f(0, 2) +\int_{\gamma} (0,x^3)\cdot d\mathbf{s}\\
&=4-4+\int_{2}^0 (0,t^3)\cdot (-1,1)\,dt\\
&=0+\left[\frac{t^4}{4}\right]_2^0=-4
\end{align}$$
where $\gamma(t)=(2-t,t)$ with $t\in[0,2]$.


Enviando dados com php/jquery para o mysql

Question:
Como poderia enviar os dados da tela index.php para o mysql , sendo que foi usado o javascript/jquery para fazer essa função que está sendo mostrada na imagem abaixo.
meus código estão abaixo :
O meu index

Peixaria

        <?php categoriaas(); ?>

            <input type="text" id="theinputsum">

                <button class="btn btn-lg btn-success btn-block">

                    Finalizar Pedido
                </button>

O meu processfunction:
require_once 'resfunctions.php';

if (isset($_POST['categoria'])) {
    getproductos($_POST['categoria']);
}

E outros que se eu colocar na pergunta vai ficar grande.
Fico grato desde já.
Comment: Leia sobre ajax.
Answer: Já que você já está usando jQuery, utilize a função Ajax dele (http://api.jquery.com/jquery.ajax/).
Você chama o arquivo PHP que vai inserir no MySQL, dá um retorno ao javascript e faz os demais procedimentos do javascript.
Um exemplo de utilização da função ajax
$.ajax({
  method: "POST",
  url: "some.php",
  data: $("#iDdoForm").serialize()
})
  .done(function( retorno) {
    alert( "faça as ações necessárias de acordo com o retorno" );
  });

Comment: @RodrigoSartoriJaraouch teria como me mostrar em código como fazer isso ?
Comment: Na edição do meu comentário, tem um exemplo de código, para o total entendimento do que você quer fazer você deverá ler sobre ajax.
Comment: @RodrigoSartoriJarouche o que seria esse $("#iDdoForm")
Comment: O  seletor do form(que você) vai enviar as informações, que vai ter um id, isso no html p.ex


Probability of at least one success in a series of independent, non-identical Bernoulli trials

Question: Let's say I have a set of independent Bernoulli trials each with a different probability:
$$
x_i \sim \operatorname{Bernoulli}(p_i)
$$
The number of successes (sum of x) will be distributed according to the Poisson-Binomail distribution:
$$
S = \sum_{i = 0}^n x_i \sim \operatorname{PoissonBinomial}(p)
$$
However, I am interested in the the probability that there is at least 1 success. In other words:
$$
S > 0 \sim  \cdots\text{?}
$$
Comment: $S>0$ has a distribution. $p(S>0)$ can be calculated, but does not itself have a distribution. Which are you asking?
Comment: The distribution of $1 - \sum_i (1 - p_i)$ depends on the distribution of the $p$s. If the $p$s are known exactly, then the distribution of $1 - \sum_i (1 - p_i)$ is a delta function.
Comment: S=0 means all the $x_i$ are 0, so why are you summing $1-p_i$?
Comment: Sorry, yes what I'm interested in is the distribution of $S > 0$. Thank you
Comment: S>0 is a binary event (yes, no) so the *distribution* for it is Bernoulli.
Comment: Hint: write out all of the events that would need to be considered in order to calculate the probability of s. Then see if you notice an easier way to find the probability.
Comment: Okay, so I think that the answer should be $S > 0 \sim Bernoulli(1 - \sum(1 - p))$.

I think what I'm _actually_ interested in is the distribution of $1 - \sum(1 - p)$. But of course, that's not the question that I asked.
Comment: Right, that makes sense. Thank you.
Comment: Whoops - I meant product, not sum
Answer: The probability that there is at least one success is P(S>0).
Because there can't be less than S successes and S is a discrete quantity, then: P(S>0) = 1 - P(S=0)
Each trial has a probability of success p_i, so it has a probability of failure (1-p_i)
P(S=0) = P(all fail)
Because the n trials are independent, then P(all fail) = P(trial 1 fails) * ... * P(trial n fails)
And those are the (1-p_i), so:
P(S=0) = (1-p_1) * ... * (1-p_n)
So your answer is:
P(S>0) = 1 - (1-p_1) * ... * (1-p_n)


How to select YAML mapping keys if they contain special keys

Question: I have a big YAMl file and i need to select all top mapping keys, that have other mapping key under them. It would be great if i could done parsing with yq, but other solutions are welcome too
For example, i have yaml file
foo:
  bar:
    - "hello"
quz:
  bar:
    - "hi"
der:
  boo: true

and i need to select just foo and bar so my final yaml will look like this:
foo:
  bar:
    - "hello"
quz:
  bar:
    - "hi"

I already tried something like this, it is do nothing
test.yaml contains example above
yq eval 'select(.[] | has("bar"))' test.yml
yq eval 'select(.[] | .bar != null)' test.yml

And i generally do not understand why using query without select gives me correct boolean output
yq eval '.[] | has("bar")' test.yml

true
true
false

Answer: With .[] | has("bar") you get the booleans you would use in a wrapping select expression, but you're missing that .[] destructures the outer map (to generate the booleans) while select is still applied to the whole map (as it's in the outer context).
One way to achieve what you want is using with_entries, which takes a function that is provided access to each .key and .value, but retains the outer structure:
yq 'with_entries(select(.value | has("bar")))'

Another way could be to use the pick function, which takes a list of keys to keep. Generate that list by applying your original filter, and extracting each key from the matches (while using map instead of .[] to retain the array):
yq 'pick(map(select(has("bar")) | key))'

Both output:
foo:
  bar:
    - "hello"
quz:
  bar:
    - "hi"

Tested with mikefarah/yq version v4.35.1. Note that since version v4.18.1, the eval/e command is the default, and can be omitted. (As an aside, the with_entries approach should also work as is using kislyuk/yq.)


Conical hull of two circles

Question: Let $X=A\cup B$ with $A$ and $B$ circles of radius $1$, parallels to the plane $XZ$ that lie in $(0,1,0)$ and $(0,-1,0)$ respectively.
I'm asked to characterize the $cone(X)$, the conical hull of $X$. The definition can be found here Conical Hull
I'm suggested to use polar coordinates.
I think that the solution of this problem is all the open upper semispace plus the y axis. But I don't know how to prove formally and I don't know why I am suggested to use polar coordinates. Maybe I have characterize $X$ analytically and then transform it into polar coordinates.
Answer: Answer is entire $R^3$.
Hint: Try to show that Conic hull of $X$ contains three axis X,Y and Z. Thus since Conic hull is always convex it has to contains entire space.
Comment: Is this right? I mean, how can u create any point wich the form (x,y,z) with z<0 if both A and B are over the plane z=0.
Comment: @Lecter As I understand your question you have two circles with radius $1$ parallel to paln xz and centered those two points. In this case points like $(0,1,-1)$ and $(0,-1,-1)$ living on them.  If this not what you meant then I didn't get your question.

Conical hull of two circles


Using PostgreSQL table as tumbling window persistence layer

Question: Currently, I'm storing a large amount of time-series data into the following PostgreSQL table:
create table view (
  user_id uuid,
  product_id integer,
  banner_id integer,
  campaign_id integer,
  price integer,
  created_at timestamp
);

I get around 80 million entries on this table per day and then aggregate daily into another table. I've decided to reduce my aggregation window into a smaller tumbling window, of 1 minute, aligning itself to the top of the hour. This was done to save on storage space, since this table is getting bigger and bigger.
This means that I will aggregate every 1 minute and store the results of the calculation into another table. I am, however, afraid that my constant deletions (every 1 minute) will lock the table and prevent insertions from happening. Here's the deletion query:
delete from view where created_at between '2023-01-01 13:58:00' and '2023-01-01 13:59:00'

Which I run after my aggregation one, which looks a bit like this:
select * from view where created_at between '2023-01-01 13:58:00' and '2023-01-01 13:59:00'

I have around ~900 inserts per second on the table. The tumbling window allows me to not worry about race conditions or missing any data, but I'm concerned the deletes might affect the table.
Therefore, my question is:

Is it recommended to delete daily or every hour instead of every minute?
Would creating an unlogged table help in this scenario?
Comment: Why do you think that a DELETE would lock the table for INSERT? It's not mentioned anywhere in the documentation. See also https://www.postgresql.org/docs/current/explicit-locking.html
Comment: If deletions every day don't lock it, why would deletions every minute?  But on the other hand if deletions every day don't free space to be reused, why would deletions every minute?
Answer: DELETE does not block INSERT
I don't see how a DELETE could block INSERT. Sure, it competes for general resources like RAM and I/O (like any other process on the same server). And it leads to some table (and index) bloat and work in the background for autovacuum. But no blockage.
Endless growth?

... since this table is getting bigger and bigger.

This should not happen. Whether you delete daily or every minute, deleted rows should be marked dead by autovacuum eventually, and space should be reused. After growing by some factor, depending on your autovacuum settings and write patterns, the table should stop growing further. Bigger for only daily deletes, but all the same. If your table does not stop growing, something's not right in your DB.
Partitioning
That said, your case sounds like a textbook example for range partitioning with the timestamp as partition key. Attach a new partition for every next day (ahead of time, by an automated process). Postgres will redirect entries to the partition for the current day. Drop (or detach) yesterday's partition once you are done with it.
Not only is dropping a partition hugely faster than deleting millions of rows. It also removes most work for autovacuum, keeps storage to a minimum (no bloat in table or indexes), and keeps inserted rows in physical storage order (which typically helps performance of aggregating data). All earlier points (including your question, really) become irrelevant.
There are detailed instructions for Partition Maintenance in the manual.
Unless there is more going on, that would stand against it, switch to a partitioned table at your earliest opportunity.
Unlogged?

Would creating an unlogged table help in this scenario?

Sure. Not writing to WAL saves a lot of I/O and storage. But you buy that at the risk of data loss. The manual:

However, they are not crash-safe: an unlogged table is automatically
truncated after a crash or unclean shutdown. The contents of an
unlogged table are also not replicated to standby servers.

Asides
Don't name a table "view". (Probably just obfuscating the real name here.)
Don't use BETWEEN for timestamps. See:

Selecting records between two timestamps
Don't use BETWEEN (especially with timestamps)
Comment: @vinnylinux: Certainly.
Comment: @vinnylinux: Yes. But [the manual](https://www.postgresql.org/docs/current/ddl-partitioning.html#DDL-PARTITIONING-DECLARATIVE-MAINTENANCE) also mentions that the operation is very quick. Only updates meta-data in some system catalogs. We are talking milliseconds. If that's still too long / too disruptive, use [`ALTER TABLE ... DETACH PARTITION ... CONCURRENTLY`](https://www.postgresql.org/docs/current/sql-altertable.html#SQL-ALTERTABLE-DETACH-PARTITION), which only takes a `SHARE UPDATE EXCLUSIVE` lock on the parent table that does not block `INSERT`.
Comment: Would the partition also work well with a smaller time frame, such as hourly?
Comment: The manual states: Note however that the above command requires taking an ACCESS EXCLUSIVE lock on the parent table.

Does this mean that deleting a partition locks the table to new inserts?


How to write a vector into several columns of the same row of a data table?

Question: I have an empty data table and want to write a pre-defined vector of numeric data into a subset of columns of the data table (all in the same row). Here an example:
require(data.table)
mydf <- data.table(matrix(0, nrow = 13, ncol = 15))
input <- seq(2.22, 14.22, by = 1)
set(mydf, 3L, 2L:14L, input)
# Trying another form of writing into the data table
mydf[3, 2:14] <- input

This returns the error:
Error in set(mydf, 3L, 2L:14L, input) : Supplied 13 items to be assigned to 1 items of column 'V2'. If you wish to 'recycle' the RHS please use rep() to make this intent clear to readers of your code.
I cannot manually write in every element as in my actual problem this command is in an apply function where the input vector size differs and the number of columns to write the vector in differs in the same manner. How can I write the vector in columns 2 to 14 of row 3?
Answer: Use as.list
library(data.table)
mydf[3, 2:14 := as.list(input)]
mydf

#   V1   V2   V3   V4   V5   V6   V7   V8   V9   V10   V11   V12   V13   V14 V15
#1:  0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00  0.00  0.00  0.00  0.00  0.00   0
#2:  0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00  0.00  0.00  0.00  0.00  0.00   0
#3:  0 2.22 3.22 4.22 5.22 6.22 7.22 8.22 9.22 10.22 11.22 12.22 13.22 14.22   0
#4:  0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00  0.00  0.00  0.00  0.00  0.00   0
#5:  0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00  0.00  0.00  0.00  0.00  0.00   0
#....

This will also work with set
set(mydf, 3L, 2L:14L, as.list(input))


Como executar o método somente após término da função anterior

Question: Tenho o código abaixo, porém o método showVideo() é executado e segue a execução ao mesmo tempo do código abaixo dele, sem esperar o showVideo() terminar, o que ocorre é devido a execução simultânea o valor setado no storage não fica correto.
buscaBonus() {

     this.servicoGeral.showVideo(); //esse metodo chama o `addTempo()` que por
     sua vez chama um localStorage.setItem para setar o tempo ganho, e o código
     abaixo recupera esse valor para mostrar em tela. Só deveria executar o
     código abaixo após o `showVideo()`.

     if (localStorage.getItem("segundos") == undefined) {
       this.totalBonus = localStorage.getItem("segundos");
     }

     let alert = this.alertCtrl.create({
      title: 'Você ganhou 5 segundos de bônus!',
      message: 'Poderá utilizar e até acumular para jogar qualquer fase.',
      buttons: [
        {
          text: 'Entendi ',
          handler: () => {
            return true;
          }
        }
      ],
      enableBackdropDismiss: false
      });
      alert.present();
    }

     showvideo(): Promise<boolean>{
        const rewardVideoConfig: AdMobFreeRewardVideoConfig = {
          id: 'ca-app-pub-1390341047819209/6782590495',
          isTesting: true,
          autoShow: true
        }

        this.admobFree.rewardVideo.config(rewardVideoConfig);
        return new Promise<boolean>((resolve) => {

          rewardVideoClose = this.admobFree.on(this.admobFree.events.REWARD_VIDEO_CLOSE).subscribe(() => {

          });
          rewardVideoReward = this.admobFree.on(this.admobFree.events.REWARD_VIDEO_REWARD).subscribe(() => {
            this.addTempo();
            rewardVideoReward.unsubscribe();
          });

          this.admobFree.rewardVideo.prepare()
            .then(() => { })
            .catch(() => {
              loading.dismiss();
              resolve(false);
            });
        });
     }
      addTempo() {
         if (localStorage.getItem("segundos") == null) {
           this.tempoSegundos = 5
         } else {
           let tempo = localStorage.getItem("segundos");
           this.tempoSegundos = (parseInt(tempo) + 5)
         }
         let tempo: string;
         tempo = this.tempoSegundos.toString()
         localStorage.setItem('segundos', tempo);
     }

Answer: Qual seria a a primeira função que executa?
Tentar chamar o this.addTempo()como nesse exemplo, usando um callback.
funcao() {
  let loader = this._loaderCtrl.create();
  loader
    .present()
        .then(() => {
           .subscribe(
              () => {
              let toast = this._toastCtrl.create({
                message: "mensagem",
                duration: 3000
              });
              toast.onDidDismiss(() => {
                this.addTempo()
              });
          toast.present();
        loader.dismiss();
 }

Exemplo com loading:
loader.dismiss(()=>{
    this.addTempo()
 });

Comment: Essa função deve ser observable? estou tentando utilizar seu código para fazer um teste e ocorre erro no subscribe.
Comment: Tentar usar sem o subscribe mesmo, foi apenas um exemplo.
Comment: Acho que meu problema está antes então, pois eu tenho um método que chama esse
showVideo:
 buscaBonus() {
    this.servicoGeral.showVideo();
    //NESSE MOMENTO ANTES DE TERMINAR A FUNÇÃO ACIMA JÁ EXECUTA O CÓDIGO ABAIXO

      this.totalBonus = localStorage.getItem("segundos");

//E CONSEQUENTEMENTE AINDA NÃO TEM VALOR GRAVADO NO STORAGE
  }
Comment: Queria formatar o código acima, mas não consegui
Comment: Consegue editar e colocar no post? talvez fique melhor de entender
Comment: feito, acho que mudou até o problema agora, refiz toda a pergunta.
Comment: `this.admobFree.rewardVideo.prepare()
            .then(() => {this.addTempo })
            .catch(() => {
              loading.dismiss();
              resolve(false);
            });`
Comment: não funciona amigo
Comment: chamando no prepare o vídeo não foi assistido ainda e não deveria passar pelo `addTempo()`, o certo seria nesse evento `REWARD_VIDEO_REWARD`, mas já fiz com promisse e as funções são executadas uma atras da outra não esperando o término da primeira. Já tentei várias formas.
Answer: Pode criar uma barreira, mesmo método utilizado em requisições assíncronas, da uma olhada, talvez possa te ajudar.
var simpleBarrier = require('simple-barrier'),
fs = require('fs');

// create a barrier instance
var barrier = simpleBarrier();

// load some files, let the barrier handle the callbacks:
fs.readFile('foo.txt', barrier.waitOn());
fs.readFile('bar.txt', barrier.waitOn());
fs.readFile('baz.txt', barrier.waitOn());

// add a callback for when all files are loaded
barrier.endWith(function( results ){

   // Results is an array of the values given by fs.readFile
   // the array is in the order that barrier.waitOn() was called, regardless of the
   // order they were loaded in
   console.log('foo, bar, and baz are:', results.join('\n'));
});

Fonte: https://github.com/jimhigson/simple-barrier
Comment: O ideal é trazer as informações importantes dos links para a respostas considerando que elas podem ser alteradas/excluídas na fonte, o que vai acabar deixando um vácuo na sua resposta. Claro que o link permanece como referência.
Comment: Agradeço a ajuda amigo, mas ainda não consegui resolver o meu problema, infelizmente, fiz de várias formas para barras o processamento e mesmo assim nada adiantou.


Why Im getting this error identifier 'procedure' must be declared Oracle PL/SQL

Question: UPDATED: thanks to @littlefoot I got it running, but now I have another problem, it gets me negative numbers and the end in the field "Balance final" when it should said 0, here's the result so you can see what I mean. Hopefully with the full code below somebody can spot where the error is because I could not see it myself.
UPDATED: I found the issue, it was the order of parameters in the function, it was monto NUMBER, plazo NUMBER, tasa FLOAT when it should be monto NUMBER, tasa FLOAT, plazo NUMBER
Thanks to everybody for helping me out!
<code>User created.

Grant succeeded.

Grant succeeded.

Grant succeeded.

Connected.

Table created.

Table created.

Sequence created.

Function created.

Procedure created.

Enter value for prestamo: 2000000
Enter value for tasa: 12
Enter value for tiempo_en_a±os: 15
Enter value for fecha: 26/jul/19
Enter value for pago_extraordinario: 0
old   2:      amortizacion_proc(&prestamo,&tasa,&tiempo_en_a±os,'&fecha',&Pago_extraordinario);
new   2:      amortizacion_proc(2000000,12,15,'26/jul/19',0);
$30,017.54
ID PrÚstamo: 1

Monto:  $2,000,000.00

Tasa :12%

Plazo :15 A±os

Fecha Prestamo: 06-AGO-20

Fecha Saldo: 06-AGO-35

Pago Extra:         $.00

Cuota Mensual:   $30,017.54

PL/SQL procedure successfully completed.

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
         1 26-AGO-19  2,000,000.00      30017.54          0   30017.54   10017.53      20000    1989982.46
         2 26-SEP-19  1,989,982.46      30017.54          0   30017.54   10117.71   19899.82    1979864.75
         3 26-OCT-19  1,979,864.75      30017.54          0   30017.54   10218.88   19798.64    1969645.86
         4 26-NOV-19  1,969,645.86      30017.54          0   30017.54   10321.07   19696.45    1959324.78
         5 26-DIC-19  1,959,324.78      30017.54          0   30017.54   10424.28   19593.24     1948900.5
         6 26-ENE-20  1,948,900.50      30017.54          0   30017.54   10528.53      19489    1938371.97
         7 26-FEB-20  1,938,371.97      30017.54          0   30017.54   10633.81   19383.71    1927738.15
         8 26-MAR-20  1,927,738.15      30017.54          0   30017.54   10740.15   19277.38       1916998
         9 26-ABR-20  1,916,998.00      30017.54          0   30017.54   10847.55   19169.98    1906150.44
        10 26-MAY-20  1,906,150.44      30017.54          0   30017.54   10956.03    19061.5    1895194.41
        11 26-JUN-20  1,895,194.41      30017.54          0   30017.54   11065.59   18951.94    1884128.82

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
        12 26-JUL-20  1,884,128.82      30017.54          0   30017.54   11176.24   18841.28    1872952.57
        13 26-AGO-20  1,872,952.57      30017.54          0   30017.54      11288   18729.52    1861664.56
        14 26-SEP-20  1,861,664.56      30017.54          0   30017.54   11400.88   18616.64    1850263.67
        15 26-OCT-20  1,850,263.67      30017.54          0   30017.54   11514.89   18502.63    1838748.78
        16 26-NOV-20  1,838,748.78      30017.54          0   30017.54   11630.04   18387.48    1827118.73
        17 26-DIC-20  1,827,118.73      30017.54          0   30017.54   11746.34   18271.18    1815372.38
        18 26-ENE-21  1,815,372.38      30017.54          0   30017.54   11863.81   18153.72    1803508.57
        19 26-FEB-21  1,803,508.57      30017.54          0   30017.54   11982.44   18035.08    1791526.12
        20 26-MAR-21  1,791,526.12      30017.54          0   30017.54   12102.27   17915.26    1779423.84
        21 26-ABR-21  1,779,423.84      30017.54          0   30017.54   12223.29   17794.23    1767200.55
        22 26-MAY-21  1,767,200.55      30017.54          0   30017.54   12345.52      17672    1754855.02

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
        23 26-JUN-21  1,754,855.02      30017.54          0   30017.54   12468.98   17548.55    1742386.03
        24 26-JUL-21  1,742,386.03      30017.54          0   30017.54   12593.67   17423.86    1729792.36
        25 26-AGO-21  1,729,792.36      30017.54          0   30017.54   12719.61   17297.92    1717072.75
        26 26-SEP-21  1,717,072.75      30017.54          0   30017.54    12846.8   17170.72    1704225.94
        27 26-OCT-21  1,704,225.94      30017.54          0   30017.54   12975.27   17042.25    1691250.66
        28 26-NOV-21  1,691,250.66      30017.54          0   30017.54   13105.02    16912.5    1678145.63
        29 26-DIC-21  1,678,145.63      30017.54          0   30017.54   13236.07   16781.45    1664909.56
        30 26-ENE-22  1,664,909.56      30017.54          0   30017.54   13368.43   16649.09    1651541.12
        31 26-FEB-22  1,651,541.12      30017.54          0   30017.54   13502.12   16515.41    1638038.99
        32 26-MAR-22  1,638,038.99      30017.54          0   30017.54   13637.14   16380.38    1624401.85
        33 26-ABR-22  1,624,401.85      30017.54          0   30017.54   13773.51   16244.01    1610628.33

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
        34 26-MAY-22  1,610,628.33      30017.54          0   30017.54   13911.25   16106.28    1596717.08
        35 26-JUN-22  1,596,717.08      30017.54          0   30017.54   14050.36   15967.17    1582666.71
        36 26-JUL-22  1,582,666.71      30017.54          0   30017.54   14190.86   15826.66    1568475.84
        37 26-AGO-22  1,568,475.84      30017.54          0   30017.54   14332.77   15684.75    1554143.07
        38 26-SEP-22  1,554,143.07      30017.54          0   30017.54    14476.1   15541.43    1539666.96
        39 26-OCT-22  1,539,666.96      30017.54          0   30017.54   14620.86   15396.66     1525046.1
        40 26-NOV-22  1,525,046.10      30017.54          0   30017.54   14767.07   15250.46    1510279.02
        41 26-DIC-22  1,510,279.02      30017.54          0   30017.54   14914.74   15102.79    1495364.28
        42 26-ENE-23  1,495,364.28      30017.54          0   30017.54   15063.89   14953.64    1480300.39
        43 26-FEB-23  1,480,300.39      30017.54          0   30017.54   15214.53      14803    1465085.85
        44 26-MAR-23  1,465,085.85      30017.54          0   30017.54   15366.67   14650.85    1449719.18

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
        45 26-ABR-23  1,449,719.18      30017.54          0   30017.54   15520.34   14497.19    1434198.83
        46 26-MAY-23  1,434,198.83      30017.54          0   30017.54   15675.54   14341.98    1418523.29
        47 26-JUN-23  1,418,523.29      30017.54          0   30017.54    15832.3   14185.23    1402690.98
        48 26-JUL-23  1,402,690.98      30017.54          0   30017.54   15990.62    14026.9    1386700.36
        49 26-AGO-23  1,386,700.36      30017.54          0   30017.54   16150.53      13867    1370549.83
        50 26-SEP-23  1,370,549.83      30017.54          0   30017.54   16312.03   13705.49    1354237.79
        51 26-OCT-23  1,354,237.79      30017.54          0   30017.54   16475.15   13542.37    1337762.63
        52 26-NOV-23  1,337,762.63      30017.54          0   30017.54    16639.9   13377.62    1321122.72
        53 26-DIC-23  1,321,122.72      30017.54          0   30017.54    16806.3   13211.22    1304316.42
        54 26-ENE-24  1,304,316.42      30017.54          0   30017.54   16974.37   13043.16    1287342.04
        55 26-FEB-24  1,287,342.04      30017.54          0   30017.54   17144.11   12873.42    1270197.93

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
        56 26-MAR-24  1,270,197.93      30017.54          0   30017.54   17315.55   12701.97    1252882.37
        57 26-ABR-24  1,252,882.37      30017.54          0   30017.54   17488.71   12528.82    1235393.66
        58 26-MAY-24  1,235,393.66      30017.54          0   30017.54   17663.59   12353.93    1217730.06
        59 26-JUN-24  1,217,730.06      30017.54          0   30017.54   17840.23    12177.3    1199889.83
        60 26-JUL-24  1,199,889.83      30017.54          0   30017.54   18018.63   11998.89    1181871.19
        61 26-AGO-24  1,181,871.19      30017.54          0   30017.54   18198.82   11818.71    1163672.37
        62 26-SEP-24  1,163,672.37      30017.54          0   30017.54   18380.81   11636.72    1145291.56
        63 26-OCT-24  1,145,291.56      30017.54          0   30017.54   18564.61   11452.91    1126726.94
        64 26-NOV-24  1,126,726.94      30017.54          0   30017.54   18750.26   11267.26    1107976.67
        65 26-DIC-24  1,107,976.67      30017.54          0   30017.54   18937.76   11079.76     1089038.9
        66 26-ENE-25  1,089,038.90      30017.54          0   30017.54   19127.14   10890.38    1069911.76

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
        67 26-FEB-25  1,069,911.76      30017.54          0   30017.54   19318.41   10699.11    1050593.34
        68 26-MAR-25  1,050,593.34      30017.54          0   30017.54    19511.6   10505.93    1031081.74
        69 26-ABR-25  1,031,081.74      30017.54          0   30017.54   19706.71   10310.81    1011375.02
        70 26-MAY-25  1,011,375.02      30017.54          0   30017.54   19903.78   10113.75     991471.23
        71 26-JUN-25    991,471.23      30017.54          0   30017.54   20102.82    9914.71     971368.41
        72 26-JUL-25    971,368.41      30017.54          0   30017.54   20303.85    9713.68     951064.56
        73 26-AGO-25    951,064.56      30017.54          0   30017.54   20506.88    9510.64     930557.67
        74 26-SEP-25    930,557.67      30017.54          0   30017.54   20711.95    9305.57     909845.71
        75 26-OCT-25    909,845.71      30017.54          0   30017.54   20919.07    9098.45     888926.63
        76 26-NOV-25    888,926.63      30017.54          0   30017.54   21128.26    8889.26     867798.36
        77 26-DIC-25    867,798.36      30017.54          0   30017.54   21339.55    8677.98     846458.81

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
        78 26-ENE-26    846,458.81      30017.54          0   30017.54   21552.94    8464.58     824905.87
        79 26-FEB-26    824,905.87      30017.54          0   30017.54   21768.47    8249.05     803137.39
        80 26-MAR-26    803,137.39      30017.54          0   30017.54   21986.16    8031.37     781151.23
        81 26-ABR-26    781,151.23      30017.54          0   30017.54   22206.02    7811.51     758945.21
        82 26-MAY-26    758,945.21      30017.54          0   30017.54   22428.08    7589.45     736517.12
        83 26-JUN-26    736,517.12      30017.54          0   30017.54   22652.36    7365.17     713864.76
        84 26-JUL-26    713,864.76      30017.54          0   30017.54   22878.88    7138.64     690985.87
        85 26-AGO-26    690,985.87      30017.54          0   30017.54   23107.67    6909.85     667878.19
        86 26-SEP-26    667,878.19      30017.54          0   30017.54   23338.75    6678.78     644539.44
        87 26-OCT-26    644,539.44      30017.54          0   30017.54   23572.14    6445.39      620967.3
        88 26-NOV-26    620,967.30      30017.54          0   30017.54   23807.86    6209.67     597159.44

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
        89 26-DIC-26    597,159.44      30017.54          0   30017.54   24045.94    5971.59      573113.5
        90 26-ENE-27    573,113.50      30017.54          0   30017.54    24286.4    5731.13      548827.1
        91 26-FEB-27    548,827.10      30017.54          0   30017.54   24529.26    5488.27     524297.83
        92 26-MAR-27    524,297.83      30017.54          0   30017.54   24774.55    5242.97     499523.27
        93 26-ABR-27    499,523.27      30017.54          0   30017.54    25022.3    4995.23     474500.97
        94 26-MAY-27    474,500.97      30017.54          0   30017.54   25272.52       4745     449228.45
        95 26-JUN-27    449,228.45      30017.54          0   30017.54   25525.25    4492.28      423703.2
        96 26-JUL-27    423,703.20      30017.54          0   30017.54    25780.5    4237.03     397922.69
        97 26-AGO-27    397,922.69      30017.54          0   30017.54    26038.3    3979.22     371884.38
        98 26-SEP-27    371,884.38      30017.54          0   30017.54   26298.69    3718.84     345585.69
        99 26-OCT-27    345,585.69      30017.54          0   30017.54   26561.67    3455.85     319024.01

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
       100 26-NOV-27    319,024.01      30017.54          0   30017.54   26827.29    3190.24     292196.72
       101 26-DIC-27    292,196.72      30017.54          0   30017.54   27095.56    2921.96     265101.15
       102 26-ENE-28    265,101.15      30017.54          0   30017.54   27366.52    2651.01     237734.63
       103 26-FEB-28    237,734.63      30017.54          0   30017.54   27640.18    2377.34     210094.44
       104 26-MAR-28    210,094.44      30017.54          0   30017.54   27916.59    2100.94     182177.85
       105 26-ABR-28    182,177.85      30017.54          0   30017.54   28195.75    1821.77     153982.09
       106 26-MAY-28    153,982.09      30017.54          0   30017.54   28477.71    1539.82     125504.38
       107 26-JUN-28    125,504.38      30017.54          0   30017.54   28762.49    1255.04      96741.88
       108 26-JUL-28     96,741.88      30017.54          0   30017.54   29050.11     967.41      67691.77
       109 26-AGO-28     67,691.77      30017.54          0   30017.54   29340.61     676.91      38351.15
       110 26-SEP-28     38,351.15      30017.54          0   30017.54   29634.02     383.51       8717.13

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
       111 26-OCT-28      8,717.13      30017.54          0   30017.54   29930.36      87.17     -21213.23
       112 26-NOV-28    -21,213.23      30017.54          0   30017.54   30229.66    -212.13     -51442.89
       113 26-DIC-28    -51,442.89      30017.54          0   30017.54   30531.96    -514.42     -81974.86
       114 26-ENE-29    -81,974.86      30017.54          0   30017.54   30837.28    -819.74    -112812.14
       115 26-FEB-29   -112,812.14      30017.54          0   30017.54   31145.65   -1128.12     -143957.8
       116 26-MAR-29   -143,957.80      30017.54          0   30017.54   31457.11   -1439.57    -175414.91
       117 26-ABR-29   -175,414.91      30017.54          0   30017.54   31771.68   -1754.14     -207186.6
       118 26-MAY-29   -207,186.60      30017.54          0   30017.54    32089.4   -2071.86       -239276
       119 26-JUN-29   -239,276.00      30017.54          0   30017.54   32410.29   -2392.76    -271686.29
       120 26-JUL-29   -271,686.29      30017.54          0   30017.54   32734.39   -2716.86    -304420.69
       121 26-AGO-29   -304,420.69      30017.54          0   30017.54   33061.74    -3044.2    -337482.43

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
       122 26-SEP-29   -337,482.43      30017.54          0   30017.54   33392.35   -3374.82    -370874.79
       123 26-OCT-29   -370,874.79      30017.54          0   30017.54   33726.28   -3708.74    -404601.08
       124 26-NOV-29   -404,601.08      30017.54          0   30017.54   34063.54   -4046.01    -438664.62
       125 26-DIC-29   -438,664.62      30017.54          0   30017.54   34404.18   -4386.64    -473068.81
       126 26-ENE-30   -473,068.81      30017.54          0   30017.54   34748.22   -4730.68    -507817.03
       127 26-FEB-30   -507,817.03      30017.54          0   30017.54    35095.7   -5078.17    -542912.73
       128 26-MAR-30   -542,912.73      30017.54          0   30017.54   35446.66   -5429.12     -578359.4
       129 26-ABR-30   -578,359.40      30017.54          0   30017.54   35801.12   -5783.59    -614160.53
       130 26-MAY-30   -614,160.53      30017.54          0   30017.54   36159.14    -6141.6    -650319.67
       131 26-JUN-30   -650,319.67      30017.54          0   30017.54   36520.73   -6503.19     -686840.4
       132 26-JUL-30   -686,840.40      30017.54          0   30017.54   36885.93    -6868.4    -723726.34

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
       133 26-AGO-30   -723,726.34      30017.54          0   30017.54   37254.79   -7237.26    -760981.14
       134 26-SEP-30   -760,981.14      30017.54          0   30017.54   37627.34   -7609.81    -798608.48
       135 26-OCT-30   -798,608.48      30017.54          0   30017.54   38003.62   -7986.08     -836612.1
       136 26-NOV-30   -836,612.10      30017.54          0   30017.54   38383.65   -8366.12    -874995.76
       137 26-DIC-30   -874,995.76      30017.54          0   30017.54   38767.49   -8749.95    -913763.25
       138 26-ENE-31   -913,763.25      30017.54          0   30017.54   39155.16   -9137.63    -952918.42
       139 26-FEB-31   -952,918.42      30017.54          0   30017.54   39546.71   -9529.18    -992465.14
       140 26-MAR-31   -992,465.14      30017.54          0   30017.54   39942.18   -9924.65    -1032407.3
       141 26-ABR-31 -1,032,407.33      30017.54          0   30017.54    40341.6  -10324.07    -1072748.9
       142 26-MAY-31 -1,072,748.94      30017.54          0   30017.54   40745.02  -10727.48      -1113494
       143 26-JUN-31 -1,113,493.96      30017.54          0   30017.54   41152.47  -11134.93    -1154646.4

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
       144 26-JUL-31 -1,154,646.44      30017.54          0   30017.54   41563.99  -11546.46    -1196210.4
       145 26-AGO-31 -1,196,210.44      30017.54          0   30017.54   41979.63   -11962.1    -1238190.1
       146 26-SEP-31 -1,238,190.08      30017.54          0   30017.54   42399.43   -12381.9    -1280589.5
       147 26-OCT-31 -1,280,589.51      30017.54          0   30017.54   42823.43  -12805.89    -1323412.9
       148 26-NOV-31 -1,323,412.94      30017.54          0   30017.54   43251.66  -13234.12    -1366664.6
       149 26-DIC-31 -1,366,664.61      30017.54          0   30017.54   43684.18  -13666.64    -1410348.8
       150 26-ENE-32 -1,410,348.79      30017.54          0   30017.54   44121.02  -14103.48    -1454469.8
       151 26-FEB-32 -1,454,469.81      30017.54          0   30017.54   44562.23  -14544.69    -1499032.1
       152 26-MAR-32 -1,499,032.05      30017.54          0   30017.54   45007.85  -14990.32    -1544039.9
       153 26-ABR-32 -1,544,039.90      30017.54          0   30017.54   45457.93  -15440.39    -1589497.8
       154 26-MAY-32 -1,589,497.84      30017.54          0   30017.54   45912.51  -15894.97    -1635410.4

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
       155 26-JUN-32 -1,635,410.35      30017.54          0   30017.54   46371.63   -16354.1      -1681782
       156 26-JUL-32 -1,681,781.99      30017.54          0   30017.54   46835.35  -16817.81    -1728617.3
       157 26-AGO-32 -1,728,617.34      30017.54          0   30017.54    47303.7  -17286.17    -1775921.1
       158 26-SEP-32 -1,775,921.05      30017.54          0   30017.54   47776.74  -17759.21    -1823697.8
       159 26-OCT-32 -1,823,697.80      30017.54          0   30017.54   48254.51  -18236.97    -1871952.3
       160 26-NOV-32 -1,871,952.31      30017.54          0   30017.54   48737.05  -18719.52    -1920689.4
       161 26-DIC-32 -1,920,689.37      30017.54          0   30017.54   49224.42  -19206.89    -1969913.8
       162 26-ENE-33 -1,969,913.80      30017.54          0   30017.54   49716.67  -19699.13    -2019630.5
       163 26-FEB-33 -2,019,630.47      30017.54          0   30017.54   50213.84   -20196.3    -2069844.3
       164 26-MAR-33 -2,069,844.31      30017.54          0   30017.54   50715.97  -20698.44    -2120560.3
       165 26-ABR-33 -2,120,560.29      30017.54          0   30017.54   51223.13   -21205.6    -2171783.4

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
       166 26-MAY-33 -2,171,783.43      30017.54          0   30017.54   51735.36  -21717.83    -2223518.8
       167 26-JUN-33 -2,223,518.80      30017.54          0   30017.54   52252.72  -22235.18    -2275771.5
       168 26-JUL-33 -2,275,771.52      30017.54          0   30017.54   52775.25  -22757.71    -2328546.8
       169 26-AGO-33 -2,328,546.77      30017.54          0   30017.54      53303  -23285.46    -2381849.8
       170 26-SEP-33 -2,381,849.78      30017.54          0   30017.54   53836.03  -23818.49    -2435685.8
       171 26-OCT-33 -2,435,685.81      30017.54          0   30017.54   54374.39  -24356.85    -2490060.2
       172 26-NOV-33 -2,490,060.20      30017.54          0   30017.54   54918.13   -24900.6    -2544978.3
       173 26-DIC-33 -2,544,978.34      30017.54          0   30017.54   55467.31  -25449.78    -2600445.7
       174 26-ENE-34 -2,600,445.66      30017.54          0   30017.54   56021.99  -26004.45    -2656467.7
       175 26-FEB-34 -2,656,467.65      30017.54          0   30017.54   56582.21  -26564.67    -2713049.9
       176 26-MAR-34 -2,713,049.86      30017.54          0   30017.54   57148.03  -27130.49    -2770197.9

     PmtNo Fecha     Balance Inici Cuota a pagar Pago extra Total pago    Capital  Intereses Balance Final
---------- --------- ------------- ------------- ---------- ---------- ---------- ---------- -------------
       177 26-ABR-34 -2,770,197.90      30017.54          0   30017.54   57719.51  -27701.97    -2827917.4
       178 26-MAY-34 -2,827,917.41      30017.54          0   30017.54    58296.7  -28279.17    -2886214.1
       179 26-JUN-34 -2,886,214.12      30017.54          0   30017.54   58879.67  -28862.14    -2945093.8
       180 26-JUL-34 -2,945,093.80      30017.54          0   30017.54   59468.47  -29450.93    -3004562.3

180 rows selected.

</code>
The entire code is this
<code>--PASO 1, crear el usuario y asignar roles y privilegios

DROP USER amortiz CASCADE;
CREATE USER amortiz IDENTIFIED BY "amortiz";
GRANT CONNECT TO amortiz;
GRANT RESOURCE TO amortiz;
GRANT UNLIMITED TABLESPACE TO amortiz;

--PASO 2, conectarse con el usuario nuevo y crear las tablas

CONNECT amortiz/amortiz;

CREATE TABLE param_amortizacion (
amortiz_id number(10),
monto number(9,2),
tasa number(5,2),
plazo number(3),
fecha_inicio date,
pago_extra number(9,2),
cuota_programada number(9,2),
CONSTRAINT param_amortiz_pk PRIMARY KEY (amortiz_id)
);

CREATE TABLE amortizacion (
ID number(6),
fecha_pago date,
balance_inicial number(9,2),
pago_extra number(9,2),
capital number(9,2),
interes number(9,2),
balance_final number(9,2),
amortiz_id number(10),
CONSTRAINT amortiz_pk PRIMARY KEY (ID),
CONSTRAINT amortiz_fk FOREIGN KEY (amortiz_id) REFERENCES param_amortizacion(amortiz_id)
);

--PASO 3 crear la secuencia

CREATE SEQUENCE amortiz_seq
START WITH 1
INCREMENT BY 1;

--PASO 4, crear la funcion calc_cuota_prog para calcular la cuota programada, parametros a introducir son monto, tasa y plazo

CREATE OR REPLACE FUNCTION calc_cuota_prog (monto NUMBER, plazo NUMBER, tasa FLOAT)
RETURN NUMBER
IS

cuota_v NUMBER;
m NUMBER;
t NUMBER;
p NUMBER;

BEGIN
m:=monto;
t:=(tasa/12)/100;
p:=plazo*12;
cuota_v:=m*((power(1+t,p)*t)/(power(1+t,p)-1));
DBMS_OUTPUT.PUT_LINE(TO_CHAR(cuota_v, '$9,999,999.99'));
RETURN cuota_v;

END;

/
--PASO 5, crear el procedure amortizacion_proc

/*
Dicho procedimiento debe hacer lo siguente:

reciba como parámetros de entrada el monto total del préstamo,
la tasa expresada en %, el plazo del préstamo expresado en años,
la fecha de inicio del préstamo y si va a realizar un pago extraordinario (0 defecto).

Esta información guárdela en la tabla param_amortizacion de parámetros del préstamo.

Guarde en la tabla amortizacion las transacciones mensuales de la amortización del préstamo hasta que se termine de pagar el préstamo en el plazo pautado.

Dentro del procedimiento muestre por pantalla los datos generales del préstamo.
*/

CREATE OR REPLACE PROCEDURE amortizacion_proc (TOTAL NUMBER,TASA NUMBER,PLAZO NUMBER,FECHA_INICIO DATE,PAGO_EXTRA NUMBER)
IS

MES NUMBER := PLAZO*12;
INTERESES NUMBER;
CAPITAL NUMBER;
INICIO NUMBER := TOTAL;
FINAL1 NUMBER;
AM_ID NUMBER;
PROMEDIO NUMBER :=calc_cuota_prog(TOTAL,TASA,PLAZO);
TASA1 number:=(TASA/12)/100;

BEGIN
INSERT INTO param_amortizacion
VALUES (amortiz_seq.NEXTVAL,TOTAL,TASA,PLAZO,TO_CHAR(fecha_inicio, 'dd-MON-RR'),pago_extra,PROMEDIO);

FOR i IN 1..MES LOOP
INTERESES := INICIO*TASA1;
CAPITAL := PROMEDIO-INTERESES;
FINAL1 := INICIO-CAPITAL-pago_extra;
SELECT amortiz_id INTO AM_ID FROM param_amortizacion WHERE ROWNUM = (SELECT MAX(ROWNUM) FROM param_amortizacion);

INSERT INTO amortizacion
VALUES (i,ADD_MONTHS(TO_CHAR(fecha_inicio,'dd-MON-RR'),i), TRUNC(INICIO,2),pago_extra, TRUNC(CAPITAL, 2), TRUNC(INTERESES, 2), TRUNC(FINAL1, 2), AM_ID);
INICIO := FINAL1;

EXIT WHEN FINAL1 = 0;
END LOOP;

--PASO 6, mostrar datos generales del prestamo dentro del procedure

           DBMS_OUTPUT.PUT_LINE('ID Préstamo: '|| AM_ID||chr(10));

           DBMS_OUTPUT.PUT_LINE('Monto: '||TO_CHAR(TOTAL,'$9,999,999.99')||chr(10));

           DBMS_OUTPUT.PUT_LINE('Tasa :' ||TASA||'%' ||chr(10));

           DBMS_OUTPUT.PUT_LINE('Plazo :' ||PLAZO||' Años' ||chr(10));

           DBMS_OUTPUT.PUT_LINE('Fecha Prestamo: '||TO_CHAR(SYSDATE, 'dd-MON-RR')|| chr(10));

           DBMS_OUTPUT.PUT_LINE('Fecha Saldo: '||ADD_MONTHS(TO_CHAR(SYSDATE, 'dd-MON-RR'),PLAZO*12)||chr(10));

           DBMS_OUTPUT.PUT_LINE('Pago Extra: '||TO_CHAR(0,'$999,999.99')||chr(10));

           DBMS_OUTPUT.PUT_LINE('Cuota Mensual: ' ||TO_CHAR(PROMEDIO,'$999,999.99')||chr(10));

END;

--PASO 7, llamar al procedure y pedir los datos por pantalla
 /
 SET SERVEROUTPUT ON
    BEGIN
     amortizacion_proc(&prestamo,&tasa,&tiempo_en_años,'&fecha',&Pago_extraordinario);
    END;
/

--PASO 8, Hacer un select para el reporte

SELECT v.id "PmtNo", v.fecha_pago "Fecha", TO_CHAR(v.balance_inicial,'9,999,999.99') "Balance Inicial ", c.cuota_programada "Cuota a pagar", c.pago_extra "Pago extra", c.cuota_programada "Total pago",v.capital "Capital",v.interes "Intereses",v.BALANCE_FINAL "Balance Final"
FROM amortizacion v INNER JOIN param_amortizacion c ON v.amortiz_id=c.amortiz_id;
</code>
Comment: Do you own that procedure?
Comment: You'll have to debug it yourself. I'm going to sleep. Good luck!
Comment: What happens if you rerun the procedure declaration?
Comment: Did you change to a new schema/database?
Comment: @Littlefoot excuse me what do you mean by that?
Comment: @DavidG.Pickett Istart the .sql file as System and then, inside the .sql file I create a new user to execute everytime with that user inside it
Comment: If you don't own it, owner should grant you EXECUTE privilege. Furthermore, you should create a SYNONYM to it, or precede procedure's name with owner's name.
Comment: I updated the post with the entire code now, hopefully somebody could see what Im doing wrong
Comment: You're missing a slash at line #58, in front of "PASO 5" comment.
Comment: @Littlefoot excuse me but I don't see it, I'm blind or something
Comment: You can't see it as it isn't there. If you're running that code as a script, it fails because function isn't terminated by a slash at line 58 so - all code that follows fails as well. Procedure that troubles you doesn't exist. Add slash.
Comment: @Littlefoot omg it runs now but I still got a problem, I got numbers in negative instead of 0 at the end, in the "Balance final" field at the end it should said 0. let me add the result to the post so you can see what I mean.
Answer: Executing a PL/SQL procedure
The following shows the syntax for executing a procedure:
EXECUTE procedure_name( arguments);
Or
EXEC procedure_name( arguments);
https://www.oracletutorial.com/plsql-tutorial/plsql-procedure/
Comment: Oracle internally converts `exec/execute procedure_name(arguments)` to `BEGIN procedure_name(arguments) END`
Answer: I found the issue, it was the order of parameters in the function, it was
monto NUMBER, plazo NUMBER, tasa FLOAT
when it should be
monto NUMBER, tasa FLOAT, plazo NUMBER
Comment: OOh, just like C++, the call signature must match!  :D
Answer: Please add on the top
<code>USE [DatabseName]
GO
</code>
Sometime we execute the query in wrong database. Pardon me if I am wrong.
Comment: You are wrong. This is Oracle. There's no USE nor GO there.


Using R's aov() for two-way repeated-measurement ANOVA

Question: We analyze blood vessel samples of patients in an organ bath which gives us force values. Each subject (patient) donates two types of blood vessels (pulmonary vein and pulmonary artery). The organ bath measurements include dose-response curves with a pharmaceutical, i.e. different concentrations are applied. From what I understand, this should be analyzed using a two-way RM ANOVA test. There are two variables (vessel type and concentration), and all levels of both are applied to each subject. The data table looks like this:
subject  vessel  conc  force
20110818 PA      -12   0
20110818 PV      -12   0
20110818 PA      -11   0.09
20110818 PV      -11   0.15
...

There are no missing values or anything like that to consider.
Perusing several R tutorials, I came up with the following query:
aov.ex2=aov(force~(vessel*conc)+Error(subject/(vessel*conc)),data=data.ex2)

However, the results are somewhat unclear to me:
> summary(aov.ex2)

Error: subject
          Df Sum Sq Mean Sq F value Pr(>F)
Residuals  1 15.370  15.370

Error: subject:vessel
       Df Sum Sq Mean Sq
vessel  1 166.72  166.72

Error: subject:concentration
              Df Sum Sq Mean Sq
concentration  1 3134.3  3134.3

Error: subject:vessel:concentration
                     Df Sum Sq Mean Sq
vessel:concentration  1 148.32  148.32

Error: Within
           Df Sum Sq Mean Sq F value Pr(>F)
Residuals 219   3031  13.840

This is quite a lot of information, but in contrast to the nice examples on the web I can't seem to find the useful part of the information: p values and whether or not there are significant differences. Is there something wrong with my input, or does the result simply mean there is nothing interesting to see in these data?
Comment: An output of "str(data.ex2)" would be helpful. This is because if "subject", "concentration" and "vessel" are not factors, aov will give strange numbers (particularly subject and concentration in this instance).
Comment: `> str(data.ex2)

'data.frame':   224 obs. of  4 variables:

 $ subject      : int  20110818 20110818 20110818 20110818 20110818 20110818 20110818 20110818 20110818 20110818 ...

 $ vessel       : Factor w/ 2 levels "PA","PV": 1 1 1 1 1 1 1 1 1 1 ...

 $ concentration: num  -12 -11 -10.5 -10 -9.5 -9 -8.5 -8 -7.5 -7 ...

 $ force        : num  0 -1.2425 -1.4525 -1.755 0.0925 ...`
Answer: You don't get any p-values or f-values because you don't have an error term.  You don't have an error term because there are no discrete replicates of your measures.  Either get get more than one subject or make your subject a factor.
data.ex2$subject <- factor(data.ex2$subject)

Also, as is typical with ANOVA's you might want your predictors to be categorical (but maybe not).  Something like...
data.ex2$conc <- factor(data.ex2$conc)

Comment: Now if I combine the helpful comments above, I seem to arrive at a result. The main problem appears to be that I (ab)use integers as subject names and integers as labels for the concentration. After converting both subject and concentration into factors, I get more reasonable output. Thanks everyone for their help.
Comment: @mhoenicka Your last comment suggest that John was right which makes this response eligible for the "green mark" (i.e., you can check this answer as accepted since it solved your problem).
Comment: I'm afraid my data description was too terse as I didn't want to post the entire data table. Of course there are several subjects included (n=8), and a total of 14 different concentrations. I just wanted to sketch the layout. I can post the entire data somewhere if that makes things clearer
Comment: As for the categorical predictors, this is pretty much right. I use the numbers as mere labels but I was not aware that R would treat them as numerical data. In any case, after using factor there are still no p values.
Comment: I don't think you read my answer carefully because it included the argument that you don't have "discrete" subjects and that you had to factor it.  I mentioned the number of them because it can also cause this issue.  Regardless... glad you got it working.