text:
Q: MD5 base64 hash is different when compiled in Delphi as 32-bit or 64-bit - how can I make them the same? I am using Delphi XE2 and the below code to create an MD5 base64 hash to use with Amazon MWS. It works if I compile it for 32-bit Windows, but if I compile for 64-bit windows the return hash changes. What is causing this and how can I change this so that they return the same hash?
function getMd5HashString(value: string): string;
var
  MessageDigest: TIdHashMessageDigest5;
  Content: TBytes;
begin
  Content := TEncoding.UTF8.GetBytes(value);
  MessageDigest:=TIdHashMessageDigest5.Create;
  Result:=Data.Cloud.CloudAPI.EncodeBytes64(MessageDigest.HashBytes(Content));
end;

Thansk in advance.
Edit:
I am using the above function in the following test;
procedure Button1Click(Sender: TObject);
begin
  Edit2.Text := getMd5HashString(Edit1.Text);
end;

I am passing
<?xml version="1.0" encoding="utf-8"?>

as the string, just to test with. If I compile the program with a Target Platform of Windows 32-bit the returned hash is;
I3pK/R+hpYOKY1IQRviZbQ==
Whereas if I compile the program with a Target Platform of Windows 64-bit I get;
bmkkAOXGhLdDFCUuNBuSxw==
I hope that answers you David?
Edit2: Full program as suggested by David;
unit ContentHashTest;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.Cloud.CloudAPI, IdGlobal, IdHash, IdHashMessageDigest,
  IdCoder, IdCoderMIME, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    Edit2: TEdit;
    procedure Button1Click(Sender: TObject);
  private
    function getMd5HashString(value: string): string;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  Edit2.Text := getMd5HashString(Edit1.Text);
end;

function TForm1.getMd5HashString(value: string): string;
var
  MessageDigest: TIdHashMessageDigest5;
  Content: TBytes;
begin
  Content := TEncoding.UTF8.GetBytes(value);
  MessageDigest:=TIdHashMessageDigest5.Create;
  Result:=Data.Cloud.CloudAPI.EncodeBytes64(MessageDigest.HashBytes(Content));
end;

end.

That was my starting attempt. After David's suggestion below I changed this to;
unit ContentHashTest;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdGlobal, IdHash, IdHashMessageDigest,
  IdCoder, IdCoderMIME, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    Edit2: TEdit;
    procedure Button1Click(Sender: TObject);
  private
    function getMd5HashString(value: string): string;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  Edit2.Text := getMd5HashString(Edit1.Text);
end;

function TForm1.getMd5HashString(value: string): string;
var
  MessageDigest: TIdHashMessageDigest5;
  Content: TIdBytes;
begin
  Content := TIdTextEncoding.UTF8.GetBytes(value);
  MessageDigest := TIdHashMessageDigest5.Create;
  try
    Result := TIdEncoderMIME.EncodeBytes(MessageDigest.HashBytes(Content));
  finally
    MessageDigest.Free;
  end;
end;

end.

Unfortunately with the same differing results.
Win32 = I3pK/R+hpYOKY1IQRviZbQ==
Win64 = bmkkAOXGhLdDFCUuNBuSxw==

A: I turned the extracts in the question into this complete program:
{$APPTYPE CONSOLE}

uses
  SysUtils,
  IdGlobal,
  IdCoderMIME,
  IdHashMessageDigest;

function getMd5HashString(value: string): string;
var
  MessageDigest: TIdHashMessageDigest5;
  Content: TIdBytes;
begin
  //Content := TIdTextEncoding.UTF8.GetBytes(value); // for older versions of Indy
  Content := IndyTextEncoding_UTF8.GetBytes(value);
  MessageDigest := TIdHashMessageDigest5.Create;
  try
    Result := TIdEncoderMIME.EncodeBytes(MessageDigest.HashBytes(Content));
  finally
    MessageDigest.Free;
  end;
end;

begin
  Writeln(getMd5HashString('<?xml version="1.0" encoding="utf-8"?>'));
  Readln;
end.

I'm using Indy to perform all of the conversions: text to UTF-8 bytes, MD5 hashing, and the base64 encoding. But you should use any libraries for this, since they should all give the same output.
This program produces the same output for 32 and 64 bit, as would be expected:

I3pK/R+hpYOKY1IQRviZbQ==

You report different behaviour though, so what could be the cause? I can think of the following possible explanations:

*

*You are not in fact passing the same input value to the function in both versions.

*TEncoding.UTF8.GetBytes is defective.

*TIdHashMessageDigest5.HashBytes is defective.

*Data.Cloud.CloudAPI.EncodeBytes64 is defective.

In any case, I don't see any sense in using Data.Cloud.CloudAPI to perform base64 encoding, although I have no reason to believe that it does not work. Since you are already using the Indy library, it makes more sense to do that uniformly.
I cannot tell from here which of the above explanations is the cause of what you report. You should be able to debug this further to find out. Look at the output of each step in the process to figure out where the behaviour varies.

Update: I've managed now to reproduce the error, but only by using the version of Indy that ships with XE2. I was using a more up-to-date version of Indy in my initial experiments.
The problem appears to be item 3 in my list. This gives incorrect results under the x64 compiler.
You should solve the problem by finding a different MD5 implementation. My recommendation is to do this by upgrading Indy.


text:
Q: The request signature we calculated does not match the signature you provided, even signature created Signature is created successfully when passed as authorization to access service, facing an error like
The request signature we calculated does not match the signature you provided.
Below the class used to create the authorization. Kindly assist.

public class Canonical {
  //public static String authorization_header;
  public static String auth() throws Exception  {

      //canonical string creation
      String currentDate  = getDate();
      String xAmzDate = getTimeStamp();
      String region = "eu-west-1";
      String serviceName ="execute-api";

      String canonical_uri = "pathdetailsofservice";

      URL url = new URL("endpointurl");
      String req_query_string = orderQuery(url );
      String canonical_querystring = req_query_string;
      String host ="dataservices.whssng.uk";
      String method ="POST";
      String ContentType ="application/json";
      String canonical_headers = "host:" + host + "\n" + "x-amz-date:" + xAmzDate + "\n";
      String signed_headers = "Content-Type;host;x-amz-date";
      String secret_key ="secretkey";
      String access_key ="accesskey";

      String request_parameters = "";
      String payload_hash = generateHex(request_parameters);
      String canonical_request = method + "\n" + canonical_uri + "\n" + ContentType+ "\n" + canonical_querystring + "\n" + canonical_headers + "\n" + signed_headers + "\n" + payload_hash;
      System.out.println("canonical_request"+"\n"+canonical_request);

      //Create  String to Sign

      String algorithm = "AWS4-HMAC-SHA256";
              String credential_scope = currentDate + "/" + region + "/" + serviceName + "/" + "aws4_request";
              String hash_canonical_request = generateHex(canonical_request);
              String string_to_sign = algorithm + "\n" +  xAmzDate + "\n" +  credential_scope + "\n" +  hash_canonical_request;
      System.out.println("string_to_sign"+"\n"+string_to_sign);

  ////Calculate the String to Sign

  byte[] signing_key = getSignatureKey(secret_key, xAmzDate, region, serviceName);
  byte[] signature =hmac_sha256(signing_key, string_to_sign);
  String strHexSignature = bytesToHex(signature);
   System.out.println("Signature:"+strHexSignature);

  //Add Signing information to Variable

  String authorization_header = algorithm + " " + "Credential=" + access_key + "/" + credential_scope + ", " +  "SignedHeaders=" +

signed_headers + ", " + "Signature=" + strHexSignature;
System.out.println("Authorization:"+authorization_header);
return authorization_header;
}

private static String generateHex(String data) {
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(data.getBytes("UTF-8"));
            byte[] digest = messageDigest.digest();
            return String.format("%064x", new java.math.BigInteger(1, digest));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

public static String getDate() {
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));//server timezone
    return dateFormat.format(new Date());
}

public static String orderQuery(URL url) throws UnsupportedEncodingException {

    String orderQueryString = "";
    Map<String, String> queryPairs = new LinkedHashMap<>();
    String queryParams = url.getQuery();

    if (queryParams != null) {
        String[] pairs = queryParams.split("&");

        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            queryPairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
        }
       TreeMap<String, String> orderQueryArray = new TreeMap<String, String>(queryPairs);
        orderQueryString  = urlEncodeUTF8(orderQueryArray);
    }
    return orderQueryString;
}

public static String urlEncodeUTF8(String s) {
    try {
        return URLEncoder.encode(s, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new UnsupportedOperationException(e);
    }
}

public static String urlEncodeUTF8(Map<?,?> map) {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<?,?> entry : map.entrySet()) {
        if (sb.length() > 0) {
            sb.append("&");
        }
        sb.append(String.format("%s=%s",
            urlEncodeUTF8(entry.getKey().toString()),
            urlEncodeUTF8(entry.getValue().toString())
        ));
    }
    return sb.toString();
}

public static String getTimeStamp() {
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));//server timezone
    return dateFormat.format(new Date());
}

public static byte[] getSignatureKey(String key, String dateStamp, String regionName, String serviceName) throws Exception {
    byte[] kSecret = ("AWS4" + key).getBytes("UTF-8");
    byte[] kDate = hmac_sha256(kSecret, dateStamp);
    byte[] kRegion = hmac_sha256(kDate, regionName);
    byte[] kService = hmac_sha256(kRegion, serviceName);
    byte[] kSigning = hmac_sha256(kService, "aws4_request");
    return kSigning;
}

public static byte[]  hmac_sha256(byte[] key, String data) throws InvalidKeyException, NoSuchAlgorithmException {
    Mac mac = Mac.getInstance("HmacSHA256");
    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "HmacSHA256");
    mac.init(secretKeySpec);
    byte[] digest = mac.doFinal(data.getBytes());
    return digest;

}
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
private static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars).toLowerCase();
}
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: ExpressJS session expiring despite activity Bringing this question to SO since the express group didn't have an answer.
I'm setting the session maxAge = 900000 and I see that the the expires property on the session cookie is set correctly.
However, on subsequent requests the timeout is not being extended. It is never extended and the cookie eventually expires.
The session middleware docs say that Session#touch() isn't necessary because the session middleware will do it for me. I actually tried calling req.session.touch() manually and that did nothing, I also tried setting the maxAge on the req.session.cookie as well and that did nothing :-(
Am I missing a setting somewhere to automatically extend active sessions? Short of recreating the cookie manually on each request is there any other way to extend a session timeout after end-user activity?

EDIT: I experienced this problem in express v3. I'm not 100% sure but I think this note from the express changelog may have been the culprit:

*

*changed session() to only set-cookie on modification (hashed session json)

A: Rolling sessions now exist in express sessions. Setting the rolling attribute to true in the options, it will recalculate the expiry value by setting the maxAge offset, applied to the current time.
https://github.com/expressjs/session/issues/3
https://github.com/expressjs/session/issues/33
https://github.com/expressjs/session (search for rolling)
For example, note the rolling:
app.use(session({
  secret: 'a secret',
  cookie: {
    path: '/',
    httpOnly: true,
    secure: false,
    maxAge: 10 * 60 * 1000
  },
  rolling: true
}));

A: Here is the solution in case anyone else has the same issue:
function (req, res, next) {

    if ('HEAD' == req.method || 'OPTIONS' == req.method) return next();

    // break session hash / force express to spit out a new cookie once per second at most
    req.session._garbage = Date();
    req.session.touch();

    next();

}


text:
Q: Way to pass Long parameter in url request using volley Server is not accepting String parameters when making json object request (by post method) using volley, also in custom volley request it is required to pass a string Hash map in getParams() method i am having string as well as long values to be pass over there, Also tried by Uri class but there is also sting is required in appendQueryParameter(). i have used below links Link 1
Link 2 Link 3
Volley class

