text:
Q: How do I resolve 302 Error when using HttpClient? I've created a custom DNN module that uses HTTPClient to send information to an external API.  My HttpClient method is as follows:
public static async Task<string> CreatePayerResponse()
    {
        var credentials = GetCredentials();
        var objEventLog = new EventLogController();
        var gatewaySettings = new GatewaySetting_ProPay();
        SignupResult_ProPay result = new SignupResult_ProPay();
        using (HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler())))
        {
            HttpRequestMessage request = new HttpRequestMessage();
            HttpResponseMessage response = new HttpResponseMessage();
            response.EnsureSuccessStatusCode();
            client.BaseAddress = new Uri("https://xmltestapi.propay.com/ProPayAPI/signup");
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            string responseBody;
            GatewaySetting_ProPay gatewaySetting = new GatewaySetting_ProPay();
            SignupRequest payerRequest = new SignupRequest();
            HttpContent content = new StringContent(payerRequest.ToString());
            try
            {
                request.Headers.Add("Authorization", credentials);
                request.Headers.Add("accept", "application/json");
                response = await client.PutAsync("https://xmltestapi.propay.com/ProPayAPI/signup", content);
                responseBody = await response.Content.ReadAsStringAsync();
                objEventLog.AddLog("Merchant Onboarding Request Sent", portalSettings, userId,
                    response.ToString(), EventLogController.EventLogType.ADMIN_ALERT);
                Console.WriteLine(responseBody);

            }
            catch (HttpRequestException ex)
            {
                result.Succeeded = false;
                result.Status = ex.Message;
                objEventLog.AddLog("Merchant Onboarding Error!", portalSettings, userId, response.ToString(),
                    EventLogController.EventLogType.ADMIN_ALERT);
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", ex.Message);
            }

            return response.Content.ToString();
        }
    }
public static string GetCredentials()
    {
        GatewaySetting_ProPay gatewaySettings = new GatewaySetting_ProPay();
        var billerAccountId = "mycreds";
        var authToken = "mycreds";
        var encodedCredentials =
            Convert.ToBase64String(Encoding.Default.GetBytes(billerAccountId + ":" + authToken));
        var credentials = string.Format("Basic {0}", encodedCredentials);
        return credentials;
    }

When I wire this method up to a click event, an HTTP 302 response is received and nothing is sent to the API.  What modifications are needed to ensure proper transmission?
Update
I still receive the following response:
Error code 302 was received from server response.

This is despite implementing the AllowAutoRedirect property and setting it to true.  Here's the LoggingHandler class I've written:
public LoggingHandler(HttpMessageHandler innerHandler) : base(innerHandler)
    {

    }
    protected async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken, HttpClientHandler handler)
    {
        Console.WriteLine("Request:");
        Console.WriteLine(request.ToString());
        if (request.Content != null)
        {
            Console.WriteLine(await request.Content.ReadAsStringAsync());
        }
        Console.WriteLine();
        handler.AllowAutoRedirect = true;
        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

        Console.WriteLine("Response:");
        Console.WriteLine(response.ToString());
        if (response.Content != null)
        {
            Console.WriteLine(await response.Content.ReadAsStringAsync());
        }
        Console.WriteLine();

        return response;
    }

Is this the proper way to implement HttpClientHandler and associated properties?

A: Make sure that instance of HttpClientHandler has AllowAutoRedirect property set true and is used by your HttpClient.

A: After implementing trace logs for System.Net.Http and related namespaces, the logs stated that the connection was forcibly closed.  After further research, it turns out the .NET Framework 4.5 is not compatible with more modern Transport Layer Security (TLS) versions.  As such, the approach of calling the API from our DNN application had to be jettisoned because the source code we're extending targets .NET Framework version 4.5.


text:
Q: How can I do instructions in function of the result of a test .gz? LINUX i have a .gz file. I want to know whether the .gz is corrupted or not.
If it is corrupted I need to do something and if it is not, i need to do other things.
My script is this:
#!/bin/sh
gunzip --test  file.gz
if [[ I DON´T KNOW WHAT TO PUT HERE ]];
then
//THINGS TO DO IF FILE.GZ IS NOT CORRUPTED
else
//THINGS TO DO IF FILE.GZ IS CORRUPTED
fi

How can I do the condition of the if? Thanks in advance

A: #!/bin/sh
if gunzip --test file.gz
then
//THINGS TO DO IF FILE.GZ IS NOT CORRUPTED
else
//THINGS TO DO IF FILE.GZ IS CORRUPTED
fi

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add and Customize Pages permissions required for Full Control user to add Basic page to document library I'm an admin on a modern Hub Team Site in SharePoint Online, with Full Control Permissions.  I created a Document Library and enabled content types and added the Basic Page type so I can add pages to this library.
Whenever I try to create an entry in this library from the Basic Page option, I am able to create the page by naming the file, but the following step that should open the page in design mode shows this error:

Web Part Error: A Web Part or Web Form Control on this Page cannot be displayed or imported. You don't have Add and Customize Pages permissions required to perform this action.

I've seen various posts from the classic experience talking about the need to create a new permission at the site level with the required permissions, but doing that and adding my user which already has Full Control doesn't fix it.
How can this be the out-of-the-box experience for page content types in a document library for a user who already has full control?? Is this a long-standing bug?

A: This is by design, often to discourage the use of classic features or due to potential security issues with scripting. You can run this on the site:
Set-SPOSite -DenyAddAndCustomizePages:$false

That will allow you to leverage these features.


text:
Q: How to combine non-tail recursion + effective and synchronized memoization + bounded stack consumption in Clojure? How can one combine non-tail recursion with synchronized memoization and bounded stack consumption (thus no risk of stack overflow) in Clojure? By synchronized memoization I mean that the memo/cache must be concurrently and efficiently shared among threads.
My specific case is as follows:
; g() is non recursive
; i is an integer
; h is a hash with int keywords and vector of ints values
; w is a hash with int keywords and int values
(defn g [i h w]
  (filter
    #(-> (w %)
         (= i))
    (h i)))

; f is recursive, recurses non-trivially (non-tail, multiple times)
; TODO: be memoizable (ideally in a synchronized way, for parallelism)
; TODO: pose no risk stack overflow
(defn f [i h w]
  (if (nil? (h i))
    0
    (let [part_sum
      (map                     ; will change this map to pmap or pvmap
        #(f % h w)
        (g i h))]
      (-> (reduce + part_sum)
          (/ 2)
          (+ 1)))))

; trivial, shown for completeness
(defn ff [i h w]
  (-> (f i h w)
      (- 1)
      (* 2)
      (max 0)))

A: Fortunately These questions can be addressed independently:

*

*a consistent shared memoize cache

*non-tail recursive iteration without blowing the stack

For question 1, you need to first decided at what point the cache should be populated. Should it be populated at the time that you start computing the function. Meaning that it should be absolutely guaranteed that each function will only run once, even if a second call is made while the first one is running. Or if you want to allow two calls to the function to happen at the same time and store only one of them into the cache. A slight variation on this is when you simply store the last result returned into the cache.
This last approach is what you get by default if you just call
(def memoized-function (memoize function-name))

ans it's suficient for almost all cases. If you need the other options then make the funtion you wish to memoize return a future rather than the result, and just deref the values you get from the cache before you use them.
For option two, the built in trampoline function allows you to have constant stack non-tail recursive functions. You change your function to return a value that is not a function (just a normal result) in the base case (when recursion has finished) and to return a function if further recursion is required. then the trampoline function "bounces" into the function repeatedly until a value falls out the other side. It looks like this:
user> (defn foo-helper [x]
        (let [result
              (if (pos? x)
                #(foo-helper (dec x))
                x)]
          (println "foo" x)
          result))
#'user/foo-helper
user> (trampoline foo-helper 4)
foo 4
foo 3
foo 2
foo 1
foo 0
0

So you can combine the normal caching from Clojure with the normal trampline function invocation without having to worry about "thread safety"


text:
Q: Double integration using Python I have the following integral (I don't know why the screenshot went so low so you need to scroll a bit).
I tried the following code:
from scipy import pi, sqrt
from scipy.integrate import dblquad
func = lambda x,y: ((1-sqrt(x**2+y**2))/(sqrt(x**2+y**2)))*(x**2)
x1,x2 = -1, 1
y1,y2 = lambda x: -sqrt(1-x**2), lambda x: sqrt(1-x**2)
print (dblquad(func, x1, x2, y1, y2))

But I keep getting
The occurrence of roundoff error is detected, which prevents
  the requested tolerance from being achieved.  The error may be
  underestimated.
  **opt)

The result I get doesn't seem correct:
(nan, 1.0867783627477699e-07)

A: The integrand of your integral is not defined at the point (0, 0). Mathematically, you end up dividing 0 by 0. Computationally, func(0.0, 0.0) will give a NaN, so if dblquad happens to evaluate your integrand at that point, you can expect to get a NaN as a result.
However, the integrand is continuous near (0, 0), and has a limit of 0 as (x, y) approaches (0, 0) from any direction, so it's natural to extend the definition of the integrand to the whole unit disk by specifying that its value at (0, 0) is 0.
So to fix the integration, you can rewrite func to special-case the point (0, 0), for example with:
def func(x, y):
    if x == y == 0.0:
        return 0.0
    else:
        return (1-sqrt(x**2+y**2))/(sqrt(x**2+y**2)))*(x**2)

On my machine, if I make that replacement for func and then execute the rest of your code exactly as written, I get the following result:
>>> print (dblquad(func, x1, x2, y1, y2))
(0.261799387785821, 1.4745421123040386e-08)

And as I'm sure you're aware, it's straightforward to evaluate the integral analytically to find that the value should be π/12. So let's compare the value we got with the expected value:
>>> pi / 12.
0.2617993877991494

So it looks as though SciPy is giving a result that's accurate to within the desired error bounds.


text:
Q: ExtJS Split button in grid cell I want to use split button in grid cell. I define renderer for cell, but I can't put extjs component in grid cell. Can anyone help?
Split button: http://dev.sencha.com/deploy/ext-3.4.0/examples/menu/menus.html

A: You can't put components in grid cells, which is an odd limitation.
Check out http://skirtlesden.com/ux/component-column , he has built an extension that overcomes this.


