问:
Create a reusable layout component with multiple columns
I have a reusable layout component accepting children as props. This way I can separate the components needed for each page in a separate file as shown in the example below:

// Layout.jsx

function Main({ children }) {
  return (

      {children}

  );
}

function Side({ children }) {
  return (

      {children}

  );
}

function Layout({ children }) {
  return (

      {children}

  );
}

Layout.Main = Main;
Layout.Side = Side;

export default Layout;
```
<pre class="lang-js prettyprint-override"><code>// Home.jsx

function Home() {
  return (
    <Layout>
      <Layout.Main>
        foo
      </Layout.Main>

      <Layout.Side>
        bar
      </Layout.Side>
    </Layout>
  );
}

export default Home;
</code>```

This works pretty well, but now I want to add a component which is shown in all of the Layout pages. The problem is, this component is animated so when it's added to the Layout component, it will rerender everytime the page changes.

I want to keep my code between my pages separated but still want to use the Layout component and use the animated component. How can I do this?

// Home.jsx

function Home() {
  return (
    <Layout>
      <Layout.Main>
        {/* This component moves from x to y depending on the url */}
        <ComponentWithAnimation />

        <Home.mainColumn.components />
      </Layout.Main>

      <Layout.Side>
        <Home.sideColumn.components />
      </Layout.Side>
    </Layout>
  );
}

export default Home;
```
<pre class="lang-js prettyprint-override"><code>// Other.jsx

function Other() {
  return (
    <Layout>
      <Layout.Main>
        {/* This component moves from x to y depending on the url */}
        <ComponentWithAnimation />

        <Other.mainColumn.components />
      </Layout.Main>

      <Layout.Side>
        <Other.sideColumn.components />
      </Layout.Side>
    </Layout>
  );
}

export default Other;
</code>```

In the example above, instead of having the ComponentWithAnimation animate to y, it starts immediately at y. I could add logic to add a starting position to the last location, but I was wondering if there's a solution using a layout.

Body:
I have a reusable layout component accepting children as props. This way I can separate the components needed for each page in a separate file as shown in the example below:

// Layout.jsx

function Main({ children }) {
  return (

      {children}

  );
}

function Side({ children }) {
  return (

      {children}

  );
}

function Layout({ children }) {
  return (

      {children}

  );
}

Layout.Main = Main;
Layout.Side = Side;

export default Layout;

// Home.jsx

function Home() {
  return (
    <Layout>
      <Layout.Main>
        foo
      </Layout.Main>

      <Layout.Side>
        bar
      </Layout.Side>
    </Layout>
  );
}

export default Home;

This works pretty well, but now I want to add a component which is shown in all of the Layout pages. The problem is, this component is animated so when it's added to the Layout component, it will rerender everytime the page changes.

I want to keep my code between my pages separated but still want to use the Layout component and use the animated component. How can I do this?

// Home.jsx

function Home() {
  return (
    <Layout>
      <Layout.Main>
        {/* This component moves from x to y depending on the url */}
        <ComponentWithAnimation />

        <Home.mainColumn.components />
      </Layout.Main>

      <Layout.Side>
        <Home.sideColumn.components />
      </Layout.Side>
    </Layout>
  );
}

export default Home;

// Other.jsx

function Other() {
  return (
    <Layout>
      <Layout.Main>
        {/* This component moves from x to y depending on the url */}
        <ComponentWithAnimation />

        <Other.mainColumn.components />
      </Layout.Main>

      <Layout.Side>
        <Other.sideColumn.components />
      </Layout.Side>
    </Layout>
  );
}

export default Other;

In the example above, instead of having the ComponentWithAnimation animate to y, it starts immediately at y. I could add logic to add a starting position to the last location, but I was wondering if there's a solution using a layout.


来源: stackexchange

问:
"Content-Encoding: gzip" HTTP response header unity webgl error
I keep on getting this error and don't know what to do. Please help!

Unable to parse Build/WebGL.framework.js.gz! This can happen if build compression was enabled but web server hosting the content was misconfigured to not serve the file with HTTP Response Header "Content-Encoding: gzip" present. Check browser Console and Devtools Network tab to debug.

BTW i"m using Firefox

I can't find anything that will help me, and I tried reading documentation, but nothing!

ContentLicense: CC BY-SA 4.0


问:
Ranking across multiple grouping columns in R
I'm a relatively new R user. I would like to determine the rank of each cause of death by examing the pct_of_deaths for each year and sex. When I run this reprex it doesn't rank in the way I would expect. Because the pct_of_deaths for cancer is higher, I would expect it to be ranked as 1. I have tried this a number of ways including reordering the arrange variables with various results. Thanks in advance for the help.

Expecting cancer to be ranked 1 for Male, Female, and Total for 2016 and 2017. See desired below.

```<code>do <- data.frame(
  year = c("2016","2016","2016", "2016", "2016","2016","2017", "2017","2017","2017", "2017", "2017"),
  sex = c("Male", "Female", "Total","Male", "Female", "Total","Male", "Female", "Total","Male", "Female", "Total"),
  cause = c("cancer","cancer","cancer","stroke","stroke","stroke", "cancer","cancer","cancer","stroke","stroke","stroke"),
  pct_of_deaths = c(20,24,23,14,18,15,22,20,21,17,15,16), stringsAsFactors = FALSE)

do2 <- do %>% arrange(year,sex,pct_of_deaths) %>%
  group_by(year,sex) %>%
  mutate(cod_rank = rank(pct_of_deaths)) %>%
  ungroup()
</code>```
```<code># A tibble: 12 × 5
   year  sex    cause  pct_of_deaths cod_rank
   <chr> <chr>  <chr>          <dbl>    <dbl>
 1 2016  Female stroke            18        1
 2 2016  Female cancer            24        2
 3 2016  Male   stroke            14        1
 4 2016  Male   cancer            20        2
 5 2016  Total  stroke            15        1
 6 2016  Total  cancer            23        2
 7 2017  Female stroke            15        1
 8 2017  Female cancer            20        2
 9 2017  Male   stroke            17        1
10 2017  Male   cancer            22        2
11 2017  Total  stroke            16        1
12 2017  Total  cancer            21        2
>
</code>```

Desired

year    sex     cause   pct_of_deaths   rank
2016    Female  cancer  24  1
2016    Male    cancer  20  1
2016    Total   cancer  23  1
2016    Female  stroke  18  2
2016    Male    stroke  14  2
2016    Total   stroke  15  2
2017    Female  cancer  20  1
2017    Male    cancer  22  1
2017    Total   cancer  21  1
2017    Female  stroke  15  2
2017    Male    stroke  17  2
2017    Total   stroke  16  2

Body:
I'm a relatively new R user. I would like to determine the rank of each cause of death by examing the pct_of_deaths for each year and sex. When I run this reprex it doesn't rank in the way I would expect. Because the pct_of_deaths for cancer is higher, I would expect it to be ranked as 1. I have tried this a number of ways including reordering the arrange variables with various results. Thanks in advance for the help.

Expecting cancer to be ranked 1 for Male, Female, and Total for 2016 and 2017. See desired below.

do <- data.frame(
  year = c("2016","2016","2016", "2016", "2016","2016","2017", "2017","2017","2017", "2017", "2017"),
  sex = c("Male", "Female", "Total","Male", "Female", "Total","Male", "Female", "Total","Male", "Female", "Total"),
  cause = c("cancer","cancer","cancer","stroke","stroke","stroke", "cancer","cancer","cancer","stroke","stroke","stroke"),
  pct_of_deaths = c(20,24,23,14,18,15,22,20,21,17,15,16), stringsAsFactors = FALSE)

do2 <- do %>% arrange(year,sex,pct_of_deaths) %>%
  group_by(year,sex) %>%
  mutate(cod_rank = rank(pct_of_deaths)) %>%
  ungroup()

# A tibble: 12 × 5
   year  sex    cause  pct_of_deaths cod_rank
   <chr> <chr>  <chr>          <dbl>    <dbl>
 1 2016  Female stroke            18        1
 2 2016  Female cancer            24        2
 3 2016  Male   stroke            14        1
 4 2016  Male   cancer            20        2
 5 2016  Total  stroke            15        1
 6 2016  Total  cancer            23        2
 7 2017  Female stroke            15        1
 8 2017  Female cancer            20        2
 9 2017  Male   stroke            17        1
10 2017  Male   cancer            22        2
11 2017  Total  stroke            16        1
12 2017  Total  cancer            21        2
>

Desired

year    sex     cause   pct_of_deaths   rank
2016    Female  cancer  24  1
2016    Male    cancer  20  1
2016    Total   cancer  23  1
2016    Female  stroke  18  2
2016    Male    stroke  14  2
2016    Total   stroke  15  2
2017    Female  cancer  20  1
2017    Male    cancer  22  1
2017    Total   cancer  21  1
2017    Female  stroke  15  2
2017    Male    stroke  17  2
2017    Total   stroke  16  2


问:
how to handle a unhandled key code qt android
im trying to handle when a button is pressed but isn't handled by QT

on main qml file have this code

```<code>Keys.onPressed: {
        console.log(event.key);

        if(event.key === 302){
            console.log("hello world");
        }
    }
</code>```

but on console show me the next error:

bDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

Body:
im trying to handle when a button is pressed but isn't handled by QT

on main qml file have this code

Keys.onPressed: {
        console.log(event.key);

        if(event.key === 302){
            console.log("hello world");
        }
    }

but on console show me the next error:

bDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !

W libDroidStar_arm64-v8a.so: Unhandled key code  302 !


问:
How to handle React requests that don't match "basename"?
Can I add some sort of Handler to my React Router to forward or redirect a URL like https://example.com/a/b;planId=TPM-123 to https://example.com/a/b/instance/TPM-123.

Today, when react runs localhost, the Chrome Console records these URLs as failures like...

```<code><Router basename="/a/b"> is not able to match the URL "/a/b;planId=TPM-123" because it does not start with the basename, so the <Router> won't render anything.
</code>```

Can I put some handling on the Router to catch these and redirect? I really can't change basename...

```<code>...
export const AppRoutes: React.FunctionComponent = () => (
  <Routes>
    ...
    <Route
      path="/instance/:planId"
      element={<TpmPlanInstance />}
    />
    ...
    <Route
      path="*"
      element={
        <BackwardsCompSemiColonParams defaultRedirectPath="/search" />
      }
    />
  </Routes>
);
...
  return (
    <Router basename="/a/b">
      <MatomoRouterTracker />
      <GlobalErrors />
      <AppRoutes />
      # is there something I can add here to rewrite the URL and redirct onto basename?
    </Router>
  );
</code>```

Because these strange "semi-colon delimited parameters" exist on the basename, they can't be handled by the Routes themselves. They never make it to the Route.path="*" we already have.

Alternatively...is there a way to "express" multiple Routers? Like one Router basename="/a/b" and one Router basename="/a/b;planId="?

How do I get the bizarre semi-colon delimited URL into my Routes on a React App?