public class CustomRequest extends Request {
private Listener<JSONObject> listener;
private Map<String, String> params;

public CustomRequest(String url, Map<String, String> params,
                     Listener<JSONObject> reponseListener, ErrorListener errorListener) {
    super(Method.GET, url, errorListener);
    this.listener = reponseListener;
    this.params = params;
}

public CustomRequest(int method, String url, Map<String, String> params,
                     Listener<JSONObject> reponseListener, ErrorListener errorListener) {
    super(method, url, errorListener);
    this.listener = reponseListener;
    this.params = params;
}

protected Map<String, String> getParams()
        throws com.android.volley.AuthFailureError {
    return params;
}

@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers));
        return Response.success(new JSONObject(jsonString),
                HttpHeaderParser.parseCacheHeaders(response));
       /* return Response.success(
                gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));*/
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = new HashMap<>();
    String loginEncoded = new String(Base64.encode(("uictester:?f!T!ziX}.,(").getBytes(), Base64.DEFAULT));
    headers.put("Authorization", "Basic " + loginEncoded);
    return headers;
}

@Override
protected void deliverResponse(JSONObject response) {
    // TODO Auto-generated method stub
    listener.onResponse(response);
}

}

A: You first need to convert the long parameter to String using String.valueOf(long value) method and then put this param to the hashmap with its key. as:
params.put("key", String.valueOf(long value));


text:
Q: Why does the first mobile css menu item not position properly? I created my own CSS only mobile menu similar to slicknav but without the javascript required.   Everything works properly (3 level menu) but the first item in the menu is not positioned as all of the rest of the items.
.menuV
{
     margin: 0; /*width: 100%;*/ float:none;
    width:130px;
    position:relative;
    z-index:4;
    font-family: Arial, Helvetica, sans-serif;
    list-style: none;
    padding: 0;
    top:26px;
    left:-53px;
    display:none;
    border: 2px solid #DDD;
    background: #FFF;

}

.menuV li
{
    padding: 0;
    height: 36px;
    position: relative;
}

I created a jsfiddle https://jsfiddle.net/hLene9a3/ that contains the all of the ul li menu items and all of the css.  The css for hover/dropdown is too long to post here.
Any help would be greatly appreciated.

A: I don't know what causes this but putting position:absolute on it correct this. I can only test in FF here though. Try putting this on your css.
#menuFile > a{position:absolute;}


text:
Q: Android cryptography library FIPS validation I want to know, is the android's cryptography library (javax.crypto) "validated to FIPS 140-2"?
I need for a specific product which FIPS is important.

A: No, javax.crypto is not FIPS-validated, you'll need another lib for that.
However, it is impossible to reach level 2 with libraries alone, as it has requirements
on the hardware too (and a typical Android device is not validated either).


text:
Q: How connect $x^2+xy+y^2$ to $j^3*4*n-27 = t^2$ $x^2 + xy + y^2 = (x^3 - y^3)/(x - y)$
Now let me show a subject not connected with above form (at least in some known way).
By trying solve equation
$1 \cdot 4 \cdot n - 27 = t^2$  ($n,t$ integers)
$n=(7+(m(m+1))$ works fine, since $4(7+m(m+1)) - 27 = 28 + 4m^2 + 4m - 27 = (2m+1)^2$
so $t = 2m+1$
Now look "$1 \cdot 4 \cdot n$" at left, the "1" part really means "$1^{3} \cdot 4 \cdot n$" , so I searched which other $j^{3} \cdot 4 \cdot n - 27$ forms could produce perfect squares.
I wrote a tiny BASIC program to check whether
$j^{3} \cdot 4 \cdot n - 27 = t^2$  ($j,n,t$ integers) ... (A)
and found the following $j$ solving it for some $n$ (and only those $j$ and no others)
1, 3, 7, 13, 19, 21, 31, 37, 39, 43, 49, 57, 61, 67, 73, 79, 91, 93, 97, 103, 109, 111, 127, 129, 133, 139, 147, 151, 157, 163, 169, 181, 183, 193, 199, 201, 211, 217, 219, 223, 229, 237, 241, 247, 259, 271, 273, 277, 283, 291, 301, 307, 309, 313, 327, 331, ..... (more)
For every "$j$" found, there are probably infinite "$n$" to produce perfect squares (I suppose, but couldn´t prove it)
I searched on database sequence integers oeis.org for this sequence, and it is exactly the sequence generated by
$x^2 + xy + y^2$  (oeis sequence A034017)
Some $j$ wait for a big $n$ to show the first solution, ex.  $j=259$ starts with $n=4225513$ to compute $t=17136391$
$259^{3} \cdot 4 \cdot 4225513 - 27 = 17136391^2$
Now the question, why should $j$ present this pattern $j = x^2+xy+y^2$ ?
Anybody can check list of $j$ by running this tiny UBASIC program for some hours. It will search all integers to 500 and will list only those $j$ which solves (A) first time.

800   for J=1 to 500
900   V=JJJ
1000   for N=1 to 5000000
1100   X=V*4*N-27
1240   T=sqrt(abs(X))
1250   if T=int(T+0.0000000001) then print J;:cancel for:goto 1400
1300   next N
1400   next J

A: You wrote
$$ t^2 + 27 = 4 n j^3. $$ This means that $t$ is odd and $t^2 + 27 \equiv 4 \pmod 8.$ This means, in turn, that $n,j$ are both odd.
Meanwhile, if we have odd prime $p,$ with
$$ x^2 + 27 y^2 \equiv 0 \pmod p, $$ it follows that, whenever $(-3|p) = -1,$ both $$ x, y \equiv 0 \pmod p. $$
Therefore, since we demand $y=0,$ we have demanded that $(-3|p) = 1.$ By quadratic reciprocity, this means either $p=3$ or $(p|3) = 1.$ That is, either $p=3$ or $p \equiv 1 \pmod 3.$
Both $n$ and $j$ are products of such primes. $u^2 + uv + v^2$ is of class number one and represents all such primes, and represents all products of such primes. That is, you are entitled to write $n = u^2 + uv + v^2$ and $j = x^2 + xy + y^2$
Let's see. For any such $j$ and $n,$ both $j^3$ and $4n$ can be written as
$r^2 + 27 s^2.$ This is not obvious. The trouble comes when you try to force this $s=1.$

A: I did not realize that you wanted to specify $j$ first and only then find an $n.$ This requires some knowledge but is algorithmic.
First, $259 = 7 \cdot 37.$ We automatically have some ways to write $259 = x^2 + 3 y^2.$ However, the class group of discriminant $-108$ has three forms, $x^2 + 27 y^2,$ $4x^2 + 2 x y + 7 y^2,$ $4x^2 - 2 x y + 7 y^2.$
As it happens, $$ 259 = 4^2 + 27 \cdot 3^2. $$ We need to primitively represent $259^3.$ Squared,
$$ 259^2 = 227^2 + 27 \cdot 24^2. $$ Finally,
$$ 259^3 = 2852^2 + 27 \cdot 585^2, $$
with $$  \gcd(2852,585) = 1.$$
We use some version of an extended euclidean algorithm (I use simple continued fractions) to find
$$  2852 \cdot 8 -  585 \cdot 39 = 1.  $$
The $8$ is unfortunate, as $39^2 + 27 \cdot 8^2$ is not a multiple of $4.$ We switch from $(-39,8)$ to $(-39 - 2852, 8 + 585) = (-2891, 593 )$ and check that
$$ 2852 \cdot 593 -  585 \cdot 2891 = 1,  $$
which works.
Now we do have
$$ 4n = 2891^2 + 27 \cdot 593^2 = 17852404  $$
and
$$ n = 4463101  $$
So far, we have $j^3$ represented as $x^2 + 27 y^2$ with $(x,y)$ as $(2852,585),$ and $4n$ as $(2891,593).$ From Brahmagupta's identity we get
$4nj^3$ represented as
$$ ( 2852 \cdot 2891 + 27 \cdot 585 \cdot 593, \; \;2852 \cdot 593 -  585 \cdot 2891 ),  $$ that is
$$  (17611567, \; \; 1  \; ).   $$ That is,
$$ 4nj^3 = t^2 + 27  $$
with $t = 17611567.$
Things change when representing $j^3$ as $x^2 + 27 y^2$ when we begin with some $j = 4 u^2 + 2 uv + 7 v^2.$ We still use composition in the class group, but it does look a little different from $j = r^2 + 27 s^2.$ For your main example, we could have begun with $259 = 4 u^2 + 2 uv + 7 v^2,$ with $(u,v) = (6,-5).$
Did some calculations. When we have  $j = 4 u^2 + 2 uv + 7 v^2,$ one way of writing $j^3 = x^2 + 27 y^2$ is with
$$ x =  8u^3 + 6u^2 v - 39 u v^2 - 10 v^3, \; \; y =  6 u^2 v + 3 u v^2 - 3 v^3. $$
Starting with $259$ as $(6,-5),$ this leads to $259^3$ as $(3952,-255),$ and we can repeat the bit about gcd and so on.
Continued fractions give
$$ 3952 (-2) + 255 (31) = 1. $$
Once again, the even $(-2)$ is bad, so we switch to
$$ 3952 \cdot 253 - 255 \cdot 3921 = 1. $$
This leads us to $4nj^3 = t^2 + 27,$ with
$$ t = 3952 \cdot 3921 + 27 \cdot 255 \cdot 253 = 17237697  $$
Also
$$ n =4275621  $$
Anyway, all algorithmic, and those algorithms can produce some fairly large numbers, but not enormous.

A: Thanks very much for your explanations, I am still reading carefully your posts.
First of all, let me say this problem is part of another which I posted some months ago in this link
When is $\bigl( \frac{a}{b} \bigr)^{3} \pm \bigl( \frac{x}{y}\bigr)^{3}$ an integer?
When searching some parametric forms to problem in above link, I reached the expression
$j^3.4.n - 27 = t^2$
which when solved for $j=1$ and $n=(7+m(m+1))$ lead me to
$(5+m)^3 + (4-m)^3 = (7+m(m+1)).3^3$
or else
$(5+m)^3 / 3^3 + (4-m)^3 / 3^3 = 7+m(m+1)$
This form solves infinite cases, like m=0 to $(5/3)^3+(4/3)^3=7$ or m=6 to $(11/3)^3-(2/3)^3=49$ , but there are still "infinite x infinite" cases to solve , one for every j.
By analyzing j=2 ,it appeared difficult to me, so I take next j
For $j=3$ I found $n=1+3m(m+1)$ which works fine giving $t=9(2m+1)$ since
$3^3.4.(1+3m(m+1)) - 27 = 27[4(1+3m(m+1)) - 1] = 27(12m^2+12m+3) = [9(2m+1)]^2$
but unfortunately this j leads to an indentity instead a solution, because denominators cancell all of them
Now comes the moment when I asked "which other j produces squares when applied to $j^3.4.n$ ? . I made this question preventing some hard job to find j=f(z) for some z, which would produce squares.
I supposed these j´s would follow a single variable pattern (z), so it would be relatively easy to assemble a more general form to solve those cubic fractions, by includind now the parametric form of j in the same way I included parametric form of n.
I wrote that basic program to learn it, and result appeared in the form of the sequence j=1,3,7,13... Next I run to database of sequences (OEIS) to see what could be that thing, and here is when my surprise came, because j is not a single variable function, but a two variables function, which complicates a lot the searching for more general form.
For next j=7 , things turns to be very more complicated (to find f(n)), so just think about the task for j=13,19,21 ....
Now about your analysis of j=259 , this is an example I used to show how can be difficult to find the first "n" for given "j" . 259 is only one of those elements in the sequence, there are other examples also which delay a lot to produce first "n" like j=223 or j=229 which give first solution for n=1517139 and n=2582431
$223^3.4.1517139 - 27 = 8203515^2$
$229^3.4.2582431 - 27 = 1137753^2$
Increasing difficulty to find first solution doesn´t follow j size. Some big "js" have first solution with little n, like j=1011 which starts with n=28009
$1011^3.4.28009 - 27 = 10759833^2$
Now turning to j=259 , it appears solutions of these problems try to group in "clumps" , look for the first 8 solutions of 259, the first four "ts" more or less 1/3 of the second four "ts".
1- n=  4225513  t= 17136391
2- n=  4275621  t= 17237697 (your solution)
3- n=  4411903  t= 17510261
4- n=  4463101  t= 17611567 (your solution)
5- n=  38735883 t= 51884349
6- n=  38887297 t= 51985655
7- n=  39296143 t= 52258219
8- n=  39448647 t= 52359525
I found these solutions with a tiny change in the listed basic program.

A: For this question, everything you want can be written in terms of (positive) binary quadratic forms with integer coefficients. You need to know that the discriminant $-108$ possesses  imprimitive forms, $2x^2 + 2 xy + 14 y^2$ and $3x^2 + 9 y^2$ and $6x^2 + 6 xy + 6 y^2,$ along with the three primitive forms that make up the class group,
$$ x^2 + 27 y^2, $$
$$ 4 x^2 + 2 xy + 7 y^2, $$
$$ 4 x^2 - 2 xy + 7 y^2. $$
You need to know something about Gauss/Dirichlet composition. I recommend some modern books, i especially like Buell, Binary Quadratic Forms. For the part of your problem that requires proving divisibility, there is a book from 1929 by Leonard Eugene Dickson, Introduction to the Theory of Numbers. You need pages 91-95 in particular. If you are patient, you should be able to recover all the $8$ or so solutions you found to $4nj^3 = t^2 + 27$ by these methods. I admit, it will get more difficult when writing $j^3 = 4 u^2 + 2 uv + 7 v^2$ to find $4n = 4 x^2 - 2 xy + 7 y^2$ for $4nj^3 = r^2 + 27 s^2$ with the restriction $s=\pm1.$

A: As I thought, we could have found your smallest $n$ and $t$ by a little more imaginative bookkeeping.
$$  \gcd(2852,585) = 1.$$
We use some version of an extended euclidean algorithm (I use simple continued fractions) to find
$$  2852 \cdot 8 -  585 \cdot 39 = 1.  $$
That is, the determinant of
$$
\left(
\begin{array}{rr}
2852 & 585 \\
39 & 8
\end{array}
\right)
$$
is $1.$ In the other answer, in order to get rid of the even $8,$ i added the first row to the second to get
$$
\left(
\begin{array}{rr}
2852 & 585 \\
2891 & 593
\end{array}
\right)
$$
Nothing wrong with that. However i could just as well have subtracted the first row from the second, giving
$$
\left(
\begin{array}{rr}
2852 & 585 \\
-2813 & -577
\end{array}
\right)
$$
The minus signs do not matter here.
This does give us
$$ 4n = 2813^2 + 27 \cdot 577^2 = 16902052  $$
and
$$ n = 4225513  $$


text:
Q: Change Rewrite rule depending on the URL I have a domain example.com which currently points to example123.com. I only want to hide the index.php file when I am at example.com, not example123.com. I'm on Apache 2.2 so I can't use the <if> statement.
How can I possibly do it?
I currently have:
RewriteCond %{REQUEST_URI} ^example.com.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

But this doesn't work because this can take away the index.php from both domains. I only need to do that with one.

A: You can use the following code in you htaccess :
RewriteEngine On

RewriteCond %{HTTP_HOST} ^(www\.)?example.com$ [NC]
RewriteRule ^(.*)$ /index.php?/$1 [NC,L]


text:
Q: ¿Como quitar slash invertido en json? Al ejecutar este código:
    $array =array();
    $sqli=mysqli_connect('localhost', 'dbuser', 'pass', 'db');
    $query = mysqli_query($sqli,"SELECT * FROM usuarios");
    while ($fila = $query->fetch_assoc()) {
        $res=array('nombre'=>$fila["nombre"],'tipo'=>$fila["tipo"] 'contraseña'=>$fila["user"]);
        array_push($array,$res);
    }
    header("Content-type:application/json");
    echo json_encode($array);

me obtiene este resultado:
{"nombre":"admin","tipo":"1","contrase\u00f1a":"$2y$10$H5GU7rN38jo3n\/eJW6KMHuovnCFYymi8GrQpshuhowWxYVZdq8r2S"}]