text:
Q: Dynamically add instance inherited from QWidget I have already searched for similar questions but couldn't find anything related to this particular problem. If somebody has any idea, it would be very appreciated. :)
I am working on a image annotation tool (the annotation is made of landmarks to be positioned/dragged over the image). The image is being displayed in a subwindow (the main window has a MDI container). Inside the widget class that inherits the subwindow I am trying to create several instances of a FeatureWidget class (code bellow), inherited from QWidget and that will later be further coded to handle dragging and a couple of other things. The features are being stored in a std vector (std::vector), and I am not using pointers on purpose (I've implemented the copy constructor and assignment operator and intended to use vector.resize to handle changes in the number of features).
The problem is the following: if I create the features at the subwindow widget constructor, they are displayed as expected; however, if I create the features later on (when the open annotation file menu slot is called), the features are simply not shown at all. No error ocurr and the rest of the code works indeed ok (meaning I can even iterate the vector and log feature coordinates).
Just to point out: I already tested with pointer instances in the vector (i.e.: std::vector) and that seems not to be the problem. The feature widgets are being set with the same parent (the QLabel that displays the image).
Here are some snippets of the code:

*

*FeatureWidget class:
class FeatureWidget: public QWidget
{
    Q_OBJECT
public:
    explicit FeatureWidget(QWidget *pParent = 0);
    FeatureWidget(const FeatureWidget &oOther);
    ~FeatureWidget();

    FeatureWidget& operator=(const FeatureWidget &oOther);
. . .

*Widget class used in the MDI subwindow:
class ChildAnnotationWidget : public QWidget
    {
        Q_OBJECT

    private:
        std::vector<FeatureWidget> m_vFeatureWidgets;
. . .

*Method from subwindow widget that instantiates the feature widgets:
void ff::ChildAnnotationWidget::updateFeatureWidgets()
{
    if(m_oTrainingSet.numFeatures() == 0)
        m_vFeatureWidgets.clear();
    else
    {
        m_vFeatureWidgets.resize(m_oTrainingSet.numFeatures());
        for(unsigned int i = 0; i < m_vFeatureWidgets.size(); i++)
            m_vFeatureWidgets[i].setParent(ui->lbImage);
    }
}

*Slot method from subwindow widget that opens the annotation file and redefines the feature widgets in the vector:
void ff::ChildAnnotationWidget::openAnnotation()
{
    QString sFile = QFileDialog::getOpenFileName(this, tr("Open Annotation File"), ".", tr("Annotation Files (*.yaml)"));
    if(sFile.length())
    {
        if(m_oTrainingSet.loadFromFile(qPrintable(sFile)))
        {
            m_sFileName = sFile;
            m_bChanged = false;
            updateFeatureWidgets();
            showSample(1);
            updateStatusBar();
        }
        else
            QMessageBox::critical(NULL, tr("Error Opening Annotation"), tr("It was not possible to open the annotation file. Please verify if the file format is correct."), QMessageBox::Ok);
    }
}

The annotation file that I am using in the tests contains 76 features. As I said before, if I force the creation of those 76 features at the constructor (calling updateFeatureWidgets and passing the size as a parameter instead of getting from m_oTrainingSet.numFeatures), the features are correctly displayed. Otherwise, they are not.
Any ideas/suggestions?


text:
Q: MySQL query to update records with incremented date I am trying to

*

*get the latest date in a database, and

*based on that date update every record that has a NULL date, increasing the date by 1 day.

I can get the latest date by using the Latest Date query below. I need to do this first because the dates in the table are not in order. If need be, I can run this query, manually write it down, then run the UPDATE query based on this date. I would prefer to run everything without the manual process.
The last query I have at the bottom of the question is my test query for trying to update the dates, however I had no luck getting it to work.
Table (dates are not in order)
id     date
-----  ----------
10500  2013-08-18
10501  2013-08-16
10502  2013-08-17
10503  2013-08-19
10504  NULL
10505  NULL
...
11800  NULL
11801  NULL

Selecting the latest date (starting point for UPDATE)
SELECT date
FROM my_table
ORDER BY date DESC
LIMIT 1

Updating NULL dates (doesn't work)
UPDATE my_table
SET date = DATE_ADD((SELECT date FROM my_table ORDER BY date DESC LIMIT 1), INTERVAL 1 DAY)
WHERE date IS NULL
ORDER BY id ASC

How can I accomplish this? Or is this not possible?

A: Try
UPDATE Table1 t1 JOIN
(
  SELECT id, @n := @n + 1 rnum
    FROM Table1 CROSS JOIN (SELECT @n := 0) i
   WHERE date IS NULL
   ORDER BY id
) t2 ON t1.id = t2.id CROSS JOIN
(
  SELECT MAX(date) date FROM Table1
) q
   SET t1.date = q.date + INTERVAL t2.rnum DAY

Result:

|    ID |       DATE |
----------------------
| 10500 | 2013-08-18 |
| 10501 | 2013-08-16 |
| 10502 | 2013-08-17 |
| 10503 | 2013-08-19 |
| 10504 | 2013-08-20 | --  date has been assigned
| 10505 | 2013-08-21 | --  date has been assigned

Here is SQLFiddle demo
Explanation: In a subquery with an alias t2 we grab all rows where date IS NULL order them by id and assign row numbers starting from 1. Unfortunately MySql doesn't have an implementation for ROW_NUMBER() function so we do it with a user variable @n which is incremented while rows are selected. To initialize this variable we use a subquery with an alias i. And use CROSS JOIN to make it available for our subquery t2. We then use the same technique (CROSS JOIN) to grab a max date in the table and make it available for every row in our JOIN. ONce we have all that we just add a line number,  which represents a number of days) add it to the max date and assign to date column in our table.

A: Use join syntax instead:
UPDATE my_table cross join
       (SELECT max(date) as maxdate FROM my_table) const
SET my_table.date = DATE_ADD(const.maxdate, INTERVAL 1 DAY)
WHERE my_table.date IS NULL;


text:
Q: RepositoryItemReader skipping chunks I am using RepositoryItemReader to read records from the database and using Chunk oriented process these records. I am using 100 as page size and commit interval.
    Query for the reader has "timestamp" in where condition and this date will be get updated by chunk processing when a chunk of 100 get the process and committed. The problem I am running is let's say I have 986 records that need's to be read and updated the date in a chunk of size 100 (1-100). All works as expected first time but when it picks up the second chunk it is processing 201-300, not 101-200 which is unexpected. This pattern continues, the third time it is picking up 501-600 and so on. The pattern is skipping 100 first time and 200 second time and so on. Is my update and commit of chunks causing this? Please advise how to fix this, so it can process all the records.
Spring batch version:   4.0.1.RELEASE
Code:
 @Autowired
    private MpImportRepository importRepo;
@Autowired
    JpaTransactionManager jpaTransactionManager;
   @Autowired
    private MpImportRepository importRepo;

 @Bean
    @StepScope
    public RepositoryItemReader<MpImport> importDataReader() {
           RepositoryItemReader<MpImport> reader = new RepositoryItemReader<>();
           reader.setPageSize(100);
           reader.setRepository(importRepo);
           reader.setMethodName("findAllImportedMissingPersons");
           reader.setSort(Collections.singletonMap("missingDate", Sort.Direction.ASC));
        return reader;
    }

@Bean
    @Qualifier("mpDataExtractAndSaveToYrstJob")
    public Job mpDataExtractAndSaveToYrstJob() {
        return jobBuilderFactory.get("mpDataExtractAndSaveToYrstJob")
                .incrementer(new RunIdIncrementer())
                .listener(jobCompletionListener)
                .flow(mpDataExtractAndSaveToYrstStep())
                .end().build();

 @Bean
    @Qualifier("mpDataExtractAndSaveToYrstStep")
    public Step mpDataExtractAndSaveToYrstStep() {
           return stepBuilderFactory.get("mpDataExtractAndSaveToYrstStep")
                   .<VMpHotfilesDailyExtract, MpImport> chunk(Integer.parseInt(100))
                   .reader(hotFilesReader())
                   .processor(hotFilesProcessor())
                   .writer(importDataWriter())
                   .transactionManager(jpaTransactionManager)
                   .listener(mpdataExtractStepListener)
                   .listener(chunkCompletionListener)
                   .build();
    }

 @Bean
    @StepScope
    public RepositoryItemWriter<MpImport> importDataWriter() {
        RepositoryItemWriter<MpImport> writer = new RepositoryItemWriter<>();
          writer.setRepository(importRepo);
          writer.setMethodName("save");
       return writer;
    }


text:
Q: Angular: Is *ngFor suitable for extemely long arrays? I'm programming a web version for our Android app, which is similar to Instagram. I chose this to create the feed:
<div *ngFor="let post of postList"> ... </div>

Inside that div tag is the HTML of a single post, like the image, the caption etc.
My question is if that is a good choice of architecture. In particular, I'm concerned if this works if the user keeps scrolling to the bottom and the array postList becomes arbitrarily big.
If I understand it correctly, the HTML code of the site will grow arbitrarily big too (for each new post, one clone of that div is appended, right?).
But doesn't that cause performance issues at scale? Coming from Android I know that when you use ListView you will get exactly those performance issues, so you use RecylcerView instead, which recycles views, so no matter how big the array is, you only have a "small" amount of views being used due to the recycling.
How to handle this in web dev? Am I good to go with my solution from above?

A: Another option you could try if you do not want pagination but want the list to be performant, would be cdkVirtualFor from angular material.  With little setup this can turn a large list into something that performs very well.
https://material.angular.io/cdk/scrolling/overview

A: In short, that will be a problem if you're not limiting the number of results returned. I would recommend researching pagination for limiting query results


text:
Q: Make Socks 5 requires username / password authentication? Titanium web proxy How do users connect to SocksProxyEndPoint must authenticate username and password.
I have read that in the latest version of Titanium web proxy which allows to enable username password authentication when creating a SocksProxyEndPoint. But I don't know how to write that code and also can't find illustrative example, can someone help me do this

A: For basic authentication, just set the ProxyBasicAuthenticateFunc property on the ProxyServer instance. For example:
void Main()
{
    var proxyServer = new ProxyServer();

    proxyServer.OnClientConnectionCreate += OnConnect;
    proxyServer.BeforeRequest += OnBeforeRequest;

    var socksProxy = new SocksProxyEndPoint(IPAddress.Loopback, 1080, false);

    proxyServer.ProxyBasicAuthenticateFunc = OnBasicAuth;

    proxyServer.AddEndPoint(socksProxy);
    proxyServer.Start();

    ...
}

public Task<bool> OnBasicAuth(SessionEventArgsBase ev, string u, string p) {
   if (u == "test" && p == "pass") {
       return Task.FromResult(true);
   }
   return Task.FromResult(false);
}

Note that the data will be sent in plain text (no encryption). It could be acceptable in intranets, but if you allow public access to your proxy, either use a different authentication scheme (ProxySchemeAuthenticateFunc) or tunnel the traffic.


text:
Q: c++ return array of unsigned char I have this function:
    unsigned char* encrypt_decrypt( unsigned char* text,unsigned char* pass)
    {
       unsigned char *s=(unsigned char*)malloc(strlen((char*)text+1)*sizeof(unsigned char));
       int length=strlen((char*)text);
       printf("chestii:%d",sizeof(s));
       for(int i=0;i<length;i++)
       {

        s[i]=text[i]^pass[i];
        printf("text:%d\n",text[i]);
        printf("pass:%d\n",pass[i]);
        printf("cript:%d\n",s[i]);
       }
       s[length]='\0';

       return s;
    }

The text and pass have the exact length and the s pointer should have the same length as the text at the end of the function.For example let's say that the text and pass have 26 characters.I don't know why but at the end of the for instruction,the length of the s pointer is only 10.I allocated enough memory and I think i put 26 elements in s.Please help me figure out why strlen(s) is only 10 ?

A: strlen counts up to a 0 byte so if a letter is in common in text and pass it will terminate the string early because text[i]^pass[i]==0 if text[i]==pass[i].


text:
Q: Data Validation Warning Message with openxlsx Package in R: Sprintf Basically, I am creating data validated excel spreadsheets for data entry purposes using R. The code seems to work however I get a warning message when I run the dataValidation functions. I am curious as to why Im getting this warning and if I need to change anything? Checking the package documentation everything seems to be correct but maybe Ive missed something. I have added some code below highlighting the process of making a workbook in r for excel.
#start workbook
wb2 <- createWorkbook()

# Add worksheet "SampleEntry" to the workbook
addWorksheet(wb2, "SampleEntry")

#add site data to the new workbook
writeData(wb2, sheet = "Sites", x = site_db$site_id, startCol = 1)

#use data validation on column 2 of the first page of workbook with site data
dataValidation(wb2, "SampleEntry",
               cols = 2,
               rows = 2:10000,
               operator = "equal",
               type = "list",
               value = "'Sites'!$A:$A")

Warning message:
In sprintf("<x14:dataValidation type="list" allowBlank="%s" showInputMessage="%s" showErrorMessage="%s">",  :
one argument not used by format '<x14:dataValidation type="list" allowBlank="%s" showInputMessage="%s" showErrorMessage="%s">'


text:
Q: On Index page Display IP address in PHP On My index page I want display the IP address of system or client. For that I wrote this function in separate file.
This is my function:-
function getClientIp() {
    $ipaddress = '';
    if ($_SERVER['HTTP_CLIENT_IP'])
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if($_SERVER['HTTP_X_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if($_SERVER['HTTP_X_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if($_SERVER['HTTP_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if($_SERVER['HTTP_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if($_SERVER['REMOTE_ADDR'])
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    $_SESSION['myIp'] = $ipaddress;
}

I want to use this function on my index page to display IP address.

A: Suggestion:-
remove @ from your code,skipping errors is not a good practice at all.
add session_start(); on top of your both page (code page and index page) just after <?php
In index page you can fetch value by just doingecho $_SESSION['myIp'];
Call the function in your code page:-
function getClientIp() {
    $ipaddress = '';
    if ($_SERVER['HTTP_CLIENT_IP'])
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if($_SERVER['HTTP_X_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if($_SERVER['HTTP_X_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if($_SERVER['HTTP_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if($_SERVER['HTTP_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if($_SERVER['REMOTE_ADDR'])
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    $_SESSION['myIp'] = $ipaddress;
}
getClientIp();

A: If this is your get_ip.php
session_start(); // this is required on both the pages

function getClientIp() {
    $ipaddress = '';
    if ($_SERVER['HTTP_CLIENT_IP'])
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if($_SERVER['HTTP_X_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if($_SERVER['HTTP_X_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if($_SERVER['HTTP_FORWARDED_FOR'])
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if($_SERVER['HTTP_FORWARDED'])
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if($_SERVER['REMOTE_ADDR'])
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $_SESSION['myIp'] = $ipaddress;

}

Your index.php
session_start(); // this is required on both the pages

include("get_ip.php");

echo getClientIp();

OR
session_start(); // this is required on both the pages

include("get_ip.php");

echo $_SESSION['myIp'];


text:
Q: Second identical jest test failing after the first one passes I have two identical jest tests, the first one passes and the second fails. From what I have read it could be something to do with mocking the someFunction. I am clearing all the mocks before each test, I have tried jest.resetAllMocks(); but that does not seem to work.
const authenticatedUser = {
    "id": 1,
    "accessFlags": [],
}

jest.mock("../src/someFunction", () => ({
  return {someData: ["a", "b"]}
}));

describe("My Tests", () => {
  let ex;

  beforeEach(() => {
    jest.clearAllMocks();

    ex = new FauxExpress();
  });

  it("Description", async () => {
    const req = {
      user: { ...authenticatedUser, access: ["admin"] },
    };

    await doSomethingUsingMockedSomeFunction(req, ex.res);

    expect(ex.res.statusCode).toBe(200);
  });

  it("Description", async () => {
    const req = {
      user: { ...authenticatedUser, access: ["admin"] },
    };

    await doSomethingUsingMockedSomeFunction(req, ex.res);

    expect(ex.res.statusCode).toBe(200);
  });
});


text:
Q: Gradle multiproject define dependency on root project I have a multi project gradle build, configured in this way:
root
  |
  |---- projectA
  |
  |---- projectB

I want to declare in the root/build.gradle a dependency for all nested projects, this is the file:
subprojects {
      version = '1.0-SNAPSHOT'
      repositories {
           mavenLocal()
           mavenCentral()
           maven {
               url 'https://repository.jboss.org/nexus/content/groups/public-jboss/'
           }
       }
}

allprojects {
    dependencies {
        compile 'org.projectlombok:lombok:1.12.2'
    }
}

But when I execute the build, I have:
* What went wrong:

A problem occurred evaluating root project 'code'.
No signature of method:
org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.compile() is applicable for argument types: (java.lang.String) values: [org.projectlombok:lombok:1.12.2]

Possible solutions: module(java.lang.Object)
What I am doing wrong?

A: compile method is part of the plugin you've been using (reference).
allprojects {

    apply plugin: 'java'
    //so that we can use 'compile', 'testCompile' for dependencies

    dependencies {
        implementation 'org.projectlombok:lombok:1.12.2'
    }
}

A: If you got the 'java' plugin has been applied, but it is not compatible with the Android plugins error, try this
subprojects {
    afterEvaluate {
        dependencies {
            implementation "YOUR DEPENDENCIES"
        }
    }
}


text:
Q: Background task in windows store App I'm developing an application which communicates with REST services. I want to implement a background process/task which continues to run throughout the life-cycle of the application.
Expected behavior of background process/task is it should monitor/listen the local DB(Sqlite) and whenever a record added to local db it sends it to Server using Restful APIs. Kinda synchronization.
It may happen that the application gets disconnected from internet/network and let's assume few records were not synced due to N/W unavailability. So next time whenever N/W gets up the background process starts sending pending records to the server.

Question: How can i achieve this? Do i need to do some threading?
Reference links are welcomed :-)

A: You need to create a Windows Runtime Component project fo background tasking. Follow this Link.
I think this example is similar to your requirements :
Be aware, that a Windows Runtime Component has limitations, check "Declaring types in Windows Runtime Components" section for example.


text:
Q: How to check that an auction is finished - Triggered PHP processing I have a few ideas about this but here is what I need to do and just wanted some second opinions really.
I am writing a small auction site in PHP/SQL, but I have come up against a hurdle.
When an item finishes, much like eBay, I need to be able to tell that it's finished and send out the emails to who has won it and who has sold it.
The only way I can think of is to schedule a piece of code to keep checking what auctions have ended but surely there is a better way?

A: The solution can be in multiple parts :

*

*A script that is launched via Cron (every 5 minutes could be good, even less...). It detects the finished auction and put them in a queue.

*A script, that pretty much runs continuously, and that processes items in the queue.
Note that :

*

*You have to ensure that an auction is still open before displaying the page ! (a simple test) That way people can't join in after it closes.

*For each script, you can use PHP, or any other language

Advantages :

*

*The cron job is very fast, low on resources, and if there are a lot of auction to process, there is no risk it will be run in parallel (and then conflicts)

*The queue system ensure that your system won't crash because there is too much going on... It will process the queue as fast as possible, but if it is not fast enough, the website will continue to run. You can however end up with emails being sent hours or days after the auction is closed. But the "limit" is way more predictible, and won't crash your system.

*You can extend it in the future with multithreading processing of the queue, distributed processing... This is a scalable architecture.

*This architecture is fun.

Additionnal informations :

*

*Regarding the daemon script, I doesn't have to run continuously. What you can do is : at the end of the cron job, if there are items in the queue, then it checks if the other script (processing) is running. If yes then exit. If the other script is not running, it launches it...

*The daemon script gets an item out of the queue and process it. At the end, if there are still items in the queue, it processes it, else, it exits.

*With this system, everything is optimal and everyone loves each other !

To check if the other script is running, you can use a file and write in it "1" or "0" (= running / not running). The first script reads it, the second writes it... You can also use the database to do it. Or you can maybe use system tools or shell command...

A: Please be kind to share the SQL script that query the highest bidder based on the bidding end date (how to know the bidding is over) and award the product to the highest bidder

A: I would setup a cron job to run every 10-20-30-60 minutes etc to send out emails and update the auction details.
If you're script is fast, running it every minute or so may be alright.
Be aware that many shared hosting will only allow you to send out a certain number of emails per hour.
Do these emails need to be sent out instantly?,

A: I can see 2 possible problems and goals you are trying to achive:

*

*Visual: You want that when a user browse your website, without updating or refreshing the page, it keeps updating the page so that if an audition ends, it appears something like "Audition ended, the item goes to...".
Solution: You should use Javascript and AJAX. (I assume you are already using it for countdowns or something). Make an AJAX call every 5 seconds (could be enough) and update the content.

*Pratical: You want that if an audition is ended an user cannot join it. Solution: You can do it just with PHP and mysql. You could create a fields where you store the audition start timestamp and then make a simple if (time() >= ($timestamp + $duration)) {} (where $timestamp is the start of the audition and $duration is the duration of the audition) to block possible bad users trying to do it.


text:
Q: How do I sized of grid in Gridview flutter? I want to change the dynamic size of children according to its array count.
It is a way same like GridLayoutManger in android java.
What I did in android(java)
GridLayoutManager mng_layout = new GridLayoutManager(this, 4/*In my case 4*/);
        mng_layout.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position)
            {
                int mod = position % 6;
                if (fullSizeGrid(position))
                    return 4;  //one grid take space of four grid
                else if (position == 0 || position == 1)
                    return 2;
                else if (position < 6)
                    return 1;
                else if (position<18)
                {
                    return method1(mod);
                }
                else if (position>18)
                {
                    return method2(position);
                }
                else
                    return 1;
            }

        });

By this I can change any grid size dynamically , I have my own formula for my layout.
So Is there any way to change size of any grid in Gridview Flutter?
Please Don't suggest staggered GridView it is not for me.

A: GridView does not support dynamic span, you can use spannable_grid

A: you can wrap you grid inside container and set size of container using height and width


text:
Q: can't pass arguments to running flask webserver From my android app I make pictures with my raspberry pi via ssh and i try to upload them to a website with Flask. Before that the app ask the users to enter a code and I want this code to be in the url, this is why I need the argparse.
I want the server to be running and in the meantime I want to pass new urls to the script that creates pages. When I'm running pitonka.py and I add arguments, tnb_flask.py doesn't get them.
What can be the solution?
Thanks in advance!
pitonka.py:
   from flask import Flask
   import argparse
   import random

   tenor = ''
   def tuzok():
          if args.arg_name == "az":
          else:
                 tenor = ''
                 if args.arg_name == '':
                        tenor = ''
                 else:
                        tenor = args.arg_name
          print("tenor", tenor)

   if __name__ == "__main__":
          parser = argparse.ArgumentParser()
          parser.add_argument("arg_name", help="Enter function's name", type=str, default ="az")
          args = parser.parse_args()
          tuzok()

tnb_flask.py
   from flask import Flask
   from pitonka import *
   app = Flask(__name__)

   @app.route('/')
   def index():
          denis = 25
          print("tenor:+", tenor, "+")
          to_ret = "tenor:+" + tenor+  "+\n" + str(denis)
          return to_ret

   if __name__ == "__main__":
          app.run(debug=True)
          if tenor != "az":
                 print("nem az!!!")
                 @app.route('/tuna/<tenor>')
                 def index__(numbi):
                        return 'working: args.arg_name %s' % tenor
          else:
                 print("azzal egyezik meg")


text:
Q: How to print the type annotations of a function in Python? So let's say I defined the following function with type annotations:
from typing import List
def my_function(input_1: str, input_2: int) -> List[int]:
    pass

Is there a way to show the annotated types of this function? Maybe a function types_of or something similar? So that it can be used like this:
>> types_of(my_function)
[str, int] -> [List[int]]

A: You can use __annotations__
from typing import List
def my_function(input_1: str, input_2: int) -> List[int]:
    pass

In [2]: my_function.__annotations__
Out[2]: {'input_1': str, 'input_2': int, 'return': typing.List[int]}

Or you can use get_type_hints function from typing module. Actually I think this is more appropriate solution.
According to the docs get_type_hints returns a dictionary containing type hints for a function, method, module or class object.
Function example:
from typing import get_type_hints, List

def my_function(input_1: str, input_2: int) -> List[int]:
    pass

In [2]: get_type_hints(my_function)
Out[2]: {'input_1': str, 'input_2': int, 'return': typing.List[int]}

Class example:
For a classes get_type_hints returns a dictionary constructed by merging all the __annotations__ along Foo.__mro__ in reverse order.
class Bar:
    BAR_C: bool = True

class Foo(Bar):
    FOO_STR: str = 'foo'
    FOO_INT: int = 42

    def __init__(a: str, b: int) -> None:
        self._a = a
        self._b = b

    def some_method(self, foo: List, bar: bool) -> bool:
        pass

In [7]: get_type_hints(Foo)
Out[7]: {'BAR_C': bool, 'FOO_STR': str, 'FOO_INT': int}

Out[8]: get_type_hints(Foo.__init__)
Out[8]: {'a': str, 'b': int, 'return': NoneType}

In [9]: get_type_hints(Foo.some_method)
Out[9]: {'foo': typing.List, 'bar': bool, 'return': bool}

Module example
Our module test_module.py
from typing import Dict

SOME_CONSTANT: Dict[str, str] = {
    '1': 1,
    '2': 2
}

class A:
    b: str = 'b'
    c: int = 'c'

def main() -> None:
    pass

if __name__ == '__main__':
    main()

Then let's open python shell:
In [1]: from typing import get_type_hints
In [2]: import test_module

In [3]: get_type_hints(test_module)
Out[3]: {'SOME_CONSTANT': typing.Dict[str, str]}

In [4]: get_type_hints(test_module.A)
Out[4]: {'b': str, 'c': int}

In [5]: get_type_hints(test_module.main)
Out[5]: {'return': NoneType}

A: You can use inspect module:
import inspect
from typing import List

def my_function(input_1: str, input_2: int) -> List[int]:
    pass

def types_of(func):
    specs = inspect.getfullargspec(func)
    return_type = specs.annotations['return']
    input_types = [t.__name__ for s, t in specs.annotations.items() if s != 'return']
    return f'[{", ".join(input_types)}] -> {return_type}'

types_of(my_function)

output:
'[str, int] -> typing.List[int]'

A: you can use inspect
import inspect

def sum_numbers(first_number=4,second_number=5):
    return a+b

def print_argtypes(function):
    specs = inspect.getfullargspec(sum_numbers)
    for s in range(len(specs[0])):
        print(specs[0][s]+': '+str(type(specs[3][s])))

print_argtypes(sum_numbers)

output
first_number: <class 'int'>
second_number: <class 'int'>


text:
Q: Bash-script File creation and fill I am trying to write a bash-script which will create a certain number of files which are passed into an argument, and also fill that file with relevant information. However, for some reason I can't get it to work properly, and googling turned up nothing.
I want it to create files like the following:
FileName:
Prob_3_ch_17.cpp

Filled as the following:
/*
User: Johnny Smith
Prob: 3
Output:
*/

Where the first command line argument is the chapter number. The second is the starting number, and the third is the ending number. So if the following is ran
sh ../FileMaker.sh 17 1 10

It will make 10 files, each filled with the appropriate data and proper file names, for chapter 17. This is the script that I came up with.
#!/bin/bash

# Syntax:
# $1 = Chapter Number
# $2 = Starting Number
# $3 = Ending Number

CHAPTER=$1
FIRST=$2
LAST=$3
U_NAME="Johnny Smith"

# Name: Prob_$NUMBER_Ch_$1.cpp

for ((NUMBER=$FIRST; $NUMBER<=$LAST; $NUMBER++));
   do
      if [ -e "Prob_$NUMBER_Ch_$CHAPTER.cpp" ]; then
         echo "File Prob_$NUMBER_Ch_$CHAPTER.cpp already exists!"
      else
         echo "/* \n User: $U_NAME \n Problem: $NUMBER \n Output: \n */" >> "Prob_$NUMBER_Ch_$CHAPTER.cpp"
   done

However, it doesn't run. I get the following error:
../FileMaker.sh: line 21: syntax error near unexpected token `done'
../FileMaker.sh: line 21: `done'

I've googled and found other people have had the same problem, but I didn't fully understand what was meant in the solution. Can someone please help me? I'm not the best at shell scripting, and I'm trying to learn by making scripts like this.
Thanks in advanced.

A: Syntax for if block and for-loop is wrong. correct syntax would be -
    for ((NUMBER=FIRST; NUMBER<=LAST; NUMBER++));
   do
      if [ -e "Prob_$NUMBER_Ch_$CHAPTER.cpp" ]; then
         echo "File Prob_$NUMBER_Ch_$CHAPTER.cpp already exists!"
      else
         echo "/* \n User: $U_NAME \n Problem: $NUMBER \n Output: \n */" >> "Prob_$NUMBER_Ch_$CHAPTER.cpp"
      fi
   done

See example 11.12 for c style for loop.
To create files use "Prob_"$NUMBER"Ch"$CHAPTER".cpp" at all the places.

A: Most shells allow a set -x at the top.  This show you tracing of the script as it executes.

*

*You need a trailing fi to close the if statement.

*Shell math need NUMBER=$(expr $NUMBER + 1), it doesn't understand $NUMBER++.

*You might find the printf command more handy than echo.

You will still have your variable use wrong in the loop and are only creating one file.  I hope you can figure that out as this seems like homework.


text:
Q: Symbol to integer error in inject this should be pretty easy for ruby wizards here. I'm having a problem with inject. This is it simply :
a = Resource.all
a.inject({ :wood => 0 }) { |res, el| res[:wood] + el.cost(1)[:wood] }
TypeError: can't convert Symbol into Integer

a is a collection and i would like to create a sum of all the wood resources of this collection. The el.cost(1)[:wood] works fine and gets an integer (resources value). So this part is correct. It seems that i have a problem with initializing my new hash with the :wood symbol and setting that value in each iteration, but i can't really find the problem.
Any ideas ?

A: inject works like this:

*

*take initialization value, pass it into the lambda with the first element in the list. Use the result of the lambda as the new accumulator

*pass that new accumulator into the lambda together with the next element in the list. Use the result of the lambda as the new accumulator

*And so on...

So what you have to do in the lambda is:

*

*Take the hash in res.

*Modify it.

*Return the hash.

You fail to do 2 and 3, that's why that code doesn't work. Try the following:
a.inject({ :wood => 0 }) { |res, el| res[:wood] += el.cost(1)[:wood]; res }

This is however a bit redundant. You can easily accumulate the integers first and then create a hash:
{ :wood => a.map { |el| el.cost(1)[:wood] }.reduce(0, :+) }


text:
Q: How exactly do static fields work internally? Say you have a class,
class Foo
{
    public static bar;
}

When you say:
new Foo();

I can imagine that in memory, a space is reserved for this object.
...and when you say again:
new Foo();

...well now you have another space available for the object.
However, where exactly does the static field live?
What I am really trying to learn is:
How do the references to the objects reference the same field of the objects they reference?

A: For Java, objects referred to by static fields will reside on the heap like other objects:

The heap is the runtime data area from which memory for all class instances and arrays is allocated.

The field will be initialised (if the declaration contains an initialization) when the class is loaded, which happens immediately before the first occurrence of any one of the following:

*

*an instance of the class is created.

*a static method declared by the class is invoked.

*a static field declared by the class is assigned.

*a static field declared by the class is used and the field is not a constant variable (§4.12.4).

The access to the static field is done via 2 special JVM instructions, getstatic and putstatic. But apart from that distinction, static fields are similar to non static fields.

A: This varies wildly from language to language, and can even vary wildly from platform to platform...
For example, on the .NET side, static members are "associated" with the governing EEClass definition, which can be a heap-allocated OR a "wherever" allocated member (the C# spec doesn't specify heap/stack behavior, it's an implementation detail of the VM)

A: Im only familiar with C#, and this is my understanding of it:
Then your program starts, it loads all the related assemblies into an AppDomain.
When the assambly is loaded, all static constructors are called, including static fields. They will live in the there, and the only way to unload them, is to unload the AppDomain.

A: There might be exceptions, but for reference types the new-keyword usually creates an object in an internal data structure called "heap". The heap is managed by the CLR (Common Language Runtime). It makes no difference whether you have a static or instance member or a local variable.
The difference between static members and instance members (the ones without the keyword static) is, that static members exist only once per type (class, struct) and instance members exist once per instance (per object).
It is only the reference which is static or not; this distinction does not apply to the referenced object (unless the object is a value type). A static member, an instance member and a local variable can all reference the same object.

A: Static members and constants are stored on heap. Unlike objects on heap that can get garbage collection, Static members and constants do stay till Appdomain is torn down, Hence once should be carefull in dealing with static fields

A: Static variables belong to the class not the object so there is only one bar in the memory even if you initialize thousands of instants of Foo.

A: This completely depends on the implementation in question.  For C# and Java, the runtime is allowed to determine where to store the memory for the variable.  For C and most compiled languages, the compiler makes this determination.
That being said, in practice, it doesn't matter.  The usage it determined by specification, so you are free to use the variable knowing the behavior will be guaranteed.

A: While the exact details of the type system are implementation dependent, let me go into some more detail than just stating that it depends and you should not care. I'll describe how it approximately works in Microsoft's implementation (.NET) according to the book CLR via C# by Jeffrey Richter and the article See How the CLR Creates Runtime Objects by Hanu Kommalapati et al. (original MSDN May 2005 issue).

Say you have a class:
class Foo
{
    // Instance fields
    string myBar = "Foobar";
    int myNum;

    // Static fields
    static string bar = "Foobar";
    static int num;
}

Foo myFoo = new Foo();
Type typeOfFoo = typeof(Foo);

Where do the instance fields live?
Whenever you say new Foo(), space is allocated and initialized for the object instance, and the constructor is called. This instance is shown as instance of Foo in the image below. Such as instance contains only the instance fields of the class (in this case myBar and myNum), and for objects allocated on the heap two extra fields used by the runtime (Sync block index and Type handle). The type handle is a pointer to a Type object that describes the type of the instance, in this case type of Foo.
When you say new Foo() again, new space is allocated which will again contain space for the instance fields of the type. As you can see, instance fields are associated with object instances.
The runtime puts each instance field at a fixed offset from the start of the object's data. For example, myBar might live at offset +4. The address of the instance field is simply the address of the object plus the offset of the field.
Where do the static fields live?
Static fields in C# and Java are not associated with any object instance, but with a type. Classes, structs and enums are examples of types. Only once (per type) is some space allocated to hold the values of the static fields. It would make sense to allocate space for the static fields in the Type structure that describes the type, since there is also only one Type object per type. This is the approach taken by C# and Java.
The Type object1 is created when the type is loaded by the runtime. This structure contains all sorts of information needed for the runtime to be able to allocate new instances, call methods and perform casting, among other things. It also contains the space for the static fields, in this case bar and num.
The runtime has put each static field at some offset from the start of the type's data. This is different for each type. For example, bar might live at offset +64. The address of the static field is the address of the Type object plus the offset of the field. The type is statically known.

1) In Microsoft .NET multiple different structures describe a type, such as the MethodTable and the EEClass structures.

A: This depends on the language to language or the designer of the language. If I talk about Java, static members store in the Method area of the JVM and all the object are linked to them. One more thing that is very important to know is that we can access the static data member without creating the object of the class.It means the allocation of the memory to the static data members doesn't depend on the creation of the object of that class.

A: By specification static variables are stored in Constant Pool. JVM stores this info in Permanent Generation.

A: Typically Static variables are stored on the data-segment of the program memory.
so for every class that is created/is in the running program will create the static variable on data-segment and all other variables are initialized in the code segment.
so basically it is like
+++++++++++++++++++++++++++++++++++++
+ DATA Segment
+   -static vars
+
+----------------------------------
+  instances | instances | instances|
+            |           |          |

here single area is shared among instances.
from wikipedia
    "The data area contains global and static variables used by the program that are
    explicitly initialized with a value."


text:
Q: My WebAPI responses 301 I'm developing a Chat Bot for the Streaming Service Twitch.tv. They can provide webhooks which request your api. Everytime when I want to register a webhook and Twitch tries to contact my api, my api responsed with 301 for no reason. I don't response to 301 in my code.
I don't use https and a few weeks ago it worked.
I would be happy if someone could help me.

A: u can try to add this Propertie in your HttpWebRequest
request.AllowAutoRedirect = true

that if u use HttpWebRequest. so pls share your request code


text:
Q: Kivy: how to stop touch screen events passing through to desktop I have a Python Kivy (v1.11.1) app on Raspberry Pi 3B+, and use touch screen to interact with the app. The touch screen events work well with the Kivy app. However the same touch screen events also pass through to the Raspbian desktop. When I hit a button in the Kivy app, the same touch event also passes through to the desktop which may hit an icon on the desktop which may make a mess to the desktop after I use the app for a while. I wonder how to stop the events passing through from the app? I only want the app to consume the events! There must be an option in the Kivy app config but I don't know what that it. Please help...

A: That's what you mean? -
from kivy.config import Config
Config.set('input', 'mouse', 'mouse,disable_multitouch')


text:
Q: Creating a custom form type in symfony2: can't overwrite buildView() I am creating a custom form type in symfony2. But every time I try to overwrite the buildForm() method I get this error:

Fatal error: Declaration of SeduceMe\SiteBundle\Form\Type\UniFormTextType::buildView() must be compatible with that of Symfony\Component\Form\FormTypeInterface::buildView() in /Users/alexander/Projekte/SeduceMe/serversymfony204/src/SeduceMe/SiteBundle/Form/Type/UniFormTextType.php on line 33

Of course I understand what this means. I even copied the method signature from the mentioned interface. Still the same. This is my class:
namespace SeduceMe\SiteBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class UniFormTextType extends AbstractType
{
    public function getDefaultOptions(array $options)
    {
        return array('placeholder' => null);
    }

    public function getParent(array $options)
    {
        return 'text';
    }

    public function getName()
    {
        return 'UniFormText';
    }

    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->setAttribute('placeholder', $options['placeholder']);
    }

    public function buildView(FormView $view, FormInterface $form)
    {
        $view->set('placeholder', $form->getAttribute('placeholder'));
    }
}

A: Need to add use statements for FormView and FormInterface.
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\CallbackValidator;
use Symfony\Component\Form\FormValidatorInterface;

A: The symfony doc is wrong in this section:
http://symfony.com/doc/2.0/book/forms.html#creating-form-classes
FormTypeInterface::buildView() now requires FormBuilderInterface, not FormBuilder, which is what that error is complaining about.
So you must do:
use Symfony\Component\Form\FormBuilderInterface;

And use that in your method declaration also like so:
public function buildForm(FormBuilderInterface $builder, array $options)


text:
Q: How save password of a third party application in my app for use with a api? I need to save a third-party application password in my PHP application for connect to a API in a background process. I need store the password in a DB, and the password is for each user of the application. But I don´t know what is the correct way to save it for retrieve it after.
I don´t want to save the password without encryption, but I don´t know which is the best method (and easy) to do this
Any idea?

A: Unless there's some sort of OAuth mechanism available for the API you might as well store it in plain text. Once an attacker has access to the encrypted form of the password then they more than likely have access to the code that decrypts it.
My preferred method is:
inc.credentials.php
<?php
$app_creds = array(
  'username' => 'sammitch',
  'password' => 'isgreat'
);

actual_code.php
<?php
require('inc.credentials.php');
app_login($app_creds['username'], $app_creds['password']);
unset($app_creds);

*

*Always uses a file extension that's run through the PHP interpreter so that the file will not be served as plain text.

*Always leave off the closing ?> so nothing is accidentally output. [most likely whitespace]

*unset() is mostly paranoia, but just in case of code injection.


text:
Q: Flex RichText shows Jagged text, sometimes I'm building an iPad app with Flex/CS3 in Flash Builder 4.7. Making an iPad app. However, when being tested some people started telling me that some screens have the RichText sparks elements showing text jagged, rather than smooth.
However, it only happens sometimes. If you go back to that screen the text looks fine. Any ideas why such a thing might be happening? Most of the time everything looks fine, both locally on my development machine as well as on the iPad app when it's being looked at on a tablet.

A: The problem was that under certain circumstances it was adding multiple rich text components with the exact same text in it over and over itself, meaning I'd have several layers of identical content that, when overlapped, made it look pixelated on most devices.
I've made the app be a little smarter and not add what's already there, and it's looks great. Thanks.


text:
Q: Kalman Filter Matrix Dimensions Mismatch at Estimating New Value Im referring to the Kalman Filter Explanation. When applying the mentioned operation and when estimating the new value, I cannot do the operations mentioned since the matrix dimensions are not matching.
I have the variables as below
A transition matrix - 2x2 - {{1d, timestampDiff}, {0d, 1d}};
X from the previous state - 2x1 - {{measuredValue}, {measuredChangingRate}}
P variance matrix - 2x2 - {{1000, 0}, {0, 1000}}
H Measurement matrix - 1x2 - {1,1}
Z measured values - 1x2 - {34.5,4}

My calculations are as below
t - denotes the transpose
' - denotes the inverse
1. Xk = A.X ( 2x2 . 2x1 = 2x1 )
2. Pk = A.P.At ( 2x2 . 2x2 . 2x2 = 2x2 )

3. K = Pk.Hkt / (Hk.Pk.Hkt + Rk )
   (2x2 . 2x1 ) / ( 1x2 . 2x2 . 2x1 + 1x1 ) = 2x1
4. Xk(estimate) = Xk + K.(Z - Hk.Xk)
   2x1 + (2x1 . (1x2 - 1x2 . 2x1)) = 2x1 + 2x2

In the 4th step, i cannot add the two matrices since its dimensions are different.
Please point me out where I did my mistake.
Thanks a lot.

A: You have too many measurements.  z should be a vector with as many rows as H.

A: I referred to the 2 links [1] and [2] and managed to configure my matrix. My measurement matrix H was defined with the wrong dimensions. And the correct dimension is 2x2.
H Measurement matrix - 2x2 - {{1,0},{0,1}}

*

*https://courseware.ee.calpoly.edu/~fdepiero/fdepiero_dsp_notes/notes%20&%20materials/kalman%20filter%20notes.pdf

*http://www.swarthmore.edu/NatSci/echeeve1/Ref/Kalman/MatrixKalman.html


text:
Q: get mail attribute from LDAP using c# I use this function to access LDAP and get user's email address attribute
public string Login(string userName, string password)
{
        DirectoryEntry de = new DirectoryEntry();

        de.Path = "LDAP://000.000.0.00"; // forexample
        de.AuthenticationType = AuthenticationTypes.Secure;
        de.Username = userName;
        de.Password = password;

        DirectorySearcher search = new DirectorySearcher(de);
        search.Filter = "(&(samaccountname=" + userName + "))";
        search.ReferralChasing = ReferralChasingOption.All;

        SearchResult resultCol = search.FindOne();
        string mailProperty="";
        if (resultCol != null)
        {
            if (resultCol.Properties["mail"] != null && resultCol.Properties["mail"].Count > 0)
            {
                mailProperty = resultCol.Properties["mail"][0].ToString();
            }
        }

        return mailProperty;
    }

I didn't get mail attribute in the list of returned attributes, that is the list of attributes I got which doesn't contain the mail attribute

*

*givenname              , samaccountname        , cn                    ,
pwdlastset            , whencreated           , badpwdcount
, displayname           , lastlogon             , samaccounttype
, countrycode           , objectguid            , usnchanged
, whenchanged           , name                  , objectsid
, logoncount            , badpasswordtime       , accountexpires
, primarygroupid        , objectcategory        , userprincipalname
, useraccountcontrol    , description           ,
dscorepropagationdata , distinguishedname     , objectclass          , usncreated            , lastlogontimestamp    , adspath           , lastlogoff            , instancetype          , codepage           , sn

A: After investigation with the system admin, I found that to retrieve mail attribute from LDAP user has to have both accounts, the normal active directory account and mail box account (exchange), if user does not have mailbox account so any LDAP query will not retrieve the mail attribute


text:
Q: Broadcasting from processes if a condition is met in MPI I am new to MPI and and I'm trying to broadcast from one of the processes if a condition is met. The problem is that I don't see broadcasted messages on other processes when I try to print it out. When a process passes the second if condition it broadcasts a numpy array. In my code, processes 0, 1, 3, 5, 7 pass the second if condition. Here's the code:
import numpy as np
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()

rand_num=np.empty(5,dtype='float')
bands  = [(0, 65), (66, 132), (133, 198), (199, 264), (265, 330), (331, 396), (397, 462), (463, 529)]
volts = {'map1':[478], 'map2':[346], 'map3':[213], 'map4':[81], 'map5':[34]}

for items in volts.keys():
    if(len(volts[items])!=0):
        neur_id = volts[items][0]
        if neur_id in range(bands[comm.rank][0],bands[comm.rank][1]):
            rand_num = np.array([comm.rank for i in range(0,5)],dtype='float')
            comm.Bcast(rand_num, root=comm.rank)
        comm.Barrier() #hoping to stop other processes from proceeding.
    print 'data and rank',rand_num,comm.rank

I was expecting the output to look like:
data and rank [ 0.  0.  0.  0.  0.] 0           data and rank [ 1.  1.  1.  1.  1.] 0          data and rank [ 3.  3.  3.  3.  3.] 0          data and rank [ 5.  5.  5.  5.  5.] 0          data and rank [ 7.  7.  7.  7.  7.] 0
data and rank [ 0.  0.  0.  0.  0.] 1           data and rank [ 1.  1.  1.  1.  1.] 1          data and rank [ 3.  3.  3.  3.  3.] 1          data and rank [ 5.  5.  5.  5.  5.] 1          data and rank [ 7.  7.  7.  7.  7.] 1
data and rank [ 0.  0.  0.  0.  0.] 2           data and rank [ 1.  1.  1.  1.  1.] 2          data and rank [ 3.  3.  3.  3.  3.] 2           data and rank [ 5.  5.  5.  5.  5.] 2         data and rank [ 7.  7.  7.  7.  7.] 2
data and rank [ 0.  0.  0.  0.  0.] 3          data and rank [ 1.  1.  1.  1.  1.] 3           data and rank [ 3.  3.  3.  3.  3.] 3          data and rank [ 5.  5.  5.  5.  5.] 3          data and rank [ 7.  7.  7.  7.  7.] 3
data and rank [ 0.  0.  0.  0.  0.] 4          data and rank [ 1.  1.  1.  1.  1.] 4            data and rank [ 3.  3.  3.  3.  3.] 4          data and rank [ 5.  5.  5.  5.  5.] 4          data and rank [ 7.  7.  7.  7.  7.] 4
data and rank [ 0.  0.  0.  0.  0.] 5          data and rank [ 1.  1.  1.  1.  1.] 5           data and rank [ 3.  3.  3.  3.  3.] 5          data and rank [ 5.  5.  5.  5.  5.] 5           data and rank [ 7.  7.  7.  7.  7.] 5
data and rank [ 0.  0.  0.  0.  0.] 6          data and rank [ 1.  1.  1.  1.  1.] 6            data and rank [ 3.  3.  3.  3.  3.] 6         data and rank [ 5.  5.  5.  5.  5.] 6           data and rank [ 7.  7.  7.  7.  7.] 6
data and rank [ 0.  0.  0.  0.  0.] 7          data and rank [ 1.  1.  1.  1.  1.] 7             data and rank [ 3.  3.  3.  3.  3.] 7         data and rank [ 5.  5.  5.  5.  5.] 7            data and rank [ 7.  7.  7.  7.  7.] 7

However, the output looks completely different. I don't see anything logically wrong with my code.
PS: It has brought to my attention that this question is a duplicate of this. None of my processes are deadlocking. My problem is about synchronizing. I also read here that MPI will not synchronize Bcasts if all the processes don't call Bcast, which is why I used Barrier immediately after Bcast. This was marked as duplicate by the fact that bcast was not called on all processes(ranks). If in my application  MPI's bcast can't be used as required then which MPI command should I use for "broadcasting"?
Since, this question was marked as duplicate, I couldn't answer it myself. I am posting my solution, I used Send and Recv over a for loop to solve my issue:
import numpy as np
from mpi4py import MPI
from mpi4py.MPI import ANY_SOURCE
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()

rand_num=np.empty(5,dtype='float')
bands  = [(0, 65), (66, 132), (133, 198), (199, 264), (265, 330), (331, 396), (397, 462), (463, 529)]
volts = {'map1':[478], 'map2':[346], 'map3':[213], 'map4':[81], 'map5':[34]}

for items in volts.keys():
    if(len(volts[items])!=0):
        neur_id = volts[items][0]
        if neur_id in range(bands[comm.rank][0],bands[comm.rank][1]):
            rand_num = np.array([comm.rank for i in range(0,5)],dtype='float')
            all_ranks = [i for i in range(0,size)]
            all_ranks.remove(rank)
            rest_ranks = all_ranks
            for ranks in rest_ranks:
                comm.Send(rand_num, dest= ranks)

        else:
            comm.Recv(rand_num, source = ANY_SOURCE)

    print 'data and rank',rand_num,comm.rank, items


text:
Q: Service Bus PeekLock issue with Azure Function I have multiple message in my Service Bus Topic and I would like to process this message one by one and on a Service Bus Trigger, it should get all the messages which has not been processed. and since I am doing testing and debugging, I would not like the messages to be completed i.e. if it is not completed it stays in the topic for any other services to consume.
I have started with Azure Function App with Service Bus Topic Trigger and have moved up til here where I get all the message in my log but once it is done, I don't get any other messages because all have been consumed and they move to the "Dead-letter message count", so its become very difficult for me to do any debugging and testing.
I would like to know how can I handle this with Azure Function Service Bus trigger where I run the Function see the body of my message in console, exit it and then do the necessary transformation and then repeat the process. Without service bus trigger, I can do it with PeekLock thing and dont allow any message to be completed, but how do i do it with Function as it seems to take the messages at once for triggering.
 namespace ServiceBusCopyFunction
{
    public static class GetMetadataFromSB
    {
        static ISubscriptionClient subscriptionClient;
        [FunctionName("GetMetadataFromSB")]
        public static void Run([ServiceBusTrigger("TopicNameSB", "SubscriptionNameSB", Connection = "AzureServiceBusString")] string mySbMsg, ILogger log)
        {
            log.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg}");

        }
    }
}

A: You can deactivate the autoComplete functionality in the host.json file. Here's the reference:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus-output?tabs=csharp#hostjson-settings
Example:
{
    "version": "2.0",
    "extensions": {
        "serviceBus": {
            "messageHandlerOptions": {
                "autoComplete": false
            }
        }
    }
}

So the messages won't get completed after processing them.


text:
Q: SQL Server to count how many times a value appears between multiple date ranges and compare to previous weeks I first asked a similar question at
SQL Server to count how many times a value appears between multiple date ranges
and wasn't sure if I should post a new question or modify the original post.  Though it's building on the original post I felt it was different enough to render a new post - please advise if this was the correct thing to do.
I wasn't given a few solutions that worked well but unfortunately a caveat was thrown at me and I need to make some modifications based on an additional criteria and not able to solve it.
First off here again are some sample data and the expected output
|   Time_Stamp    | Emp_ID  | Balance | Hours |
|-----------------|---------|---------|-------|
| 7/16/2017 19:40 | 3140340 |    2250 |  37.5 |
| 7/16/2017 19:40 | 2000950 |    4050 |  67.5 |
| 7/16/2017 19:40 | 3118410 |     400 |   6.7 |
| 7/16/2017 19:40 |  311840 |   11700 |   195 |
| 7/23/2017 21:19 | 3140340 |    2250 |  37.5 |
| 7/23/2017 21:19 | 2000950 |    4050 |  67.5 |
| 7/23/2017 21:19 | 3118410 |     800 |  13.3 |
| 7/23/2017 21:19 | 3124160 |     450 |   7.5 |
| 7/23/2017 21:19 |  311840 |     400 |   6.7 |
| 7/30/2017 7:00  | 3140340 |    2250 |  37.5 |
| 7/30/2017 7:00  | 2000950 |     400 |   6.7 |
| 7/30/2017 7:00  | 3118410 |    1200 |    20 |
| 7/30/2017 7:00  |  311840 |     700 |  11.7 |
| 8/6/2017 12:00  | 3140340 |     444 |   7.4 |
| 8/6/2017 12:00  | 3118410 |     444 |   7.4 |
| 8/6/2017 12:00  | 3124160 |      90 |   1.5 |
| 8/6/2017 12:00  |  311840 |     325 |   5.4 |
| 8/13/2017 12:00 | 3140340 |     900 |    15 |
| 8/13/2017 12:00 | 3118410 |    1350 |  22.5 |
| 8/13/2017 12:00 | 3124160 |      90 |   1.5 |
| 8/13/2017 12:00 |  311840 |    1700 |  28.3 |

Expected output is as follows
|         | 16-Jul | 23-Jul | 30-Jul | 6-Aug | 13-Aug |
|---------|--------|--------|--------|-------|--------|
| emp_id  | wk1    | wk2    | wk3    | wk4   | wk5    |
| 3140340 | 1      | 2      | 3      | 0     | 1      |
| 2000950 | 1      | 2      | 0      | 0     | 0      |
| 3118410 | 0      | 1      | 2      | 0     | 1      |
| 311840  | 1      | 0      | 1      | 0     | 1      |
| 3124160 | 0      | 1      | 0      | 1     | 2      |

An important note - unfortunately the data type for balance (minutes) is in varchar and I need to convert it to hours by dividing by 60.  I used the following for that
ROUND(CONVERT(varchar(50),CONVERT(float,([BALANCE]/convert(float,60.0)))),2) AS [Hours]

With that being said what I now need to accomplish is if the balance of each week is less than 7.5 hours then just put a 0 (zero).
If it is >= 7.5 hours then a count of 1.  If consecutive weeks are >= 7.5 hours - for example 2 consecutive weeks then the first week will have a count of 1 and the 2nd week a count of 2.  IF the 3rd week is below 7.5 hours then 0.
As stated earlier the original question along with the solutions can be found at
SQL Server to count how many times a value appears between multiple date ranges
Two of the solutions that worked really well for the original question were
;WITH
weekcounts AS (
SELECT Time_Stamp, Emp_ID, DATEPART(week, Time_Stamp) AS int_week FROM sampleData
)

,counts AS (
SELECT Emp_ID, int_week, 1 AS int_count
FROM weekcounts
UNION ALL
SELECT weekcounts.Emp_ID, weekcounts.int_week, 1 AS int_count
FROM weekcounts
    INNER JOIN counts
        ON weekcounts.Emp_ID = counts.Emp_ID
        AND (weekcounts.int_week - 1) = counts.int_week
)

,countsagg AS (
SELECT Emp_ID, int_week, SUM(int_count) AS int_count
FROM counts
GROUP BY Emp_ID, int_week
)

SELECT * FROM countsagg
PIVOT (MAX(int_count) FOR int_week IN ([29],[30],[31],[32],[33])) piv

and
; with wk_nbrs as
(
    --recursive CTE that generates the week numbers.
    -- 7/23 thru 7/29 is Week 1
    select cast('2017-07-23' as date) as wk_bgn
    , cast('2017-07-29' as date) as wk_end
    , 1 as wk_nbr
    union all
    select dateadd(d,7,fw.wk_bgn) as wk_bgn
    , dateadd(d,7,fw.wk_end) as wk_end
    , fw.wk_nbr + 1 as wk_nbr
    from wk_nbrs as fw
    where 1=1
    and fw.wk_nbr < 100
)
, emp_wk_cnt as
(
    --Getting the running total count of emp_id by week
    select a.emp_id
    , b.wk_nbr
    , count(*) over (partition by a.emp_id order by b.wk_nbr asc) as emp_wk_cnt
    from @emp_ts as a
    inner join wk_nbrs as b on cast(a.time_stamp as date) between b.wk_bgn and b.wk_end
    group by a.emp_id
    , b.wk_nbr
)
--pivoting the results out to final expected output
select post.emp_id
, post.wk2
, post.wk3
, post.wk4
from (
select a.emp_id
, 'wk' + cast(a.wk_nbr as varchar(10)) as wk_nbr
, a.emp_wk_cnt
from emp_wk_cnt as a
) as pre
pivot (sum(pre.emp_wk_cnt)
    for pre.wk_nbr in
        ([wk2],[wk3],[wk4])
) post
order by post.emp_id

Any additional assistance with this will be greatly appreciated.
Thanks in advance.

A: I think this might give you what you are looking for:
;WITH
weekcounts AS (
    SELECT Time_Stamp, Emp_ID, [Balance], ROUND(CONVERT(FLOAT,[Balance]) / 60.0,2) AS [Hours], DATEPART(week, Time_Stamp) AS int_week FROM newSampleData
)

,counts AS (
    SELECT Emp_ID, int_week, 1 AS int_count
    FROM weekcounts
    WHERE ([Hours] >= 7.5)
    UNION ALL
    SELECT weekcounts.Emp_ID, weekcounts.int_week, 1 AS int_count
    FROM weekcounts
        INNER JOIN counts
            ON weekcounts.Emp_ID = counts.Emp_ID
            AND (weekcounts.int_week - 1) = counts.int_week
            AND ([Hours] >= 7.5)
)

,countsagg AS (
    SELECT Emp_ID, int_week, SUM(int_count) AS int_count
    FROM counts
    GROUP BY Emp_ID, int_week
)

SELECT Emp_ID,
       ISNULL([29],0) AS [week 29],
       ISNULL([30],0) AS [week 30],
       ISNULL([31],0) AS [week 31],
       ISNULL([32],0) AS [week 32],
       ISNULL([33],0) AS [week 33]
FROM countsagg
PIVOT (MAX(int_count) FOR int_week IN ([29],[30],[31],[32],[33])) piv

Also if Balance is a varchar you are doing more converts than needed in your code provided. This will give the result for hours with less code:
ROUND(CONVERT(FLOAT,[Balance]) / 60.0,2)


text:
Q: Should I install Microsoft Redistributables not marked as "Supported"? I have a requirement to upgrade one of our Operating Systems from Windows Server 2012R2 to Windows Server 2016. The hosted application requires numerous ODBC Drivers that in turn require a bunch of Microsoft Redistributables. My problem is that several of the redistributable packages are not listed as supported for Windows Server 2016.
For example

*

*Microsoft Access Runtime 2016

*Microsoft Access Database Engine 2016
We also need to install Cloudera Impala ODBC driver which according to the documentation is compatible with Windows Server 2016, however the documentation also tells us the driver needs Visual C++ Redistributable Packages for Visual Studio 2013 which according to Microsoft is not supported on Windows Server 2016.
We also require SQL Server ODBC Driver 17 and this is listed as Windows Server 2016 supported, so it looks like Microsoft's documentation is updated.
What's the risk of proceeding with installing these redistributable packages on an apparently unsupported OS? Should this be avoided completely? Or would it be reasonable to test and risk accept if successful?


text:
Q: Error with GAM in mgcv: step failure in theta estimation I'm running a GAM using the mgcv package. Here is my model code. I'm using method ="ML" as I'm hoping to use the MuMIn package and dredge() for model selection on this model, and you can't use REML for model comparison.
mDEG_nb <- bam(deg ~ s(SE_score) + s(ri) + TL + species + sex + season + year +
                 s(code, bs = 're') + s(station, bs = 're'),
               family=nb(), data=node_dat, method = "ML")

th1 <- mDEG_nb$family$getTheta(TRUE) #extracts theta

mDEG_nb <- bam(deg ~ s(SE_score) + s(r)i + TL + species + sex + season + year +
              s(code, bs = 're') + s(station, bs = 're'),
            family=nb(th1), data=node_dat, method = "ML", na.action = "na.fail")

However using gam.check() I can see that I have an issue with the residuals with one of the smooths.
Method: ML   Optimizer: outer newton
full convergence after 7 iterations.
Gradient range [-0.001295518,0.002610357]
(score 82388.55 & scale 1).
Hessian positive definite, eigenvalue range [0.001293007,29.20119].
Model rank =  224 / 224

Basis dimension (k) checking results. Low p-value (k-index<1) may
indicate that k is too low, especially if edf is close to k'.

                k'    edf k-index p-value
s(SE_score)   9.00   1.00    0.90    0.59
s(ri)         9.00   8.98    0.34  <2e-16 ***
s(code)     134.00 100.15      NA      NA
s(station)   63.00  54.46      NA      NA

To deal with this, I tried to increase the value of K, however I keep getting this error indicating there's a problem issue estimating theta when I use values of K greater than 12.
Warning messages:
1: In estimate.theta(theta, family, G$y, linkinv(eta), scale = scale1,  :
  step failure in theta estimation
2: In estimate.theta(theta, family, G$y, linkinv(eta), scale = scale1,  :
  step failure in theta estimation

In addition I still have the residual issue no matter how much I increase K by. But that could be due to the error not calculating a new value of theta.
Is this warning an issue? And how can I change my model so that the residuals of this smoother are no longer a problem? If the residuals are not random, how does this impact my model results? I assume they are not to be trusted?
An example of my dataset is below should you need it.
> dput(head(node_dat))
structure(list(station = structure(c(17L, 49L, 23L, 25L, 25L,
9L), .Label = c("BE01", "BE02", "BEUWM01", "BL01", "BL02", "GCB01",
"GCB02", "GCB03", "NI01", "NI01b", "NI03", "PB01", "PB02", "PB03",
"PB04", "PB05", "PB06", "PB07", "PB08", "PB09", "PB10", "PB11",
"PB12", "PB13", "PB14", "PB15", "PB16", "PB17", "PB18", "PB19",
"PB20", "PB21", "PB22", "PB23", "PB24", "PB25", "PB26", "PB27",
"PB28", "PB29", "PB30", "PB4G01", "PB4G02", "PBUWM01", "PBUWM02",
"SA01", "SA02", "SA02b", "SA03", "SA04", "SA05", "SA06", "SA07",
"SA11", "SAUWM01", "SB01", "SB02/AR02", "SB03/AR05", "SB04/AR06",
"VB01", "VB02", "VB03", "VB04"), class = "factor"), monthyear = structure(c(27L,
17L, 38L, 4L, 19L, 29L), .Label = c("2014/01", "2014/02", "2014/03",
"2014/04", "2014/05", "2014/06", "2014/07", "2014/08", "2014/09",
"2014/10", "2014/11", "2014/12", "2015/01", "2015/02", "2015/03",
"2015/04", "2015/05", "2015/06", "2015/07", "2015/08", "2015/09",
"2015/10", "2015/11", "2015/12", "2016/01", "2016/02", "2016/03",
"2016/04", "2016/05", "2016/06", "2016/07", "2016/08", "2016/09",
"2016/10", "2016/11", "2016/12", "2017/01", "2017/02", "2017/03",
"2017/04", "2017/05", "2017/06", "2017/07", "2017/08", "2017/09",
"2017/10", "2017/11", "2017/12", "2018/01", "2018/02", "2018/03",
"2018/04", "2018/05", "2018/06", "2018/07", "2018/08", "2018/09",
"2018/10", "2018/11", "2018/12"), class = "factor"), code = structure(c(99L,
204L, 183L, 146L, 4L, 135L), .Label = c("2390", "13573", "13574",
"13575", "13576", "19318", "19319", "19321", "19322", "19506",
"19514", "19519", "19520", "19524", "25537", "25540", "25541",
"25543", "25546", "25549", "25552", "25553", "27583", "27585",
"27586", "27591", "27592", "27593", "27594", "27595", "27596",
"27597", "27600", "27601", "27605", "27607", "27608", "27613",
"27614", "27617", "27619", "27620", "27621", "27626", "27627",
"27629", "27630", "27631", "27632", "28608", "28611", "28612",
"28618", "28625", "28628", "28629", "28631", "28632", "28633",
"28638", "28641", "28644", "28662", "28672", "28674", "52978",
"54815", "54846", "54852", "54860", "54863", "54865", "54866",
"54868", "54877", "54882", "54883", "54884", "54886", "54890",
"54892", "54895", "54896", "54901", "54904", "54914", "54919",
"54920", "54922", "54925", "54931", "54932", "54938", "54952",
"54954", "54955", "54958", "54959", "54962", "59950", "59953",
"59954", "59955", "59957", "59958", "59959", "59960", "59961",
"59962", "59964", "59966", "59969", "59970", "59971", "59972",
"59973", "59975", "59976", "59979", "59981", "59988", "2388",
"12950", "12952", "12956", "12958", "12960", "12962", "12964",
"12966", "12968", "13577", "14203", "19320", "19523", "25534",
"25535", "25536", "25539", "25542", "25544", "25545", "25547",
"25548", "25550", "27584", "27588", "27589", "27590", "27598",
"27599", "27602", "27603", "27604", "27606", "27609", "27610",
"27611", "27615", "27616", "27618", "27622", "27624", "27625",
"28624", "28627", "28637", "28639", "28642", "28660", "28670",
"34176", "34177", "34178", "34179", "52975", "52977", "54817",
"54821", "54822", "54825", "54845", "54849", "54880", "54887",
"54889", "54893", "54898", "54899", "54905", "54911", "54912",
"54915", "54933", "54947", "54957", "54961", "59951", "59963",
"59968", "59978", "59991", "59992", "59993", "59994", "59995"
), class = "factor"), species = structure(c(1L, 2L, 2L, 2L, 1L,
2L), .Label = c("Grey Reef Shark", "Silvertip Shark"), class = "factor"),
    deg = c(0, 0, 0, 0, 0, 0), gs = c(0, 0, 0, 0, 0, 0), btw = c(0,
    0, 0, 0, 0, 0), ud = c(0, 0, 0, 0, 0, 0), ri = c(0, 0, 0,
    0, 0, 0), SE_score = c(0.35, 0.39, 0.18, 0.23, 0.36, 0.42
    ), region = structure(c(5L, 6L, 5L, 5L, 5L, 4L), .Label = c("Benares",
    "Blenheim", "Grand Chagos Bank", "Nelsons Island", "Peros Banhos",
    "Saloman", "Speakers Bank", "Victory Bank"), class = "factor"),
    date = structure(c(1456790400, 1430434800, 1485907200, 1396306800,
    1435705200, 1462057200), class = c("POSIXct", "POSIXt"), tzone = ""),
    month = c(3, 5, 2, 4, 7, 5), season = structure(c(2L, 1L,
    2L, 1L, 1L, 1L), .Label = c("dry.season", "wet.season"), class = "factor"),
    year = structure(c(3L, 2L, 4L, 1L, 2L, 3L), .Label = c("2014",
    "2015", "2016", "2017", "2018"), class = "factor"), sex = structure(c(1L,
    2L, 2L, 1L, 1L, 2L), .Label = c("F", "M"), class = "factor"),
    TL = c(117, 157, 137, 108, 94, 137), TL_stand = c(0.353383458646617,
    0.654135338345865, 0.503759398496241, 0.285714285714286,
    0.180451127819549, 0.503759398496241), btw_stand = c(0, 0,
    0, 0, 0, 0)), na.action = structure(c(`59` = 59L, `91` = 91L,
`119` = 119L, `144` = 144L, `715` = 715L, `754` = 754L, `780` = 780L,
`803` = 803L, `2116` = 2116L, `2452` = 2452L, `2489` = 2489L,
`2504` = 2504L, `2544` = 2544L, `3070` = 3070L, `3092` = 3092L,
`3126` = 3126L, `3151` = 3151L, `4464` = 4464L, `4800` = 4800L,
`4842` = 4842L, `4862` = 4862L, `4893` = 4893L, `6181` = 6181L,
`8221` = 8221L, `10073` = 10073L, `11232` = 11232L, `11603` = 11603L,
`11639` = 11639L, `11663` = 11663L, `11688` = 11688L, `12266` = 12266L,
`12288` = 12288L, `12322` = 12322L, `12347` = 12347L, `13660` = 13660L,
`14023` = 14023L, `14045` = 14045L, `14075` = 14075L, `14104` = 14104L,
`15417` = 15417L, `15780` = 15780L, `15795` = 15795L, `15837` = 15837L,
`15877` = 15877L, `17138` = 17138L, `17164` = 17164L, `17194` = 17194L,
`17219` = 17219L, `18532` = 18532L, `18895` = 18895L, `18917` = 18917L,
`18951` = 18951L, `18976` = 18976L, `20289` = 20289L, `20652` = 20652L,
`20674` = 20674L, `20704` = 20704L, `20729` = 20729L, `22055` = 22055L,
`22409` = 22409L, `22435` = 22435L, `22461` = 22461L, `22490` = 22490L,
`23803` = 23803L, `24166` = 24166L, `24188` = 24188L, `24218` = 24218L,
`24247` = 24247L, `25560` = 25560L, `25919` = 25919L, `25939` = 25939L,
`25976` = 25976L, `25996` = 25996L, `27308` = 27308L, `27330` = 27330L,
`27360` = 27360L, `27385` = 27385L, `28702` = 28702L, `29065` = 29065L,
`29087` = 29087L, `29121` = 29121L, `29146` = 29146L, `30459` = 30459L,
`30822` = 30822L, `30844` = 30844L, `30874` = 30874L, `30903` = 30903L,
`32216` = 32216L, `32579` = 32579L, `32605` = 32605L, `32631` = 32631L,
`32660` = 32660L, `33973` = 33973L, `34336` = 34336L, `34369` = 34369L,
`34397` = 34397L, `34415` = 34415L, `34875` = 34875L, `34901` = 34901L,
`34931` = 34931L, `34956` = 34956L, `36269` = 36269L, `36632` = 36632L,
`36658` = 36658L, `36684` = 36684L, `36709` = 36709L, `38026` = 38026L,
`38389` = 38389L, `38415` = 38415L, `38441` = 38441L, `38466` = 38466L,
`39783` = 39783L, `40146` = 40146L, `40168` = 40168L, `40198` = 40198L,
`40223` = 40223L, `41540` = 41540L, `41914` = 41914L, `41937` = 41937L,
`41960` = 41960L, `41984` = 41984L, `43297` = 43297L, `43633` = 43633L,
`43675` = 43675L, `43695` = 43695L, `43730` = 43730L, `45014` = 45014L,
`45363` = 45363L, `45400` = 45400L, `45415` = 45415L, `45455` = 45455L,
`45954` = 45954L, `45991` = 45991L, `46009` = 46009L, `46048` = 46048L,
`46541` = 46541L, `46576` = 46576L, `46602` = 46602L, `46627` = 46627L,
`46817` = 46817L, `46859` = 46859L, `46879` = 46879L, `46910` = 46910L,
`48198` = 48198L, `48547` = 48547L, `48589` = 48589L, `48609` = 48609L,
`48640` = 48640L, `49928` = 49928L, `50277` = 50277L, `50319` = 50319L,
`50345` = 50345L, `50370` = 50370L, `51658` = 51658L, `52007` = 52007L,
`52048` = 52048L, `52069` = 52069L, `52100` = 52100L, `53388` = 53388L,
`53737` = 53737L, `53778` = 53778L, `53799` = 53799L, `53830` = 53830L,
`55118` = 55118L, `55467` = 55467L, `55508` = 55508L, `55529` = 55529L,
`55560` = 55560L, `56848` = 56848L, `57197` = 57197L, `57238` = 57238L,
`57264` = 57264L, `57295` = 57295L, `58555` = 58555L, `58596` = 58596L,
`58617` = 58617L, `58648` = 58648L, `59936` = 59936L, `60285` = 60285L,
`60322` = 60322L, `60337` = 60337L, `60377` = 60377L, `60875` = 60875L,
`60905` = 60905L, `60931` = 60931L, `60972` = 60972L, `61441` = 61441L,
`61463` = 61463L, `61497` = 61497L, `61522` = 61522L, `62835` = 62835L,
`63197` = 63197L, `63236` = 63236L, `63260` = 63260L, `63276` = 63276L,
`63793` = 63793L, `64180` = 64180L, `64206` = 64206L, `64232` = 64232L,
`64261` = 64261L, `65574` = 65574L, `65937` = 65937L, `65959` = 65959L,
`65993` = 65993L, `66018` = 66018L, `67331` = 67331L, `67694` = 67694L,
`67716` = 67716L, `67746` = 67746L, `67772` = 67772L, `69088` = 69088L,
`69424` = 69424L, `69466` = 69466L, `69486` = 69486L, `69517` = 69517L,
`70805` = 70805L, `72253` = 72253L, `73419` = 73419L, `73760` = 73760L,
`73802` = 73802L, `73828` = 73828L, `73859` = 73859L, `75141` = 75141L,
`76590` = 76590L, `77752` = 77752L, `78906` = 78906L, `79486` = 79486L,
`79523` = 79523L, `79536` = 79536L, `79556` = 79556L, `80122` = 80122L,
`80159` = 80159L, `80174` = 80174L, `80214` = 80214L, `82125` = 82125L
), class = "omit"), row.names = c(31669L, 80335L, 63799L, 59674L,
1051L, 51949L), class = "data.frame")

A: After a bit of help from Simon Wood, I found an answer to removing residual errors. The issue was basically that ri=0 guarantees that deg=0, but to match that with a smooth requires a very sharp upswing from ri=0 to ri>0. As such you can use an adaptive spline, s(ri,bs="ad"), to deal with this upswing.


text:
Q: Android: Detect opened keyboard, onApplyWindowListener not working I am trying to hide one specific button at the bottom of my layout when the keyboard is opened, in order to make more view available for the user.
With the release of androidx.core:core-ktx:1.5.0-alpha02 google (finally) added a method called insets.isVisible(WindowInsetsCompat.Type.ime()) which returns a boolean whether the keyboard is opened or clicked.
I am using a base class EmailFragment where I set the function in order to achieve the above written functionality. My problem is that my ViewCompat.setOnApplyWindowInsetsListener(view) gets never called (no toast etc).
I've also tried to set ViewCompat.setOnApplyWindowInsetsListener(view) directly in the used Fragments, but that changed nothing.
My min API is 21, in my AndroidManifest.XML I have android:windowSoftInputMode = adjustResize
Code
abstract class EmailFragment<out T: ViewDataBinding>(
    layout: Int,
    // ... some other stuff that is not necessary for the question
) : BaseFragment<T>(layout) {
    // ... some other stuff that is not necesarry for the question

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        hideButton(view)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    private fun hideButton(view: View) {
        ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
            val isKeyboardVisible = insets.isVisible(WindowInsetsCompat.Type.ime())
            if (isKeyboardVisible) {
                btn.visibility = View.GONE
                Toast.makeText(requireContext(), "KEYBOARD OPEN", Toast.LENGTH_SHORT).show()
            } else {
                btn.visibility = View.VISIBLE
                Toast.makeText(requireContext(), "KEYBOARD CLOSED", Toast.LENGTH_SHORT).show()
            }

            // Return the insets to keep going down this event to the view hierarchy
            insets
        }
    }
}

Fragment that inherits from EmailFragment (one out of five)
class CalibrateRepairMessageFragment(
    //... some other stuff that is not necessary for this question
) : EmailFragment<FragmentCalibrateRepairMessageBinding>(
    R.layout.fragment_calibrate_repair_message,
    //... some other stuff that is not necessary for this question
) {
    //... some other stuff that is not necessary for this question

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //... some other stuff that is not necessary for this question
    }

Screenshot 1 (censored)

Screenshot 2, not working (censored)

I know that using android:windowSoftInputMode = adjustPen makes my button "invisible" but then I cannot scroll anymore, big sad..
Another solution could be that the keyboard just overlaps the button, but I have no clue how to do that...
I appreciate every help, thank you.

A: I was able to get this to work by:

*

*Adding android:windowSoftInputMode="adjustResize" to Activity tag in manifest

*Setting OnApplyWindowInsetsListener on window.decorView.

However, this had unfortunate side effects to the statusbar which means that OP's comment ("I have no hope that this will ever work") is probably accurate. Hopefully it will work when it graduates from alpha and beta.


text:
Q: onLocationChanged returns old location In my application which tracks traveled distance i have two buttons. First one start's location updates, second stops them.
public void start(View view){
    cords = new ArrayList<LatLng>();

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED){
        return;
    }

    LocationServices.FusedLocationApi.requestLocationUpdates(
            googleApiClient, locationRequest, this);
}

public void stop(View view) {
    LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}

Then i declare onLocationChanged where i calculate distance that user have traveled.
@Override
public void onLocationChanged(Location location) {
    cords.add(new LatLng(location.getLatitude(), location.getLongitude()));

    if (cords.size() > 1) {
        Location previousLocation = new Location("");
        previousLocation.setLatitude(cords.get(cords.size() - 2).latitude);
        previousLocation.setLongitude(cords.get(cords.size() - 2).longitude);

        stats.updateDistance(location.distanceTo(previousLocation));
    }
}

The problem is that when i stop measurements and then start them again, location returns old value. How could i get rid of this old value and start distance measurement from brand new location.

A: I figured out that i didnt get old location but instead i got location measured by network not gps, that's why it was so inaccurate. When i was moving further away from buildings, gps started to work and location was correct. So to get rid of network measurement i check if location hasAltitude(), if it doesn't it means that it was measured by network so i can ignore it.
 @Override
public void onLocationChanged(Location location) {
    if(location.hasAltitude()) {
        cords.add(new LatLng(location.getLatitude(), location.getLongitude()));

        if (cords.size() > 1) {
            Location previousLocation = new Location("");
            previousLocation.setLatitude(cords.get(cords.size() - 2).latitude);
            previousLocation.setLongitude(cords.get(cords.size() - 2).longitude);

            stats.updateDistance(location.distanceTo(previousLocation));
    }


text:
Q: How to prevent submit button submitting a form using Foundation 6.6 and Abide I am trying to use Foundation 6.6 Abide to validate a form and if the form is valid, I DO NOT want it to submit - but rather trigger another another event. Whatever I do - the form always seem to submit.
<form data-abide novalidate id="contactForm" >
  ...
  <input type="submit" value="Next " id="goToBillingAddressTab"/>
</form>

I have added this code - but it always submits.
// script to prevent form from submitting
$('#contactForm').on("submit", function(ev) {
    ev.preventDefault();
    console.log("Submit for form intercepted");
      return false;
  });

// script to trigger other events
    $('#contactForm').on("formvalid.zf.abide", function(ev,frm) {
      console.log("Form is valid");
      ev.preventDefault(); // also added prevent submit here
      // perform other tasks here

      return false; // and another version of prevent submit
  });

I have also tried this - but it still submits:
  $('#contactForm').on("submit", function(ev) {
  ev.stopPropagation();
  ev.stopImmediatePropagation();
  ev.preventDefault();
  console.log("Submit for form intercepted");
  return false;
});

$('#contactForm').on("formvalid.zf.abide", function(ev) {
console.log("Form is valid");
    ev.stopPropagation();
    ev.stopImmediatePropagation();
    ev.preventDefault();
    // perform other task

    return false;
});

A: SOLUTION!
I was using the "DOWNLOAD VERSION" of Foundation 6.6.1. That is where the bug creeps in somewhere.
If I use the CDNS:
https://cdnjs.cloudflare.com/ajax/libs/foundation/6.6.1/js/foundation.min.js
Then it works as it should


text:
Q: Open an url without using Browser using excel on Macbook Basically I want to open an URL where the browser windows doesn't show up to the user and fetch the output. I'm in the process of writing a Function need help. I'm trying to do this in Macbook.

A: if you turn off screen updating for this part of the process would that work?
Application.ScreenUpdating = False

your code for the url
Application.ScreenUpdating = True


text:
Q: Howto pass array values via from ejs to Javascript? I am passing an array via ejs with JavaScript. I can get to the values inside ejs but not from JavaScript. Below is more information.
node.js
FileTypes = {"application/octet-stream":20,
                 "audio/mpeg":12,
                 "text/html" :71}
res.render('index.ejs', {FileTypes: JSON.stringify(FileTypes)});

index.ejs
 <script type="text/javascript">

   var FileTypes =  <%=FileTypes%>;
   //Error message on the console - Uncaught SyntaxError: Unexpected token &

 </script>

Any ideas?

A: Using the <%= %> tag in EJS will escape the output, so {"application/octet-stream": ... } is being turned into {"application/octet-stream": ... }, resulting in JavaScript like this:
<script type="text/javascript">
  var FileTypes = {"application/octet-stream":20,"audio/mpeg":12,"text/html":71};
</script>

So, you can see where the "Unexpected token &" is coming from. The solution is to use the <%- %> tag, which won't escape the output:
<script type="text/javascript">
  var FileTypes = <%- FileTypes %>;
  //      here -----^
</script>

...and will give you what you want:
<script type="text/javascript">
  var FileTypes = {"application/octet-stream":20,"audio/mpeg":12,"text/html":71};
</script>