text:
Q: Compile time/macro swap of endianess of float in c99 I have some floats (IEEE-754) that I want to initialize. The floats are fetched by another device (automagically) which runs big endian where I am using little endian and I can't change that.
Normally I would just swap with some built in function, but they are all run-time functions. I'd perfer not having to have an init() function just to swap endianess and it would be great if I could use it for const initializations also.
Something that result in this would be perfect:
#define COMPILE_TIME_SWAPPED_FLOAT(x) (...)
const float a = COMPILE_TIME_SWAPPED_FLOAT(1.0f);
Any great ideas?

A:
Compile time/macro swap of endian-ness of float in c99

OP has other problem with using  "reverse" float as a float
A local variable of type float encoding the "reverse" endian floating point value cannot certainly be initialized as a float.  Many of the values in reverse byte order would correspond to a Not-A-Number (NAN) in the local float.  The assignment may not be stable (bit pattern preserving). It could be:
// not a good plan
float f1 = some_particulate_not_a_number_bit_pattern;
float f2 = some_other_particulate_not_a_number_bit_pattern;

Instead the local "reversed" endian float should just be a uint32_t, 4-byte structure/union or 4-byte array initialized in some way with a float.
// Demo of why a reversed `float` can fail
// The Not-a-numbers bit to control signaling NaN vs. quiet NaN isn't certainly preserved.

int main(void) {
  for (;;) {
    union {
      int32_t i32;
      int32_t u32;
      float f;
    } x,y;
    x.i32 = rand();
    y.f = x.f;
    if (x.u32 ^ y.u32) {
      // If bit pattern preserved, this should never print
      //                                 v-------+---- biased exponent max (NaN)
      //                                 |-------|v--- signaling/quiet bit
      // On my machine output is always x1111111 1?xxxxxx xxxxxxxx xxxxxxxx
      printf("%08x\n",   (unsigned) x.u32);
      printf("%08x\n\n", (unsigned) y.u32);
    }
  }
}

Output
7f8181b1
7fc181b1
...

The below uses a compound literal to meet OP's goal.  First initialize a union's float member with the desired float.  Then extract it byte-by-byte from its uint8_t member (per desired endian) to initialize a new  compound literal's uint8_t array member.  Then extract the uint32_t.  Works for local variables.
#include <stdint.h>
#include <stdio.h>

typedef uint32_t float_reversed;

typedef union  {
  uint8_t u8[4];
  float_reversed u32;
  float f;
} endian_f;

#define ENDIAN_FN(_f,_n)  ( (endian_f){.f=(_f)}.u8[(_n)] )
#define ENDIAN_F(_f) ((endian_f){ \
    ENDIAN_FN(_f,3), ENDIAN_FN(_f,2), \
    ENDIAN_FN(_f,1), ENDIAN_FN(_f,0)}.u32)

void print_hexf(void *f) {
  for (size_t i=0; i<sizeof f; i++) {
    printf("%02X", ((unsigned char *)f)[i]);
  }
  puts("");
}

int main(void) {
  float f1 = 1.0f;
  print_hexf(&f1);

  float_reversed f1r = ENDIAN_F(f1);
  print_hexf(&f1r);
  float_reversed f2r = ENDIAN_F(1.0);
  print_hexf(&f2r);
}

Output
0000803F
3F800000
3F800000

A: I'd say having the preprocessor to swap bytes of some non byte variable isn't possible.
The preprocessor does not know about data types and their representation on byte-level.

A: If the endian reversal code is available to be inlined then any half decent optimizing compiler will work out the reversed value at compile time.
Taking the reversal code from https://stackoverflow.com/a/2782742/2348315 :
inline float ReverseFloat( const float inFloat )
{
   float retVal;
   char *floatToConvert = ( char* ) & inFloat;
   char *returnFloat = ( char* ) & retVal;

   // swap the bytes into a temporary buffer
   returnFloat[0] = floatToConvert[3];
   returnFloat[1] = floatToConvert[2];
   returnFloat[2] = floatToConvert[1];
   returnFloat[3] = floatToConvert[0];

   return retVal;
}

And using it in away that compiler can see all the details:
float reversed10(){
  const float reversed = ReverseFloat(10.0f);
  return reversed;
}

Compiles to:
reversed10():
        vmovss  xmm0, DWORD PTR .LC0[rip]
        ret
.LC0:
        .long   8257

with GCC 7.1 with -O2 enabled.
You can try other compilers over here:
https://godbolt.org/g/rFmJGP


text:
Q: Is it possible to only expand the width of a responsive image? I have a responsive image slider in my header but i would like for it to only expand the width when the viewport changes. A fixed height centered image that shows more when the viewport widens. A bit like opening curtains. Is this possible? Tried to google but not sure how to word it properly.
I'm using the carousel from bootstrap with this added code:
header{
    margin: 0;
    max-height: 507px;
    max-width: 1920px;
    -webkit-box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.25);
    -moz-box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.25);
    box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.25);
    border-bottom: 7px solid #9ccb43;
}

#header-carousel{
    width: 100%;
    margin: 0;
    max-height: 500px;
}

    .carousel-inner{
        max-height: 500px;
    }

and my html:

Isoleren Loont

A: As I say, yes, this is possible. I did very quick example, but I believe, you can improve this code
Use background-image
JSFiddle demo

redpajama_set_name: RedPajamaStackExchange


text:
Q: Logstash timezone configuration I'm using logstash quite a while, but now I have the problem with timezones.
Logstash is reading a logfile which has the time in UTC. So in summersaving I'm UTC+2.
If I configure Kibana to use UTC, it shows the log files to hours before the current time.
Example timezone = "user"
Log.txt 2013-06-22 08:29:10 TestLog
Kibana 2013-06-22 08:29:10 TestLog
Current Time: 10:29

Example timezone = "UTC"
Log.txt 2013-06-22 08:29:10 TestLog
Kibana 2013-06-22 06:29:10 TestLog
Current time: 08:29

Because of this issue I can't use the stream.
Thanks for your answer

A: You can adjust the timezone and date of the incoming event with the 'date' filter.  This is two different things.
"Adjust the date" means the filter is capable of changing the event's timestamp to some value derived from the @message, overwriting the default value of when it arrived.  Useful for replaying logs.
"Adjust the timezone" shifts the time according to the delta between system tz and the value set in this data filter.
You state you are in UTC+2, and the event comes from UTC.  Assuming a tag of "mytag":
filters {
  date {
    tags => ["mytag"]
    timezone => "utc"
    add_tag => ["tz_utc"]
  }
}

I added a tag to make it easier to filter for it in kibana, etc.


text:
Q: How to solve gradle transitive dependency with credentials? I'm currently has two Android project, SDK and App. In SDK there's several dependencies stores in my private artifactory, which need credentials to access. I put the credential in SDK's gradle file.
In App layer, when I try to pull the SDK and transitively solve the dependencies, I can't get access to those dependencies. It's like gradle don't even know to look up these dependencies in my artifactory. Btw, other dependencies in SDK which pull from maven or Jcenter works just fine.
So how could I solve this thing? These dependencies are third party so I can't put them on public. Please help me about it if you know how. Very thanks to you.

A: You have to add the repository with credential also in your app module.
 repositories {
        jcenter()
        maven {
            credentials {
                username 'xxxx'
                password 'xxxxx'
            }
            url 'xxxx'
        }

Since some dependencies are located in the private repository you have to add this url to the repository block in the module.
It can't know the credentials.


text:
Q: IIS 6 ignores Web.config authorization settings Context:

*

*IIS 6 on Windows 2003 Server

*ASP.NET 3.5 sp1

*C# Web Application running from a virtual directory

There are a few files that I would like not to serve. For example, there's a hibernate.cfg.xml in the root directory that should not be accessible. There are also log files in a logs directory. On the local development server (Visual Studio 2008) The NHibernate config file can be protected in a couple of ways through Web.config:
<location path="hibernate.cfg.xml">
    <system.web>
      <authorization>
        <deny users="?"/>
        <deny users="*"/>
      </authorization>
    </system.web>
</location>

OR
<httpHandlers>
...
    <add path="*.cfg.xml" verb="*" type="System.Web.HttpForbiddenHandler" />
</httpHandlers>

The logs in a different directory can be protected through another Web.config file:
<?xml version="1.0"?>
<configuration>
  <system.web>
    <authorization>
      <deny users="*"/>
    </authorization>
  </system.web>
</configuration>

None of these work when the application is compiled using aspnet_compiler.exe and deployed to an IIS 6 server. No errors in the logs. The files are readable to anyone. The application is compiled and installed using MSBuild as follows:
<AspNetCompiler Force="true" Debug="true" PhysicalPath="$(DeploymentTempPath)\$(DeploymentAppName)" TargetPath="$(DeploymentPath)\$(DeploymentAppName)" VirtualPath="/$(DeploymentAppName)" />

How do I make IIS 6 respect the authorization rules in Web.config.
Note: assume that I can't move these files outside of the deployment directory.

A: It looks like IIS does not forward the request for .xml or .txt files to ASP.NET, so it has no chance to apply its authorization controls.
To work around this, I had to do the following (from this forum post):

*

*From IIS Console, open properties of the virtual directory of my app.

*Virtual Directory > Configuration

*Add new handler for extension ".xml" using the ASP.NET filter (c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll in my case)

*All verbs. Uncheck both "Script engine" and "Verify that file exists".

Is there any way to do this from within Web.config?

A: Try this:
<location path="hibernate.cfg.xml">
    <system.web>
      <authorization>
        <deny users="?"/>
        <deny users="*"/>
      </authorization>
    </system.web>
</location>

A: Static files such as .jpg, .xml and .pdf are by default handled directly by the kernel mode http.sys driver. Unless you've mapped these extensions to ASP.NET they will never hit the ASP.NET pipeline and hence the authorisation mechanism within ASP.NET.

A: To force static files such as .xml to be processed by .NET on .NET 2.0/3.5/4.0 and IIS6, do the following:
1) Add the entries for.xml (or other file type) to IIS as described above (IIS6 website properties, Home Directory, Configuration)
2) in web.config add the location for the restricted directory or file
<location path="directory_or_file_name">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
</location>

3) Add the following to the httpHandlers section:
<add path="*.xml" verb="*" type="System.Web.StaticFileHandler" validate="true" />

This will force .NET to only serve .xml files as specified in the <location> tag to authenticated users.

A:
URL Authorization: The URLAuthorizationModule class is
  responsible for URL authorization on
  Windows 2003. This mechanism uses the
  URL namespace to store user details
  and access roles. The URL
  authorization is available for use at
  any time. You store authorization
  information in a special XML file in a
  directory. The file contains tags to
  allow or deny access to the directory
  for specific users or groups. Unless
  specified, the tags also apply to
  subdirectories.

You need to do the following:
<deny users="?"/>
<deny users="*"/>

The wild card entry "?" means that no one else will be able to gain access to this directory.


text:
Q: how to solve type redefinition error in this C program I'm a new C programmer,
the program I was writing has to return 0 if the points are colinear, otherwise it has to return 1.
I've split the code in .h and .c.
This is the code: [geometry.c]
struct point {
    int x;
    int y;
} p1;

struct point {
    int x;
    int y;
} p2;

struct point {
    int x;
    int y;
} p3;

int colinear(struct point* p1, struct point* p2, struct point* p3) {

    if (((p1->x - p2->x)* (p1->y - p2->y) == ((p3->y - p2->y) * (p1->x - p2->x))))

    return 0;

    else
        return 1;
        }

and: [geometry.h]
#ifndef geometry.h
#define geometry.h
#endif
#include "geometry.c"

extern int colinear(struct point *p1, struct point *p2, struct point *p3);

Using the debugger:
"C2011: 'point': 'struct' type redefinition".
Where are the errors?

A: No Need to define 3 times
struct point {
    int x;
    int y;
} p1;

struct point {
    int x;
    int y;
} p2;

struct point {
    int x;
    int y;
} p3;

define only once, and create variables as you wish.
struct point {
    int x;
    int y;
};
struct point p1,p2,p3;