me genera slashes invertidos despues de un / y me cambia la ñ por su entidad html ¿Cómo puedo arreglar esto?

A: Utiliza la opción JSON_UNESCAPED_SLASHES para que no escape los /.
En cuanto a la ñ te lo esta convirtiendo a unicode, puedes forzar tambien para que no lo convierta con JSON_UNESCAPED_UNICODE
// JSON_UNESCAPED_SLASHES => 64
// JSON_UNESCAPED_UNICODE => 256
// JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE => 320

$arrayName = array('Contraseña' => '$2y$10$H5GU7rN38jo3n/eJW6KMHuovnCFYymi8GrQpshuhowWxYVZdq8r2S');
echo json_encode($arrayName, 320);
// {"Contraseña":"$2y$10$H5GU7rN38jo3n/eJW6KMHuovnCFYymi8GrQpshuhowWxYVZdq8r2S"}
echo json_encode($arrayName);
// {"Contrase\u00f1a":"$2y$10$H5GU7rN38jo3n\/eJW6KMHuovnCFYymi8GrQpshuhowWxYVZdq8r2S"}

Más informacion en http://php.net/manual/es/json.constants.php


text:
Q: How to access listboxitem template data when an event of it's item control is fired? I want to access each listboxitem template control's(image and 4 textblock controls  )data when the button is clicked from the following hierarchy.
 <ListBox x:Name="lstBoxNearbyPlaces" ItemsSource="{Binding Items}" Grid.Row="2" Margin="0,10,0,0"  >
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <Button Width="400" Height="150" Name="btnPlace" Click="btnPlace_Click_1">
                                    <Button.Content>
                                        <StackPanel Orientation="Horizontal" >
                                            <Image  Name="ImgPlace"  Source="{Binding PlaceIconURL}" Width="50" />
                                            <TextBlock Name="lblPlaceLat" Text="{Binding PlaceLatLocation}" Visibility="Collapsed"/>
                                            <TextBlock Name="lblPlaceLng" Text="{Binding PlaceLongLocation}" Visibility="Collapsed"/>
                                            <StackPanel Width="350" >
                                                <TextBlock FontSize="20"   Text="{Binding PlaceName}" Name="txtAddress" TextWrapping="Wrap" ></TextBlock>
                                                <TextBlock FontSize="20" Text="{Binding PlaceVicinity}" Name="txtLocation" TextWrapping="Wrap"></TextBlock>
                                            <Line MinHeight="5"></Line>
                                            </StackPanel>
                                        </StackPanel>
                                    </Button.Content>
                                </Button>
                            </DataTemplate>

                        </ListBox.ItemTemplate>
                    </ListBox>

Is it possible to get or read the data of the every control here when the button click event is fired ?

A: You can get the binding object in the ListBox_SelectionChanged as the selected item.
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      ItemModel model= listBox.SelectedItem as ItemModel ;
    }

Or In the Buttonclick event you can get it as
 private void Button_Click(object sender, RoutedEventArgs e)
    {
        Button button = sender as Button;
        ItemModel model = button.DataContext as ItemModel;
    }

Here model is the object which you have bind to that template.


text:
Q: iterate over days and pull in price information This is a follow on question from here. Thanks to @nate for the helpful solution.
I am trying to collect price data from coinbase. What I have so far is the following:
start <- strftime(Sys.time() - 86400, "%Y-%m-%dT%H:%M:%SZ", tz = "UTC")
end <- strftime(Sys.time(), "%Y-%m-%dT%H:%M:%SZ", tz = "UTC")
product_id = "ETH-EUR"
granularity = 300
# request url
req.url <- paste0("https://api.pro.coinbase.com/products/", product_id, "/candles")
req.url
# fetching the data ourselves - the return
res <- httr::GET(url = req.url,
                 query = list(start = start, end = end,
                              granularity = granularity))
res <- as.data.frame(t(matrix(unlist(httr::content(res)), nrow = 6)))
res[['V1']] <- as.POSIXct(.subset2(res,1L), origin="1970-01-01")
c(min(res$V1),max(res$V1))

colnames(res) <- c("time", "low", "high", "open", "close", "volume")

Which gives the following:
> c(min(res$V1),max(res$V1))
[1] "2019-01-23 13:45:00 CET" "2019-01-24 13:40:00 CET"

(The last 24 hours worth of data)
If I change the start and end times to the following:
start <- strftime(Sys.time() - 86400*5, "%Y-%m-%dT%H:%M:%SZ", tz = "UTC")
end <- strftime(Sys.time(), "%Y-%m-%dT%H:%M:%SZ", tz = "UTC")

(Collect the last 5 days worth of data) - coinbase does not allow so much data to be collected.
However it is possible to collect:
 t = 5 and t = 4
 t= 4 and t = 3
 t = 3 and t = 2
 t = 2 and t = 1
 t = 1 and t = 0

So collect data 5 days ago and subtract 24 hours from that date.
 Something like the following:
start <- strftime(Sys.time() - 86400*5, "%Y-%m-%dT%H:%M:%SZ", tz = "UTC")
end <- strftime(Sys.time() - 86400*(5-1), "%Y-%m-%dT%H:%M:%SZ", tz = "UTC")

Which Works. So knowing this I am trying to créate a function which Will "loop" of iterate over the dates and pull in the information.
I have been working on the following - but I know a function would be 100 times better than what I currentlu have:
start <- NULL
end <- NULL
for(i in 1:5){
  start[[i]] <- as.data.frame(strftime(Sys.time() - 86400*i, "%Y-%m-%dT%H:%M:%SZ", tz = "UTC"))
  end[[i]] <- as.data.frame(strftime(Sys.time() - 86400*(i-1), "%Y-%m-%dT%H:%M:%SZ", tz = "UTC"))
}

start <- do.call(rbind.data.frame, start)
end <- do.call(rbind.data.frame, end)

colnames(start) <- "start"
colnames(end) <- "end"

for(i in 1:5){
  res[[i]] <- httr::GET(url = req.url,
                   query = list(start = start[i, ], end = end[i, ],
                                granularity = 300))
}

Do you have any tips on how to apply this to a function?

A: You could create a function like this
# Function
coinbaseGET <- function (product_id, start, end, granularity) {
  # request url
  req.url <- paste0("https://api.pro.coinbase.com/products/", product_id, "/candles")
  req.url
  # fetching the data ourselves - the return
  res <- httr::GET(url = req.url,
                   query = list(start = start, end = end,
                                granularity = granularity))
  res <- as.data.frame(t(matrix(unlist(httr::content(res)), nrow = 6)))
  res[['V1']] <- as.POSIXct(.subset2(res,1L), origin="1970-01-01")
  res
}

And the looping through the dates using for instance lapply
# Variables
product_id = "ETH-EUR"
granularity = 300
start_dates <- Sys.time() -  86400*(1:10)         # considering the last 10 days
end_dates <- Sys.time() -  86400*(0:9)

# Looping
res <- lapply(seq_along(end_dates),
              function (k) coinbaseGET(product_id, start_dates[k], end_dates[k], granularity))