Body:
Can I add some sort of Handler to my React Router to forward or redirect a URL like https://example.com/a/b;planId=TPM-123 to https://example.com/a/b/instance/TPM-123.

Today, when react runs localhost, the Chrome Console records these URLs as failures like...

<Router basename="/a/b"> is not able to match the URL "/a/b;planId=TPM-123" because it does not start with the basename, so the <Router> won't render anything.

Can I put some handling on the Router to catch these and redirect? I really can't change basename...

...
export const AppRoutes: React.FunctionComponent = () => (
  <Routes>
    ...
    <Route
      path="/instance/:planId"
      element={<TpmPlanInstance />}
    />
    ...
    <Route
      path="*"
      element={
        <BackwardsCompSemiColonParams defaultRedirectPath="/search" />
      }
    />
  </Routes>
);
...
  return (
    <Router basename="/a/b">
      <MatomoRouterTracker />
      <GlobalErrors />
      <AppRoutes />
      # is there something I can add here to rewrite the URL and redirct onto basename?
    </Router>
  );

Because these strange "semi-colon delimited parameters" exist on the basename, they can't be handled by the Routes themselves. They never make it to the Route.path="*" we already have.

Alternatively...is there a way to "express" multiple Routers? Like one Router basename="/a/b" and one Router basename="/a/b;planId="?

How do I get the bizarre semi-colon delimited URL into my Routes on a React App?


问:
How can i access all table row in DataTable
I'm trying to select all the table row, but i can only access all rows which shown in the current page of the DataTable

(I'm using table row class attr to access).

Is there any way to access all row in all pages in DataTable?

Here's what i tried and it can only select all rows in current page

```<code>   $("#uploadAllDataNewHired").click(function () {
      var tableRow = $(".rowArray");
   })
</code>```

Body:
I'm trying to select all the table row, but i can only access all rows which shown in the current page of the DataTable

(I'm using table row class attr to access).

Is there any way to access all row in all pages in DataTable?

Here's what i tried and it can only select all rows in current page

   $("#uploadAllDataNewHired").click(function () {
      var tableRow = $(".rowArray");
   })


问:
Cucumber: undefined method `<<' for hash
When I was running cucumber tests, I got the following error:

```<code>undefined method `<<' for #<Hash:0x00007fc100cc5218>
      Did you mean?  < (NoMethodError)
</code>```

My gem file:

```<code>group :development, :test do
  gem 'spring', '3.1.1'

  gem 'rspec-rails', '~> 4.0.0'
  gem 'guard-rspec'

  gem 'rspec_junit_formatter'
  gem 'database_cleaner', '1.6.0'

  gem 'rails-controller-testing'

  gem 'factory_girl_rails'
end

group :test do

  gem 'capybara', '2.7.1'
  gem 'capybara-webkit'
  gem 'selenium-webdriver', '2.53.0'
  gem 'chromedriver-helper'

  gem 'cucumber-rails', require: false

  gem 'shoulda-matchers', git: 'https://github.com/thoughtbot/shoulda-matchers'

  gem 'timecop', '0.3.5'
end
</code>```

Code to run the test:

```<code>Given /^ Something $/ do
  user = FactoryGirl.create(:user)

  visit '/'

  fill_in 'User', with: user
end
</code>```

I found that when I tried to run

```<code>fill_in 'User', with: user
</code>```

in test files, it returned a hash, which is nil, rather than an empty string ""

I guess it's because there is no method << for a hash, but I don't know how that does happen

Thank you very much

Body:
When I was running cucumber tests, I got the following error:

undefined method `<<' for #<Hash:0x00007fc100cc5218>
      Did you mean?  < (NoMethodError)

My gem file:

group :development, :test do
  gem 'spring', '3.1.1'

  gem 'rspec-rails', '~> 4.0.0'
  gem 'guard-rspec'

  gem 'rspec_junit_formatter'
  gem 'database_cleaner', '1.6.0'

  gem 'rails-controller-testing'

  gem 'factory_girl_rails'
end

group :test do

  gem 'capybara', '2.7.1'
  gem 'capybara-webkit'
  gem 'selenium-webdriver', '2.53.0'
  gem 'chromedriver-helper'

  gem 'cucumber-rails', require: false

  gem 'shoulda-matchers', git: 'https://github.com/thoughtbot/shoulda-matchers'

  gem 'timecop', '0.3.5'
end

Code to run the test:

Given /^ Something $/ do
  user = FactoryGirl.create(:user)

  visit '/'

  fill_in 'User', with: user
end

I found that when I tried to run

fill_in 'User', with: user

in test files, it returned a hash, which is nil, rather than an empty string ""

I guess it's because there is no method << for a hash, but I don't know how that does happen

Thank you very much


问:
git -- correlate commit with branch
I need to correlate each commit with the branch it is in.  The only thing I have found that does this so far is "git show-branch" ... but this has problems with "cannot handle more than 25 refs" if there are more than 25 branches.   I inherited this repo, and can not prune branches until I have an idea what commits have been duplicated in other branches, so I can not reduce the number of branches below the current 30 for now.  Is there any other way to get a listing of all of the commits that identifies which branch the commit belongs to (e.g. some argument for git log --format)?</p>

Title: git -- correlate commit with branch


问:
Avoid testsuite embedding code-under-test with browserify
I have inherited a project whose tests are compiled (with babeljs-7) from ES6 to ES5 first, then bundled (with browserify) into a huge .js file, which is then run under PhantomJS. Unfortunately, I barely know ES3? ES5?

This complex process however embeds the code-under-test into that huge .js file as well because of lines like import Dygraph from '../../src/dygraph'; which is unfortunate and additionally prevents testing e.g. the minified js bundle. (This is just one example; basically all imports from ../../src/ must go away… and I think I’d also prefer to load those from ../../src/extras/ separately, as that’s what browsers in prod do.)

How do I split things up so that I can add the code-under-test into the runner as a separate  tag, like things do in production, and the tests will require the runner to do that and stop embedding the code-under-test, without breaking the babeljs and browserify chains? I can then do the remaining splitting like optionally test the minified code and accounting for the stripping of some debug functionality in it.


问:
Why my MQL5 indicator is displaying one moving average instead of two?
I took the code of VIDYA from the examples library of MQL5 and added a second moving average to it; basically, another VIDYA line.

The newly created code is compiling without errors or warnings but only one moving average (VIDYA) is being displayed on the chart instead of two. It seems I am missing something. Your help will be much appreciated!

```<code>#property copyright   "2009-2020, MetaQuotes Software Corp."
#property link        "http://www.mql5.com"
#property description "Double Variable Index Dynamic Average"

//--- indicator settings

#property indicator_chart_window
#property indicator_buffers    2
#property indicator_plots      2

#property indicator_type1      DRAW_LINE
#property indicator_color1     Navy
#property indicator_width1     3
#property indicator_label1     "VIDYA 1"

#property indicator_type2      DRAW_LINE
#property indicator_color2     Navy
#property indicator_width2     3
#property indicator_label2     "VIDYA 2"

#property indicator_applied_price  PRICE_MEDIAN

//--- input parameters
input int InpPeriodCMO = 9;   // Period CMO
input int InpPeriodEMA = 12;  // Period EMA
input int InpShift     = 0;   // Indicator's shift

//--- indicator buffer
double VIDYA_Buffer_1[];
double VIDYA_Buffer_2[];

double ExtF; // smooth factor
//+------------------------------------------------------------------+
//| Custom indicator initialization function             |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
  SetIndexBuffer(0, VIDYA_Buffer_1, INDICATOR_DATA);
  SetIndexBuffer(1, VIDYA_Buffer_2, INDICATOR_DATA);

//--- sets first bar from what index will be drawn
  PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpPeriodEMA+InpPeriodCMO-1);
  PlotIndexSetInteger(1, PLOT_DRAW_BEGIN, InpPeriodEMA+InpPeriodCMO-1);

//--- sets indicator shift
  PlotIndexSetInteger(0, PLOT_SHIFT, InpShift);
  PlotIndexSetInteger(1, PLOT_SHIFT, InpShift);

//--- name for indicator label
  string short_name = StringFormat("VIDYA(%d,%d)", InpPeriodCMO, InpPeriodEMA);

  IndicatorSetString(INDICATOR_SHORTNAME,short_name);
  PlotIndexSetString(0, PLOT_LABEL, short_name+"1");
  PlotIndexSetString(1, PLOT_LABEL, short_name+"2");

//--- calculate smooth factor
  ExtF = 2.0/(1.0+InpPeriodEMA);
}
//+------------------------------------------------------------------+
//| Variable Index Dynamic Average                  |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
        const int prev_calculated,
        const int begin,
        const double &price[])
{
  if(rates_total < InpPeriodEMA+InpPeriodCMO-1)
    return(0);
//---
  int i,start;
  if(prev_calculated < InpPeriodEMA+InpPeriodCMO-1)
  {
    start = InpPeriodEMA+InpPeriodCMO-1;
    for(i = 0; i<start; i++)
    {
      VIDYA_Buffer_1[i] = price[i];
      VIDYA_Buffer_2[i] = price[i];
    }
  }
  else
    start = prev_calculated-1;
//--- main cycle
  for(i = start; i<rates_total && !IsStopped(); i++)
  {
    double mul_CMO = MathAbs(CalculateCMO(i,InpPeriodCMO,price));
    //--- calculate VIDYA 1 & 2
    VIDYA_Buffer_1[i] = price[i]*ExtF*mul_CMO+VIDYA_Buffer_1[i-1]*(1-ExtF*mul_CMO)*1;
    VIDYA_Buffer_2[i] = price[i]*ExtF*mul_CMO+VIDYA_Buffer_2[i-1]*(1-ExtF*mul_CMO)*2;
  }
//--- OnCalculate done. Return new prev_calculated.
  return(rates_total);
}
//+------------------------------------------------------------------+
//| Chande Momentum Oscillator                    |
//+------------------------------------------------------------------+
double CalculateCMO(int pos,const int period,const double &price[])
{
  double res = 0.0;
  double sum_up = 0.0,sum_down = 0.0;
//---
  if(pos >= period && pos<ArraySize(price))
  {
    for(int i = 0; i<period; i++)
    {
      double diff = price[pos-i]-price[pos-i-1];
      if(diff>0.0)
        sum_up += diff;
      else
        sum_down += (-diff);
    }
    if(sum_up+sum_down != 0.0)
      res = (sum_up-sum_down)/(sum_up+sum_down);
  }
//---
  return(res);
}
</code>```

Body:
I took the code of VIDYA from the examples library of MQL5 and added a second moving average to it; basically, another VIDYA line.

The newly created code is compiling without errors or warnings but only one moving average (VIDYA) is being displayed on the chart instead of two. It seems I am missing something. Your help will be much appreciated!

#property copyright   "2009-2020, MetaQuotes Software Corp."
#property link        "http://www.mql5.com"
#property description "Double Variable Index Dynamic Average"

//--- indicator settings

#property indicator_chart_window
#property indicator_buffers    2
#property indicator_plots      2

#property indicator_type1      DRAW_LINE
#property indicator_color1     Navy
#property indicator_width1     3
#property indicator_label1     "VIDYA 1"

#property indicator_type2      DRAW_LINE
#property indicator_color2     Navy
#property indicator_width2     3
#property indicator_label2     "VIDYA 2"

#property indicator_applied_price  PRICE_MEDIAN

//--- input parameters
input int InpPeriodCMO = 9;   // Period CMO
input int InpPeriodEMA = 12;  // Period EMA
input int InpShift     = 0;   // Indicator's shift

//--- indicator buffer
double VIDYA_Buffer_1[];
double VIDYA_Buffer_2[];

double ExtF; // smooth factor
//+------------------------------------------------------------------+
//| Custom indicator initialization function             |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
  SetIndexBuffer(0, VIDYA_Buffer_1, INDICATOR_DATA);
  SetIndexBuffer(1, VIDYA_Buffer_2, INDICATOR_DATA);

//--- sets first bar from what index will be drawn
  PlotIndexSetInteger(0, PLOT_DRAW_BEGIN, InpPeriodEMA+InpPeriodCMO-1);
  PlotIndexSetInteger(1, PLOT_DRAW_BEGIN, InpPeriodEMA+InpPeriodCMO-1);

//--- sets indicator shift
  PlotIndexSetInteger(0, PLOT_SHIFT, InpShift);
  PlotIndexSetInteger(1, PLOT_SHIFT, InpShift);

//--- name for indicator label
  string short_name = StringFormat("VIDYA(%d,%d)", InpPeriodCMO, InpPeriodEMA);

  IndicatorSetString(INDICATOR_SHORTNAME,short_name);
  PlotIndexSetString(0, PLOT_LABEL, short_name+"1");
  PlotIndexSetString(1, PLOT_LABEL, short_name+"2");

//--- calculate smooth factor
  ExtF = 2.0/(1.0+InpPeriodEMA);
}
//+------------------------------------------------------------------+
//| Variable Index Dynamic Average                  |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
        const int prev_calculated,
        const int begin,
        const double &price[])
{
  if(rates_total < InpPeriodEMA+InpPeriodCMO-1)
    return(0);
//---
  int i,start;
  if(prev_calculated < InpPeriodEMA+InpPeriodCMO-1)
  {
    start = InpPeriodEMA+InpPeriodCMO-1;
    for(i = 0; i<start; i++)
    {
      VIDYA_Buffer_1[i] = price[i];
      VIDYA_Buffer_2[i] = price[i];
    }
  }
  else
    start = prev_calculated-1;
//--- main cycle
  for(i = start; i<rates_total && !IsStopped(); i++)
  {
    double mul_CMO = MathAbs(CalculateCMO(i,InpPeriodCMO,price));
    //--- calculate VIDYA 1 & 2
    VIDYA_Buffer_1[i] = price[i]*ExtF*mul_CMO+VIDYA_Buffer_1[i-1]*(1-ExtF*mul_CMO)*1;
    VIDYA_Buffer_2[i] = price[i]*ExtF*mul_CMO+VIDYA_Buffer_2[i-1]*(1-ExtF*mul_CMO)*2;
  }
//--- OnCalculate done. Return new prev_calculated.
  return(rates_total);
}
//+------------------------------------------------------------------+
//| Chande Momentum Oscillator                    |
//+------------------------------------------------------------------+
double CalculateCMO(int pos,const int period,const double &price[])
{
  double res = 0.0;
  double sum_up = 0.0,sum_down = 0.0;
//---
  if(pos >= period && pos<ArraySize(price))
  {
    for(int i = 0; i<period; i++)
    {
      double diff = price[pos-i]-price[pos-i-1];
      if(diff>0.0)
        sum_up += diff;
      else
        sum_down += (-diff);
    }
    if(sum_up+sum_down != 0.0)
      res = (sum_up-sum_down)/(sum_up+sum_down);
  }
//---
  return(res);
}


问:
Undeclared identifier with definition in header file
include "spinach.h" is included in the main.c file

main.c makes a function call to a struct defined in spinach.h header. The function call occurs in the main.c function, and is the first reference to this type Lexer. The main.c file runs without error absent this line.

```<code>  Lexer *lex = malloc(sizeof(Lexer));