A: The other answer addresses the problem well.  (i.e. why the code resulted in multiply defined compiler error.) But as a possible enhancement to your corrected code, the following is a related construct using an array of a typedef struct. This may make some of what you need to do a little easier to pass around and manipulate the struct member values:
typedef struct {
   int x;
   int y;
} point_s;

point_s p[3];

This effectively allows the prototype:
int colinear(struct point* p1, struct point* p2, struct point* p3) {

To be refactored into:
int colinear(point_s *p) { //where p is an pointer to 3 instances of point_s

Usage example:
int main(void)
{
    point_s p[3] = {{4,6}, {-2, 5}, {-0.4, 15}};

    int result = colinear(p);

    return 0;
}

int colinear(point_s *p)
{
    if (((p[0].x - p[1].x)* (p[0].y - p[1].y) == ((p[2].y - p[1].y) * (p[0].x - p[1].x))))
    {
        return 0;
    }

    else
    {
        return 1;
    }
}


text:
Q: 'Unless' in hypothetical constructions I have been told that 'unless' can't be used in hypothetical clauses as follows:
Unless Ann had studied hard, she would have failed the exam.
My question is, why is using 'unless' in the conditional clause above unacceptable?

A: You're correct, that sentence

*

*?Unless Ann had studied hard, she would have failed the exam.
is not fully grammatical. OK, that happens. What makes it interesting is that, normally, unless means if not. And if you use if ... not instead of unless, everything works just fine:

*

*If Ann had not studied hard, she would have failed the exam.
But it clearly doesn't work with unless very well. The effect of this sentence on a native speaker is telling. The meaning is reasonable but the parsing sends up a flag. Frankly, I don't know why. It must be something about putting the negation and the if together in one lexical item, but why it's flagged here is very puzzling.

A: Because we think of a hypothetical situation as not happening yet, or hard to happen and for this reason, no one can be sure whether the situation can happen or not, "unless" doesn't feel appropriate to use for describing the hypothetical situation.

A: Here is what Cambridge says:

We don't use unless for things that we know to be true:
You won't be able to get a ticket for the match unless you're prepared to pay a lot of money for it. (The speaker doesn't know if
you're prepared to pay a lot of money for a ticket.)
I don't know what we would have done if we hadn't seen you. (We did see you.)
Not: I don't know what we would have done unless we'd seen you.

I think Collins Cobuild also gets unless right in this regard by using will not and not would not. In other words, it's not approving it for cases that are contrary to fact.
unless (conjunction)

CONJUNCTION You use unless to introduce the only circumstances in
which an event you are mentioning will not take place or in which
a statement you are making is not true.
Unless you are trying to lose weight to please yourself, it's going to be tough to keep your motivation level high.

Unless Ann had studied hard, she would have failed the exam sounds at least odd or even wrong to many—we just don't often hear it, even though we were probably never taught an explicit rule.

A: Rare does not mean ungrammatical. If we take the example to have the construction

unless ... (had done something), ... (preterite modal auxiliary + have
done something)

where 'preterite modal auxilialy' = could, would, should...
then it is possible to find examples of its use that seem quite natural.

But, even as she prayed, she feared her prayers were vain; if Savoie
and Cary had come out through the hall, she would already have seen
them; and there was no stairway leading directly from their quarters
to the ground . Unless they had leaped from a window, they
could not have reached it. (Steamboat Gothic; Frances Parkinson Keyes; New York: Julian Messner, Inc.1952)
Unless you had seen it you would never have believed hair could be so curly! It was no wonder that even strangers called the
children "Curlytops." (Curlytops at Uncle Frank's Ranch; Garis, Howard
Roger; 1918)
And if the man lived, Conan felt certain that he was riding along the
road somewhere ahead of him . Unless he had intended going
into Argos he would never have taken the eastward road in the
first place. (Hour of the Dragon; Robert E. Howard; 1977)
The 1933 Act, permitting the creation of federal savings and loan
associations, contained a provision respecting local taxation which
stated in part: "... no State... shall impose any tax on such federal
associations or their franchise, capital, reserves, surplus, loans, or
income greater than that imposed by such authority on other similar
local mutual or cooperative thrift and home financing institutions. "
48 Stat. 134 . Unless Congress had recognized that States
taxing national bank shares were free, in spite of 5219, to exempt
their own savings and loan associations from local taxation, it
would have used language similar or referring to 5219, as it did in other federal statutes creating different types of thrift
institutions. (US Supreme Court 365 U.S. 467; MICHIGAN NAT. BANK v.
MICHIGAN 1961)
Unless Congress had exercised its power over interstate commerce to bring about allocation of available frequencies and to
regulate the employment of transmission equipment the result would
have been an impairment of the effective use of these facilities by
anyone. (US Supreme Court 309 U.S. 470; FEDERAL COMMUNICATIONS COM'N
v. SANDERS BROS. RADIO STATION 1940)
Unless she had fled faster than Atalanta, William must have been but a
few minutes in reaching her immediate neighborhood. (A Dunnet
Shepherdess - Sarah Orne Jewett Text Project)
Unless he had taken the senses into account, he would not have argued immutability from sensible mutations not being seen.  (Galileo Galilei | Calendars - Webexhibits)
Unless he had created them in righteousness and true holiness, he would himself have been the author of sin, and would by this means have possessed no right either to punish them to the praise of his justice, or to save them to the praise of his mercy. (The Wesley Center Online: Arminius' Theological Sentiments)


text: Q: Widehat symbol at the same height of the text I use \widehat to indicate estimated values in a document. Then I need to prepare a table in which for instance I show in the superscript section of the table: * is a superscript for dimensionless quantities, widehat is used to indicate estimated quantities, etc. and I want the widehat symbol to stay right at the same height of the text in the adjacent column of the table in this case. How can I do?


text:
Q: Statistical Inference - Finite Population Correction I am studying for an exam in Quantitative Analysis and I am looking through past exam papers (here's a link the exercise I'm referring to: http://i62.tinypic.com/2cz1nqh.jpg).
I understand all of the questions but I have a slight issue: it asks for standard error for proportion which is √pq/n and then asks what correction factor would apply if n/N > 0.05 (5%). In this case the fpc, or finite population correction factor would apply: √(N-n)/(N-1).
Now, in the next part it asks you to calculate proportion of all employees who would participate in the dental plan. This is 137/200 employees. This means that n/N is greater than 5%. So would I apply the fpc here and how should I do it?

A: The estimated standard error would be $\sqrt{\frac{\hat p \cdot (1-\hat p) }{n}}$, if N would be much larger than n. And if $\frac{n}{N} >0.05$, then estimated standard error would be $\sqrt{\frac{\hat p \cdot (1-\hat p) }{n}\cdot \frac{N-n}{N-1}}$. I agree with you.
Ad 2(b)
$\frac{137}{200}=\frac{x}{n}$ and not $\frac{n}{N}$. Here you have to assume, that N is much larger than n. N is not given.


text:
Q: Сжатие картинки с сохранением пропорций Как сделать умное сжатие картинки при загрузке? То есть максимальный размер фото 200x200, я загружаю 360x500 — фото уменьшается и становится не 200x200, а, например, 200x179, чтобы не испортить фотографию.
Можно пример кода загрузки, или ссылку на сам скрипт.

A: Вот PHP класс как раз вам надо

class Picture {

    private $image_file;

    public $image;
    public $image_type;
    public $image_width;
    public $image_height;

    public function __construct($image_file) {
        $this->image_file=$image_file;
        $image_info = getimagesize($this->image_file);
        $this->image_width = $image_info[0];
        $this->image_height = $image_info[1];
        switch($image_info[2]) {
            case 1: $this->image_type = 'gif'; break;//1: IMAGETYPE_GIF
            case 2: $this->image_type = 'jpeg'; break;//2: IMAGETYPE_JPEG
            case 3: $this->image_type = 'png'; break;//3: IMAGETYPE_PNG
            case 4: $this->image_type = 'swf'; break;//4: IMAGETYPE_SWF
            case 5: $this->image_type = 'psd'; break;//5: IMAGETYPE_PSD
            case 6: $this->image_type = 'bmp'; break;//6: IMAGETYPE_BMP
            case 7: $this->image_type = 'tiffi'; break;//7: IMAGETYPE_TIFF_II (порядок байт intel)
            case 8: $this->image_type = 'tiffm'; break;//8: IMAGETYPE_TIFF_MM (порядок байт motorola)
            case 9: $this->image_type = 'jpc'; break;//9: IMAGETYPE_JPC
            case 10: $this->image_type = 'jp2'; break;//10: IMAGETYPE_JP2
            case 11: $this->image_type = 'jpx'; break;//11: IMAGETYPE_JPX
            case 12: $this->image_type = 'jb2'; break;//12: IMAGETYPE_JB2
            case 13: $this->image_type = 'swc'; break;//13: IMAGETYPE_SWC
            case 14: $this->image_type = 'iff'; break;//14: IMAGETYPE_IFF
            case 15: $this->image_type = 'wbmp'; break;//15: IMAGETYPE_WBMP
            case 16: $this->image_type = 'xbm'; break;//16: IMAGETYPE_XBM
            case 17: $this->image_type = 'ico'; break;//17: IMAGETYPE_ICO
            default: $this->image_type = ''; break;
        }
        $this->fotoimage();
    }

    private function fotoimage() {
        switch($this->image_type) {
            case 'gif': $this->image = imagecreatefromgif($this->image_file); break;
            case 'jpeg': $this->image = imagecreatefromjpeg($this->image_file); break;
            case 'png': $this->image = imagecreatefrompng($this->image_file); break;
        }
    }

    public function autoimageresize($new_w, $new_h) {
        $difference_w = 0;
        $difference_h = 0;
        if($this->image_width image_height imageresize($this->image_width, $this->image_height);
        }
        else {
            if($this->image_width > $new_w) {
                $difference_w = $this->image_width - $new_w;
            }
            if($this->image_height > $new_h) {
                $difference_h = $this->image_height - $new_h;
            }
            if($difference_w > $difference_h) {
                $this->imageresizewidth($new_w);
            }
            elseif($difference_w imageresizeheight($new_h);
            }
            else {
                $this->imageresize($new_w, $new_h);
            }
        }
    }

    public function percentimagereduce($percent) {
        $new_w = $this->image_width * $percent / 100;
        $new_h = $this->image_height * $percent / 100;
        $this->imageresize($new_w, $new_h);
    }

    public function imageresizewidth($new_w) {
        $new_h = $this->image_height * ($new_w / $this->image_width);
        $this->imageresize($new_w, $new_h);
    }

    public function imageresizeheight($new_h) {
        $new_w = $this->image_width * ($new_h / $this->image_height);
        $this->imageresize($new_w, $new_h);
    }

    public function imageresize($new_w, $new_h) {
        $new_image = imagecreatetruecolor($new_w, $new_h);
        imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $new_w, $new_h, $this->image_width, $this->image_height);
        $this->image_width = $new_w;
        $this->image_height = $new_h;
        $this->image = $new_image;
    }

    public function imagesave($image_type='jpeg', $image_file=NULL, $image_compress=100, $image_permiss='') {
        if($image_file==NULL) {
            switch($this->image_type) {
                case 'gif': header("Content-type: image/gif"); break;
                case 'jpeg': header("Content-type: image/jpeg"); break;
                case 'png': header("Content-type: image/png"); break;
            }
        }
        switch($this->image_type) {
            case 'gif': imagegif($this->image, $image_file); break;
            case 'jpeg': imagejpeg($this->image, $image_file, $image_compress); break;
            case 'png': imagepng($this->image, $image_file); break;
        }
        if($image_permiss != '') {
            chmod($image_file, $image_permiss);
        }
    }

    public function imageout() {
        imagedestroy($this->image);
    }

    public function __destruct() {

    }

}

Пример использование

 public function makeImage($image) {

        $width = 200; // Максимальная ширина картинки
        $height = 200; // Максимальная высота картинки
        $new_image = new Picture($image);
        if($new_image->image_width > $width)
            $new_image->imageresizewidth($width);
        if($new_image->image_height > $height)
            $new_image->imageresizeheight($height);

        $new_image->imagesave($new_image->image_type, $image);
        $new_image->imageout();
    }


text:
Q: Do we need injection (Dagger2 for example) between Model and Presenter in MVP structure? I know we can implement Dagger 2 to inject between Presenter and View layer, but do we need injection between M and P? Can you explain the reason?

A: Everything depends on the situation but generaly each layer should be independent of the others, so Presenter shouldn't be dependent on Model. So generally yes.
If you examine this very good example:
https://medium.com/@nurrohman/a-simple-android-apps-with-mvp-dagger-rxjava-and-retrofit-4edb214a66d7#.89j5gtafn
you will see that NetworkService (in this example is a class of Model layer) is injected into HomePresenter (a class of Presenter layer) by Dagger.
This example also confirms it:
https://github.com/grandstaish/hello-mvp-dagger-2


text:
Q: Firestore: what's difference between Firebase.firestore and FirebaseFirestore.getInstance() What's difference between Firebase.firestore and FirebaseFirestore.getInstance()?
When do I want to update DB, which one is appropriate for this purpose?
And when I want to check the extracted result value from Firestore.
if I log it, it only prints the object name not result in string value that is contained in the object.
db.collection("users").whereEqualTo("userId", userId?.toInt())
  .get()
  .addOnSuccessListener {
    documents - >
      for (document in documents) {
        Log.d("결과", documents.toString())
      }
  }

If I print this, it throws result like below:
com.google.firebase.firestore.QuerySnapshot@b38fd47b
I want to read fields and values of this QuerySnapshot, how can I do this?

share code and error:
var db = Firebase.firestore
        val stDocRef = db.collection("users").whereEqualTo("userId", userId?.toInt())
        db.runTransaction { transaction ->
            transaction.update(stDocRef,"name", "new name")
            null
        }.addOnSuccessListener {  Log.d("결과", "Transaction success!") }

A: You are trying to print the QuerySnapshot Object , Hence it is giving you the Memory Address of the Object. To overcome this, try to print document.data as show in the below example.

According to docs use Firebase.firestore to initialize the db

val db = Firebase.firestore // Access a Cloud Firestore instance from your Activity

Refer the following links for CRUD operation in firebase with kotlin :

*

*https://firebase.google.com/docs/database/android/read-and-write

*https://firebase.google.com/docs/firestore/query-data/get-data

A:
What's the difference between Firebase.firestore and FirebaseFirestore.getInstance()?

None. Both are creating the same instance. The first instance is created by using an extension property of the Firebase class, while the second one is creating an instance using the getInstance() method of the FirebaseAuth. The latter one is also a singleton.

If I log it, it only prints the object name, not the result string value which is contained in the object.

That's the expected behavior, since your calling toString() on the documents object:
Log.d("결과", documents.toString())
//

The documents that comes from the lambda expression is actually a document of type QuerySnapshot which:

contains the results of a query. It can contain zero or more DocumentSnapshot objects.

So you have to loop through the documents, as you already and get the data according to the type of the field:
.addOnSuccessListener { documents - >
    for (document in documents) {
      Log.d("결과", document.getString("userId"))
      //
    }
}

If you however want to run a transaction, which in my opinion doesn't make any sense, since you're only reading data, then please check the documentation, or my answer from the following post:

*

*Can I make firestore transaction that reads from firestore, but write on the realtime database?


text:
Q: tftp config for autoconfiguration of 2 different switches I currently have a Cisco switch (CBS-350) which is autoconfigured with isc-dhcp-server and atftpd on Ubuntu 18.04.
This is the dhcpd config:
subnet 192.168.0.0 netmask 255.255.255.0 {
      option routers 192.168.0.1;
      range 192.168.0.100 192.168.0.120;
      option tftp-server-name "192.168.0.1";
      option bootfile-name "config/cisco-switch1.cfg"; }

I would like to have another different switch model on the same subnet that I would like also to be autoconfigured. Any idea on how I can achieve this?
Both switches will not be running at the same time. I just would like to have each switches take the good autoconfig file.
Thanks for your help

A: Typically you would autoconfig enough of a device configlet to allow it to be manageable - VLANs, SNMP, username/password, routing, etc.  You may not need to push a full config.  Then the 'template' of this baseline config could be used for multiple devices, especially if DHCP allocated IPs are an option.
THEN you would use some 2nd stage configuration management system to push the remaining, device-specific parts.
Otherwise you have to start doing some distinguishing identifiers (eg. MAC address or serial number) and use that to map a device to a waiting config on the file server.

A: I've found that using a SubClass might be an option:
      subclass "Vendor-Class" "CiscoPnP" {
          option bootfile-name "config/cisco-switch1.cfg";
      }

Unfortunately, both switches have the same Vendor-Class (CiscoPnP) so I cannot use this to distinguished them.


text:
Q: If $f:[a, b] \to \mathbb{R}$ is a continuous function, s.t. $f(x)>0$ for all $x$, prove that there exists $c >0$, s.t. $f(x) > c$ for all $x$. If $f:[a, b] \to \mathbb{R}$ is a continuous function, s.t. $f(x)>0$ for all $x$, prove that there exists $c >0$, s.t. $f(x) > c$ for all x.
I am not sure how to approach this problem, I have tried proving this by using IVT but no results so far.

A: $f$ continuous on $[a,b]$, $f$ attains its minimum , i.e there is a $m \in [a,b]$   such that $f(x)  \ge f(m) \gt 0.$
For $c:= (1/2)f(m)$ we have:
$f(x) \gt c,$ for $x\in [a,b].$


text:
Q: A/B Testing with apache and mod_rewrite Tried searching for this but my google-fu is lacking today.
So I have 2 versions of site, in
/var/www/vhosts/testa.mydomain.com/httpdocs and
/var/www/vhosts/testb.mydomain.com/httpdocs

where each documentroot is pretty much a complete site overhaul, and I want to do A/B (multivariate) testing to see which site performs better.
Googling last week I saw suggestions on doing this time based (even & odd seconds), but because the site is a basket site (or perhaps even a basket-case!), I don't want to flit between 2 different processing scenarios mid-transaction.
So I thought it would be good to serve from testa if client ip address last octet was even, and from testb if last octet was odd. We could then at least gain some metrics on how many people abandoned the basket as too unwieldy in different versions of the site.
I'm pretty sure that a bunch of RewriteCond lines based on %{REMOTE_ADDR} will do it, but I'm pretty hopless at mod_rewrite.
users would visit test.mydomain.com, and be should served from one or the other DocumentRoot's evenly, not seeing testa or testb in their url, but we could log each variant's performance.
Any kindly guru's able to advise ?
TIA
David
Update: I can set up testa.mydomain and testb.mydomain as subdomains via virtual hosts if that would help any.

A: Option 1 (Redirects) add one of these to both domains
Place on even number site (testb.mydomain.com)
RewriteEngine On
RewriteCond %{REMOTE_ADDR} [13579]$
RewriteRule .* http://testa.mydomain.com/$1 [R=301,L]

Place on odd number site (testa.mydomain.com)
RewriteEngine On
RewriteCond %{REMOTE_ADDR} [02468]$
RewriteRule .* http://testb.mydomain.com/$1 [R=301,L]

Option 2 (subfolders NOT subdomains)
RewriteEngine On
#direct to EVEN SITE
RewriteCond %{REMOTE_ADDR} [02468]$
RewriteRule (.*) /testa.mydomain.com/$1 [L]

#direct to ODD SITE
RewriteCond %{REMOTE_ADDR} [13579]$
RewriteRule (.*) /testb.mydomain.com/$1 [L]

A: Google now offers A/B/N testing through its Google Analytics Experiments Interface / API.
The article about this is written at: https://blog.crazyegg.com/2015/06/02/ab-testing-google-analytics/
You can read more about it from Google at:
https://developers.google.com/analytics/solutions/experiments
So, one possibility would be to put Google's tracking in both versions of your site and let Google handle redirects of your site (you can make redirects be equal at all times or take Multi-Armed bandits approach).

A: Have you tried the load balancer?
You can set up load balancing rules with the file rules.xml or using code (Rule and RuleChain). There should be an example system in /balancer, which shows you how to write rules.
See also
http://tomcat.apache.org/tomcat-5.5-doc/balancer-howto.html#Sample_Configuration
http://onjava.com/pub/a/onjava/2004/03/31/clustering.html


text:
Q: Query metadata for NTFS special files as unprivileged user? From an unprivileged user context, how can I query the size of the NTFS special files?
The size is the most important piece of metadata for me, but if I could get everything that is typically found in WIN32_FIND_DATA I would not mind it.
The NTFS special files I mean are (among others): $Mft, $MftMirr, $LogFile, $BadClus et cetera.
In order to open the MFT, I'd have to acquire certain privileges, open the volume and then parse the MFT. So that's out.
Also it seems to be impossible to open these files by name (for the majority of them), which precludes NtQueryInformationFile() and GetFileInformationByHandle(). Or maybe there is a combination of flags I haven't tried and it is possible to open them somehow for querying the file information?
Last but not least I don't get these files returned when using the respective Win32 APIs (FindFirstFile() et. al.), nor with NtQueryDirectoryFile() nor by using IRP_MN_QUERY_DIRECTORY directly.

Yes, I understand that I can effectively get the size of the MFT using FSCTL_GET_NTFS_VOLUME_DATA, but that's just one of these special files.

A: on ntfs volume we can enumerate all file records with FSCTL_GET_NTFS_FILE_RECORD. unfortunatelly format of FileRecordBuffer is undocumented/undeclared in windows headers. but this is common ntfs structs. buffer begin with NTFS_RECORD_HEADER (base class) after which will be several NTFS_ATTRIBUTE records. partial and custom definitions:
union NTFS_FILE_ID
{
    LONGLONG IndexNumber;

    struct
    {
        LONGLONG MftRecordIndex : 48;
        LONGLONG SequenceNumber : 16;
    };
};

struct NTFS_RECORD_HEADER
{
    enum {
        FILE = 'ELIF',
        INDX = 'XDNI',
        BAAD = 'DAAB',
        HOLE = 'ELOH',
        CHKD = 'DKHC'
    } Type;
    USHORT UsaOffset;
    USHORT UsaCount;
    USN Usn;
};

struct NTFS_FILE_RECORD_HEADER : public NTFS_RECORD_HEADER
{
    USHORT SequenceNumber;
    USHORT LinkCount;
    USHORT AttributesOffset;
    USHORT Flags;
    ULONG BytesInUse;
    ULONG BytesAllocated;
    ULONGLONG BaseFileRecord;
    USHORT NextAttributeNumber;

    enum{
        flgInUse = 1, flgDirectory = 2
    };
};

struct NTFS_ATTRIBUTE
{
    enum ATTRIBUTE_TYPE {
        StandardInformation = 0x10,
        AttributeList = 0x20,
        FileName = 0x30,
        ObjectId = 0x40,
        SecurityDescriptor = 0x50,
        VolumeName = 0x60,
        VolumeInformation = 0x70,
        Data = 0x80,
        IndexRoot = 0x90,
        IndexAllocation = 0xa0,
        Bitmap = 0xb0,
        ReparsePoint = 0xc0,
        EAInformation = 0xd0,
        EA = 0xe0,
        PropertySet = 0xf0,
        LoggedUtilityStream = 0x100,
        StopTag = MAXDWORD
    } Type;
    ULONG Length;
    BOOLEAN Nonresident;
    UCHAR NameLength;
    USHORT NameOffset;
    USHORT Flags;// 1 = Compresed
    USHORT AttributeNumber;
};

struct NTFS_RESIDENT_ATTRIBUTE : public NTFS_ATTRIBUTE
{
    ULONG ValueLength;
    USHORT ValueOffset;
    USHORT Flags;
};

struct NTFS_NONRESIDENT_ATTRIBUTE : public NTFS_ATTRIBUTE
{
    LONGLONG LowVcn;
    LONGLONG HighVcn;
    USHORT RunArrayOffset;
    UCHAR CompressionUnit;
    UCHAR Unknown[5];
    LONGLONG AllocationSize;
    LONGLONG DataSize;
    LONGLONG InitializedSize;
    LONGLONG CompressedSize;
};

struct NTFS_ATTRIBUTE_LIST
{
    NTFS_ATTRIBUTE::ATTRIBUTE_TYPE Type;
    USHORT Length;
    UCHAR NameLength;
    UCHAR NameOffset;
    LONGLONG LowVcn;
    LONGLONG FileReferenceNumber : 48;
    LONGLONG FileReferenceNumber2 : 16;
    USHORT AttributeNumber;
    USHORT Unknown[3];
};

struct NTFS_STANDARD_ATTRIBUTE
{
    LONGLONG CreationTime;
    LONGLONG ChangeTime;
    LONGLONG LastWriteTime;
    LONGLONG LastAccessTime;
    ULONG FileAttributes;
    ULONG Unknown[3];
    ULONG QuotaId;
    ULONG SecurityId;
    ULONGLONG QuotaChange;
    USN Usn;
};

struct NTFS_FILENAME_ATTRIBUTE
{
    NTFS_FILE_ID DirectoryId;
    LONGLONG CreationTime;
    LONGLONG ChangeTime;
    LONGLONG LastWriteTime;
    LONGLONG LastAccessTime;
    LONGLONG AllocationSize;
    LONGLONG DataSize;
    ULONG FileAttributes;
    ULONG EaSize;
    UCHAR FileNameLength;// in symbols !!
    UCHAR NameType;
    WCHAR FileName[];

    enum {
        systemName , longName, shortName, systemName2
    };
};

the code of enumeration all files can look like:
inline ULONG BOOL_TO_ERROR(BOOL f)
{
    return f ? NOERROR : GetLastError();
}

ULONG QFMD(PCWSTR szVolumeName)
{
    HANDLE hVolume = CreateFile(szVolumeName, FILE_GENERIC_READ, FILE_SHARE_VALID_FLAGS, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);

    if (hVolume == INVALID_HANDLE_VALUE)
    {
        return GetLastError();
    }

    ULONG cb, BytesReturned;
    NTFS_VOLUME_DATA_BUFFER nvdb;

    ULONG err = BOOL_TO_ERROR(DeviceIoControl(hVolume, FSCTL_GET_NTFS_VOLUME_DATA, 0, 0, &nvdb, sizeof(nvdb), &BytesReturned, 0));

    if (err == NOERROR)
    {
        NTFS_FILE_RECORD_INPUT_BUFFER nfrib;

        cb = FIELD_OFFSET(NTFS_FILE_RECORD_OUTPUT_BUFFER, FileRecordBuffer[nvdb.BytesPerFileRecordSegment]);

        PNTFS_FILE_RECORD_OUTPUT_BUFFER pnfrob = (PNTFS_FILE_RECORD_OUTPUT_BUFFER)alloca(cb);

        // search for maximum valid FileReferenceNumber
        LONG a = 0, b = MAXLONG, o;
        do
        {
            nfrib.FileReferenceNumber.QuadPart = o = (a + b) >> 1;

            err = BOOL_TO_ERROR(DeviceIoControl(hVolume, FSCTL_GET_NTFS_FILE_RECORD,
                &nfrib, sizeof nfrib, pnfrob, cb, &BytesReturned, 0));

            err ? b = o : a = o + 1;

        } while(a < b);

        nfrib.FileReferenceNumber.QuadPart--;

        DbgPrint("MftRecordCount=%u\n", nfrib.FileReferenceNumber.LowPart);

        union {
            PVOID FileRecordBuffer;
            PBYTE pb;
            NTFS_RECORD_HEADER* pnrh;
            NTFS_FILE_RECORD_HEADER* pnfrh;
            NTFS_ATTRIBUTE* pna;
            NTFS_RESIDENT_ATTRIBUTE* pnra;
            NTFS_NONRESIDENT_ATTRIBUTE* pnaa;
        };

        NTFS_FILE_ID nfi;
        UNICODE_STRING us = { sizeof (nfi), sizeof (nfi), (PWSTR)&nfi };
        OBJECT_ATTRIBUTES oa = { sizeof(oa), hVolume, &us };

        do
        {
            FileRecordBuffer = pnfrob->FileRecordBuffer;

            if (err = BOOL_TO_ERROR(DeviceIoControl(hVolume, FSCTL_GET_NTFS_FILE_RECORD,
                &nfrib, sizeof nfrib, pnfrob, cb, &BytesReturned, 0)))
            {
                break;
            }

            // are really file
            if (
                pnrh->Type != NTFS_RECORD_HEADER::FILE ||
                !(pnfrh->Flags & NTFS_FILE_RECORD_HEADER::flgInUse) ||
                pnfrh->BaseFileRecord
                )
            {
                continue;
            }

            ULONG FileAttributes = INVALID_FILE_ATTRIBUTES;
            ULONGLONG FileSize = 0;

            nfi.MftRecordIndex = pnfrob->FileReferenceNumber.QuadPart;
            nfi.SequenceNumber = pnfrh->SequenceNumber;

            pb += pnfrh->AttributesOffset;

            for( ; ; )
            {
                NTFS_FILENAME_ATTRIBUTE* pnfa;
                NTFS_STANDARD_ATTRIBUTE* pnsa;

                switch (pna->Type)
                {
                case NTFS_ATTRIBUTE::StopTag:
                    goto __end;

                case NTFS_ATTRIBUTE::FileName:

                    pnfa = (NTFS_FILENAME_ATTRIBUTE*)RtlOffsetToPointer(pnra, pnra->ValueOffset);

                    if (pnfa->NameType == NTFS_FILENAME_ATTRIBUTE::longName)
                    {
                        //DbgPrint("<< %.*S\n", pnfa->FileNameLength, pnfa->FileName);
                    }
                    break;

                case NTFS_ATTRIBUTE::StandardInformation:

                    pnsa = (NTFS_STANDARD_ATTRIBUTE*)RtlOffsetToPointer(pnra, pnra->ValueOffset);
                    FileAttributes = pnsa->FileAttributes;
                    break;

                case NTFS_ATTRIBUTE::Data:
                    FileSize += pna->Nonresident ? pnaa->DataSize : pnra->ValueLength;
                    break;
                }

                pb += pna->Length;
            }

__end:;

            //HANDLE hFile;
            //IO_STATUS_BLOCK iosb;

            //NTSTATUS status = NtOpenFile(&hFile, FILE_READ_ATTRIBUTES, &oa, &iosb, FILE_SHARE_VALID_FLAGS,
            //  FILE_OPEN_REPARSE_POINT| FILE_OPEN_BY_FILE_ID | FILE_OPEN_FOR_BACKUP_INTENT);

            //if (0 <= status)
            //{
            //  NtClose(hFile);
            //}

        } while (0 <= (nfrib.FileReferenceNumber.QuadPart = pnfrob->FileReferenceNumber.QuadPart - 1));

    }

    CloseHandle(hVolume);

    return err;
}

some NTFS System Files, but this list already old, exist more system files. if want concrete system file query need assign it number to NTFS_FILE_RECORD_INPUT_BUFFER. little changed code for query sys files only:
ULONG QFMD(PCWSTR szVolumeName)
{
    HANDLE hVolume = CreateFile(szVolumeName, FILE_GENERIC_READ, FILE_SHARE_VALID_FLAGS, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);

    if (hVolume == INVALID_HANDLE_VALUE)
    {
        return GetLastError();
    }

    ULONG cb, BytesReturned;
    NTFS_VOLUME_DATA_BUFFER nvdb;

    ULONG err = BOOL_TO_ERROR(DeviceIoControl(hVolume, FSCTL_GET_NTFS_VOLUME_DATA, 0, 0, &nvdb, sizeof(nvdb), &BytesReturned, 0));

    if (err == NOERROR)
    {
        NTFS_FILE_RECORD_INPUT_BUFFER nfrib;

        nfrib.FileReferenceNumber.QuadPart = 0x30;

        cb = FIELD_OFFSET(NTFS_FILE_RECORD_OUTPUT_BUFFER, FileRecordBuffer[nvdb.BytesPerFileRecordSegment]);

        PNTFS_FILE_RECORD_OUTPUT_BUFFER pnfrob = (PNTFS_FILE_RECORD_OUTPUT_BUFFER)alloca(cb);

        union {
            PVOID FileRecordBuffer;
            PBYTE pb;
            NTFS_RECORD_HEADER* pnrh;
            NTFS_FILE_RECORD_HEADER* pnfrh;
            NTFS_ATTRIBUTE* pna;
            NTFS_RESIDENT_ATTRIBUTE* pnra;
            NTFS_NONRESIDENT_ATTRIBUTE* pnaa;
        };

        NTFS_FILE_ID nfi;
        UNICODE_STRING us = { sizeof (nfi), sizeof (nfi), (PWSTR)&nfi };
        OBJECT_ATTRIBUTES oa = { sizeof(oa), hVolume, &us };

        do
        {
            FileRecordBuffer = pnfrob->FileRecordBuffer;

            if (err = BOOL_TO_ERROR(DeviceIoControl(hVolume, FSCTL_GET_NTFS_FILE_RECORD,
                &nfrib, sizeof nfrib, pnfrob, cb, &BytesReturned, 0)))
            {
                break;
            }

            // are really file
            if (
                pnrh->Type != NTFS_RECORD_HEADER::FILE ||
                !(pnfrh->Flags & NTFS_FILE_RECORD_HEADER::flgInUse) ||
                pnfrh->BaseFileRecord
                )
            {
                continue;
            }

            ULONG FileAttributes = INVALID_FILE_ATTRIBUTES;
            ULONGLONG FileSize = 0;
            PCWSTR ShortName = 0, LongName = 0, SystemName = 0;
            UCHAR ShortNameLength = 0, LongNameLength = 0, SystemNameLength = 0;

            nfi.MftRecordIndex = pnfrob->FileReferenceNumber.QuadPart;
            nfi.SequenceNumber = pnfrh->SequenceNumber;

            pb += pnfrh->AttributesOffset;

            BOOL bSysFile = FALSE;

            for( ; ; )
            {
                union {
                    NTFS_FILENAME_ATTRIBUTE* pnfa;
                    NTFS_STANDARD_ATTRIBUTE* pnsa;
                };

                switch (pna->Type)
                {
                case NTFS_ATTRIBUTE::StopTag:
                    goto __end;

                case NTFS_ATTRIBUTE::FileName:

                    pnfa = (NTFS_FILENAME_ATTRIBUTE*)RtlOffsetToPointer(pnra, pnra->ValueOffset);

                    switch (pnfa->NameType)
                    {
                    case NTFS_FILENAME_ATTRIBUTE::systemName:
                    case NTFS_FILENAME_ATTRIBUTE::systemName2:
                        bSysFile = TRUE;
                        SystemName = pnfa->FileName, SystemNameLength = pnfa->FileNameLength;
                        break;
                    case NTFS_FILENAME_ATTRIBUTE::longName:
                        LongName = pnfa->FileName, LongNameLength = pnfa->FileNameLength;
                        break;
                    case NTFS_FILENAME_ATTRIBUTE::shortName:
                        ShortName = pnfa->FileName, ShortNameLength = pnfa->FileNameLength;
                        break;
                    }
                    break;

                case NTFS_ATTRIBUTE::StandardInformation:

                    pnsa = (NTFS_STANDARD_ATTRIBUTE*)RtlOffsetToPointer(pnra, pnra->ValueOffset);
                    FileAttributes = pnsa->FileAttributes;
                    break;

                case NTFS_ATTRIBUTE::Data:
                    FileSize += pna->Nonresident ? pnaa->DataSize : pnra->ValueLength;
                    break;
                }

                pb += pna->Length;
            }

__end:;

            if (bSysFile)
            {
                HANDLE hFile;
                IO_STATUS_BLOCK iosb;

                NTSTATUS status = NtOpenFile(&hFile, FILE_READ_ATTRIBUTES, &oa, &iosb, FILE_SHARE_VALID_FLAGS,
                    FILE_OPEN_REPARSE_POINT| FILE_OPEN_BY_FILE_ID | FILE_OPEN_FOR_BACKUP_INTENT);

                if (0 <= status)
                {
                    NtClose(hFile);
                }

                char sz[32];
                StrFormatByteSize64A(FileSize, sz, RTL_NUMBER_OF(sz));
                DbgPrint("%I64u: %08x %s [%x] %.*S\n", pnfrob->FileReferenceNumber.QuadPart,
                    FileAttributes, sz, status, SystemNameLength, SystemName);
            }

        } while (0 <= (nfrib.FileReferenceNumber.QuadPart = pnfrob->FileReferenceNumber.QuadPart - 1));

    }

    CloseHandle(hVolume);

    return err;
}

with it i got next result:
38: 10000006 0 bytes [0] $Deleted
34: 00000020 10.0 MB [0] $TxfLogContainer00000000000000000002
33: 00000020 10.0 MB [0] $TxfLogContainer00000000000000000001
32: 00000020 64.0 KB [0] $TxfLog.blf
31: 00000026 1.00 MB [0] $Tops
30: 80000006 0 bytes [0] $Txf
29: 00000006 0 bytes [0] $TxfLog
28: 00000026 27.0 MB [0] $Repair
27: 00000006 0 bytes [0] $RmMetadata
26: 20000026 0 bytes [c0000034] $Reparse
25: 20000026 0 bytes [c0000034] $ObjId
24: 20000026 0 bytes [c0000034] $Quota
11: 00000006 0 bytes [0] $Extend
10: 00000006 128 KB [0] $UpCase
9: 20000006 0 bytes [c0000034] $Secure
8: 00000006 237 GB [c0000022] $BadClus
7: 00000006 8.00 KB [c0000022] $Boot
6: 00000006 7.42 MB [c0000022] $Bitmap
5: 00000806 0 bytes [0] .
4: 00000006 2.50 KB [0] $AttrDef
3: 00000006 0 bytes [0] $Volume
2: 00000006 64.0 MB [c0000022] $LogFile
1: 00000006 4.00 KB [0] $MFTMirr
0: 00000006 212 MB [0] $MFT

A: Yes, it is possible to use DeviceIoControl / FSCTL_GET_NTFS_FILE_RECORD to read the $MFT without elevation. With the help of this page, I have worked out the minimum settings. Note the last few paragraphs at the bottom of that page.

*

*in Group Policy gpedit.msc, add the (non-elevated) user account you'll be running under to the following to the following policies:

Windows Settings/Security Settings/Local Policies/User Rights Assignment/...Perform Volume Maintenance tasks     (definitely needed)
Windows Settings/Security Settings/Local Policies/User Rights Assignment/...Back up files and directories     (not sure if this is essential)

*So far, I haven't needed the following, but make a note of it in case you need to come back to it:

Windows Settings/Security Settings/Local Policies/User Rights Assignment/...Restore files and directories

*Run gpupdate.exe from a Windows command prompt, or wait about 15 minutes for the group policy changes to take effect.

*Those changes allow your user account to acquire the privileges. As a one-time step every time your app starts, you'll have to explicitly adjust your token. Here's a standalone version of the Win32 API AdjustTokenPrivileges:
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.ComponentModel;

[SuppressUnmanagedCodeSecurity]
public static class AdjPriv
{
    [DllImport("kernel32.dll")]
    static extern IntPtr GetCurrentProcess();

    [DllImport("advapi32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool OpenProcessToken(IntPtr h, int acc, out IntPtr phtok);

    [DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool LookupPrivilegeValueW(IntPtr host, [MarshalAs(UnmanagedType.LPWStr)] String name, out long pluid);

    [DllImport("advapi32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, in TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);

    const int
        SE_PRIVILEGE_ENABLED    /**/ = 0x00000002,
        TOKEN_QUERY             /**/ = 0x00000008,
        TOKEN_ADJUST_PRIVILEGES /**/ = 0x00000020,
        ERROR_NOT_ALL_ASSIGNED  /**/ = 0x00000514;

    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    struct TokPriv1Luid
    {
        public int Count;
        public long Luid;
        public int Attr;
    };

    public static bool SetPrivilege(String szSe)
    {
        if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out IntPtr htok))
            goto _error;

        var tp = new TokPriv1Luid { Count = 1, Attr = SE_PRIVILEGE_ENABLED };

        if (!LookupPrivilegeValueW(IntPtr.Zero, szSe, out tp.Luid))
            goto _error;

        if (!AdjustTokenPrivileges(htok, false, in tp, 0, IntPtr.Zero, IntPtr.Zero))
            goto _error;

        return Marshal.GetLastWin32Error() != ERROR_NOT_ALL_ASSIGNED;

    _error:
        throw new Win32Exception();
    }
};

*Give the current user account the "SeManageVolumePrivilege" privilege when the app starts up by calling the AdjPriv.SetPrivilege utility function shown above. Call it once for each additional privilege you may also want to add.

static MyProgram()
{
    if (!AdjPriv.SetPrivilege("SeManageVolumePrivilege"))
        throw new SecurityException();

    /// etc...
}

*And now for the code. I won't go into detail with the p/Invoke since everyone has their own way of doing it. I'll just show the exact flags and constants values passed into the two critical two API calls in order to work without prompting for elevation.

IntPtr h = CreateFileW(@"\\?\Volume{c2655473-adc2-4fe3-99a0-77d5bb1b809f}\",
                       FILE_ACCESS_READ_CONTROL,   // 0x00020000
                       FILE_SHARE_ANY,             // 7
                       IntPtr.Zero,
                       CREATE_MODE_OPEN_EXISTING,  // 3
                       FILE_FLAG_BACKUP_SEMANTICS, // 0x02000000
                       IntPtr.Zero);

*And then finally...

/// <summary>
/// Given a 48-bit MFT index 'frn', recover the current "sequence number" of the file, which
/// can be used as the upper 16-bits to complete a usable FILE_REFERENCE (NTFS FileId):
/// </summary>
var frn = (FILE_REFERENCE)0x_0000_000000000218;
                    //       ^^^^----- ???

// lookup proceeds downwards, so set the sought-after upper 16 bits to max. seq. value
frn.Seq = 0xFFFF;

if (!DeviceIoControl(h, FSCTL_GET_NTFS_FILE_RECORD, in frn, out FILE_RECORD_OUTPUT_BUFFER rec) ||
    frn.Index != rec.file_ref.Index)
    throw new Win32Exception();

frn.Seq = rec.frh.SequenceNumber;
                                          //    vvvv--- !!!
Console.WriteLine($"0x{frn:X16}");        // 0x_0092_000000000218

Notes:
It works! Well at least for me on Windows 10, Version 10.0.18362.387. Please notice the backslash ...\ at the end of the Volume Guid path in CreateFileW. The code will not work without it.


text:
Q: form.serialise is returning null to controller I am a new programmer and I am trying to add a row in the database using ajax, by sending the new row with form.serialise. The model new row that i am sending is a  part of the main model that is used to create a view.
I know there is a tedious way of going through each column to match the column of the table in the database, however, I want to use the easier option-using ajax.
This is a part of my model used to create a view:
    public List <Appliance> Appliances { get; set; }

    public Appliance NewAppliance { get; set; }
    public string DepositTotalBalance { get; set; }

    public string DepositGiven { get; set; }
    public string DepositReturned { get; set; }

This is my controller method:
              public ActionResult CreateCheck(Appliance NewAppliance)
    {
            db.Appliances.InsertOnSubmit(app);
        db.SubmitChanges();

        var appIndb = (from a in db.Appliances
                             where a.ApartmentID == app.ApartmentID
                             select a).LastOrDefault();

              var applianceNew= appRepo.Add(appIndb );
                  return Json(new { success = true, appliance =
             applianceNew},
                     JsonRequestBehavior.AllowGet);
                      }

This is my view - my fields in the form are ALL
                          html.editorfor or hiddenfor- i have not specified
                         names for any of
                         them:
                     <form id="hidden-form-appliance">
                @Html.AntiForgeryToken()

                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

Appliance Name

                            @*@Html.LabelFor(model => model.NewAppliance.ApplianceName, htmlAttributes: new { @class = "control-label col-md-2" })*@

                                @Html.EditorFor(model => model.NewAppliance.ApplianceName, new { htmlAttributes = new { @class = "form-control", id = "applianceName" } })
                                @Html.ValidationMessageFor(model => model.NewAppliance.ApplianceName, "", new { @class = "text-danger" })

 Unit

                                @{ var unitsList = new List<SelectListItem>();

                                    foreach (var item in Model.AllApartmentsForID)
                                    {
                                        var unitType = new SelectListItem();
                                        unitType.Value = item.ApartmentID.ToString();
                                        unitType.Text = item.ApartmentNumber;

                                        unitsList.Add(unitType);
                                    }
                                }
                                @Html.DropDownListFor(model => model.NewAppliance.ApartmentID, unitsList, "Select Unit", new { @class = "form-control", @id = "ap_ApartmentID" })
                                @Html.ValidationMessageFor(model => model.NewAppliance.ApartmentID, "", new { @class = "text-danger" })

 Make

                                @Html.EditorFor(model => model.NewAppliance.Make, new { htmlAttributes = new { @class = "form-control", id = "editedDistrict" } })
                                @Html.ValidationMessageFor(model => model.NewAppliance.Make, "", new { @class = "text-danger" })

 Model

                                @Html.EditorFor(model => model.NewAppliance.Model, new { htmlAttributes = new { @class = "form-control", id = "editedDistrict" } })
                                @Html.ValidationMessageFor(model => model.NewAppliance.Model, "", new { @class = "text-danger" })

Description

                        <textarea class="text-area-input-form">
                        @Model.NewAppliance.DescriptionDetails

                    </textarea>

 Store

                                @Html.EditorFor(model => model.NewAppliance.Store, new { htmlAttributes = new { @class = "form-control", id = "editedAddress" } })
                                @Html.ValidationMessageFor(model => model.NewAppliance.Store, "", new { @class = "text-danger" })

 Cost

                                @Html.EditorFor(model => model.NewAppliance.Cost, new { htmlAttributes = new { @class = "form-control", id = "editedAddress" } })
                                @Html.ValidationMessageFor(model => model.NewAppliance.Cost, "", new { @class = "text-danger" })

 Installed On

                            @Html.EditorFor(model => model.NewAppliance.DateOfInstallment, new { htmlAttributes = new { @class = "form-control", id = "datepicker" } })
                            @Html.ValidationMessageFor(model => model.NewAppliance.DateOfInstallment, "", new { @class = "text-danger" })

                </form>

This is the js:
                                  $('.btn.btn--
                         primary.saveNewAppliance').on('click',
                               function () {

            alert($('#hidden-form-appliance').serialize());

            $.ajax({

                url: '@Url.Action("CreateCheck", "Appliance")',
                data:{ NewAppliance: $('#hidden-form-
                 appliance').serialize()},
              success: function(data) {
        if (data) {  // check if data is defined
           if (data.success) { // if success is true
               alert("It Worked!");

               }
             }
          }
         });

Update:    This is the source code:
            <form id="hidden-form-appliance">
                <input name="__RequestVerificationToken" type="hidden"
             value="MLW1wQJnd0WnHyzEaOJO6kAEVm-r_9YYhDliWfy28Qxs6-
                 Q6kabsK48RICT5uAIhtJ1WQ3Hrq6S-axQwIoMw5F32t6webLXW-
                     T7npEad1lkn-7dVDO6HFyGcXsJpv2ayhiithucgvg3Ro2kd8Pk5MQ2"
                         />

                               <input class="form-control text-box single-
                            line" id="applianceName"
                        name="NewAppliance.ApplianceName"
                          type="text" value="" />

                                <select class="form-control" data-
                           val="true" data-val-number="The field
                            ApartmentID must be a number."
                             id="ap_ApartmentID"
                           name="NewAppliance.ApartmentID"><option
                       value="">Select Unit</option>
                            </select>

                                <input class="form-control text-box single-
                          line" id="editedDistrict"
                               name="NewAppliance.Make" type="text"
                value="" />

                                <input class="form-control text-box single-
                            line" id="editedDistrict"
                               name="NewAppliance.Model" type="text"
                                           value="" />

Description

                        <textarea class="text-area-input-form">

                    </textarea>

                                <input class="form-control text-box single-
                               line" id="editedAddress"
                           name="NewAppliance.Store" type="text" value=""
                                  />

                                <input class="form-control text-box single-
                                       line" data-val="true" data-val-
                                   number="The field Cost must be a
                                   number." id="editedAddress"
                               name="NewAppliance.Cost" type="text"
                           value="" />

                            <input class="form-control text-box single-
                     line" data-val="true" data-val-date="The field
                     DateOfInstallment must be a date." data-val-
                         required="The DateOfInstallment field is
                         required." id="datepicker"
                     name="NewAppliance.DateOfInstallment" type="date"
                       value="" />

            </form>

I get the error "Value cannot be null". (Appliance model is being sent as null).
Update 2:
console.log($('#hidden-form-appliance').serialize()) yields:
Appliance.ApplianceName=jhbk&Appliance.ApartmentID=1388&Appliance.ApplianceID=0&Appliance.Make=hhj&Appliance.Model=hku&Appliance.DescriptionDetails=bhjk&Appliance.Store=gjh&Appliance.Cost=789&Appliance.DateOfInstallment=09%2F08%2F2009

Anyone can help? Thank you

A:
i have not specified names for any of them

It appears that you specify the editors' id attributes, for example:
@Html.EditorFor(model => model.NewAppliance.Cost, new { htmlAttributes = new { @class = "form-control", id = "editedAddress" } })

what may affect the resultant request data pairs. Since you use the strong-typed editors, try not to specify this html attribute explicitly. If you need to manipulate them in js/css, try to operate the css class(es) instead.


text:
Q: AH00961 Proxy redirect I'm trying to redirect my node.js app which is using port 9025 to port 80 and 443 using Apache's Proxy Redirect, but when I reload apache I get this:
[Sun Dec 17 18:18:08.235231 2017] [ssl:error] [pid 20851] [remote VPSip:9025] AH01961: SSL Proxy requested for VPSIp:80 but not enabled [Hint: SSLProxyEngine]
[Sun Dec 17 18:18:08.235297 2017] [proxy:error] [pid 20851] AH00961: HTTPS: failed to enable ssl support for VPSIp:9025 (VPSIp)
And yes, I have enabled SSLProxyEngine on the VirtualHost's config.


text:
Q: merge_asof multiple columns I know that a similar question has been asked before. However, my question is slightly different. I am trying to get the functionality of the merge_asof across multiple columns. Here is the dataset:
import pandas as pd
left = pd.DataFrame({'a':[1,5,10]\
                    ,'business'['FRC','FRC','FRC']\
                    ,'left_val':['a','b','c']})
right = pd.DataFrame({'a':[1,2,3,6]\
                    ,'business':['ED','ED','ED','ED']\
                    ,'right_val':[1,2,3,6]})
pd.merge_asof(left,right,on='a',direction='forward')

the output that I get is:

I would like to include business in the join as well. So , the right_val and business of the join should show NaN for all values.

A: I believe you need parameter by in merge_asof:

by : column name or list of column names
  Match on these columns before performing merge operation.

print (pd.merge_asof(left,right,on='a',direction='forward', by='business'))
    a business left_val  right_val
0   1      FRC        a        NaN
1   5      FRC        b        NaN
2  10      FRC        c        NaN


text:
Q: Excel Sum Product Currently in my excel spreadsheet i have this formula in one of my cell
=SUMPRODUCT(('CDT DWGS-2014'!G:G=2014)*
            ('CDT DWGS-2014'!S:S<>"")*
            ('CDT DWGS-2014'!Q:Q>='CDT DWGS-2014'!S:S)*
            ('CDT DWGS-2014'!S:S>=DATEVALUE("01-Jan-2014"))*
            ('CDT DWGS-2014'!S:S<DATEVALUE("01-Feb-2014"))
  )

i want to add this next line of code into the previous code but it keeps giving me a #value error.
*('CDT DWGS-2014'!T:T>1)*

is it because in the column T, i have both numbers and text in there? How would i go about getting the sum product value without changing the column T? I need both number and text in the column. In each cell in column T, it's either "Jon Not Finished" or negative or positive numbers
Thank you

A: If the values in column T contain positive values or negative values or a text string, but not zero then replace the text values with the value zero and format these zero cells as Custom
;;"Jon Not Finished";
These cells will show the text, but behave like zero!


text:
Q: Insert sendo executado duas vezes Tenho um código para quando se realizar um logout no sistema, ser registrado em uma tabela do banco de dados.
Eu chamo esse arquivo que faz o logout quando clico no botão sair e também quando fecho a janela no navegador.
O problema é que algumas vezes o INSERT faz a inserção dos registros duas vezes.
Não sei se o problema é o problema. Já tentei diversas maneira de corrigir isso, porém todas sem sucesso.
Vou deixar os código abaixo:

//Código JavaScript para chamar o arquivo logout.php quando o navegador é fechado

window.onbeforeunload = function() {
  $.get("../banco/validador-de-login/logout.php", function(data) {
    return false;
  });
}

<?php

require_once("../conexao/conexao-com-banco.php");

session_start(); //iniciamos a sessão que foi aberta

require_once("../login-logout/login.php");

$usuario = $_SESSION['usuario'];

//Esse IF verifica se a sessão está ativa. Só chama a função se a sessão está ativa.
if(session_status() == PHP_SESSION_ACTIVE)
{
pegarLogout($conecta, $usuario);

}

session_destroy(); //destruimos a sessão ;)

session_unset(); //limpamos as variaveis globais das sessões

/*aqui você pode redirecionar para uma determinada página*/
/*
echo "";
*/

header('location:../../index.php');

?>

  <?php

 /* Função para realizar o controle de login de usuários */
 function pegarLogin($conexao, $user)
 {

  $query_login = "INSERT INTO log(tipo_reg,horario,usuario,data) VALUES('LOGIN',CURTIME(),'$user',CURDATE())";
  $resultado_query_login =  mysqli_query($conexao, $query_login);

  if(!$resultado_query_login) /*Verifica se o resultado deu certo ou errado*/
  {
   /*Se deu erro, então exibe a mensagem do sql sobre o erro */
   die("Falha no registro do login: " . mysqli_error($conexao));
  }

  //echo "
 Concluído a atualização das atividades com sucesso.
 Quantidade de atividades atualizadas: " . $contador;
 }

 /* Função para realizar o controle de login de usuários */
 function pegarLogout($conexao_2, $user)
 {

  $query_login_2 = "INSERT INTO log(tipo_reg,horario,usuario,data) VALUES('LOGOUT',CURTIME(),'$user',CURDATE())";
  $resultado_query_login_2 =  mysqli_query($conexao_2, $query_login_2);

  if(!$resultado_query_login_2) /*Verifica se o resultado deu certo ou errado*/
  {
   /*Se deu erro, então exibe a mensagem do sql sobre o erro */
   die("Falha no registro do login: " . mysqli_error($conexao_2));
  }

  //echo "
 Concluído a atualização das atividades com sucesso.
 Quantidade de atividades atualizadas: " . $contador;
 }

?>

    Sair

Imagem da tabela

Reparem que é feito uma segunda inserção com o coluna que guarda o nome do usuário em branco.
Não sei onde eu posso estar errando.
Se puderem me ajudar, ficaria grato.

A: Análise
Nesse código:
//Esse IF verifica se a sessão está ativa. Só chama a função se a sessão está ativa.
if(session_status() == PHP_SESSION_ACTIVE)
{
  pegarLogout($conecta, $usuario);

}

Parece que a intenção é descobrir estado da sessão atual e prevenir uma chamada de logout baseado no estado atual da sessão. O porém é que esse código não faz isso, ou pelo menos ele não faz bem a tarefa a qual foi designado.
No manual está especificado que session_status() é usada para retornar o status atual da sessão. Porém se session_status() for utilizado após a chamada da função session_start(), como é o caso, apenas informará se as sessões estão ou não habilitadas nas configurações.
Outra coisa é fato de mesmo você ter usado esse código:
session_destroy(); //destruimos a sessão ;)

session_unset(); //limpamos as variaveis globais das sessões

A variável superglobal $_SESSION ainda persiste, mesmo sem refrência, um id ou valores associados.
session_destroy() não elimina completa ou definitivamente a sessão. session_destroy() apenas elimina a referência $_SESSION, a sessão, temporariamente até a próxima chamada de session_start() onde a referência $_SESSION, a sessão, é retomada.
Solução
Só pela pergunta não dá para saber o que leva o código do logout a ser chamado duas vezes, mas o que dá para ser feito é criar condições para prevenir uma segunda chamada do logout usando a variável de sessão.

<?php

  require_once("../conexao/conexao-com-banco.php");

  session_start(); //<-- Retoma a referência para o superglobal $_SESSION

  require_once("../login-logout/login.php");

  // Verifica se o valor 'usuario' está definido no array $_SESSION
  if(isset($_SESSION['usuario'])) {
        pegarLogout($conecta, $_SESSION['usuario']);
  }

  //Libera os valores atualmente registradas na sessão. Chame antes de
  //session_destroy.
  session_unset();

  //Não destrói a sessão ou cookie de sessão. Só invalida temporariamente a referência
  //para a superglobal $_SESSION. A referência pode ser retomada com `session_start()`
  session_destroy();

  header('location:../../index.php');

?>


text:
Q: Unpredictable counting of number Say I have a 32-bit integer. Initially I seed this black box with something random/secret.
Each time I call, advance, I get the next number in the sequence but the next number in the sequence isn't necessarily the the next largest number, as with ++ it's something unpredictable. I've done this using a permutation table but that requires a lot of space and I was wondering if anyone knows of a specific construct that would give me an entire range in some deterministic order that's based on some seed value and then only yield each value exactly once per cycle.
Does anyone know of such a scheme?

A: There's an intresting answer to a question on crypto.stackexchange.com by Thomas Pornin that goes into how to design a secure alternating step generator (ASG).
It's not the fastest solution to my problem but I think it will do.
I wrote this code to test my theory
struct Lfsr
{
    public readonly int State;

    public Lfsr(int seed)
    {
        this.State = seed;
    }

    public Lfsr Advance()
    {
        var bit = ((State >> 30) ^ (State >> 27)) & 1; //  ^ (State >> 1) ^ (State >> 0)
        return new Lfsr(((State << 1) | bit) & 0x7fffffff);
    }
}

static void Main(string[] args)
{
    var n = 0;

    var lfsr = new Lfsr(1);

    do
    {
        lfsr = lfsr.Advance();

        ++n;
    }
    while (lfsr.State != 1);

    Console.WriteLine(n);
}

On my machine it took about 7 seconds to cycle through with a period of 2147483647 counted numbers. In order to make it secure you'd have to combine these into an ASG and use three times as large linear feedback shift registers (LFSRs).
You also need to use maximal-length feedback polynomials for strength. the Wikipedia article references a PDF that lists maximal-length feedback polynomials up to 168-bits in length.


text:
Q: How to support multiple private npm packages living in one git repo? npm is very good at supporting packages publishes to the global/central npm repo, which doesn't work well for private, application code.  npm also supports adding a git repo as a dependency, which lets you have a private dependency.
The problem is, as I understand to be best practice, my npm packages tend to be very tight and small, whereas my git repos tend to be larger, and will include several npm packages.  I do not know any way to attain this granularity while pointing to a github URL.  How to solve this?
UPDATE
I accepted the answer that says "don't do this, stay on the rails." I agree with this recommendation, but YMMV.

A: I would suggest that one repo with multiple packages is a bad idea to start with for several reasons. You should be viewing a package as its own entity: independently built, tested, and deployed. All that to say, each package should live in its own repo.
That being said, I definitely understand the benefit of being able to do an npm install <package-group> of one "commons" package and have it grab all the packages you need in one shot. I would suggest looking at the grunt-contrib model for accomplishing this. In short, they have a bunch of grunt-contrib- packages (ex. grunt-contrib-coffee) each living in their own repositories. They then create a separate repository that defines the parent "grunt-contrib" package. All this parent package does is specify dependencies on all of the sub-packages. This allows you to do an npm install grunt-contrib-coffee (for example) and get just the grunt-contrib-coffee package; or you can do npm install grunt-contrib and get their entire suite all in one shot.
Hope this helps!

A: You could also set up your own local npm repository.

*

*Instructions for *nix/OSX

*Instructions for Windows


text:
Q: How to delete a specific line from record in C programming (it can't proceed deletion) #include <stdio.h>
#include <conio.h>
#include <string.h>
#include<stdlib.h>

struct person{
 char stdNumb [20];
    char firstName [20],lastName [20], icPass [20], nationality [20], gender [20], dateOfBirth [20];
    char contact [20], address [30];
};

void appendData(){
  FILE *fp;
  struct person obj;
  fp=fopen("D:\\data.txt","a");
  printf("\n============================");
  printf("\n            ADD");
  printf("\n============================\n\n");

  printf("Student Number: ");
  scanf("%s",&obj.stdNumb);

  printf("First Name: ");
  scanf(" %[^\n]s",obj.firstName);

  printf("Last Name: ");
  scanf(" %[^\n]s",&obj.lastName);

  printf("IC/ Passport: ");
  scanf("%s",&obj.icPass);

  printf("Nationality: ");
  scanf("%s",obj.nationality);

  printf("Gender: ");
  scanf("%s",&obj.gender);

  printf("Date of Birth: ");
  scanf("%s",obj.dateOfBirth);

  printf("Contact: ");
  scanf("%s", &obj.contact);

  printf("Address: ");
  scanf(" %[^\n]s", &obj.address);

  fprintf(fp,"\n%s\n%s %s\n%s\n%s\n%s\n%s\n%s\n%s\n", obj.stdNumb, obj.firstName, obj.lastName, obj.icPass, obj.nationality, obj.gender, obj.dateOfBirth, obj.contact, obj.address);
  fclose(fp);
}

void editRecord()
{
  FILE *fp;
  struct person obj;

  fp=fopen("D:\\data.txt","r");
  printf("\n============================");
  printf("\n            EDIT");
  printf("\n============================\n\n");
  while(!feof(fp))
  {
  fscanf(fp,"%s\n%s\n",obj.firstName,&obj.stdNumb);
  printf("%s\n%s\n",obj.firstName,obj.stdNumb);
  }
  fclose(fp);
  getch();
}

void searchRecord()
{
  FILE *fp;
  struct person obj;
  char number[20];
  int totrec=0;
  fp=fopen("D:\\data.txt","r");
  printf("\n\n============================");
  printf("\n           SEARCH");
  printf("\n============================");
  printf("\nEnter student number to search  : ");
  scanf("%s",&number);
  while(!feof(fp))
  {
      fscanf(fp,"\n%s\n%s %s\n%s\n%s\n%s\n%s\n%s\n%s\n", obj.stdNumb, obj.firstName, obj.lastName, obj.icPass, obj.nationality, obj.gender, obj.dateOfBirth, obj.contact, obj.address);
  if(strcmpi(obj.stdNumb,number)==0){
    printf("\nStudent Number : %s",obj.stdNumb);
    printf("\n\nName   :  %s",obj.firstName);
    totrec++;
     }
  }
  if(totrec==0)
     printf("\n\n\nNo Data Found");
  else
     printf("\n\n===Total %d Record found===",totrec);
  fclose(fp);
  getch();
}

void deleteRecord()
{
FILE *fp, *fdel;
struct person obj;
char number[20];
fflush(stdin);
printf("\n============================");
printf("\n            DELETE");
printf("\n============================\n\n");
printf("Enter student number to delete  :");
scanf("%s", number);
fp=fopen("D:\\student.txt","r");
fdel=fopen("D:\\del.txt","w");
while(fscanf(fp,"\n%s\n%s %s\n%s\n%s\n%s\n%s\n%s\n%s\n", obj.stdNumb, obj.firstName, obj.lastName, obj.icPass, obj.nationality, obj.gender, obj.dateOfBirth, obj.contact, obj.address)!=0);
{
    if(stricmp(number, obj.stdNumb)!=0)
        fprintf(fdel,"\n%s\n%s %s\n%s\n%s\n%s\n%s\n%s\n%s\n", obj.stdNumb, obj.firstName, obj.lastName, obj.icPass, obj.nationality, obj.gender, obj.dateOfBirth, obj.contact, obj.address);
}
fclose(fp);
fclose(fdel);
remove("D:\\data.txt");
rename("D:\\del.txt","D:\\data.txt");

printf("Successully Deleted.");
getch();
}

void main()
{
char choice;
while(1)
{
    printf("\n============================");
    printf("\n            MENU");
    printf("\n============================");
    printf("\n1. ADD");
    printf("\n2. SEARCH");
    printf("\n3. EDIT");
    printf("\n4. DELETE");
    printf("\n5. EXIT");
    printf("\n============================");
    printf("\n\n");
    printf("Enter your choice : ");
    fflush(stdin);
    choice = getche();
    switch(choice)
    {
    case'1' : //call append record
        appendData();
        break;
    case'2' : //call search record
        searchRecord();
        break;
    case'3' : //edit record
        editRecord();
        break;
    case'4' : //Read all record
        deleteRecord();
        break;
    case'5':
         exit(0);
defaut:
        printf("ss");
    }
}

}
Here is my full code. I'm done with append and search. The problem is, when I try to run, and delete a record, it doesn't work after I input the student number. How to fix this?

A: You try to read in a string with scanf("%s", &number); but number is already a pointer so you need to write scanf("%s", number);.
When you normally try to read in something with scanf you need to give it an address which points to the place where the value shall be stored.
So when i have something like
int a;
scanf("%d", &a);

you give scanf the address of a.
char str[100];
scanf("%s", str);

Here str is already a pointer to a char array.
That is why we don't need to add the address operator &.
But when you add the address operator you give scanf the address were the pointer value is stored.
EDIT:
I compiled your code with clang on my machine and it warns me about 7 scanf statements:
a.c:20:11: warning: format specifies type 'char *' but the argument has type 'char (*)[20]' [-Wformat]
  scanf("%s",&obj.stdNumb);
         ~^  ~~~~~~~~~~~~
a.c:26:12: warning: format specifies type 'char *' but the argument has type 'char (*)[20]' [-Wformat]
  scanf(" %[^\n]s",&obj.lastName);
          ~^~~     ~~~~~~~~~~~~~
a.c:29:11: warning: format specifies type 'char *' but the argument has type 'char (*)[20]' [-Wformat]
  scanf("%s",&obj.icPass);
         ~^  ~~~~~~~~~~~
a.c:35:11: warning: format specifies type 'char *' but the argument has type 'char (*)[20]' [-Wformat]
  scanf("%s",&obj.gender);
         ~^  ~~~~~~~~~~~
a.c:41:11: warning: format specifies type 'char *' but the argument has type 'char (*)[20]' [-Wformat]
  scanf("%s", &obj.contact);
         ~^   ~~~~~~~~~~~~
a.c:44:12: warning: format specifies type 'char *' but the argument has type 'char (*)[30]' [-Wformat]
  scanf(" %[^\n]s", &obj.address);
          ~^~~      ~~~~~~~~~~~~
a.c:61:19: warning: format specifies type 'char *' but the argument has type 'char (*)[20]' [-Wformat]
  fscanf(fp,"%s\n%s\n",obj.firstName,&obj.stdNumb);

and three typos
a.c:83:6: warning: implicit declaration of function 'strcmpi' is invalid in C99 [-Wimplicit-function-declaration]
  if(strcmpi(obj.stdNumb,number)==0){
     ^
a.c:112:8: warning: implicit declaration of function 'stricmp' is invalid in C99 [-Wimplicit-function-declaration]
    if(stricmp(number, obj.stdNumb)!=0)
       ^
a.c:141:14: warning: implicit declaration of function 'getche' is invalid in C99 [-Wimplicit-function-declaration]
    choice = getche();
             ^


text:
Q: How can I extract CSS files from JS files with Webpack? I am using Architect UI free version.
Download Link
I downloaded the file and When I ultimately run this command
npm run build

It generates all html files and an asset folder containing images and js files. In those js files CSS is embedded.

Now I want to extract the css file.
How can I generate the css file. Let me know the step by step procedure.
I was trying to use the mini-css-extract-plugin plugin but failed in generating the css file.
Help me in this regard.

A: I downloaded the package and did a little debugging.
webpack.config.js should be the following:

'use strict';
const Path = require('path');
const Webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const ExtractSASS = new MiniCssExtractPlugin({filename:'./[name].css'});
const CopyWebpackPlugin = require('copy-webpack-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const webpack = require('webpack');

const pages = require('./src/pages');
let renderedPages = [];
for (let i = 0; i < pages.length; i++) {
    let page = Object.assign({}, pages[i]);
    renderedPages.push(
        new HtmlWebpackPlugin({
            template: page.template,
            filename: page.output,
            title: page.content.title,
            heading_icon: page.content.heading_icon,
            description: page.content.description
        })
    );
}

module.exports = (options) => {
    const dest = Path.join(__dirname, 'architectui-html-free');

    let webpackConfig = {
        mode: 'none',
        devtool: options.devtool,
        entry: {
            main: './src/app.js',
            demo: './src/scripts-init/demo.js',
            toastr: './src/scripts-init/toastr.js',
            scrollbar: './src/scripts-init/scrollbar.js',
            fullcalendar: './src/scripts-init/calendar.js',
            maps: './src/scripts-init/maps.js',
            chart_js: './src/scripts-init/charts/chartjs.js',
        },
        output: {
            path: dest,
            filename: './assets/scripts/[name].js'
        },
        plugins: [
            new Webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                'window.jQuery': 'jquery',
                Tether: 'tether',
                'window.Tether': 'tether',
                Popper: ['popper.js', 'default'],
            }),
            new CopyWebpackPlugin({
              patterns: [
                { from: './src/assets/images', to: './assets/images' }
              ]
            }),
            new Webpack.DefinePlugin({
                'process.env': {
                    NODE_ENV: JSON.stringify(options.isProduction ? 'production' : 'development')
                }
            })
        ],
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    loader: 'babel-loader'
                },
                {
                    test: /\.hbs$/,
                    loader: 'handlebars-loader',
                    options: {
                        helperDirs: [
                            Path.join(__dirname, 'src', 'helpers')
                        ],
                        partialDirs: [
                            Path.join(__dirname, 'src', 'layout'),
                            Path.join(__dirname, 'src', 'DemoPages'),
                        ]
                    }
                },
                {
                    test: /\.(woff|woff2|eot|ttf|otf)$/i,
                    type: 'asset/resource',
                },
                {
                    test: /\.(png|svg|jpg|jpeg|gif)$/i,
                    type: 'asset/resource',
                }
            ]
        }
    };

    if (options.isProduction) {
        webpackConfig.entry = [
            './src/app.js',
            './src/scripts-init/demo.js',
            './src/scripts-init/toastr.js',
            './src/scripts-init/scrollbar.js',
            './src/scripts-init/calendar.js',
            './src/scripts-init/maps.js',
            './src/scripts-init/charts/chartjs.js',

        ];

        webpackConfig.plugins.push(
            ExtractSASS,
            new CleanWebpackPlugin(/*[dest], {
                verbose: true,
                dry: false
            }*/)
        );

        webpackConfig.module.rules.push({
            test: /\.scss$/i,
            use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
        }, {
            test: /\.css$/i,
            use: [MiniCssExtractPlugin.loader, 'css-loader']
        });

    } else {
        webpackConfig.plugins.push(
            new Webpack.HotModuleReplacementPlugin()
        );

        webpackConfig.module.rules.push({
            test: /\.scss$/i,
            use: ['style-loader', 'css-loader', 'sass-loader']
        }, {
            test: /\.css$/i,
            use: ['style-loader', 'css-loader']
        },
        );

        webpackConfig.devServer = {
            port: options.port,
            historyApiFallback: true,
            hot: !options.isProduction,
        };

        webpackConfig.plugins.push(
            new BrowserSyncPlugin({
                host: 'localhost',
                port: 3002,
                files: ["public/**/*.*"],
                browser: "google chrome",
                reloadDelay: 1000,
            }, {
                reload: false
            })
        );

    }

    webpackConfig.plugins = webpackConfig.plugins.concat(renderedPages);

    return webpackConfig;

};

We just changed some of the plugin definitions. Do a diff on the files to see what has changed.
Your package.json file should contain:

{
  "name": "architectui-html-free",
  "version": "3.0.0",
  "description": "ArchitectUI - Free Bootstrap 5 Admin Dashboard Template",
  "author": "DashboardPack.com",
  "homepage": "https://dashboardpack.com",
  "private": false,
  "scripts": {
    "start": "webpack server",
    "build": "webpack --env isProduction"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/DashboardPack/architectui-html-theme-free"
  },
  "eslintConfig": {
    "env": {
      "browser": true,
      "node": true
    },
    "parserOptions": {
      "ecmaVersion": 6,
      "sourceType": "module"
    },
    "rules": {
      "semi": 2
    }
  },
  "dependencies": {
    "@fortawesome/fontawesome-free": "^6.1.1",
    "@fullcalendar/core": "^5.10.1",
    "@fullcalendar/daygrid": "^5.10.1",
    "@fullcalendar/interaction": "^5.10.1",
    "@fullcalendar/list": "^5.10.1",
    "@fullcalendar/timegrid": "^5.10.1",
    "@popperjs/core": "^2.11.4",
    "animate.css": "^4.1.1",
    "bootstrap": "^5.1.3",
    "chart.js": "^2.9.4",
    "fullcalendar": "^5.10.2",
    "gmaps": "^0.4.25",
    "jquery": "^3.6.0",
    "mapbox-gl": "^2.7.1",
    "metismenu": "^3.0.7",
    "moment": "^2.29.2",
    "pe7-icon": "^1.0.4",
    "perfect-scrollbar": "^1.5.5",
    "toastr": "^2.1.4",
    "wnumb": "^1.2.0",
    "yarn": "^1.22.18"
  },
  "resolutions": {
    "**/event-stream": "^4.0.1"
  },
  "devDependencies": {
    "@babel/core": "^7.17.8",
    "@babel/preset-env": "^7.16.11",
    "animate-sass": "^0.8.2",
    "babel-loader": "^8.2.4",
    "browser-sync": "^2.27.9",
    "browser-sync-webpack-plugin": "^2.3.0",
    "clean-webpack-plugin": "^4.0.0",
    "copy-webpack-plugin": "^10.2.4",
    "css-loader": "^6.7.1",
    "eslint": "^8.12.0",
    "eslint-webpack-plugin": "^3.1.1",
    "file-loader": "^6.2.0",
    "handlebars": "^4.7.7",
    "handlebars-loader": "^1.7.1",
    "html-webpack-plugin": "^5.5.0",
    "mini-css-extract-plugin": "^2.6.0",
    "nodemon": "^2.0.15",
    "sass": "^1.49.11",
    "sass-loader": "^12.6.0",
    "style-loader": "^3.3.1",
    "webpack": "^5.71.0",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.7.4"
  }
}

We needed to change:

"scripts": {
    "start": "webpack server",
    "build": "webpack --env isProduction"
  },

So that it runs the config.isProduction build. HTML will output the following:

<script defer src="./assets/scripts/main.js"></script><link href="./main.css" rel="stylesheet"></head>


text:
Q: How to make a functional PHP contact form that sends email to @outlook.com account on a website that is going to be published on ftp server? I am building a website that has a php contact form that will send an email on @outlook.com address. Website will be published on ftp server, but till then I published it on this free one https://www.000webhost.com/ so I can test contact form but it is not working. I've read somewhere that php mail() function does not work with smtp so I tried using PHPMailer as I found in some suggestions here (Trying to send email through PHP using an email address that is configured on Microsoft's SMTP servers (@live.com, @outlook.com, etc.)) but it's also not working or maybe I'm not doing it correctly since I don't quite understand it. The code is written without using PHPMailer:
PHP:
<?php
if ($_POST["submit"]) {
    if (!$_POST['name']) {
        $error="
Please enter your name";
    }
    if (!$_POST['email']) {
        $error.="
Please enter your email address";
    }

    if (!$_POST['message']) {
        $error.="
Please enter a message";
    }
    if ($_POST['email']!="" AND !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {
        $error.="
Please enter a valid email address";
    }
    if ($error) {
        $result='
There were error(s)in your form:'.$error.'
';
    } else {
        if (mail("mymail@outlook.com", "message from website!", "Name: ".$_POST['name']."Email: ".$_POST['email']."message: ".$_POST['message'])) {
            $result='
Thank you! I\'ll be in touch.
';
        } else {
            $result='
Sorry, there was an error sending your message. Please try again later.
';
        }
    }
}
?>

HTML:

<?php echo $result; ?>
<form method="POST" enctype="multipart/form-data ">

Your name:

            <input name="name" type="text " id="exampleInputName" class="form-control" placeholder="Name" value="<?php echo $_POST['name']; ?>">

Your e-mail:

        <input name="email" type="email " id="exampleInputEmail" class="form-control" placeholder="name@email.com" value="<?php echo $_POST['email']; ?>">

Message:

        <textarea name="message" class="form-control " rows="5" placeholder="Your message... " value="<?php echo $_POST['message']; ?>"></textarea>

            <button class="button" type= "submit" name="submit" value="Submit">send</button>

</form>

Another separate code where I tried using PHPMailer looks like this, which is basically copied from this link getting custom php contact form to send email to exchange 365 account
:
<?php
    if ($_POST["submit"]) {

    include("PHPMailer-master/class.PHPMailer.php");

    $mail = new PHPMailer();

    $mail->IsSMTP();
    $mail->Host     = "localhost";
    $mail->SMTPAuth = false;
    $mail->Username = "mymail@outlook.com"; #or do i put my account for webhostapp?
    $mail->Password = "my_password_for_outlook";

    $mail->From     = 'https://webpage.000webhostapp.com/';
    $mail->FromName = $_POST['name'];

    $mail->AddAddress('mymail@outlook.com');

    $mail->IsHTML(true);

    $mail->Subject  =  'Subject line goes here';

    $mail->Body     =  $_POST['message'];
    $mail->AltBody  =  $_POST['message'];

    $mail->Send();
}?>

result after submitting form


text:
Q: Modelica Class Method I would like to use a class function/method in my Modelica model as follows:
optimization Moo(objective=-x(finalTime), startTime = 0, finalTime = 12)
  parameter Real e = 0.05;

  Real x(start=2, fixed=true, min=0, max=100);

  input Real v (min=0, max=1);

  function omega
    input  Real t;
    output Real y;
  algorithm
    y := e;
  end omega;

equation
  der(x) = v*omega(time);
constraint
  v<=1;
end Moo;

I would like the variable e in the function omega to be a variable so that I can easily change its value at a later point in time when I am doing a parameter sweep. Unfortunately, the function omega does not seem to know about the variable e and the JModelica compiler returns the error:

Cannot find class or component declaration for e

I would naïvely expect that since omega and e belong to the same class omega would be able to see e.
Is there a way to achieve this?

A: Member functions are not supported in Modelica, so a function declared inside a model acts like a standalone function without having access to the surrounding model variables.
Member functions are not allowed due to functions need to be pure, i.e. they are not allowed to have any side effect. This is a fundamental assumption in Modelica that makes it possible for a tool to apply symbolic transformation and rearrange calculations.

A: You can have something like a member function, if you explicitly pass the needed variables as additional input to the function. See this example:
package MemberFunction

  model A
    Real x=1;
    function get_x = MemberFunction.get(u=x);
  end A;

  function get
    input Real u;
    output Real y;
  algorithm
    y := u;
  end get;

  model Test
      A a;
      Real x;
  equation
    x = a.get_x();
  end Test;

end MemberFunction;


text:
Q: Poor performance of QNetworkAccessManages::get() QNetwotkAccessManages::get() function lasts for a while (about 7-10 seconds) getting a page that opens in a moment in any browser.
Actually, I try to get http://suggestqueries.google.com/complete/search?client=chrome&q=myrequest.
Here's the simplified code:
void ApiGoogleSearch::getSuggestions()
{
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),
            SLOT(getSuggestionsFinished(QNetworkReply*)));

    QUrl url("http://suggestqueries.google.com/complete/search"
             "?client=chrome&q=myrequest");
    manager->get(QNetworkRequest(url));
    qDebug() << "get() started";
}

void ApiGoogleSearch::getSuggestionsFinished(QNetworkReply *reply)
{
    qDebug() << "ApiGoogleSearch::getSuggestionsFinished() started";
}

A: Well, Google somewhy returns that page for my app in a long time. Any other webpage loads quite quick.


text:
Q: I use the example named MoviePlayer from SDK 3.0, but it sometimes crashes I use the example named MoviePlayer from SDK 3.0, but it sometimes crashes.
PS: I never change any code.

Question 1:
My enviroment:

lan media server:10.0,0.118

I enter an MP4 address:

http://10.0.0.118/1.mp4

It works fine, but sometimes it crashes.

using gdb:bt
mach_msg_trap
mach_msg
CFRunLoopRunSpecific
CFRunLoopRunInMode
GSEventRunModal
GSEventRun
UIApplicationMain
main

What does it mean? I never modify any code.

Question 2:
And sometimes, if I play an MP4 file, and then I play it again, the screen of the simulater will shock. If I play another MP4 file it works fine.
How can I make it work?

Question 3:
The delegate named MPMoviePlayerContentPreloadDidFinishNotification does not work the first time  I play the movie. If I play it again or I play another movie, it is called.
Why?

A: *

*Question 2) This shock and blinking is only
a bug in the emulator. It is not
happening on a real iPhone device so
don't worry about it.

*Question 3) I too saw
that the delegate named
MPMoviePlayerContentPreloadDidFinishNotification
does not work the first time
I play the movie which is totally
strange. Maybe this is fixed in
newest firmware? I don't know. I can't
check it. Did you find any workaround for Question 3?


text:
Q: How to push docker image to Nexus repository through Jenkinsfile? I have a Jenkinsfile pipeline creating 3 docker images/containers as below:
stage('Build images')
{
    echo "workspace directory is ${workspace}"
    dir ("$workspace/build/virtuoso")
    {
      sh 'docker build -t virtuoso -f $WORKSPACE/build/virtuoso/Dockerfile .'
    }
    dir ("$workspace/build/wildfly")
    {
      sh 'docker build -t wildfly -f $WORKSPACE/build/wildfly/Dockerfile .'
    }
    dir ("$workspace/build/postgres")
    {
      sh 'docker build -t postgres -f $WORKSPACE/build/postgres/Dockerfile .'
    }
}

I need to push these 3 images to Nexus repository manager. Can somebody help me on this?

A: The solution to this is:
stage('Push Docker Images to Nexus Registry'){
sh 'docker login -u user -p password NexusDockerRegistryUrl'
sh 'docker push NexusDockerRegistryUrl/Imagename}'
sh 'docker rmi $(docker images --filter=reference="NexusDockerRegistryUrl/ImageName*" -q)'
sh 'docker logout NexusDockerRegistryUrl'
}

The above stage in Jenkins pipeline would push the docekr image to nexus docker registry and remove existing image.
Thanks