res <- do.call(rbind, res)

With the result
str(res)
# 'data.frame': 2813 obs. of  6 variables:
#   $ V1: POSIXct, format: "2019-01-24 13:55:00" "2019-01-24 13:50:00" "2019-01-24 13:45:00" "2019-01-24 13:40:00" ...
# $ V2: num  103 102 102 103 102 ...
# $ V3: num  103 103 103 103 103 ...
# $ V4: num  103 102 103 103 102 ...
# $ V5: num  103 103 102 103 103 ...
# $ V6: num  9.63 18.11 30.07 80.98 12.75 ...

# Checking the dates
c(min(res$V1), max(res$V1))
# [1] "2019-01-14 15:00:00 CET" "2019-01-24 13:55:00 CET"]


text:
Q: nsis delete doesn't work I am trying to delete files from a directory.
The Delete commands appear to work but the files are not being deleted.
    Delete $fn

    IfErrors fail continue

    DetailPrint "Delete failed, file=$fn"
fail:
    MessageBox MB_ICONSTOP "Could not delete $fn"

    Abort
continue:
    DetailPrint "Deleted $fn"

I check the log after the run and it lists all files are deleted but when I check the folders, all the files are still there.
Is there any way to get a reason or message text after a delete executes?

A: Could you double check that the path is correct. Things like InstallDirRegKey might set $instdir to something other than your expected folder.
Make sure that you have the RequestExecutionLevel attribute in your script.
If it still is unable to delete, try running Process Monitor to see which file is failing and why...


text:
Q: app(): Argument #2 ($parameters) must be of type array Laravel I'm migrating from Laravel 7.1 to Laravel 8, after moving all related file and customizing the way of calling class (cause of differences of Laravel 7 and 8). Migration and seeding are successful, but I got this error when application run after login to admin. This is the error:
app(): Argument #2 ($parameters) must be of type array, Closure given, called in /media/mulyawansentosa/Data/Home Production/Project/Rahaya/hotelbaru/hotel/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php on line 149

and after lookup to the error pointed, here is content on Pipeline.php on line 149:
...
    if (is_callable($pipe)) {
        //This is line 149
        return $pipe($passable, $stack);
...

I really confused how to fix this?


text:
Q: React: How to use different layouts for different routes, when the layouts share components? In the following react app, I have a Layout component which contains a Navbar and a Footer (these are the same for all pages and thus they never need to be re-rendered) ...
<BrowserRouter>
   <Layout>
      <Navbar />
      <Footer />
      <Routes>
         <Route path="/" element={<Home />} />
         <Route path="/about" element={<About />} />
         <Route path="/contact" element={<Contact />} />
      </Routes>
   </Layout>
</BrowserRouter>

... and a Content and a Sidebar -- these depend on the page, and thus they are rendered from the page component, for example:
const About = () => {
    return (
       <>
          <Content>
             ...
          </Content>
          <Sidebar>
             ...
          </Sidebar>
       </>
   )
}

I want Contact to use a different layout: same Navbar and a Footer but no Sidebar and different dimensions for content (i.e. I cannot just not render the sidebar). Is there a way to do this without having to declare <Navbar/> and <Footer/> in multiple places?
The only way I see is to use nested layouts, i.e. a parent layout with navbar and footer, and then child layouts either with sidebar and smaller content or without sidebar and bigger content. However, I'd like to avoid nested layouts if possible.


text:
Q: Is **kwargs in Python eager or lazy? I'm trying to execute a Django query:
#att.name is a string
kwargs = {att.name : F('node__product__' + att.name) }
temps = Temp.objects.exclude(**kwargs)

I'm wondering if this is correct. All the examples I've seen so far use strings in the values,  but what if the value is a function, should I make the value a string, like this?
kwargs = {att.name : 'F('node__product__' + att.name)' }

Does the function in the value get executed eagerly in the argument list or does it wait until it's needed?

A: In python, expressions are always evaluated eagerly.  There is no lazy evaluation in python.  Some libraries get around the absence of this useful feature by allowing values that should be of some specific type to instead be a string, which it later evals.  You can declare some parts of a django model this way (so that you can declare mutually referential foreign key relationships), but django's query interface does not.  You wouldn't normally be able to use this kind of technique when a string is "expected", because you'd have no way to distinguish string values from strings that should be evaled.

A: Only the first one is correct:
kwargs = {att.name : F('node__product__' + att.name) }
temps = Temp.objects.exclude(**kwargs)

I don't understand how lazy/eager is related to this question.

A: Function arguments are evaluated before the function is called:
>>> def foo(x): return x
...:

>>> foo(sum(range(10)))
<<< 45

When you create a dict everything is evaluated at that moment:
>>> kwargs = {'key': sum(range(10))}

>>> kwargs
<<< {'key': 45}

So...
>>> def foo(**kwargs): return kwargs
...:

>>> foo(**kwargs)
<<< {'key': 45}

A: I am not sure if this question is because you are curious or if you are trying to find ways to load querys. So I will take a guess:
I would be using the Q() function and maybe load them on args to later use a for to set them on the Temp.objects.exclude, would be something like this:
def mylolfunc(self, *args,**kwargs):
    queryset = Q()
    for query in args:
        queryset |= query
return Temp.objects.filter(queryset)

Where query is a Q(att.name = F('node_product_' + att.name)) or a lot more of Q objects.
Here is the documentation if you want to check it out.
This query will not execute until you ask for information, so it would be lazy. by that I mean until you do something like
myquery = mylolfunc(*args)
myquery[0]  #-----> executes query here


text:
Q: How to prevent Durandal to (re)load a page on startup? Let's say I use standard SPA project with Durandal. Routing is with pushState: true.
And everything goes great.
However.
I want to generate the page fully prepared (i.e., generated on server (for instance, ASP.NET MVC)) (for SEO optimization, as well as to minimize traffic). I.e., the page generation is not a thing here: I just use server routing and generating appropriate page -- not a question.
(for instance, 'mydomain.com/about/' page).
And everything goes great so far as well.
But.
Now, when the page is loaded, Durandal obviously recognizes the 'about' page and starts loading it from server again (in case of caching, it does not, but if I need actual data, my services would still go to get the data, which is additional request+time).
So, the question is how I can prevent that reloading and simply bind the ViewModel to already existing HTML (which already rendered on server and is a part of currently loaded page)?
(just to clarify it one more time: the main thing is to prevent duplicate loading of the page on startup)
Thank you!

A: You could try customising the viewEngine; specifically, the createView method.
Effectively, you'd have to pre-check to see if your view is already loaded, then return a deferred promise which resolves your view; otherwise, return the default from createView. Something along these lines:
define([
    "jquery",
    "durandal/viewEngine"
],
function($, viewEngine) {
    var defaultCreateView = viewEngine.createView;

    viewEngine.createView = function(viewId) {
        if (viewId == "about") {
            // Some jQuery expression to find your view
            var $about = $("#about");

            // Emulate what createView would have done when the view was loaded
            $about.setAttribute("data-view", viewId)

            // Return the view element as a resolved promise
            return $.when($about);
        }

        // View is not loaded - defer to default createView implementation.
        return defaultCreateView.call(this, viewId);
    };
});


text:
Q: Entity Framework and MVC 3: The relationship could not be changed because one or more of the foreign-key properties is non-nullable I have been trying to use one View for updating an object and all its child collections (based on one-to-many relationships in an SQL Server database with an Entity Framework model).
It was suggested I should use AutoMapper, and I tried that and got it to work. (see Trying to use AutoMapper for model with child collections, getting null error in Asp.Net MVC 3 ).
But the solution is really hard to maintain. And when I try the simple one I had to begin with, using an entity object directly as the model (a "Consultant" object, the parent of all the child collections), I am able to get all the correct changed data back in the POST, and I can use UpdateModel to get them, including child collections. Simple. Granted, UpdateModel only worked after creating a custom model binder from a tip here at SO:
From my custom model binder:
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;

            return base.BindModel(controllerContext, bindingContext);
        }

        protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
        {
            ModelMetadata propertyMetadata = bindingContext.PropertyMetadata[propertyDescriptor.Name];
            propertyMetadata.Model = value;
            string modelStateKey = CreateSubPropertyName(bindingContext.ModelName, propertyMetadata.PropertyName);

            // Try to set a value into the property unless we know it will fail (read-only
            // properties and null values with non-nullable types)
            if (!propertyDescriptor.IsReadOnly)
            {
                try
                {
                    if (value == null)
                    {
                        propertyDescriptor.SetValue(bindingContext.Model, value);
                    }
                    else
                    {
                        Type valueType = value.GetType();

                        if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(EntityCollection<>))
                        {
                            IListSource ls = (IListSource)propertyDescriptor.GetValue(bindingContext.Model);
                            IList list = ls.GetList();

                            foreach (var item in (IEnumerable)value)
                            {
                                list.Add(item);
                            }
                        }
                        else
                        {
                            propertyDescriptor.SetValue(bindingContext.Model, value);
                        }
                    }

                }
                catch (Exception ex)
                {
                    // Only add if we're not already invalid
                    if (bindingContext.ModelState.IsValidField(modelStateKey))
                    {
                        bindingContext.ModelState.AddModelError(modelStateKey, ex);
                    }
                }
            }
        }

Here's my simple Edit POST method:
    [HttpPost]
    [ValidateInput(false)] //To allow HTML in description box
    public ActionResult Edit(int id, FormCollection collection)
    {

        Consultant consultant = _repository.GetConsultant(id);
        UpdateModel(consultant);
        _repository.Save();

        return RedirectToAction("Index");
    }

But after that UpdateModel worked. The problem is, at the next stage, when trying to call SaveChanges on the context, that fails. I'm getting this error:

The operation failed: The relationship
  could not be changed because one or
  more of the foreign-key properties is
  non-nullable. When a change is made to
  a relationship, the related
  foreign-key property is set to a null
  value. If the foreign-key does not
  support null values, a new
  relationship must be defined, the
  foreign-key property must be assigned
  another non-null value, or the
  unrelated object must be deleted.

I don't understand what is wrong. I'm seeing all the correct values in the Consultant object posted, I just can't save it to database. The route of AutoMapper in this case (although an interesting tool) is not working well, it's complicating my code immensely and making the application, which should be rather simple, a nightmare to maintain.
Can anyone offer any insight into why I'm getting this error and how to overcome it?
UPDATE:
Reading some posts here, I found one that seemed slightly related: How to update model in the database, from asp.net MVC2, using Entity Framework? . I don't know if it relates to this, but when I inspected the Consultant object after POST it seems this object itself has entitykey, but the individual items in a collection do not (EntityKeySet = null). Each item however does have the correct id. I don't pretend to understand any of this with the EntityKey, so please explain if it has any bearings on my issue, and if so, how to resolve it...
UPDATE 2:
I thought of something that might have something to do with my problems: The View is using a technique described by Steven Sanderson (see http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ ), and when debugging it seems to me as if UpdateModel has trouble matching the items in a collection in the View with the ones in the actual Consultant object. I'm wondering if this has to do with the indexing in this technique. Here's the helper from that code (I can't follow it very well myself, but it uses a Guid to create indexes, which might be the problem):
public static class HtmlPrefixScopeExtensions
    {
        private const string idsToReuseKey = "__htmlPrefixScopeExtensions_IdsToReuse_";

        public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName)
        {
            var idsToReuse = GetIdsToReuse(html.ViewContext.HttpContext, collectionName);
            string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : Guid.NewGuid().ToString();

            // autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync.
            html.ViewContext.Writer.WriteLine(string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, html.Encode(itemIndex)));

            return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, itemIndex));
        }

        public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix)
        {
            return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
        }

        private static Queue<string> GetIdsToReuse(HttpContextBase httpContext, string collectionName)
        {
            // We need to use the same sequence of IDs following a server-side validation failure,
            // otherwise the framework won't render the validation error messages next to each item.
            string key = idsToReuseKey + collectionName;
            var queue = (Queue<string>)httpContext.Items[key];
            if (queue == null)
            {
                httpContext.Items[key] = queue = new Queue<string>();
                var previouslyUsedIds = httpContext.Request[collectionName + ".index"];
                if (!string.IsNullOrEmpty(previouslyUsedIds))
                    foreach (string previouslyUsedId in previouslyUsedIds.Split(','))
                        queue.Enqueue(previouslyUsedId);
            }
            return queue;
        }

        private class HtmlFieldPrefixScope : IDisposable
        {
            private readonly TemplateInfo templateInfo;
            private readonly string previousHtmlFieldPrefix;

            public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix)
            {
                this.templateInfo = templateInfo;

                previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
                templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
            }

            public void Dispose()
            {
                templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;
            }
        }
    }

