text:
Q: Authenticating HMAC in MVC3 Im building my own web service on the premise of 2-legged OAuth.
With each authenticated request there will be an included HMAC.
I know it could be done like this:
public ActionResult userInfoExample(string HMAC, string username)
    {
        MyMembership.checkHMAC(HMAC);
        //get user
        return View();
    }

but that is fairly nasty, because HMAC needs to be included in the parameters for every action. Its weakly typed and crap.
I wanted to do something like this:
[AuthorizeHMAC]
    public ActionResult userInfoExample(string username)
    {
        //get user
        return View();
    }

I found this, and it mentioned I should look at Custom Modal Binders, so then I found this and after reading it I am unsure how I could make that work.
My goal is to authenticate (/authorise) using a HMAC that (I assume) is placed in the URL parameters i.e.: http:// www.website.com/foo/bar?username=xxx&hmac=xxxxxxxxx
I would like to know if anyone has any references I can read or a direct solution.
I am also welcome to criticism on my fundamental understanding of API security, or how I am doing things, I am fairly new to this area of

A: Check out my code at
http://mvcsecurity.codeplex.com/
I do something similar to validate parameters on the page (it is not an HMAC though). Since you will be generating it on the View Im assuming (or passing it to the view) you can check it the same way a similar way I check it in my attribute.
From:

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //The hidden form field that contains our hash - for ex. CustomerId is rendered as a hidden input  id="_CustomerIdToken"
            string encryptedPropertyName = string.Format("_{0}Token", _propertyName);

            //grab the token
            string hashToken = filterContext.HttpContext.Request.Form[encryptedPropertyName];

            //The encrypted form data MUST be there. We do not allow empty strings otherwise this could give
            //an attack vector in our filter as a means to bypass checks by simply passing in an empty validation token.
            if (string.IsNullOrEmpty(hashToken))
            {
                throw new MissingFieldException(string.Format("The hidden form field named value {0} was missing. This is created by the Html.AntiModelInjection methods. Ensure the name used on your [ValidateAntiModelInjectionAttribute(\"!HERE!\")] matches the field name used in Html.AntiModelInjection method. If this attribute is used on a controller method that is meant for HttpGet, then the form value would not yet exist. This attribute is meant to be used on controller methods accessed via HttpPost.", encryptedPropertyName));
            }

            //Get the plain text value
            string formValue = filterContext.HttpContext.Request.Form[_propertyName];

            //Plain text must be available to compare.
            if (string.IsNullOrEmpty(formValue))
            {
                throw new MissingFieldException(string.Format("The form value {0} was missing. If this attribute is used on a controller method that is meant for HttpGet, then the form value would not yet exist. This attribute is meant to be used on controller methods accessed via HttpPost.", _propertyName));
            }

            //We cannot encrypt the form value and compare to the previously encrypted form token.
            //Each time you Encrypt() with the MachineKey class even using the same plain text, the end result is difference.
            byte[] plainTextBytes = MachineKey.Decode(hashToken, MachineKeyProtection.Encryption);

            string plainText = Encoding.Unicode.GetString(plainTextBytes);

            //And compare
            if (string.Compare(plainText, formValue , false, CultureInfo.InvariantCulture) != 0)
            {
                throw new HttpAntiModelInjectionException(string.Format("Failed security validation for {0}. It is possible the data was tampered with as the original value used to create the form field does not match the current property value for this field. Ensure if this is a web farm, the machine keys are the same.",_propertyName));
            }

            filterContext.HttpContext.Trace.Write("(Logging Filter)Action Executing: " +
                filterContext.ActionDescriptor.ActionName);

            base.OnActionExecuting(filterContext);
        }


text:
Q: Are static variables in a base class shared by all derived classes? If I have something like
class Base {
    static int staticVar;
}

class DerivedA : public Base {}
class DerivedB : public Base {}

Will both DerivedA and DerivedB share the same staticVar or will they each get their own?
If I wanted them to each have their own, what would you recommend I do?

A: They will each share the same instance of staticVar.
In order for each derived class to get their own static variable, you'll need to declare another static variable with a different name.
You could then use a virtual pair of functions in your base class to get and set the value of the variable, and override that pair in each of your derived classes to get and set the "local" static variable for that class. Alternatively you could use a single function that returns a reference:
class Base {
    static int staticVarInst;
public:
    virtual int &staticVar() { return staticVarInst; }
}
class Derived: public Base {
    static int derivedStaticVarInst;
public:
    virtual int &staticVar() { return derivedStaticVarInst; }
}

You would then use this as:
staticVar() = 5;
cout << staticVar();

A: To ensure that each class has its own static variable, you should use the "Curiously recurring template pattern" (CRTP).
template <typename T>
class Base
{
    static int staticVar;
};

template <typename T> int Base<T>::staticVar(0);

class DerivedA : public Base<DerivedA> {};
class DerivedB : public Base<DerivedB> {};

A: They will share the same instance.
You'll need to declare separate static variables for each subclass, or you could consider a simple static map in which you could store variables that are referenced by derived classes.

Edit: A possible solution to this would be to define your base class as a template.  Having a static variable defined in this template would mean that each derived class will have it's own instance of the static.

A: There is only one staticVar in your case:  Base::staticVar
When you declare a static variable in a class, the variable is declared for that class alone.  In your case, DerivedA can't even see staticVar (since it's private, not protected or public), so it doesn't even know there is a staticVar variable in existence.

A: The sample code given by @einpoklum is not working as it is because of the missing initialization of the static member foo_, missing inheritance in FooHolder declaration, and missing public keywords since we are dealing with classes. Here is the fixed version of it.
#include <iostream>
#include <string>

class A {
public:
    virtual const int& Foo() const = 0;
};

template <typename T>
class FooHolder : public virtual A {
public:
    const int& Foo() const override { return foo_; }
    static int foo_;
};

class B : public virtual A, public FooHolder<B> { };
class C : public virtual A, public FooHolder<C> { };

template<>
int FooHolder<B>::foo_(0);
template<>
int FooHolder<C>::foo_(0);

int main()
{
  B b;
  C c;
  std::cout << b.Foo() << std::endl;
  std::cout << c.Foo() << std::endl;
}

A: I know that this question has already been answered but I would like to provide a small example of inheritance with static members. This is a very nice way to demonstrate the usefulness as well as what is happening with the static variables and the respective constructors.
FooBase.h
#ifndef FOO_BASE_H
#define FOO_BASE_H

#include <string>

class FooBase {
protected:
    std::string _nameAndId;
private:
    std::string _id;
    static int _baseCounter;

public:
    std::string idOfBase();
    virtual std::string idOf() const = 0;

protected:
    FooBase();
};

#endif // !FOO_BASE_H

FooBase.cpp
#include "FooBase.h"
#include <iostream>

int FooBase::_baseCounter = 0;

FooBase::FooBase() {
    _id = std::string( __FUNCTION__ ) + std::to_string( ++_baseCounter );
    std::cout << _id << std::endl;
}

std::string FooBase::idOfBase() {
    return _id;
}

std::string FooBase::idOf() const {
    return "";
} // empty

DerivedFoos.h
#ifndef DERIVED_FOOS_H
#define DERIVED_FOOS_H

#include "FooBase.h"

class DerivedA : public FooBase {
private:
    static int _derivedCounter;

public:
    DerivedA();

    std::string idOf() const override;
};

class DerivedB : public FooBase {
private:
    static int _derivedCounter;

public:
    DerivedB();

    std::string idOf() const override;
};

#endif // !DERIVED_FOOS_H

DerivedFoos.cpp
#include "DerivedFoos.h"
#include <iostream>

int DerivedA::_derivedCounter = 0;
int DerivedB::_derivedCounter = 0;

DerivedA::DerivedA() : FooBase() {
    _nameAndId = std::string( __FUNCTION__ ) + std::to_string( ++DerivedA::_derivedCounter );
    std::cout << _nameAndId << std::endl;
}

std::string DerivedA::idOf() const {
    return _nameAndId;
}

DerivedB::DerivedB() : FooBase() {
    _nameAndId = std::string( __FUNCTION__ ) + std::to_string( ++DerivedB::_derivedCounter );
    std::cout << _nameAndId << std::endl;
}

std::string DerivedB::idOf() const {
    return _nameAndId;
}

main.cpp
#include "DerivedFoos.h"

int main() {
    DerivedA a1;
    DerivedA a2;
    DerivedB b1;
    DerivedB b2;

    system( "PAUSE" );
    return 0;
}

If __FUNCTION__ is not working for you in your constructors then you can use something similar that can replace it such as __PRETTY_FUNCTION__ or __func__, or manually type out each class's name :(.

A: Alas, C++ has no virtual static data members. There are several ways to simulate this, more or less:

*

*@GregHewgill's solution has you replicate the static variable in each derived class; this solution is simple, straightforward and doesn't introduce additional classes, but I don't like this one since it's verbose, and you have to be rather disciplined with it.

*@MarkIngram suggested a CRTP-based solution, which saves you most of the typing; however, it messes up the inheritance structure, because what were previously subclasses of A are no longer really related as classes. After all, two templated types with the same name but different template arguments could be just any two types.

I suggest a different CRTP-based solution, using a mix-in class:
 class A {
      virtual const int& Foo() const = 0;
 }

 template <typename T>
 class FooHolder {
      static int foo_;
      const int& Foo() const override { return foo_; }
 }

 class B : A, virtual FooHolder<B> { }

 class C : B, virtual FooHolder<B> { }

The only thing you need to do in a subclass is also indicate the mix-in inheritance. There might be some virtual inheritance caveats I'm missing here (as I rarely use it).
Note that you either have to instantiate and initialize each subclass' static variable somewhere, or you can make it an inline variable (C++17) and initialize it within the template.
This answer was adapted from my answer to a dupe question.

redpajama_set_name: RedPajamaStackExchange


text:
Q: BSON Message To Map in JAVA We are currently sending messages to a Redis Queue, which is being picked up by our JAVA application.
Anyone have an idea how to convert the BSON message to a Map in JAVA?
Here is an example MSG in BSON we pop from the Redis queue:
\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00

A: You can use MongoDB Driver:
Parse your BSON data just like this:
    RawDBObject obj(your ByteBuffer buf );
    obj.toMap();

done.
https://github.com/mongodb/mongo-java-driver/blob/master/src/main/com/mongodb/RawDBObject.java
or BSON official site may help:
http://bsonspec.org/#/implementation

A: You can use a BSON parser to parse your BSON input.  Google gives me bson4jackson but I have never tried it myself.


text:
Q: Image from blob object not displayed in a page This is my HTML code for displaying image stored as blob object which is stored in a database.

photo	<img src="image.php?id=<?php echo $employee['id']; ?>" />

This is the image.php file:
<?php

include db.php;

$employee_id = (isset($_GET['id']) && is_numeric($_GET['id'])) ? intval($_GET['id']) : 0;

try
{
  $sql = "SELECT photo
          FROM employee where id = $employee_id limit 1";
  $s = $pdo->prepare($sql);
  $s->execute();
}
catch (PDOException $e)
{
  $error = 'Employee not found' . $e->getMessage();
  include 'error.html.php';
  exit();
}