</code>```

The definition is on the 0 indentation level (it is not defined in local scope); it is given below in triple quotes. In the header (spinach.h)

```<code>typedef struct {
  char **lines;
  char* current;
  int pos;
  int line;
  int col;

  int* indentlevel;
  int indentcap;
  int indentlen;
} Lexer;
</code>```

What happpens?

```<code> bash run.sh
main.c:115:3: error: use of undeclared identifier 'Lexer'
  Lexer *lex;
  ^
main.c:115:10: error: use of undeclared identifier 'lex'
  Lexer *lex;
         ^
2 errors generated.
</code>```

Any variation that includes Lexer, including using pointers, references to malloc or the output of a custom initializer function will throw related errors.

Looked for multiple references (same global variable in 2 files in main.py references) to Lexer. All references on the internet are examples wherein the header file is not included, the variable or function is defined after the reference or call, or is absent entirely, else the error will show where there shows a reference in a global scope to a local definition. I do not see this to be the case. All references to custom struct lever in the main.c file, main function will throw this error. If the definitions are placed in the main.c file itself, instead of the header spinach.h referenced, it runs without error.

Body:
include "spinach.h" is included in the main.c file

main.c makes a function call to a struct defined in spinach.h header. The function call occurs in the main.c function, and is the first reference to this type Lexer. The main.c file runs without error absent this line.

  Lexer *lex = malloc(sizeof(Lexer));

The definition is on the 0 indentation level (it is not defined in local scope); it is given below in triple quotes. In the header (spinach.h)

typedef struct {
  char **lines;
  char* current;
  int pos;
  int line;
  int col;

  int* indentlevel;
  int indentcap;
  int indentlen;
} Lexer;

What happpens?

 bash run.sh
main.c:115:3: error: use of undeclared identifier 'Lexer'
  Lexer *lex;
  ^
main.c:115:10: error: use of undeclared identifier 'lex'
  Lexer *lex;
         ^
2 errors generated.

Any variation that includes Lexer, including using pointers, references to malloc or the output of a custom initializer function will throw related errors.

Looked for multiple references (same global variable in 2 files in main.py references) to Lexer. All references on the internet are examples wherein the header file is not included, the variable or function is defined after the reference or call, or is absent entirely, else the error will show where there shows a reference in a global scope to a local definition. I do not see this to be the case. All references to custom struct lever in the main.c file, main function will throw this error. If the definitions are placed in the main.c file itself, instead of the header spinach.h referenced, it runs without error.


问:
How to save images in NedB database and be able to show it in the frontend
I'm working on a recipe website with React and using NedB as the database.
For each recipe, I want to store an image that I can retrieve later to be able to show it on the website but can't find any resources online to know how to do it.

This is my current code for initializing the database and inserting the elements in it

```<code>const nedb = require("nedb");

class Recipes {
  constructor(recipeFilePath) {
    console.log(recipeFilePath);
    if (recipeFilePath) {
      this.recipes = new nedb(recipeFilePath);
      console.log("recipes connected to " + recipeFilePath);
      recipeFilePath;
    } else {
      this.recipes = new nedb();
    }
  }

  init() {
    this.recipes.insert({
      id: "1",
      name: "carrot cake",
      description: "home made here",
      category: "cake",
      prep_time: 20,
      cook_time: 30,
      serving: 4,
      ingredients: [],
      rating: [],
      photo_location:""
    });

    this.recipes.insert({
      id: "1",
      name: "carrot cake",
      description: "home made here",
      category: "cake",
      prep_time: 20,
      cook_time: 30,
      serving: 4,
      ingredients: [],
      photo_location:""
    });
  }