But then again, I wouldn't have thought this should be the problem since the hidden input contains the id in the value attribute, and I thought UpdateModel just looked at the name of the field to get Programs (the collection) and Name (the property), and then the value to the the id...? And then again there's seems to be some mismatch during update. Anyway, here's the generated html from FireBug also:

            <input type="hidden" value="1" name="Programs[cabac7d3-855f-45d8-81b8-c31fcaa8bd3d].Id" id="Programs_cabac7d3-855f-45d8-81b8-c31fcaa8bd3d__Id" data-val-required="The Id field is required." data-val-number="The field Id must be a number." data-val="true">
            <input type="text" value="Visual Studio" name="Programs[cabac7d3-855f-45d8-81b8-c31fcaa8bd3d].Name" id="Programs_cabac7d3-855f-45d8-81b8-c31fcaa8bd3d__Name">

Anyone know if this is the problem? And if so, how can I work around it to be able to easily update the collections with UpdateModel? (While still being able to add or remove items in the View before POST, which was the purpose of this technique to begin with).

A: It looks like there is a Parent entity that has a one to many relationship with your Consultant entity. When you change an attribute of the Consultant entity that is used as the ForeignKey for that relationship, Entity Framework sets the relevant field in the Parent entity to null to decouple the relationship. When that field is not nullable you'll get this error. Actually that error definition is surprisingly good, I've seen this problem with far more cryptic errors.
So, I recommend that you check the parent entity in the database, and proceed to a remedy from there (if you can change it to nullable all is well, if it is part of a different constraint -pk or suchlike- you'll have to fiddle with your object models). I'd ask you to post your entity models, but the chunk of text is intimidating as it is.

A: I think the error you are getting is related to: EF 4: Removing child object from collection does not delete it - why? You have created an orphan somewhere.

A: Yes it is related to HtmlPrefixScopeExtensions, but only because you are using Mvc Futures model binders.
In global.asax.cs comment out the line
Microsoft.Web.Mvc.ModelBinding.ModelBinderConfig.Initialize();

and retry: it will work ok !
The problem happens because the MVC futures model binder does not handle correctly this case. It converts ok the form data into your model when you submit the form, but it has a problem when filling the ModelState object when you use HtmlPrefixScopeExtensions to generate non incremental ids.
The model itself is correctly created from the form data. The problem lies inside ModelState which contains only the last value of the collection instead of all elements of the collection.
The strongly typed helper method - which renders the list - only select items which are in your Model property list AND in the matching ModelState entry which is converted into a list. So because there is only one item in the matching ModelState entry other list items get deselected.
This method called by the strongly typed helper code:
htmlHelper.GetModelStateValue(fullName, typeof(string[]))

returns only the last element of the list, because ModelState["Programs[cabac7d3-855f-45d8-81b8-c31fcaa8bd3d].List"].Value contains only the last element of the list.
This is a bug (or non supported scenario) in MVC3 Futures extensible model binders.


text:
Q: Deploy code directly to AWS EC2 instance using Github Actions As the title says I am trying to deploy my Laravel-Angular application directly from Github to AWS EC2 instance using Github Actions.
In my application there are 3 Angular 8+ projects which are needed to be build before deployment. Where as laravel does not need to be build.
The solutions that are available suggests to use AWS Elastic Beanstalk to deploy code. But, if that is to be done how to attach an elastic beanstalk to an existing instance is not clear enough.
Is there a way to deploy code to AWS EC2 without using Elastic Beanstalk?
Here is my Github Actions build.yml :
name: Build Develop Branch

on:
  push:
    branches: [ develop ]
  pull_request:
    branches: [ develop ]

jobs:
  build:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [14.x]

    steps:
    - name: Code Checkout
      uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v1
      with:
        node-version: ${{ matrix.node-version }}
    - name: App 1 npm install
      run: npm install
      working-directory: angular-app-1
    - name: App 1 Build
      run: npm run build:staging
      working-directory: angular-app-1
    - name: App 2 npm install
      run: npm install
      working-directory: angular-app-2
    - name: App 2 Build
      run: node node_modules/@angular/cli/bin/ng build --configuration=staging
      working-directory: angular-app-2
    - name: App 3 npm install
      run: npm install
      working-directory: angular-app-3
    - name: App 3 Build
      run: node node_modules/@angular/cli/bin/ng build --configuration=staging
      working-directory: angular-app-3

A: Real final edit
A year later, I finally got around to making the tutorial: https://github.com/Andrew-Chen-Wang/cookiecutter-django-ec2-github.
I found a Medium tutorial that also deserves some light if anyone wants to use Code Pipeline (there's a couple of differences; I store my files on GitHub while the Medium tutorial is on S3. I create a custom VPC that the other author doesn't).

Earlier final edit
AWS has finally made a neat tutorial for CodeDeploy w/ GitHub repository: https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorials-github-prerequisites.html take a look there and enjoy :)
Like the ECS tutorial, we're using Parameter Store to store our secrets. The way AWS previous wanted us to grab secrets was via a script in a bash script: https://aws.amazon.com/blogs/mt/use-parameter-store-to-securely-access-secrets-and-config-data-in-aws-codedeploy/
For example:
password=$(aws ssm get-parameters --region us-east-1 --names MySecureSQLPassword --with-decryption --query Parameters[0].Value)
password=`echo $password | sed -e 's/^"//' -e 's/"$//'`
mysqladmin -u root password $password

New edit (24 December 2020): I think I've nailed it. Below I pointed to Donate Anything for AWS ECS. I've moved to a self deploying setting. If you take a look at bin/scripts, I'm taking advantage of supervisord and gunicorn (for Python web development). But in context of EC2, you can simply point your AppSpec.yml to those scripts! Hope that helps everyone!
Before I start:
This is not a full answer. Not a complete walkthrough, but a lot of hints and some code that will help you with setting up certain AWS stuff like ALB and your files in your repo for this to work. This answer is more like several clues jumbled together from my sprint run trying to make ECS work last night.
I also don't have enough points to neither comment nor chat soo... here's the best thing I can offer.
Quick links (you should probably just skip these two points, though):

*

*Check this out: https://docs.aws.amazon.com/codedeploy/latest/userguide/instances-ec2-configure.html

*I don't have enough points to comment or chat... This won't be a full answer, as well, though, as I'm trying to first finish an ECS deploy from GH before moving on to EC2 from GH. Anyhow...