$employee = $s->fetch();

$image = $employee['photo'];

header('Content-Type: image/jpeg');
echo $image;

?>

When I look at the HTML code in Firebug, I can see

But no image is displayed in the table row. Do you know how to find out what is wrong?
When I open the page ...image.php?id=9 in Firefox
It shows a message

The image ...image.php?id=9 cannot be
  displayed because it contains errors.

It is strange that every image I have contains an error. I inserted only images with
size smaller than the blob object.

A: do you get an error?
try to use "exit;" after the echo and remove the closing php tag.
it's optional and you don't really need it (http://php.net/manual/en/language.basic-syntax.instruction-separation.php).
header('Content-Type: image/jpeg');
echo $image;
exit;


text:
Q: Error while parsing UI hierarchy XML file: Invalid ui automator hierarchy file in ubuntu I am trying to capture the snapshot using ui automator view but when i try to take the snap shot i am getting the following error:
Error while parsing UI hierarchy XML file: Invalid ui automator hierarchy file.

Even i have tried to restart the device multiple times as well but still i am getting the same issue.

A: Instead of opening automator using "uiautomatorviewer" Paste this in your terminal. It will open the correct Autmator
Android/Sdk/tools/bin/uiautomatorviewer


text:
Q: click submit button automatically if a condition is satisfied I am making an online examination system in PHP.this is a part of my huge examination code..every thing is working well.When the time is up, the page is redirecting to result page by
window.location = "http://localhost/result.php";//which is in comment line

but here the value of answers are not posting. But when i click the submit button it works.
So i make a function to submit the form automatically.but it is not working , dont know why.
Here "if" block is checking whether the time is up or not. if up then do the following.
Inside "if" I want either to click the "submit button"
 echo '<input type="submit" name="submit" id="submit" value="SUBMIT"/></FORM>';

or submit the the form, so that i can get the result in next page- "result.php".
<FORM name ='form1' id='form1' method ='post' action='result.php' >

Thanks in advance. Hope you understand my problem.
function myfunc () {
    var frm = document.getElementById("form1");
    frm.submit();
}

document.getElementById("remain").innerHTML = hours+" hours : "+minutes+" minutes : "+seconds+" seconds";
SD=window.setTimeout( "setCountDown()", 1000 );
if (minutes == '00' && seconds == '00') { seconds = "00"; window.clearTimeout(SD);
    window.alert("Time is up. Press OK to continue.");
    window.onload = myfunc;
    //document.form1.submit();
    //window.location = "http://localhost/result.php"
}

A: Try this..
window.onload = function(){
    myfunc();
};

A: If you're trying to submit the form after window.alert("Time is up. Press OK to continue.") shows, you don't need a load event. You can just put your code immediately after the alert and it will run once the alert is closed (by clicking 'okay'):
alert("Time is up. Press OK to continue.");
myfunc();

Alternatively, you could use confirm instead of alert:
var timesUp = confirm("Time is up. Press OK to continue.");

if (timesUp) {
    myfunc();
}

With a confirm you'll get two buttons and could run a different event for ok (true) and cancel (false). One of these options should solve your problem though.

A: just use this
      document.form1.submit.click();


text:
Q: How to test Material UI 'error' color (red) with Jest/React Testing Library I have
<AppBar position='relative' color='error' data-testid='appbar'>
   ...
</AppBar>

and want to test
test('Appbar background color must be red', () => {
    render(<App />)
    const element = screen.getByTestId('appbar')
    expect(element).toHaveStyle(???)

})

The ??? part is where I am not sure what to put

A: use toHaveClass instead of toHaveStyle and add the apprpriate class in terms of material UI.
test('Appbar background color must be red', () => {
    render(<App />);

    const element = screen.getByTestId('appbar')
    expect(element).toHaveClass("MuiAppBar-colorError");
});

Live Preview live preview demo


text:
Q: 2D line renderer reflection issue - Unity I make a 2d line renderer reflection on a specific object tag, it's working but only on the left side when on the right side the reflection is not showing, I don't have any idea why because when my script is on 3d it's working fine.
this is a script that I convert from 3D and I change it all to 2D.
    public int reflections;
    public float maxLength;

    private LineRenderer lineRenderer;
    public LayerMask layerMask;
    private Ray2D ray;
    private RaycastHit2D hit;

    private void Awake()
    {
        lineRenderer = GetComponent<LineRenderer>();
    }

    private void Update()
    {
        ray = new Ray2D(transform.position, transform.up);

        lineRenderer.positionCount = 1;
        lineRenderer.SetPosition(0, transform.position);
        float remainingLength = maxLength;

        for (int i = 0; i < reflections; i++)
        {
            hit = Physics2D.Raycast(ray.origin, ray.direction, remainingLength, layerMask);

            if (hit)
            {
                lineRenderer.positionCount += 1;
                lineRenderer.SetPosition(lineRenderer.positionCount - 1, hit.point);
                remainingLength -= Vector2.Distance(ray.origin, hit.point);
                ray = new Ray2D(hit.point, Vector2.Reflect(ray.direction, hit.normal));
                if (hit.collider.tag != "Reflect")
                    break;
            }
            else
            {
                lineRenderer.positionCount += 1;
                lineRenderer.SetPosition(lineRenderer.positionCount - 1, ray.origin + ray.direction * remainingLength);
            }
        }
    }

PREVIEW

When going to the right.

When going to left.
Sometimes it flickers too, I don't have any idea how this happens, I thought it was because order layer I have changed this but nothing happen.

A: In regard to the flickering, this is occuring due to a clipping issue with the collided object and the line itself.
Inside of the condition:
if (hit)

Adjust the code to be the following:
// Get the reflected vector of the raycast.
Vector2 updatedDirection = Vector2.Reflect(ray.direction, hit.normal);

// Create new Ray object & set origin to be 0.01f away from hitpoint so the line is not colliding with the gameobject collider.
ray = new Ray2D(hit.point + updatedDirection * 0.01f, updatedDirection);

You can find out more from these links:
https://answers.unity.com/questions/1602542/line-renderer-flickering-when-updated-in-runtime.html
https://answers.unity.com/questions/1690411/help-with-reflecting-in-2d.html?childToView=1690554#comment-1690554
As for the reason the line is not reflecting on the right wall, this is more than likely due to the gameObjects tag not being set to "Reflect". You are only creating a new reflected line when colliding with an object with that tag. Double check that the right walls gameObject has the tag "Reflect" set in the inspector.


text:
Q: Column Qualifier/Mutiple Data in same columns With SQL, is it possible to have one table that, in a column, there is information that identifies what column information comes after? For example:
Column1,  Column2, Column3
CustName, ID1,     Date
CustName, ID1,     Date
CustName, ID2,     PaymentType
CustName, ID2,     PaymentType
CustName, ID3,     Address

Could this be done with just string information?

A: You should explain a bit further. What do you mean is it possible? You can of course create a table with this structure
CREATE TABLE customer_data
(
  customer_name varchar(255),
  customer_id varchar(255),
  data_field varchar(255),
  data_value varchar(255)
);

What is the purpose? Obviously if you have differing data_types for data_value you would have to convert them in a query or in code but to answer is it possible? Then yes.


text:
Q: git ignoring .gitattributes pattern I've a directory structure like this:
root/
  .git
  deploy/
  Site/
    blah/
    more_blah/
      something.local
      else.development
    Rakefile
    .gitattributes

Edit: to further clarify the above, directories have a trailing / and children are indented beneath a directory, so blah and more_blah are directories but Rakefile and .gitattributes are files, but all four are children of Site.

I'm running git-archive from the Site directory like so:
git archive --format=tar --prefix=git-v0.0.1/ v0.0.1 | gzip > ../deploy/git-v0.0.1.tar.zip

but whatever pattern I put in .gitattributes, the resulting archive always contains Rakefile. I've tried:

*

*Rakefile

*Site/Rakefile

**/Rakefile

*./Rakefile

*Rakefile*

**

None of them work as I'd expect. Is anyone willing to point out the obvious yet non-obvious to me solution? Any help is much appreciated.

My apologies for not being clear.

*

*I said the pattern I was using didn't seem to work, but I am using "export-ignore" after the pattern.

*Rakefile is not a directory, just a file

*The .gitattributes file is successful in removing other patterns from the archive, Rakefile is not the only pattern used, but is the only one that doesn't work. It doesn't work whether I have it on its own or with other patterns, and at any place in the file. This is not true, due to having renamed certain files but not archiving the commit with the rename I was appearing to get some good results. My bad! :S

This is my .gitattributes (sitting in the directory Site)
Rakefile        export-ignore
*.local         export-ignore
*.development   export-ignore
*.staging       export-ignore

A: Not sure this is common case but I had trouble excluding folder tests from source tree which have many nested levels of folders. If I wrote only this line to .gitattributes
tests/* export-ignore

It didnt work and entire directory was remain in archive. The solution was to add wildcards for all subdirs levels:
tests/* export-ignore
tests/*/* export-ignore
tests/*/*/* export-ignore
tests/*/*/*/* export-ignore
tests/*/*/*/*/* export-ignore

With these lines the tests directory finally disappeared from archive.

A: I believe @Jefromi gave the information needed for me to resolve this with his comments, but is too humble to take the credit, and I'd like to keep my acceptance rating at 100% (quite rightly) so I'll give the answer here:

First edit:
Ok, two things were needed. --worktree-attributes on its own did not work, but when I moved the .gitattributes file into the root dir from the Site dir, then it worked. Again, the Git book implies that the file doesn't need to be in the root for it to work (note: dead link)

... (normally the root of your project)

Much later edit:
Even the latest version of the docs (2.35.1) there are references to .gitattributes files that aren't in the root of the repo (GIT_WORK_TREE / GIT_DIR) e.g.

not in .gitattributes files in working tree subdirectories

Git does not follow symbolic links when accessing a .gitattributes file in the working tree.

I feel a bit let down by those docs (for once). I also think it's not-what-you'd-think behaviour to have to opt in the file when .gitignore just works, IMO.

A: Note: to ignore a directory, you needs to have a '/' at the end of said directory.
Rakefile/

For archive, like Arrowmaster mentions in his answer, and like the Pro Git book details, you need the export-ignore option:
Rakefile/ export-ignore

A: If you want git to ignore a file put it in the .gitignore file not the .attributes file.
If you want to ignore your Rakefile put the following in the .gitignore file at the root of your project.
/**/Rakefile

Specify the full path if you have more than one and you only want to ignore one of them.
A few examples of how to implement pattern matching for these files:

For All Files in All Folders

/**/*.ext

For A File in All Folders

/**/some_file.ext

File in Root Folder

/some_file.ext

File in A Folder

/some_folder/some_file.ext

All Files in A Folder

/some_folder/*

A: With git version 1.7.2.5, which is the default on debian squeeze (hence this post), there must not be a slash at the end to ignore a directory. So in order to ignore the deploy dir in the above question the following line must be used (no slash):
deploy        export-ignore

This is in contradiction to the documentation (man gitattributes / man gitignore) and the git book. The documentation of gitattributes references gitignore. Interestingly dirs with a slash (deploy/) work in a .gitignore file.
I did not test later versions of git.

A: For directories I had problems with different versions of git, so I had to include an entry both with and without a training slash:

*

*foo/bar export-ignore

*foo/bar/ export-ignore

Where foo/bar is relative to the where I ran git archive, but the actual .gitattributes was in the project root directory in addition to --worktree-attributes as noted above.

A: Are you trying to have the files included in the repository but not in the archive created from git archive? If so the syntax of your .gitattributes files wrong. If not then .gitattributes is not what you should be using.
To have files excluded from the archive produced by git archive you should put the following into the .gitattrubutes.
Rakefile export-ignore


text:
Q: How to align this div contents properly? Here is my layout,
Summary view http://img689.imageshack.us/img689/2500/yuidtsum.jpg
I am using one div and many spans for getting the above view... Look at all the rows ther are not properly aligned...

' + employee.Emp_Name + '
Category :
' + employee.Desig_Name + '

Salary Basis : ' + employee.SalaryBasis + '
Salary : ' + employee.FixedSalary + '
Address :
' + employee.Address + '

and my css are
.resultsdiv
{
    background-color: #FFF;border-top:solid 1px #ddd; height:50px; border-bottom:solid 1px #ddd; padding-bottom:15px; width:450px;
}
.resultseven { background-color: #EFF1f1; }
.resultshover { background-color: #F4F2F2; cursor:pointer; }

.resultName
{
    font-size:125%;font-weight:bolder;color:#476275;font-family:Arial,Liberation Sans,DejaVu Sans,sans-serif;
}
.resultfields
{
    font-size:110%;font-weight:bolder;font-family:Arial,Liberation Sans,DejaVu Sans,sans-serif;
}
.resultfieldvalues
{
    color:#476275;font-size:110%;font-weight:bold;font-family:Arial,Liberation Sans,DejaVu Sans,sans-serif;
}

Any suggestion to get it aligned properly.... Should i use divs insted of spans to get this
properly aligned...

A: In my opinion, that is the type of data that should be in a table. It's not layout, it's tabular, repeating data.

A: Here is a rough cut of some rewritten HTML and CSS.  I have not tested this, but it should get you close.  Post a screenshot if it doesn't work.
HTML

' + employee.Emp_Name + '

Category : ' + employee.Desig_Name + '

Salary Basis : ' + employee.SalaryBasis + '

Salary : ' + employee.FixedSalary + '

Address : ' + employee.Address + '

CSS
.resultsdiv { color: black }
.resultsdiv span { color: #666 }
.resultsdiv { width: 600px}
.resultsdiv div { float: left }
.resultsdiv .name { width: 230px; padding-right 20px; }
.resultsdiv .category { width: 350px }
.resultsdiv .salary_basis { clear: left; width: 180px; padding-right: 20px }
.resultsdiv .salary { width: 180px; padding-right: 20px }
.resultsdiv .address { width: 200px; }


text:
Q: Get newly added value in Array Powershell for (;;) {

  #Get All Files from the Folder

  $FolderItems = @(Get-PnPFolderItem -FolderSiteRelativeUrl $FolderURL -ItemType File)

  Write-Host "Total Number of Files in the Folder:" $FolderItems.Count
  if ($FolderItems.Count -gt $oldCount) {
    foreach ($item in $FolderItems) {
      if ($oldFolderItems -contains $item) {
      }
      else {
        Write-Host $item.Name
      }

    }
  }
  $oldCount = $FolderItems.Count
  $oldFolderItems = $FolderItems

  timeout 180

}

It prints all the names instead of the one new item

A: tl;dr
Replace your foreach loop with the following call to Compare-Object:
# Compare the new and the old collection items by their .Name property
# and output the name of those that are unique to the new collection.
Compare-Object -Property Name $FolderItems $oldFolderItems |
  Where-Object SideIndicator -eq '<=' |
    ForEach-Object Name

You should also initialize $oldFolderItems  to $null and $oldCount to 0, to be safe, and - unless you want all names to be output in the first iteration - change the enclosing if statement to:
if ($oldFolderItems -and $FolderItems.Count -gt $oldCount) { # ...
Note: The immediate - but inefficient - fix to your attempt would have been the following, for the reasons explained in the next section:
if ($oldFolderItems.Name -contains $item.Name) { # Compare by .Name values

Note: $oldFolderItems.Name actually returns the array of .Name property values of the elements in collection $oldFolderItems, which is a convenient feature named member-access enumeration.

As for what you tried:
It's unclear what .NET type Get-PnPFolderItem returns instances of, but it's fair to assume that the type is a .NET reference type (as opposed to a value type).
Unless a reference type is explicitly designed to compare its instances based on identifying properties,[1] reference equality is tested for in equality test-based operations such as -contains (but also in other equality-comparison operations, such as with -in and -eq), i.e. only two references to the very same instance are considered equal.
Therefore, using -contains in your case won't work, because the elements of the collections - even if they conceptually represent the same objects - are distinct instances that compare as unequal.
A simplified example, using System.IO.DirectoryInfo instances, as output by Get-Item:
# !! Returns $false, because the two [System.IO.DirectoryInfo]
# !! instances are distinct objects.
@(Get-Item /) -contains (Get-Item /)

Therefore, instances of .NET reference types must be compared by the value of an identifying property (if available, such as .Name in this case) rather than as a whole.
To discover whether a given instance is one of a .NET reference type, access the type's .IsValueType property: a return value of $false indicates a reference type; e.g.:
(Get-Item /).GetType().IsValueType # -> $false -> reference type

# Equivalent, with a type literal
[System.IO.DirectoryInfo].IsValueType # -> $false

[1] A notable example is the [string] type, which, as an exception, generally behaves like a value type, so that the following is still $true, despite technically distinct instances being involved: $s1 = 'foo'; $s2 = 'f' + 'oo'; $s1 -eq $s2


text:
Q: How to use property placeholder inside a Camel Processor I'm writing some routes with camel, and I want to make some transformations using a Processor. I have a properties file and it is working ok.
    from(URI_LOG)
    .routeId("{{PREFIX_LOG}}.prepareForMQ")
    .log("Mail to: {{MAIL}}") //The value is read from a property file
    .process(new ProcessorPrepareMail())
    .log("${body}");

Now... I want to read the value of {{MAIL}} inside the processor but I don't know how.
I tried these things:
public class ProcessorPrepareMail implements Processor
{

    @Override
    public void process(Exchange exchange) throws Exception
    {
        //Plan A: Does not work.... I get an empty String
        String mail = exchange.getProperty("MAIL", String.class);

        //Plan B: Does not work.... I get the String "{{MAIL}}"
        Language simple = exchange.getContext().resolveLanguage("simple");
        Expression expresion = simple.createExpression("{{MAIL}}");
        String valor = expresion.evaluate(exchange, String.class);

        //Plan C: Does not work. It activates the default error handler
        Language simple = exchange.getContext().resolveLanguage("simple");
        Expression expresion = simple.createExpression("${MAIL}");
        String valor = expresion.evaluate(exchange, String.class);
    }
}

Can you help me?
Thanks

A: There is API on CamelContext to do that:
String mail = exchange.getContext().resolvePropertyPlaceholders("{{MAIL}}");


text:
Q: Can I use Django to prevent direct access to an image file? I'd like to prevent my web users from simply right clicking an image and copying/sharing the URL.  Certain authenticated users have access to certain images, and I'd like to enforce this as much as possible.  Non authenticated users should have no access to image files.
It's generally recommended to avoid storing/fetching images from a DB, due to performance issues, from what I have read.
I've considered having a function that reads the file (server side, in python) and inserts it into the webpage (base64 encoded, possibly, or some other way) in the Django view functions.  Combined with an .htaccess file that denies external requests, this would likely work, but it seems like it'd be resource intensive.
Is there any other options for enforcing this rule?  I realize users can screenshot, save images, etc, but it's my responsibility to enforce these restrictions as much as possible, what are my best options?
edit: I have no experience using a CDN, but would be willing to use this if it's a viable option that covers these needs.

A: I'll bite.
Session Middleware - not elegant, but it will work
You'll want the images you don't want served publicly to not be served through your standard apache/django static files config.
your session middleware can then check all incoming requests for the path and if the path is your image directory (such as /privateimg/) and the user is not authenticated you can bounce them back out or replace it inline with another image (such as one that has a watermark).
You can check out the django docs on how session middleware works https://docs.djangoproject.com/en/dev/topics/http/sessions/
People can still pass your links around, but only authenticated users can actually see the contents of said links (called gating your content)
To elaborate:
settings.py
GATED_CONTENT = (
    '/some_content_dir/', # This is a directory we want to gate
    '.pdf', # maybe we want to gate an entire content type
)

MIDDLEWARE_CLASSES = (
    ...  # Out of the box middleware...blah blah
    'yourapp.somemodule.sessionmiddleware.GatedContent',
)

Then you have the following app structure
yourapp
   |-somemodule
        |-sessionmiddleware.py

Now to the meat (yum!)
sessionmiddleware.py
class GatedContent(object):
"""
Prevents specific content directories and types
from being exposed to non-authenticated users
"""

def process_request(self, request):
   path = request.path
   user = request.user # out of the box auth, YMMV

   is_gated = False
   for gated in settings.GATED_CONTENT:
      if path.startswith(gated) or path.endswith(gated):
          is_gated = True
          break
  # Validate the user is an authenticated/valid user
  if is_gated and not user.is_authenticated():
      # Handle redirect

A: You might be interested in XSendfile.
This is most [elegant and] performance choice IMO: actual files will be served by you webserver, while access control to this files will be done using your Django app.
You may google for "django xsendfile", there are lot of useful posts.


text:
Q: Monitoring file change sequenes with Inotifywait Currently I am monitoring the files by using above code, it works as expected. Basically I am monitoring the opened text files and executing commands.
inotifywait -m -q /home/TestDirectory |
    while read path action file; do

             if [[ ("$action" == "MOVED_TO") ]]; then
                  #Do something

            fi
    done

I wonder, how can I monitor the sequences of the inotifywait events and execute command.
For example, how can I execute a command or echo something when there is a open,access,close_nowrite event in the directory?
/home/TestDir OPEN test.txt
/home/TestDir ACCESS test.txt
/home/TestDIr CLOSE_NOWRITE,CLOSE test.txt


text:
Q: Pass variable with jquery, open php page and pick it up I have two pages. On page one, called test1.html, I try to retreive the users timezone. I would like to send it of to a php page called test2.php and load that page instead of test1 with the variable (timezone). This is the code.
Test1.html:
<script type="text/javascript">

$(document).ready(function() {
    var tz = jstz.determine(); // Determines the time zone of the browser client
    var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.

$.ajax({
        type: 'POST',
        url: 'test2.php',
        data: {'timezone': timezone},
        cache: false,
        success: function(){
                setTimeout(function () {
                        window.location = 'test2.php';
                }, 3000);//this will redirct to somefile.php after 3 seconds
        }
    });
});
</script>

Test2.php
<?php

if(isset($_POST['timezone']))
{

        $tz = $_POST['timezone'];
        echo "Timezone is " .$tz;
}
else {
        echo "Fail!";
}

?>

On pageload of test2.php, I only ever get the 'Fail!' message. The jquery and php part do work correct as I tested it with an alert call in test1.html to log the reponse from the php page. It gave the response I expected.
I think I lose my variable when the code is executed to reload test2.php in the same window. I just don't know how to bypass this problem. I want to use POST rather then GET if possible.
Any help greatly appreciated.
Little note: Idealy I want to use this javascript and the php to be on the same page but the 'problem' there is that php is of course executed serverside first and then it runs je js client side afterwards...

A: An alternative solution that still allows you to use POST, which you said you'd like, is to store the information in a session variable. The session is an object that can be used to store values between requests. See http://php.net/manual/en/book.session.php
Test1.html:
<script type="text/javascript">

$(document).ready(function() {
    var tz = jstz.determine(); // Determines the time zone of the browser client
    var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.

$.ajax({
        type: 'POST',
        url: 'test2.php',
        data: {'timezone': timezone},
        cache: false,
        success: function(){
                setTimeout(function () {
                        window.location = 'test3.php';
                }, 3000);            }
    });
});
</script>

Test2.php
<?php
// Start your session (if not already started)
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Store posted timezone in the session, which will be available in future calls
if(isset($_POST['timezone'])) {
    $_SESSION['timezone'] = $_POST['timezone'];
}
else {
    echo "Fail!";
}

?>

Test3.php
<?php
// Start your session (if not already started)
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
if(isset($_SESSION['timezone']) {
    echo "Your timezone is " . $_SESSION['timezone'];
} else {
    echo "Fail!";
}

A: You are misunderstanding the flow of how your client and server are interacting with each other. Your code sends a POST request to test2.php, and THEN (in the success callback that triggers when your request is done) it redirects to test2.php. The first time test2.php is run, it gets the timezone POST variable, but the second time it doesn't. You can see this by looking at network traffic in your browser's developer tools - you'll see two requests to test2.php. The first will return "Timezone is...", and the second (which your browser is showing) says "Fail!"
There are different ways to get what you want, but the easiest would be to skip the AJAX altogether and just send the timezone along with the redirect:
$(document).ready(function() {
    var tz = jstz.determine(); // Determines the time zone of the browser client
    var timezone = tz.name(); //'Asia/Kolhata' for Indian Time.

    // This redirects to test2.php while setting a GET parameter called "timezone"
    window.location = 'test2.php?timezone='+encodeURIComponent(timezone);
});

<?php

if(isset($_GET['timezone']))
{

        $tz = $_GET['timezone'];
        echo "Timezone is " .$tz;
}
else {
        echo "Fail!";
}

?>


text:
Q: Derivation of formula for $\pi$ There is a well known formula for approximating the value $\pi$, namely
$$\pi = 4 \times arctg 1 = 4 \int^1_0 (arctg x)' dx = 4 \int^1_0 \frac{1}{1+x^2}dx  \approx \frac{1}{N} \sum_{i=1}^N \frac{4}{1 + (\frac{i - 0.5}{N})^2}$$
Even though the formula can be encountered in many sources, I have never been able to understand the last step of the derivation. How do we arrive at $\frac{1}{N} \sum_{i=1}^N \frac{4}{1 + (\frac{i - 0.5}{N})^2}$ as an approximation for the integral? It's probably some well-known numerical method that I don't know about?
I think that the sum tries to emulate the calculation of the area as given by the function $f(x) = \frac{1}{1+x^2}$. We divide the integration range $[0; 1]$ into $N$ parts, and calculate the value of integral in those $N$ points. What I don't get is:

*

*Why do we substract $0.5$ from $i$? I've written two programs to check whether  the results are more accurate when the substition is in there  (i.e. when we calculate $\sum_{i=1}^N \frac{4}{1 + (\frac{i}{N})^2}$) - and indeed they are, but the disparity is not very big (for $N = 10000$ I get $\pi = 3.1413926444228837$ in the first case vs $\pi = 3.14129265192314$ in the second case).

*Why do we multiply whole sum by $1/N$?

A: In geometric and graphical terms, we are approximating the area enclosed by a witch of Agnesi and the $x$-axis over a certain interval, by decomposing such region into a union of rectangles with the same base length:

Can you see it now (pretty literally)?

A: This is the disappointingly–little-known midpoint rule for approximating integrals, namely
$$ \int_a^b f(x) \, dx  = h \sum_{n=0}^{(b-a)/h-1} f\left( a + \left(n+\frac{1}{2}\right)h \right) + R, $$
where the error $R$ is bounded by
$$ \lvert R \rvert \leq \frac{(b-a)}{24}h^2 \max_{[a,b]} \lvert f''(x) \rvert, $$
 (see e.g. here for a derivation). This is half that of the trapezium rule. In my opinion, one should teach it instead of the trapezium rule.


text:
Q: I am using recreate() to refresh but why does it double refresh? I am using recreate and refresh() to refresh page every minute but it double refreshes. First refresh is after 1minute, and the next refresh is after 2 sec first refresh.
i have tried changing the code inside refresh but didnt work.
private void loadalltrolley(){
    StringRequest stringRequest = new StringRequest(Request.Method.GET,   PRODUCT_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONArray products = new JSONArray(response);

                        for(int i =0;i<products.length();i++){
                            JSONObject productObject = products.getJSONObject(i);
                            String gate_no = productObject.getString("gate_no");
                            String dock_name = productObject.getString("dock_name");
                            String dock_desc = productObject.getString("dock_desc") ;
                            int flight_arrival = productObject.getInt("flight_arrival");
                            int trolley_count = productObject.getInt("trolley_count");

                            Product product = new Product(gate_no,dock_name,dock_desc,flight_arrival,trolley_count);
                            allterminalList.add(product);

                        }

                        allterminaladapter = new ProductAdapter(alert.this,allterminalList);
                        recyclerView.setAdapter(allterminaladapter);
                        int count = allterminaladapter.getItemCount();
                        int i =0;

                        if (count>0)
                        {
                            displayNotification();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(alert.this,error.getMessage(),Toast.LENGTH_SHORT).show();
        }
    });
    Volley.newRequestQueue(this).add(stringRequest);

    refresh(60000);

}

public void refresh(int milliseconds){
    final Handler handler = new Handler();
    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            recreate();
        }
    };
    handler.postDelayed(runnable,milliseconds);
}

I want it to refresh 1 time only and not double refresh. I want to refresh the application after 1minute only.


text:
Q: When is a payment successful in Stripe? I am creating a web app:
I need to update the database when payment is successful and the card is charged (not decline).
my code is here: I first create the customer. (btw, the variables are declared, everything is working)
$customer = \Stripe\Customer::create(array(
      'email' => $_POST['stripeEmail'],
      'source'  => $_POST['stripeToken'],
      'description' => $stripeEmail
      ));

then I create the subscription for the customer:
$subscription = \Stripe\Subscription::create(array(
      "customer" => $customer->id,
      "plan" => $planName
      ));

My question: do I need to create a webhook to detect if payment is successful? or is it successful upon form submitting successfully?

A: In normal circumstances, when you create a subscription, Stripe will immediately attempt to charge the customer (subscriptions with Stripe are paid upfront). If the payment attempt fails, the API will immediately return an error and no subscription will be created.
In this case, you don't need to use webhooks. Just use normal error handling and check if a \Stripe\Error\Card exception is raised when you call \Stripe\Subscription::create(...).
Note that if there is nothing to bill immediately, the subscription creation will always succeed. This can happen in various circumstances:

*

*if you provide a trial_end parameter when creating the subscription

*if the plan has a default trial period

*if you use a coupon or a negative invoice item that reduces the first invoice's total to $0

*if the customer's account_balance can cover the cost of the first invoice


text:
Q: Dynamic javascript loading and execution I'm trying to dynamically load a Javascript based on the return value of an API call. I dynamically insert the script tag but it does not get executed. Can someone help understand why? The relevant code snippet is pasted below
onError: function(code) {
      if(code == "false") {
        var headID = document.getElementsByTagName("head")[0];
        var scriptTag = document.createElement("script");
        scriptTag.type="text/javascript";
        scriptTag.src= 'scriptURL';
        headID.appendChild(scriptTag);
      }
}

Using firebug/chrome inspector, I can see that the script tag is added to the dom but the script is not executed (at least not that I can determine). It is a 3rd Party script hence I do not have direct control over it and hence cannot modify it either.

A: After reading the comments below the question it seems that the third party script is doing its job on window.onload event. Many programmers use this style.
window.onload = function() {
    // Whatever task
};

If the onload event of your page has already been fired before you add the script tag dynamically, the 'Whatever task' code would never execute.
Check the source of the third party script. If it uses window.onload, you can try calling window.onload(); after you add the script tag dynamically.


text:
Q: inputBox or addPanel after running a couple of scripts I realized that some of my scripts are not very practical. I have a script that asks four times with inputBoxes four different variables. I was thinking if it's possible to just have like a big panel with boxes where all these data can be input and then once it's done just click submit and on that way all information is stored on their variables.. Is it possible or anyone has a clue on how to do it??
  function dashboards(){
 var name = Browser.inputBox("Enter your name:");
 var nstats1 = Browser.inputBox("Enter your last name:");
 var namedash = Browser.inputBox("Enter your DOB");
 var log = Browser.inputBox("Enter your deparmtent");

A: There are many possible ways to do this, the easiest are certainly the UI service and the GUI builder.
I' suggest you have a look at this documentation... you'll find a lot of examples here and around.
Here is a rough example using the GUI Builder, you'll see its pretty simple to use and/or customise to your needs...


text:
Q: Segmentation fault returning OGR Layer object from function in Python I have a simple programme that processes points from a Geopackage layer. On a first attempt I encapsulated file access into a function:
from osgeo import ogr

pointsFile = "points.gpkg"

def getPoints():

    driver = ogr.GetDriverByName("GPKG")
    dataSource = driver.Open(pointsFile, 0)
    layer = dataSource.GetLayer(0)
    print("Returning layer")
    return layer

def main():

    layer = getPoints()
    print("Number of points to process: ", layer.GetFeatureCount())

if __name__ == '__main__': main()

Which fails with a segmentation fault when it returns the layer object:
$ python3 testReturn.py
Returning layer
Segmentation fault (core dumped)

However, with file access inside main:
from osgeo import ogr

pointsFile = "points.gpkg"

def main():

    driver = ogr.GetDriverByName("GPKG")
    dataSource = driver.Open(pointsFile, 0)
    layer = dataSource.GetLayer(0)
    print("Number of points to process: ", layer.GetFeatureCount())

if __name__ == '__main__': main()

the programme runs as expected:
$ python3 testDirect.py
Number of points to process:  21872

What could be causing this issue?

A: Tested the code with GDB and the segmentation fault  occurs when when calling:

layer.GetFeatureCount()

Some extra debugging information:

Starting program: /usr/bin/python3 testReturn.py
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Returning layer
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff5c42298 in OGR_L_GetFeatureCount () from /usr/local/lib/libgdal.so.20
(gdb)


text:
Q: how to make call the api during button active? In this i am having three sections in a table view in which first section will have addresses and radio buttons if i click on radio button it will active and the particular address will be posting depending on the address selection the third section needs to call the api and load the data in the second table view which is present in third section can anyone help me how to do this ?
here is the code for table view class
  func numberOfSections(in tableView: UITableView) -> Int
    {
         if ((addressSelected == true || checkIsPaymentRadioSelect == true) && selected == false) {
            return 3
        }else {
            return 2
        }
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
    {
        if ((addressSelected == true || checkIsPaymentRadioSelect == true) && selected == false) {
            if (section == 0) {
                return "SHIPPING ADDRESS"
            }
            else if (section == 2) {
                return "SHIPPING METHOD"
            }
            else  {
                return ""
            }
        }
        else {
                if (section == 0) {
                return "SHIPPING ADDRESS"
                }
                else{
                    return ""
                }
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if (section == 0)
        {
            return shippingArray.count
        }
        else
        {
            return 1
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        if ((addressSelected == true || checkIsPaymentRadioSelect == true) && selected == false){
            if (indexPath.section == 0){
                return UITableViewAutomaticDimension
            }
            else if (indexPath.section == 1){
                return 62
            }
            else {
                print(height)
                return CGFloat(height)
            }

        }
        else{
            if (indexPath.section == 0){
                return UITableViewAutomaticDimension
            }
            else if (indexPath.section == 1){
                return 62
            }
            else {
                return 0
            }

        }
    }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if (indexPath.section == 0)
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AddressTableViewCell
        tableDetails.isHidden = false
        activityIndicator.stopAnimating()
        let arr = shippingArray[indexPath.row]
        cell.deleteButton.tag = indexPath.row
        cell.nameLabel.text = arr["name"] as? String
        cell.addressLabel.text = arr["address"]as? String
        let mobilenumber : Any =  arr["number"] as AnyObject
        cell.mobileNumberLabel.text = "\(mobilenumber)"
        cell.radioButton.tag = indexPath.row
        cell.editButton.tag = indexPath.row
        cell.deleteButton.tag = indexPath.row
        cell.editButton.isHidden = true
        cell.deleteButton.isHidden = true
        cell.radioButton.addTarget(self, action: #selector(selectRadioButton(_:)), for: .touchUpInside)
        cell.deleteButton.addTarget(self, action: #selector(deleteAction(button:)), for: .touchUpInside)
        let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row)
        if(checkIndex != nil){
            cell.radioButton.isSelected = true
            cell.editButton.isHidden = false
            cell.deleteButton.isHidden = false
        }
        else
        {
            cell.radioButton.isSelected = false
            cell.editButton.isHidden = true
            cell.deleteButton.isHidden = true
        }
        if (checkIsPaymentRadioSelect == true){
        let defaultvalue  = arr["default"] as! Int
        if defaultvalue == 1 {
            cell.radioButton.isSelected = true
            cell.editButton.isHidden = false
            cell.deleteButton.isHidden = false
            addressSelected = true
            tableDetails.tableFooterView?.isHidden = false
        }
        }
        return cell
    }
    else if (indexPath.section == 1){
        let cell = tableView.dequeueReusableCell(withIdentifier: "addresscell", for: indexPath) as! CreateNewAddressTableViewCell
        cell.newAddressButton.addTarget(self, action: #selector(newAddressAction(_:)), for: .touchUpInside)
        return cell
    }
    else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "shippingmethodcell", for: indexPath) as! MethodTableViewCell
        cell.delegate = self
        cell.boolDelegate = self
        cell.shippingTableView.reloadData()
        if shippingRadio == true {
            cell.select = shippingRadio
            cell.boolSelected()
            cell.shippingmethodURL()
            cell.shippingTableView.reloadData()
        }
        else{
            cell.select = methodRadio
            cell.shippingTableView.reloadData()
        }
        return cell
    }
}

in this cell class i had got the api data and is passed to table view as shown in the code now i need to call api during cell selection of address can anyone help me how to implement this or any alternative for this
 var chekIndex:IndexPath?
    var arrayss =  [String:Any]()
    var keys = [String]()
    let urlString = "http://www.json-generator.com/api/json/get/bVgbyVQGmq?indent=2"
    var delegate: CheckoutDelegate?
    var heightConstant: Int?
    var name = [String]()
    var totalCount = 0
    var radioSelected:Bool?
    var radioSelection: Bool?
    var boolDelegate: BoolValidationDelegate?
    var select:Bool?

    override func awakeFromNib() {
        super.awakeFromNib()
        radioSelection = false
        self.shippingmethodURL()
        shippingTableView.delegate = self
        shippingTableView.dataSource = self
        shippingTableView.rowHeight = UITableViewAutomaticDimension
        shippingTableView.estimatedRowHeight = shippingTableView.rowHeight
        // Initialization code
    }
    func paymentRadioAction(button : KGRadioButton) {
        _ = button.center
        let centralPoint = button.superview?.convert(button.center, to:self.shippingTableView)
        let indexPath =  self.shippingTableView.indexPathForRow(at: centralPoint!)
        if button.isSelected {

        } else{
            chekIndex = indexPath
            radioSelection = true
            self.shippingTableView.reloadData()
            self.boolDelegate?.boolvalidation(bool: radioSelection!)
        }
    }
    func shippingmethodURL() {
        guard let url = URL(string: self.urlString) else {return}
        URLSession.shared.dataTask(with: url, completionHandler: {(data, response, error) -> Void in
            if let data = data, let jsonObj = (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)) as? [String:Any] {
                self.arrayss = jsonObj
                self.keys = Array(jsonObj.keys)
                for value in jsonObj.values {
                    if let array = value as? [[String:Any]] {
                        for element in array {
                            if (element["name"] as? String) != nil {
                                self.totalCount += 1
                            }
                        }
                    }
                }
                DispatchQueue.main.async {
                    self.shippingTableView.reloadData()
                    let sectionHeight = self.arrayss.count * 31
                    let cellHeight = self.totalCount * 44
                    self.shippingHeightConstraint.constant = CGFloat(sectionHeight + cellHeight)
                    self.heightConstant = Int(self.shippingHeightConstraint.constant)
                    self.delegate?.heightConstant(int: self.heightConstant!)
                }
            }
        }).resume()
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return arrayss.count
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.keys[section]
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let key = self.keys[section]
        let a :[Any]  = arrayss[key] as! [Any]
        return a.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "shippingCell", for: indexPath) as! ShippingMethodTableViewCell
        let key = self.keys[indexPath.section]
        var a :[Any]  = arrayss[key] as! [Any]
        var dictionary = a[indexPath.row] as! [String:Any]
        let name = dictionary["name"]
        let price = dictionary ["price"]
        cell.methodLabel.text = name  as? String
        cell.priceLabel.text = price as? String
        cell.radioButton.addTarget(self, action: #selector(paymentRadioAction(button:)), for: .touchUpInside)
        if chekIndex == indexPath {
            cell.radioButton.isSelected = true
        } else {
            cell.radioButton.isSelected = false
        }
    return cell
    }

and here is the image for the three sections
enter image description here enter image description here


text:
Q: I want to replace string with Stringbuilder but it breaks my code How would I replace the string variable with a StringBuilder and still verify that a new line was read?
while ((strLine = reader.ReadLine()) != null)

I tried this and it runs forever because the StringBuilder variable is never null.
while ((strBuilder.Append(tempReader.ReadLine())) != null)

A: You can read a file via "using" statement instead of using while.
This question illustrates your problem perfectly:
Using a string builder, i've read a file.. How do i find if the given string is present in the file or not?


text:
Q: D3.js v4+ : truncate text to fit in fixed space It is not uncommon to require text elements in the SVG we are manipulating via d3 e.g. categorical tick labels. This is somewhat unfortunate as the <text> element in SVG is not the best... The size of fonts rendered is often slightly larger than that of how much one thinks the font should take. For example, if choosing a mono-space font with a width / height ratio of 0.6 (e.g. if font size is 12px then the width of a character should be 7.2px), the element's computed bounding rectangle might be 14.2px by n*8px where n is the number of characters.
Further complicating the issue is the fact that more often than not, people use fonts which are not monospaced.
It is easy enough to truncate a string which is "too long" by
string.slice(0, numChars-3)+'...'

but knowing the correct number of characters to fit within a fixed width seems non trivial.
function truncateText(t, text, space) {
  // make sure it is a string
  text = String(text)
  // set text
  t.text(text)
  // get space it takes up
  var rect = t.node().getBoundingClientRect()

  while (Math.max(rect.width, rect.height) > space) {
    text = text.slice(0, text.length - 1)
    t.text(text + '...')
    rect = t.node().getBoundingClientRect()
    if (text.length == 0) break
  }
}

the above function takes a d3.selection, the text and the space in which the text should fit in. By constantly manipulating the DOM, we can get perfect fit, however this is computationally very expensive.
To clarify, to fit text in a fix space, I mean that if I have a string var string = "this is my very long string", I want the direction of the string being rendered (left to right, i.e. we are looking at string length) to fit within a fixed space (e.g. var fixedSpace = 100 //px)
The above truncate text function works well for just a few strings, but if there are many strings that call this function, it gets laggy.
Of course we could optimized by just picking the longest string, calculate truncateText on  that string, and take the number of characters as a result (although this is still somewhat buggy as not all characters have same width).
Is there a more efficient way to truncate text into a fixed space with d3

A: I agree that the approach you've suggested is computationally expensive, but it's about the only one I can think of. However if you're only running it occasionally (i.e. just on page load, rather than on mouseover), then it shouldn't be too bad, depending on how many text elements you're applying it to.
You might want to try comparing the performance of your approach to the one in this example by Mike Bostock, which uses node().getComputedTextLength() instead of node().getBoundingClientRect() and breaks up the text by word:
function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}

PS/ There's a CSS technique for truncating text with an ellipsis, but unfortunately it doesn't work in SVG :(

A: Another option would be to use a 100px wide rect as the clipPath for your text element -- something like so:

d3.selectAll("text.label")
  .attr("x", function(t) {
    return Math.max(0, 100-this.textLength.baseVal.value);
  });
#text-box {
  stroke: green;
  fill: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg>
  <defs>
    <rect id="text-box" x="0" y="0" width="100" height="1.2em" />
    <clipPath id="clip-box">
      <use href="#text-box" />
    </clipPath>
  </defs>

  <g transform="translate(0, 0)">
    <use x="0" y="0" href="#text-box" />
    <text x="0" y="1em" class="label" clip-path="url(#clip-box)">Long text that should be clipped</text>
  </g>

  <g transform="translate(0, 50)">
    <use x="0" y="0" href="#text-box" />
    <text x="0" y="1em" class="label" clip-path="url(#clip-box)">Another long string</text>
  </g>

  <g transform="translate(0, 100)">
    <use x="0" y="0" href="#text-box" />
    <text x="0" y="1em" class="label" clip-path="url(#clip-box)">Short text</text>
  </g>
</svg>

Update: After the labels are rendered, use this function to get their lengths, and adjust the "x" attribute if the text is shorter than the clipping width:
d3.selectAll("text.label")
  .attr("x", function(t) {
    return Math.max(0, 100-this.textLength.baseVal.value);
  });


text:
Q: Haskell list of list of chars adding to tuple example original (41.12, [1,2,3,0])
name = ["pete","ben","bill","bob"]

example output   (41.12, [1,2,3,0], ["ben","bill","bob","pete"])
code so far:
getnames :: (Double, [Int]) -> (Double, [Int] -> [[Char]])
getnames ( nil , []) = error "List is empty"
getnames xs = [(doublevalue , listofints, listofstrings))  | x <- xs]

How do i use the int list to get a value from the name list and put it in the tuple (i know when i add this to the tulle it isn't a tuple anymore)
What method would i use to do this?

A: The operator (!!) can be used to index a list. Given a pair, you can use something along the lines of:
getnames :: (Double, [Int]) -> [String] -> (Double, [Int], [String])
getnames (dbl, ixes) names =
    let namesLst = map (names !!) ixes in
    (dbl, ixes, namesLst)

Live demo
To get what you want, I've fixed your signature to be able to pass the names and fixed the return value type (which was returning a triple with a function at the end). Also notice that [Char] and String are exactly the same type.
So inside the body of the function you have dbl which is your double and is directly forwarded to the final triple. Then you have ixes which are the indexes of the elements you have to take from ixes.
At this point we calculate the namesLst by mapping the index function over the indexes to get the names in the correct order. Once we have this list, we just have to put it in the third element of the triple.
If you want it to fail on empty index list (even if the names list is empty) then you can add:
getnames (_, []) _ = error "..."

where _ means "I don't care enough to name this argument". And can be seen as a placeholder for an argument you'll not use.


text:
Q: How to stop nginx pass through from resolving upstream to IP I am new to nginx reverse proxy configuration. We have a requirement to setup a proxy server to route requests to a remote server that requires IP whitelisting. Two way SSL is also in place.
We have been trying to it up hit a roadblock. Following is the configuration :
server {
   listen 80;
   server_name myserver.com;
   return 302 https://myserver.com;
}

server {
   listen 443;
   server_name myserver.com;

   ssl on;
   ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
   ssl_prefer_server_ciphers on;
   ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
   ssl_certificate           /etc/nginx/keys/my-net.crt;
   ssl_certificate_key       /etc/nginx/keys/my-net.key;
   access_log /var/log/nginx/access.log;
   error_log /var/log/nginx/error.log;

   location / {
        resolver 8.8.8.8;
        set $backend "https://remoteserver.com";
        proxy_pass $backend;

        proxy_ssl_server_name on;
        proxy_ssl_trusted_certificate /home/ubuntu/myfile.pem;
        proxy_ssl_session_reuse off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwared-For $proxy_add_x_forwarded_for;
   }
}

The problem we are facing is that the proxy server is resolving the domain name to IP because of which SSLhandshake is failing. We need to stop this and hit the domain name because the certificate is on the domain name.
Error from error.log
2022/03/02 14:10:02 [error] 27012#27012: *8 SSL_do_handshake() failed (SSL: error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:SSL alert number 40) while SSL handshaking to upstream, client: <>, server: <>, request: "POST <> HTTP/1.1", upstream: "https:<>", host: "<>"
2022/03/02 14:10:02 [alert] 27012#27012: *8 socket() failed (97: Address family not supported by protocol) while connecting to upstream, client: <>, server: <>, request: "POST /gateway/api/txb/v1/payments/transfer-payment HTTP/1.1", upstream: "https://[IPv6]:443/", host: "<>"
Already tried the solution here but no luck - How to stop nginx from resolving upstream to ip?

A: You need to off  proxy_pass_request_headers after that set headers with proxy_set_heder  and listen ssl listen 443 ssl;
server {
   listen 80;
   server_name myserver.com;
   return 302 https://myserver.com;
}

server {
   listen 443 ssl;
   server_name myserver.com;

   ssl on;
   ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
   ssl_prefer_server_ciphers on;
   ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
   ssl_certificate           /etc/nginx/keys/my-net.crt;
   ssl_certificate_key       /etc/nginx/keys/my-net.key;
   access_log /var/log/nginx/access.log;
   error_log /var/log/nginx/error.log;

   location / {
        resolver 8.8.8.8;
        set $backend "https://remoteserver.com";
        proxy_pass $backend;

        proxy_ssl_server_name on;
        proxy_ssl_trusted_certificate /home/ubuntu/myfile.pem;
        proxy_ssl_session_reuse off;
        proxy_pass_request_headers off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwared-For $proxy_add_x_forwarded_for;
   }
}


text:
Q: Is there a way to implement similar Raise Property Changed for VS2015? Seems I have syntax errors in VS2015 for the code below.
The error sounds like:

A value of type '?' cannot be used as a default parameter because
there are no standard conversions to type 'T'

Is there a way to implement similar "Raise property changed" in VS2015?
 public class ViewModel : ViewModelBase
    {

        // Property
        public const string SelectedItemPropertyName = "SelectedItem";

        private int? _selectedItem;
        public int? SelectedItem
        {
            get
            {
                return _selectedItem;
            }
            set
            {
                Set(SelectedItemPropertyName, ref _selectedItem, value);
            }
        }

        // Method
        private void Load()
        {
            int number = SelectedItem ?? -1;

            // do your work
        }

       // Raise property changed
        public override void RaisePropertyChanged<T>([CallerMemberName] string propertyName = null, T oldValue = default, T newValue = default, bool broadcast = false)
        {
            base.RaisePropertyChanged(propertyName, oldValue, newValue, broadcast);
            if (propertyName == nameof(SelectedItem))
                Load();
        }
    }

A: It looks like you are using a C# version under 7.1. In that case, you will need to use default(T), rather than simply default. Here is a link to the docs on default value expressions.


text:
Q: Flutter check internet Connection using InternetAddress.lookup not working i have a class that is checking for network connection using connectivity Package and then if there is a network connection it is checking if the internet is available using InternetAddress.lookup
the problem is that the connectivity Package is working ! and it is detected for Wi-Fi and mobile connection but the InternetAddress.lookup always returning true ! even of there is no internet !
Full Class Code :
import 'dart:io';
import 'dart:async';

import 'package:connectivity/connectivity.dart';

class ConnectionStatusSingleton {
  static Future<bool> checkConnection() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      try {
        final result = await InternetAddress.lookup('example.com');
        var res = result.isNotEmpty && result[0].rawAddress.isNotEmpty;
        return res;
      } on SocketException catch (_) {
        return false;
      }
    } else if (connectivityResult == ConnectivityResult.wifi) {
      try {
        final result = await InternetAddress.lookup('example.com');
        var res = result.isNotEmpty && result[0].rawAddress.isNotEmpty;
        return res;
      } on SocketException catch (_) {
        return false;
      }
    } else {
      return false;
    }
  }
}

im calling it using :
 bool connectionState = await ConnectionStatusSingleton.checkConnection();

A: Here is the code I use
Future<bool> isInternetConnected() async {
    try {
      final result = await InternetAddress.lookup('example.com');
      var res = result.isNotEmpty && result[0].rawAddress.isNotEmpty;
      setState(() {
        isInternet = res;
      });

      return res;
    } on SocketException catch (_) {

      setState(() {
        isInternet = false;
      });

      return false;
    }
  }

You don't seem to be doing anything specific based on wifi and cellular data so you can use this. Your problem seems to be the way you're handling the exception.
General understanding of the code is "Try to connect to something on the internet, if the device has internet, it'll connect else it'll throw exception"
In the above code I don't recommend using setState(). I've used it to satisfy an exact demand. You can tailor it accordingly.


text:
Q: Outstanding part-way balance for loan compounded quarterly A loan of $R65000$ with an interest of $16\%$ per annum, compounded quarterly, is to be amortized by equal quarterly payments over $3$ years.
Question: What is the outstanding amount on the loan at the start of the third quarter?
My attempt:
$$
S=P(1+i)^n\\
65000\left(1+\frac{0.16}{4}\right)^{36}
$$

A: A little background. When dealing with these kinds of income streams, it is important to know if the payments begin immediately or after the first interval. With loans, what usually happens is that the principal is borrowed and the first payment is due at the start of the next period. This is called an annuity immediate.
The first thing to note that if the loan is compounded quarterly, we treat it as a simple annual cash flow at the period of the compounding. So a $16\%$ per annum compounded quarterly is treated as a simple $4\%$ per quarter loan.
Secondly, the question asks for the outstanding amount of the loan, not what the value would be without payments, so the first thing we need to do is to calculate the payment.
It always pays to draw a timeline for these questions, but I'm not sure how to do that here, so forgive its lack. What are the cashflows in this problem? We have an initial loan principle $P = R65,000$ and a quarterly interest rate $i = 4\% = 0.04$. We need to calculate $p$, the payment. What happens? We borrow $P$ at $t_0$. At $t_1$, the end of the first or beginning of the second quarter, the loan gets increased by the interest, and then the payment is removed. Mathematically, this is:
$$
P(1.04) - p
$$
Next quarter, $t_2$, the remaining balance gets the interest charge and the payment is then subtracted. This is:
$$
\left(P(1.04) - p\right)(1.04) - p\\
=P(1.04)^2 - p(1.04) - p
$$
At $t_3$, the end of the third/start of the fourth quarter, we have:
$$
\left(\left(P(1.04) - p\right)(1.04) - p\right)(1.04)-p\\
=P(1.04)^3 - p(1.04)^2 - p(1.04) - p
$$
The pattern continues. In general, for the cash flows to balance we need:
$$
P(1+i)^n = p\sum_{k=0}^{n-1}(1+i)\\
P(1+i)^n = p\frac{1-(1+i)^n}{1-(1+i)}\\
p = \frac{-i\cdot P(1+i)^n}{1-(1+i)^n}
$$
Solving this equation in your case gives us $p \approx R5,578.30$.
Now the question asked what will the outstanding balance be at the beginning of the third quarter. As we are working under the assumption that all cashflows happen at the end of the quarter, this is the balance at the end of the second quarter. We can see from the above that the value of the outstanding balance at $t_k$ would be:
the value of the loan at $t_k$ would be:
$$
P(1+i)^k - p\sum_{t=0}^{k-1}(1+i)\\
$$
Plugging the values we have into the general formula where $k=2$ we get a balance of $R58,924.27$.


text:
Q: How to dynamically set the width and height in the wordpress add_image_size function Similar question was asked here, however this solution works only partially for me.
What I want to achieve is that when an admin uploads an image, four custom image sizes get registered with add_image_size function.
left-top, left-bottom, right-top, right-bottom. They must be perfect quarters.
Now the add_image_size function can take width and height, and it also takes array for crop position e.g.
add_image_size( 'custom-size', 220, 220, array( 'left', 'top' ) ); // Hard crop left top
but since uploaded images can vary in size and aspect ratio, I would need a way to set the width and height dynamically, or some way to use relative measurements.
I realise that images would end up in different sizes for the same custom "image-size", but I can handle it in my view with wp_get_attachment_image_src by setting a new size or with css.
I would very much appreciate your help on this.


text:
Q: How to fix owner draw anomaly in DBGrid? Continuing with the project started in:
How to auto fit/scale DBGrid's (or other similar) columns widths according to its contents?
I used the @alzaimar answer to auto fit the columns according to their content width, but he showed me how to increase the width, but not how to decrease, so I complemented the code as shown above:
procedure TRecordsBrowserFrameBase.JvDBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
  h, p, g, r, w, t : Integer;
const
  colSpc = 10;
begin
{ ajusta as colunas de uma grade de acordo com o conteúdo das células }
  h := Column.DropDownRows;
  p := (Sender as TJvDBGrid).CurrentDrawRow;
  g := Column.Width;
  r := (Sender as TJvDBGrid).VisibleRowCount;
  w := colSpc + (Sender as TJvDBGrid).Canvas.TextExtent(Column.Field.DisplayText).cx;
  t := colSpc + (Sender as TJvDBGrid).Canvas.TextExtent(Column.Title.Caption).cx;
{$WARNINGS OFF}
  // increase column width if needed
  if (w > g) then Column.Width := w;
  if (g < t) then Column.Width := t;
  if (p < r) and (h < w) then Column.DropDownRows := w;
  // decrease column size if needed (10th line)
  if (p = r) then
  begin
    h := Column.DropDownRows;
    g := Column.Width;
    if (h > t) and (h < g) then Column.Width := Column.DropDownRows;
    Column.DropDownRows := 0;
  end;
{$WARNINGS ON}
end;

So, now when I scroll with the down arrow key, the selected row color does not always is in the correct position as you can see in this picture:

What I am doing wrong?

A: This solution makes all columns expand or shrink according to it's contents, without care if there has to be scroll bars or not, and fix the selected cell drawing malfunction and the the record pointer malfunction.
type
  TColumnAutoAdjust = record {Save the information responsible for setting column widths in the grid}
    Field: String;           {Field name whose information is being stored}
    Registered: Boolean;     {Indicates whether the size of this column already registered}
    Updated: Boolean;        {Indicates the actual size of the column was updated}
    LastWidth: Integer;      {Width indicates the final text of a record of a row column}
    CurrWidth: Integer;      {Indicates the current size and column width}
    Reverter: Integer;       {Indicates the greatest width recorded but that is less than the current}
    Scrolls: Integer;        {Indicates the amount of scrolls present after one width adjustment}
    RecNo: Integer;          {Indicates which was the record in the table which increased the width of colune}
  end;

var { inside the forms private }
  gdCols: array of TColumnAutoAdjust; { vetor de ajuste de largura de cada coluna na grade de resultado }
  RegisteredCols: Integer; { quantas colunas já foram registradas no controle de ajuste }
  gdVisibleRows: Integer; { quantas linhas de cadastros estão visíveis da grade de resultado }
  gdVisibleCols: Integer; { quantas colunas de cadastros estão visíveis da grade de resultado }

{ before showing the grid }
    RegisteredCols := ResultGrid.Columns.Count;
    SetLength(gdCols, RegisteredCols); { determina o tamanho da vetor de controle de colunas }
    { libera a lista }
    ResultGrid.Align := alClient;
    for i := 0 to RegisteredCols -1 do { inicializando a largura das colunas no tamanho do título de cada }
    begin
      gdCols[i].Field := ResultGrid.Columns[i].FieldName;
      ResultGrid.Columns[i].Width := ResultGrid.Canvas.TextExtent(ResultGrid.Columns[i].Title.Caption).cx;
      ResultGrid.Columns[i].Alignment := taLeftJustify;
      ResultGrid.Columns[i].Title.Alignment := taLeftJustify;
    end;
    BrowserQuery.Open;
    ResultGrid.Show;
    for i := 0 to gdVisibleRows do
    begin
      BrowserQuery.Next;
      ResultGrid.Refresh;
    end;
    for i := 0 to gdVisibleRows do
    begin
      BrowserQuery.Prior;
      ResultGrid.Refresh;
    end;
    BrowserQuery.First;
    ResultGrid.SetFocus;
  end

{ after dataset scroll}
procedure TRecordsBrowserFrameBase.BrowserQueryAfterScroll(DataSet: TDataSet);
var
  i, TitleWidth: Integer;
  mayAdjustAgain: Boolean; {  }
begin
{ ajusta as colunas da grade de resultado a cada movimento da tabela de resultado }
  mayAdjustAgain := False;
  for i := 0 to RegisteredCols -1 do
  begin
    if not gdCols[i].Updated then
    begin
      ResultGrid.Columns[i].Width := gdCols[i].CurrWidth;
      gdCols[i].Scrolls := 0;
      gdCols[i].Updated := True;
    end
    else
    begin
      Inc(gdCols[i].Scrolls);
      if (DataSet.RecNo > gdCols[i].RecNo + gdVisibleRows) or (DataSet.RecNo < gdCols[i].RecNo - gdVisibleRows) then
      begin
        TitleWidth := MaxColSpacing + ResultGrid.Canvas.TextExtent(ResultGrid.Columns[i].Title.Caption).cx;
        gdCols[i].LastWidth := gdCols[i].CurrWidth;
        gdCols[i].CurrWidth := IFX(gdCols[i].Reverter > TitleWidth, gdCols[i].Reverter, TitleWidth);
        gdCols[i].Reverter := IFX(gdCols[i].Reverter > TitleWidth, TitleWidth, 0);
        gdCols[i].Updated := False;
        mayAdjustAgain := True;
      end;
    end;
  end;
  if mayAdjustAgain then
  begin
    ResultGrid.Refresh;
    BrowserQueryAfterScroll(DataSet);
  end;
end;

{ on draw column cell }

procedure TRecordsBrowserFrameBase.GridColumnWidthAdjust(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
  ColWidth, TextWidth, TitleWidth: Integer;
begin
{ ajusta a capitalização do texto das células }
  (Sender as TJvDBGrid).Canvas.Pen.Color := clWhite;
  (Sender as TJvDBGrid).Canvas.Rectangle(Rect);
  (Sender as TJvDBGrid).Canvas.TextOut(Rect.Left+2, Rect.Top+2, NameCase(Column.Field.DisplayText));
{ ajusta as colunas de uma grade de acordo com o conteúdo das células }
  gdVisibleRows := (Sender as TJvDBGrid).VisibleRowCount;
  gdVisibleCols := (Sender as TJvDBGrid).VisibleColCount;
  TitleWidth := MaxColSpacing + (Sender as TJvDBGrid).Canvas.TextExtent(Column.Title.Caption).cx;
  TextWidth := MaxColSpacing + (Sender as TJvDBGrid).Canvas.TextExtent(NameCase(Column.Field.DisplayText)).cx;
  ColWidth := Column.Width;
  {$WARNINGS OFF}
  if (TextWidth > gdCols[DataCol].Reverter) and (TextWidth < ColWidth) then gdCols[DataCol].Reverter := TextWidth;
  if (TextWidth > ColWidth) then { texto da célula é mais largo que a coluna }
  begin
    gdCols[DataCol].Registered := True;
    gdCols[DataCol].LastWidth := ColWidth;
    gdCols[DataCol].CurrWidth := TextWidth;
    gdCols[DataCol].Updated := False;
    gdCols[DataCol].RecNo := BrowserQuery.RecNo;
    gdCols[DataCol].Reverter := TitleWidth;
    Exit;
  end;
  if (ColWidth < TitleWidth) then { texto da célula é menor que o título da coluna }
  begin
    gdCols[DataCol].Registered := True;
    gdCols[DataCol].LastWidth := ColWidth;
    gdCols[DataCol].CurrWidth := TitleWidth;
    gdCols[DataCol].Updated := False;
    gdCols[DataCol].Reverter := TitleWidth;
    Exit;
  end;
{$WARNINGS ON}
end;


text:
Q: Python replace string with permutations value I have a string examplestr1 = '0x23x'
the permutation will generate all possible numbers: for i in permutations('123456789', 2):
('1', '2')
('1', '3')
('1', '4')
.
.
.

('9', '8')

After permutation runs, I wish to replace the x in str1 to numbers they permutation gets
out put will be like
01232
01233
01234
.
.
.
09238

How can I achieve that?

A: You may convert your input str to format string and just format
str_format = str1.replace('x', '{}')
for i in permutations('123456789', 2):
  print(str_format.format(*i))

A: You can use replace() to replace the first x with the first element of the permutation, then call it again to replace the second x:
from itertools import permutations

str1 = '0x23x'

for i in permutations('123456789', 2):
    print(str1.replace("x", i[0], 1).replace("x", i[1], 1))


text:
Q: direct SQL rather than curser and loop We have a requirement where we have to calculate some of the daily values based on the frequency that is being passed to SP. So basically we go a number of days behind based on the time-frequency passed within SP and calculate values till today.
Within the stored procedure, we have written curser and used a temp table to do this. Wanted to know if there is any way possible to avoid using curser or temp table here? Currently, if tie frequency is much longer like the last 20 years or so, looping through the entire 20 years of data one by one and calculating for each day is too costly and it takes time. Do we have any faster way of doing this rather than looping through each of the records? We can precalculate this data as well but in this case, it doesn't make sense as we don't know what will be the input time-frequency which will define how many days back to go and start our initial calculation from that day.
CREATE TEMPORARY TABLE IF NOT EXISTS
tmptable(someId VARCHAR(8), someDate DATE, pct DECIMAL(30,3), someValue DECIMAL(30,3));

OPEN curls;
FETCH curls INTO isomeId,  isomeDate, ipct;
    INSERT INTO db_fdsloader.tmp_tblGrowthOfTenK(someId, someDate, pct, someValue) SELECT isomeId, isomeDate, ipct, 100;
    read_loop: LOOP
    FETCH curls INTO isomeId,  isomeDate, ipct;
    IF done THEN
        LEAVE read_loop;
    END IF;

    INSERT INTO tmptable(someId, someDate, pct) SELECT isomeId, isomeDate, ipct;
    SET  @value = @value + (@value * (pct/100));
    UPDATE tmptable SET VALUE = @value WHERE someDate = isomeDate;

END LOOP read_loop;
CLOSE curls;

We, later on, use this into some joining AS below.
    SELECT
        DATE_FORMAT(t1.NavDate, '%Y-%m-%d') AS navDate,
        t3.GrowthTenK AS tenkValue,
        t1.ChangeNavPercent AS tenkPercentChange
    FROM
        table1 t1
    JOIN
        tmptable t3 ON t3.someId = t1.someId AND t3.someDate = t1.someDate
    WHERE
        t2.tk = iTk

;

A: You can do the INSERT as a single query without a cursor. You can reassign the @value variable in the query.
SET @value = 0;

INSERT INTO tmptable (someId, someDate, pct, someValue)
SELECT t1.*, @value := @value + @value * pct/100
FROM (
    your query
) AS t1;

Replace your query with the query that your cursor was connected to.
You could actually do this without the temporary table, by joining with the above SELECT as a subquery in your final query. But creating the temporary table would allow you to add an index on (someId, someDate), which should speed up the join.


text:
Q: User Idle Detection i want to detect User Idle Detection in c++
i used this winapi:
LASTINPUTINFO last_input;
last_input.cbSize = sizeof(LASTINPUTINFO);
last_input.dwTime = 0;
GetLastInputInfo(&last_input)

this methods work correctly with user Input like (mouse and keyboard),
but when i watch a movie  this methods return wrong tickcount
i want right like "windows screen Saver" that detect user activity like (watch movie,mouse and keyboard) perfectly
how i can do this
thx

A: If you want to detect user idle, actually no user input, no display required, you can determines whether a screen saver is currently running using SPI_GETSCREENSAVERRUNNING.
If you want to get time period of user idle, you can see the last user input time as starting point and the time screen saver starts running as end point. Time difference between them is what you want.
More references: "System Sleep Criteria", "SystemParametersInfo()".


text:
Q: \printbibliography only with \citetitle occurrences I want to print two bibliographies:

*

*first, a classic bibliography with documents I cited in my text, I always use \footcite{}

*and a second who references only occurrences \citetitle{}
Actually, I mark my references of pictures, artworks, musical works, performances, art exhibitions, museum exhibitions or architectural works in my text with \citetitle{}. I don't need use \footcite{} for that. I reserved to verbal works: books, articles, podcasts, etc. But I want they be referenced in another final references section, named here "Œuvres & monuments", possibly classifed by type of document.
Classify by type of document is a section named "film" with all my films referenced, another one named "paintings" with all my paintings, "photographies" etc. Types appears in my '.bib' with '@misc' for exemple. (Of course, other problem is the translation from my reference management software : @film becomes @electronic or here @painting -> @misc…)
So, it's between bibliography & index: I have a lot of entries referenced (author, title, date…) like in a bibliography but I want to facilitate indexing like in an index. My solution is using [backref=true]… Well, subsidiary question: is it possible using backref in a bibliography and not in another ?
I resume my questions:

*

*\printbibliography with only \citetitle references ?

*classify my first bibliography by sorting=nyvt & my second by type (@image,@movie…) ?

*using backref in a bibliography and not in another ?

An idea ? Thank you.
\documentclass{scrbook}
\usepackage[style=authortitle-ticomp,sorting=nyvt,isbn=false,doi=false,backref=true]{biblatex}
\usepackage[english,frenchb]{babel}
\addbibresource{Biblio.bib}

\begin{document}
… some \footnote{MerleauPonty:1985wh}, some \citetitle{Burton:1982td,Leradeaudelamedu:1819wn,Persepolis:2007wt} & some words indexed.

\printbibheading
\printbibliography[heading=subbibliography,title={Bibliographie},backref=false]
\printbibliography[heading=subbibliography,title={Œuvres & monuments},backref=true]
\printindex[nam]
\printindex[loc]

\end{document}

My biblio.bib
@electronic{Burton:1982td,
author = {Burton, Tim},
title = {{Vincent}},
year = {1982},
language = {anglais}}

@book{MerleauPonty:1985wh,
author = {Merleau-Ponty, Maurice and Lefort, Claude},
title = {{L'{\OE}il et l'Esprit}},
publisher = {Gallimard},
year = {1985},
series = {Folio. Essais},
address = {Paris},
language = {fran{\c c}ais}}

@electronic{Persepolis:2007wt,
author = {Satrapi, Marjane and Paronnaud, Vincent},
title = {{Persepolis}},
year = {2007},
language = {fran{\c c}ais}}

@misc{Leradeaudelamedu:1819wn,
title = {{Le radeau de la m{\'e}duse}},
author = {G{\'e}ricault, Th{\'e}odore},
year = {1819},
read = {Yes}}

A: We can redefine \citetitle to add all entries cited via \citetitle to a bibliography category oeuvres.
\DeclareBibliographyCategory{oeuvres}
\DeclareCiteCommand{\citetitle}
  {\boolfalse{citetracker}%
   \boolfalse{pagetracker}%
   \usebibmacro{prenote}}
  {\addtocategory{oeuvres}{\thefield{entrykey}}%
   \ifciteindex
     {\indexfield{indextitle}}%
     {}%
   \printfield[citetitle]{labeltitle}}
  {\multicitedelim}
  {\usebibmacro{postnote}}

The first bibliography can then ignore oeuvres, while the second only includes oeuvres.
\printbibliography[heading=subbibliography,title={Bibliographie},notcategory=oeuvres]
\printbibliography[heading=subbibliography,title={Œuvres \& monuments},category=oeuvres]

To get rid of the page references in the first bibliography, we use
\AtNextBibliography{\renewbibmacro*{pageref}{}}

right before the first \printbibliography.
Globally, backref is enabled, but the macro printing the backreferences is temporarily disabled in the first bibliography.
I'm not sure about your sorting requests, but is no problem to specify the sorting in the \printbibliography command:
\printbibliography[sorting=nyt, heading=subbibliography, title={Bibliographie}, notcategory=oeuvres]
\printbibliography[sorting=ynt, heading=subbibliography, title={Œuvres \& monuments}, category=oeuvres]

MWE
\documentclass{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english,frenchb]{babel}
\usepackage{csquotes}
\usepackage[style=authortitle-ticomp,isbn=false,doi=false,backref=true,backend=biber]{biblatex}
\addbibresource{biblatex-examples.bib}

\DeclareBibliographyCategory{oeuvres}
\DeclareCiteCommand{\citetitle}
  {\boolfalse{citetracker}%
   \boolfalse{pagetracker}%
   \usebibmacro{prenote}}
  {\addtocategory{oeuvres}{\thefield{entrykey}}%
   \ifciteindex
     {\indexfield{indextitle}}%
     {}%
   \printfield[citetitle]{labeltitle}}
  {\multicitedelim}
  {\usebibmacro{postnote}}

\begin{document}
some \footcite{cicero,gillies}, some \citetitle{wilde,coleridge} \& some words indexed.

\printbibheading
\AtNextBibliography{\renewbibmacro*{pageref}{}}
\printbibliography[heading=subbibliography,title={Bibliographie},notcategory=oeuvres,sorting=nyt]
\printbibliography[heading=subbibliography,title={Œuvres \& monuments},category=oeuvres,sorting=ynt]
\end{document}

To sort the bibliography by type we need to define a new sorting scheme: tnyvt.
Unfortunately,
\sort{
  \field{entrytype}
}

did not work for me, so we use a workaround: The entrytype is parked in the temporary field usera which is used for sorting.
\DeclareSourcemap{
  \maps[datatype=bibtex]{
    \map{
      \step[fieldset=usera, origentrytype]
    }
  }
}

\DeclareSortingScheme{tnyvt}{
  \sort{
    \field{presort}
  }
  \sort[final]{
    \field{sortkey}
  }
  \sort{
    \field{usera}
  }
  \sort{
    \field{sortname}
    \field{author}
    \field{editor}
    \field{translator}
    \field{sorttitle}
    \field{title}
  }
  \sort{
    \field{sortyear}
    \field{year}
  }
  \sort{
    \field[padside=left,padwidth=4,padchar=0]{volume}
    \literal{0000}
  }
  \sort{
    \field{sorttitle}
    \field{title}
  }
}


text:
Q: Error 1064 SQL en query No puedo ver el error de esta sentencia
create table authority (
id int GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1)
primary key, name varchar(50));

A: la sintaxis correcta en MySQL es:
create table authority (
    id int primary key AUTO_INCREMENT,
    name varchar(50)
);


text:
Q: Exponential moving average of just the last value of a vector in R I have a simple vector as follows:
x = c(14.24, 13.82, 12.75, 12.92, 12.94, 13.00, 14.14, 16.28, 20.64, 17.64)

I have found the EMA of this vector using
library(TTR)
y = EMA(x, 5)

and the result is
[1] NA NA NA NA 13.33400 13.22267 13.52844 14.44563 16.51042 16.88695

The next day a new value is added to the end of original vector x and the updated x vector is:
x = c(14.24, 13.82, 12.75, 12.92, 12.94, 13.00, 14.14, 16.28, 20.64, 17.64, 18.09)

The expected output is -
y = [1] NA NA NA NA 13.33400 13.22267 13.52844 14.44563 16.51042 16.88695 17.28796

This output can be produced by EMA(x, 5), but this statement will calculate EMA of the entire vector again and will be time inefficient.
Since we already have the previous day's EMA calculation in vector y,
is there a way to calculate the EMA of just the last 5 days instead of recalculating for the entire vector and merge the new value in vector y?
Thanks!

A: If you read ?TTR::EMA,

For 'EMA', 'wilder=FALSE' (the default) uses an exponential smoothing ratio of '2/(n+1)'

It helps to understand that in EMA, this ratio is effectively the weight applied to the current value (x), and the inverse (one minus this) is applied to the previous average (y).
x = c(14.24, 13.82, 12.75, 12.92, 12.94, 13.00, 14.14, 16.28, 20.64, 17.64)
n <- 5
y <- TTR::EMA(x, n)

x = c(14.24, 13.82, 12.75, 12.92, 12.94, 13.00, 14.14, 16.28, 20.64, 17.64, 18.09)
ratio <- 2/(n+1)
ratio
# [1] 0.3333333
sum( c(y[10], x[11]) * c(1-ratio, ratio) )
# [1] 17.28796

A: As already suggested in this post, looking at C code of TTR provides a possible solution :
x = c(14.24, 13.82, 12.75, 12.92, 12.94, 13.00, 14.14, 16.28, 20.64, 17.64)

n <- 5
y = TTR::EMA(x,n)

ratio <- 2 / (n+1)

newx <- 18.09
newy <- tail(y,1) * (1 - ratio) + ratio * newx
newy
#> [1] 17.28796

y = c(y,newy)
y
#>  [1]       NA       NA       NA       NA 13.33400 13.22267 13.52844 14.44563
#>  [9] 16.51042 16.88695 17.28796


text:
Q: Add new columns and rows I have PySpark dataframe:
cust |  prob
-------------------
A    |  0.1
B    |  0.7
C    |  0.4

I would like to add another column amount and add rows to each customer. My expected result would be:
cust |  prob  |  amount
------------------------
A    |  0.1   |  1000
A    |  0.1   |  2000
A    |  0.1   |  3000
A    |  0.1   |  4000
A    |  0.1   |  5000
B    |  0.7   |  1000
B    |  0.7   |  2000
B    |  0.7   |  3000
B    |  0.7   |  4000
B    |  0.7   |  5000
C    |  0.4   |  1000
C    |  0.4   |  2000
C    |  0.4   |  3000
C    |  0.4   |  4000
C    |  0.4   |  5000

I need help in making this new column and rows. My real data consist of many columns, so it should duplicate whatever the original column in the dataset.

A: You can add an exploded array:
import pyspark.sql.functions as F

df2 = df.withColumn(
    'amount',
    F.explode(
        F.array(*[F.lit(i) for i in [1000, 2000, 3000, 4000, 5000]])
    )
)

Or an exploded sequence:
df2 = df.withColumn(
    'amount',
    F.explode(
        F.sequence(F.lit(1000), F.lit(5000), F.lit(1000))
    )
)