  getAllEntries() {
    return new Promise((resolve, reject) => {
      this.recipes.find({}, function (err, entries) {
        if (err) {
          reject(err);
        } else {
          resolve(entries);
          console.log("function all() returns: ", entries);
        }
      });
    });
  }

}
module.exports = Recipes;
</code>```

Can anyone elaborate on how to store images?

Body:
I'm working on a recipe website with React and using NedB as the database.
For each recipe, I want to store an image that I can retrieve later to be able to show it on the website but can't find any resources online to know how to do it.

This is my current code for initializing the database and inserting the elements in it

const nedb = require("nedb");

class Recipes {
  constructor(recipeFilePath) {
    console.log(recipeFilePath);
    if (recipeFilePath) {
      this.recipes = new nedb(recipeFilePath);
      console.log("recipes connected to " + recipeFilePath);
      recipeFilePath;
    } else {
      this.recipes = new nedb();
    }
  }

  init() {
    this.recipes.insert({
      id: "1",
      name: "carrot cake",
      description: "home made here",
      category: "cake",
      prep_time: 20,
      cook_time: 30,
      serving: 4,
      ingredients: [],
      rating: [],
      photo_location:""
    });

    this.recipes.insert({
      id: "1",
      name: "carrot cake",
      description: "home made here",
      category: "cake",
      prep_time: 20,
      cook_time: 30,
      serving: 4,
      ingredients: [],
      photo_location:""
    });
  }

  getAllEntries() {
    return new Promise((resolve, reject) => {
      this.recipes.find({}, function (err, entries) {
        if (err) {
          reject(err);
        } else {
          resolve(entries);
          console.log("function all() returns: ", entries);
        }
      });
    });
  }

}
module.exports = Recipes;

Can anyone elaborate on how to store images?


问:
shinyCAPTCHA does not trigger the validation properly
I would like to integrate captcha verification into my shiny app (like this). But it has an unexpected behavior.

If this line:

```<code>recaptchaUI("test", sitekey = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI")
</code>```

is inside the UI, my app works fine (I mean, the validation is triggered when the checkbox and the button are clicked)

However, if it is inside renderUI, the validation is triggered only by clicking the checkbox (there is no need to click the button)

Here is my minimal working example:

```<code>library(shiny)
library(shinyCAPTCHA)

ui <- fluidPage(
  # With this line, the captcha works perfectly
  recaptchaUI("test", sitekey = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"),
  uiOutput("body")
)

server <- function(input, output, session) {

  result <- callModule(recaptcha, "test", secret = "6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe")

  output$body <- renderUI({
    fluidPage(
    # Inside renderUI, it does not work properly.
    #recaptchaUI("test", sitekey = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"),
    uiOutput("humansOnly")
    )

  })

  output$humansOnly <- renderUI({
    req(result()$success)
    tags$h1("For human eyes only!")
  })

}

shinyApp(ui, server)
</code>```

I have an app with several modules, that's why I need to use renderUI. What is the error in my code?

I appreciate any help!

Body:
I would like to integrate captcha verification into my shiny app (like this). But it has an unexpected behavior.

If this line:

recaptchaUI("test", sitekey = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI")

is inside the UI, my app works fine (I mean, the validation is triggered when the checkbox and the button are clicked)

However, if it is inside renderUI, the validation is triggered only by clicking the checkbox (there is no need to click the button)

Here is my minimal working example:

library(shiny)
library(shinyCAPTCHA)

ui <- fluidPage(
  # With this line, the captcha works perfectly
  recaptchaUI("test", sitekey = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"),
  uiOutput("body")
)

server <- function(input, output, session) {

  result <- callModule(recaptcha, "test", secret = "6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe")

  output$body <- renderUI({
    fluidPage(
    # Inside renderUI, it does not work properly.
    #recaptchaUI("test", sitekey = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"),
    uiOutput("humansOnly")
    )

  })

  output$humansOnly <- renderUI({
    req(result()$success)
    tags$h1("For human eyes only!")
  })

}

shinyApp(ui, server)

I have an app with several modules, that's why I need to use renderUI. What is the error in my code?

I appreciate any help!


问:
Understanding an Array Address Function
I am currently studying for a final in my undergraduate course and one chapter deals with the constructs behind a programming language's data types.

When discussing arrays, our professor gave us the following formula for an address function, which locates a specific index within an array:

addr(list[k]) = addr(list[lowbound]) + ((k - lowbound) * elementSize)

Now, I understand everything except for the last part, which is *elementSize).

From what I dissect, addr(list[lowbound]) retrieves the first index of the array (as lowbound is usually 0, referencing index 0). Then, (k - lowbound) moves forward k spaces by calculating the index referenced.

However, I am unsure what purpose * elementSize has on the function. If the second part already retrieves the necessary index, what does multiplying by elementSize contribute to the final product.

Title: Understanding an Array Address Function


问:
check if current is the main page react-native-webview
I have a WebView project of an PHP admin panel, that I put a custom Back Button on top of its WebView. I want this button to be visible only if the current screen can go back, which is any screen beside main screen, and in this case our main screen is a admin panel login page. So I came up with the code I shared below.

It works fine, unless you login with wrong credentials. The Back Button immediately shows up when the login button pressed inside the WebView because it gets to another url from admin.panel/login to admin.panel/login/login, but it shouldn't render unless we successfully login to the panel. How can I achieve that?

BackButton.js

```<code>import { StyleSheet, TouchableOpacity } from "react-native";
import { Ionicons } from "@expo/vector-icons";

const BackButton = (props) => {
  return (
    <TouchableOpacity style={styles.button} onPress={props.onPress}>
      <Ionicons name="arrow-back" size={24} color="black" />
    </TouchableOpacity>
  );
};

</code>```

App.js

```<code>import React, { useEffect, useRef } from "react";
import { StyleSheet, Platform, BackHandler, View } from "react-native";
import { WebView } from "react-native-webview";
import MyStatusBar from "./components/MyStatusBar";
import MyBackButton from "./components/BackButton";

export default function App() {
  const webViewRef = useRef();

  // to handle goBack function for both button and hardwareBackPress
  const onBackPress = () => {
    if (webViewRef.current) {
      webViewRef.current.goBack();
      return true;
    }
    return false;
  };

  // to check if current can go back
  const [canGoBack, setCanGoBack] = React.useState(false);

  // WebView does not support swipe back for some android devices
  // thus we have to handle the goBack function with hardwareBackPress
  useEffect(() => {
    ...
    }
  }, []);

  return (
    <View style={styles.container}>
      <MyStatusBar />
      <WebView
        allowsBackForwardNavigationGestures
        allowsInlineMediaPlayback
        ref={webViewRef}
        source={{ uri: "https://admin.panel/login" }}
        style={styles.webView}
        onNavigationStateChange={(navState) => setCanGoBack(navState.canGoBack)}
      />
      {canGoBack? (
        <View style={styles.button}>
          <MyBackButton onPress={onBackPress} />
        </View>
      ) : null}
    </View>
  );
}
</code>```

Body:
I have a WebView project of an PHP admin panel, that I put a custom Back Button on top of its WebView. I want this button to be visible only if the current screen can go back, which is any screen beside main screen, and in this case our main screen is a admin panel login page. So I came up with the code I shared below.

It works fine, unless you login with wrong credentials. The Back Button immediately shows up when the login button pressed inside the WebView because it gets to another url from admin.panel/login to admin.panel/login/login, but it shouldn't render unless we successfully login to the panel. How can I achieve that?

BackButton.js

import { StyleSheet, TouchableOpacity } from "react-native";
import { Ionicons } from "@expo/vector-icons";

const BackButton = (props) => {
  return (
    <TouchableOpacity style={styles.button} onPress={props.onPress}>
      <Ionicons name="arrow-back" size={24} color="black" />
    </TouchableOpacity>
  );
};

App.js

import React, { useEffect, useRef } from "react";
import { StyleSheet, Platform, BackHandler, View } from "react-native";
import { WebView } from "react-native-webview";
import MyStatusBar from "./components/MyStatusBar";
import MyBackButton from "./components/BackButton";

export default function App() {
  const webViewRef = useRef();

  // to handle goBack function for both button and hardwareBackPress
  const onBackPress = () => {
    if (webViewRef.current) {
      webViewRef.current.goBack();
      return true;
    }
    return false;
  };

  // to check if current can go back
  const [canGoBack, setCanGoBack] = React.useState(false);

  // WebView does not support swipe back for some android devices
  // thus we have to handle the goBack function with hardwareBackPress
  useEffect(() => {
    ...
    }
  }, []);

  return (
    <View style={styles.container}>
      <MyStatusBar />
      <WebView
        allowsBackForwardNavigationGestures
        allowsInlineMediaPlayback
        ref={webViewRef}
        source={{ uri: "https://admin.panel/login" }}
        style={styles.webView}
        onNavigationStateChange={(navState) => setCanGoBack(navState.canGoBack)}
      />
      {canGoBack? (
        <View style={styles.button}>
          <MyBackButton onPress={onBackPress} />
        </View>
      ) : null}
    </View>
  );
}


问:
Heroku - Adding SSL key throws an error - Key could not be read since it's protected by a passphrase
Hi I'm trying to add SSL certificae to Heroku for my .app domain.

Namecheap provided certificate and domain.

I added it without problem first time, but after deleting it ( to reinstall as instructed by Namecheap support ) I started getting error Key could not be read since it's protected by a passphrase. when trying to add new certificate with same keys.

It's obviously not a pasphrase because it would fail on first time I uploaded it.

Can anyone help ?


问:
Why are my final sample sizes different on SPSS compared to PROCESS MACRO
I’m doing a moderation analysis in SPSS. I recoded all my variables and coded inapplicable, don’t know, doesn’t apply as -99 so they would be considered as missing variables and not applied to the analysis. When I run the data through PROCESS MACRO, I get a sample size of 680. When I run it through SPSS, I get 768. I also centered the variables on PROCESS and SPSS

Not sure what I’m doing wrong and why I’m getting two different sample sizes.

Any suggestions?

Tried running frequency analysis but not getting same results as PROCESS. Not sure if I’m doing something wrong there.


问:
Display Image from URL in Dataspell
I would like to know how can I display images in a column by using their URL? I have tried on Google Colab and it has worked, but when I try on my jupyter notebook (data spell), it doesn't display the images.</p>
```<code>from IPython.core.display import HTML
#%%
## Converting links to html tags
def path_to_image_html(path):
    return '<img src="'+ path + '" width="60" >'
#%%
## Rendering the dataframe as HTML table
df.to_html(escape=False, formatters=dict(image=path_to_image_html))

## Rendering the images in the dataframe using the HTML method.
HTML(df.to_html(escape=False,formatters=dict(image=path_to_image_html)))

and it returned me the this instead of the image ;<img src="url of the image" width="60">
</code>```

Title: Display Image from URL in Dataspell

Body:
I would like to know how can I display images in a column by using their URL? I have tried on Google Colab and it has worked, but when I try on my jupyter notebook (data spell), it doesn't display the images.

from IPython.core.display import HTML
#%%
## Converting links to html tags
def path_to_image_html(path):
    return ''
#%%
## Rendering the dataframe as HTML table
df.to_html(escape=False, formatters=dict(image=path_to_image_html))

## Rendering the images in the dataframe using the HTML method.
HTML(df.to_html(escape=False,formatters=dict(image=path_to_image_html)))

and it returned me the this instead of the image ;


问:
Can we extract Workable api and display it via html or javascript code externally?
I'm trying to extract the Workable api and display all the jobs listings into an external site.

The api documentation is here: https://workable.readme.io/reference/generate-an-access-token.

It says on the notes here:

Workable does not support Cross-Origin Resource Sharing (CORS)`

And when I try to fetch it says Access-Control-Allow-Origin header is present on the requested resource. How do I enable it? Because the Integrations settings under workable only allows me to only generate access token.

This is a sample code here when you go to this jobs documentation:

Note: I'm only using JavaScript

```<code>const options = {
  method: 'GET',
  headers: {accept: 'application/json', Authorization: 'Bearer AccessTokenHere'}
};

fetch('https://subdomain.workable.com/spi/v3/jobs?limit=50', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));
</code>```

Body:
I'm trying to extract the Workable api and display all the jobs listings into an external site.

The api documentation is here: https://workable.readme.io/reference/generate-an-access-token.

It says on the notes here:

Workable does not support Cross-Origin Resource Sharing (CORS)`

And when I try to fetch it says Access-Control-Allow-Origin header is present on the requested resource. How do I enable it? Because the Integrations settings under workable only allows me to only generate access token.

This is a sample code here when you go to this jobs documentation:

Note: I'm only using JavaScript

const options = {
  method: 'GET',
  headers: {accept: 'application/json', Authorization: 'Bearer AccessTokenHere'}
};

fetch('https://subdomain.workable.com/spi/v3/jobs?limit=50', options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));


问:
Are there any ways to write VBA code to select autofilter field in range of another workbook
VBA code need to find the sheet name from column A and in same row it need to pick column E to filter data from another Woorkbook.

Can anyone please help me with this case.

```<code>Sub filter()
Dim lLastRow As Long
Dim wb As Workbook
Dim fieldnum As Integer

Set wb = Workbooks("Quotes_Management_Tool tersrt")
 lLastRow = ActiveSheet.Range("A1").Cells(Rows.Count, 1).End(xlUp).Row
fieldnum = wb.Sheets("QuoteExpiryDates").Range("E4:E" & lLastRow).Value
 ActiveSheet.Range("$A$5:$R$485").AutoFilter Field:=fieldnum, Criteria1:=RGB(198, _
        239, 206), Operator:=xlFilterCellColor

End Sub
</code>```

I tried this but it unable to take the column value

Body:
VBA code need to find the sheet name from column A and in same row it need to pick column E to filter data from another Woorkbook.

Can anyone please help me with this case.

Sub filter()
Dim lLastRow As Long
Dim wb As Workbook
Dim fieldnum As Integer

Set wb = Workbooks("Quotes_Management_Tool tersrt")
 lLastRow = ActiveSheet.Range("A1").Cells(Rows.Count, 1).End(xlUp).Row
fieldnum = wb.Sheets("QuoteExpiryDates").Range("E4:E" & lLastRow).Value
 ActiveSheet.Range("$A$5:$R$485").AutoFilter Field:=fieldnum, Criteria1:=RGB(198, _
        239, 206), Operator:=xlFilterCellColor

End Sub

I tried this but it unable to take the column value


问:
Image Downscaling
I need a bit of a clarification on this Process.
I am trying to downsize from 6000 * 4000 pixel to 960 * 960 for website space purpose using MagickImageMagic.
Would doing the same from 2000 * 2000 to 960 * 960 make any impact on the quality of the image.
I need some understanding weather I should proceed with capturing with resolution close to the target or should I go for high resolution for better quality.</p>
```<code>    var imageforLightbox = new MagickImage(Path.Combine(SOURCE_PATH, filename));
    MagickGeometry size = new MagickGeometry(1920, 1080);
     size.IgnoreAspectRatio = false;
     imageforLightbox.Resize(size);
</code>```

Title: Image Downscaling

Body:
I need a bit of a clarification on this Process.
I am trying to downsize from 6000 * 4000 pixel to 960 * 960 for website space purpose using MagickImageMagic.
Would doing the same from 2000 * 2000 to 960 * 960 make any impact on the quality of the image.
I need some understanding weather I should proceed with capturing with resolution close to the target or should I go for high resolution for better quality.

    var imageforLightbox = new MagickImage(Path.Combine(SOURCE_PATH, filename));
    MagickGeometry size = new MagickGeometry(1920, 1080);
     size.IgnoreAspectRatio = false;
     imageforLightbox.Resize(size);


问:
How to dynamically normalize a value based on a match from another column in Tableau
Hello I am a new user of stackoverflow, so apologies if I don't follow typical conventions.

sample
Control
Value
Normalized Value (Relative to Control)

a
e
5.5
5.5/5.7

b
e
8.3
8.3/5.7

c
f
6.6
6.6/7.7

d
f
9.9
9.9/7.7

e

5.7

f

7.7

I have an example table (shown above) where I would like Tableau to automatically calculate the last column (Normalized Value) using the data from previous columns.

How do I make the normalization dynamic to the appropriate control value?

In a simpler case, I was able to normalize all the values to a single control, however this is NOT dynamic. Below is how I use LOD to normalize to "e".

[Value]/{fixed:avg(if [sample]='e' then [Value] end )}

But this is not what I want, because sometimes I need to normalize to "e" and other times it is "f".


问:
Py4JJavaError: An error occurred while calling o10495.join. : java.lang.StackOverflowError
In Azure Synapse notebook, after running quite a number of functions, I'm trying to do a semi join of two dataframes where DF1 has one column called ID and the DF2 has five columns: ID, SID, Name, Term, Desc. Now the issue is everytime I start the session, I get this error. But when I run the code cell 5-6 times, it starts working. Not sure why it keeps happening.

df1 is a union of all distinct IDs from two other dataframes.
df2 = ogdata.select('SID', 'ID', 'Name', 'Term', 'Desc').distinct()

My Join:
df3 = df2.join(df1, ["uid"], "semi")

I've tried:
Changing it to left, different join syntax where I do df1.id = df2.id but always get the error everytime I start a session. Then when I run the cell 5-6 times, it works.

My error:

```<code>Py4JJavaError                             Traceback (most recent call last)
<ipython-input-127-9d80a53> in <module>
      1 ##teaching_data_current = teaching_data_current.join(uid_agg_course_teacher, teaching_data_current.uid == uid_agg_course_teacher.uid, "semi").drop(uid_agg_course_teacher.uid)
      2 teaching_data_c = coursedata.select('SubjectID','uid').distinct()
----> 3 teaching_data_curr = teaching_data_c.join(uid_agg_course_teacher, ["uid"], "semi")
      4 #teaching_data_curr = teaching_data_c.alias("t1").join(uid_agg_course_teacher.alias("t2"), teaching_data_c.uid==uid_agg_course_teacher.uid, "semi")

/opt/spark/python/lib/pyspark.zip/pyspark/sql/dataframe.py in join(self, other, on, how)
   1337                 on = self._jseq([])
   1338             assert isinstance(how, str), "how should be a string"
-> 1339             jdf = self._jdf.join(other._jdf, on, how)
   1340         return DataFrame(jdf, self.sql_ctx)
   1341

~/cluster-env/env/lib/python3.8/site-packages/py4j/java_gateway.py in __call__(self, *args)
   1302
   1303         answer = self.gateway_client.send_command(command)
-> 1304         return_value = get_return_value(
   1305             answer, self.gateway_client, self.target_id, self.name)
   1306

/opt/spark/python/lib/pyspark.zip/pyspark/sql/utils.py in deco(*a, **kw)
    109     def deco(*a, **kw):
    110         try:
--> 111             return f(*a, **kw)
    112         except py4j.protocol.Py4JJavaError as e:
    113             converted = convert_exception(e.java_exception)

~/cluster-env/env/lib/python3.8/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    324             value = OUTPUT_CONVERTER[type](answer[2:], gateway_client)
    325             if answer[1] == REFERENCE_TYPE:
--> 326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
    328                     format(target_id, ".", name), value)