*One last edit: this will sound like a marketing ploy but a correct implementation with GitHub actions and workflow_dispatch is located at Donate Anything's GitHub repository. You'll find the same ECS work located below in there. Do note that I changed my GitHub action to use Docker Hub since it was free (and to me cheaper if you're going to use ECS since AWS ECR is expensive).

Edit: The ECS deployment works now. Will start working on the EC2 deployment soon.
Edit 2: I added Donate Anything repo. Additionally, I'm not sure if direct EC2 deployment, at least for me, is viable since install scripts would kinda be weird. However, I still haven't found the time to get to EC2. Again, if anyone is willing to share their time, please do so and contribute!
I do want to warn everyone that SECURITY GROUPS are very important. That clogged me for a long time, so make sure you get them right. In the ECS tutorial, I teach you how I do it.

Full non-full answer:
I'm working on this issue right now in this repo and another for ECS here using GitHub actions. I haven't started too far on the EC2 one, but the basic rundown for testing is this:
CRUCIAL

*

*You need to try and deploy from the AWS CLI first. This is because AWS Actions does not have a dedicated action for deploying to EC2 yet.

*Write down each of these statements. We're going to need them later for the GitHub action.

Some hints when testing this AWS setup:

*

*Before using CodeDeploy, you need an EC2 instance, an Application Load Balancer (you'll find it under Elastic Load Balancer), and a target group (which you create DURING the ALB setup). Go to target groups, right click on the group, and register your instance.

*To deploy from CodeDeploy, create a new application. Create a new deployment group. I think, for your setup, you should do the in-place deployment type rather than the Blue/Green deployment type.

*Finally, testing on the CLI, you should run the code you see here: https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorials-wordpress-deploy-application.html#tutorials-wordpress-deploy-application-create-deployment-cli

*

*Do note, you may want to start from here (using S3 as a location to store your latest code. You can delete it afterwards anyways, as I believe DELETE requests don't incur charges): https://docs.aws.amazon.com/codedeploy/latest/userguide/tutorials-wordpress-upload-application.html I personally don't know if that GitHub OAuth integration works. I tried once before (very amateur though, i.e. no clue what I was doing before) and nothing happened, soo... I'd just stick with that tutorial.

How your test rundown will look like:

*

*For me, for my ECS repo, I just went a full 10 hours straight trying to configure everything properly step by step like the GitHub action. For you, you should do the same. Imagine you're the code: figure out where you need to start from.

*Aha! I should probably figure out CodeDeploy first. Let's right an appspec.yaml file first! The appspec file is how CodeDeploy will work on the hooks for everything. Unfortunately, I'm current going through that problem here but that's because the EC2 and ECS syntax for AppSpec files are different. Luckily, EC2 doesn't have any special areas. Just get your files and hooks right. An example from my test:

version: 0.0
os: linux

files:
  - source: /
    destination: /code

hooks:
  BeforeInstall:
    - location: aws_scripts/install_dependencies
      timeout: 300
      runas: root
  ApplicationStop:
    - location: aws_scripts/start_server
      runas: root

The GitHub action:
What you'll need at minimum:
jobs:
  deploy:
    name: Deploy
    runs-on: ubuntu-latest

    steps:
    - name: Checkout
      uses: actions/checkout@v2

    - name: Configure AWS credentials
      uses: aws-actions/configure-aws-credentials@v1
      with:
        aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        # TODO Change your AWS region here!
        aws-region: us-east-2

The checking out of code is necessary to... well... get the code.
For the configuration of AWS credentials, you'll want to add AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to your GitHub secrets with a proper IAM credential. For this, I believe the only IAM role needed is for full CodeDeploy stuff.
Deploying the code:
This is when that test code that you should've tried before reaching this step is for. Now that your workflow is setup, let's paste the code from the CLI into your action.

    - name: Deploying with CodeDeploy
      id: a-task
      env:
        an-environment-variable: anything you want
      run: |
        echo "Your CLI code should be placed here"

Sorry if this was confusing, not what you're looking for, or wanted a complete tutorial. I, too, haven't actually gotten this to work, but it's also been awhile since I last tried, and the last time I tried, I didn't even know what an EC2 instance was... I just did a standalone EC2 instance and used rsync to transfer my files. Hopefully what I've written was several clues that can guide you very easily to a solution.
If you got it to work, please share it on here: https://github.com/Andrew-Chen-Wang/cookiecutter-django-ec2-gh-action so that no one else has to suffer the pain of AWS deployment...

A: First, you need to go through this tutorial on AWS to set up your EC2 server, as well as configure the Application and Deployment Group in CodeDeploy: Tutorial: Use CodeDeploy to deploy an application from GitHub
Then, you can use the following workflow in GitHub Actions to deploy your code on push. You essentially use the AWS CLI to create a new deployment. Store the AWS credentials for the CLI in GitHub Secrets.
Here is an example for deploying a Node app:
name: Deploy to AWS

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    name: Deploy AWS
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [12.x]
        app-name: ['your-codedeploy-application']
        deployment-group: ['your-codedeploy-deploy-group']
        repo: ['username/repository-name']

    steps:
      - uses: actions/checkout@v2

      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v1
        with:
          node-version: ${{ matrix.node-version }}

      - name: Install dependencies
        run: npm install

      - name: Build app
        run: npm run build

      - name: Install AWS CLI
        run: |
          curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
          unzip awscliv2.zip
          sudo ./aws/install --update

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-session-token: ${{ secrets.AWS_SESSION_TOKEN }}
          aws-region: us-east-1

      - name: Deploy to AWS
        run: |
          aws deploy create-deployment \
          --application-name ${{ matrix.app-name }} \
          --deployment-config-name CodeDeployDefault.OneAtATime \
          --deployment-group-name ${{ matrix.deployment-group }} \
          --description "GitHub Deployment for the ${{ matrix.app-name }}-${{ github.sha }}" \
          --github-location repository=${{ matrix.repo }},commitId=${{ github.sha }}

A:
Is there a way to deploy code to AWS EC2 without using Elastic Beanstalk?

I found a simple way to deploy to EC2 instance (or to any server that accepts rsync commands over ssh) using GitHub Actions.
I have a simple file in the repo's .github/workflows folder, which GitHub Actions runs to deploy to my EC2 instance whenever a push is made to my GitHub repo.
No muss, no fuss, no special incantations or Byzantine AWS configuration details.
File .github/workflows/pushtoec2.yml:
name: Push-to-EC2

on: push

jobs:
  deploy:
    name: Push to EC2 Instance
    runs-on: ubuntu-latest

    steps:
      - name: Checkout the code
        uses: actions/checkout@v1

      - name: Deploy to my EC2 instance
        uses: easingthemes/ssh-deploy@v2.1.5
        env:
          SSH_PRIVATE_KEY: ${{ secrets.EC2_SSH_KEY }}
          SOURCE: "./"
          REMOTE_HOST: "ec2-34-213-48-149.us-west-2.compute.amazonaws.com"
          REMOTE_USER: "ec2-user"
          TARGET: "/home/ec2-user/SampleExpressApp"

Details of the ssh deploy GitHub Action, used above.


text:
Q: TFS and referenced DLLs We are using TFS and VS 2010.
I have been working on a project that is using TFS as source control.
I have quite a few dlls that I have downloaded (such as log4net) and referenced in my project.
When a new programmer connected to TFS and got my project out of source control, it failed to build as it said it was missing all these referenced dlls.
What did I do wrong here? How can I include those referenced DLLs in source control.
Do I need to add all these dlls to my project before referencing them? when I referenced them, I just browsed to where they were on my file system.

A: I created a "ThirdPartyDLL" folder in my project folder in which I copied all the extra DLLs into it.  I then went into source explorer and added those DLLs into the team foundation server so I could be sure I'm using the correct versions of the DLLS for specific versions of my application (and so everyone else is on the exact same page as I am).
View - other windows - Source coontrol explorer
Right click project folder - add items to folder
You won't be able to select a specific folder with DLLs in it, but instead you can select the individual DLL files within the folder.  You will then see the "ThirdPartyDLL" folder appear in that window.
Once this is done, those dlls are in the team foundation source control.  Whenever a dev checks in, they will get the most current version of the DLLs.
Don't forget to remove the old references in your app and change them to your thirdpartydll folder.
I used to copy the DLLs into the bin folder but the issue I ran into was when the DLLs got upgraded.  Initially when my project was small it wasn't a big deal.  Now that I have multiple DLLs and applications that I created it became very difficult to maintain consistent versions of DLLs outside my project.  My best example is the licensing dll I purchased.  When this got upgraded all applications and libraries needed to be on the same version.  If I forgot one then I had weird issues or the application just stopped working.  Now that I have everything in one folder, I make the change once and everything is upgraded.
Hope this helps.

A: I've found the best practice for 3rd party DLLs is to create a "Library" folder in your sln/proj file structure and copy all the necessary DLLs into this local folder for reference.  You'll also want to make sure these DLLs are checked into source control.  This way, everyone who works on the project gets the exact same versions of all DLLs, and the reference paths are exactly the same.
Referencing 3rd party libs in a arbitrary download or install location will be problematic, because it will require all developers to maintain the same download structure for all DLLs.  Also, if everyone references DLLs outside of the project structure, it's harder to guarantee that everyone's on the same version.
The other option would be to have everyone install the DLLs into the GAC, but that can be a real pain too, especially with version management and deployment.

A: Andy's suggestion is a good one and I've used that in the past.  At my current job, we have a "reference" folder on a network share for all of us to build from.  We have a very fast network here, though and all developers are in a single office.  This solution won't work as well if you have a lot of remote developers or a slow network.

A: I've tried various methods for dealing with this and have settled on dropping required dll's in the bin folder and making sure they are included in the project for source control. I've heard people say this might not be a good idea but nobody has provided good reasoning for it and it's worked well for me.
My second choice would be to carve out some space on a network share and organize the various 3rd party dll's there. You can put your files in folders with verion numbers to keep things straight and everyone should have access to everything they need, so long as everyone uses the normal network paths as a reference.
Adding a seperate folder within the project is also workable but seems messy, since you end up with extra files that you don't want included in your release.


text:
Q: Effect of S-gate on one qubit of a combined(maybe entangled) state of 3 qubits Suppose I have a register(qs) of 3 qubits (first 2 being used solely for control, the last one is the input) . The first two control qubits are in the |+> state and the state of the 3rd input is unknown. Let it be a|0> + b|1>.
Now I apply CCNOT(qs[0],qs[1],qs[2]) so their combined state becomes 0.5(a,b,a,b,a,b,b,a) in Transposed matrix form [Please correct if I'm wrong here] . Now I apply S-gate to the 3rd qubit which transforms |1> -> i|1> .
I am unable to guess the state of the combined state of 'qs' now.
What I thought:

*

*One logic is to multiply every state by 'i' if it has the form|XY1> so the combined state becomes 0.5(a,ib,a,ib,a,ib,b,ia) [Transposed]

*Another logic is to find tensor product of (I x I x S) since I'm not changing the first 2 qubits. Performing this yields a different result which is 0.5(a,b,a,b,ia,ib,ib,ia) [Transposed] [Again, correct me if I'm wrong].

Which is the correct output after passing through S-gate (if any) ?

A: The first two qubits can't start in |+> state, since |+> is a single-qubit state. I assume that the starting state of the first two qubits in the register is 0.5 (|00> + |01> + |10> + |11>).
Both approaches are correct, because they are different ways to represent the same transformation. The first answer 0.5(a,ib,a,ib,a,ib,b,ia) [Transposed] is correct. Your second answer 0.5(a,b,a,b,ia,ib,ib,ia) [Transposed] seems to be obtained by multiplying by S x I x I, i.e., applying S gate on the first qubit instead of the third one.
The tensor product I x I x S can be calculated as tensor product of I x I (which is just a 4x4 identity matrix) and S. The result is an 8x8 matrix which consists of 16 copies of S matrix, multiplied by corresponding elements of I x I:
1 0 | 0 0 | 0 0 | 0 0
0 i | 0 0 | 0 0 | 0 0
- -   - -   - -   - -
0 0 | 1 0 | 0 0 | 0 0
0 0 | 0 i | 0 0 | 0 0
- -   - -   - -   - -
0 0 | 0 0 | 1 0 | 0 0
0 0 | 0 0 | 0 i | 0 0
- -   - -   - -   - -
0 0 | 0 0 | 0 0 | 1 0
0 0 | 0 0 | 0 0 | 0 i

If you multiply the state of the qubits by this matrix, you'll get the same answer as in the first approach.


text:
Q: MVC 5 Change the home page I have MVC5 App which is running locally as expected ,when I run it it automatically
open the home page ,I have additional folder in the view that I can navigate to them
by specify the path(e.g.  http://12.0.0.1:80/List/Index  ) now I want to change it that when I run the main project (http://12.0.0.1:80) it automatically open the page which is http://12.0.0.1:80/List/Index  ,how should I do that ?

A: Go into your RouteConfig.cs file in the App_Start folder of your project and change the default route constraints to controller="List" instead of controller="Home".

A: Use routes if you want the url to stay as http://12.0.0.1:80 but with the new content
Use redirect if you want the url to change to http://12.0.0.1:80/List/Index


text:
Q: CollectionView items are hidden behind top bar I have a messaging application, the problem is that the first messages are not visible, when I drag the collection view to see the top messages I can see them but when I release the finger, the collection view jumps back, hiding the first 5 messages that are at the top of the screen

As we can see from the image there is a message (actually are 5 messages at the top), however I have to drag the collection view to peek those messages. I thought that the size of the collection view is actually larger that the screen, however both the collectionView.frame.height and the UIScreen.main.bounds.height have the same height, is that ok? .
Here's the code that I use to setup the collection view:
 /// Function that configures the ChatViewController collection view
    private func configureCollectionView() {
        collectionView?.backgroundColor = Theme.current.chatGeneralBackground
        collectionView?.alwaysBounceVertical = true
        collectionView?.keyboardDismissMode = .onDrag

        // Register the chat cell and the loading cellx`
        collectionView?.register(ChatCell.self, forCellWithReuseIdentifier: chatCellIdentifier)
        collectionView?.register(LoadingCollectionViewCell.self, forCellWithReuseIdentifier: loadingCellIdentifier)

        // Initialize the original height of the collection view
        collectionViewOriginalHeight = collectionView.frame.height
    }

What am I doing wrong?

A: As of iOS 7.0, all views automatically go behind navigation bars, toolbars and tab bars to provide what Apple calls "context".
For example, if you don't want a view controller to go behind any bars, use this in viewWillAppear
override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        self.edgesForExtendedLayout = []
}

A: It seems to be the problem with constraints, if you are using custom navigation bar top constraints should be in reference to it. If using default navigation controller, you might need to give the top constraint to 44 from safe area.
However UIScreen.main.bounds.height consists of complete screen including the top navigation bar and 20 px of status bar. For collectionView.frame.height you need to minus these values.


text:
Q: how to log the ping action from 111.111.111.111 into /var/log/iptables.log? My os :centos 7.
yum remove firewalld
yum install  -y iptables
yum install -y iptables-services

I want to log all the ping from 111.1111.111.111 into iptables.log.
cat /etc/rsyslog.conf
kern.* /var/log/iptables.log
systemctl restart rsyslog

iptables -N LOGGING
iptables -A INPUT -j LOGGING
iptables -A INPUT -p icmp --icmp-type 8 --source 111.111.111.111 -j LOG
iptables -A INPUT -p icmp --icmp-type 8 --source 111.111.111.111 -j DROP
service iptables save
service iptables restart

Now to ping from 111.111.111.111 to my vps.
1.iptables -A INPUT -p icmp --icmp-type 8 --source 111.111.111.111 -j DROP can work.
ping 104.223.65.117
PING 104.223.65.117 (104.223.65.117) 56(84) bytes of data. ^C --- 104.223.65.117
ping statistics --- 23 packets transmitted, 0 received, 100% packet loss, time 22003ms

2.iptables -A INPUT -p icmp --icmp-type 8 --source 111.111.111.111 -j LOG can't work
cat /var/log/iptables.log

Nothing in it,how to log the ping action from 111.111.111.111 into /var/log/iptables.log ?
I got some material here:dmesg and iptables
dmesg reads from the kernel log buffer. Since iptables uses kernel logging
facility, that is where iptables log records appear in the first place.
There is no way you can make iptables log entries not appear in dmesg.

Does that means iptables log info can't be writtten into specified file?
Iptables log info can only be written into specified file this way:
dmesg > /var/log/iptables.log

or
dmesg >> /var/log/iptables.log

?
Is there another smart way to log automactically all info into /var/log/iptables.log?

A: Let's look at what your setup does:
iptables -N LOGGING

You create a new chain called LOGGING (which never gets any rules later on).
iptables -A INPUT -j LOGGING

All packets traversing the input chain jump to LOGGING. All rules after this rules will be ignored, as you never return from the LOGGING chain.
iptables -A INPUT -p icmp --icmp-type 8 --source 111.111.111.111 -j LOG

This rule is inserted after the above jump, and never executed.
iptables -A INPUT -p icmp --icmp-type 8 --source 111.111.111.111 -j DROP

After logging it, you want to drop the packet, meaning a reply won't be generated. Not sure if this is your intention.

So, don't do this. Clear all those rules with iptables -F INPUT, and then do instead just
iptables -A INPUT -p icmp --icmp-type 8 --source 111.111.111.111 -j LOG

Nothing else. Now do a ping and see if it shows up in the syslog (it does on my system).
If you really need to, you can add a rule to drop the ping afterwards.

A: The type of vps matter.
My vps'type  is openvz.
The log file will display by dmesg and not written automatically into custome log file,it is a bug in openvz.
To change my vps into a kvm vps, problem solved.


text:
Q: Maximum and minimum value in record Pascal So I want to print the maximum and minimum scores in various exam (as you can see in my maximum and minimum function)
How to print maximum and minimum value in maksimum and minimum function in my code, cause it always giving value of 0? anybody can help?
This is my code
program data_nilai_mhs;

uses crt;
type mhs = record
     nama,nim,tgl:string;
     tugas,prak,uas,uts:integer;
     akhir:real;
     end;

var dtmhs:array [1..35] of mhs;
    i,a,uts_max,uas_max,uts_min,uas_min  :integer;
    akhir_min,akhir_max:Real;
    grade:string;
    pilih:integer;

procedure input;

begin
  clrscr;
  writeln(' ');
  writeln(' MASUKKAN DATA NILAI MAHASISWA ');
  writeln(' ----------------------------- ');
  write  (' Jumlah Mahasiswa : '); readln(a);
  writeln;
  for i:=1 to a do
  begin
  with dtmhs[i] do
     begin
     writeln(' Data Ke-',i);
     writeln(' ----------- ');
     write  (' Nama      : '); readln (dtmhs[i].nama);
     write  (' NIM       : '); readln (dtmhs[i].nim);
     write  (' Tugas     : '); readln (dtmhs[i].tugas);
     write  (' UTS       : '); readln (dtmhs[i].uts);
     write  (' UAS       : '); readln (dtmhs[i].uas);
     write  (' Praktikum : '); readln (dtmhs[i].prak);
     writeln;
     readln;
     end;
  end;
end;

procedure tabel;
begin
  writeln(' ');
  writeln('|===============================================================================================================|');
  writeln('|                    DATA NILAI MAHASISWA                                                                       |');
  writeln('|===============================================================================================================|');
  writeln('|NO.|  NAMA MAHASISWA  |     NIM     |   TUGAS   |   UTS   |    UAS   |    PRAK    |      NA       |    GRADE   |');
  writeln('|---------------------------------------------------------------------------------------------------------------|');
  for i:=1 to a do
  begin
  gotoxy(1,i+6);
  writeln('|   |                  |             |           |         |          |            |               |            |');
  writeln('|===============================================================================================================|');
  end;
end;

// Fungsi Maksimum
function utsmax(): Integer;
var
    max:Integer;
begin
  max:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].uts > dtmhs[max].uts) then max := i;
  end;
  utsmax:=dtmhs[max].uts;
end;

function uasmax(): Integer;
var
    max:Integer;
begin
  max:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].uas > dtmhs[max].uas) then max := i;
  end;
  uasmax:=dtmhs[max].uas;
