问:
Java Card count data usage of mobile user using USIM CAT event or similar
When a user consumes data in the Local Break Out (LBO) roaming mode, the actual data usage is not visible AFAIK to the home network. The CAT offers an event for call control but I don't see a functionality to monitor the data usage. Also in the USIM file system I see no file recording the data usage, again I see only files for the call metering.

Is there any chance to get the amount of consumed data from an applet?


来源: stackexchange

问:
How do I inject a large configuration file into AWS Elastic Beanstalk?
You can add files into .ebextension/ alongside the .config file but I want to keep it outside the build itself and saved configurations don't allow extra files. Should I upload the config to s3 separately?</p>

ContentLicense: CC BY-SA 4.0


问:
Add button to dockble windows in inventor?
I have made a tools. But it is not dockeble.  but I this code that make a dockbel windows. but do I add button to it that will run sub ?`

```<code>
</code>```
```<code>Dim oUserInterfaceMgr As UserInterfaceManager
        oUserInterfaceMgr = ThisApplication.UserInterfaceManager

        ' Create a new dockable window
        Dim oWindow As DockableWindow
        oWindow = oUserInterfaceMgr.DockableWindows.Add("SampleClientId6", "TestWindowInternalName6", "Test Window6")

        ' Get the hwnd of the dialog to be added as a child
        ' CHANGE THIS VALUE!
        Dim hwnd As Long
        hwnd = 4851096

        ' Add the dialog as a child to the dockable window
        oWindow.AddChild(hwnd)

        ' Don't allow docking to top and bottom
        oWindow.DisabledDockingStates = DockingStateEnum.kDockTop And DockingStateEnum.kDockBottom

        ' Make the window visible
        oWindow.Visible = True

</code>```
```<code>
</code>```

how do I add button to it. And how do I add code that run when you click the button ?
`

I want to recreat my current tools into a dockbel windows

my current tools look like this

Body:
I have made a tools. But it is not dockeble.  but I this code that make a dockbel windows. but do I add button to it that will run sub ?`

Dim oUserInterfaceMgr As UserInterfaceManager
        oUserInterfaceMgr = ThisApplication.UserInterfaceManager

        ' Create a new dockable window
        Dim oWindow As DockableWindow
        oWindow = oUserInterfaceMgr.DockableWindows.Add("SampleClientId6", "TestWindowInternalName6", "Test Window6")

        ' Get the hwnd of the dialog to be added as a child
        ' CHANGE THIS VALUE!
        Dim hwnd As Long
        hwnd = 4851096

        ' Add the dialog as a child to the dockable window
        oWindow.AddChild(hwnd)

        ' Don't allow docking to top and bottom
        oWindow.DisabledDockingStates = DockingStateEnum.kDockTop And DockingStateEnum.kDockBottom

        ' Make the window visible
        oWindow.Visible = True

how do I add button to it. And how do I add code that run when you click the button ?
`

I want to recreat my current tools into a dockbel windows

my current tools look like this


问:
Fix effect Bluetooth recording has on playback volume on Android
I'm making an application that records audio through a Bluetooth headset(or the phone's mic if there isn't a headset connected).

The application is intended to run in the background, while the user may be using the phone for something else, so it runs within a foreground service that is started manually by the user. While the device is recording, any audio that is playing(e.g. YouTube video or music from an app that also runs in the background) has a much lower playback volume than normal. This only happens when recording through the Bluetooth headset, while with the phone's default mic there isn't any effect.

The code I am using for the recorder part is the one described in the question at this post:
https://stackoverflow.com/questions/4026002/how-to-record-sound-using-bluetooth-headset
and the one for establishing the connection with the headset is the one from Stephan's answer from the same thread.

Edit:
Per suggestion the code samples that implement the recording are these:

In main activity:

```<code>@Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        registerReceiver(mBluetoothScoReceiver, intentFilter);
        audioManager = (AudioManager) getApplicationContext().getSystemService(getApplicationContext().AUDIO_SERVICE);
        // Start Bluetooth SCO.
        audioManager.setMode(audioManager.MODE_NORMAL);
        audioManager.setBluetoothScoOn(true);
        audioManager.startBluetoothSco();
        // Stop Speaker.
        audioManager.setSpeakerphoneOn(false);

    }

@Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBluetoothScoReceiver);
        // Stop Bluetooth SCO.
        audioManager.stopBluetoothSco();
        audioManager.setMode(audioManager.MODE_NORMAL);
        audioManager.setBluetoothScoOn(false);
        // Start Speaker.
        audioManager.setSpeakerphoneOn(true);
    }

private BroadcastReceiver mBluetoothScoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
            System.out.println("ANDROID Audio SCO state: " + state);
            if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
                /*
                 * Now the connection has been established to the bluetooth device.
                 * Record audio or whatever (on another thread).With AudioRecord you can record with an object created like this:
                 * new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                 * AudioFormat.ENCODING_PCM_16BIT, audioBufferSize);
                 *
                 * After finishing, don't forget to unregister this receiver and
                 * to stop the bluetooth connection with am.stopBluetoothSco();
                 */
            }
        }
    };
</code>```

In the Audiomanager class (responsible for the recording):

```<code>private MediaRecorder recorder;

    /**
     * Class constructor, creates the recorder
     */
    public AudioCaptureManager() {
        recorder = new MediaRecorder();
    }

    /**
     * Creates the audio file, sets the recorders parameters and starts the recording
     */
    public void start() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
        String externalFilesDir = Environment.getExternalStoragePublicDirectory("/").getAbsolutePath();/*
        We can change this directory to whatever we want*/
        String file = sdf.format(new Date()) + ".aac";
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.HE_AAC);
        recorder.setOutputFile(externalFilesDir + "/Recordings/" + file);
        try {
            recorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        recorder.start();
    }

    /**
     * Stops the audio recording and clears the recorder
     */
    public void stop() {
        recorder.stop();
        recorder.release();
        recorder = null;
    }
</code>```

The audiomanager's methods are called on demand by buttons in my UI.

So, is there any way to fix/avoid this?

Body:
I'm making an application that records audio through a Bluetooth headset(or the phone's mic if there isn't a headset connected).

The application is intended to run in the background, while the user may be using the phone for something else, so it runs within a foreground service that is started manually by the user. While the device is recording, any audio that is playing(e.g. YouTube video or music from an app that also runs in the background) has a much lower playback volume than normal. This only happens when recording through the Bluetooth headset, while with the phone's default mic there isn't any effect.

The code I am using for the recorder part is the one described in the question at this post:
https://stackoverflow.com/questions/4026002/how-to-record-sound-using-bluetooth-headset
and the one for establishing the connection with the headset is the one from Stephan's answer from the same thread.

Edit:
Per suggestion the code samples that implement the recording are these:

In main activity:

@Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        registerReceiver(mBluetoothScoReceiver, intentFilter);
        audioManager = (AudioManager) getApplicationContext().getSystemService(getApplicationContext().AUDIO_SERVICE);
        // Start Bluetooth SCO.
        audioManager.setMode(audioManager.MODE_NORMAL);
        audioManager.setBluetoothScoOn(true);
        audioManager.startBluetoothSco();
        // Stop Speaker.
        audioManager.setSpeakerphoneOn(false);

    }

@Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBluetoothScoReceiver);
        // Stop Bluetooth SCO.
        audioManager.stopBluetoothSco();
        audioManager.setMode(audioManager.MODE_NORMAL);
        audioManager.setBluetoothScoOn(false);
        // Start Speaker.
        audioManager.setSpeakerphoneOn(true);
    }

private BroadcastReceiver mBluetoothScoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
            System.out.println("ANDROID Audio SCO state: " + state);
            if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
                /*
                 * Now the connection has been established to the bluetooth device.
                 * Record audio or whatever (on another thread).With AudioRecord you can record with an object created like this:
                 * new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                 * AudioFormat.ENCODING_PCM_16BIT, audioBufferSize);
                 *
                 * After finishing, don't forget to unregister this receiver and
                 * to stop the bluetooth connection with am.stopBluetoothSco();
                 */
            }
        }
    };

In the Audiomanager class (responsible for the recording):

private MediaRecorder recorder;

    /**
     * Class constructor, creates the recorder
     */
    public AudioCaptureManager() {
        recorder = new MediaRecorder();
    }

    /**
     * Creates the audio file, sets the recorders parameters and starts the recording
     */
    public void start() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
        String externalFilesDir = Environment.getExternalStoragePublicDirectory("/").getAbsolutePath();/*
        We can change this directory to whatever we want*/
        String file = sdf.format(new Date()) + ".aac";
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.HE_AAC);
        recorder.setOutputFile(externalFilesDir + "/Recordings/" + file);
        try {
            recorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        recorder.start();
    }

    /**
     * Stops the audio recording and clears the recorder
     */
    public void stop() {
        recorder.stop();
        recorder.release();
        recorder = null;
    }

The audiomanager's methods are called on demand by buttons in my UI.

So, is there any way to fix/avoid this?


问:
how to make the edges in equal size in grViz function of DiagrammeR?
I am trying to create a diagram using grViz function from DiagrammeR package in R. But for some reason which I can not understand, two edges that I thought should be of equal length are drawn with different lengths which makes it asymmetrical.

Here is my code:

```<code>DiagrammeR::grViz("
      digraph G{
      rankdir = LR;
      rank1 [style = invisible];
      rank2 [style = invisible];
      rank3 [style = invisible];

      rank1 -> rank2 -> rank3 [color = white];

      graph[layout = dot,
      rankdir = LR,
      overlap = true,
      fontsize = 50]

      node[shape = circle,
      fixedsize = true
      width = 1.3
      ]

HFI [label = 'A']
NI  [label = 'B']
PRD [abel = 'C']
BMI [label = 'D']
VA  [label = 'E']
OL  [label = 'F']
CH  [label = 'G']

NI -> CH [label = 'H2']
PRD -> CH [label = 'H4']
HFI -> VA [label = 'H6']
BMI -> VA [label = 'H5']
VA -> CH [label = 'H3']
OL -> CH [label = 'H1']

{rank = same;
rank1 -> BMI -> HFI [style=invis];
rankdir = TB;}
{
rank = same;
rank2 -> OL -> NI -> VA -> PRD [style=invis];
rankdir = TB;
}
}")
</code>```

Here is the result I get:

I want H5 and H6 (the left-most edges) to appear with the same length.

Body:
I am trying to create a diagram using grViz function from DiagrammeR package in R. But for some reason which I can not understand, two edges that I thought should be of equal length are drawn with different lengths which makes it asymmetrical.

Here is my code:

DiagrammeR::grViz("
      digraph G{
      rankdir = LR;
      rank1 [style = invisible];
      rank2 [style = invisible];
      rank3 [style = invisible];

      rank1 -> rank2 -> rank3 [color = white];

      graph[layout = dot,
      rankdir = LR,
      overlap = true,
      fontsize = 50]

      node[shape = circle,
      fixedsize = true
      width = 1.3
      ]

HFI [label = 'A']
NI  [label = 'B']
PRD [abel = 'C']
BMI [label = 'D']
VA  [label = 'E']
OL  [label = 'F']
CH  [label = 'G']

NI -> CH [label = 'H2']
PRD -> CH [label = 'H4']
HFI -> VA [label = 'H6']
BMI -> VA [label = 'H5']
VA -> CH [label = 'H3']
OL -> CH [label = 'H1']

{rank = same;
rank1 -> BMI -> HFI [style=invis];
rankdir = TB;}
{
rank = same;
rank2 -> OL -> NI -> VA -> PRD [style=invis];
rankdir = TB;
}
}")

Here is the result I get:

I want H5 and H6 (the left-most edges) to appear with the same length.


问:
CSS Flexbox - Popup is still Beholden to Parent Flexbox
I have some basic code that allows for a popup to appear when something is hovered over. Codepen: https://codepen.io/Sean713/pen/GRBpVOZ

.row {
  height: 100px;
  border: 1px solid red;
  display: flex;
}

.subdiv {
  border: 1px solid green;
  position: relative;
}

.popup {
  display: none;
  position: absolute;
  left: 100px;
  border: 1px solid black;
}

.hover:hover+.popup {
  display: inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="subdiv">
    <p class="hover">Hover</p>
    <div class="popup">
      <p>Surprise I am a popup</p>
      <p> and so am I</p>
    </div>
  </div>
</div></code>```

Since .row is a flexbox, it makes sense that .subdiv should compress its width to its content, as I have not specified otherwise.

However, the popup that appears when I hover is having unexpected behavior. The actual text inside the p tags is wrapping and is only as wide as the longest word in the sentence, it seems to be acting almost like .subdiv. I'm not sure why this is the case or why the fact that .row being a flexbox is influencing this popup. I would like for the p tags inside the popup to full block and allow the popup to wrap around that.

Edit: Adding white-space: nowrap; to the p tag fixes it, but I don't understand why the wrapping issue occurs in the first place.

Body:
I have some basic code that allows for a popup to appear when something is hovered over. Codepen: https://codepen.io/Sean713/pen/GRBpVOZ

.row {
  height: 100px;
  border: 1px solid red;
  display: flex;
}

.subdiv {
  border: 1px solid green;
  position: relative;
}

.popup {
  display: none;
  position: absolute;
  left: 100px;
  border: 1px solid black;
}

.hover:hover+.popup {
  display: inline;
}

Hover

Surprise I am a popup

 and so am I

Since .row is a flexbox, it makes sense that .subdiv should compress its width to its content, as I have not specified otherwise.

However, the popup that appears when I hover is having unexpected behavior. The actual text inside the p tags is wrapping and is only as wide as the longest word in the sentence, it seems to be acting almost like .subdiv. I'm not sure why this is the case or why the fact that .row being a flexbox is influencing this popup. I would like for the p tags inside the popup to full block and allow the popup to wrap around that.

Edit: Adding white-space: nowrap; to the p tag fixes it, but I don't understand why the wrapping issue occurs in the first place.


问:
how can i solve this problem>> TclError: Item 236716 already exists
I want to display my csv data in a tkinter table, but when i run, it shows an error!

TclError: Item 236716 already exists

how can i fix it please?

```<code>csvreader=csv.reader(file)
l1=[] #liste des en-têtes de colonne
l1=next(csvreader) #column header
rset=[row for row in csvreader]  #liste des lignes de données

table=ttk.Treeview(fenetre,selectmode='browse') #mode navigation
table.place(x =550, y = 150, width=600,height=400)
table['height']=5
table['show']='headings'

table['columns']=l1

for i in l1:
    table.column(i, width=100,anchor='c')
    table.heading(i, text=i)

for j in rset:  #ajout des donnees
    v=[r for r in j] #il cree une liste dans j
    table.insert('', 'end', iid=v[0],values=v)
</code>```

Body:
I want to display my csv data in a tkinter table, but when i run, it shows an error!

TclError: Item 236716 already exists

how can i fix it please?

csvreader=csv.reader(file)
l1=[] #liste des en-têtes de colonne
l1=next(csvreader) #column header
rset=[row for row in csvreader]  #liste des lignes de données

table=ttk.Treeview(fenetre,selectmode='browse') #mode navigation
table.place(x =550, y = 150, width=600,height=400)
table['height']=5
table['show']='headings'

table['columns']=l1

for i in l1:
    table.column(i, width=100,anchor='c')
    table.heading(i, text=i)

for j in rset:  #ajout des donnees
    v=[r for r in j] #il cree une liste dans j
    table.insert('', 'end', iid=v[0],values=v)


问:
How to make an input range without snapping to tickmarks
Consider the code below that I copied from the MDN web docs:

Choose a comfortable temperature:

<input type="range" id="temp" name="temp" list="tickmarks" />

<datalist id="tickmarks">
  <option value="0"></option>
  <option value="25"></option>
  <option value="50"></option>
  <option value="75"></option>
  <option value="100"></option>
</datalist>```

As you can see the result is a nice looking range with tickmarks. However, when you try to select the value that is very close to the tickmark value, the range input will snap to that value when using a mouse-drag as input. One can use a workaround to use the keyboard to get those values, but this is not an intuitive or accessible one. This makes it in some cases impossible to select those values and is therefore not what I need since those values are valid options too.

Reading the documentation on those MDN web docs:

The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.

Clearly I am experiencing something different here, at least for mouse-drag input that is. I have tried this code snippet on both Chrome and Firefox to rule out any browser implementation inconsistencies.

How can I add an input range with tickmarks while not including the snapping?

Body:
Consider the code below that I copied from the MDN web docs:

Choose a comfortable temperature:

<input type="range" id="temp" name="temp" list="tickmarks" />

<datalist id="tickmarks">
  <option value="0"></option>
  <option value="25"></option>
  <option value="50"></option>
  <option value="75"></option>
  <option value="100"></option>
</datalist>

As you can see the result is a nice looking range with tickmarks. However, when you try to select the value that is very close to the tickmark value, the range input will snap to that value when using a mouse-drag as input. One can use a workaround to use the keyboard to get those values, but this is not an intuitive or accessible one. This makes it in some cases impossible to select those values and is therefore not what I need since those values are valid options too.

Reading the documentation on those MDN web docs:

The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.

Clearly I am experiencing something different here, at least for mouse-drag input that is. I have tried this code snippet on both Chrome and Firefox to rule out any browser implementation inconsistencies.

How can I add an input range with tickmarks while not including the snapping?


问:
How to use declarative macros to generate a self containing enum?
I want to create a declarative macro that simplifies a recursive creation of an enum structure (by hiding all the Box::new). However commas seem to cause a problem when having a deep formula that has commas in its substructures.

Here is an explanation in code:

Assume this definition for an Enum representing a subset of propositional logic

#[derive(Debug)]
enum PFormula {
    True,
    False,
    Atom(i32),
    Not(Box<PFormula>),
    And(Box<PFormula>, Box<PFormula>)
}

macro_rules! pformula {
    ($func:tt($($($sub:tt)+),+)) => { PFormula::$func($(Box::new($sub)+),+) };
    (True) => { PFormula::True };
    (False) => { PFormula::False };
    ($e:expr) => { PFormula::Atom($e) };
}

fn main() {

    let x = pformula!(And(Not(2), 3));
    let y = pformula!(And(And(1, 4), And(5, And(2, 6))));
    println!("{:?}", x);
    println!("{:?}", y);
}
```
<p>The <code>pformula</code> should take a simplified version of the syntax defined as the <code>enum</code> and create a <code>PFormula</code> representation by hiding all the <code>Box<PFormula></code>'s required for the recursive structure. What is happening is that there seems to be an ambiguity when handling the commas.</p>
<p>So the <code>x</code> in the above code should expand to:</p>
<pre class="lang-rust prettyprint-override"><code>PFormula::And(Box::new(PFormula::Not(Box::new(PFormula::Atom(2)))), Box::new(PFormula::Atom(3)))
</code>```

However this is the error returned

error: local ambiguity when calling macro `pformula`: multiple parsing options: built-in NTs tt ('sub') or 1 other option.
  --> src/main.rs:18:33
   |
18 |     let x = pformula!(And(Not(2), 3));
   |                                 ^

error: local ambiguity when calling macro `pformula`: multiple parsing options: built-in NTs tt ('sub') or 1 other option.
  --> src/main.rs:19:36
   |
19 |     let y = pformula!(And(And(1, 4), And(5, And(2, 6))));
   |                                    ^

error: could not compile `playground` due to 2 previous errors
```

Please note that this is a simplification of the syntax I am actually working on. The syntax I am using has around 8 variants of arity 1 and around 5 of arity 2, so having a match arm for each variant seemed like an overkill. Additionally I tried it and it still was not working because of the commas.

So the question, is there a way to do this in declarative macros or is this better solved using function-like proc macros?

Body:
I want to create a declarative macro that simplifies a recursive creation of an enum structure (by hiding all the Box::new). However commas seem to cause a problem when having a deep formula that has commas in its substructures.

Here is an explanation in code:

Assume this definition for an Enum representing a subset of propositional logic

#[derive(Debug)]
enum PFormula {
    True,
    False,
    Atom(i32),
    Not(Box<PFormula>),
    And(Box<PFormula>, Box<PFormula>)
}

macro_rules! pformula {
    ($func:tt($($($sub:tt)+),+)) => { PFormula::$func($(Box::new($sub)+),+) };
    (True) => { PFormula::True };
    (False) => { PFormula::False };
    ($e:expr) => { PFormula::Atom($e) };
}

fn main() {

    let x = pformula!(And(Not(2), 3));
    let y = pformula!(And(And(1, 4), And(5, And(2, 6))));
    println!("{:?}", x);
    println!("{:?}", y);
}

The pformula should take a simplified version of the syntax defined as the enum and create a PFormula representation by hiding all the Box<PFormula>'s required for the recursive structure. What is happening is that there seems to be an ambiguity when handling the commas.

So the x in the above code should expand to:

PFormula::And(Box::new(PFormula::Not(Box::new(PFormula::Atom(2)))), Box::new(PFormula::Atom(3)))

However this is the error returned

error: local ambiguity when calling macro `pformula`: multiple parsing options: built-in NTs tt ('sub') or 1 other option.
  --> src/main.rs:18:33
   |
18 |     let x = pformula!(And(Not(2), 3));
   |                                 ^

error: local ambiguity when calling macro `pformula`: multiple parsing options: built-in NTs tt ('sub') or 1 other option.
  --> src/main.rs:19:36
   |
19 |     let y = pformula!(And(And(1, 4), And(5, And(2, 6))));
   |                                    ^

error: could not compile `playground` due to 2 previous errors

Please note that this is a simplification of the syntax I am actually working on. The syntax I am using has around 8 variants of arity 1 and around 5 of arity 2, so having a match arm for each variant seemed like an overkill. Additionally I tried it and it still was not working because of the commas.

So the question, is there a way to do this in declarative macros or is this better solved using function-like proc macros?


问:
yarn registry scopes - injecting scope name + %2f into the registry url
trying to setup yarn scoped registry using example here

but the installer keeps appending scope name to the url.

.yarnrc

@myscope:registry" "https://artifactory.mycompany.com/artifactory/api/npm/myco

package.json

```<code>"dependencies": {
    "@myscope/web-components": "0.0.29",
</code>```

yarn install --verbose

```<code>Performing "GET" request to "https://artifactory.mycompany.com/artifactory/api/npm/myco/@myscope%2fweb-components  finished with status code 404.

verbose 1.176178875 Error: Couldn't find package "@myscope/web-components@0.0.29" required by "web@0.1.0" on the "npm" registry.".

</code>```

so @myscope%2f is injected into the request address.

expcting

https://artifactory.mycompany.com/artifactory/api/npm/myco/web-components

getting

https://artifactory.mycompany.com/artifactory/api/npm/myco/@myscope%2fweb-components

```<code>yarn version
1.22.19
</code>```

Body:
trying to setup yarn scoped registry using example here

but the installer keeps appending scope name to the url.

.yarnrc

@myscope:registry" "https://artifactory.mycompany.com/artifactory/api/npm/myco

package.json

"dependencies": {
    "@myscope/web-components": "0.0.29",

yarn install --verbose

Performing "GET" request to "https://artifactory.mycompany.com/artifactory/api/npm/myco/@myscope%2fweb-components  finished with status code 404.

verbose 1.176178875 Error: Couldn't find package "@myscope/web-components@0.0.29" required by "web@0.1.0" on the "npm" registry.".

so @myscope%2f is injected into the request address.

expcting

https://artifactory.mycompany.com/artifactory/api/npm/myco/web-components

getting

https://artifactory.mycompany.com/artifactory/api/npm/myco/@myscope%2fweb-components

yarn version
1.22.19


问:
Autofit Changing with Text Replace
I have used several toturials to set up a script for google sheets that takes a row and turns it into a slide with a template I have layed out. In that template I set all text-boxes to shrink text on overflow. When coppied this property remains, however after calling replaceAllText, the textboxes loose this setting and it messes with the visuals.

This is the code I have set up. I want to know how to do this without loosing those properties.

```<code>const copy = googleSlideTemplate.makeCopy(`${row[0]}, ${row[1]} Card`, destiionFolder);
const slide = SlidesApp.openById(copy.getId());
const image = slide.getSlides()[0].getImages()[0];

slide.replaceAllText('{{cardname}}',row[0]);
slide.replaceAllText('{{cardtype}}',row[1]);
slide.replaceAllText('{{cardstaminatype}}',row[2]);
slide.replaceAllText('{{cardstaminacost}}',row[3]);
slide.replaceAllText('{{cardfluff}}',row[4]);
slide.replaceAllText('{{cardabilitylist}}',row[5]);
slide.replaceAllText('{{cardstaminaatribute}}',row[6]);
slide.replaceAllText('{{cardattackatribute}}',row[7]);
slide.replaceAllText('{{cardprotectionatribute}}',row[8]);
slide.replaceAllText('{{cardpacksymbol}}',row[9]);
image.replace(row[10], true);

slide.saveAndClose();
</code>```

To replace text and not have overflow rules replaced. The overflow rules were replaced. I insured the overflow rules are in the template sheet and my prefrences defualt to those same rules.

Title: Autofit Changing with Text Replace

Body:
I have used several toturials to set up a script for google sheets that takes a row and turns it into a slide with a template I have layed out. In that template I set all text-boxes to shrink text on overflow. When coppied this property remains, however after calling replaceAllText, the textboxes loose this setting and it messes with the visuals.

This is the code I have set up. I want to know how to do this without loosing those properties.

const copy = googleSlideTemplate.makeCopy(`${row[0]}, ${row[1]} Card`, destiionFolder);
const slide = SlidesApp.openById(copy.getId());
const image = slide.getSlides()[0].getImages()[0];

slide.replaceAllText('{{cardname}}',row[0]);
slide.replaceAllText('{{cardtype}}',row[1]);
slide.replaceAllText('{{cardstaminatype}}',row[2]);
slide.replaceAllText('{{cardstaminacost}}',row[3]);
slide.replaceAllText('{{cardfluff}}',row[4]);
slide.replaceAllText('{{cardabilitylist}}',row[5]);
slide.replaceAllText('{{cardstaminaatribute}}',row[6]);
slide.replaceAllText('{{cardattackatribute}}',row[7]);
slide.replaceAllText('{{cardprotectionatribute}}',row[8]);
slide.replaceAllText('{{cardpacksymbol}}',row[9]);
image.replace(row[10], true);

slide.saveAndClose();

To replace text and not have overflow rules replaced. The overflow rules were replaced. I insured the overflow rules are in the template sheet and my prefrences defualt to those same rules.


问:
Dash: how to use progress bar with background callback with celery and redis
I am developing a dash application for machine learning project. I have used docker-compose, services as below:

redis: # built-in redis image

db: # built-in postgres image

pgadmin: # built-in pgadmin image

web: # my custom dash app image. I have used gunicorn to start it in docker-compose file

celery: # my custom dash app image. I have used celery to start it in docker-compose file

proxy: # built-in nginx image

Usecases:

Upload dataset: I'm using dcc.Upload() and file is getting uploaded successfully. e.g. user uploads data.csv

Create train, test, dev dataset files: I'm using dbc.Button() where user clicks it and all 3 files are getting created successfully [I have used sklearn]. e.g. we get train.csv, test.csv and dev.csv

Model training: I'm using dbc.Button() where user clicks it and model is getting generated and stored successfully. e.g. model.joblib

This above setup is running fine.

Now, I'm trying to use background callback with celery and redis for my above listed usecases.

First Implemented:

From dash website, I have built this demo Example 4: Progress Bar https://dash.plotly.com/background-callbacks which is running successfully.

Issues:

how to update progress bar values i.e. what value to pass.

I Read celery documentation, I have found that we can get result like state, status etc from there. So, how to use those results(state, status etc) with progress bar in dash callback.

Please suggest.


问:
MSAL Azure AD B2C Requires Administrator Privileges to Authenticate
I have a WPF application that uses the Microsoft.Identity.Client package to authenticate users using Azure AD B2C. This works well on Development, but when I distribute my application with the Setup Project, my application is installed on the Program Files directory, which is a read-only directory. I assume that MSAL writes tokens or cache files to the directory the exe is running; so, when the application is initialized without admin privileges, the app cannot write to the directory, and therefore cannot authenticate users.

I've initialized an instance of IPublicClientApplication within the OnLaunched method like this:

```<code>PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)
            .WithB2CAuthority(AuthoritySignUpSignIn)
            .WithRedirectUri(RedirectUri)
            .Build();

TokenCacheHelper.Bind(PublicClientApp.UserTokenCache);
</code>```

Body:
I have a WPF application that uses the Microsoft.Identity.Client package to authenticate users using Azure AD B2C. This works well on Development, but when I distribute my application with the Setup Project, my application is installed on the Program Files directory, which is a read-only directory. I assume that MSAL writes tokens or cache files to the directory the exe is running; so, when the application is initialized without admin privileges, the app cannot write to the directory, and therefore cannot authenticate users.

I've initialized an instance of IPublicClientApplication within the OnLaunched method like this:

PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)
            .WithB2CAuthority(AuthoritySignUpSignIn)
            .WithRedirectUri(RedirectUri)
            .Build();

TokenCacheHelper.Bind(PublicClientApp.UserTokenCache);


问:
decompressing zipped file in js
I want to have a code where I can unzip a zipped file but even after trying so many things, I am not able to do this.

I want this in my front end because I just want to unzip and process the file inside to do some computation with the data inside.

I tried

https://github.com/nika-begiashvili/libarchivejs

I followed this readme but still i got this error,

https://github.com/nika-begiashvili/libarchivejs#readme

but when I try to unzip the file I get this error

Looking at it, it looks like this error is that it is not able to decompress

i checked another popular solution in StackOverflow this is:

first answer of this:

Unzipping files

but I don't know what is

ZipFile in

```<code>var zipFile = new ZipFile(url, doneReading)
</code>```

How can I get it !!

I am so lost, can anyone please help me !!

This is the zip file that I want to compress !!

This is inside my main zip file:

Title: decompressing zipped file in js

Body:
I want to have a code where I can unzip a zipped file but even after trying so many things, I am not able to do this.

I want this in my front end because I just want to unzip and process the file inside to do some computation with the data inside.

I tried

https://github.com/nika-begiashvili/libarchivejs

I followed this readme but still i got this error,

https://github.com/nika-begiashvili/libarchivejs#readme

but when I try to unzip the file I get this error

Looking at it, it looks like this error is that it is not able to decompress

i checked another popular solution in StackOverflow this is:

first answer of this:

Unzipping files

but I don't know what is

ZipFile in

var zipFile = new ZipFile(url, doneReading)

How can I get it !!

I am so lost, can anyone please help me !!

This is the zip file that I want to compress !!

This is inside my main zip file:


问:
R arrange function seems not to be working
I am having a dataframe with timestamps that also have decimal values. I want to calculate the difference between the first and all other events from the same group. To do that I use the following code:

```<code>values <- c("1671535501.862424", "1671535502.060679","1671535502.257422",
            "1671535502.472993", "1671535502.652619","1671535502.856569",
            "1671535503.048685", "1671535503.245988")
column_b <- c("a", "a","a","a","a","a","a","a")
values<-as.numeric(values)

#-- Calculate differences
data <- data.frame(values,column_b) #create data frame
res <- data %>%
  group_by(column_b) %>%
  arrange(values) %>%
  mutate(time=values-lag(values, default = first(values)))
</code>```

In general, the code does exactly what I expect it to do. It groups them, arranges them, and calculates the difference for each group. The output looks like this:

```<code>> res
# A tibble: 8 × 3
# Groups:   column_b [2]
       values column_b       time
        <dbl> <fct>         <dbl>
1 1671535502. a        0
2 1671535502. a        0.198
3 1671535502. a        0.197
4 1671535502. a        0.216
5 1671535503. a        0.180
6 1671535503. a        0.204
7 1671535503. a        0.192
8 1671535503. a        0.197
</code>```

Nevertheless, I have my doubts about the math results. If I am not mistaken, the values in this example are prearranged. But even if that was not the case, arrange() should have done the job. Hence, IF it is arranging the values, how can the 4th have a larger value than the 5th? There are multiple examples where we see that it does not make sense. What am I missing?

Body:
I am having a dataframe with timestamps that also have decimal values. I want to calculate the difference between the first and all other events from the same group. To do that I use the following code:

values <- c("1671535501.862424", "1671535502.060679","1671535502.257422",
            "1671535502.472993", "1671535502.652619","1671535502.856569",
            "1671535503.048685", "1671535503.245988")
column_b <- c("a", "a","a","a","a","a","a","a")
values<-as.numeric(values)

#-- Calculate differences
data <- data.frame(values,column_b) #create data frame
res <- data %>%
  group_by(column_b) %>%
  arrange(values) %>%
  mutate(time=values-lag(values, default = first(values)))

In general, the code does exactly what I expect it to do. It groups them, arranges them, and calculates the difference for each group. The output looks like this:

> res
# A tibble: 8 × 3
# Groups:   column_b [2]
       values column_b       time
        <dbl> <fct>         <dbl>
1 1671535502. a        0
2 1671535502. a        0.198
3 1671535502. a        0.197
4 1671535502. a        0.216
5 1671535503. a        0.180
6 1671535503. a        0.204
7 1671535503. a        0.192
8 1671535503. a        0.197

Nevertheless, I have my doubts about the math results. If I am not mistaken, the values in this example are prearranged. But even if that was not the case, arrange() should have done the job. Hence, IF it is arranging the values, how can the 4th have a larger value than the 5th? There are multiple examples where we see that it does not make sense. What am I missing?


问:
Struggling to convert Pine from V2 to V5
Very limited experience with this if anyone can help it would be much appreciated. I think it's in V2 Pine but needs to be in V5</p>
```<code>// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © physicalcryptohut
//@version=5
persistent_bull = nz(persistent_bull[1],0)
persistent_bear  = nz(persistent_bear[1],0)

indicator(title="Bitcoin Trading Pro", shorttitle="BTC PRO", overlay=true)
// ****************************************Inputs***************************************************************
buySellSignal = input(true, "Show the buy sell signals?")
cogRegionFillTransp = input(false, "Display COG & ATR Starc+/-?")
showFibCOG=input(false, "Display COG FIB based S(upport) and R(esistance)?")
inputIndividualSiganlPlot = true
sp = input (false, "Display Parabolic SAR - SAR?")
spLines = sp ? true : false
sCloud = input(false, "Display Ichimoku - Ichimoku?")
sL = input (false, "Display Leledec Exhausion - Leledc?")
sTD = false
sRMO = input(false, "Display Rahul Mohindar Oscillator - RMO?")
inputAma = input(false, title="Display Kaufman AMA wave - AMA?")
tm = input (false, "Display Trend Magic signals - TMI?")
wtoLB = input (false, "Display WaveTrend Oscillator - WTO?")
vfiLB = input (false, "Display Volume Flow Indicator - VFI?")
maj=input(true,title="Display Major Leledc Exhausion Bar signal - Leledec")
inputNeutralMinorSignals = input (false, title="Display the minor / not strong signals from Ichimoku")
min=input(false,title="Display Minor Leledc Exhausion Bar signal - Leledec")
tenkanPeriods = input(10, minval=9, title="Tenkan Period - Ichimoku [(normal)9 or (forex)10 or (crypto)20]")
kijunPeriods = input(30, minval=26, title="Kijun Period - Ichimoku [(normal)26 or (forex)30 or (crypto)60]")
chikouPeriods = input(60, minval=52, title="Chikou - Ichimoku [(normal)52 or (forex)60 or (crypto)120]")
displacement = input(30, minval=26, title="Displacement - Ichimoku [(normal/forex)26 or (crypto)30]")
// ****************************************General Color Variables***************************************************************
colorLime = #006400 // Warning sign for long trade
colorBuy= #2DFF03 // Good sign for long trade
colorSell = #733629 // Good sign for short trade
colorMaroon =#8b0000 // Warning sign for short trade
colorBlue =#0000ff // No clear sign
colorGray = #a9a9a9 // Gray Color (For Squeeze momentum indicator)
colorBlack = #000000 // Black
colorWhite = #ffffff // White
colorTenkanViolet = #800000 // Tenkan-sen line color
colorKijun = #0000A6 // Kijun-sen line color

// TD Sequential bar colors
tdSell = #ff6666
tdSellOvershoot = #ff1a1a
tdSellOvershoot1 = #cc0000
tdSellOverShoot2 = #990000
tdSellOverShoot3 = #732626

tdBuy = #80ff80
tdBuyOverShoot = #33ff33
tdBuyOvershoot1 = #00cc00
tdBuyOverShoot2 = #008000
tdBuyOvershoot3 = #004d00

barBuy = #006a4e
barSell = #c91f37

// ****************************************Icons***************************************************************
upSign = '↑' // indicates the indicator shows uptrend
downSign = '↓' // incicates the indicator showing downtrend
exitSign ='x' //indicates the indicator uptrend/downtrend ending
// diamond signals weakBullishSignal or weakBearishsignal
// flag signals neutralBullishSignal or neutralBearishSignal

// ****************************************Parabolic SAR code***************************************************************
start = 2
increment = 2
maximum = 2
sus = true
sds = true
disc = false

startCalc = start * .01
incrementCalc = increment * .01
maximumCalc = maximum * .10

sarUp = sar(startCalc, incrementCalc, maximumCalc)
sarDown = sar(startCalc, incrementCalc, maximumCalc)

colUp = spLines and close >= sarDown ? colorLime : na
colDown = spLines and close <= sarUp ? colorSell : na

plot(sp and sus and sarUp ? sarUp : na, title="↓ SAR", style=cross, linewidth=3,color=colUp)
plot(sp and sds and sarDown ? sarDown : na, title="↑ SAR", style=circles, linewidth=3,color=colDown)

startSAR = 0.02
incrementSAR = 0.02
maximumSAR = 0.2

psar = sar(startSAR, incrementSAR, maximumSAR)
bullishPSAR = psar < high and psar[1] > low
bearishPSAR= psar > low and psar[1] < high

//***********************Leledc Exhausion Bar***********************************************
leledcSrc=input(close, "Major Leledec Exhausion Bar ::  Source")
maj_qual=input(6, "Major Leledec Exhausion Bar ::  Bar count no")
maj_len=input(30, "Major Leledec Exhausion Bar ::  Highest / Lowest")
min_qual=input(5, "Minor Leledec Exhausion Bar ::  Bar count no")
min_len=input(5, "Minor Leledec Exhausion Bar ::  Bar count no")

lele(qual,len)=>
    bindex=nz(bindex[1],0)
    sindex=nz(sindex[1],0)
    ret=0
    if (leledcSrc>leledcSrc[4])
        bindex:=bindex + 1
    if(leledcSrc<leledcSrc[4])
        sindex:=sindex + 1
    if (bindex>qual) and (leledcSrc<open) and high>=highest(high,len)
        bindex:=0
        ret:=-1
    if ((sindex>qual) and (leledcSrc>open) and (low<= lowest(low,len)))
        sindex:=0
        ret:=1
    return=ret

major=lele(maj_qual,maj_len)
minor=lele(min_qual,min_len)

leledecMajorBullish = maj ? (major==1?low:na) : na
leledecMajorBearish = maj ? (major==-1?high:na) : na

//****************Ichimoku ************************************
donchian(len) => avg(lowest(len), highest(len))

tenkan = donchian(tenkanPeriods)
kijun = donchian(kijunPeriods)
senkouA = avg(tenkan, kijun)
senkouB = donchian(chikouPeriods)
displacedSenkouA = senkouA[displacement]
displacedSenkouB = senkouB[displacement]

bullishSignal = crossover(tenkan, kijun)
bearishSignal = crossunder(tenkan, kijun)

bullishSignalValues = iff(bullishSignal, tenkan, na)
bearishSignalValues = iff(bearishSignal, tenkan, na)

strongBullishSignal = crossover(tenkan, kijun) and bullishSignalValues > displacedSenkouA and bullishSignalValues > displacedSenkouB and low > tenkan and displacedSenkouA > displacedSenkouB
strongBearishSignal = bearishSignalValues < displacedSenkouA and bearishSignalValues < displacedSenkouB and high < tenkan and displacedSenkouA <  displacedSenkouB

neutralBullishSignal = (bullishSignalValues > displacedSenkouA and bullishSignalValues < displacedSenkouB) or (bullishSignalValues < displacedSenkouA and bullishSignalValues > displacedSenkouB)
weakBullishSignal = bullishSignalValues < displacedSenkouA and bullishSignalValues < displacedSenkouB
neutralBearishSignal = (bearishSignalValues > displacedSenkouA and bearishSignalValues < displacedSenkouB) or (bearishSignalValues < displacedSenkouA and bearishSignalValues > displacedSenkouB)
weakBearishSignal = bearishSignalValues > displacedSenkouA and bearishSignalValues > displacedSenkouB

//*********************Kaufman AMA wave*********************//
srcAMA=input(close, "Kaufman AMA wave ::  Source")
lengthAMA=input(20, "Kaufman AMA wave ::  Length")
filterp = input(10, "Kaufman AMA wave ::  Efficiency Ratio")

d=abs(srcAMA-srcAMA[1])
s=abs(srcAMA-srcAMA[lengthAMA])
noise=sum(d, lengthAMA)
efratio=s/noise
fastsc=input(0.6022, "Kaufman AMA wave ::  Fastsc")
slowsc=input(0.0645, "Kaufman AMA wave ::  Slowsc")

smooth=pow(efratio*fastsc+slowsc, 2)
ama=nz(ama[1], srcAMA)+smooth*(srcAMA-nz(ama[1], srcAMA ))
filter=filterp/100 * stdev(ama-nz(ama), lengthAMA)
amalow=ama < nz(ama[1]) ? ama : nz(amalow[1])
amahigh=ama > nz(ama[1]) ? ama : nz(amahigh[1])
bw=(ama-amalow) > filter ? 1 : (amahigh-ama > filter ? -1 : 0)
s_color=bw > 0 ? colorBuy : (bw < 0) ? colorSell : colorBlue

amaLongConditionEntry = s_color==colorBuy and s_color[1]!=colorBuy
amaShortConditionEntry = s_color==colorSell and s_color[1]!=colorSell
//***********************Rahul Mohindar Oscillator ******************************//
AMASRC=input(close, "Rahul Mohindar Oscillator ::  Source")
cm2(x) => sma(x,2)
ma1=cm2(AMASRC)
ma2=cm2(ma1)
ma3=cm2(ma2)
ma4=cm2(ma3)
ma5=cm2(ma4)
ma6=cm2(ma5)
ma7=cm2(ma6)
ma8=cm2(ma7)
ma9=cm2(ma8)
ma10=cm2(ma9)
SwingTrd1 = 100 * (AMASRC - (ma1+ma2+ma3+ma4+ma5+ma6+ma7+ma8+ma9+ma10)/10)/(highest(AMASRC,10)-lowest(AMASRC,10))
SwingTrd2=ema(SwingTrd1,30)
SwingTrd3=ema(SwingTrd2,30)
RMO= ema(SwingTrd1,81)
Buy=cross(SwingTrd2,SwingTrd3)
Sell=cross(SwingTrd3,SwingTrd2)
Bull_Trend=ema(SwingTrd1,81)>0
Bear_Trend=ema(SwingTrd1,81)<0
Ribbon_kol=Bull_Trend ? colorBuy : (Bear_Trend ? colorSell : colorBlue)
Impulse_UP= SwingTrd2 > 0
Impulse_Down= RMO < 0
bar_kol=Impulse_UP ? colorBuy : (Impulse_Down ? colorSell : (Bull_Trend ?  colorBuy : colorBlue))

rahulMohindarOscilllatorLongEntry = Ribbon_kol==colorBuy and Ribbon_kol[1]!=colorBuy and Ribbon_kol[1]==colorSell and bar_kol==colorBuy
rahulMohindarOscilllatorShortEntry = Ribbon_kol==colorSell and Ribbon_kol[1]!=colorSell and Ribbon_kol[1]==colorBuy and bar_kol==colorSell

//***********************TD Sequential code ******************************//
transp=0
Numbers=false
SR=false
Barcolor=true

TD = close > close[4] ?nz(TD[1])+1:0
TS = close < close[4] ?nz(TS[1])+1:0

TDUp = TD - valuewhen(TD < TD[1], TD , 1 )
TDDn = TS - valuewhen(TS < TS[1], TS , 1 )

priceflip = barssince(close<close[4])
sellsetup = close>close[4] and priceflip
sell = sellsetup and barssince(priceflip!=9)
sellovershoot = sellsetup and barssince(priceflip!=13)
sellovershoot1 = sellsetup and barssince(priceflip!=14)
sellovershoot2 = sellsetup and barssince(priceflip!=15)
sellovershoot3 = sellsetup and barssince(priceflip!=16)

priceflip1 = barssince(close>close[4])
buysetup = close<close[4] and priceflip1
buy = buysetup and barssince(priceflip1!=9)
buyovershoot = barssince(priceflip1!=13) and buysetup
buyovershoot1 = barssince(priceflip1!=14) and buysetup
buyovershoot2 = barssince(priceflip1!=15) and buysetup
buyovershoot3 = barssince(priceflip1!=16) and buysetup

TDbuyh = valuewhen(buy,high,0)
TDbuyl = valuewhen(buy,low,0)
TDsellh = valuewhen(sell,high,0)
TDselll = valuewhen(sell,low,0)

//***********************Volume Flow Indicator [LazyBear] ******************************//
lengthVFI = input(130, title="Volume Flow Indicator :: length")
coefVFI = input(0.2, title="Volume Flow Indicator  ::  Coef")
vcoefVFI = input(2.5, title="Volume Flow Indicator ::  Max. vol. cutoff")
signalLength=input(5, title="Volume Flow Indicator ::  signal length")
smoothVFI=input(false, type=bool, title="Volume Flow  :: Indicator smooth?")

ma(x,y) => smoothVFI ? sma(x,y) : x

typical=hlc3
inter = log( typical ) - log( typical[1] )
vinter = stdev(inter, 30 )
cutoff = coefVFI * vinter * close
vave = sma( volume, lengthVFI )[1]
vmax = vave * vcoefVFI
vc = iff(volume < vmax, volume, vmax)
mf = typical - typical[1]
vcp = iff( mf > cutoff, vc, iff ( mf < -cutoff, -vc, 0 ) )

vfi = ma(sum( vcp , lengthVFI )/vave, 3)
vfima=ema( vfi, signalLength )
dVFI=vfi-vfima

bullishVFI = vfi > 0 and vfi[1] <=0
bearishVFI =  vfi < 0 and vfi[1] >=0

//***********************WaveTrend Oscillator [WT] ******************************//
n1 = input(10, "WaveTrend Oscillator:: Channel Length")
n2 = input(21, "WaveTrend Oscillator:: Average Length")
obLevel1 = input(60, "WaveTrend Oscillator:: Over Bought Level 1")
obLevel2 = input(53, "WaveTrend Oscillator:: Over Bought Level 2")
osLevel1 = input(-60, "WaveTrend Oscillator:: Over Sold Level 1")
osLevel2 = input(-53, "WaveTrend Oscillator:: Over Sold Level 2")

ap = hlc3
esa = ema(ap, n1)
dWTI = ema(abs(ap - esa), n1)
ci = (ap - esa) / (0.015 * dWTI)
tci = ema(ci, n2)

wt1 = tci
wt2 = sma(wt1,4)

wtiSignal = wt1-wt2

bullishWTI = wt1 > osLevel1 and wt1[1] <= osLevel1 and wtiSignal > 0
bearishWTI = wt1 < obLevel1 and wt1[1] >= obLevel1 and wtiSignal < 0

// **************** Trend Magic code adapted from  Glaz ********************* /
CCI = input(20, "Tend Magic:: Input for CCI")
ATR = input(5, "Tend Magic:: Input for ATRc")
Multiplier= input(1, "Tend Magic :: ATR Multiplier")

original= true
thisCCI = cci(close, CCI)
lastCCI = nz(thisCCI[1])
bufferDn= high + Multiplier * sma(tr,ATR)
bufferUp= low - Multiplier * sma(tr,ATR)
if (thisCCI >= 0 and lastCCI < 0)
    bufferUp := bufferDn[1]
if (thisCCI <= 0 and lastCCI > 0)
    bufferDn := bufferUp[1]

if (thisCCI >= 0)
    if (bufferUp < bufferUp[1])
        bufferUp := bufferUp[1]
else
    if (thisCCI <= 0)
        if (bufferDn > bufferDn[1])
            bufferDn := bufferDn[1]

x=thisCCI >= 0 ?bufferUp:thisCCI <= 0 ?bufferDn:x[1]
swap=x>x[1]?1:x<x[1]?-1:swap[1]
swap2=swap==1?lime:red
swap3=thisCCI >=0 ?lime:red
swap4=original?swap3:swap2

bullTrendMagic = swap4 == lime and swap4[1] == red
bearTrendMagic = swap4 == red and swap4[1] == lime

//********** Indicator: Support/Resistance based on COG Fib by Lazy Bear ****************
lengthFibCOG = input(20, "COG (Center of Gravity)  fibs:: Period")
srcFibCOG = input(close, title= "COG (Center of Gravity)  fibs:: ::  Source")

calc_wima(srcFibCOG, length) =>
    MA_s=(srcFibCOG + nz(MA_s[1] * (length-1)))/length
    MA_s

calc_ma(s, l) => sma(s,l)
medianCOG=input(0, title= "COG (Center of Gravity) fibs:: ::  Median")
th=linreg(high, lengthFibCOG, medianCOG)
tl=linreg(low, lengthFibCOG, medianCOG)
tr_c=th-tl
tra= calc_wima(tr_c,lengthFibCOG)

mp=calc_ma( srcFibCOG, lengthFibCOG)
ub_4p2360 = mp + ( 4.2360 * tra)
ub_3p6180=mp  + ( 3.6180 * tra)
ub_2p6180=mp  + ( 2.6180 * tra)
ub_1p6180=mp  + ( 1.6180 * tra)
ub_0p618=mp  + ( 0.618 * tra)

lb_1p6180=mp - ( 1.6180 * tra)
lb_2p6180=mp - ( 2.6180 * tra)
lb_3p6180=mp - ( 3.6180 * tra)
lb_4p2360=mp - ( 4.2360 * tra)
lb_0p618=mp - ( 0.618 * tra)

plot(mp, title="Middlepoint", color=maroon, style=line, transp=iff(showFibCOG, 0, 100), linewidth=4)
plot(lb_0p618,title="S1", color=black, style=line, transp=iff(showFibCOG, 0, 100), linewidth=3)
plot(ub_0p618,title="R1", color=black, style=line, transp=iff(showFibCOG, 0, 100), linewidth=3)
plot(ub_1p6180,title="R2", color=lime, style=line, transp=iff(showFibCOG, 0, 100), linewidth=2)
plot(lb_1p6180,title="S2", color=lime, style=line, transp=iff(showFibCOG, 0, 100), linewidth=3)
plot(ub_2p6180,title="R3", color=red, style=line, transp=iff(showFibCOG, 0, 100), linewidth=1)
plot(lb_2p6180,title="S3", color=red, style=line, transp=iff(showFibCOG, 0, 100), linewidth=1)
plot(ub_3p6180,title="R4", color=purple, style=line, transp=iff(showFibCOG, 0, 100), linewidth=1)
plot(lb_3p6180,title="S4", color=purple, style=line, transp=iff(showFibCOG, 0, 100), linewidth=1)
plot(ub_4p2360,title="R5", color=blue, style=line, transp=iff(showFibCOG, 0, 100), linewidth=1)
plot(lb_4p2360,title="S5", color=blue, style=line, transp=iff(showFibCOG, 0, 100), linewidth=1)

// ************ Indicator: Custom COG channel by Lazy Bear **************** //
srcCOG = input(close, title= "COG (Center of Gravity) channel ::  Source")
lengthCOG = input (34, title= "COG (Center of Gravity)  channel ::  Length")
median=input(0, title = "COG (Center of Gravity)  channel  ::  median")
multCOG= input(2.5, title = "COG (Center of Gravity)  channel  ::  mult")
offset = input(20, title="COG (Center of Gravity)  channel ::  offset")

tr_custom() =>
    x1=high-low
    x2=abs(high-close[1])
    x3=abs(low-close[1])
    max(x1, max(x2,x3))

atr_custom(x,y) =>
    sma(x,y)

dev = (multCOG * stdev(srcCOG, lengthCOG))
basis=linreg(srcCOG, lengthCOG, median)
ul = (basis + dev)
ll = (basis - dev)
tr_v = tr_custom()
acustom=(2*atr_custom(tr_v, lengthCOG))
uls=basis+acustom
lls=basis-acustom

cRFT = cogRegionFillTransp ? 0 : 100

// Plot STDEV channel
plot(basis, linewidth=2, color=navy, style=line, title="COG Median STDEV", transp=cRFT)
lb=plot(ul, color=red, linewidth=2, title="COG BB+", style=dashed, transp=cRFT)
tb=plot(ll, color=green, linewidth=2, title="COG BB-", style=dashed, transp=cRFT)

// Plot ATR channel
plot(basis, linewidth=2, color=navy, style=line, linewidth=2, title="COG Median ATR ", transp=cRFT)
ls=plot(uls, color=red, linewidth=2, title="COG Starc+ ATR", style=circles, transp=cRFT)
ts=plot(lls, color=green, linewidth=2, title="COG Star- ATR", style=circles, transp=cRFT)

// Mark SQZ
plot_offs_high=0.002
plot_offs_low=0.002
sqz_f=(uls>ul) and (lls<ll)
b_color=sqz_f ? colorBlack : na
plot(sqz_f ? lls - (lls * plot_offs_low) : na, color=b_color, style=cross, linewidth=3, title="COG SQZ", transp=0)
plot(sqz_f ? uls + (uls * plot_offs_high) : na, color=b_color, style=cross, linewidth=3, title="COG SQZ", transp=0)

// ****************************************All the plots and coloring of bars***************************************************************
// Trend Magic
plotchar(tm and bullTrendMagic, title="TM", char=upSign, location=location.belowbar, color=colorBuy, transp=0, text="TM", textcolor=colorBuy, size=size.auto)
plotchar(tm and bearTrendMagic, title="TM", char=downSign, location=location.abovebar, color=colorSell, transp=0, text="TM", textcolor=colorSell, size=size.auto)

// WaveTrend Oscillator
plotshape(wtoLB and bullishWTI, color=colorBuy, style=shape.labelup, textcolor=#000000, text="WTI", location=location.belowbar, transp=0)
plotshape(wtoLB and bearishWTI, color=colorSell, style=shape.labeldown, textcolor=#ffffff,  text="WTI", location=location.abovebar, transp=0)

// VFI
plotshape(vfiLB and bullishVFI, color=colorBuy, style=shape.labelup, textcolor=#000000, text="VFI", location=location.belowbar, transp=0)
plotshape(vfiLB and bearishVFI, color=colorSell, style=shape.labeldown, textcolor=#ffffff,  text="VFI", location=location.abovebar, transp=0)

// PSAR
plotshape(inputIndividualSiganlPlot and sp and bullishPSAR, color=colorBuy, style=shape.labelup, textcolor=#000000, text="Sar", location=location.belowbar, transp=0)
plotshape(inputIndividualSiganlPlot and sp and bearishPSAR, color=colorSell, style=shape.labeldown, textcolor=#ffffff,  text="Sar", location=location.abovebar, transp=0)

// Leledec
plotshape(inputIndividualSiganlPlot and sL and leledecMajorBearish, color=colorSell, style=shape.labeldown, textcolor=#ffffff,  text="Leledec", location=location.abovebar, transp=0)
plotshape(inputIndividualSiganlPlot and sL and leledecMajorBullish, color=colorBuy, style=shape.labelup, textcolor=#000000, text="Leledec", location=location.belowbar, transp=0)

plotshape(min ? (minor==1?low:na) : na, style=shape.diamond, text="Leledec", size=size.tiny, location=location.belowbar, title="Leledec :: Weak", color=colorLime)
plotshape(min ? (minor==-1?high:na) : na, style=shape.diamond, text="Leledec", size=size.tiny, location=location.abovebar, title="Leleddec :: Weak", color=colorSell)

// Ichimoku
plot(tenkan, color=iff(sCloud, colorTenkanViolet, na), title="Tenkan", linewidth=2, transp=0)
plot(kijun, color=iff(sCloud, colorKijun, na), title="Kijun", linewidth=2, transp=0)
ichimokuSrc=input(close, "Ichimoku::  Source")
plot(ichimokuSrc, offset = -displacement, color=iff(sCloud, colorLime, na), title="Chikou", linewidth=1)

p1 = plot(senkouA, offset=displacement, color=iff(sCloud, lime, na), title="Senkou A", linewidth=1, transp=0)
p2 = plot(senkouB, offset=displacement, color=iff(sCloud, colorSell, na), title="Senkou B", linewidth=1, transp=0)
fill(p1, p2, color = senkouA > senkouB ? iff(sCloud, #1eb600, na) : iff(sCloud, colorSell, na), title="Ichimoku :: Kumo")

plotshape(inputIndividualSiganlPlot and strongBearishSignal, color=colorSell, style=shape.labelup, textcolor=#000000,  text="Ichimoku", location=location.abovebar, transp=0)
plotshape(inputIndividualSiganlPlot and strongBullishSignal, color=colorBuy, style=shape.labeldown, textcolor=#ffffff,  text="Ichimoku", location=location.belowbar, transp=0)

plotshape(inputNeutralMinorSignals and neutralBullishSignal, style=shape.flag, text="Ichimoku", size=size.small, location=location.belowbar, title="Ichimoku :: Neutral Bullish", color=colorLime)
plotshape(inputNeutralMinorSignals and weakBullishSignal, style=shape.diamond, text="Ichimoku", size=size.tiny, location=location.belowbar, title="Ichimoku :: Weak Bullish", color=colorLime)

plotshape(inputNeutralMinorSignals and neutralBearishSignal, style=shape.flag, text="Ichimoku", size=size.small, location=location.abovebar, title="Ichimoku :: Neutral Bearish", color=colorMaroon)
plotshape(inputNeutralMinorSignals and weakBearishSignal, style=shape.diamond, text="Ichimoku", size=size.tiny, location=location.abovebar, title="Ichimoku :: Weak Bearish", color=colorMaroon)

// AMA
plotshape(inputIndividualSiganlPlot and inputAma and amaLongConditionEntry, color=colorBuy, style=shape.labelup, textcolor=#000000, text="AMA", location=location.belowbar, transp=0)
plotshape(inputIndividualSiganlPlot and inputAma and amaShortConditionEntry, color=colorSell, style=shape.labeldown, textcolor=#ffffff,  text="AMA", location=location.abovebar, transp=0)

// RMO
plotshape(inputIndividualSiganlPlot and sRMO and rahulMohindarOscilllatorLongEntry, color=colorBuy, style=shape.labelup, textcolor=#000000, text="RMO", location=location.belowbar, transp=0)
plotshape(inputIndividualSiganlPlot and sRMO and rahulMohindarOscilllatorShortEntry, color=colorSell, style=shape.labeldown, textcolor=#ffffff,  text="RMO", location=location.abovebar, transp=0)

// TD
plot(sTD and SR?(TDbuyh ? TDbuyl: na):na,style=circles, linewidth=1, color=red)
plot(sTD and SR?(TDselll ? TDsellh : na):na,style=circles, linewidth=1, color=lime)

barColour = sell? tdSell : buy? tdBuy : sellovershoot? tdSellOvershoot : sellovershoot1? tdSellOvershoot1 : sellovershoot2?tdSellOverShoot2 : sellovershoot3? tdSellOverShoot3 : buyovershoot? tdBuyOverShoot : buyovershoot1? tdBuyOvershoot1 : buyovershoot2? tdBuyOverShoot2 : buyovershoot3? tdBuyOvershoot3 : na
barcolor(color=barColour, title ="TD Sequential ::  Bar Colour")

// ****************************************BUY/SELL Signal ***************************************************************
bull = leledecMajorBullish or strongBullishSignal or rahulMohindarOscilllatorLongEntry or bullishVFI or amaLongConditionEntry or bullTrendMagic or bullishWTI
bear =  leledecMajorBearish or bearishPSAR or strongBearishSignal or rahulMohindarOscilllatorShortEntry or bearishVFI or amaShortConditionEntry or bearTrendMagic or bearishWTI

if bull
    persistent_bull := 1
    persistent_bear := 0

if bear
    persistent_bull := 0
    persistent_bear := 1

plotshape(buySellSignal and bull and (persistent_bull[1] != 1 or bear), style=shape.labelup, location=location.belowbar, color=colorBuy, text="Buy", textcolor=#000000, transp=0)
plotshape(buySellSignal and bear and (persistent_bear[1] != 1 or bull), style=shape.labeldown, color=colorSell, text="Sell", location=location.abovebar, textcolor =#ffffff, transp=0)
// ****************************************Alerts***************************************************************
// For global buy/sell
alertcondition(bull and persistent_bull[1] != 1, title='Buy', message='Buy')
alertcondition(bear and persistent_bear[1] != 1, title='Short', message='Short')

// For WaveTrend Oscillator
alertcondition(bullishWTI, title='Bullish - WaveTrend Oscillator', message='Bullish - WaveTrend Oscillator')
alertcondition(bearishWTI, title='Bearish - WaveTrend Oscillator', message='Bearish - WaveTrend Oscillator')

// For Volume Flow Indicator
alertcondition(bullishVFI, title='Bullish - Volume Flow Indicator', message='Bullish - Volume Flow Indicator')
alertcondition(bearishVFI, title='Bearish - Volume Flow Indicator', message='Bearish - Volume Flow Indicator')

// For major Leledc Exhausion
alertcondition(leledecMajorBullish, title='Bullish - Leledec Exhausion', message='Bullish - Leledec Exhausion')
alertcondition(leledecMajorBearish, title='Bearish - Leledec Exhausion', message='Bearish - Leledec Exhausion')

// For Kaufman AMA wave
alertcondition(amaLongConditionEntry, title='Bullish - Kaufman AMA wave', message='Bullish - AMA ::  Kaufman AMA wave')
alertcondition(amaShortConditionEntry, title='Bearish - Kaufman AMA wave', message='Bearish - AMA :: Kaufman AMA wave')

// For Rahul Mohindar Oscillator
alertcondition(rahulMohindarOscilllatorLongEntry, title='Bullish - Rahul Mohindar Oscillator', message='Bullish - RMO :: Rahul Mohindar Oscillator')
alertcondition(rahulMohindarOscilllatorShortEntry, title='Bearish - Rahul Mohindar Oscillator', message='Bearish - RMO :: Rahul Mohindar Oscillator')

// For Parabolic Sar
alertcondition(bullishPSAR, title='Bullish - Sar :: Parabolic SAR', message='Bullish - Sar :: Parabolic SAR')
alertcondition(bearishPSAR, title='Bearish - Sar :: Parabolic SAR', message='Bearish - Sar :: Parabolic SAR')

// For Ichimoku
alertcondition(strongBullishSignal, title='Bullish - Ichimoku', message='Bullish Ichimoku- Ichimoku')
alertcondition(strongBearishSignal, title='Bearish - Ichimoku', message='Bearish Ichimoku - Ichimoku')

</code>```
<p>I just keep getting errors I am very new to coding please help. I think this is all in V2 but I need it in V5. Any help will be much appreciated.
I am trying to make an indicator for trading bitcoin but every time I edit something, more errors pop up and its very stressful.</p>

Body:
Very limited experience with this if anyone can help it would be much appreciated. I think it's in V2 Pine but needs to be in V5

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © physicalcryptohut
//@version=5
persistent_bull = nz(persistent_bull[1],0)
persistent_bear  = nz(persistent_bear[1],0)

indicator(title="Bitcoin Trading Pro", shorttitle="BTC PRO", overlay=true)
// ****************************************Inputs***************************************************************
buySellSignal = input(true, "Show the buy sell signals?")
cogRegionFillTransp = input(false, "Display COG & ATR Starc+/-?")
showFibCOG=input(false, "Display COG FIB based S(upport) and R(esistance)?")
inputIndividualSiganlPlot = true
sp = input (false, "Display Parabolic SAR - SAR?")
spLines = sp ? true : false
sCloud = input(false, "Display Ichimoku - Ichimoku?")
sL = input (false, "Display Leledec Exhausion - Leledc?")
sTD = false
sRMO = input(false, "Display Rahul Mohindar Oscillator - RMO?")
inputAma = input(false, title="Display Kaufman AMA wave - AMA?")
tm = input (false, "Display Trend Magic signals - TMI?")
wtoLB = input (false, "Display WaveTrend Oscillator - WTO?")
vfiLB = input (false, "Display Volume Flow Indicator - VFI?")
maj=input(true,title="Display Major Leledc Exhausion Bar signal - Leledec")
inputNeutralMinorSignals = input (false, title="Display the minor / not strong signals from Ichimoku")
min=input(false,title="Display Minor Leledc Exhausion Bar signal - Leledec")
tenkanPeriods = input(10, minval=9, title="Tenkan Period - Ichimoku [(normal)9 or (forex)10 or (crypto)20]")
kijunPeriods = input(30, minval=26, title="Kijun Period - Ichimoku [(normal)26 or (forex)30 or (crypto)60]")
chikouPeriods = input(60, minval=52, title="Chikou - Ichimoku [(normal)52 or (forex)60 or (crypto)120]")
displacement = input(30, minval=26, title="Displacement - Ichimoku [(normal/forex)26 or (crypto)30]")
// ****************************************General Color Variables***************************************************************
colorLime = #006400 // Warning sign for long trade
colorBuy= #2DFF03 // Good sign for long trade
colorSell = #733629 // Good sign for short trade
colorMaroon =#8b0000 // Warning sign for short trade
colorBlue =#0000ff // No clear sign
colorGray = #a9a9a9 // Gray Color (For Squeeze momentum indicator)
colorBlack = #000000 // Black
colorWhite = #ffffff // White
colorTenkanViolet = #800000 // Tenkan-sen line color
colorKijun = #0000A6 // Kijun-sen line color

// TD Sequential bar colors
tdSell = #ff6666
tdSellOvershoot = #ff1a1a
tdSellOvershoot1 = #cc0000
tdSellOverShoot2 = #990000
tdSellOverShoot3 = #732626

tdBuy = #80ff80
tdBuyOverShoot = #33ff33
tdBuyOvershoot1 = #00cc00
tdBuyOverShoot2 = #008000
tdBuyOvershoot3 = #004d00

barBuy = #006a4e
barSell = #c91f37

// ****************************************Icons***************************************************************
upSign = '↑' // indicates the indicator shows uptrend
downSign = '↓' // incicates the indicator showing downtrend
exitSign ='x' //indicates the indicator uptrend/downtrend ending
// diamond signals weakBullishSignal or weakBearishsignal
// flag signals neutralBullishSignal or neutralBearishSignal

// ****************************************Parabolic SAR code***************************************************************
start = 2
increment = 2
maximum = 2
sus = true
sds = true
disc = false

startCalc = start * .01
incrementCalc = increment * .01
maximumCalc = maximum * .10

sarUp = sar(startCalc, incrementCalc, maximumCalc)
sarDown = sar(startCalc, incrementCalc, maximumCalc)

colUp = spLines and close >= sarDown ? colorLime : na
colDown = spLines and close <= sarUp ? colorSell : na

plot(sp and sus and sarUp ? sarUp : na, title="↓ SAR", style=cross, linewidth=3,color=colUp)
plot(sp and sds and sarDown ? sarDown : na, title="↑ SAR", style=circles, linewidth=3,color=colDown)

startSAR = 0.02
incrementSAR = 0.02
maximumSAR = 0.2

psar = sar(startSAR, incrementSAR, maximumSAR)
bullishPSAR = psar < high and psar[1] > low
bearishPSAR= psar > low and psar[1] < high

//***********************Leledc Exhausion Bar***********************************************
leledcSrc=input(close, "Major Leledec Exhausion Bar ::  Source")
maj_qual=input(6, "Major Leledec Exhausion Bar ::  Bar count no")
maj_len=input(30, "Major Leledec Exhausion Bar ::  Highest / Lowest")
min_qual=input(5, "Minor Leledec Exhausion Bar ::  Bar count no")
min_len=input(5, "Minor Leledec Exhausion Bar ::  Bar count no")

lele(qual,len)=>
    bindex=nz(bindex[1],0)
    sindex=nz(sindex[1],0)
    ret=0
    if (leledcSrc>leledcSrc[4])
        bindex:=bindex + 1
    if(leledcSrc<leledcSrc[4])
        sindex:=sindex + 1
    if (bindex>qual) and (leledcSrc<open) and high>=highest(high,len)
        bindex:=0
        ret:=-1
    if ((sindex>qual) and (leledcSrc>open) and (low<= lowest(low,len)))
        sindex:=0
        ret:=1
    return=ret

major=lele(maj_qual,maj_len)
minor=lele(min_qual,min_len)

leledecMajorBullish = maj ? (major==1?low:na) : na
leledecMajorBearish = maj ? (major==-1?high:na) : na

//****************Ichimoku ************************************
donchian(len) => avg(lowest(len), highest(len))

tenkan = donchian(tenkanPeriods)
kijun = donchian(kijunPeriods)
senkouA = avg(tenkan, kijun)
senkouB = donchian(chikouPeriods)
displacedSenkouA = senkouA[displacement]
displacedSenkouB = senkouB[displacement]

bullishSignal = crossover(tenkan, kijun)
bearishSignal = crossunder(tenkan, kijun)

bullishSignalValues = iff(bullishSignal, tenkan, na)
bearishSignalValues = iff(bearishSignal, tenkan, na)

strongBullishSignal = crossover(tenkan, kijun) and bullishSignalValues > displacedSenkouA and bullishSignalValues > displacedSenkouB and low > tenkan and displacedSenkouA > displacedSenkouB
strongBearishSignal = bearishSignalValues < displacedSenkouA and bearishSignalValues < displacedSenkouB and high < tenkan and displacedSenkouA <  displacedSenkouB

neutralBullishSignal = (bullishSignalValues > displacedSenkouA and bullishSignalValues < displacedSenkouB) or (bullishSignalValues < displacedSenkouA and bullishSignalValues > displacedSenkouB)
weakBullishSignal = bullishSignalValues < displacedSenkouA and bullishSignalValues < displacedSenkouB
neutralBearishSignal = (bearishSignalValues > displacedSenkouA and bearishSignalValues < displacedSenkouB) or (bearishSignalValues < displacedSenkouA and bearishSignalValues > displacedSenkouB)
weakBearishSignal = bearishSignalValues > displacedSenkouA and bearishSignalValues > displacedSenkouB

//*********************Kaufman AMA wave*********************//
srcAMA=input(close, "Kaufman AMA wave ::  Source")
lengthAMA=input(20, "Kaufman AMA wave ::  Length")
filterp = input(10, "Kaufman AMA wave ::  Efficiency Ratio")

d=abs(srcAMA-srcAMA[1])
s=abs(srcAMA-srcAMA[lengthAMA])
noise=sum(d, lengthAMA)
efratio=s/noise
fastsc=input(0.6022, "Kaufman AMA wave ::  Fastsc")
slowsc=input(0.0645, "Kaufman AMA wave ::  Slowsc")

smooth=pow(efratio*fastsc+slowsc, 2)
ama=nz(ama[1], srcAMA)+smooth*(srcAMA-nz(ama[1], srcAMA ))
filter=filterp/100 * stdev(ama-nz(ama), lengthAMA)
amalow=ama < nz(ama[1]) ? ama : nz(amalow[1])
amahigh=ama > nz(ama[1]) ? ama : nz(amahigh[1])
bw=(ama-amalow) > filter ? 1 : (amahigh-ama > filter ? -1 : 0)
s_color=bw > 0 ? colorBuy : (bw < 0) ? colorSell : colorBlue

amaLongConditionEntry = s_color==colorBuy and s_color[1]!=colorBuy
amaShortConditionEntry = s_color==colorSell and s_color[1]!=colorSell
//***********************Rahul Mohindar Oscillator ******************************//
AMASRC=input(close, "Rahul Mohindar Oscillator ::  Source")
cm2(x) => sma(x,2)
ma1=cm2(AMASRC)
ma2=cm2(ma1)
ma3=cm2(ma2)
ma4=cm2(ma3)
ma5=cm2(ma4)
ma6=cm2(ma5)
ma7=cm2(ma6)
ma8=cm2(ma7)
ma9=cm2(ma8)
ma10=cm2(ma9)
SwingTrd1 = 100 * (AMASRC - (ma1+ma2+ma3+ma4+ma5+ma6+ma7+ma8+ma9+ma10)/10)/(highest(AMASRC,10)-lowest(AMASRC,10))
SwingTrd2=ema(SwingTrd1,30)
SwingTrd3=ema(SwingTrd2,30)
RMO= ema(SwingTrd1,81)
Buy=cross(SwingTrd2,SwingTrd3)
Sell=cross(SwingTrd3,SwingTrd2)
Bull_Trend=ema(SwingTrd1,81)>0
Bear_Trend=ema(SwingTrd1,81)<0
Ribbon_kol=Bull_Trend ? colorBuy : (Bear_Trend ? colorSell : colorBlue)
Impulse_UP= SwingTrd2 > 0
Impulse_Down= RMO < 0
bar_kol=Impulse_UP ? colorBuy : (Impulse_Down ? colorSell : (Bull_Trend ?  colorBuy : colorBlue))

rahulMohindarOscilllatorLongEntry = Ribbon_kol==colorBuy and Ribbon_kol[1]!=colorBuy and Ribbon_kol[1]==colorSell and bar_kol==colorBuy
rahulMohindarOscilllatorShortEntry = Ribbon_kol==colorSell and Ribbon_kol[1]!=colorSell and Ribbon_kol[1]==colorBuy and bar_kol==colorSell

//***********************TD Sequential code ******************************//
transp=0
Numbers=false
SR=false
Barcolor=true

TD = close > close[4] ?nz(TD[1])+1:0
TS = close < close[4] ?nz(TS[1])+1:0

TDUp = TD - valuewhen(TD < TD[1], TD , 1 )
TDDn = TS - valuewhen(TS < TS[1], TS , 1 )

priceflip = barssince(close<close[4])
sellsetup = close>close[4] and priceflip
sell = sellsetup and barssince(priceflip!=9)
sellovershoot = sellsetup and barssince(priceflip!=13)
sellovershoot1 = sellsetup and barssince(priceflip!=14)
sellovershoot2 = sellsetup and barssince(priceflip!=15)
sellovershoot3 = sellsetup and barssince(priceflip!=16)

priceflip1 = barssince(close>close[4])
buysetup = close<close[4] and priceflip1
buy = buysetup and barssince(priceflip1!=9)
buyovershoot = barssince(priceflip1!=13) and buysetup
buyovershoot1 = barssince(priceflip1!=14) and buysetup
buyovershoot2 = barssince(priceflip1!=15) and buysetup
buyovershoot3 = barssince(priceflip1!=16) and buysetup

TDbuyh = valuewhen(buy,high,0)
TDbuyl = valuewhen(buy,low,0)
TDsellh = valuewhen(sell,high,0)
TDselll = valuewhen(sell,low,0)

//***********************Volume Flow Indicator [LazyBear] ******************************//
lengthVFI = input(130, title="Volume Flow Indicator :: length")
coefVFI = input(0.2, title="Volume Flow Indicator  ::  Coef")
vcoefVFI = input(2.5, title="Volume Flow Indicator ::  Max. vol. cutoff")
signalLength=input(5, title="Volume Flow Indicator ::  signal length")
smoothVFI=input(false, type=bool, title="Volume Flow  :: Indicator smooth?")

ma(x,y) => smoothVFI ? sma(x,y) : x

typical=hlc3
inter = log( typical ) - log( typical[1] )
vinter = stdev(inter, 30 )
cutoff = coefVFI * vinter * close
vave = sma( volume, lengthVFI )[1]
vmax = vave * vcoefVFI
vc = iff(volume < vmax, volume, vmax)
mf = typical - typical[1]
vcp = iff( mf > cutoff, vc, iff ( mf < -cutoff, -vc, 0 ) )

vfi = ma(sum( vcp , lengthVFI )/vave, 3)
vfima=ema( vfi, signalLength )
dVFI=vfi-vfima

bullishVFI = vfi > 0 and vfi[1] <=0
bearishVFI =  vfi < 0 and vfi[1] >=0

//***********************WaveTrend Oscillator [WT] ******************************//
n1 = input(10, "WaveTrend Oscillator:: Channel Length")
n2 = input(21, "WaveTrend Oscillator:: Average Length")
obLevel1 = input(60, "WaveTrend Oscillator:: Over Bought Level 1")
obLevel2 = input(53, "WaveTrend Oscillator:: Over Bought Level 2")
osLevel1 = input(-60, "WaveTrend Oscillator:: Over Sold Level 1")
osLevel2 = input(-53, "WaveTrend Oscillator:: Over Sold Level 2")

ap = hlc3
esa = ema(ap, n1)
dWTI = ema(abs(ap - esa), n1)
ci = (ap - esa) / (0.015 * dWTI)
tci = ema(ci, n2)

wt1 = tci
wt2 = sma(wt1,4)

wtiSignal = wt1-wt2

bullishWTI = wt1 > osLevel1 and wt1[1] <= osLevel1 and wtiSignal > 0
bearishWTI = wt1 < obLevel1 and wt1[1] >= obLevel1 and wtiSignal < 0

// **************** Trend Magic code adapted from  Glaz ********************* /
CCI = input(20, "Tend Magic:: Input for CCI")
ATR = input(5, "Tend Magic:: Input for ATRc")
Multiplier= input(1, "Tend Magic :: ATR Multiplier")

original= true
thisCCI = cci(close, CCI)
lastCCI = nz(thisCCI[1])
bufferDn= high + Multiplier * sma(tr,ATR)
bufferUp= low - Multiplier * sma(tr,ATR)
if (thisCCI >= 0 and lastCCI < 0)
    bufferUp := bufferDn[1]
if (thisCCI <= 0 and lastCCI > 0)
    bufferDn := bufferUp[1]

if (thisCCI >= 0)
    if (bufferUp < bufferUp[1])
        bufferUp := bufferUp[1]
else
    if (thisCCI <= 0)
        if (bufferDn > bufferDn[1])
            bufferDn := bufferDn[1]

x=thisCCI >= 0 ?bufferUp:thisCCI <= 0 ?bufferDn:x[1]
swap=x>x[1]?1:x<x[1]?-1:swap[1]
swap2=swap==1?lime:red
swap3=thisCCI >=0 ?lime:red
swap4=original?swap3:swap2

bullTrendMagic = swap4 == lime and swap4[1] == red
bearTrendMagic = swap4 == red and swap4[1] == lime

//********** Indicator: Support/Resistance based on COG Fib by Lazy Bear ****************
lengthFibCOG = input(20, "COG (Center of Gravity)  fibs:: Period")
srcFibCOG = input(close, title= "COG (Center of Gravity)  fibs:: ::  Source")

calc_wima(srcFibCOG, length) =>
    MA_s=(srcFibCOG + nz(MA_s[1] * (length-1)))/length
    MA_s

calc_ma(s, l) => sma(s,l)
medianCOG=input(0, title= "COG (Center of Gravity) fibs:: ::  Median")
th=linreg(high, lengthFibCOG, medianCOG)
tl=linreg(low, lengthFibCOG, medianCOG)
tr_c=th-tl
tra= calc_wima(tr_c,lengthFibCOG)

mp=calc_ma( srcFibCOG, lengthFibCOG)
ub_4p2360 = mp + ( 4.2360 * tra)
ub_3p6180=mp  + ( 3.6180 * tra)
ub_2p6180=mp  + ( 2.6180 * tra)
ub_1p6180=mp  + ( 1.6180 * tra)
ub_0p618=mp  + ( 0.618 * tra)

lb_1p6180=mp - ( 1.6180 * tra)
lb_2p6180=mp - ( 2.6180 * tra)
lb_3p6180=mp - ( 3.6180 * tra)
lb_4p2360=mp - ( 4.2360 * tra)
lb_0p618=mp - ( 0.618 * tra)

plot(mp, title="Middlepoint", color=maroon, style=line, transp=iff(showFibCOG, 0, 100), linewidth=4)
plot(lb_0p618,title="S1", color=black, style=line, transp=iff(showFibCOG, 0, 100), linewidth=3)
plot(ub_0p618,title="R1", color=black, style=line, transp=iff(showFibCOG, 0, 100), linewidth=3)
plot(ub_1p6180,title="R2", color=lime, style=line, transp=iff(showFibCOG, 0, 100), linewidth=2)
plot(lb_1p6180,title="S2", color=lime, style=line, transp=iff(showFibCOG, 0, 100), linewidth=3)
plot(ub_2p6180,title="R3", color=red, style=line, transp=iff(showFibCOG, 0, 100), linewidth=1)
plot(lb_2p6180,title="S3", color=red, style=line, transp=iff(showFibCOG, 0, 100), linewidth=1)
plot(ub_3p6180,title="R4", color=purple, style=line, transp=iff(showFibCOG, 0, 100), linewidth=1)
plot(lb_3p6180,title="S4", color=purple, style=line, transp=iff(showFibCOG, 0, 100), linewidth=1)
plot(ub_4p2360,title="R5", color=blue, style=line, transp=iff(showFibCOG, 0, 100), linewidth=1)
plot(lb_4p2360,title="S5", color=blue, style=line, transp=iff(showFibCOG, 0, 100), linewidth=1)

// ************ Indicator: Custom COG channel by Lazy Bear **************** //
srcCOG = input(close, title= "COG (Center of Gravity) channel ::  Source")
lengthCOG = input (34, title= "COG (Center of Gravity)  channel ::  Length")
median=input(0, title = "COG (Center of Gravity)  channel  ::  median")
multCOG= input(2.5, title = "COG (Center of Gravity)  channel  ::  mult")
offset = input(20, title="COG (Center of Gravity)  channel ::  offset")

tr_custom() =>
    x1=high-low
    x2=abs(high-close[1])
    x3=abs(low-close[1])
    max(x1, max(x2,x3))

atr_custom(x,y) =>
    sma(x,y)

dev = (multCOG * stdev(srcCOG, lengthCOG))
basis=linreg(srcCOG, lengthCOG, median)
ul = (basis + dev)
ll = (basis - dev)
tr_v = tr_custom()
acustom=(2*atr_custom(tr_v, lengthCOG))
uls=basis+acustom
lls=basis-acustom

cRFT = cogRegionFillTransp ? 0 : 100

// Plot STDEV channel
plot(basis, linewidth=2, color=navy, style=line, title="COG Median STDEV", transp=cRFT)
lb=plot(ul, color=red, linewidth=2, title="COG BB+", style=dashed, transp=cRFT)
tb=plot(ll, color=green, linewidth=2, title="COG BB-", style=dashed, transp=cRFT)

// Plot ATR channel
plot(basis, linewidth=2, color=navy, style=line, linewidth=2, title="COG Median ATR ", transp=cRFT)
ls=plot(uls, color=red, linewidth=2, title="COG Starc+ ATR", style=circles, transp=cRFT)
ts=plot(lls, color=green, linewidth=2, title="COG Star- ATR", style=circles, transp=cRFT)

// Mark SQZ
plot_offs_high=0.002
plot_offs_low=0.002
sqz_f=(uls>ul) and (lls<ll)
b_color=sqz_f ? colorBlack : na
plot(sqz_f ? lls - (lls * plot_offs_low) : na, color=b_color, style=cross, linewidth=3, title="COG SQZ", transp=0)
plot(sqz_f ? uls + (uls * plot_offs_high) : na, color=b_color, style=cross, linewidth=3, title="COG SQZ", transp=0)

// ****************************************All the plots and coloring of bars***************************************************************
// Trend Magic
plotchar(tm and bullTrendMagic, title="TM", char=upSign, location=location.belowbar, color=colorBuy, transp=0, text="TM", textcolor=colorBuy, size=size.auto)
plotchar(tm and bearTrendMagic, title="TM", char=downSign, location=location.abovebar, color=colorSell, transp=0, text="TM", textcolor=colorSell, size=size.auto)

// WaveTrend Oscillator
plotshape(wtoLB and bullishWTI, color=colorBuy, style=shape.labelup, textcolor=#000000, text="WTI", location=location.belowbar, transp=0)
plotshape(wtoLB and bearishWTI, color=colorSell, style=shape.labeldown, textcolor=#ffffff,  text="WTI", location=location.abovebar, transp=0)

// VFI
plotshape(vfiLB and bullishVFI, color=colorBuy, style=shape.labelup, textcolor=#000000, text="VFI", location=location.belowbar, transp=0)
plotshape(vfiLB and bearishVFI, color=colorSell, style=shape.labeldown, textcolor=#ffffff,  text="VFI", location=location.abovebar, transp=0)

// PSAR
plotshape(inputIndividualSiganlPlot and sp and bullishPSAR, color=colorBuy, style=shape.labelup, textcolor=#000000, text="Sar", location=location.belowbar, transp=0)
plotshape(inputIndividualSiganlPlot and sp and bearishPSAR, color=colorSell, style=shape.labeldown, textcolor=#ffffff,  text="Sar", location=location.abovebar, transp=0)

// Leledec
plotshape(inputIndividualSiganlPlot and sL and leledecMajorBearish, color=colorSell, style=shape.labeldown, textcolor=#ffffff,  text="Leledec", location=location.abovebar, transp=0)
plotshape(inputIndividualSiganlPlot and sL and leledecMajorBullish, color=colorBuy, style=shape.labelup, textcolor=#000000, text="Leledec", location=location.belowbar, transp=0)

plotshape(min ? (minor==1?low:na) : na, style=shape.diamond, text="Leledec", size=size.tiny, location=location.belowbar, title="Leledec :: Weak", color=colorLime)
plotshape(min ? (minor==-1?high:na) : na, style=shape.diamond, text="Leledec", size=size.tiny, location=location.abovebar, title="Leleddec :: Weak", color=colorSell)

// Ichimoku
plot(tenkan, color=iff(sCloud, colorTenkanViolet, na), title="Tenkan", linewidth=2, transp=0)
plot(kijun, color=iff(sCloud, colorKijun, na), title="Kijun", linewidth=2, transp=0)
ichimokuSrc=input(close, "Ichimoku::  Source")
plot(ichimokuSrc, offset = -displacement, color=iff(sCloud, colorLime, na), title="Chikou", linewidth=1)

p1 = plot(senkouA, offset=displacement, color=iff(sCloud, lime, na), title="Senkou A", linewidth=1, transp=0)
p2 = plot(senkouB, offset=displacement, color=iff(sCloud, colorSell, na), title="Senkou B", linewidth=1, transp=0)
fill(p1, p2, color = senkouA > senkouB ? iff(sCloud, #1eb600, na) : iff(sCloud, colorSell, na), title="Ichimoku :: Kumo")

plotshape(inputIndividualSiganlPlot and strongBearishSignal, color=colorSell, style=shape.labelup, textcolor=#000000,  text="Ichimoku", location=location.abovebar, transp=0)
plotshape(inputIndividualSiganlPlot and strongBullishSignal, color=colorBuy, style=shape.labeldown, textcolor=#ffffff,  text="Ichimoku", location=location.belowbar, transp=0)

plotshape(inputNeutralMinorSignals and neutralBullishSignal, style=shape.flag, text="Ichimoku", size=size.small, location=location.belowbar, title="Ichimoku :: Neutral Bullish", color=colorLime)
plotshape(inputNeutralMinorSignals and weakBullishSignal, style=shape.diamond, text="Ichimoku", size=size.tiny, location=location.belowbar, title="Ichimoku :: Weak Bullish", color=colorLime)

plotshape(inputNeutralMinorSignals and neutralBearishSignal, style=shape.flag, text="Ichimoku", size=size.small, location=location.abovebar, title="Ichimoku :: Neutral Bearish", color=colorMaroon)
plotshape(inputNeutralMinorSignals and weakBearishSignal, style=shape.diamond, text="Ichimoku", size=size.tiny, location=location.abovebar, title="Ichimoku :: Weak Bearish", color=colorMaroon)

// AMA
plotshape(inputIndividualSiganlPlot and inputAma and amaLongConditionEntry, color=colorBuy, style=shape.labelup, textcolor=#000000, text="AMA", location=location.belowbar, transp=0)
plotshape(inputIndividualSiganlPlot and inputAma and amaShortConditionEntry, color=colorSell, style=shape.labeldown, textcolor=#ffffff,  text="AMA", location=location.abovebar, transp=0)

// RMO
plotshape(inputIndividualSiganlPlot and sRMO and rahulMohindarOscilllatorLongEntry, color=colorBuy, style=shape.labelup, textcolor=#000000, text="RMO", location=location.belowbar, transp=0)
plotshape(inputIndividualSiganlPlot and sRMO and rahulMohindarOscilllatorShortEntry, color=colorSell, style=shape.labeldown, textcolor=#ffffff,  text="RMO", location=location.abovebar, transp=0)

// TD
plot(sTD and SR?(TDbuyh ? TDbuyl: na):na,style=circles, linewidth=1, color=red)
plot(sTD and SR?(TDselll ? TDsellh : na):na,style=circles, linewidth=1, color=lime)

barColour = sell? tdSell : buy? tdBuy : sellovershoot? tdSellOvershoot : sellovershoot1? tdSellOvershoot1 : sellovershoot2?tdSellOverShoot2 : sellovershoot3? tdSellOverShoot3 : buyovershoot? tdBuyOverShoot : buyovershoot1? tdBuyOvershoot1 : buyovershoot2? tdBuyOverShoot2 : buyovershoot3? tdBuyOvershoot3 : na
barcolor(color=barColour, title ="TD Sequential ::  Bar Colour")

// ****************************************BUY/SELL Signal ***************************************************************
bull = leledecMajorBullish or strongBullishSignal or rahulMohindarOscilllatorLongEntry or bullishVFI or amaLongConditionEntry or bullTrendMagic or bullishWTI
bear =  leledecMajorBearish or bearishPSAR or strongBearishSignal or rahulMohindarOscilllatorShortEntry or bearishVFI or amaShortConditionEntry or bearTrendMagic or bearishWTI

if bull
    persistent_bull := 1
    persistent_bear := 0

if bear
    persistent_bull := 0
    persistent_bear := 1

plotshape(buySellSignal and bull and (persistent_bull[1] != 1 or bear), style=shape.labelup, location=location.belowbar, color=colorBuy, text="Buy", textcolor=#000000, transp=0)
plotshape(buySellSignal and bear and (persistent_bear[1] != 1 or bull), style=shape.labeldown, color=colorSell, text="Sell", location=location.abovebar, textcolor =#ffffff, transp=0)
// ****************************************Alerts***************************************************************
// For global buy/sell
alertcondition(bull and persistent_bull[1] != 1, title='Buy', message='Buy')
alertcondition(bear and persistent_bear[1] != 1, title='Short', message='Short')

// For WaveTrend Oscillator
alertcondition(bullishWTI, title='Bullish - WaveTrend Oscillator', message='Bullish - WaveTrend Oscillator')
alertcondition(bearishWTI, title='Bearish - WaveTrend Oscillator', message='Bearish - WaveTrend Oscillator')

// For Volume Flow Indicator
alertcondition(bullishVFI, title='Bullish - Volume Flow Indicator', message='Bullish - Volume Flow Indicator')
alertcondition(bearishVFI, title='Bearish - Volume Flow Indicator', message='Bearish - Volume Flow Indicator')

// For major Leledc Exhausion
alertcondition(leledecMajorBullish, title='Bullish - Leledec Exhausion', message='Bullish - Leledec Exhausion')
alertcondition(leledecMajorBearish, title='Bearish - Leledec Exhausion', message='Bearish - Leledec Exhausion')

// For Kaufman AMA wave
alertcondition(amaLongConditionEntry, title='Bullish - Kaufman AMA wave', message='Bullish - AMA ::  Kaufman AMA wave')
alertcondition(amaShortConditionEntry, title='Bearish - Kaufman AMA wave', message='Bearish - AMA :: Kaufman AMA wave')

// For Rahul Mohindar Oscillator
alertcondition(rahulMohindarOscilllatorLongEntry, title='Bullish - Rahul Mohindar Oscillator', message='Bullish - RMO :: Rahul Mohindar Oscillator')
alertcondition(rahulMohindarOscilllatorShortEntry, title='Bearish - Rahul Mohindar Oscillator', message='Bearish - RMO :: Rahul Mohindar Oscillator')

// For Parabolic Sar
alertcondition(bullishPSAR, title='Bullish - Sar :: Parabolic SAR', message='Bullish - Sar :: Parabolic SAR')
alertcondition(bearishPSAR, title='Bearish - Sar :: Parabolic SAR', message='Bearish - Sar :: Parabolic SAR')

// For Ichimoku
alertcondition(strongBullishSignal, title='Bullish - Ichimoku', message='Bullish Ichimoku- Ichimoku')
alertcondition(strongBearishSignal, title='Bearish - Ichimoku', message='Bearish Ichimoku - Ichimoku')

I just keep getting errors I am very new to coding please help. I think this is all in V2 but I need it in V5. Any help will be much appreciated.
I am trying to make an indicator for trading bitcoin but every time I edit something, more errors pop up and its very stressful.


问:
Implementing Sarsa(lambda) - Gridworld - in Julia language
Could you explain me what is wrong in this code ? I am trying to implement SARSA(lamda) with eligibility  traces.

```<code>using ReinforcementLearningBase, GridWorlds
using PyPlot

world = GridWorlds.GridRoomsDirectedModule.GridRoomsDirected();
env = GridWorlds.RLBaseEnv(world)

mutable struct Agent
    env::AbstractEnv
    algo::Symbol
    ϵ::Float64 # exploration coefficient
    ϵ_decay::Float64
    ϵ_min::Float64
    λ::Float64 # parametr lambda
    β::Float64 # discount factor
    α::Float64 # learning rate
    Q::Dict
    score::Int # number of times the agent reached the goal
    steps_per_episode::Vector{Float64} # average number of steps per episode
    E::Dict
end
</code>```
```<code>
function Agent(env, algo; ϵ = 1.0, ϵ_decay = 0.9975, ϵ_min = 0.005, λ=0.9,
        β = 0.99, α = 0.1)
    if algo != :SARSA && algo != :Qlearning
        @error "unknown algorithm"
    end
    Agent(env, algo,
        ϵ, ϵ_decay, ϵ_min,λ, β, α,
        Dict(), 0, [0.0,],Dict())
end

</code>```
```<code>function learn!(agent, S, A, r, S′,A′)
    if !haskey(agent.Q, S)
        agent.E[S] = zeros(length(action_space(agent.env)))
        agent.Q[S] = zeros(length(action_space(agent.env)))
        agent.Q[S][A] = r
        agent.E[S][A]=1
    else
        Q_S′ = 0.0
        haskey(agent.Q, S′) && (Q_S′ += agent.Q[S′][A′])
        Δ = r + agent.β * agent.Q[S′][A′] - agent.Q[S][A]
        agent.E[S][A]=agent.β*agent.λ*agent.E[S][A]+1
        agent.Q[S][A] += agent.α * Δ*agent.E[S][A]

    end
end
</code>```
```<code>function run_learning!(agent, steps; burning = true, animated = nothing)
    step = 1.0
    steps_per_episode = 1.0
    episode = 1.0
    if !isnothing(animated)
        global str = ""
        global str = str * "FRAME_START_DELIMITER"
        global str = str * "step: $(step)\n"
        global str = str * "episode: $(episode)\n"
        global str = str * repr(MIME"text/plain"(), env)
        global str = str * "\ntotal_reward: 0"
    end
    while step <= steps
        if (burning && step < 0.1*steps) || rand() < agent.ϵ || !haskey(agent.Q, state(agent.env))
            A = rand(1:length(action_space(agent.env)))
        else
            A = argmax(agent.Q[state(agent.env)])
        end
        S = deepcopy(state(agent.env))
        agent.env(action_space(agent.env)[A])
        r = reward(agent.env)
        S′ = deepcopy(state(agent.env))
        if agent.algo == :SARSA
            if (burning && step < 0.1 * steps) || rand() < agent.ϵ || !haskey(agent.Q, state(agent.env))
                A′ = rand(1:length(action_space(agent.env)))
            else
                A′ = argmax(agent.Q[state(agent.env)])
            end
            learn!(agent, S, A, r, S′,A′)
        else
            learn!(agent, S, A, r, S′)
        end
        if !isnothing(animated)
            global str = str * "FRAME_START_DELIMITER"
            global str = str * "step: $(step)\n"
            global str = str * "episode: $(episode)\n"
            global str = str * repr(MIME"text/plain"(), env)
            global str = str * "\ntotal_reward: $(agent.score)"
        end
        if is_terminated(agent.env)
            eps = agent.ϵ * agent.ϵ_decay
            agent.ϵ = max(agent.ϵ_min, eps)
            agent.score += 1.0
            push!(agent.steps_per_episode,
                agent.steps_per_episode[end] + (steps_per_episode - agent.steps_per_episode[end])/episode)
            episode += 1.0
            steps_per_episode = 0
            reset!(agent.env)
        end
        step += 1.0
        steps_per_episode += 1.0
    end
    if !isnothing(animated)
        write(animated * ".txt", str)
    end
end

</code>```

agent_SARSA = Agent(env,:SARSA);

run_learning!(agent_SARSA, 2500)
@info "agent score: $(agent_SARSA.score)"

after running the code I receive such info, but i don't uderstand why.

```<code>KeyError: key ([0 0 … 0 0; 1 1 … 1 1; 0 0 … 0 0;;; 0 0 … 0 0; 1 0 … 0 1; 0 0 … 0 0;;; 0 0 … 0 0; 1 0 … 0 1; 0 0 … 0 0;;; 0 0 … 1 0; 1 0 … 0 1; 0 0 … 0 0;;; 0 0 … 0 0; 1 1 … 1 1; 0 0 … 0 0;;; 0 0 … 0 0; 1 0 … 0 1; 0 0 … 0 0;;; 0 0 … 0 0; 1 0 … 0 1; 0 0 … 0 0;;; 0 0 … 0 0; 1 0 … 0 1; 0 0 … 0 0;;; 0 0 … 0 0; 1 1 … 1 1; 0 0 … 0 0], 1) not found

Stacktrace:
 [1] getindex(h::Dict{Any, Any}, key::Tuple{BitArray{3}, Int64})
   @ Base .\dict.jl:498
 [2] learn!(agent::Agent, S::Tuple{BitArray{3}, Int64}, A::Int64, r::Float32, S′::Tuple{BitArray{3}, Int64}, A′::Int64)
   @ Main .\In[44]:10
 [3] run_learning!(agent::Agent, steps::Int64; burning::Bool, animated::Nothing)
   @ Main .\In[45]:31
 [4] run_learning!(agent::Agent, steps::Int64)
   @ Main .\In[45]:1
 [5] top-level scope
   @ In[51]:1
 [6] eval
   @ .\boot.jl:368 [inlined]
 [7] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base .\loading.jl:1428

</code>```

I have tried manipulating with Dictionary but without any succes.

Body:
Could you explain me what is wrong in this code ? I am trying to implement SARSA(lamda) with eligibility  traces.

using ReinforcementLearningBase, GridWorlds
using PyPlot

world = GridWorlds.GridRoomsDirectedModule.GridRoomsDirected();
env = GridWorlds.RLBaseEnv(world)

mutable struct Agent
    env::AbstractEnv
    algo::Symbol
    ϵ::Float64 # exploration coefficient
    ϵ_decay::Float64
    ϵ_min::Float64
    λ::Float64 # parametr lambda
    β::Float64 # discount factor
    α::Float64 # learning rate
    Q::Dict
    score::Int # number of times the agent reached the goal
    steps_per_episode::Vector{Float64} # average number of steps per episode
    E::Dict
end

function Agent(env, algo; ϵ = 1.0, ϵ_decay = 0.9975, ϵ_min = 0.005, λ=0.9,
        β = 0.99, α = 0.1)
    if algo != :SARSA && algo != :Qlearning
        @error "unknown algorithm"
    end
    Agent(env, algo,
        ϵ, ϵ_decay, ϵ_min,λ, β, α,
        Dict(), 0, [0.0,],Dict())
end

function learn!(agent, S, A, r, S′,A′)
    if !haskey(agent.Q, S)
        agent.E[S] = zeros(length(action_space(agent.env)))
        agent.Q[S] = zeros(length(action_space(agent.env)))
        agent.Q[S][A] = r
        agent.E[S][A]=1
    else
        Q_S′ = 0.0
        haskey(agent.Q, S′) && (Q_S′ += agent.Q[S′][A′])
        Δ = r + agent.β * agent.Q[S′][A′] - agent.Q[S][A]
        agent.E[S][A]=agent.β*agent.λ*agent.E[S][A]+1
        agent.Q[S][A] += agent.α * Δ*agent.E[S][A]

    end
end

function run_learning!(agent, steps; burning = true, animated = nothing)
    step = 1.0
    steps_per_episode = 1.0
    episode = 1.0
    if !isnothing(animated)
        global str = ""
        global str = str * "FRAME_START_DELIMITER"
        global str = str * "step: $(step)\n"
        global str = str * "episode: $(episode)\n"
        global str = str * repr(MIME"text/plain"(), env)
        global str = str * "\ntotal_reward: 0"
    end
    while step <= steps
        if (burning && step < 0.1*steps) || rand() < agent.ϵ || !haskey(agent.Q, state(agent.env))
            A = rand(1:length(action_space(agent.env)))
        else
            A = argmax(agent.Q[state(agent.env)])
        end
        S = deepcopy(state(agent.env))
        agent.env(action_space(agent.env)[A])
        r = reward(agent.env)
        S′ = deepcopy(state(agent.env))
        if agent.algo == :SARSA
            if (burning && step < 0.1 * steps) || rand() < agent.ϵ || !haskey(agent.Q, state(agent.env))
                A′ = rand(1:length(action_space(agent.env)))
            else
                A′ = argmax(agent.Q[state(agent.env)])
            end
            learn!(agent, S, A, r, S′,A′)
        else
            learn!(agent, S, A, r, S′)
        end
        if !isnothing(animated)
            global str = str * "FRAME_START_DELIMITER"
            global str = str * "step: $(step)\n"
            global str = str * "episode: $(episode)\n"
            global str = str * repr(MIME"text/plain"(), env)
            global str = str * "\ntotal_reward: $(agent.score)"
        end
        if is_terminated(agent.env)
            eps = agent.ϵ * agent.ϵ_decay
            agent.ϵ = max(agent.ϵ_min, eps)
            agent.score += 1.0
            push!(agent.steps_per_episode,
                agent.steps_per_episode[end] + (steps_per_episode - agent.steps_per_episode[end])/episode)
            episode += 1.0
            steps_per_episode = 0
            reset!(agent.env)
        end
        step += 1.0
        steps_per_episode += 1.0
    end
    if !isnothing(animated)
        write(animated * ".txt", str)
    end
end

agent_SARSA = Agent(env,:SARSA);

run_learning!(agent_SARSA, 2500)
@info "agent score: $(agent_SARSA.score)"

after running the code I receive such info, but i don't uderstand why.

KeyError: key ([0 0 … 0 0; 1 1 … 1 1; 0 0 … 0 0;;; 0 0 … 0 0; 1 0 … 0 1; 0 0 … 0 0;;; 0 0 … 0 0; 1 0 … 0 1; 0 0 … 0 0;;; 0 0 … 1 0; 1 0 … 0 1; 0 0 … 0 0;;; 0 0 … 0 0; 1 1 … 1 1; 0 0 … 0 0;;; 0 0 … 0 0; 1 0 … 0 1; 0 0 … 0 0;;; 0 0 … 0 0; 1 0 … 0 1; 0 0 … 0 0;;; 0 0 … 0 0; 1 0 … 0 1; 0 0 … 0 0;;; 0 0 … 0 0; 1 1 … 1 1; 0 0 … 0 0], 1) not found

Stacktrace:
 [1] getindex(h::Dict{Any, Any}, key::Tuple{BitArray{3}, Int64})
   @ Base .\dict.jl:498
 [2] learn!(agent::Agent, S::Tuple{BitArray{3}, Int64}, A::Int64, r::Float32, S′::Tuple{BitArray{3}, Int64}, A′::Int64)
   @ Main .\In[44]:10
 [3] run_learning!(agent::Agent, steps::Int64; burning::Bool, animated::Nothing)
   @ Main .\In[45]:31
 [4] run_learning!(agent::Agent, steps::Int64)
   @ Main .\In[45]:1
 [5] top-level scope
   @ In[51]:1
 [6] eval
   @ .\boot.jl:368 [inlined]
 [7] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base .\loading.jl:1428

I have tried manipulating with Dictionary but without any succes.