Py4JJavaError: An error occurred while calling o10428.join.
: java.lang.StackOverflowError
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$$anonfun$findAliases$1.applyOrElse(Analyzer.scala:1763)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$$anonfun$findAliases$1.applyOrElse(Analyzer.scala:1763)
    at scala.PartialFunction.$anonfun$runWith$1$adapted(PartialFunction.scala:145)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.collection.TraversableLike.collect(TraversableLike.scala:359)
    at scala.collection.TraversableLike.collect$(TraversableLike.scala:357)
    at scala.collection.immutable.List.collect(List.scala:327)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.findAliases(Analyzer.scala:1763)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.collectConflictPlans$1(Analyzer.scala:1388)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.$anonfun$dedupRight$10(Analyzer.scala:1464)
    at scala.collection.TraversableLike.$anonfun$flatMap$1(TraversableLike.scala:245)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.collection.TraversableLike.flatMap(TraversableLike.scala:245)
    at scala.collection.TraversableLike.flatMap$(TraversableLike.scala:242)
    at scala.collection.immutable.List.flatMap(List.scala:355)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.collectConflictPlans$1(Analyzer.scala:1464)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.$anonfun$dedupRight$10(Analyzer.scala:1464)
    at scala.collection.TraversableLike.$anonfun$flatMap$1(TraversableLike.scala:245)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.collection.TraversableLike.flatMap(TraversableLike.scala:245)
    at scala.collection.TraversableLike.flatMap$(TraversableLike.scala:242)
    at scala.collection.immutable.List.flatMap(List.scala:355)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.collectConflictPlans$1(Analyzer.scala:1464)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.$anonfun$dedupRight$10(Analyzer.scala:1464)
    at scala.collection.TraversableLike.$anonfun$flatMap$1(TraversableLike.scala:245)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.collection.TraversableLike.flatMap(TraversableLike.scala:245)
    at scala.collection.TraversableLike.flatMap$(TraversableLike.scala:242)
    at scala.collection.immutable.List.flatMap(List.scala:355)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.collectConflictPlans$1(Analyzer.scala:1464)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.$anonfun$dedupRight$10(Analyzer.scala:1464)
    at scala.collection.TraversableLike.$anonfun$flatMap$1(TraversableLike.scala:245)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.collection.TraversableLike.flatMap(TraversableLike.scala:245)