end;

function tugasmax(): Integer;
var
    max:Integer;
begin
  max:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].tugas > dtmhs[max].tugas) then max := i;
  end;
  tugasmax:=dtmhs[max].tugas;
end;

function prakmax(): Integer;
var
    max:Integer;
begin
  max:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].prak > dtmhs[max].prak) then max := i;
  end;
  prakmax:=dtmhs[max].prak;
end;

function namax(): Real;
var
    max:Integer;
begin
  max:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].akhir > dtmhs[max].akhir) then max := i;
  end;
  namax:=dtmhs[max].akhir;
end;

// Fungsi minimum
function utsmin(): Integer;
var
    min:Integer;
begin
  min:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].uts < dtmhs[min].uts) then min := i;
  end;
  utsmin:=dtmhs[min].uts;
end;

function uasmin(): Integer;
var
    min:Integer;
begin
  min:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].uas < dtmhs[min].uas) then min := i;
  end;
  uasmin:=dtmhs[min].uas;
end;

function tugasmin(): Integer;
var
    min:Integer;
begin
  min:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].tugas < dtmhs[min].tugas) then min := i;
  end;
  tugasmin:=dtmhs[min].tugas;
end;

function prakmin(): Integer;
var
    min:Integer;
begin
  min:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].prak < dtmhs[min].prak) then min := i;
  end;
  prakmin:=dtmhs[min].prak;
end;

function namin(): Real;
var
    min:Integer;
begin
  min:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].akhir < dtmhs[min].akhir) then min := i;
  end;
  namin:=dtmhs[min].akhir;
end;

function maksimum(): Integer;
var
  chose: Char;
begin
  clrscr;
  writeln('a. Nilai UTS      ');
  writeln('b. Nilai UAS      ');
  writeln('c. Nilai Tugas    ');
  writeln('d. Nilai Praktikum');
  writeln('e. Nilai Akhir    ');
  write  ('Masukkan Pilihan [a/b/c/d/e] ? : ');readln(chose);
  case chose of
    'a': writeln('Nilai terbesar UTS adalah ',utsmax());
    'b': writeln('Nilai terbesar UAS adalah ',uasmax());
    'c': writeln('Nilai terbesar Tugas  adalah ',tugasmax());
    'd': writeln('Nilai terbesar Praktikum adalah ',prakmax());
    'e': writeln('Nilai terbesar NA adalah ',namax():0:2);
  end;
end;

function minimum(): Integer;
var
  chose: Char;
begin
  clrscr;
  writeln('a. Nilai UTS      ');
  writeln('b. Nilai UAS      ');
  writeln('c. Nilai Tugas    ');
  writeln('d. Nilai Praktikum');
  writeln('e. Nilai Akhir    ');
  write  ('Masukkan Pilihan [a/b/c/d/e] ? : ');readln(chose);
  case chose of
    'a': writeln('Nilai terbesar UTS adalah ',utsmin());
    'b': writeln('Nilai terbesar UAS adalah ',uasmin());
    'c': writeln('Nilai terbesar Tugas  adalah ',tugasmin());
    'd': writeln('Nilai terbesar Praktikum adalah ',prakmin());
    'e': writeln('Nilai terbesar NA adalah ',namin():0:2);
  end;
end;

function rerata_uts():real;
var
    temp:real;
begin
    temp:=0;
    for i:=1 to a do begin
        temp:=temp+dtmhs[i].uts;
    end;
    rerata_uts:=temp/a;
end;

function rerata_uas():real;
var
    temp:real;
begin
    temp:=0;
    for i:=1 to a do begin
        temp:=temp+dtmhs[i].uas;
    end;
    rerata_uas:=temp/a;
end;

function rerata_tugas():real;
var
    temp:real;
begin
    temp:=0;
    for i:=1 to a do begin
        temp:=temp+dtmhs[i].tugas;
    end;
    rerata_tugas:=temp/a;
end;

function rerata_prak():real;
var
    temp:real;
begin
    temp:=0;
    for i:=1 to a do begin
        temp:=temp+dtmhs[i].prak;
    end;
    rerata_prak:=temp/a;
end;

function rerata_akhir():real;
var
    temp:real;
begin
    temp:=0;
    for i:=1 to a do begin
        temp:=temp+dtmhs[i].akhir;
    end;
    rerata_akhir:=temp/a;
end;

function rerata_semua(): real;
var
  chose: Char;
begin
  clrscr;
  writeln('a. Rata-rata UTS      ');
  writeln('b. Rata-rata UAS      ');
  writeln('c. Rata-rata Tugas    ');
  writeln('d. Rata-rata Praktikum');
  writeln('e. Rata-rata Akhir    ');
  write  ('Masukkan Pilihan [a/b/c/d/e] ? : ');readln(chose);
  case chose of
    'a': writeln('Nilai rata-rata UTS adalah ',rerata_uts():0:2);
    'b': writeln('Nilai rata-rata UAS adalah ',rerata_uas():0:2);
    'c': writeln('Nilai rata-rata Tugas  adalah ',rerata_tugas():0:2);
    'd': writeln('Nilai rata-rata Praktikum adalah ',rerata_prak():0:2);
    'e': writeln('Nilai rata-rata NA adalah ',rerata_akhir():0:2);
  end;
end;
procedure output;
var
  chose: Integer;
 begin
 clrscr;
 tabel;
 for i:=1 to a do
 begin
   dtmhs[i].akhir := (0.1*dtmhs[i].tugas) + (0.3*dtmhs[i].uts) + (0.3*dtmhs[i].uas) + (0.3*dtmhs[i].prak);
   with dtmhs[i] do
   begin
        if (akhir>=0)  and (akhir < 20) then grade:='E' else
        if (akhir>=20) and (akhir < 40) then grade:='D' else
        if (akhir>=40) and (akhir < 60) then grade:='C' else
        if (akhir>=60) and (akhir < 80) then grade:='B' else
        grade:='A' ;
   end;
 end;
 for i:=1 to a do
 begin
   with dtmhs[i] do
   begin
     gotoxy(3,i+6); writeln(i);
     gotoxy(9,i+6); writeln(nama);
     gotoxy(26,i+6);writeln(nim);
     gotoxy(43,i+6);writeln(tugas);
     gotoxy(56,i+6);writeln(uts);
     gotoxy(69,i+6);writeln(uas);
     gotoxy(82,i+6);writeln(prak);
     gotoxy(95,i+6);writeln(akhir:0:2);
     gotoxy(108,i+6);writeln(grade);
   end;
 end;
 readln;
end;

begin
  // repeat
  clrscr;
  writeln('|     SELAMAT DATANG DI PROGRAM ENTRI MAHASISWA     |');
  writeln('|===================================================|');
  writeln('|                                                   |');
  writeln('| 1. Input Data Mahasiswa                           |');
  writeln('| 2. Tampilan Data Mahasiswa                        |');
  writeln('| 3. Nilai Alpro Terbesar                           |');
  writeln('| 4. Nilai Alpro Terkecil                           |');
  writeln('| 5. Rata-rata Nilai Alpro                          |');
  writeln('| 6. Keluar                                         |');
  writeln('|===================================================|');
  writeln(' ');
  write  ('Masukkan Pilihan [1/2/3/4/5/6] ? : ');readln(pilih);
      case pilih of
      1 : input;
      2 : output;
      3 : maksimum;
      4 : minimum;
      5 : rerata_semua();
      6 : writeln('Terima kasih');
      end;
  // until pilih=6;
  write('Ingin menampilkan apa[2/3/4/5/6] ?');readln(pilih);
  case pilih of
    2: output;
    3: maksimum;
    4: minimum;
    5: rerata_semua();
    6: writeln('Terima kasih');
  end;
