text:
Q: error CS0012: The type ... is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=2.0.5.0 I get this error when I build the code using my fork of StackExchange.Precompilation - https://github.com/MarkKharitonov/StackExchange.Precompilation
So I took it (following the advice in https://stackoverflow.com/a/71611526/80002), adjusted it to work with the most recent versions of the packages and it works well:
C:\work\StackExchange.Precompilation [master ≡]> git lg -4
e9055ed |  (HEAD -> master, origin/master, origin/HEAD) Enable convenient debugging of the precompiler. (6 minutes ago) [Kharitonov, Mark] (2022-03-26 20:04:24 -0400)
7568de6 |  Minor changes, #define SE_PRECOMPILER_INCLUDE_RAZOR automatically when necessary. (4 hours ago) [Kharitonov, Mark] (2022-03-26 15:44:05 -0400)
50349c3 |  Update the code to use the most recent packages. (7 hours ago) [Kharitonov, Mark] (2022-03-25 20:01:26 -0400)
d595fac |  sourcelink it is (3 years, 3 months ago) [sprelog] (2018-12-14 14:41:05 +0100)
C:\work\StackExchange.Precompilation [master ≡]> .\BuildAndPack.ps1 -Debug
  Determining projects to restore...
  Restored C:\work\StackExchange.Precompilation\StackExchange.Precompilation.Tests\StackExchange.Precompilation.Tests.csproj (in 592 ms).
  Restored C:\work\StackExchange.Precompilation\Test.Module\Test.Module.csproj (in 592 ms).
  Restored C:\work\StackExchange.Precompilation\Test.ConsoleApp\Test.ConsoleApp.csproj (in 592 ms).
  Restored C:\work\StackExchange.Precompilation\Test.WebApp.ExternalViews\Test.WebApp.ExternalViews.csproj (in 592 ms).
  Restored C:\work\StackExchange.Precompilation\StackExhcange.Precompilation.MVC5\StackExchange.Precompilation.MVC5.csproj (in 592 ms).
  Restored C:\work\StackExchange.Precompilation\Test.WebApp\Test.WebApp.csproj (in 592 ms).
  Restored C:\work\StackExchange.Precompilation\StackExchange.Precompilation\StackExchange.Precompilation.csproj (in 592 ms).
  Restored C:\work\StackExchange.Precompilation\StackExchange.Precompilation.Build\StackExchange.Precompilation.Build.csproj (in 592 ms).
  StackExchange.Precompilation -> C:\work\StackExchange.Precompilation\StackExchange.Precompilation\bin\Debug\net472\StackExchange.Precompilation.dll
  StackExchange.Precompilation.Build -> C:\work\StackExchange.Precompilation\StackExchange.Precompilation.Build\bin\Debug\net472\StackExchange.Precompiler.exe
  Test.Module -> C:\work\StackExchange.Precompilation\Test.Module\bin\Debug\net472\Test.Module.dll
  StackExchange.Precompilation.MVC5 -> C:\work\StackExchange.Precompilation\StackExhcange.Precompilation.MVC5\bin\Debug\net472\StackExchange.Precompilation.MVC5.dll
  Test.ConsoleApp -> C:\work\StackExchange.Precompilation\Test.ConsoleApp\bin\Debug\net472\Test.ConsoleApp.exe
  Test.WebApp.ExternalViews -> C:\work\StackExchange.Precompilation\Test.WebApp.ExternalViews\bin\Debug\net472\Test.WebApp.ExternalViews.dll
  Test.WebApp -> C:\work\StackExchange.Precompilation\Test.WebApp\bin\Test.WebApp.dll
  StackExchange.Precompilation.Tests -> C:\work\StackExchange.Precompilation\StackExchange.Precompilation.Tests\bin\Debug\net472\StackExchange.Precompilation.Tests.dll
  Successfully created package 'C:\work\StackExchange.Precompilation\packages\obj\StackExchange.Precompilation.Build.6.1.0-local1648325439.nupkg'.
  Successfully created package 'C:\work\StackExchange.Precompilation\packages\obj\StackExchange.Precompilation.6.1.0-local1648325439.nupkg'.
  Successfully created package 'C:\work\StackExchange.Precompilation\packages\obj\StackExchange.Precompilation.MVC5.6.1.0-local1648325439.nupkg'.
C:\work\StackExchange.Precompilation\Test.ConsoleApp\Program.cs
C:\work\StackExchange.Precompilation\Test.ConsoleApp\Program.cs
Test.ConsoleApp.AliasTest
C:\work\StackExchange.Precompilation [master ≡]>

I made a small change to Test.WebApp and now it fails:
C:\work\StackExchange.Precompilation [master ≡]> git co WithCommonLogging
Switched to branch 'WithCommonLogging'
Your branch is up to date with 'origin/WithCommonLogging'.
C:\work\StackExchange.Precompilation [WithCommonLogging ≡]> git lg -2
13a2c5f |  (HEAD -> WithCommonLogging, origin/WithCommonLogging) Add a test case involving Common.Logging, which depends on mscorlib 2.0.5.0 - currently breaks the build. (8 minutes ago) [Kharitonov, Mark] (2022-03-26 20:05:26 -0400)
e9055ed |  (origin/master, origin/HEAD, master) Enable convenient debugging of the precompiler. (9 minutes ago) [Kharitonov, Mark] (2022-03-26 20:04:24 -0400)
C:\work\StackExchange.Precompilation [WithCommonLogging ≡]> .\BuildAndPack.ps1 -Debug
  Determining projects to restore...
  Restored C:\work\StackExchange.Precompilation\StackExchange.Precompilation\StackExchange.Precompilation.csproj (in 585 ms).
  Restored C:\work\StackExchange.Precompilation\StackExchange.Precompilation.Tests\StackExchange.Precompilation.Tests.csproj (in 586 ms).
  Restored C:\work\StackExchange.Precompilation\Test.ConsoleApp\Test.ConsoleApp.csproj (in 586 ms).
  Restored C:\work\StackExchange.Precompilation\StackExhcange.Precompilation.MVC5\StackExchange.Precompilation.MVC5.csproj (in 586 ms).
  Restored C:\work\StackExchange.Precompilation\Test.WebApp\Test.WebApp.csproj (in 586 ms).
  Restored C:\work\StackExchange.Precompilation\Test.Module\Test.Module.csproj (in 586 ms).
  Restored C:\work\StackExchange.Precompilation\StackExchange.Precompilation.Build\StackExchange.Precompilation.Build.csproj (in 586 ms).
  Restored C:\work\StackExchange.Precompilation\Test.WebApp.ExternalViews\Test.WebApp.ExternalViews.csproj (in 585 ms).
  StackExchange.Precompilation -> C:\work\StackExchange.Precompilation\StackExchange.Precompilation\bin\Debug\net472\StackExchange.Precompilation.dll
  StackExchange.Precompilation.Build -> C:\work\StackExchange.Precompilation\StackExchange.Precompilation.Build\bin\Debug\net472\StackExchange.Precompiler.exe
  Test.Module -> C:\work\StackExchange.Precompilation\Test.Module\bin\Debug\net472\Test.Module.dll
  StackExchange.Precompilation.MVC5 -> C:\work\StackExchange.Precompilation\StackExhcange.Precompilation.MVC5\bin\Debug\net472\StackExchange.Precompilation.MVC5.dll
  Test.ConsoleApp -> C:\work\StackExchange.Precompilation\Test.ConsoleApp\bin\Debug\net472\Test.ConsoleApp.exe
  Test.WebApp.ExternalViews -> C:\work\StackExchange.Precompilation\Test.WebApp.ExternalViews\bin\Debug\net472\Test.WebApp.ExternalViews.dll
C:\work\StackExchange.Precompilation\Test.WebApp\MvcApplication.cs(29,13): error CS0012: The type 'Action<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes'. [C:\work\StackExchange.Precompilation\Test.WebApp\Test.WebApp.csproj]
  StackExchange.Precompilation.Tests -> C:\work\StackExchange.Precompilation\StackExchange.Precompilation.Tests\bin\Debug\net472\StackExchange.Precompilation.Tests.dll
MSBuild failed

The change is:

*

*Add NuGet reference to Common.Logging

*Call ILog.Info
https://github.com/MarkKharitonov/StackExchange.Precompilation/commit/13a2c5f4a27915307d0a403d1c73f0922da87ebe
And now it fails with the error message
C:\work\StackExchange.Precompilation\Test.WebApp\MvcApplication.cs(29,13): error CS0012: The type 'Action<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes'. [C:\work\StackExchange.Precompilation\Test.WebApp\Test.WebApp.csproj]

Now I understand that StackExchange.Precompilation copies the logic of csc.exe code from 7 years ago. Unfortunately, so far it is the best I have to replace aspnet_compiler.exe.
So my question is simple - how do we fix it?


text:
Q: chance for re-using oracle database after system migration? I have an ERP application running with Oracle forms and Oracle database. Now I am planning to migrate this application to a java based enterprise application. will it be a good idea to keep the existing oracle database as back end and developing a web application with certain level of changes/additions in the DB design.

A: There are two facts to know before answer your questions:

*

*has your database schema some oracle forms special structures or is it in 3rd normal form and simply stores data using keys and enforced referential integrity?

*How much stored code contains your database?

Ad 1. Oracle forms don't have specific schema reqiurements. They work best if your schema if based on 3rd normal form. If your schema is like this, use it for new Java application. We have both forms and Java EE applications on same database schemas and is works fine.
Advantage is, if you have keys (primary, unique, foreign) in your schema. Use them when generating Java app.
Probably you will have to add @Version columns for optimistic locking (see https://docs.oracle.com/javaee/6/api/javax/persistence/Version.html). But there is not reason to build new schema for it.
Ad 2. Your will have to overwrite bigger part of database stored code (triggers, procedures, functions) to Java. In most cases this does not have dramatic impact to schema structure, but deal with it.
So - if your database schema is not tailored to some UI client needs AND you want only use a new client, use your schema. If not, create a new one.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Updating text of element makes it disappear In Chrome 27 (Windows) when I update the text of a specific element, the text disappears completely until I make it "refresh" but changing the CSS of any element or window size or whatever.
Firefox is fine, haven't tried any other browser or OS (yet). I suspect its a Chrome-specific bug. I just want to make sure I'm not going insane.
I am using: CSS3 transforms in some places; web fonts (tested without them and it still happens); nested position: fixed and z-index
It's similar to this SO question however when I disable web fonts (and falled back to Arial then sans-serif) it still occurs. I suspect it has something to do with the layering I'm doing and CSS3 transforms.
The element updating is a DIV within this container:
NAV {width:100%;height:50px;position:fixed;top:0;left:0;z-index:110;padding:15px 0;text-shadow:1px 1px 2px #FFF;font-size:110%;font-weight:500;color:#565656}

Which is wrapped in a parent page:
#pages {width:100%;position:relative;overflow-x:hidden}

#pages .page {width:100%;height:100%;position:absolute;top:0;left:0;padding-top:50px;-webkit-transition:all 0.5s ease-in-out;-moz-transition:all 0.5s ease-in-out;-o-transition:all 0.5s ease-in-out;-ms-transition:all 0.5s ease-in-out;transition:all 0.5s ease-in-out}

I apply CSS3 transforms only when animating pages in/out, however the bug occurs after the transform is complete:
#pages .page.left {-ms-transform:translateX(-100%);-o-transform:translateX(-100%);-moz-transform:translateX(-100%);-webkit-transform:translateX(-100%);transform:translateX(-100%)}
#pages .page.right {-ms-transform:translateX(100%);-o-transform:translateX(100%);-moz-transform:translateX(100%);-webkit-transform:translateX(100%);transform:translateX(100%)}

The code that updates the text (trimmed down):
$('.page[data-page="Game"]').find('NAV .title').text('My text');

I don't have a demo to show you yet, sorry. If you need more code, please let me know in the comments (as I'm sure you would do anyway). I've left out the HTML because I believe it's irrelevant unless you really want to see it.


text:
Q: Is a class "cannot be subclassed" implied by "composed solely of static members"? in C# in a nutshell,

A class can be marked  static , indicating that it must be composed
  solely of static members and cannot be subclassed.

*

*Is "cannot be subclassed" implied by "composed solely of static members"?

*If a class is composed solely of static members but not declared with static, is it effectively a static class? Can it be subclassed?
Thanks.

A: Is "cannot be subclassed" implied by "composed solely of static members"?
Nope
If a class is composed solely of static members but not declared with static, is it effectively a static class? Can it be subclassed?
it is still a normal class and can be subclassed (not discussing the sealed classes)


text:
Q: Add DATE to Xcode xcconfig file I have an Xcode config file, Config.xcconfig that contains this row only:
BUILD_DATE=`date "+%B %Y"`

I added this configuration to project in correct way, i hope.

I want to use the content of BUILD_DATE variable in the Application-info.plist file. How?
I tried get value using ${BUILD_DATE} but result is the string ``date "+%B %Y"` not the value!

From terminal, result is correct:
alp$ BUILD_DATE=`date "+%B %Y"`
alp$ echo $BUILD_DATE
March 2013
alp$

but in Xcode no!

How can i fix this?

A: You cannot get the build date using the backtick command as the .xcconfig file is not interpreted as a shell script.
Your best bet is to use a similar approach the Bump Build Number script in this SO question (that I asked a while back), which provides a solution for using an external build script to update the .plist file.
For example:
#!/bin/sh

if [ $# -ne 1 ]; then
    echo usage: $0 plist-file
    exit 1
fi

plist="$1"
build_date=$(date "+%B %Y")

/usr/libexec/Plistbuddy -c "Set BUILD_DATE \"$build_date\"" "$plist"

and invoke it from the Xcode Build Script using something like:
"${PROJECT_DIR}/tools/set_build_date.sh" "${PROJECT_DIR}/${INFOPLIST_FILE}"


text:
Q: Sort multi array by number javascript I have this multi array with a url and number in each inner array, how do i sort so the array is organized by highest number to smallest.
var arr = [
["http://example.com", "3"],
["http://example.com2", "1"],
["http://example.com3", "22"]
]

i want it to look like this
var arr = [
["http://example.com3", "22"],
["http://example.com", "3"],
["http://example.com2", "1"],
]

A: You can use .sort function with custom compareFunction, like this

var arr = [
  ["http://example.com", "3"],
  ["http://example.com2", "1"],
  ["http://example.com3", "22"]
];

var res = arr.sort(function (a, b) {
  return b[1] - a[1];
});

console.log(res);


text:
Q: Whether a FormControl value can be an array? I am working on Angular Reactive form. This is my component class code:
ngOnInit(){
        this.reviewForm = this.fb.group({
            'controlArray': new FormArray([])
        });
        this.showDefaultForm();
    }

addForm() {
    (<FormArray>this.reviewForm.get('controlArray')).push(this.fb.group({
        controlType: control.controlType,
        options: control.options,

    }));
}

I am getting TypeError: this.validator is not a function with this. I think its due to assigning a string array (i.e. control.options) as value to FormControl.
If I make it a FormArray then this error resolves, but I am having issue to handle it as FormArray in template. Please tell if I don't use FormArray, can I assign a string array as value to FormControl? If no then  how to handle it as FormArray in template. Thanks

A: Finally I solved it, and the answer is yes. A FormControl's value can be an array. But for this you must have to enclose the value with in square brackets [ ]. Moreover, for simple values(Non arrays) these Square brackets are optional, meaning you may enclose the value within or without square brackets.
Code explanation:
(<FormArray>this.reviewForm.get('controlArray')).push(this.fb.group({
        controlType: control.controlType,
        options: [control.options], //previously I was not using square brackets with options value i.e. options: control.options which was wrong.

    }));


text:
Q: Slider not responsive and creates extra height into the section below it I have been working on websites that use the Bodega theme from Select themes and the Select Slider keeps creating weird issues on scroll and in responsive view.
The website with issues is this one: http://185.56.86.90/~onetoncr/friedmanpr.com/. And in mobile view, there is a weird expanding white section beneath the slider that gets larger as you scroll.
https://postimg.cc/bG3PbXyS
https://postimg.cc/jw2b482g
This seems to be the code at hand with this slider:

I want the slider to just not interact at all with the section below it.

A: #qode-home-slider has height that is too much for mobile prortrait display. You can add CSS rule with media query that will fix this. Something like:
@media only screen and (max-width: 768px) {
   #qode-home-slider{
       height: 340px;
   }
}

Please note that height values may change as your code is changing.


text:
Q: How do I get Mockito to return data if parameter fields match but not necessarily the parameter object references themselves? I'm using Mockito 1.9.5, Maven 3.2.3, and JUnit 4.11.  I have the following set up in a JUnit test ...
    final Set<Account> accounts = new HashSet<Account>();
    final Account acct1 = new Account();
    acct1.setId("id1");
    accounts.add(acct1);
    …
    Mockito.doReturn(acctTeamMemberMap).when(m_accountTeamMemberDao).getManagers(accounts);

The problem is the Account objects I'm creating in my JUnit test are not the same objects that are actually being passed in as parameters when I execute the method call.  My question is, how do I tell Mockito to return the results when the ID fields of the various objects match the IDs I have in my JUnit test?  In other words, if the above Account objects have ids "id1" and "id2", I would want Mockito to return the results always if the actual parameters also have ids "id1" and "id2".
Thanks, - Dave

A: You can use any() matcher from Mockito, and just return result no matter what value was passed:
Mockito.doReturn(acctTeamMemberMap).when(any()).getManagers(accounts);

Alternatively you can implement your own matcher and check if value that is was passed follows the specified constraints:
class IsListOfTwoElements extends ArgumentMatcher<List> {
      public boolean matches(Object myDao) {
          String id =  ((MyDao) myDao).size().getId();
          return id.equals("id1") || id.equals("id2");
      }
   }


text:
Q: Wrangling Control of HTTP Headers in ASP.NET I'm working with ASP.NET MVC3, and I'm trying to get absolute control over my headers because a client application that I'm working with expects a very specific content type. What I'm finding when using Fiddler to examine the HTTP traffic is that the text encoding is being returned as part of the header.
For example, the client is expecting application/appname in the Content-Type header, but the server is returning application/appname; charset=utf-8. I think the client is using a strict comparison for checking the type, so I want to be able to specify exactly what is emitted in the headers.
Right now I have a custom ActionResult in which I clear the headers and then specify only the content type, but the encoding still seems to be added on.
How can I remove the encoding from the Content-Type header?

A: Charset Encoding in ASP.NET Response from Rick Strahl is an older (2007) article, but maybe give it a try.
Response.ContentType = "application/appname";
Response.Charset = null;


text:
Q: How to apply transfer learning to Lasso model (or other linear models)? I am familiar with the use of Transfer Learning to Neural Networks models, but I am wondering whether it would be possible to apply it to linear models, and in particular to parsimonious models such as Lasso.
More formally, I have an initial dataset $D$ containing $N$ observations $(y^{(i)}, \mathbf{X}^{(i)})_{1 \leq i \leq N}$, where $y^{(i)}$ is a (scalar) response variable, and $\mathbf{X}^{(i)} \in \mathbb{R}^{p}$ is a vector of predictors. This dataset is used to fit a linear model $\mathcal{L}$, which writes in vector notation:
$y = \mathbf{\alpha}^T \mathbf{X}$, where $\mathbf{\alpha} \in \mathbb{R}^{p}$ is the vector of model coefficients (note that $\mathbf{\alpha}$ has many zero, or at least very small, components if I use a Lasso regularization).
Then, I have a second dataset $D'$ containing $M$ observations $(y, \mathbf{X})$. Typically this second dataset is much smaller than the initial one: $M \ll N$. The objective is now to fit a new linear model $\mathcal{L}'$ on $D'$, while reusing the initial model $\mathcal{L}$.
$\mathcal{L}'$ could write:  $y = \mathcal{T}(\mathbf{\alpha})^T \ \mathbf{X}$, where $\mathcal{T}(\mathbf{\alpha})$ is a function of the initial model coefficients, that also depends on the new dataset $D'$.
The new model coefficients $\mathcal{T}(\mathbf{\alpha})$ could be a nonlinear function of $\mathbf{\alpha}$, but it could also depend linearly on $\mathbf{\alpha}$: $\mathcal{T}(\mathbf{\alpha}) = \mathbf{\beta} \mathbf{\alpha} $ with $\mathbf{\beta} \in  \mathbb{R}^{p \times p}$. I have a few questions about how to construct the new model coefficients $\mathcal{T}(\mathbf{\alpha})$, and once again I would like to emphasize that my main concern is related to the very low-data regime, where $M \ll p , N$.

*

*Would a nonlinear $\mathcal{T}(\mathbf{\alpha})$ be preferable to a linear one? In particular, I am thinking of incorporating any type of available prior knowledge or inductive bias into the nonlinearity of $\mathcal{T}(\mathbf{\alpha})$. This is a very broad question, but any suggestion of reference to literature would be welcome.

*In the case where $\mathcal{T}(\mathbf{\alpha}) = \mathbf{\beta} \mathbf{\alpha} $ is linear, there is nothing that guarantees that the new model coefficients would still be sparse. Is there any type of method to impose a structure on the $\mathbf{\beta}$ matrix, such that there would a guarantee on the resulting $\mathcal{T}(\mathbf{\alpha})$ to still be sparse? In particular, how to preserve the same sparsity structure as the original $\mathbf{\alpha}$?

*If I have some prior knowledge about the general structure of $\mathbf{\beta}$, are there any Bayesian method that could help me to incorporate this prior information into $\mathbf{\beta}$, and would this help to deal with the very low-data regime?

*How would you perform cross-validation to select the best possible $\mathbf{\beta}$? $M$ could be really small, so I am thinking of something like "leave one out" or the "jackknife", to keep as many observations as possible for the training itself.


text:
Q: Data transfer from gridview column of one page to label of another page in C# where the gridview is autogenerated protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var firstCell = e.Row.Cells[0];
            firstCell.Controls.Clear();
            firstCell.Controls.Add(new HyperLink { NavigateUrl = "ser_job_status1.aspx?Complaint_No = " + firstCell.Text, Text = firstCell.Text, Target = "_blank" });
        }
    }
}

I have used this to include hyperlink in my gridview.If that link is clicked it may take me to   ser_job_status1.aspx where Complaint_No is my table field name.
is it correct...
If correct how do i get that Complaint_No value in the Label field of my second page..
Kindly help me to figure it out...
I use C# in code behind

A: In ser_job_status1.aspx page:
string strComplaintNo=Request.Querystring["Complaint_No"];
label1.text=strComplaintNo
or
Use Session rowdatabound page
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var firstCell = e.Row.Cells[0];
            Session["ComplaintNo"]=firstCell.text;
            firstCell.Controls.Clear();
            firstCell.Controls.Add(new HyperLink { NavigateUrl = "ser_job_status1.aspx?Complaint_No = " + firstCell.Text, Text = firstCell.Text, Target = "_blank" });
        }
    }
}
In ser_job_status1.aspx page:
label1.text=convert.tostring(Session["ComplaintNo"]);


text:
Q: Linux Bash: cURL - how to pass variables to the URL I want to do cURL GET-request. The following URL should be used:
https://iant.toulouse.inra.fr/bacteria/annotation/cgi/rhime.cgi' -H 'Host: iant.toulouse.inra.fr' -H 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H 'Accept-Language: de,en-US;q=0.7,en;q=0.3' --compressed -H 'Referer: https://iant.toulouse.inra.fr/bacteria/annotation/cgi/rhime.cgi?__wb_cookie=&__wb_cookie_name=auth.rhime&__wb_cookie_path=/bacteria/annotation/cgi&__wb_session=WB84Qfsf&__wb_main_menu=Genome&__wb_function=$parent' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Connection: keep-alive' -H 'Upgrade-Insecure-Requests: 1' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' --data '__wb_function=PortalExtractSeq&mode=run&species=rhime&fastafile=%2Fwww%2Fbacteria%2Fannotation%2F%2Fsite%2Fprj%2Frhime%2F%2Fdb%2F$ab.genomic&begin=$start&end=$end&strand=$strand

At the end of the URL, I have some words, which I want to design as variables, so depending on the input, the URL is different and I then request another resource.
The end of the URL. $ab, $start, $end and $strand are the variables, all of them are Strings.
...2Frhime%2F%2Fdb%2F$ab.genomic&begin=$start&end=$end&strand=$strand

I came across "urlencode" and I though of storing my URL as one big String in a variable and pass it to URL encode, but I am not sure, how to do it.
I tried this/I am searching for something like this:
#!bin/bash
[...]
cURL="https://iant.toulouse.inra.fr/bacteria/annotation/cgi/rhime.cgi' -H 'Host: iant.toulouse.inra.fr' -H 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H 'Accept-Language: de,en-US;q=0.7,en;q=0.3' --compressed -H 'Referer: https://iant.toulouse.inra.fr/bacteria/annotation/cgi/rhime.cgi?__wb_cookie=&__wb_cookie_name=auth.rhime&__wb_cookie_path=/bacteria/annotation/cgi&__wb_session=WB84Qfsf&__wb_main_menu=Genome&__wb_function=$parent' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Connection: keep-alive' -H 'Upgrade-Insecure-Requests: 1' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' --data '__wb_function=PortalExtractSeq&mode=run&species=rhime&fastafile=%2Fwww%2Fbacteria%2Fannotation%2F%2Fsite%2Fprj%2Frhime%2F%2Fdb%2F$ab.genomic&begin=$start&end=$end&strand=$strand"

# storing HTTP response code in variable response. Only if the
# reponse code is OK (200), we move on
  response=$(curl -X HEAD -I --header 'Accept:txt/html' "https://iant.toulouse.inra.fr/bacteria/annotation/cgi/rhime.cgi?__wb_cookie=&__wb_cookie_name=auth.rhime&__wb_cookie_path=/bacteria/annotation/cgi&__wb_session=WB8jqwTM&__wb_main_menu=Genome&__wb_function="$location""|head -n1|awk '{print $2}')

  echo "$response"

# getting information via curl request
  if [ $response = 200 ] ; then
    info=$(curl -G "$ (urlencode "$cURL")")
  fi

  echo $info

For my response-code checkup, the method of directly passing $location seems to work, but with more variables, I get an error (response code 100, whereas I get 200 with the code-checkup)
Do I have a general error in understanding curl/urlencode? What did I miss?
Thanks for you time and effort in advance :)
UPDATE
#!/bin/sh
# handling command-line input
file=$1
ecf=$2

# iterating through file and pulling out
# information for the GET- and POST-request

while read -r line
  do
    parent=$(echo $line | awk '{print substr($1,2,3)}')
    start=$(echo $line | awk '{print substr($2,2,6)}')
    end=$(echo $line | awk '{print substr($3,2,6)}')
    strand=$(echo $line | awk '{print substr($4,2,1)}')
    locus=$(echo $line | awk '{print substr($6,2,8)}')

# depending on $parent, the right insertion for the URL is generated
    if [ $parent = "SMc" ] ; then
      location="Genome"
      ab="SMc"
    elif [ $parent = "SMa" ] ; then
      location="PrintPsyma"
      ab="pSymA"
    else [ $parent = "SMb" ]
      location="PrintPsymb"
      ab="pSymB"
    fi
# building variables for curl content request

  options=( --compressed)

  headers=(
    -H 'Host: iant.toulouse.inra.fr'
    -H 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0'
    -H 'Accept: txt/html,application/xhtml+xml,application/xml;1=0.9,*/*;q=0.8'
    -H 'Accept-Language: de,en-US;q=0.7,en;q=0.3'
    -H 'Referer: https://iant.toulouse.inra.fr/bacteria/annotation/cgi/rhime.cgi?__wb_cookie=&__wb_cookie_name=auth.rhime&__wb_cookie_path=/bacteria/annotation/cgi&__wb_session=WB84Qfsf&__wb_main_menu=Genome&__wb_function=$parent'
    -H 'Content-Type: application/x-www-form-urlencoded'
    -H 'Connection: keep-alive'
    -H 'Upgrade-Insecure-Requests: 1'
    -H 'Pragma: no-cache'
    -H 'Cache-Control: no-cache'
  )

    url='https://iant.toulouse.inra.fr/bacteria/annotation/cgi/rhime.cgi'

    ab=$(urlencode "${ab}")
    start=$(urlencode "${start}")
    end=$(urlencode "${end}")
    strand=$(urlencode "${strand}")
    data="__wb_function=PortalExtractSeq&mode=run&species=rhime&fastafile=%2Fwww%2Fbacteria%2Fannotation%2F%2Fsite%2Fprj%2Frhime%2F%2Fdb%2F$ab.genomic&begin=$start&end=$end&strand=$strand"

# storing HTTP response code in variable response. Only if the
# reponse code is OK (200), we move on
    response=$(curl -X HEAD -I --header 'Accept:txt/html' "https://iant.toulouse.inra.fr/bacteria/annotation/cgi/rhime.cgi?__wb_cookie=&__wb_cookie_name=auth.rhime&__wb_cookie_path=/bacteria/annotation/cgi&__wb_session=WB8jqwTM&__wb_main_menu=Genome&__wb_function="$location""|head -n1|awk '{print $2}')

    echo "$response"

# getting information via curl request
    if [ $response = 200 ] ; then
        info=$(curl -G "${options[@]}" "${headers[@]}" --data "${data}" "${url}")
    fi

    echo $info

done < $file

A: You need to separate concepts. That string that you put in cURL variable is not a URL, it is URL + set of headers + parameters + one option for compression. They all are different things.
Define them separately like this:
url='https://iant.toulouse.inra.fr/bacteria/annotation/cgi/rhime.cgi'
headers=(
    -H 'Host: iant.toulouse.inra.fr'
    -H 'User-Agent: ...'
    -H 'Accept: ...'
    -H 'Accept-Language: ...'
    ... other headers from your example ...
)
options=(
    --compressed
)
data="__wb_function=PortalExtractSeq&mode=run&species=rhime&fastafile=%2Fwww%2Fbacteria%2Fannotation%2F%2Fsite%2Fprj%2Frhime%2F%2Fdb%2F$ab.genomic&begin=$start&end=$end&strand=$strand"

And then run curl in this fashion:
curl -G "${options[@]}" "${headers[@]}" --data "${data}" "${url}"

This will expand to correct curl command.
About urlencode part: You need encode each of $ab, $start, $end and $strand separately. If you insert them in the string and then encode, then all special characters in that string like & and = will be encoded too, and those already encoded ones like %2F in your example will be encoded twice (will become %252F).
To keep the code tidy, you can encode them beforehand:
ab=$(urlencode "${ab}")
start=$(urlencode "${start}")
end=$(urlencode "${end}")
strand=$(urlencode "${strand}")
data="__wb_function=PortalExtractSeq&mode=run&species=rhime&fastafile=%2Fwww%2Fbacteria%2Fannotation%2F%2Fsite%2Fprj%2Frhime%2F%2Fdb%2F$ab.genomic&begin=$start&end=$end&strand=$strand"

... or do it in a cumbersome way:
data="__wb_function=PortalExtractSeq&mode=run&species=rhime&fastafile=%2Fwww%2Fbacteria%2Fannotation%2F%2Fsite%2Fprj%2Frhime%2F%2Fdb%2F$(urlencode "${ab}").genomic&begin=$(urlencode "${start}")&end=$(urlencode "${end}")&strand=$(urlencode "${strand}")"

I hope this helps.


text:
Q: Record and send user input to CSV I have a "Stroop test" page that i modified from a github source to fit my needs.
Basically its a cognitive test which shows a colored word with a different color name, like the word Red, but colored in green, and then the user has 4 options to choose the correct color of the word.
I have a Record function in the js file which records the time it took to answer a question and the total time as well, and output to CSV file at the end of the test.
But also, i wish to record to that CSV: the specific word that was displayed, the color of the word that was displayed, and what dose the user answered, in each question. Is it possible?
JS:
 var COLORS = new Array(
  "red",
  "blue",
  "green",
  "yellow",
  "black",
  "pink",
  //"brown",
  "#FE642E",
  "purple",
  "gray"
);
// Text can be anything.
var TEXT = new Array(
  "RED",
  "BLUE",
  "GREEN",
  "YELLOW",
  "BLACK",
  "PINK",
  //"BROWN",
  "ORANGE",
  "PURPLE",
  "GRAY"
);

var info = new Array(["Name",""],["AGE",""],["Date",""],["Sex",""],["Education",""],
                      ["Mother Tougue",""],["Place",""]);
var formObj=document.getElementById('han-form');
var IntroObj=document.getElementById('han-Intro');
var InstructionsObj=document.getElementById('instructions');
var Start=document.getElementById('startstop');
var hanTitle=document.getElementById('han-title');
var hanIntro=document.getElementById('han-Intro');
var Content=document.getElementById('content');
var name=document.getElementById('names');
var opt=document.getElementById('options');
var maxCount

function form1 () {
  formObj.style.display='block';
  IntroObj.style.display='None';
  hanIntro.style.display='None';
  document.getElementById('AGE').value=info[1][2];
  document.getElementById('MT').value=info[5][3];
}

function trim(stringToTrim) {
  return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function validate () {
  if(trim(document.getElementById('AGE').value)=="")
  {
  alert("Please fill in your Age");
  document.getElementById('AGE').focus();
  return false;
  }
  if(trim(document.getElementById('sex').value)=="")
  {
  alert("Please fill in your Gender");
  document.getElementById('sex').focus();
  return false;
  }
  if(trim(document.getElementById('MT').value)=="")
  {
  alert("Please fill in your Native Tounge");
  document.getElementById('MT').focus();
  return false;
  }

  var d=new Date();
  info[1][4]=document.getElementById('AGE').value;
  info[2][5]=d.toDateString();
  info[3][6]=document.getElementById('sex').value;
  info[5][7]=document.getElementById('MT').value;
Instructions();
}

function Instructions () {
  IntroObj.style.display='None';
  hanIntro.style.display='None';
  formObj.style.display='None';
  InstructionsObj.style.display='block';
}

function Demo()
{
  maxCount=5;
  hanTitle.style.display='None';
  InstructionsObj.style.display='None';
  Start.style.display='block';
  document.getElementById('timetext').innerHTML="Here's an example test with 5 questions:";

  var initial=document.getElementById('time').innerHTML;
    var timeElement=document.getElementById('time');
    var myVar=setInterval(function () {myTimer()}, 1000);
    function myTimer () {
      initial=initial-1;
      //alert(typeof 'timeElement');
      if(timeElement.innerHTML!='0')
      {
          timeElement.innerHTML=initial;
      }
      else
      {
        clearInterval(myVar);
        Questions ();
      }
    }

}

function StartTest () {
  hanTitle.style.display='None';
  InstructionsObj.style.display='None';
  Start.style.display='block';
  Content.style.display='None';
  opt.style.display='None';
  initial=5;
  document.getElementById('time').innerHTML="5";
  document.getElementById('timetext').innerHTML="Test Starts In:";
    var timeElement=document.getElementById('time');
    var myVar=setInterval(function () {myTimer()}, 1000);
    function myTimer () {
      initial=initial-1;
      //alert(typeof 'timeElement');
      if(timeElement.innerHTML!='0')
      {
          timeElement.innerHTML=initial;
      }
      else
      {
        clearInterval(myVar);
        Questions ();
      }
    }
}

function reload () {
  location.reload();
}

var Result=new Array([1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[8,0],[9,0],[10,0],
                     [11,0],[12,0],[13,0],[14,0],[15,0],[16,0],[17,0],[18,0],[19,0],[20,0],
                     [21,0],[22,0],[23,0],[24,0],[25,0],[26,0],[27,0],[28,0],[29,0],[30,0]);

var lastColorIndex="red";
  var  lastTextIndex="RED";
  var a;
  var Count=0;
  var Score=0;
  var TotalTime=0;

function Questions (){
  document.getElementById('startstop').style.display='None';
  Content.style.display='block';
  opt.style.display='block';
  var options=new Array(4);
  var hash = [0,0,0,0,0,0,0,0,0,0];
  var i=0;
  var colorIndex = Math.floor(COLORS.length * Math.random());
  while (colorIndex == lastColorIndex)
  {
    colorIndex = Math.floor(COLORS.length * Math.random());
  }

  // Do not repeat last text.
  var textIndex = Math.floor(TEXT.length * Math.random());
  while (textIndex == lastTextIndex) {
    textIndex = Math.floor(TEXT.length * Math.random());
  }

  document.getElementById('content').innerHTML=TEXT[textIndex];
  document.getElementById('content').style.color=COLORS[colorIndex];
  AnswerIndex=Math.floor(options.length*Math.random());
  options[AnswerIndex]=TEXT[colorIndex];
  hash[colorIndex]=1;
  for (i =0 ; i < 4; i++) {
    if(i!=AnswerIndex)
      {
        while (true)
        {
          Index = Math.floor(COLORS.length * Math.random());
          if (hash[Index]!=1) {
            options[i]=TEXT[Index];
            hash[Index]=1;
            break;
          }
        }
      }
  }
  document.getElementById('A').innerHTML=options[0];
  document.getElementById('B').innerHTML=options[1];
  document.getElementById('C').innerHTML=options[2];
  document.getElementById('D').innerHTML=options[3];

  lastColorIndex = colorIndex;
  lastTextIndex = textIndex;
   a = performance.now();
}

function Record (Answer) {
  var b = performance.now();
  if (maxCount==35)
  {
    Result[Count-5][8]=Math.round(((b-a)/1000)*100)/100;
    TotalTime=TotalTime+(b-a)/1000;
    if (document.getElementById(Answer).innerHTML==TEXT[lastColorIndex]) {
        Score+=1;
    }
  }
  Count+=1;
  if (Count<maxCount)
  {
    Questions();
  }
  else if(Count==5 && maxCount==5)
  {
    maxCount=35;
    StartTest();
  }
  else
  {
    document.getElementById('content').style.display='None';
    document.getElementById('options').style.display='None';
    var myChart = new JSChart('chartcontainer', 'line');
    myChart.setDataArray(Result);
    myChart.setSize(1300,500);
    myChart.setTitle('A customized chart');
    myChart.setAxisNameX('Questions');
    myChart.setAxisNameY('Time');
    myChart.setAxisPaddingBottom(40);
    myChart.setAxisPaddingLeft(50);
    myChart.setAxisPaddingRight(30);
    myChart.setAxisPaddingTop(50);
    myChart.draw();
    document.getElementById('score').innerHTML=Score;
    document.getElementById('totaltime').innerHTML=Math.round(TotalTime*100)/100;
    document.getElementById('chartcontainer').style.display='block';
    document.getElementById('endButton').style.display='block';
    var csvContent = "data:text/csv;charset=utf-8,";
    info.forEach(function(infoArray,index){dataString=infoArray.join(",");csvContent+=dataString+"\n";});
    csvContent+="Score"+","+Score+"\n";
    csvContent+="TotalTime"+","+Math.round(TotalTime*100)/100+"\n";
    Result.forEach(function(infoArray, index)
    {
    dataString = infoArray.join(",");
    csvContent += dataString + "\n";
    });

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "my_data.csv");
    link.click();
    window.open(encodedUri);
  }
}

The whole test code:
JSfiddle


text:
Q: How to get a specific time on a specific day SQL query I'm looking to do something similar to Simple DateTime sql query but with a difference: I want to specify the time (7.00 am) on today's date.
I want to count the number of records that match the criteria at that time:
SELECT COUNT(SEQNO)
FROM TABLE
WHERE [CRITERIA]
and [datetimecolumn] between (datetime=[today's date]at 7.00am)
and (datetime=[today's date]at 10.00am)

I can do it with date alone, but the time bit has me confused.

A: Not sure if this will help you as I assume 7am and 10am would remain the same as it is.
============================================
BETWEEN syntax should be something like this
mysql> SELECT * FROM employee_tbl
    -> WHERE daily_typing_pages BETWEEN 170 AND 300;

Credited to this site
So your code should be: (Please include the brackets for the  datetimecolumn)
and ([datetimecolumn] between CONCAT( CURDATE(),  " 07:00:00" )
and CONCAT( CURDATE() ,  " 10:00:00" )

A: try this
 Declare @i date=getdate()
Declare @j varchar(10)='07:00'
Declare @k varchar(10)= '10:00:00'

select COALESCE(COUNT(DISTINCT SOH.SEQNO),0) from dbo.SALESORD_HDR SOH
inner join SALESORDHIST SOHIS on SOH.SEQNO = SOHIS.HEADER_SOURCE_SEQ
where SOHIS.HISTDATETIME between ( DATEADD(day, DATEDIFF(day, 0, @i), @j)
and DATEADD(day, DATEDIFF(day, 0, @i), @k))
and SOHIS.EVENT_TYPE = 'I'


text:
Q: request.auth.token.email not present in the rules Our app uses Firebase as the back end database. Firebase provides authentication for our app with google as the only provider. The authentication works fine. I am getting a "SUCCESS" in the authentication result. I would like to change my firebase rules so only the users that are present in a collection can access the data. For it, I have the rules in firebase to control access to the data. The rules are not working when I use any variables from request.auth.(where as the same works from a simulator)
Below rule working in both app and simulator:
match /restaurants/{$rId}/addresses/{document=**} {
    allow read, write : if get(/databases/$(database)/documents/users/abc@gmail.com).data.restaurantId == $rId;
}

Below rule NOT working from app but working in simulator
match /restaurants/{$rId}/addresses/{document=**} {
    allow read, write : if get(/databases/$(database)/documents/users/$(request.auth.token.email)).data.restaurantId == $rId;
}

I am sending the authentication request from the app as follows:
private void signIn() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

Handling the authentication result below:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
             Toast.makeText(MyApplication.getAppContext(), "Login Successfull", Toast.LENGTH_LONG);
         }
    }
}

My firebase database contains the following structures
Users:
/users
   abc@gmail.com
            -restaurantId: "1"

Restaurants:
/restaurants
   1
          addresses
                 local
                     -name: a
                 international
                     -name: b

   2
          addresses
                 local
                     -name: c
                 international
                     -name: d
   3
          addresses
                 local
                     -name: e
                 international
                     -name: f

I am able to see the Toast "Login successful" when the user tries to login with a valid password.
Should I save the authentication result in the onActivityResult so that further requests will have the request.auth.token.email present? Kinldy please guide me.
Can anyone please let me know if I am doing anything wrong?


text:
Q: Deploy a rails app from a git repo I have a git bare repo on production server:
/home/username/railsapp.git

Now I would like to have a copy to use with mod_rails. Something like:
/home/username/railsapp/

What is the best way to copy the files from the repo to the "production" directory?
Should I do something like a shallow clone?

A: The usual way to "pull" the files out of a bare git repository is indeed to clone the repo and then pull it every time you need to update it.
You can also use hooks to automatically update the code used in production when it's pushed to the repository, but that's another topic.

A: I would recommend using Capistrano, which wraps up the commands to deploy projects from source control (primarily Git).
In short, you configure your environment(s) (multi-stage), indicate which branch should be tracked and when deploying it will clone directly on your deployment machine from your source control (with various caching options).
In addition to that you can wrap in anything else you need bound in to the process, cache clears, database migrations, etc.

With regards to Rails, there'll certainly be Capistrano recipes to get you going that will cache clear, rake and perform other basic tasks on demand.


text:
Q: How correctly get object by screenshot point coordinates in Unity3d? I want to make next:

*

*get screenshot from camera

*process it with python script and find some points

*for each point - find object that projected to this point

Screenshot getting code works well. Python script output has next view:
x=X1 y=Y1 ... \n
x=X2 y=Y2 ... \n

Where 0 <= X1 < screenshot width, 0 <= Y1 < screenshot height.
E.g. in debug mode I can see next image :
As you can see - part of points located on chairs/table projections.
And I need to get this chair/table objects (each object have attached BoxCollider).
I trying to get ray with camera.ScreenPointToRay and Physics.Raycast, but I have wrong output:
private void ApplyClassTextures()
{
    var screenshot = GetComponent<Screenshoter>().MakeScreenshot();
    Debug.Log(screenshot);
    var map = GetComponent<Scenemap>().MakeMap(screenshot);
    var objectContours = new Dictionary<GameObject, List<Scenemap.MapContour>>();
    var camera = GetComponent<Camera>();
    foreach (var item in map)
    {
        var ray = camera.ScreenPointToRay(new Vector3(item.X, item.Y, 0.0f));
        var rayHit = new RaycastHit();
        if (Physics.Raycast(ray, out rayHit, raycastHitDistance))
        {
            var obj = rayHit.collider.gameObject;
            if (!objectContours.ContainsKey(obj))
            {
                Debug.Log(obj);
                objectContours.Add(obj, new List<Scenemap.MapContour>());
            }
            objectContours[obj].Add(item);
        }
    }
}

And there I can see few floor/wall plane and one chair, but not other and table.


text:
Q: Terraform dynamically loop over elements in a list and expand based on values This is a bit hard to describe. So I have a map that looks like this after I've simplified it for clarity:
server_ip_configs = {
mgmt        = {
    ct      = "1"
    }
applicationgateway    = {
    ct      = "1"
    }
monitor     = {
    ct      = "1"
    }
app      = {
    ct      = "3"
    }
}

What I want to do is iterate over the map to create a flat list where elements are multiplied by the number of the ct property into a new flat list.
So we end up with a list that looks a bit like this:
server_ip_configs_mapped = [
       {
        name      = "mgmt-1"
        }
       {
        name      = "applicationgateway-1"
        }
       {
        name      = "monitor-1"
        }
       {
        name      = "app-1"
        }
       {
        name      = "app-2"
        }
       {
        name      = "app-3"
        }

    ]

Creating a list of elements for each row explicitly by setting a variable is trivial:
data "null_data_source" "server_list_ip_configs" {
  count = lookup(var.server_ip_configs[var.server_role], "ct", 0)

  inputs = {
    name    =   "${var.server_role}-${count.index +1}"
  }
}

I can put this in a module and call multiple instances of the module and concat the results. But this is not a nice way to do it and not at all DRY. Am I right in thinking there is no other way of doing this in Terraform? Is it because terraform is essentially declarative and maybe I should declare a list with multiple instance in it rather than try and generate one?
Using a for loop won't work because you cant use an integer to iterate over explicitly from what I can see. So no:
for i in 5

Any answers to this welcome. Thanks.

A: @Helder came close, but I interpreted the request slightly different. Your intentions are to build the list based on the ct value, which looks like a count. This should be what you are looking for. Notice the use of range() to do what you were looking in regard to the for i in 5 statement.
variable "server_ip_configs" {
  default = {
    mgmt               = { ct = "1" }
    applicationgateway = { ct = "1" }
    monitor            = { ct = "1" }
    app                = { ct = "3" }
  }
}

locals {
  server_ip_configs_mapped = flatten([
    for server, count in var.server_ip_configs : [
      for i in range(count.ct) : {
        "name" = join("-", [server, i+1])
      }
    ]
  ])
}

output server_ip_configs_mapped { value = local.server_ip_configs_mapped }

Output:
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

server_ip_configs_mapped = [
  {
    "name" = "app-1"
  },
  {
    "name" = "app-2"
  },
  {
    "name" = "app-3"
  },
  {
    "name" = "applicationgateway-1"
  },
  {
    "name" = "mgmt-1"
  },
  {
    "name" = "monitor-1"
  },
]

A: Terraform 0.12 introduced for loops, you can do something like:
variable "server_ip_configs" {
  default = {
    mgmt               = { ct = "1" }
    applicationgateway = { ct = "1" }
    monitor            = { ct = "1" }
    app                = { ct = "3" }
  }
}

output "myout" {
  value = [for k, v in var.server_ip_configs : { "name" = join("-", [k, v.ct]) }]
}

Here the terraform output of that

terraform apply

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

myout = [
  {
    "name" = "app-3"
  },
  {
    "name" = "applicationgateway-1"
  },
  {
    "name" = "mgmt-1"
  },
  {
    "name" = "monitor-1"
  },
]


text:
Q: Which php files are secure? For example, using CodeIgniter, and not really dealt with .php files.  Are any of the .php files in the directory structure readable?  If not why not?  Why can't I browse to config.php in my CI directory?  Is it just unix file permissions?
Thank you.

A: I'm going at this from a 'Browser' standpoint. If you want to see the directory standpoint, look at the zombat's answer.

In CodeIgniter specifically, they have probably set up a .htaccess file that directs all of the requests to a single script so they can process it in one script rather than 2 dozen scripts.
Because PHP is a 'server-side' programming language, none of the information in the files ever gets sent to client. This allows yo use any method to produce an HTML page you want, because the client will never see the code. This doubles as a security device.
In most PHP situations, developers will build the libraries and classes into a folder above the Document_Root (Where the website starts), and then simply put in files that run those classes. This allows them to be absolutely sure that there is no chance of a person finding out their document structure, and using that information to download files that could give them information on how to hack the system.
This method also allows people to not care about what language the server runs on. All web pages are created in HTML, so all the server needs to produce is an HTML file. Whether they use Perl, Python, PHP, or another language is completely up to the developers.

A: Generally, files like config.php do not have any output. Therefore, they can be accessed by the browser, but the user won't see anything.
Users never see the source code of your .php files, if that's what you are worried about. Your web server will pass all .php files through the PHP processor; only the output generated by your .php files is ever sent to the user.
If config.php is in the same directory as your other .php files (and it usually is) then there is no Unix file permissions or .htaccess stuff going on. It is simply a file that produces no output.

A: To answer your question about why you can't browse to your config.php in CodeIgniter, it's not because of Unix permissions nor is it an .htaccess file protecting it.
All CodeIgniter PHP files have a line at the top of the file that checks for a constant "BASEPATH".  The constant is only set when you're going through the framework, so when you try to access a file without going through the framework, "BASEPATH" won't be set and the script will exit.
This is CodeIgniter's portable way of securing files since not everyone uses Apache (.htaccess files).

A: PHP files on a linux/unix system follow the same file permission rules as everything else.  If you can't browse to your config.php file, then yes, the user you are logged in as doesn't have the appropriate file permissions.
Generally you want your permissions on a PHP project to be set up so that the uid that your webserver runs under has appropriate permissions to read and execute files within your web structure.
For myself, I generally set up a webdev group on my LAMP systems, and put the apache user into this group.  I set all group permissions properly on a PHP file structure so that Apache can do what it needs to do.  This way a user can own all their own web files, and the webdev group can be used to control any other accesses to the structure.  This alleviates worries on multi-user systems of someone going in and reading the config file to get, say, your database password.


text:
Q: Voltage RC smoothing circuit analysis I'm reading an article about voltage smoothing and I intuitively understand why we need capacitors in output power supply circuit to provide stable voltage. But I can make out this

and

why does \$i_D\$ decreases from an value at \$\theta_1\$ to 0 at \$\theta_2=\pi/2\$? apparently there will be some different currents that pass through capacitor and resistor as long as the source is higher > 0.7V (diode voltage) allowing current pass the circuit .

A: The curve you've included is pretty accurate.
The details on the rising edge of the diode current is complex and beyond the scope of the mathematics I'd want to present here. Suffice it that the complexities include a diode drop that starts out as zero and then follows the Shockley equation for a rising current edge that almost instantly reaches a nominal situation where the diode drop doesn't change much anymore. We can ignore this and consider it to be instantaneous here. (It's not, but close enough that it doesn't matter except perhaps to Spice simulators or someone going after some very strange idea in electronics.)
But what is the peak current? And what shape does it follow? Let's start with the peak current estimate.

To get an estimate about the peak diode current we need an estimate of when the diode kicks in and starts to conduct. There will be some moment \$t_x\$ where the voltage curve itself first rises over the declining capacitor voltage (declining because the load resistor is drawing current from it when the diode isn't conducting.) Let's call this voltage at time \$t_x\$ to be \$V_x\$. In steady state and assuming the load \$R\$ doesn't vary, \$t_x\$ and \$V_x\$ will be constant. Our first job is to work out these values.
Technically, the declining voltage on the capacitor falls according to an exponential decay. Trying to solve that as equal to a sinusoidal voltage curve is beyond the mathematics I'd like to work on. (It involves the LambertW function, followed by yet another difficult solution; neither of which are worth elaborating here.) Let's also ignore the diode drop itself (treating the diode as ideal in this sense.) Since we are assuming it is fixed, we might as well assume it is fixed at zero. (You can always go back and put it in, if you want.)
There are several approaches to try, even given the above. You could start out assuming the exponential decay and work from there. But one useful simplification is to just assume an average current based upon the starting and ending points. Let's assume that the voltage is \$V_t=V_0\cdot \operatorname{cos}\left(2\pi\: f\: t\right)\$, or \$0\:\textrm{V}\$ at other times when the diode isn't conducting. (\$V_0\$ is your peak voltage, of course.) Using the cosine allows me to start time (\$t=0\$) at a convenient moment, when the capacitor starts supplying the current into the load. Assuming the starting point when the capacitor is supplying all the current begins at \$t=0\$ (but close enough but not always exactly true), then the average current through the load resistor is \$\frac{V_0+V_x}{2\cdot R}\$, and therefore the total charge lost from the capacitor is \$\frac{V_0+V_x}{2\cdot R}\cdot t_x\$. This must be restored during the time from \$t_x\$ to the beginning of the next cycle at \$t=\frac{1}{f}\$. So we know that the integral of the current times time during this last recharge period must equal our other equation:
$$\frac{V_0+V_x}{2\cdot R}\cdot t_x\approx \int_{t_x}^{\frac{1}{f}}C\: \textrm{d} V_C$$
But \$\textrm{d} V_C = -2\pi\: f \: V_0\cdot \operatorname{sin}\left(2\pi\: f\: t\right)\:\textrm{d}t\$, so:
$$\begin{align*}
\frac{V_0+V_x}{2\cdot R}\cdot t_x&\approx \int_{t_x}^{\frac{1}{f}}C\: \textrm{d} V_C\\\\
&\approx -2\pi\:f\:C\:V_0\:\int_{t_x}^{\frac{1}{f}} \operatorname{sin}\left(2\pi\: f\: t\right)\:\textrm{d}t\\\\
&\approx C\:V_0\cdot\left[1-\operatorname{cos}\left(2\pi\: f\: t_x\right)\right]\\\\
\frac{V_0+V_0\cdot \operatorname{cos}\left(2\pi\: f\: t_x\right)}{2\cdot R}\cdot t_x&\approx C\:V_0\cdot\left[1-\operatorname{cos}\left(2\pi\: f\: t_x\right)\right] \\\\
\frac{1+ \operatorname{cos}\left(2\pi\: f\: t_x\right)}{2\:R\: C}\cdot t_x&\approx \left[1-\operatorname{cos}\left(2\pi\: f\: t_x\right)\right] \\\\
&\therefore\\\\
t_x &= 2\: R\: C \:\frac{1-\operatorname{cos}\left(2\pi\: f\: t_x\right)}{1+ \operatorname{cos}\left(2\pi\: f\: t_x\right)}
\end{align*}$$
That can be solved for \$t_x\$. For example, with \$R=1\:\textrm{k}\Omega\$ and \$C=47\:\mu\textrm{F}\$ and \$f=60\:\textrm{Hz}\$, it solve out as \$t_x\approx 14.671\:\textrm{ms}\$.
I'd simplified a little bit, earlier, using an average for the load current. You can also use the following as a starting point, keeping the exponential decay rather than assuming that average current. This is:
$$\begin{align*}C\: V_0\left(1- e^{\frac{-t_x}{R\: C}}\right)&\approx \int_{t_x}^{\frac{1}{f}}C\: \textrm{d} V_C\\\\
V_0\left(1- e^{\frac{-t_x}{R\: C}}\right)&\approx \int_{t_x}^{\frac{1}{f}} \textrm{d} V_C\\\\
V_0\left(1- e^{\frac{-t_x}{R\: C}}\right) &\approx V_0\cdot\left[1-\operatorname{cos}\left(2\pi\: f\: t_x\right)\right]\\\\
e^{\frac{-t_x}{R\: C}} &\approx \operatorname{cos}\left(2\pi\: f\: t_x\right)
\end{align*}$$
And solve that for \$t_x\$. But it won't be that much better for the usual cases. In this case I get \$t_x\approx 14.6775\:\textrm{ms}\$

Now that you know the time, the peak current is easy. You can compute it from the rate of change of voltage times the capacitance, so:
$$I_{peak} \approx - C\: 2\pi\: f \: V_0\cdot \operatorname{sin}\left(2\pi\: f\: t_x\right)$$
In the above case, where I computed \$t_x\approx 14.671\:\textrm{ms}\$, and assuming for now that \$V_0=100\:\textrm{V}\$, then this works out to \$I_{peak} \approx 1.211\:\textrm{A}\$.
So I just ponied up an LTSpice circuit to see what all these "predictions" do for us. Here are the results:

You can see that the peak current is pretty close to where I predicted it would be. But smaller. What did I miss? Well, I didn't include the current through \$R\$ at that moment.
Here's a more complete expression that includes \$R\$ and can be used to compute the current starting at time \$t=t_x\$ until \$t=\frac{1}{f}\$:
$$I \approx \frac{V_0\:\operatorname{cos}\left(2\pi\: f\: t\right)}{R} - C\: 2\pi\: f \: V_0\cdot \operatorname{sin}\left(2\pi\: f\: t\right)$$
Using that, I now compute \$I_{peak} \approx 1.284\:\textrm{A}\$ at \$t=t_x\approx 14.671\:\textrm{ms}\$. Which is almost an exact fit to LTSpice's output. (I get \$I_{peak} \approx 1.281\:\textrm{A}\$ using \$t=t_x\approx 14.6775\:\textrm{ms}\$.)
That also provides the shape of the current pulse for you, as well. (And it can predict approximately when, after the peak of the input voltage is reached, that the current will go to zero. In the example case I've been discussing, it predicts this to occur approximately \$150\:\mu\textrm{s}\$ after the peak point.)

A: That \$i_D\$ is the sum of load current and capacitor charging current. Since the latter goes with \$1-e^\frac{-t}{\tau}\$ (\$\tau\$ being a positive real number), you see an overall decline of current.
Pretty logical if you think about it: first the voltage across the capacitor is very low, making it extremely easy to charge it, and then the voltage across the capacitor rises faster than the supply voltage, so that it becomes harder to push in more charge in the same time.

A: Capacitor  current is always \$ i_\mathrm{C}=C\,\mathrm{d}v_\mathrm{C}/\mathrm{dt}\$ .
Since while diode is ON  voltage is an arc of sine then current is an arc of cosine dropping to zero when input voltage derivative is naught at top of wave, as depicted in the question.
Exponential decay rules capacitor discharge into the load, a small negative exponential current should actually be visible in \$i_\mathrm{C}\$ graph in between charging pulses.
Even though normally much smaller than charging pulses it would  definitely be a good idea to include it to  account that in steady state capacitor average current has obviosly to be zero (on one period averaged quantities).
Diodes forward drop and eventually power source internal impedance are both further second order details not needed at all to justify shown waveforms

A:
why does i_D decreases from an value at theta1 to 0 at theta2=pi/2?

At \$\theta_2 = \frac{\pi}{2}\$, \$v_L = V_m\$, thus voltage difference, \$v_D\$ across diode is 0V.
Thus, diode current \$I_D = I_S(e^{\frac{v_D}{V_T}} - 1) = 0\$.
Remember, the diode acting as a short circuit above 0.7V input is only an approximation.


text:
Q: Passing an interface pointer in a function parameter I am trying to understand Golang (1.12) interfaces. I found out that interface pointers must be explicitly dereferenced, unlike structs:
import "fmt"

// A simple interface with one function
type myinter interface {
    hello()
}

// Implement myinter
type mystruct struct {}

func (mystruct) hello() {
    fmt.Println("I am T!")
}

// Some function that calls the hello function as defined by myinter
func callHello(i *myinter) {
    i.hello()  // <- cannot resolve reference 'hello'
}

func main() {
    newMystruct := &mystruct{}
    callHello(newMystruct)
}

Here, my callHello function cannot resolve the reference to my hello function as defined in the interface. Of course, dereferencing the interface works:
func callHello(i *myinter) {
    (*i).hello()  // <- works!
}

But in structs, we can call the function directly, none of this cumbersome dereference notation is necessary:
func callHello(s *mystruct) {
    s.hello()  // <- also works!
}

Why is this the case? Is there a reason why we must explicitly dereference interface pointers? Is Go trying to discourage me from passing interface pointers into functions?

A: It is related to the way the type system works. An interface type I defines a method set. The method set is defined for type I, and not for type *I. Because of this, the use of *I is limited. It can be used when a function is to set the interface value, but it is rare:
func f(x *error) {
  *x = fmt.Errorf("Some error")
}

Note that the interface itself can have an underlying pointer value:
func f(x someInterface) {
   *x.(*someType) = value
}

func main() {
   x := someType{}
   f(&x)
}

This is different for non-interface types. When you define a method for a non-interface type T, the method is defined for both T and *T. If you define a method for *T, it is only defined for *T, and not for T.

A:
Is Go trying to discourage me from passing interface pointers into functions?

Yes.
Pointer-to-interface is wrong in (almost*) all cases.
(* There are very rare and delicate cases where pointer-to-interface makes sense but chances are high you won't see them more than once every 5 years.)
(Nitpick: The language is called "Go". "golang.org" is the website. Basics like this are covered by the compatibility promise and do not depend on the version: Go 1.0, 1.12 and 1.16 behave exactly the same in this regard.)

A: Simply remove the pointer and use the interface.
func callHello(i myinter) {
    i.hello()
}

This func will now accept either an instance of a struct that implements the interface, or a pointer to an instance of a struct that implements the interface.
func main() {
    instance := mystruct{}
    pointer := &mystruct{}
    callHello(instance)
    callHello(pointer)
}

outputs the following:
I am T!
I am T!

Program exited.


text:
Q: ImageMagick with Grails I want to use ImageMagick in my Grails application. I am using the following dependencies in BuildConfig.groovy
compile('jmagick:jmagick:6.6.9')
compile('org.im4java:im4java:1.2.0')

however when I try and run I get this error:
org.im4java.core.CommandException: java.io.IOException: Cannot run program
"convert": error=2, No such file or directory.

How do I use ImageMagick or Jmagick with Grails without installing it directly, am I missing some dependencies?

A: jmagick and im4java take two different approaches to using ImageMagick. In short, jmagick uses Java INI to access the ImageMagick API and im4java calls the ImageMagick tools. In other words, jmagick bundles ImageMagick while im4java does not. As you probably know, the error is due to ImageMagick either not being installed or not being in the environment PATH.
im4java
The two don't go together. For example, you cannot use im4java to call out to jmagick in order to avoid installing ImageMagick on the computer hosting the Grails app. To use im4java you need to install ImageMagick.
jmagick
Because jmagick is partly implemented in C, it might be problematic to use in a Servlet container. It would certainly make the web app non-portable. What might work is to have the Servlet container provide jmagick compiled for that platform, and exclude jmagick from the war file. Don't ask me how to do that :)

A: First thing first: i suggest you to use 1.4.0 version of imagemagick :).
Reading the error seems that you have not configured the imagemagick path.
In my grails application that uses imagemagick code looks like this:
 @Value('${externalTools.imagemagick.path:/usr/local/bin}')
 private String imagemagickPath

 CreateTemporaryThumbnailsResult call(CreateTemporaryThumbnailsEvent event){

    log.debug("IMAGEMAGICK PATH: $imagemagickPath")

    String originalFilePath = generateOriginalFilePath(event.fileName, event.fileExtension)
    String mediumFilePath = generateMediumFilePath(event.fileName, event.fileExtension)

    // create command
    ConvertCmd cmd = new ConvertCmd();
    cmd.setSearchPath(imagemagickPath)

    // create the operation, add images and operators/options
    IMOperation op = new IMOperation();
    op.addImage(originalFilePath);

    op.thumbnail(mediumSizeImage, mediumSizeImage)
    op.background("white")
    op.gravity("center")
    op.extent(mediumSizeImage,mediumSizeImage)
    op.addImage(mediumFilePath);

    // execute the operation
    try {
        cmd.run(op);
    } catch (IOException e) {
        return new CreateTemporaryThumbnailsResult(false)
    } catch (InterruptedException e){
        return new CreateTemporaryThumbnailsResult(false)
    } catch(Exception e){
        return new CreateTemporaryThumbnailsResult(false)
    }

    return new CreateTemporaryThumbnailsResult(true, event.fileName + ImageSize.MEDIUM.toString() + "." + event.fileExtension, event.fileName)
}

I used hipsteroid grails project as example to discover how to use imagemagick with grails, i suggest you to do the same if you have any doubts, it's really full of information about images manipulation with groovy and imagemagick.

A: You could also install imageMagick on your machine and use "executeCommand" to execute a shell command to edit the images, like:
 def resizeCommand = "/usr/bin/convert pathTo/myOriginalImage.jpg -resize 1920 -quality 80 pathTo/myNewImage.jpg"
            executeCommand(resizeCommand)


text:
Q: How to print java.lang.Class object to a file? I have tried looking for a way to compile a class on the fly and I have got as for as create a compiled Class instance. However, I want to be able to create a .class file that is executable. How would I, if possible, be able to output the Class object to a .class file. If this is incorrect, please explain how I would be able to do this.

A: Don't. Make an executable jar instead.
There are other options as outlined here, if you feel and executable jar is not what you need.

A: This page http://www.accordess.com/wpblog/an-overview-of-java-compilation-api-jsr-199/  describes the process of compiling Java code from string, producing a .class file.  Here's an abbreviated version of that page's otherwise well-commented code.
public class CompilerAPITest {
    final Logger logger = Logger.getLogger(CompilerAPITest.class.getName()) ;

    /** Java source code to be compiled dynamically */
    static String sourceCode = "package com.accordess.ca;" +
        "class DynamicCompilationHelloWorld{" +
            "public static void main (String args[]){" +
                "System.out.println (\"Hello, dynamic compilation world!\");" +
            "}" +
        "}" ;

    /* Object initialization and compilation. */
    public void doCompilation (){
        SimpleJavaFileObject fileObject = new DynamicJavaSourceCodeObject ("com.accordess.ca.DynamicCompilationHelloWorld", sourceCode) ;
        JavaFileObject javaFileObjects[] = new JavaFileObject[]{fileObject} ;
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null);
        Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(javaFileObjects);
        //This example places the output files under bin folder.
        String[] compileOptions = new String[]{"-d", "bin"} ;
        Iterable<String> compilationOptions = Arrays.asList(compileOptions);
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        CompilationTask compilerTask = compiler.getTask(null, stdFileManager, diagnostics, compilationOptions, null, compilationUnits) ;
        boolean status = compilerTask.call();
        if (!status){//If compilation error occurs
            for (Diagnostic diagnostic : diagnostics.getDiagnostics()){
                System.out.format("Error on line %d in %s", diagnostic.getLineNumber(), diagnostic);
            }
        }
        try {
            stdFileManager.close() ;//Close the file manager
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String args[]){
        new CompilerAPITest ().doCompilation() ;
    }
}

class DynamicJavaSourceCodeObject extends SimpleJavaFileObject{
    private String qualifiedName ;
    private String sourceCode ;

    protected DynamicJavaSourceCodeObject(String name, String code) {
        super(URI.create("string:///" +name.replaceAll("\\.", "/") + Kind.SOURCE.extension), Kind.SOURCE);
        this.qualifiedName = name ;
        this.sourceCode = code ;
    }

    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors)
            throws IOException {
        return sourceCode ;
    }
    // ... getters and setters
}


text:
Q: Data in the receipt-data sometimes malformed I'm encountering a problem that I can't explain.
I provide an auto-renewing subscription in my app. I'm verifying the receipt data by sending it from my server to the app store.
I've tested it many times, and it has passed Apple review. Now my app is online and many users were able to subscribe. But from times to times, App Store give me back a 21002 status meaning that the data in the receipt-data property was malformed.
Here is an example of a receipt returning a 21002 status (decode with the base64_decode function of php) :
{
"pod"="0";
"purchase-info"=
 {

"app-item-id"="*********";
 "bvrs"="2.0";
 "purchase-date"="2013-07-31 23:49:36 Etc/GMT";
 "quantity"="1";
 "bid"="com.mycompany.myapp";
 "version-external-identifier"="********";
 "purchase-date-pst"="2013-07-31 16:49:36 America/Los_Angeles";
 "purchase-date-ms"="1375314576739";
 "unique-vendor-identifier"="*******-****-****-****-**********";
 "original-purchase-date-ms"="1375314576739";
 "original-transaction-id"="**********************";
 "item-id"="*********";
 "original-purchase-date-pst"="2013-07-31 16:49:36 America/Los_Angeles";
 "product-id"="com.mycompany.myapp.1Month";
 "transaction-id"="**********************";
 "original-purchase-date"="2013-07-31 23:49:36 Etc/GMT";
 "unique-identifier"="***********************************************";
 }
"signature"="ApdxJdtNwPU2rA5..........";
"signing-status"="0";
}

I've hidden some private info, but I've verified that the bvrs, item-id, transaction-id, bid are correct.
What to think about that? Is there a problem from Apple? Is it a hack attempt?
Thanks for your answers.

A: When I see signature beginning with "ApdxJdtNwPU2rA5" I know that somebody is trying to "steal" our InApp. Apple is not paying us for these InApps.


text:
Q: php error on my error_log while posting this is my php codes getting Post Successfully response when true but when it failed for some reason.
i got this error.

mysqli_error() expects parameter 1 to be mysqli, null given

$result = mysqli_query($connection, $query) ;
    if($result){$response["msg"] = "Post Successfully";
echo json_encode($response);} else {$response["msg"] = "failed ".mysqli_error($con);
echo json_encode($response);
    }
    mysqli_close($connection);
}

A: $con is null
mysqli_error($con); should be  mysqli_error($connection);  as you have declared connection as $connection.

A: According to this line:
mysqli_query($connection, $query)

You are using variable $connection for link identifier, and in mysqli_error($con) you are using $con variable which is undefined or NULL, this should be:
mysqli_error($connection)


text:
Q: Best way to block countries I was requested to prevent access to a website.
There are two ways I know I can choose -
1. At apache level (a tool like this: http://www.ip2location.com/blockvisitorsbycountry.aspx) which generates a long htaccess file with list of IP ranges.
The other way I know of is using PHP (be it a local DB, remote webservice or just a list just like the htaccess).
My question is what is more effective -
I think that if I use apache, it is faster then PHP but done each and every page accessed.
If I use PHP, I can do it once and save in the session.
What is the more efficient way?
Thanks!

A: You don't have to fill your .htaccess file with thousands of lines of IPs. Instead, you can install a C library and an Apache module to do the heavy lifting for you.
MaxMind provides a popular free database that is often used for IP lookups. Their GeoLite2 is a free database that is updated monthly. Their paid product is more accurate and updated more frequently if you require that.
By using this database and installing one of their various APIs, you can handle traffic as you see fit.
For our purposes, you would need to install the C library API as well as the Apache module. Once those are working and enabled, place the database file somewhere, and then you can set up your country blocks with code as simple as this in the .htaccess or Apache config file:
MaxMindDBEnable On
MaxMindDBFile DB /path/to/GeoIP/GeoLite2-Country.mmdb
MaxMindDBEnv MM_COUNTRY_CODE DB/country/iso_code

SetEnvIf MM_COUNTRY_CODE ^(RU|DE|FR) BlockCountry
Deny from env=BlockCountry

This would block Russia, Germany, and France. Get your two-letter ISO country codes here.
This would perform much better than your server having to parse thousands of lines of text on every request in the .htaccess file!
You do need advanced access to your server to install the library and module, so this is no good on shared hosts or where you don't have such access on a VPS.
This would also work if, for some reason, you wanted specific blocking rules at the folder level.
Nice Article / Reference


text:
Q: Как построить рисунок Можете мне помочь с кодом для рисунка?
Я не могу его сделать. Понимаю, что по координатам надо строить, но у меня не получается. На с# или с++.

A: Всё очень просто:
using System.Drawing;
using System.IO;
using System.Net;
using System.Windows.Forms;

class Program
{
    static void Main ()
    {
        new Form {
            Controls = {
                new PictureBox {
                    Image = Image.FromStream(new MemoryStream(
                        new WebClient().DownloadData("http://i.stack.imgur.com/XAUao.png"))),
                    AutoSize = true,
                }
            },
            AutoSize = true,
        }.ShowDialog();
    }
}

A: Пожалуй, добавлю полноценное решение с честной отрисовкой векторного изображения.
<Window x:Class="BlendApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Height="838" Width="1215">
    <Grid>
        <Path Data="
            M253.5,145 C253.5,172.89038 229.99495,195.5 201,195.5 C172.00505,195.5
            148.5,172.89038 148.5,145 C148.5,117.10962 172.00505,94.5 201,94.5
            C229.99495,94.5 253.5,117.10962 253.5,145 z M200.5,196.5 L200.5,421.50202
            M200.5,237.5 L272.5,305.5 M200.5,237.5 L126.5,306.5 M200.5,422.50199
            L273.5,560.5 M200.5,422.50199 L126.5,561.5 M46.5,561.5 L357.5,562.5
            M125.5,592.5 C125.5,609.62083 111.62083,623.5 94.5,623.5 C77.379173,623.5
            63.5,609.62083 63.5,592.5 C63.5,575.37917 77.379173,561.5 94.5,561.5
            C111.62083,561.5 125.5,575.37917 125.5,592.5 z M336.5,592.5 C336.5,609.62083
            322.62083,623.5 305.5,623.5 C288.37917,623.5 274.5,609.62083 274.5,592.5
            C274.5,575.37917 288.37917,561.5 305.5,561.5 C322.62083,561.5 336.5,575.37917
            336.5,592.5 z M0.5,624.5 L1094.5,624.5 M947.5,0.5 L1024.5,0.5 L1024.5,623.5
            L947.5,623.5 z M946.5,94.5 L836,151 945,205 z M946.5,211 L836,267.5
            945,321.5 z M946.5,322.5 L836,379 945,433 z M946.5,434 L836,490.5 945,544.5 z"
            HorizontalAlignment="Left" Height="625" Margin="37,138,0,0" Stretch="Fill"
            Stroke="Black" VerticalAlignment="Top" Width="1095"/>
    </Grid>
</Window>

A: Эх вы! Всё вам новые технологии!
Вот вам на старом добром C++.
vector<string> data =
{
    "                                         /||",
    "                                        / ||",
    "                                        \\ ||",
    "                                         \\||",
    "                                          ||",
    "           _                             /||",
    "          / \\                           / ||",
    "          \\_/                           \\ ||",
    "           |                             \\||",
    "          /|\\                             ||",
    "         / | \\                           /||",
    "        /  |  \\                         / ||",
    "          / \\                           \\ ||",
    "         /   \\                           \\||",
    "        /     \\                          /||",
    "   \\_________________/                  / ||",
    "      / \\      / \\                      \\ ||",
    "      \\_/      \\_/                       \\||",
    "------------------------------------------------"
};

for (auto& s : data)
    cout << s << endl;

http://ideone.com/8KH7lb
PS: Для любителей современных версий: http://ideone.com/DxlHkC (спасибо @Abyx за подсказку).

A: Поучаствую-ка и я в специальной олимпиаде.
Вот решение на WPF, мне оно кажется проще:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

class App : Application
{
    [STAThread]
    public static void Main()
    {
        new App().Run();
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        new Window()
        {
            Content = new Image()
            {
                Source = (ImageSource)new ImageSourceConverter()
                            .ConvertFromString("http://i.stack.imgur.com/XAUao.png")
            }
        }.Show();
    }
}


text:
Q: NSUInteger Equivalent for use in cocos2d-x project Is there any macro for NSUInteger implemented in cocos2d-x for use in visual c++. I need this to port a project from obj-c to c++.
And also , I have seen these  variables written after the declaration of the variables in the header file  :
@property (nonatomic, readonly) CGPoint stickPosition;
@property (nonatomic, readonly) float degrees;
@property (nonatomic, readonly) CGPoint velocity;
@property (nonatomic, assign) BOOL autoCenter;
@property (nonatomic, assign) BOOL isDPad;
@property (nonatomic, assign) BOOL hasDeadzone;
@property (nonatomic, assign) NSUInteger numberOfDirections;
@property (nonatomic, assign) float joystickRadius;
@property (nonatomic, assign) float thumbRadius;
@property (nonatomic, assign) float deadRadius;"
Is there use in writing these in any way in c++ and is it possible? If so How?

A: NSUInteger is just the biggest-sized unsigned integer. In C++, you can use
unsigned long       // when building a 64-Bit OS app
unsinged int        // when building a 32-Bit OS app (ie iOS, Android)

instead of it. Or, to make it convenient:
typedef unsigned long NSUInteger;
typedef unsigned int NSUInteger;

If you want to represent a property in C++, that doesn't really belong to this topic - it's not Cocoa-dependent but language-dependent, simply solvable by reading the topic on member variables of a C++ book. Here's how:
class Whatever {
   public:
   CGRect rect;
}

then access it like:
Whatever *instance = new Whatever();
CGRect r = instance->rect;


text:
Q: Java Double Linked List Stack Tail error I searched for this alot found alota similar answers but nothing to help my exact problem.
I'm doing a push method for my double linked list, while the pointers on the head work fine, the tail next and previous pointers do not work please help.
public class MyStack<E> implements MyDeque {

    private Node<E> head;
    private Node<E> tail;
    private int size;

    public MyStack() {
        head = null;
        tail = null;
        size = 0;
    }
    public void push(Object element) {
        Node<E> newNode = new Node(element);
       if(size == 0) {
           Node temp = new Node(head);
           head = newNode;
           head.next = head;
           head.previous = head;
           tail = head;
           tail.next = head;
           tail.previous = temp;

          }
       else {

           newNode.previous = head;
           head = newNode;
           newNode.next = tail;
           (tail.next).previous = tail;

       }//else statement
       size++;
    }//push()

    public Object peek() {
        if (size==0) return null;
        else
            return head;
    }

    public Object pop() {

      size--;
      if(size == 0)
          return null;
      else {

         Node temp = new Node(head.previous);
         head = head.previous;
         head.next = tail;
         head.previous = temp;

         return head;

      }//else

    }//pop()

    @Override
    public int size() {

        return size;
    }

     private class Node<E> {
        private E data;
        private Node<E> next;
        private Node<E> previous;

        public Node(E data) {
            this.data = data;
            this.next = null;
            this.previous = null;
        }
        public Node(E data, Node<E> next, Node<E> previous) {

            this.data = data;
            this.next = next;
            this.previous = previous;

        }//constructor

        public String toString() {
            return data+"";
        }

    }//class Node<E>
    public String toString() {

        return (head+" Head\n" + head.next  +" Head.Next\n" + head.previous+ " Head.previous\n"
                + tail+" Tail\n" + tail.next+" tail.next\n" + tail.previous+" tail.previous\n");

    }

}

A: The case where you push an object when the stack is empty does not look correct. The first node added should be assigned to head. Then the tail becomes the new node's head, this new node becomes the tail node's tail, and the new node itself becomes the tail.
Usually in a stack you add and remove elements at the end (the tail). The code doesn't make it very clear what you are trying to do with the head and tail members. Maybe it would be clearer for you if you name them firstNode and lastNode.

A: I can actually see a few issues with this code
public class MyStack<E> implements MyDeque {

private Node<E> head;
private Node<E> tail;
private int size;

public MyStack() {
    head = null;
    tail = null;
    size = 0;
}

This looks fine
public void push(Object element) {
    Node<E> newNode = new Node(element);
   if(size == 0) {
       Node temp = new Node(head);
       head = newNode;
       head.next = head;
       head.previous = head;
       tail = head;
       tail.next = head;
       tail.previous = temp;

      }
   else {

       newNode.previous = head;
       head = newNode;
       newNode.next = tail;
       (tail.next).previous = tail;

   }//else statement
   size++;
}//push()

Bit confused why you are taking in an object instead of your generic E.
You really don't need the temp value here, in fact it looks like you are breaking your previous when you set tail.previous = temp
In your else you aren't setting the tail.previous correctly. The last line should be tail.previous = head. You also missed the head.next
So cleaned up a bit
public void push(E element) {
    Node newNode = new Node(E);
    if(size == 0) {
        head = newNode;
        head.next = head;
        head.previous = head;
        tail = head;
    } else {
        newNode.previous = head;
        head.next = newNode;
        newNode.next = tail;
        tail.previous = newNode;
        head = newNode;
    }
    size++;
}

In your pop method you probably want to move your size decrement after your size check, otherwise a 1 element stack will return null when popped.
edit: This would probably be easier with a singly linked list, or at least not a circular doubly linked list.
and adding at the end would probably be the more conventional way to do things.


text:
Q: Restart when trying to resize partition I am brand new to Ubuntu (and installing operative systems/partitioning/etc...) and up to know everything has been going smoothly, but now I'm having a problem that I think I can fix, but just don't know how...
I wanted to have a dual-boot, so I installed Windows and then Ubuntu in separate partitions. My disk available space is about 580GB, I gave 230GB to Windows and when installing Ubuntu, I set up a partition of 120GB with a 8GB swap space. The problem I have now is that Ubuntu took all the remaining space in my disk. I wanted the remaining 230GB to be a partition to keep my files.
So, what I tried to do was to resize (reduce) the Ubuntu partition from the Ubuntu Installation CD. I started GParted after running the "Try Ubuntu" option, made "swapoff" to the swap partition, reduced the size and then applying the operations... up to know everything seemed to work, just that the computer turns off itself after five minutes or so when applying the operations.
I tried this several times with no success. Now I'm afraid I won't be able to make the resize operation... I don't adventure into any other possibilities, since I'm afraid to screw up my boot. What am I missing? Is there any other alternative I can use?

A: If you need to resize a partition, on which you already installed Ubuntu, the best way is to do it from right to left, so the data will not have to be moved.
The whole procedure should take a minute or two.

*

*first choose to resize:

*

*then drag the partition's right side to the left

*

*and then creat a new partition in the unallocated space

I am not sure what went wrong in your case, but this way, it should work, I just tried to resize on my laptop. If it does not solve your problem, I will remove the answer.


text:
Q: SwiftUI App Crashes with 'NSInvalidArgumentException' only when List Cell Tapped From Search Update:
I have now been able to successfully reproduce the issue in a minimal app environment. See the new MyView.swift.
As the title suggests, My SwiftUI app crashes with 'NSInvalidArgumentException' only when a List cell is tapped from a search bar.
My issue is this:
I have a List that is declared .searchable, which uses a navigation link to link to another List, which is also declared .searchable. The second list bring up a modal page with .sheet The searching in the first list works fine. The second list, on the other hand, works fine if the user apps a row without searching. However, if the user searches in the search box, and then taps one of the filtered results, the app presents the modal page and loads everything, then crashes.
If I remove the NavigationView from the popup, then the app no longer crashes. However, then the search bar from the view behind it carries on to the popup which I do not want.
Here is the error message from the console:
2022-05-21 08:34:38.579406-0700 MyApp[68653:3984705] [Presentation] Attempt to present <_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x100baa2d0> on <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x100c08680> (from <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_24NavigationColumnModifier__: 0x102d0bdf0>) which is already presenting <_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x100b8f3f0>.
2022-05-21 08:34:38.579913-0700 MyApp[68653:3984705] [Presentation] Attempt to present <_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x100bb3260> on <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_12RootModifier__: 0x100c08680> (from <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVS_7AnyViewVS_24NavigationColumnModifier__: 0x102d0bdf0>) which is already presenting <_TtGC7SwiftUI29PresentationHostingControllerVS_7AnyView_: 0x100b8f3f0>.
2022-05-21 08:34:38.605787-0700 MyApp[68653:3984705] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present modally a view controller <SwiftUI.SwiftUISearchController: 0x10119f000> that is already being presented by <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVVS_22_VariadicView_Children7ElementVS_24NavigationColumnModifier__: 0x100bac8b0>.'
*** First throw call stack:
(0x1c9b0dd78 0x1e2772734 0x1cc3b4e98 0x1cc1a1b68 0x1cc152210 0x1cc385898 0x1cc1239dc 0x1cc20cd38 0x1cc1200c8 0x100a18c6c 0x100a1a7bc 0x100a2ac68 0x100a2a7a4 0x1c9ac62f0 0x1c9a801f4 0x1c9a936b8 0x1e5b2d374 0x1cc3f8e88 0x1cc17a5ec 0x1d18ca640 0x1d17f8524 0x1d17d9810 0x1004da4c0 0x1004da570 0x100985ce4)
libc++abi: terminating with uncaught exception of type NSException
dyld4 config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Developer/usr/lib/libBacktraceRecording.dylib:/Developer/usr/lib/libMainThreadChecker.dylib:/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present modally a view controller <SwiftUI.SwiftUISearchController: 0x10119f000> that is already being presented by <_TtGC7SwiftUI19UIHostingControllerGVS_15ModifiedContentVVS_22_VariadicView_Children7ElementVS_24NavigationColumnModifier__: 0x100bac8b0>.'
terminating with uncaught exception of type NSException
(lldb)

_
Steps To Reproduce:

*

*Get sample code provide below

*Run the app

*Tap an item in the first list

*Search "1" in the search box in the next list

*Tap the first result

*The app should crash

_
Here is a sample app in which I was able to replicate the behavior.
Test_AppApp.swift:
import SwiftUI

@main
struct Test_AppApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

ContentView.swift:
import SwiftUI

struct ContentView: View {

    @State var sheetIsPresented:Bool = false

    @State var searchText:String = ""

    struct item: Identifiable {
        var id:String
        var string:String
    }

    func getItems() -> Array<item> {
        let items = ["Item 1", "Item 2", "Item 3", "Item 4"].map({ item(id: UUID().uuidString, string: $0) })

        if searchText == "" {
            return items
        } else {
            return items.filter({ $0.string.contains(searchText) })
        }
    }

    var body: some View {
        NavigationView {
            List {
                ForEach(getItems()) { item in
                    NavigationLink(item.string) {
                        NextView()
                    }
                }
                /*
                .onDelete { index in
                    print("delete")

                }
                 */

            }
            .searchable(text: $searchText)
            .navigationTitle("Test App")
            .navigationBarTitleDisplayMode(.large)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

NextView.swift:
import SwiftUI

struct NextView: View {

    @State var sheetIsPresented:Bool = false

    @State var searchText:String = ""

    struct item: Identifiable {
        var id:String
        var string:String
    }

    func getItems() -> Array<item> {
        let items = ["Item 1", "Item 2", "Item 3", "Item 4"].map({ item(id: UUID().uuidString, string: $0) })

        if searchText == "" {
            return items
        } else {
            return items.filter({ $0.string.contains(searchText) })
        }
    }

    var body: some View {
        List {
            ForEach(getItems()) { item in

                HStack {
                    Button {
                        sheetIsPresented = true
                    } label: {
                        HStack {
                            Image(systemName: "shippingbox")
                            Text(item.string)
                                .foregroundColor(Color.black)
                        }
                    }
                    .sheet(isPresented: $sheetIsPresented, content: {
                        MyView()
                    })
                }
            }
            /*
            .onDelete { index in
                print("delete")

            }
             */

        }
        .searchable(text: $searchText)
        .navigationTitle("Test App")
    }
}

struct NextView_Previews: PreviewProvider {
    static var previews: some View {
        NextView()
    }
}

MyView.swift:
import SwiftUI

struct MyView: View {
    var body: some View {
        NavigationView {
            List {
                Text("Test")
            }
        }
        .navigationBarTitle("Test Page")
    }
}

struct MyView_Previews: PreviewProvider {
    static var previews: some View {
        MyView()
    }
}


text:
Q: How to reflect from an ellipse while solving a system of differential equations? While solving a system of differential equations to plot trajectories, we can use NDSolve and WhenEvent like shown here.
I am trying to solve this for a system of equations (Hamiltons Equations) for a free particle, so that the reflection is from a surface of ellipse (like elliptical pool table).

Where r and th are r and theta coordinates.
In the r, theta cordinates, the equation of ellipse reads as:

The initial conditions I have given (in the variable of time i.e. r(t), theta(t), etc) are r(t=0)= 2.29 (which is r(theta=Pi)), theta(t=0) = Pi, pr(t=0)=1, pth(t=0) = 0.
Where pr and pth are radial and angular momentum given by Hamilton's Equations
This is how I am implementing it, but the reflection is occurring from a circle and not an ellipse. Please help.
The code is:
b=1;
eps=0.9;
m=1;
R=b/(Sqrt[1-(eps*Cos[th])^2]);
H = pr[t]^2/(2*m) + pth[t]^2/(2*m*r[t]^2);
xxx = NDSolve[{r'[t] == D[H, pr[t]],th'[t] == D[H, pth[t]], pr'[t] == -D[H, r[t]], pth'[t] == -D[H, th[t]],r[0] == 2.29, th[0] == Pi, pr[0] == 1, pth[0] == 0,WhenEvent[r[t]^2 == (b/Sqrt[1 - (eps*Cos[th[t]])^2])^2, pr[t] -> -pr[t]]}, {r[t], th[t], pr[t], pth[t]},{t, 0,100}]
Show[PolarPlot[{xxx[[1]][[1]][[2]]}, {t, 0, 100}],PolarPlot[b/(Sqrt[1 - (eps*Cos[th])^2]), {th, 0, 2*Pi},PlotStyle -> Red]]

The output I get is a very pretty but wrong image:
The trajectories must lie inside the ellipse (red), because the reflection condition given by WhenEvent defines the boundary of the circle.
What am I doing wrong?

A: So, the problem here is the use of PolarPlot. Once we use PolarPlot, the function takes the parameter 't' as the theta variable and hence generates faulty graph.
Here the interpolating functions generated are of $r(t)$ and $\theta(t)$. We need to do a ParametricPlot of $r(t)cos(\theta(t))$ vs $r(t)sin(\theta(t))$ and it will give the correct graph.
Show[ParametricPlot[{xxx[[1]][[1]][[2]]*Cos[xxx[[1]][[2]][[2]]], xxx[[1]][[1]][[2]]*Sin[xxx[[1]][[2]][[2]]]}, {t, 0, 100}], PolarPlot[b/Sqrt[1 - (eps*Cos[th])^2], {th, 0, 2*Pi}],PlotStyle -> Red], PlotRange -> All]