</code>```

Body:
In Azure Synapse notebook, after running quite a number of functions, I'm trying to do a semi join of two dataframes where DF1 has one column called ID and the DF2 has five columns: ID, SID, Name, Term, Desc. Now the issue is everytime I start the session, I get this error. But when I run the code cell 5-6 times, it starts working. Not sure why it keeps happening.

df1 is a union of all distinct IDs from two other dataframes.
df2 = ogdata.select('SID', 'ID', 'Name', 'Term', 'Desc').distinct()

My Join:
df3 = df2.join(df1, ["uid"], "semi")

I've tried:
Changing it to left, different join syntax where I do df1.id = df2.id but always get the error everytime I start a session. Then when I run the cell 5-6 times, it works.

My error:

Py4JJavaError                             Traceback (most recent call last)
<ipython-input-127-9d80a53> in <module>
      1 ##teaching_data_current = teaching_data_current.join(uid_agg_course_teacher, teaching_data_current.uid == uid_agg_course_teacher.uid, "semi").drop(uid_agg_course_teacher.uid)
      2 teaching_data_c = coursedata.select('SubjectID','uid').distinct()
----> 3 teaching_data_curr = teaching_data_c.join(uid_agg_course_teacher, ["uid"], "semi")
      4 #teaching_data_curr = teaching_data_c.alias("t1").join(uid_agg_course_teacher.alias("t2"), teaching_data_c.uid==uid_agg_course_teacher.uid, "semi")

/opt/spark/python/lib/pyspark.zip/pyspark/sql/dataframe.py in join(self, other, on, how)
   1337                 on = self._jseq([])
   1338             assert isinstance(how, str), "how should be a string"
-> 1339             jdf = self._jdf.join(other._jdf, on, how)
   1340         return DataFrame(jdf, self.sql_ctx)
   1341

~/cluster-env/env/lib/python3.8/site-packages/py4j/java_gateway.py in __call__(self, *args)
   1302
   1303         answer = self.gateway_client.send_command(command)
-> 1304         return_value = get_return_value(
   1305             answer, self.gateway_client, self.target_id, self.name)
   1306

/opt/spark/python/lib/pyspark.zip/pyspark/sql/utils.py in deco(*a, **kw)
    109     def deco(*a, **kw):
    110         try:
--> 111             return f(*a, **kw)
    112         except py4j.protocol.Py4JJavaError as e:
    113             converted = convert_exception(e.java_exception)

~/cluster-env/env/lib/python3.8/site-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    324             value = OUTPUT_CONVERTER[type](answer[2:], gateway_client)
    325             if answer[1] == REFERENCE_TYPE:
--> 326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
    328                     format(target_id, ".", name), value)

Py4JJavaError: An error occurred while calling o10428.join.
: java.lang.StackOverflowError
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$$anonfun$findAliases$1.applyOrElse(Analyzer.scala:1763)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$$anonfun$findAliases$1.applyOrElse(Analyzer.scala:1763)
    at scala.PartialFunction.$anonfun$runWith$1$adapted(PartialFunction.scala:145)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.collection.TraversableLike.collect(TraversableLike.scala:359)
    at scala.collection.TraversableLike.collect$(TraversableLike.scala:357)
    at scala.collection.immutable.List.collect(List.scala:327)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.findAliases(Analyzer.scala:1763)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.collectConflictPlans$1(Analyzer.scala:1388)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.$anonfun$dedupRight$10(Analyzer.scala:1464)
    at scala.collection.TraversableLike.$anonfun$flatMap$1(TraversableLike.scala:245)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.collection.TraversableLike.flatMap(TraversableLike.scala:245)
    at scala.collection.TraversableLike.flatMap$(TraversableLike.scala:242)
    at scala.collection.immutable.List.flatMap(List.scala:355)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.collectConflictPlans$1(Analyzer.scala:1464)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.$anonfun$dedupRight$10(Analyzer.scala:1464)
    at scala.collection.TraversableLike.$anonfun$flatMap$1(TraversableLike.scala:245)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.collection.TraversableLike.flatMap(TraversableLike.scala:245)
    at scala.collection.TraversableLike.flatMap$(TraversableLike.scala:242)
    at scala.collection.immutable.List.flatMap(List.scala:355)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.collectConflictPlans$1(Analyzer.scala:1464)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.$anonfun$dedupRight$10(Analyzer.scala:1464)
    at scala.collection.TraversableLike.$anonfun$flatMap$1(TraversableLike.scala:245)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.collection.TraversableLike.flatMap(TraversableLike.scala:245)
    at scala.collection.TraversableLike.flatMap$(TraversableLike.scala:242)
    at scala.collection.immutable.List.flatMap(List.scala:355)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.collectConflictPlans$1(Analyzer.scala:1464)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveReferences$.$anonfun$dedupRight$10(Analyzer.scala:1464)
    at scala.collection.TraversableLike.$anonfun$flatMap$1(TraversableLike.scala:245)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.collection.TraversableLike.flatMap(TraversableLike.scala:245)


问:
When are .dll addresses resolved when running an executable?
When we have a C++ executable constructed from successfully compiled code, during the linking stage if I need to use a .dll the addresses will be correctly resolved in the executable to find them. Would this not suggest that if I drag the executable to a new computer that the addresses resolved during linking into the executable would be incorrect and pointing to memory address locations on the previous computer?

How is this issue resolved or when are the .dll addresses resolved so that the .exe can correctly find them?

So far it seems this may not be the case.


问:
How to make a update or create eloquent faster with dealing large data
Iam finishing a system where a user can register a parent and its child. so the system will save the parent and if the parent has a child it will also be register here is the database the relation is Parent can have many Child

Parent
Child

id
id

fullname
parent_id

address
fullname

age
age

So I am  only doing the backend and the data that is being passed look like this

```<code>[
  {
     id:0,
     fullname:"John Doe",
     address:"Cebu City",
     age:"35",
     child:[]
  },
  {
     id:null,
     fullname:"Jane Doe",
     address:"Cebu City",
     age:"45",
     child:[
        {
           id:null,
           parent_id:null,
           fullname:"Jake Doe",
           age:"18"
        }
     ]
  },
]
</code>```

So the jane doe data has null because it actually just got appended so its not saved to database yet.
The problem here is that if I will use for each and every for each i will create or update the passed data it takes more than 10 seconds for 15parents with 4 of them have child. The parent child property can be empty because pregnant are not allowed to register a child.

I tried for-each to loop all the data being passed after every loop i check if the id is null or not and then creates it if ID is null after that I will again do a for loop or the child and checking if the child has id and then create or update the database. I am expecting a more faster and efficient way to do this.

```<code>foreach($data as $parent => $parentValue){
    $parent_id = null;
    if($parentValue['id']){
        $parent_id = $parentValue['id'];
        $update_parent_info = $this->Parent->whereId($parent_id)->update(array(
            "fullname"=>$parentValue['fullname'],
             "address"=>$parentValue['address'],
             "age"=>$parentValue['age'],
        ))

    }else{
        $create_parent_info = $this->Parent->create(array(
             "fullname"=>$parentValue['fullname'],
             "address"=>$parentValue['address'],
             "age"=>$parentValue['age'],
        ))
        $parent_id = $create_parent_info->id;
    };

    if(count($parentValue['child']) != 0){
        foreach($parentValue['child'] as $child => $childValue){
            if($childValue['id']){
                $update_parent_info = $this->Child->whereId($childValue['id'])->update(array(
                    "fullname"=>$childValue['fullname'],
                     "address"=>$childValue['address'],
                     "age"=>$childValue['age'],
                ))

            }else{
                $create_parent_info = $this->Child->create(array(
                     "parent_id"=>$parent_id
                     "fullname"=>$childValue['fullname'],
                     "address"=>$childValue['address'],
                     "age"=>$childValue['age'],
                ))
            };
        }
    }
};
</code>```

Body:
Iam finishing a system where a user can register a parent and its child. so the system will save the parent and if the parent has a child it will also be register here is the database the relation is Parent can have many Child

Parent
Child

id
id

fullname
parent_id

address
fullname

age
age

So I am  only doing the backend and the data that is being passed look like this

[
  {
     id:0,
     fullname:"John Doe",
     address:"Cebu City",
     age:"35",
     child:[]
  },
  {
     id:null,
     fullname:"Jane Doe",
     address:"Cebu City",
     age:"45",
     child:[
        {
           id:null,
           parent_id:null,
           fullname:"Jake Doe",
           age:"18"
        }
     ]
  },
]

So the jane doe data has null because it actually just got appended so its not saved to database yet.
The problem here is that if I will use for each and every for each i will create or update the passed data it takes more than 10 seconds for 15parents with 4 of them have child. The parent child property can be empty because pregnant are not allowed to register a child.

I tried for-each to loop all the data being passed after every loop i check if the id is null or not and then creates it if ID is null after that I will again do a for loop or the child and checking if the child has id and then create or update the database. I am expecting a more faster and efficient way to do this.

foreach($data as $parent => $parentValue){
    $parent_id = null;
    if($parentValue['id']){
        $parent_id = $parentValue['id'];
        $update_parent_info = $this->Parent->whereId($parent_id)->update(array(
            "fullname"=>$parentValue['fullname'],
             "address"=>$parentValue['address'],
             "age"=>$parentValue['age'],
        ))

    }else{
        $create_parent_info = $this->Parent->create(array(
             "fullname"=>$parentValue['fullname'],
             "address"=>$parentValue['address'],
             "age"=>$parentValue['age'],
        ))
        $parent_id = $create_parent_info->id;
    };

    if(count($parentValue['child']) != 0){
        foreach($parentValue['child'] as $child => $childValue){
            if($childValue['id']){
                $update_parent_info = $this->Child->whereId($childValue['id'])->update(array(
                    "fullname"=>$childValue['fullname'],
                     "address"=>$childValue['address'],
                     "age"=>$childValue['age'],
                ))

            }else{
                $create_parent_info = $this->Child->create(array(
                     "parent_id"=>$parent_id
                     "fullname"=>$childValue['fullname'],
                     "address"=>$childValue['address'],
                     "age"=>$childValue['age'],
                ))
            };
        }
    }
};


问:
Aurora MySQL 5.7 ignores primary key index
I have a particular query that uses IN() in the where condition which pass set of IDs.

Table Name - A
Primary Key - id

When 2000 ids passed to the IN() - eg: select col1,col2 from A where id IN (1,2,3,4,5,*******) , query uses the primary key(obvious index) as the index to execute the query.

When 20000 ids passed to the IN() - query ignores the primary key and runs in 70sec with a full table scan, I used index hint (use index(PRIMARY)) and with this query used the primary key and executed under 4sec.

When 200000 ids passed to the IN() - query ignores the primary key even with 'hint' and 'force' index options. Output will retrieve 6000 rows.

Total number of rows in the table A - 100 million

Further this query used to run under 5sec with 200000 ids in IN() before upgrading to MySQL5.7 from MySQL 5.6.

My Question - Is this a bug, or does the behavior of MySQL 5.7 optimizer change with the number of values passed inside IN() compared to MySQL 5.6 ?


问:
Rail Add Password on Uploaded PDF file
I have an Rails application where the user can upload a PDF. The application will add a password automatically(the password will be generated using the user's data) then will save it to AWS S3. So, when the user opens that PDF, the PDF would ask for the password.

Right now I am able to upload the PDF without adding password and it is working. My problem is adding password on it automatically.

On the same application, I also used Prawn since I have separate feature where the system will generate the PDF(not upload by the user) and I can add password into it.

P.S. I also need to add password if the user upload an image file. I just want to ask if there is a way I can add password to uploaded image file OR I need to convert it to PDF?

Thanks for the help!

Title: Rail Add Password on Uploaded PDF file


问:
Errors in folder?
enter image description here Can someone please explain me what is wrong here?
The code runs but still there's some problem.

Hopefully someone can has the answer to my problem.

Title: Errors in folder?


问:
What should I use as entry point for multiple cloud application?
I am deploying two K8S clusters, one in AWS EKS, the other is on GCP GKE. Each cluster exports an ingress which is a load balancer for consumers to connect. They work as high availability application in case one cloud is down, the other cloud can pick up the traffic.

Now I need to create another entry point which point to these two load balancers so that clients can consume one entry point. I have two options here, DNS like route53, or another load balancer.

But I don't know which one is better and the main different between them. I'd like to achieve

high availability goal which mean if one region is down, clients can still use my application from the other cloud.

both clusters from two clouds are active. The entry point can route the traffic based on some rules like weighted, random, geolocation etc.


问:
Pass variable from bash to R with commandArgs
I'm having a terrible go trying to pass some variables from the shell to R. I am hesitant to post this because I can't figure out a reasonable way to make this reproducible, since it involves a tool that has to be downloaded, and really it's more of a general methodology issue that I don't think needs to be reproducible, if you can just suspend your disbelief and bear with me for a quick minute.

I have arguments that are defined in a bash script: $P, $G, and $O.

I have some if/then statements and everything is fine until I get to the $O options.

This is the first part of the $O section and it works fine. It grabs data from $P and passes it to the twoBitToFa utility from UCSC's genome project and outputs the data correctly in a .fa file. Beautiful. (Although I think using 'stdout' and '>' is perhaps redundant?)

```<code>if [ "$O" = "fasta" ]
    then
        awk '{print $0" "$1":"$2"-"$3}' "$P" |
        twoBitToFa -bed=stdin -udcDir=. "$twobit" stdout > "${P%.bed}".fa
    fi
</code>```

The next section is where I am stuck. If the $O option is "bed", then I want to invoke the Rscript command and pass my stuff over to R. I am able to pass my $P, $G, and $O variables without issue, but now I also need to pass the output from the twoBitToFa function. I could add a step and make the .fa file and then pick that up in R, but I am trying to skip the .fa file creation step and output a different file type instead (.bed). Here are some things I have tried:

```<code># try saving twoBitToFa output to variable and including it in the variables passed to R:
if [ "$O" = "bed" ]
    then
        awk '{print $0" "$1":"$2"-"$3}' "$P" |
        myvar=$(twoBitToFa -bed=stdin -udcDir=. "$twobit" stdout) \
        Rscript \
        GetSeq_R.r \
        $P \
        $G \
        $O \
        $myvar
    fi