end.

*Edit
This is my code so far
I can get the everything except for the namax, namin and rerata_akhir function. They all return 0 value instead of the calculated formula below
dtmhs[i].akhir := (0.1*dtmhs[i].tugas) + (0.3*dtmhs[i].uts) + (0.3*dtmhs[i].uas) + (0.3*dtmhs[i].prak);
How can I do with this?Thanks in advance
program data_nilai_mhs;

uses crt;
type mhs = record
     nama,nim,tgl:string;
     tugas,prak,uas,uts:integer;
     akhir:real;
     end;

var dtmhs:array [1..35] of mhs;
    i,a,uts_max,uas_max,uts_min,uas_min  :integer;
    akhir_min,akhir_max:Real;
    grade:string;
    pilih:integer;

procedure input;

begin
  clrscr;
  writeln(' ');
  writeln(' MASUKKAN DATA NILAI MAHASISWA ');
  writeln(' ----------------------------- ');
  write  (' Jumlah Mahasiswa : '); readln(a);
  writeln;
  for i:=1 to a do
  begin
  with dtmhs[i] do
     begin
     writeln(' Data Ke-',i);
     writeln(' ----------- ');
     write  (' Nama      : '); readln (dtmhs[i].nama);
     write  (' NIM       : '); readln (dtmhs[i].nim);
     write  (' Tugas     : '); readln (dtmhs[i].tugas);
     write  (' UTS       : '); readln (dtmhs[i].uts);
     write  (' UAS       : '); readln (dtmhs[i].uas);
     write  (' Praktikum : '); readln (dtmhs[i].prak);
     writeln;
     readln;
     end;
  end;
end;

procedure tabel;
begin
  writeln(' ');
  writeln('|===============================================================================================================|');
  writeln('|                    DATA NILAI MAHASISWA                                                                       |');
  writeln('|===============================================================================================================|');
  writeln('|NO.|  NAMA MAHASISWA  |     NIM     |   TUGAS   |   UTS   |    UAS   |    PRAK    |      NA       |    GRADE   |');
  writeln('|---------------------------------------------------------------------------------------------------------------|');
  for i:=1 to a do
  begin
  gotoxy(1,i+6);
  writeln('|   |                  |             |           |         |          |            |               |            |');
  writeln('|===============================================================================================================|');
  end;
end;

// Fungsi Maksimum
function utsmax(): Integer;
var
    max:Integer;
begin
  max:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].uts > dtmhs[max].uts) then max := i;
  end;
  utsmax:=dtmhs[max].uts;
end;

function uasmax(): Integer;
var
    max:Integer;
begin
  max:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].uas > dtmhs[max].uas) then max := i;
  end;
  uasmax:=dtmhs[max].uas;
end;

function tugasmax(): Integer;
var
    max:Integer;
begin
  max:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].tugas > dtmhs[max].tugas) then max := i;
  end;
  tugasmax:=dtmhs[max].tugas;
end;

function prakmax(): Integer;
var
    max:Integer;
begin
  max:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].prak > dtmhs[max].prak) then max := i;
  end;
  prakmax:=dtmhs[max].prak;
end;

function namax(): Real;
var
    max:Integer;
begin
  max:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].akhir > dtmhs[max].akhir) then max := i;
  end;
  namax:=dtmhs[max].akhir;
end;

// Fungsi minimum
function utsmin(): Integer;
var
    min:Integer;
begin
  min:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].uts < dtmhs[min].uts) then min := i;
  end;
  utsmin:=dtmhs[min].uts;
end;

function uasmin(): Integer;
var
    min:Integer;
begin
  min:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].uas < dtmhs[min].uas) then min := i;
  end;
  uasmin:=dtmhs[min].uas;
end;

function tugasmin(): Integer;
var
    min:Integer;
begin
  min:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].tugas < dtmhs[min].tugas) then min := i;
  end;
  tugasmin:=dtmhs[min].tugas;
end;

function prakmin(): Integer;
var
    min:Integer;
begin
  min:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].prak < dtmhs[min].prak) then min := i;
  end;
  prakmin:=dtmhs[min].prak;
end;

function namin(): Real;
var
    min:Integer;
begin
  min:=1;
  for i := 2 to a do
  begin
    if (dtmhs[i].akhir < dtmhs[min].akhir) then min := i;
  end;
  namin:=dtmhs[min].akhir;
end;

function maksimum(): Integer;
var
  chose: Char;
begin
  clrscr;
  writeln('a. Nilai UTS      ');
  writeln('b. Nilai UAS      ');
  writeln('c. Nilai Tugas    ');
  writeln('d. Nilai Praktikum');
  writeln('e. Nilai Akhir    ');
  write  ('Masukkan Pilihan [a/b/c/d/e] ? : ');readln(chose);
  case chose of
    'a': writeln('Nilai terbesar UTS adalah ',utsmax());
    'b': writeln('Nilai terbesar UAS adalah ',uasmax());
    'c': writeln('Nilai terbesar Tugas  adalah ',tugasmax());
    'd': writeln('Nilai terbesar Praktikum adalah ',prakmax());
    'e': writeln('Nilai terbesar NA adalah ',namax():0:2);
  end;
end;

function minimum(): Integer;
var
  chose: Char;
begin
  clrscr;
  writeln('a. Nilai UTS      ');
  writeln('b. Nilai UAS      ');
  writeln('c. Nilai Tugas    ');
  writeln('d. Nilai Praktikum');
  writeln('e. Nilai Akhir    ');
  write  ('Masukkan Pilihan [a/b/c/d/e] ? : ');readln(chose);
  case chose of
    'a': writeln('Nilai terbesar UTS adalah ',utsmin());
    'b': writeln('Nilai terbesar UAS adalah ',uasmin());
    'c': writeln('Nilai terbesar Tugas  adalah ',tugasmin());
    'd': writeln('Nilai terbesar Praktikum adalah ',prakmin());
    'e': writeln('Nilai terbesar NA adalah ',namin():0:2);
  end;
end;

function rerata_uts():real;
var
    temp:real;
begin
    temp:=0;
    for i:=1 to a do begin
        temp:=temp+dtmhs[i].uts;
    end;
    rerata_uts:=temp/a;
end;

function rerata_uas():real;
var
    temp:real;
begin
    temp:=0;
    for i:=1 to a do begin
        temp:=temp+dtmhs[i].uas;
    end;
    rerata_uas:=temp/a;
end;

function rerata_tugas():real;
var
    temp:real;
begin
    temp:=0;
    for i:=1 to a do begin
        temp:=temp+dtmhs[i].tugas;
    end;
    rerata_tugas:=temp/a;
end;

function rerata_prak():real;
var
    temp:real;
begin
    temp:=0;
    for i:=1 to a do begin
        temp:=temp+dtmhs[i].prak;
    end;
    rerata_prak:=temp/a;
end;

function rerata_akhir():real;
var
    temp:real;
begin
    temp:=0;
    for i:=1 to a do begin
        temp:=temp+dtmhs[i].akhir;
    end;
    rerata_akhir:=temp/a;
end;

function rerata_semua(): real;
var
  chose: Char;
begin
  clrscr;
  writeln('a. Rata-rata UTS      ');
  writeln('b. Rata-rata UAS      ');
  writeln('c. Rata-rata Tugas    ');
  writeln('d. Rata-rata Praktikum');
  writeln('e. Rata-rata Akhir    ');
  write  ('Masukkan Pilihan [a/b/c/d/e] ? : ');readln(chose);
  case chose of
    'a': writeln('Nilai rata-rata UTS adalah ',rerata_uts():0:2);
    'b': writeln('Nilai rata-rata UAS adalah ',rerata_uas():0:2);
    'c': writeln('Nilai rata-rata Tugas  adalah ',rerata_tugas():0:2);
    'd': writeln('Nilai rata-rata Praktikum adalah ',rerata_prak():0:2);
    'e': writeln('Nilai rata-rata NA adalah ',rerata_akhir():0:2);
  end;
end;
procedure output;
var
  chose: Integer;
 begin
 clrscr;
 tabel;
 for i:=1 to a do
 begin
   dtmhs[i].akhir := (0.1*dtmhs[i].tugas) + (0.3*dtmhs[i].uts) + (0.3*dtmhs[i].uas) + (0.3*dtmhs[i].prak);
   with dtmhs[i] do
   begin
        if (akhir>=0)  and (akhir < 20) then grade:='E' else
        if (akhir>=20) and (akhir < 40) then grade:='D' else
        if (akhir>=40) and (akhir < 60) then grade:='C' else
        if (akhir>=60) and (akhir < 80) then grade:='B' else
        grade:='A' ;
   end;
 end;
 for i:=1 to a do
 begin
   with dtmhs[i] do
   begin
     gotoxy(3,i+6); writeln(i);
     gotoxy(9,i+6); writeln(nama);
     gotoxy(26,i+6);writeln(nim);
     gotoxy(43,i+6);writeln(tugas);
     gotoxy(56,i+6);writeln(uts);
     gotoxy(69,i+6);writeln(uas);
     gotoxy(82,i+6);writeln(prak);
     gotoxy(95,i+6);writeln(akhir:0:2);
     gotoxy(108,i+6);writeln(grade);
   end;
 end;
 readln;
end;

begin
  // repeat
  clrscr;
  writeln('|     SELAMAT DATANG DI PROGRAM ENTRI MAHASISWA     |');
  writeln('|===================================================|');
  writeln('|                                                   |');
  writeln('| 1. Input Data Mahasiswa                           |');
  writeln('| 2. Tampilan Data Mahasiswa                        |');
  writeln('| 3. Nilai Alpro Terbesar                           |');
  writeln('| 4. Nilai Alpro Terkecil                           |');
  writeln('| 5. Rata-rata Nilai Alpro                          |');
  writeln('| 6. Keluar                                         |');
  writeln('|===================================================|');
  writeln(' ');
  write  ('Masukkan Pilihan [1/2/3/4/5/6] ? : ');readln(pilih);
      case pilih of
      1 : input;
      2 : output;
      3 : maksimum;
      4 : minimum;
      5 : rerata_semua();
      6 : writeln('Terima kasih');
      end;
  // until pilih=6;
  write('Ingin menampilkan apa[2/3/4/5/6] ?');readln(pilih);
  case pilih of
    2: output;
    3: maksimum;
    4: minimum;
    5: rerata_semua();
    6: writeln('Terima kasih');
  end;
end.

A: In function maksimum(): integer; you print uts_max, uas_max and akhir_max, but you never assign any value to these variables.
In the for i := 2 to a do loop you want to write
if (dtmhs[i].uas > uas_max) then uas_max := dtmhs[i].uas;

Similar changes to the other values.
In function maksimum(): integer; you attempt to initialize the uts_min, uas_min and akhir_min like this:
dtmhs[1].uts := uts_min;
dtmhs[1].uas := uas_min;
dtmhs[1].akhir := akhir_min;

which is opposite to what you need to do. You should instead do
uts_min := dtmhs[1].uts;
uas_min := dtmhs[1].uas;
akhir_min := dtmhs[1].akhir;

and also change the search for min values like this:
if (dtmhs[i].uas < uas_min) then uas_min := dtmhs[i].uas;

again, same for the other values.