</code>```

To check what variables come through, my GetSeq_R.r script starts with:

```<code>args = commandArgs(trailingOnly=TRUE)
print(args)
</code>```

and with the above code, the output only includes my $P, $G, and $O variables. $myvar doesn't make it. $P is the TAD-1 file, $G is "hg38", and $O is "bed".

```<code>[1] "TAD-1_template.bed" "hg38"               "bed"
</code>```

I am not sure if the way I am trying to pass the data in the variable is wrong. From everything I've read, it seems like it should work. I've also tried using tee to see what is in my stdout at that step like so:

```<code>    if [ "$O" = "bed" ]
    then
        awk '{print $0" "$1":"$2"-"$3}' "$P" |
        twoBitToFa -bed=stdin -udcDir=. "$twobit" stdout | tee \
        Rscript \
        GetSeq_R.r \
        $P \
        $G \
        $O
    fi

</code>```

And the data I want to pass to R is correctly shown in my console by using tee. I've tried saving stdout and tee to a variable and passing that variable to R, thinking maybe it's something about twoBitToFa that refuses to be put inside a variable, but was unsuccessful. I've spent hours looking up info about tee, stdout, and passing variables from bash to R. I feel like I'm missing something fundamental, or trying to do something impossible, and would really appreciate some other eyes on this.

Here's the whole bash script, in case that's illuminating. Do I need to define a variable in "$@" for what I am trying to pass to R, even though it's not something I want the user to be aware of? Am I capturing the variable with $myvar incorrectly? Can I get the contents of stdout or tee to show up in R?

Thanks in advance.

```<code>for arg in "$@"; do
  shift
  case "$arg" in
      "--path")         set -- "$@" "-P" ;;
      "--genome")       set -- "$@" "-G" ;;
      "--output")       set -- "$@" "-O" ;;
      "--help")         set -- "$@" "-h" ;;
       *)               set -- "$@" "$arg"
  esac
done

while getopts ":P:G:O:h" OPT
do
    case $OPT in
  P) P=$OPTARG;;
  G) G=$OPTARG;;
  O) O=$OPTARG;;
  h) help ;;
  \?)
      echo "Invalid option: -$OPTARG" >&2
      usage
      exit 1
      ;;
  :)
      echo "Option -$OPTARG requires an argument." >&2
      usage
      exit 1
      ;;
    esac
done

num_col=$(cat "$P" | awk "{print NF; exit}")

if [ "$num_col" = 3 ]
then
echo -e "\n\n3 column bed file detected; no directional considerations for sequences \n\n"
    if [ "$G" = "hg38" ]
    then
        twobit="https://hgdownload.cse.ucsc.edu/goldenpath/hg38/bigZips/hg38.2bit"
    fi
    if [ "$G" = "hg19" ]
    then
        twobit="https://hgdownload.cse.ucsc.edu/goldenpath/hg19/bigZips/hg19.2bit"
    fi
    if [ "$O" = "fasta" ]
    then
        awk '{print $0" "$1":"$2"-"$3}' "$P" |
        twoBitToFa -bed=stdin -udcDir=. "$twobit" stdout > "${P%.bed}".fa
    fi
    if [ "$O" = "bed" ]
    then
        awk '{print $0" "$1":"$2"-"$3}' "$P" |
        #myvar=$(twoBitToFa -bed=stdin -udcDir=. "$twobit" stdout) \
        Rscript \
        GetSeq_R.r \
        $P \
        $G \
        $O \
        $myvar
    fi
fi
</code>```

Body:
I'm having a terrible go trying to pass some variables from the shell to R. I am hesitant to post this because I can't figure out a reasonable way to make this reproducible, since it involves a tool that has to be downloaded, and really it's more of a general methodology issue that I don't think needs to be reproducible, if you can just suspend your disbelief and bear with me for a quick minute.

I have arguments that are defined in a bash script: $P, $G, and $O.

I have some if/then statements and everything is fine until I get to the $O options.

This is the first part of the $O section and it works fine. It grabs data from $P and passes it to the twoBitToFa utility from UCSC's genome project and outputs the data correctly in a .fa file. Beautiful. (Although I think using 'stdout' and '>' is perhaps redundant?)

if [ "$O" = "fasta" ]
    then
        awk '{print $0" "$1":"$2"-"$3}' "$P" |
        twoBitToFa -bed=stdin -udcDir=. "$twobit" stdout > "${P%.bed}".fa
    fi

The next section is where I am stuck. If the $O option is "bed", then I want to invoke the Rscript command and pass my stuff over to R. I am able to pass my $P, $G, and $O variables without issue, but now I also need to pass the output from the twoBitToFa function. I could add a step and make the .fa file and then pick that up in R, but I am trying to skip the .fa file creation step and output a different file type instead (.bed). Here are some things I have tried:

# try saving twoBitToFa output to variable and including it in the variables passed to R:
if [ "$O" = "bed" ]
    then
        awk '{print $0" "$1":"$2"-"$3}' "$P" |
        myvar=$(twoBitToFa -bed=stdin -udcDir=. "$twobit" stdout) \
        Rscript \
        GetSeq_R.r \
        $P \
        $G \
        $O \
        $myvar
    fi

To check what variables come through, my GetSeq_R.r script starts with:

args = commandArgs(trailingOnly=TRUE)
print(args)

and with the above code, the output only includes my $P, $G, and $O variables. $myvar doesn't make it. $P is the TAD-1 file, $G is "hg38", and $O is "bed".

[1] "TAD-1_template.bed" "hg38"               "bed"

I am not sure if the way I am trying to pass the data in the variable is wrong. From everything I've read, it seems like it should work. I've also tried using tee to see what is in my stdout at that step like so:

    if [ "$O" = "bed" ]
    then
        awk '{print $0" "$1":"$2"-"$3}' "$P" |
        twoBitToFa -bed=stdin -udcDir=. "$twobit" stdout | tee \
        Rscript \
        GetSeq_R.r \
        $P \
        $G \
        $O
    fi

And the data I want to pass to R is correctly shown in my console by using tee. I've tried saving stdout and tee to a variable and passing that variable to R, thinking maybe it's something about twoBitToFa that refuses to be put inside a variable, but was unsuccessful. I've spent hours looking up info about tee, stdout, and passing variables from bash to R. I feel like I'm missing something fundamental, or trying to do something impossible, and would really appreciate some other eyes on this.

Here's the whole bash script, in case that's illuminating. Do I need to define a variable in "$@" for what I am trying to pass to R, even though it's not something I want the user to be aware of? Am I capturing the variable with $myvar incorrectly? Can I get the contents of stdout or tee to show up in R?

Thanks in advance.

for arg in "$@"; do
  shift
  case "$arg" in
      "--path")         set -- "$@" "-P" ;;
      "--genome")       set -- "$@" "-G" ;;
      "--output")       set -- "$@" "-O" ;;
      "--help")         set -- "$@" "-h" ;;
       *)               set -- "$@" "$arg"
  esac
done

while getopts ":P:G:O:h" OPT
do
    case $OPT in
  P) P=$OPTARG;;
  G) G=$OPTARG;;
  O) O=$OPTARG;;
  h) help ;;
  \?)
      echo "Invalid option: -$OPTARG" >&2
      usage
      exit 1
      ;;
  :)
      echo "Option -$OPTARG requires an argument." >&2
      usage
      exit 1
      ;;
    esac
done

num_col=$(cat "$P" | awk "{print NF; exit}")

if [ "$num_col" = 3 ]
then
echo -e "\n\n3 column bed file detected; no directional considerations for sequences \n\n"
    if [ "$G" = "hg38" ]
    then
        twobit="https://hgdownload.cse.ucsc.edu/goldenpath/hg38/bigZips/hg38.2bit"
    fi
    if [ "$G" = "hg19" ]
    then
        twobit="https://hgdownload.cse.ucsc.edu/goldenpath/hg19/bigZips/hg19.2bit"
    fi
    if [ "$O" = "fasta" ]
    then
        awk '{print $0" "$1":"$2"-"$3}' "$P" |
        twoBitToFa -bed=stdin -udcDir=. "$twobit" stdout > "${P%.bed}".fa
    fi
    if [ "$O" = "bed" ]
    then
        awk '{print $0" "$1":"$2"-"$3}' "$P" |
        #myvar=$(twoBitToFa -bed=stdin -udcDir=. "$twobit" stdout) \
        Rscript \
        GetSeq_R.r \
        $P \
        $G \
        $O \
        $myvar
    fi
fi


问:
Run-time error '462': The remote server machine does not exist or unavailable - Populating word document from excel with content controls / VBA
Attempting to create a template document that can be pre-populated / generated from an excel template.

Not overly experienced with VBA so I currently have a lot of repeating code. Nonetheless it seems to work okay but only runs successfully maybe 1/3 times.

On failed attempts I get the following error message:

Run-time error '462': The remote server machine does not exist or unavailable

Any help appreciated

```<code>Option Explicit

Sub Gen_Proposal()

Dim wrdApp As Word.Application
Dim WdDoc As Word.Document
Dim BmkNm As String
Dim newBooktxt As String
Dim FileNm As String

Dim Customer As String
Dim State As String
Dim ProposalType As String
Dim Version As String
Dim ProjectNum As String
Dim ProposalDate As String
Dim ws As Excel.Worksheet

'Select Proposal input excel sheet
Set ws = Excel.Worksheets("Sheet1")

Customer = ws.Range("Customer").Value
State = ws.Range("State").Value
ProposalType = ws.Range("ProposalType").Value
Version = ws.Range("Version").Value
ProjectNum = ws.Range("ProjectNum").Value
ProposalDate = ws.Range("ProposalDate").Value

Set wrdApp = CreateObject("Word.Application")
FileNm = Application.ActiveWorkbook.Path & "\Template.docx"
Set WdDoc = wrdApp.Documents.Add(FileNm)
wrdApp.Visible = True

Dim oCC As ContentControl

Set oCC = ActiveDocument.SelectContentControlsByTitle("Customer").Item(1)
oCC.Range.Text = Customer

Set oCC = ActiveDocument.SelectContentControlsByTitle("State").Item(1)
oCC.Range.Text = State

Set oCC = ActiveDocument.SelectContentControlsByTitle("ProposalType").Item(1)
oCC.Range.Text = ProposalType

Set oCC = ActiveDocument.SelectContentControlsByTitle("Version").Item(1)
oCC.Range.Text = Version

Set oCC = ActiveDocument.SelectContentControlsByTitle("ProjectNum").Item(1)
oCC.Range.Text = ProjectNum

Set oCC = ActiveDocument.SelectContentControlsByTitle("ProposalDate").Item(1)
oCC.Range.Text = ProposalDate

WdDoc.Fields.Update
WdDoc.PrintPreview
WdDoc.ClosePrintPreview
wrdApp.Activate

End Sub
</code>```

Body:
Attempting to create a template document that can be pre-populated / generated from an excel template.

Not overly experienced with VBA so I currently have a lot of repeating code. Nonetheless it seems to work okay but only runs successfully maybe 1/3 times.

On failed attempts I get the following error message:

Run-time error '462': The remote server machine does not exist or unavailable

Any help appreciated

Option Explicit

Sub Gen_Proposal()

Dim wrdApp As Word.Application
Dim WdDoc As Word.Document
Dim BmkNm As String
Dim newBooktxt As String
Dim FileNm As String

Dim Customer As String
Dim State As String
Dim ProposalType As String
Dim Version As String
Dim ProjectNum As String
Dim ProposalDate As String
Dim ws As Excel.Worksheet

'Select Proposal input excel sheet
Set ws = Excel.Worksheets("Sheet1")

Customer = ws.Range("Customer").Value
State = ws.Range("State").Value
ProposalType = ws.Range("ProposalType").Value
Version = ws.Range("Version").Value
ProjectNum = ws.Range("ProjectNum").Value
ProposalDate = ws.Range("ProposalDate").Value

Set wrdApp = CreateObject("Word.Application")
FileNm = Application.ActiveWorkbook.Path & "\Template.docx"
Set WdDoc = wrdApp.Documents.Add(FileNm)
wrdApp.Visible = True

Dim oCC As ContentControl

Set oCC = ActiveDocument.SelectContentControlsByTitle("Customer").Item(1)
oCC.Range.Text = Customer

Set oCC = ActiveDocument.SelectContentControlsByTitle("State").Item(1)
oCC.Range.Text = State

Set oCC = ActiveDocument.SelectContentControlsByTitle("ProposalType").Item(1)
oCC.Range.Text = ProposalType

Set oCC = ActiveDocument.SelectContentControlsByTitle("Version").Item(1)
oCC.Range.Text = Version

Set oCC = ActiveDocument.SelectContentControlsByTitle("ProjectNum").Item(1)
oCC.Range.Text = ProjectNum

Set oCC = ActiveDocument.SelectContentControlsByTitle("ProposalDate").Item(1)
oCC.Range.Text = ProposalDate

WdDoc.Fields.Update
WdDoc.PrintPreview
WdDoc.ClosePrintPreview
wrdApp.Activate

End Sub


问:
Is there a way to automate transitions while zooming into a picture using python.pptx?
I've been reading the documentation and I'm completely lost. I found somebody else's question on adding transition animation 'fade', but that only helped a little. I currently have a Power point with a bunch of images. I want it to automatically transition at each timestamp in timearr[] using fade while constantly slowly zooming in. This is more like a 2 part question of how to use animation and zooming functions in python.pptx. I'm using python 3.9 because 3.10 and 3.11 make pptx hard to use.</p>
```<code>from pptx import Presentation #
import collections
import collections.abc
from pptx.util import Inches
import os
from PIL import Image
import numpy as np
from pptx.oxml import parse_xml

#This is just to make pptx work
try:
    from collections.abc import Container
except ImportError:
    from collections import Container
collections.Container = collections.abc.Container
collections.Mapping = collections.abc.Mapping
collections.MutableMapping = collections.abc.MutableMapping
collections.Iterable = collections.abc.Iterable
collections.MutableSet = collections.abc.MutableSet
collections.Callable = collections.abc.Callable

#when to switch
timearr = [15,30,45,60] #Array of when it should change
imgarr = [] #later to be array of images
image_dir = "Z:\Programming Stuff\Images\Testing" #Library of images you should drop stuff into

#Makes the array of images into imgarr
for filename in os.listdir(image_dir):
    if filename.endswith(".jpg") or filename.endswith(".png"):
        imgarr.append(os.path.join(image_dir, filename))

#Makes the slides in powerpoint
prs = Presentation()
blank_slide_layout = prs.slide_layouts[6]
for numslides in range(len(imgarr)):
    slide = prs.slides.add_slide(blank_slide_layout)
    left = Inches(-.5) #for 1024x1024 this is pretty much centered
    top = Inches(-1.2)
    pic = slide.shapes.add_picture(imgarr[numslides], left, top, Inches(11))
    #THIS IS WHERE THE AUTO TRANSITION SHOULD BE

prs.save('test.pptx')

#we're gonna be making the image HUGE since it's 1024x1024, but it will zoom in and/or out at 130% mag over the course of the show

#Code from the other question that adds transition but not automated
xml = '''
      <mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
    <mc:Choice xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" Requires="p14">
      <p:transition xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" spd="slow" p14:dur="3400">
        <p14:ripple />
      </p:transition>
    </mc:Choice>
    <mc:Fallback>
      <p:transition xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" spd="slow">
        <p:fade />
      </p:transition>
    </mc:Fallback>
  </mc:AlternateContent>
   '''
xmlFragment = parse_xml(xml)
slide.element.insert(-1, xmlFragment)
</code>```

Body:
I've been reading the documentation and I'm completely lost. I found somebody else's question on adding transition animation 'fade', but that only helped a little. I currently have a Power point with a bunch of images. I want it to automatically transition at each timestamp in timearr[] using fade while constantly slowly zooming in. This is more like a 2 part question of how to use animation and zooming functions in python.pptx. I'm using python 3.9 because 3.10 and 3.11 make pptx hard to use.

from pptx import Presentation #
import collections
import collections.abc
from pptx.util import Inches
import os
from PIL import Image
import numpy as np
from pptx.oxml import parse_xml

#This is just to make pptx work
try:
    from collections.abc import Container
except ImportError:
    from collections import Container
collections.Container = collections.abc.Container
collections.Mapping = collections.abc.Mapping
collections.MutableMapping = collections.abc.MutableMapping
collections.Iterable = collections.abc.Iterable
collections.MutableSet = collections.abc.MutableSet
collections.Callable = collections.abc.Callable

#when to switch
timearr = [15,30,45,60] #Array of when it should change
imgarr = [] #later to be array of images
image_dir = "Z:\Programming Stuff\Images\Testing" #Library of images you should drop stuff into

#Makes the array of images into imgarr
for filename in os.listdir(image_dir):
    if filename.endswith(".jpg") or filename.endswith(".png"):
        imgarr.append(os.path.join(image_dir, filename))

#Makes the slides in powerpoint
prs = Presentation()
blank_slide_layout = prs.slide_layouts[6]
for numslides in range(len(imgarr)):
    slide = prs.slides.add_slide(blank_slide_layout)
    left = Inches(-.5) #for 1024x1024 this is pretty much centered
    top = Inches(-1.2)
    pic = slide.shapes.add_picture(imgarr[numslides], left, top, Inches(11))
    #THIS IS WHERE THE AUTO TRANSITION SHOULD BE

prs.save('test.pptx')

#we're gonna be making the image HUGE since it's 1024x1024, but it will zoom in and/or out at 130% mag over the course of the show

#Code from the other question that adds transition but not automated
xml = '''
      <mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
    <mc:Choice xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" Requires="p14">

        <p14:ripple />

    </mc:Choice>
    <mc:Fallback>

    </mc:Fallback>
  </mc:AlternateContent>
   '''
xmlFragment = parse_xml(xml)
slide.element.insert(-1, xmlFragment)


问:
Automatically Include external project files on publish

Background

Suppose I have two Typescript project at hand, Project A and Project B.

Project A is, say, a complete Electron project that runs Todo App.

Project B is pure utility library that has no specific purpose.

Problem

Project A makes use of Project B. For example, for fetching JSON from web, Project A uses FetchGranma() function from Project B.

```<code>Project A
-> index.tsx
    -> GrandmaModal.tsx
        -> import FetchGrandma() from Project B
</code>```

Now obviously, If I were to publish only Project A, it wouldn't work. So naturally, I could simply publish both projects and so be it.

However I wish Project B to be kept private. I can not publish Project B as a whole. Thus, the most logical way of achieving this as following:

Make Project C. It acts like an intermediate project that combines the whole Project A with only the portion of Project B.

Like so:

```<code>Project A
- index.ts
- Main.tsx
- boringStuffs.ts
- etc...

Project B
- CallFBI()
- MakeMoney()
- FetchGranma()
- others...

Project C
- <Entire Project A as-is>
    - index.ts
    - Main.tsx
    - boringStuffs.ts
    - etc...
- <Portion of Project B that were referenced>
    - FetchGranma()
</code>```

Note that all files that Prject C uses should be on their own directory, so that if I were to publish Project C, end users would see it as a single standalone repository without any dependencies.

I have hundreds of such references at hand. I can not possibly do this manually; painfully fixing import/export syntaxes and so on. Can it be automated? If so, how?

Body:
Background

Suppose I have two Typescript project at hand, Project A and Project B.

Project A is, say, a complete Electron project that runs Todo App.

Project B is pure utility library that has no specific purpose.

Problem

Project A makes use of Project B. For example, for fetching JSON from web, Project A uses FetchGranma() function from Project B.

Project A
-> index.tsx
    -> GrandmaModal.tsx
        -> import FetchGrandma() from Project B

Now obviously, If I were to publish only Project A, it wouldn't work. So naturally, I could simply publish both projects and so be it.

However I wish Project B to be kept private. I can not publish Project B as a whole. Thus, the most logical way of achieving this as following:

Make Project C. It acts like an intermediate project that combines the whole Project A with only the portion of Project B.

Like so:

Project A
- index.ts
- Main.tsx
- boringStuffs.ts
- etc...

Project B
- CallFBI()
- MakeMoney()
- FetchGranma()
- others...

Project C
- <Entire Project A as-is>
    - index.ts
    - Main.tsx
    - boringStuffs.ts
    - etc...
- <Portion of Project B that were referenced>
    - FetchGranma()

Note that all files that Prject C uses should be on their own directory, so that if I were to publish Project C, end users would see it as a single standalone repository without any dependencies.

I have hundreds of such references at hand. I can not possibly do this manually; painfully fixing import/export syntaxes and so on. Can it be automated? If so, how?


问:
Dropdown only displaying the first option
I’ve been trying to create an app that displays information from a dataset. The problem is it only displays the data for the first option not the option the user selected. Can someone please help me

I tried changing creating a variable for the dropdown and then adding another first option. I also tried creating an array that holds the information for the option the user chose. They didn’t work


问:
WebStorm + Prettier setting that keeps putting my HTML into one line
I'm trying to set up Prettier to run every time I save but I can't seem to find a certain setting.

export default function RaisedContainer({ children }: IProps) {
  return (

      {children}

  );
}
```
<p>gets turned into</p>
<pre class="lang-js prettyprint-override"><code>export default function RaisedContainer({ children }: IProps) {
  return <div>{children}</div>;
}
</code>```

I do not want this to happen. Where in the settings can I stop this from happening?

Body:
I'm trying to set up Prettier to run every time I save but I can't seem to find a certain setting.

export default function RaisedContainer({ children }: IProps) {
  return (

      {children}

  );
}

gets turned into

export default function RaisedContainer({ children }: IProps) {
  return
{children}
;
}

I do not want this to happen. Where in the settings can I stop this from happening?


问:
configure firefox/brave to store webpages in safari webarchive format?
I want to configure firefox/brave to store webpages in safari webarchive format.

There used to be a plugin for firefox. But it is not available anymore.

Is there a way to do so?