text:
Q: Removing convex sets that are unions of other convex sets from a large combinatorial enumeration An addition chain for $n$ is a sequence of integers $1=a_0<a_1<...<a_r=n$ with $a_i=a_j+a_k,i>j\ge k\ge 0$. We say $r$ is the addition chain length. We define the length of the smallest addition chain for $n$ by $l(n)$.
We have a measure of complexity of addition chains called the small step count. We define $s(n)=l(n)-\lambda(n)$ where $\lambda(n)=\lfloor {log_2(n)}\rfloor$.
If $s(n)=0$ we have $n=2^a$. With $s(n)=1$ we have $n=2^a+2^b,a>b\ge0$. These two cases can be seen with simple limits on $n$ and was first done in 1894 [1]. With $s(n)=2$ things get more complicated. We have 4 cases:
$n=2^a+2^b+2^c,a>b>c\ge0$
$n=2^a+2^b+2^c+2^d,a>b>c>d,1\ge a-b-c+d >= 0$
$n=2^a+2^{a-5}+2^{a-6}+2^{a-7},a\ge7$
$n=2^a+2^{a-3}+2^b+2^{b-1},a>b+3,b\ge1$
Knuth [2] in 1969 has laborious proofs of these cases (stated as 5 cases) in section 4.6.3. He asked though in question 15 to write a computer program to enumerate the $s(n)=3$ case.
Flammenkamp [3] in 1991 wrote the computer program and found 200 cases.
It's clear from the way these cases are constructed that each case has the power of 2 exponents as lattice points in a convex set in $R^{v(n)}$. Here $v(n)$ is the hamming weight of $n$. These are expressed in half-space format. It's clear that some cases could be removed if they are subsets of the unions of other cases. If the union of multiple cases is itself a convex set, we could replace multiple cases with their union. This process can be repeated until each convex set has a unique single vector of exponents as it's member that prevents further reduction. This reduced the $s(n)=3$ from 200 to 150 cases.
This explodes with $s(n)=4$. A new computer program I wrote can enumerate all the cases in under two minutes. It generates 251213 cases. Reducing the number of convex sets by detecting the subsets as mentioned above yielded 40206 cases. This process though is expensive. I detect if two convex sets ($U_1$,$U_2$) have a non-empty intersection. If they do then I compute $U_1\smallsetminus U_2$ as a union of convex sets. This process is repeated in the hopes that the union of convex sets becomes empty and $U_1$ can be discarded.
The case $s(n)=5$ took about 2 weeks to run and has generated 240439903 cases. It's clear I need some different approach to removing these overlaps. No algorithm that's $O(n^2)$ or worse I think has any hope of working. So, the question is are there tricks I can use here to help me reduce the number of cases?
Why do we care? Well, it seems remarkable that $v(n)$ appears to be bounded from above with $s(n)+1\le v(n)\le 2^{s(n)}$ The enumeration clearly shows this for $s(n)\le 5$. To get confidence in the enumeration I check it by making sure the convex sets contain the exponents for all known $n$ with $s(n)\le5$ with $n\le 2^{63}$ (the limits of direct calculations and storage). I can only do this I think if the number of convex sets is much smaller. I expect a vector equivalent of the Frobenius Number might say that if you can test all cases up until some particular vector you have essentially exhausted all cases.
UPDATE:
I was able to find a strategy that seems to make the computation at least possible to perform. Run time to reduce the data will probably still take months.
The trick is to identify what you might call primitive convex sets. If we say the data, we are trying to reduce is a union of convex sets $D=\cup_{i=1}^n C_i$. We say a convex set $C_q$ is primitive if a lattice point $x\in C_q$ but $x\notin C_j, j\ne q$. A primitive convex set can't be removed from $D$ without causing the lattice point $x$ being dropped from $D$.
It turns out a depth first search to enumerate all possible lattice points $x\in C_q$ with $x$ elements bounded from above is very fast. I search for all exponents less that 128 so essentially a search over all numbers $n<2^{128}$. For each lattice point $x \in C_q$ we try and find another set $C_p$ with $x \in C_p$. It turns out it's fast to determine if a lattice point is contained in another set. If we do not find a $C_p$ then the set is primitive, and we need process it no longer. Otherwise, we stop at the first set we find and record the matching. We use these recorded sets as a cache, and we further enumerate the lattice points in $C_q$. This also turns out to be fast since generally very few and often only one set overlaps with $C_q$. At the end of enumeration, we either know the set is primitive or we have a small list of sets we know can likely be used to eliminate $C_q$. This is obviously multi pass as sets can become primitive as we remove other sets.
1: Goulard, A. Question 393, L'Intermédiaire des Mathématiciens, Vol. 1, 1894
2: Knuth, Donald E. The art of computer programming, 2: seminumerical algorithms, 1969
3: Flammenkamp, A. Drei Beiträge zur diskreten Mathematik: Additionsketten, No-Three-in-Line-Problem, Sociable Numbers 1991


text:
Q: what's integration experience in java context? A client is looking for integration experience - I have done JMS and web services work in the past, but I am not too sure if that qualifies as integration experience. Pardon my limited knowledge about this field but I don't want to let go on this opportunity. Just in a bit of rush .. So asking it here..
They are also looking for ESB (enterprise service bus) experience.. perhaps that's more related to integration work.. isn't it.

A: This could mean anything. It might be integration with their legacy, business critical, application that runs on some ancient hardware. It might be integrating with third party web services. It could be anything.
One thing that might help is to know what area of business the client is in. That might give some hints.

A: Most of the time a job as integrator means you are not working on the code base of a specific product, but on the glue to integrate application togethers.
The glue itself can imply using ESB, message broker, web service, transforming data, scripts to automate job, adapters, ... a lot of possible things.
But the nature of the job is quite different from "pure" development. You don't have the control over everything, you will need to do with applications that exists and make them work together. Whether you would enjoy such a job I don't know, but take some time to think whether you would like this shift or not.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can CSS truly override the order of HTML elements on a page? If you have several divs on a page, you can use CSS to size, float them and move them round a little... but I can't see a way to get past the fact that the first div will show near the top of the page and the last div will be near the bottom! I cannot completely override the order of the elements as they come from the source HTML, can you?
I must be missing something because people say "we can change the look of the whole website by just editing one CSS file.", but that would depend on you still wanting the divs in the same order!
(P.S. I am sure no one uses position:absolute on every element on a page.)

A: With Floating, and with position absolute, you can pull some pretty good positioning magic to change some of the order of the page.
For instance, with StackOverflow, if the markup was setup right, the title, and main body content could be the first 2 things in the markup, and then the navigation/search, and finally the right hand sidebar.  This would be done by having a content container with a top margin big enough to hold the navigation and a right margin big enough to hold the sidebars.  Then both could be absolutely positioned in place.  The markup might look like:

h1 {
  position: absolute;
  top: 0;
  left: 0;
}

#content {
  margin-top: 100px;
  margin-right: 250px;
}

#nav {
  position: absolute;
  top: 0;
  left: 300px;
}

#side {
  position: absolute;
  right: 0;
  top: 100px;
}

 Stack Overflow

 Can Css truly blah blah?

  ...

quiestions
 ...

  ....

 Sponsored By

 New Zelands fish market

    ....

The important thing here is that the markup has to be done with this kind of positioning magic in mind.
Changing things so that the navbar is on the left and the sidebar below the nav be too hard.

A: CSS can take elements out of the normal flow and position them anywhere, in any manner you want.  But it cannot create a new flow.
By this I mean that you can position the last item from the html document at the beginning/top of the page/window, and you can position the first item from the html document at the end/bottom of the page/window.  But when you do this you can't position these items relative to each other; you have to know for yourself how far down the end of the page will be for the first item from the html document to be positioned correctly. If that content is dynamic (ie: from a database or CMS), this can be far from trivial.

A: You may want to look at CSS Zen Garden for excellent examples of how to do what you want.  Plenty of sample layouts via the links on the right to see the various way to move everything using strictly CSS.

A: There are a couple of ways of doing it today. The first one works on more browsers but is more limited:

*

*Using the CSS display values of table-caption, table-row and table-cell allow vertical ordering of at most three elements controlled exclusively with CSS.

*This is much more recent and will only work in all latest browsers (yes, it will fail in IE9): Use of the flexbox CSS properties.
You can view live examples and read more about these techniques at the "this is responsive" patterns page. The two I'm talking about are in the section titled "Source-Order Shift"

A: You don't need position:absolute on every element to do what you want.
You just use it on a few key items and then you can position them where-ever you want, moving all the items contained within them along with the root element of the section.

A: I think that the most important factor is to place your html elements in a way that makes sense semantically, and with luck your layout in CSS will not have to do too much work.  For example, your site's header will probably be the first element on the page, followed by common navigation, then sub-navigation, content and the footer (incomplete list).
Probably around 90-95% of the layouts you'll want to work with should be relatively trivial to manipulate that markup into something like what you're after.  the other 5-10% will still be possible, with a little more effort, but the question you need to ask yourself is "How often am I likely to want my site header positioned in the bottom-right corner of the page?"
I've always found that the layout of a site is not too tough to manipulate after the fact if you do want to dramatically change the look and feel, at least in comparison with a ground-up recode.
</2c>

A: You can position individual boxes completely independent from the source order using position:absolute. So you can move the header to the bottom of the page, and the footer to the top using CSS.
Note however that this is genereally bad for accessibility: You should have the order of the content in the source more or less in the same order that you would present it for the reader. The reason is that a screen reader or similar device will present the content in the order it is defined in the source rather than the visual order defined by your CSS.

A: Good point about the header always being first and the footer last! But I might want to move my advertising DIV from along the top, to down the right.
The other thing I've heard about is putting the content DIV first, so Google pays you more attention (relevant keywords near the top of the page score higher)...or is that a myth? Doing that would require the sort of CSS trick I'm enquiring about too.


text:
Q: Mingw32-make exits with code 2 error on my 64-bit system I need to compile and install a toolkit for a project I'm working on. However, according to the documentation the toolkit needs to be compiled using Mingw32 and I have a 64-bit system. While Mingw configures the source code without any errors or warnings, mingw32-make exits with a code 2 error.
Executing mingw-32-make throws the following errors:
In file included from src/SMILExtract.cpp:39:
src/smileCommon.hpp:162:16: error: ambiguating new declaration of 'long int getline(char**, size_t*, FILE*)'
 DLLEXPORT long getline (char **lineptr, size_t *n, FILE *stream);
                ^~~~~~~
In file included from src/smileCommon.hpp:55,
             from src/SMILExtract.cpp:39:
c:\mingw\include\stdio.h:655:33: note: old declaration 'ssize_t getline(char**, size_t*, FILE*)'
__cdecl __MINGW_NOTHROW ssize_t getline
                                 ^~~~~~~
In file included from src/smileLogger.hpp:73,
             from src/smileLogger.cpp:46:
src/smileCommon.hpp:162:16: error: In file included from ambiguating new declaration of 'src/configManager.hpp:43long int getline(char**, size_t*, FILE*),
             from '
DLLEXPORT long src/configManager.cpp:55:
getline (char **lineptr, size_t *n, FILE *stream);
            src/smileCommon.hpp:162:16: error: ambiguating new declaration of 'long int getline(char**, size_t*, FILE*)    ^~~~~~~'

and continues to exit with error code 2 as such:
Makefile:1152: recipe for target 'src/libopensmile_la-SMILExtract.lo' failed
mingw32-make[1]: *** [src/libopensmile_la-SMILExtract.lo] Error 1
mingw32-make[1]: Leaving directory 'c:/Users/MaaikeK/openEAR'
Makefile:450: recipe for target 'all' failed
mingw32-make: *** [all] Error 2

As I understand it, this may involve casting 32-bit long variables to 64-bit long variables. However, I'm not familiar with C or C++ and am not sure how to fix it so that mingw32-make is successfully executed.
Any help is appreciated!


text:
Q: MATLAB: How to convert SURF feature descriptor to SIFT feature descriptor? I am using SURF feature detector and descriptor to find feature points in images using MATLAB. I want to use these feature points and feature descriptors in another program that only accepts feature points and descriptors in Lowe's ASCII format. I found that SIFT feature descriptors are normalized to 512 and I need to do the same with SURF feature descriptor in MATLAB but I didn't get it. I have tried norm function with no luck/success. Here is how I implemented this but I could not get what I want.
I = imread('cameraman.tif');
[r, c, p] = size(I);
if p > 1
    I = rgb2gray(I);
end
points = detectSURFFeatures(I);
[features, vldPoints] = extractFeatures(I, points, 'FeatureSize', 128,...
    'Method', 'SURF');
% imshow(I); hold on;
% plot(points);
for ii = 1:size(features,1)
    v = features(ii,:);
    normFeatures(ii,:) = round(v/norm(v) * 512);
end

More about the question can be found here.
EDIT: I tried the same process to normalize the SIFT feature descriptors found using the original sift binary in MATLAB and it worked (I matched temp.key file provided by Lowe in the sift folder and my features files and both are same). It means the SURF 'features' are not the right data to normalize.
Please guide me about the SURF features found in MATLAB. I mean how they are different to sift feature descriptors?

A: This is Herbert, co-author of the SURF paper. Unfortunately, it is not possible to convert SURF features into SIFT features as the underlying math is different. Therefore, it is not possible to match SURF features against SIFT features. If you only want to normalize the features, please refer to the original source code for maybe better understanding https://github.com/herbertbay/SURF. Hope this helps...


text:
Q: Isn't a chinese character 4bytes? When I interpret this in php:
$html = htmlentities("漢");
    var_dump($html);

the output says, string(3) "漢", so 3 bytes?

A: I'm going to use a lot of @MiguelMunoz answer on a similar question here (link) :

For Chinese characters, UTF-8 only uses 6 bits of each byte to store the data.
  The other two bits contain control information. (It varies depending
  on the character. For ASCII characters, UTF-8 uses 7 bits.) It's a
  complicated encoding mechanism, but it allows UTF-8 to store
  characters up to 32-bits long. This has the advantage of taking only
  one byte per character for 7-bit (ASCII) characters, making it
  backward compatible with ASCII. But it needs 3 bytes to store 16-bits
  of data. You can learn how it works by looking it up on Wikipedia.

So : it is indeed 3 bytes.


text:
Q: Show label if Table View is empty I'm using Core Data to store a project name and display it in a table view. When the table view is empty (no data in the database) it is blank. From a user perspective this isn't great, so I want to be able to display a label that says "No Projects".
How would I do this? I would need to:

*

*Check that the database is empty and set a BOOL

*if this BOOL is set to true or YES, show a label? or set the cell.textLabel.text as "No Projects"

If i'm on the right tracks I'd really appreciate some example code to give me a push in the right direction.
Thanks

A: I ended up using the following code to check if my Core Data database is empty. Works brilliantly. This must go in the CoreDataController.m file.
NSLog(@"Total number of rows = %d ", totalNumberOfRowsInDatabase);

    if (totalNumberOfRowsInDatabase == 0)
    {

        NSLog(@"Database is empty");
        UIImage *image = [UIImage imageNamed:@"emptyTable.png"];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        [imageView setFrame:self.tableView.bounds];
        [self.tableView setBackgroundView:imageView];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.tableView setBackgroundColor:[UIColor clearColor]];

    }
    else
    {
        [self.tableView setBackgroundView:nil];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        [self.tableView setBackgroundColor:[UIColor whiteColor]];
    }

    return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];

A: -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   if (section == mySection) return MAX(dataCount, 1);
   else // yadda
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   // yadda

   if ([indexPath section] == mySection) {
      if (dataCount == 0) return mySpecialCell;
   }

   // yadda
}

A: There is a convenient lib for that: UITableView-NXEmptyView
As easy as:
tableView.nxEV_emptyView = yourView

UPD: There's something more flexible and up-to-date solution.


text:
Q: Drupal & Regular PHP Integration I'm building a new website which has one core application and many content pages. Content pages are mostly dynamic and I require a way to manage this dynamic content on a regular basis. The core application's main functionality is a 3 step process or reading user data (input page), reading data from MySQL (product page) and submitting an application to an email address (application page).
Ideally I would like to build the core application in regular PHP and leverage Drupal for its content management capabilities. Can Drupal and regular PHP be integrated as I suggest easily? My feeling is that coding the core application as a Drupal module(s) will add layers of complexity that could be difficult to code from the outset and maintain later on as the system matures - so I would really like to just use regular PHP.
Let me explain where dynamic content (managed by the CMS) intersects with the core application:
Dynamic content such as FAQ data is used both on the 'normal' help pages and also within a mini-feed displayed within core application pages down a right hand side column. In this column, 3 random questions are pulled from the database and displayed as a feed. When users click on FAQ question they are not taken away from the core application product page but are instead shown data in a pop-up window displaying the question and answer. In addition, users can browse other questions and answers through a simple navigation menu within this popup. There are 3 such like feeds as I describe above that I require on the core application product page.
So, what is the ideal solution here in terms of 'keeping things simple' for both the management of dynamic content and the ease of coding the core application? Can 'regular PHP' and Drupal co-exist 'peacefully'? If so, how is this technically possible? Because there is some content managed by Drupal contained within core application pages, can the core application still be coded in regular PHP?
Any advice / suggestions?
Thank you!
Jim.

A: This is part of a post I submitted few years ago. Unfortunately the linked article is long gone, but it might still be relevant for your needs:
Importing old-style standalone PHP scripts into Drupal system
Drupal system is a very strong CMS, but taking an existing PHP site and trying to force it on Drupal might be a hard thing to do.
The "right" way to convert a site into Drupal is to "Drupalize" it, which means to do everything "the Drupal way", which is really the right thing to do - but is some cases not everybody agrees about that.
I had an example with a company that has many HTML/PHP based sites. They heard about the flexibility and strength of Drupal, and decided it is their choice for the revolution. But, on the other hand, they want not to change anything, and that I will do it as fast as possible.
The "right way" to do it was to break each PHP script they have to its pieces, find the commons, create the right methodology with existing Drupal modules, and finish the gaps with my own additional module.
But this is not what they asked me to do - instead, I looked for a way to just import the existing PHP script into Drupal environment.
Searching for am existing solution brought me to a proof-of-concept described by Dan Morrison. In the bottom line it uses PHP output buffering commands it order to collect everything the old script does, and then to display it as part of a Drupal module. In my case I had to make some small modifications (mainly to pass variables from the request to the PHP in the relevant scope), but in the bottom line it did exactly what I needed.
Well, almost... In other cases, in which I wanted to enjoy from Drupal's Form API, I handled it differently, as I will describe later on.

A: It sounds like you are asking about two things:

*

*Including Drupal content in a custom-built PHP application.

*Displaying Drupal content in a pop-up window from the PHP application.

There are a number of different levels of integration- if your need is as simple as pulling content into a page then you may be able to simply create a view (http://drupal.org/project/views)                                                                                with that content from Drupal that you can make available to  and then include it in your web app.
If you are looking for a tighter integration between the 2 including sharing of users, sessions, etc... then it is likely also "possible" but would take additional information to understand what you need.


text:
Q: Are we need to join the Magento community? Anyone can tell me.
I am a beginner Magento developer So are we need to join the Magento community?
If yes, What are the benefits of Magento community?

A:
Just my personal perspective, joining to any online communities is up to your own discretion, it is not mandatory nor a requirement. But it can be very beneficial to someone, like us, who is just starting to learn or to get into a specific subject matter.
Magento Community in particular has offered lots of online benefits for aspiring Magento developers. One of which is the co-developer technical support. You can find a specific help to a specific issue you have or might have in your magento development.
Of course as we will become part of this community we will be imparting reliable information as well that might be helpful to others. As Magento Community is basically powered by exchanging and sharing of useful contents and information.

A: Not more idea about magento1.
In magento2.x
->Enables you to reuse third-party libraries without bundling them with source code.

->Component-based architecture with robust dependency management.

->Manages dependencies to reduce extension conflicts and compatibility issues.

->Versioned dependencies.

Semantic versioning.
Supports the PHP Framework Interoperability standard.
Refrence from
Magento 2: what are the benefits of installing magento 2 using composer?


text:
Q: Why stm32f103's elf file works well, but binary not? I'm trying to run out my firmware inside stm32f103. So when I use opencod+gdb uploading and debugging elf file, everything is fine, my firmware is working and I can set and remove breakpoints.
But it doens't work when I try to upload this firmware (which was built together with elf file) using st-flash and writing it into 0x8000000. Although I get the message that 'the firmware was uploaded successfully'.
I can see if my code runs when my leds start blinking.
BOOT0 is connected to the DTR pin of a cp2102 via npn transistor, according to the datasheet to enable bootloader. I have to set BOOT0 to high. But my serial (cp2102) is not connected when I upload my fw via st-link. So I think that DTR pin is floating or pulled down. Where is my mistake?
I was trying to mass erase my flash before uploading, it gives the same results

here is my linker's ld file:
MEMORY
{
  RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 20K
  CCMRAM (xrw) : ORIGIN = 0x00000000, LENGTH = 0
  FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 64K
  FLASHB1 (rx) : ORIGIN = 0x00000000, LENGTH = 0
  EXTMEMB0 (rx) : ORIGIN = 0x00000000, LENGTH = 0
  EXTMEMB1 (rx) : ORIGIN = 0x00000000, LENGTH = 0
  EXTMEMB2 (rx) : ORIGIN = 0x00000000, LENGTH = 0
  EXTMEMB3 (rx) : ORIGIN = 0x00000000, LENGTH = 0
  MEMORY_ARRAY (xrw)  : ORIGIN = 0x00000000, LENGTH = 0
}

and sections https://pastebin.ubuntu.com/p/N32zQf9sCm/

A: Have you tried to use the STM32CubeProgrammer?
It allows you to program the firmware using UART, SWD, JTAG and USB. Please try SWD firstly and then the UART mode to see if it is a ST bug or your UART wiring.

A: Try this
.globl _start
_start:

.word 0x20001000
.word reset
.word loop
.word loop

.thumb_func
reset:
    add r0,#1
    b reset

.thumb_func
loop:
    b loop

build, can use arm-whatever-whatever (arm-none-eabi, arm-linux-gnueabi, etc)
arm-none-eabi-as so.s -o so.o
arm-none-eabi-ld -Ttext=0x08000000 so.o -o so.elf
arm-none-eabi-objcopy -O binary so.elf so.bin
arm-none-eabi-objdump -D so.elf

so.elf:     file format elf32-littlearm

Disassembly of section .text:

08000000 <_start>:
 8000000:   20001000    andcs   r1, r0, r0
 8000004:   08000011    stmdaeq r0, {r0, r4}
 8000008:   08000015    stmdaeq r0, {r0, r2, r4}
 800000c:   08000015    stmdaeq r0, {r0, r2, r4}

08000010 <reset>:
 8000010:   3001        adds    r0, #1
 8000012:   e7fd        b.n 8000010 <reset>

08000014 <loop>:
 8000014:   e7fe        b.n 8000014 <loop>

Not that the vectors are odd, they are the address of the handler orred with one.  If you don't see this the processor won't boot.
You have said you have openocd+gdb working so either through that path or via openocd+telnet or if you have another way using the uart bootloader for example.  But use reset or a power on with boot0 set for application and then attach with openocd without resetting it, then halt and examine r0, resume, halt and examine again, is it counting, did this code load and run from flash.
If you have a blue pill then you can use this code to blink the led.
flash.s
.cpu cortex-m0
.thumb

.thumb_func
.global _start
_start:
stacktop: .word 0x20001000
.word reset
.word hang
.word hang
.word hang
.word hang
.word hang
.word hang
.word hang
.word hang
.word hang
.word hang
.word hang
.word hang
.word hang
.word hang

.thumb_func
reset:
    bl notmain
    b hang
.thumb_func
hang:   b .

.align

.thumb_func
.globl PUT32
PUT32:
    str r1,[r0]
    bx lr

.thumb_func
.globl GET32
GET32:
    ldr r0,[r0]
    bx lr

.thumb_func
.globl dummy
dummy:
    bx lr

.end

blinker01.c
void PUT32 ( unsigned int, unsigned int );
unsigned int GET32 ( unsigned int );
void dummy ( unsigned int );

#define GPIOCBASE 0x40011000
#define RCCBASE 0x40021000

int notmain ( void )
{
    unsigned int ra;
    unsigned int rx;

    ra=GET32(RCCBASE+0x18);
    ra|=1<<4; //enable port c
    PUT32(RCCBASE+0x18,ra);
    //config
    ra=GET32(GPIOCBASE+0x04);
    ra&=~(3<<20);   //PC13
    ra|=1<<20;      //PC13
    ra&=~(3<<22);   //PC13
    ra|=0<<22;      //PC13
    PUT32(GPIOCBASE+0x04,ra);

    for(rx=0;;rx++)
    {
        PUT32(GPIOCBASE+0x10,1<<(13+0));
        for(ra=0;ra<200000;ra++) dummy(ra);
        PUT32(GPIOCBASE+0x10,1<<(13+16));
        for(ra=0;ra<200000;ra++) dummy(ra);
    }
    return(0);
}

flash.ld
MEMORY
{
    rom : ORIGIN = 0x08000000, LENGTH = 0x1000
    ram : ORIGIN = 0x20000000, LENGTH = 0x1000
}

SECTIONS
{
    .text : { *(.text*) } > rom
    .rodata : { *(.rodata*) } > rom
    .bss : { *(.bss*) } > ram
}

build
arm-none-eabi-as --warn --fatal-warnings  flash.s -o flash.o
arm-none-eabi-gcc -Wall -Werror -O2 -nostdlib -nostartfiles -ffreestanding  -mthumb -c blinker01.c -o blinker01.o
arm-none-eabi-ld -o blinker01.elf -T flash.ld flash.o blinker01.o
arm-none-eabi-objdump -D blinker01.elf > blinker01.list
arm-none-eabi-objcopy blinker01.elf blinker01.bin -O binary

examine vector table
Disassembly of section .text:

08000000 <_start>:
 8000000:   20001000    andcs   r1, r0, r0
 8000004:   08000041    stmdaeq r0, {r0, r6}
 8000008:   08000047    stmdaeq r0, {r0, r1, r2, r6}
 800000c:   08000047    stmdaeq r0, {r0, r1, r2, r6}
 8000010:   08000047    stmdaeq r0, {r0, r1, r2, r6}
 8000014:   08000047    stmdaeq r0, {r0, r1, r2, r6}
 8000018:   08000047    stmdaeq r0, {r0, r1, r2, r6}
 800001c:   08000047    stmdaeq r0, {r0, r1, r2, r6}
 8000020:   08000047    stmdaeq r0, {r0, r1, r2, r6}
 8000024:   08000047    stmdaeq r0, {r0, r1, r2, r6}
 8000028:   08000047    stmdaeq r0, {r0, r1, r2, r6}
 800002c:   08000047    stmdaeq r0, {r0, r1, r2, r6}
 8000030:   08000047    stmdaeq r0, {r0, r1, r2, r6}
 8000034:   08000047    stmdaeq r0, {r0, r1, r2, r6}
 8000038:   08000047    stmdaeq r0, {r0, r1, r2, r6}
 800003c:   08000047    stmdaeq r0, {r0, r1, r2, r6}

08000040 <reset>:
 8000040:   f000 f80a   bl  8000058 <notmain>
 8000044:   e7ff        b.n 8000046 <hang>

08000046 <hang>:
 8000046:   e7fe        b.n 8000046 <hang>

Looks good.  Now program and reset.
Your schematic is not a blue pill so adjust accordingly to enable the gpio clocks and make the pin an output and so on for your led.
with either of these programs or your own, I don't use gdb have no use for it I use openocd+telnet if anything.  but either should let you dump the flash  with telnet
mdw 0x00000000 20
mdw 0x08000000 20

both should have the same data.  If not then you have a boot0 problem.
Edit
If DTR is high then boot0 is 0/GND yes?  That is what is required to boot normally.  boot0 tied low and reset tied high with a power on or low to high.
You can write a program to force DTR one way or the other.
int dtr_bit=TIOCM_DTR;
...
dtr_bit=TIOCM_DTR;
ioctl(ser_hand,TIOCMBIC,&dtr_bit);
...
dtr_bit=TIOCM_DTR;
ioctl(ser_hand,TIOCMBIS,&dtr_bit);

with the usual termios stuff to open the handle.
Or assuming DTR is supported by your dumb terminal (minicom, etc), attach to the uart, then power on and/or reset the board (paperclip, or whatever you have handy).
Since I often use the serial bootloader to load my stm32 parts or even if I use SWD, I always provide myself a solution to control boot0 and reset, be it push-buttons or jumpers or pads or some combination.

A: @old_timer Thank you very much for your detailed answer. I found that the problem is in oversized firmware. My chip has only 64k of flash and fw is 68k, so eclipse didn't tell me that the firmware is oversized and tried to flash it. Also, template in which my project based uses newlib, where startup.s was replaced by C files and I guess there is some issue. So I created a new project from openstm32 tamplate (it copied all necessary files from stdperiph lib, cmsis, etc + ld), after that I added my files, optimized build by removing unused files and set -Os flag, and it seems working for me, but the firmware size is almost oversized. I will try yr explanation )


text:
Q: Strange Internal server error on Synapse pipeline I received the below error on Synapse pipeline. I am running pipeline with more cluster size with memory optimized clusters. I am just processing 7-8 JSON files of around 90MB of size each.
Error

{ "errorCode": "145", "message": "Internal Server Error in Synapse
batch operation: '[plugins.C4T-PRIV-SAW-CAS.IR-Test.19
WorkspaceType: CCID:]
[Monitoring] Livy Endpoint=[
https://hubservice1.westeurope.azuresynapse.net:8001/api/v1.0/publish/c1e53348-b457-4afd-a61d-76553bdd369c
]. Livy Id=[4] Job failed during run time with state=[dead].'.",
"failureType": "SystemError", "target": "DF_Load_CustomsShipment",
"details": [] }

A: The internal server errors are mostly noticed when there is an intermittent/transient issue with the dependent service.
If the issue is not auto resolved or you still experience the issue consistently, I would recommend raising a support ticket for the support engineer to investigate.


text:
Q: Floating point error with rotation matrix I have been working on a c# vector class in order to practice my skills and teach myself and I came across a rather infuriating issue.
    public void Rotate (double rotation)
    {
        double xT;
        xT = x * Math.Cos (rotation * (Math.PI / 180)) - y * Math.Sin (rotation * (Math.PI / 180));
        y = x * Math.Sin (rotation * (Math.PI / 180)) + y * Math.Cos (rotation * (Math.PI / 180));
        x = xT; /*Figure out a better way to this*/
    }

This code is sloppy I know, but the issue comes from when I try a simple rotation of (1,0) 180 degrees around, instead of the expected (-1,0) that I should get, it instead returns (-1, -6.2343e-12) or something to that extent.
I understand that this is a issue with a lack of exactness in doubles, but I want to know if there is a way to have it still return a 0 instead of a number to the -12th.
Is there any way to do this?

A: It is usually faster/cleaner to work with immutable structs for vectors
public struct Vector
{
   readonly double x, y;
   public Vector(double x, double y) { this.x=x; this.y=y; }
   public Vector Rotate(double angle)
   {
       angle *= Math.PI/180;
       double cos = Math.Cos(angle), sin=Math.Sin(angle);
       return new Vector(
          x*cos-y*sin,
          x*sin+y*cos );
   }
}

Now as far as precision goes, the is no alternative but to use the trig functions in System.Math. I recommend sanitizing the angle inputs by wrapping them between -180..180 before converting into radians and using into the trig functions.


text:
Q: Full TargetPlatform to be able to use the xtext editor I need to integrate xtext with other Eclipse based tool (based on RCP plugins).
I have used as example the target platform provided in the eclipse example xtext project:

If I use the target platform from org.eclipse.xtext.example.domainmodel.releng I see no errors in my workspace. Target platform:

After setting the Target Platoform and run Eclipse runtime app, I am not able to use the xtext editor in my Eclipe runtime instance.
EDIT:
I cannot open with Domainmodel editor after changing the Target Platform:

A: The target platform may actually be flawed: tons of errors are shown when launching an Eclipse runtime on 2019-12 (which you seem to use).
It may be caused by the includeMode="slicer" which tells PDE not to fetch additional dependencies. I crafted the following target platform which seems to work well:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?pde?>
<target name="Xtext Domainmodel Example - Eclipse 2019-12" sequenceNumber="1526502000">
  <locations>
      <location includeAllPlatforms="false" includeConfigurePhase="true" includeMode="planner" includeSource="true" type="InstallableUnit">
          <repository location="http://download.eclipse.org/releases/2019-12"/>
          <unit id="org.eclipse.emf.sdk.feature.group" version="2.20.0.v20191028-0905"/>
          <unit id="org.eclipse.jdt.feature.group" version="3.18.200.v20191210-0610"/>
          <unit id="org.eclipse.sdk.feature.group" version="4.14.0.v20191210-0610"/>
          <unit id="org.eclipse.xtext.sdk.feature.group" version="2.20.0.v20191202-1256"/>
      </location>
  </locations>
</target>

A: The target platform below worked for me, used xtext 2.21:
<target name="Xtext Domainmodel Example - Eclipse Photon" sequenceNumber="1526501985">
  <locations>
    <location includeAllPlatforms="false" includeConfigurePhase="true" includeMode="planner" includeSource="true" type="InstallableUnit">
      <unit id="org.eclipse.jdt.feature.group" version="0.0.0"/>
      <unit id="org.eclipse.platform.feature.group" version="0.0.0"/>
      <unit id="org.eclipse.pde.feature.group" version="0.0.0"/>
      <unit id="org.eclipse.emf.sdk.feature.group" version="0.0.0"/>
      <repository location="https://download.eclipse.org/releases/2019-12"/>
    </location>
    <location includeAllPlatforms="false" includeConfigurePhase="true" includeMode="planner" includeSource="true" type="InstallableUnit">
      <unit id="org.eclipse.emf.mwe.sdk.feature.group" version="0.0.0"/>
      <unit id="org.eclipse.emf.mwe2.runtime.sdk.feature.group" version="0.0.0"/>
      <unit id="org.eclipse.emf.mwe2.language.sdk.feature.group" version="0.0.0"/>
      <repository location="https://download.eclipse.org/modeling/emft/mwe/updates/releases/2.11.2"/>
    </location>
    <location includeAllPlatforms="false" includeConfigurePhase="true" includeMode="planner" includeSource="true" type="InstallableUnit">
        <unit id="org.eclipse.xtext.sdk.feature.group" version="0.0.0"/>
        <repository location="https://download.eclipse.org/modeling/tmf/xtext/updates/releases/2.21.0/"/>
    </location>
    <location includeAllPlatforms="false" includeConfigurePhase="true" includeMode="planner" includeSource="true" type="InstallableUnit">
      <unit id="org.objectweb.asm" version="7.2.0.v20191010-1910"/>
      <unit id="org.objectweb.asm.tree" version="7.2.0.v20191010-1910"/>
      <unit id="com.google.inject" version="3.0.0.v201605172100"/>
      <unit id="org.apache.commons.cli" version="1.2.0.v201404270220"/>
      <unit id="com.google.guava" version="27.1.0.v20190517-1946"/>
      <unit id="io.github.classgraph" version="4.8.35.v20190528-1517"/>
      <repository location="https://download.eclipse.org/tools/orbit/downloads/2019-12"/>
    </location>
    <location includeAllPlatforms="false" includeConfigurePhase="true" includeMode="planner" includeSource="true" type="InstallableUnit">
      <unit id="org.eclipse.draw2d.feature.group" version="3.10.100.201606061308"/>
      <repository location="https://download.eclipse.org/tools/gef/updates/legacy/releases"/>
    </location>
  </locations>
</target>


text:
Q: Select Negation of one table from another along with data in master table sql query for oracle I am stuck with an issue. I have 3 tables in my oracle database.
First table contains all registered employees: ID, FNAME, LNAME
Second table contains all employees(Registered + Unregistered): - ID, FNAME, LNAME
Third table is a master table having all details of employee along with address. ID is common in all 3 tables.
Here my requriment is to write a query which will display all not registered employees with there address details.
Some ID's are null as well in all tables which have to be neglected.
Table 1 - Registered Users
Table 2 - Registered+Not Registered
Table 3 - Master Table which contains additional information
Requirement:- Select ID, Name, Address for not registered users.
Query will be more helpful instead of explanation.
Thanks,

A: I think not exists or not in does what you want:
select m.*
from masters m
where not exists (select 1
                  from registered r
                  where r.id = m.id
                 );


text:
Q: PCRE replace multiple values with multiple strings I am trying to mass replace some keywords in a csv file, for example I have a list of keywords cat,mouse,dog with i would like to replace with something,else,here , I am currently using this http://phpcsv.sourceforge.net/phpcsv-1.0.php it is perfect and it says it uses PCRE for replacing values , my question is what do i need to type in the search and replace field to achieve this result ?

A: You could use
Search (?<=^|,)(cat|mouse|dog)(?=,|$) Replace ${1}2
The ${1} is used to reference the string captured by the () in the Search field.
Normally you could just use $1, but because it is followed immediately by 2, the 1 needs to be enclosed in {}.
If the values may be enclosed in " add "? before and after (cat|mouse|dog).
(?<=^|,) means looking behind there must be the start of a line or a comma.
(?=,|$) means looking ahead there must be a comma or the end of a line.
If the replacements are different for each keyword, I think you would have to do each separately, e.g.
Search (?<=^|,)cat(?=,|$) Replace hamster
Alternatively, if using your own code you could make all the replacements in one go by passing arrays as arguments to preg_replace.


text:
Q: Editing a previously saved document also updates it in the db FYI, using Mongodb, Express, and Mongoose on node.js.
I'm saving a document (a user, that contains data) with .save(), and then I want to return this user on the request through the .send().
However I certainly do not want to return its password, so I'm accessing the previously saved document and removing the password with the following:
user.status = /* Create new status and assign */;
user.save();
user.password = undefined;

It should be noted that this is inside a couple of callbacks as such (pseudo-code):
Users.findOne (
    // Do stuff
    user.token = /* New token */;
    user.save();

    Shops.findOne( /* search by userId */
        // Do stuff
        user._shopId = shopId;
        user.status = "active";
        user.save();

        // Hide password
        user.password = undefined;

        // Send
        res.send({success: true, user: user});
    )
)

I expected the database document for this user to remain the same, since I did not save it after editing it. And yes, if I don't .save(), I can change it at will (like using an update to update it and on its callback .send()).
However, the document's password gets removed. Is the .save() somehow asynchronous, or only runs at the end of the thread's life even though I put it at the middle of its code?
Thanks.

A: To the user.save(); give a callback. Something like this :
Users.findOne (
// Do stuff
user.token = /* New token */;
user.save();

Shops.findOne( /* search by userId */
    // Do stuff
    user._shopId = shopId;
    user.status = "active";
    user.save(function(err, user){
        if(err) console.log(err);
        if(user){
            // Hide password
            user.password = undefined;
            res.send({success: true, user: user});
        }
});
));

Everything in the callback will be synchronous. So the response will be sent only when the user is saved.
Should be noted that .save() uses the object's pointer to save, and doesn't statically send the object through a parameter, therefore changing this object before the .save() finishes means it will be changed before it's saved in the database.


text:
Q: Is there a way in gmock to return modified input arg without invoke? I want to do something like this:
EXPECT_CALL(*mock, method(5)).WillOnce(Return(arg1 * 2));

where arg1 should be equal to first arg of called method. Is there a way to do that without testing::Invoke?

A: Method 1:
You can use a custom matcher, as the other answer mentioned, however, notice that the preferred way of using custom matchers is by using functors, not the ACTION macro (See here).
Here is an example:
// Define a functor first:
struct Double {
  template <typename T>
  T operator()(T arg) {
    return 2 * (arg);
  }
};

TEST(MyTest, CanDoubleWithFunctor) {
  MyMock mock;

  // Use the functor in the test:
  EXPECT_CALL(mock, method(5)).WillOnce(Double{});

  EXPECT_EQ(mock.method(5), 10);
}

See a working example here: https://godbolt.org/z/h4aaPdWMs

Method 2:
Besides the custom matcher, you can use WithArg see here, and pass the first argument to it, which will then be passed to a function that takes one argument. This function can be standalone, or a lambda function:
class MyMock {
 public:
  MOCK_METHOD(int, method, (int), ());
};

TEST(MyTest, CanDouble) {
  MyMock mock;

  EXPECT_CALL(mock, method(5)).WillOnce(WithArg<0>([](int x) {
    return x * 2;
  }));

  EXPECT_EQ(mock.method(5), 10);
}

See this working example.

A: You can define custom action for that:
ACTION(ReturnDoubled) {
    return arg0 * 2;
}

class Mock {
   public:
    MOCK_METHOD(int, method, (int), ());
};

TEST(Foo, bar) {
    Mock mock;
    EXPECT_CALL(mock, method(5)).WillOnce(ReturnDoubled());

    ASSERT_EQ(mock.method(5), 10);
}

https://godbolt.org/z/dare654Yj


text:
Q: Open Firefox iMacro From Mac Terminal I'm trying to open an iMacro from the mac terminal. I have the following:
    open -a Firefox imacros://run/?m=#Current.iim
This however tries to read the link as a file on my computer. Is there anyway to say that this is a link and not a file. If I run imacros://run/?m=#Current.iim right on the browser it works fine.


text:
Q: Fill rectangle with image in Java How can I fill the following rectangle using an image? Can anyone help me please?
public void paintComponent(Graphics g) {
         setOpaque(false);
        //Paint a filled rectangle at user's chosen point.
        if (point != null) {
            g.drawRect(0, 0,
                       rectWidth - 1, rectHeight - 1);
            g.setColor(Color.yellow);
            g.fillRect(1, 1,
                       rectWidth - 2, rectHeight - 2);
            }}

I tried this code but I couldn't find a way to make it work:
File imageFile = new File("duck.jpg");
BufferedImage img;
Graphics2D graph = img.createGraphics();
graph.setColor(Color.BLACK);
graph.fill(new Rectangle(1, 2, rectWidth, rectHeight));
graph.dispose();
ImageIO.write(img, "jpg", new File("duck.jpg"));

A: You have to load an image into an Image object (like BufferedImage) and then call
graphics.drawImage()
on that image, giving the coordinates and other info.
Look in the tutorial for more info


text:
Q: How do you access the Google Sheets API via a Google Apps Script? I am trying to call the Google Sheets API via a Google Apps Script. As an example, I have followed the instructions provided here:
https://developers.google.com/sheets/api/quickstart/js
I have generated the client ID and API Key via my Google Cloud Platform project as suggested elsewhere.
Now, I have created a google apps script with two files, the Code.gs file and a file called index.html containing the code copied and pasted from the Google Sheets API Quickstart above (with my client ID and API inserted).
When testing deployment, I get the following error message:
{
  "error": "idpiframe_initialization_failed",
  "details": "Not a valid origin for the client: https://<some numbers>-script.googleusercontent.com has not been registered for client ID <MY_CLIENT_ID>. Please go to https://console.developers.google.com/ and register this origin for your project's client ID."
}

I have registered script.google.com as an origin for my project.
Am I doing something obviously wrong? How would I proceed from here to get past this error?

A: If you want to make use of the Sheets API in Apps Script you will have to make use of the Sheets Advanced Service.
For this you will have to go to Services + and then add the Google Sheets API:

Since this is an advanced service, the authorization flow will be handled by Google so you won't have to provide the clientId and the API key.
Reference

*

*Apps Script Advanced Google Services.


text:
Q: Save quiver plot with tikzplotlib I want to save a quiver plot using tikzplotlib.
Here is a MWE:
import matplotlib.pyplot as plt
import numpy as np
x,y = np.meshgrid(np.arange(-2, 2, .2), np.arange(-2, 2, .25))
z = x*np.exp(-x**2 - y**2)
v, u = np.gradient(z, .2, .2)
fig, ax = plt.subplots()
q = ax.quiver(x,y,u,v)
import tikzplotlib

tikzplotlib.save("2delete.tex")

I get an error like this:
 File "/usr/local/lib/python3.6/dist-packages/tikzplotlib/_patch.py", line 69, in <genexpr>
    yield tuple(seq[i % len(seq)] for seq in seqs)
ZeroDivisionError: integer division or modulo by zero

Does anybody know this problem and a workaround?
Thank you!

A: From GitHub repository:
Of course, not all figures produced by matplotlib can be converted without error

Instead of load plot directly into tex you can load saved image.


text:
Q: Is it possible to change the style of CustomComponent caption in Vaadin 8 I am using a CustomComponent inside a VerticalLayout in Vaadin. I want to change the style of caption to bold But it is not working.
My calss  as below:
public class MyTab extends CustomComponent implements UpdatableComponent {
    public MyTab() {

        HorizontalSplitPanel panel = new HorizontalSplitPanel();
        panel.setSplitPosition(218, Unit.PIXELS);
        panel.setFirstComponent(createFirstPanelComponent());
        panel.setSecondComponent(createSecondPanelComponent());
        panel.setLocked(true);
        panel.addStyleName("has_border");
        setCaption("This is my title");
        addStyleName("padding-bottom-10px");
        addStyleName("bold-caption");
        }
        setSizeFull();
        setCompositionRoot(panel);
    }

}

I have tried these definitions for "bold-caption" inside my scss file . None of them has worked:

*

*.bold-caption {
       font-weight: bolder !important;   }

*.bold-caption.v-caption{
    font-weight: bolder !important;
}

*.bold-caption.v-caption.v-captiontext{
    font-weight: bolder !important;
}

*.bold-caption { .v-caption{
    font-weight: bolder !important;
} }

The main question is also how to style caption of custom component in Vaadin inside different layout?
Any solution?

A: I figured this out.
I used:
.v-caption.bold-caption {
    font-weight: bolder !important;
  }

Don't forget to remvoe cache and build the application if you are using Vaadin add-ones.


text:
Q: How to get xml format in Django Rest Framework I'm trying to get xml format in Django Rest FrameWork,I tried the tutorial provided by Django Rest Framework, I'm new to django, I did the following.
settings.py
 INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',
        'books',
        'users',
    ]

urls.py
from django.conf.urls import url
from django.contrib import admin
from books.views import *
from users.views import *
from rest_framework.urlpatterns import format_suffix_patterns

    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^books/all/$', all_books),
        url(r'^user/', get_user)
    ]

    urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html','xml'])

views.py
from rest_framework.response import Response
from rest_framework.decorators import api_view
from books.serializers import *
from books.models import *

# Create your views here.

@api_view(['GET'])
def all_books(request):
    books = Book.objects.all()
    serializers = BookSerializer(books,many=True)
    return Response(serializers.data)

When I try to access the xml data, I Get this error by doing ?format=xml
{"detail":"Not found."}

the tutorial link http://www.django-rest-framework.org/api-guide/format-suffixes/

A: Actually your settings.py is missing the xml parser config.

*

*install rest_framework_xml : pip install djangorestframework-xml

*Update INSTALLED_APPS in settings.py
INSTALLED_APPS = [
  'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',
  'rest_framework',
  'rest_framework_xml',
  'books',
  'users',
]

*Add xml parser in settings.py:

REST_FRAMEWORK = {
  'DEFAULT_PARSER_CLASSES': (
    'rest_framework_xml.parsers.XMLParser',
  ),
    'DEFAULT_RENDERER_CLASSES': (
    'rest_framework_xml.renderers.XMLRenderer',
  ),
}


text:
Q: Article usage here? Someone in my office has written this email.
I am on leave after 2:30pm today. Have a doctor's appointment for my son.
Is the above sentence correct?
My correction would be -
I will be on a leave after 2:30 pm today. I have an appointment with doctor for my son.

A: The first sentence is using the present tense to describe a current state of affairs, even though the action is in the future. We can use the present tense when future events are seen as timetabled, or inevitable. Examples

*

*The plane leaves at six pm.

*My music lesson is on Saturday next week.

*The Juno probe arrives at Jupiter on the 4th of July.

It would be equally correct to use a future tense:

*

*I will be on leave...

*I'll be on leave ....

*I'm going to be on leave...

The second sentence has had the word "I" cut from it. This is an example of ellipsis of the subject. It is more common in spoken English, and is normally avoided in formal written English. The use of the possessive (doctor's) is natural and correct.
Your second sentence is not idiomatic, since the word "doctor" needs an article. You could say "I have an appointment with the doctor...", however the original version means the same and is shorter.

A: In the first sentence

I am on leave after 2:30pm today.

your office coworker is saying they will be out for an extended period of time ("on leave"), beginning at 2:30pm in the afternoon.
In the second sentence, your coworker is telling you why they are out

Have a doctor's appointment for my son.

They need to take their son to the doctor's.
The listener could easily assume that both are related, and possibly your coworker's son has a serious condition since your coworker is taking "leave" (possibly "medical leave") to look after their son.
If your coworker was only leaving for the afternoon because of the doctor's appointment, they might usually say

I am out of the office today after 2:30pm.
  I am leaving the office at 2:30pm.
  I will be out after 2:30pm today.

It might be that their son is fairly young since

(I) Have a doctor's appointment for my son.

implies the appointment was made by the parent, instead of

My son has a doctor appointment.


text:
Q: JQuery blockUI plugin - can't remove iFrame I have upload image form implemented. When user click submit to upload image to server I display modal window with Jquery.BlockUI plugin. In that modal view I display iFrame with uploading information data. Problem is when I add iFrame it displays fine, however it stays on body after closing modal view. I don't know how to remove it from body?
$(function () {
            $("#Form").ajaxForm({
                iframe: true,
                dataType: "html",
                url: "/Images/Upload",
                target: "body",
                type: "POST",
                success: function (result) {
                    //$.unblockUI();
                    $('body.divAI').unblock();
                },
                beforeSubmit: function () {
                    $('body').append('

Add Item

');

                    $.blockUI({ message: $("#divAI"), css: {
                        width: '425px',
                        height: '225px',
                        left: ($(window).width() - 425) / 2 + 'px',
                        top: '10%'
                    }
                    });
                },
                error: function (response) {
                    $.unblockUI();
                }
            });
        });

A: Have you tried $("iframe").remove(); before closing the modal? You could also target the iframe by id if there are more iframe's on the page.


text:
Q: Run bash script from PHP script I am running an Apache server on CentOS and need to run some bash scripts from PHP page. Running commands which do NOT need write or execute permission from PHP file works fine (for example shell_exec('ls /var/www/html/scripts/')), but I have problem running the commands that do need write or execute permission. For example this commands does nothing:
<?php
   $output = shell_exec('/var/www/html/scripts/test.sh');
   echo $output;
?>

I made apache user owner and granted necessary permissions to scripts directory:
drwxr-xr-x. 2 apache apache   21 Jun  3 09:54 scripts

and test.sh file as can be seen, but there was no lock.
-rwxr-xr-x. 1 apache apache 51 Jun  3 09:54 test.sh

I also tried to sudo the command in PHP file and added the line below to the end of Sudoers file, but nothing changed.
apache ALL=NOPASSWD: /var/www/html/scripts/test.sh

Also I checked PHP safe_mode which is off and there is no restriction in php.ini file:
disable_functions =

Your kind help would be highly appreciated.
NOTE:
I edited my bash script and added sudo like below:
#!/bin/bash
echo "Hi from test.sh";
sudo touch /var/www/html/scripts/file.log;

Now when I run the file as apache user using this command, it runs successfully:
su -s /bin/sh apache -c "/var/www/html/scripts/test.sh"

But through the php web page it only runs echo "Hi from test.sh"; line. When I check logs, there are lines below for running command above:
su: pam_unix(su:session): session opened for user apache by root(uid=0)
sudo:  apache : TTY=unknown ; PWD=/var/www/html ; USER=root ; COMMAND=/bin/touch fromweb.log
su: pam_unix(su:session): session closed for user apache

And the generated log when running from php web page:
sudo:  apache : TTY=unknown ; PWD=/var/www/html/scripts ; USER=root ; COMMAND=/bin/touch fromweb.log

Missing pam_unix(su:session) open and close.

A: I found what the issue was. It was because of Linux SELinux feature. This feature applies a least-privilege policy and denies any unnecessary command from running on Linux. The bash script is running successfully after disabling this feature. To do so, edit the file /etc/selinux/config and change SELINUX=enforcing to SELINUX=disabled and reboot the system. THIS IS NOT RECOMMENDED FOR SECURITY REASONS, however. You may check the link below to only create some exceptions rather than completely disabling SELinux.
https://wiki.centos.org/HowTos/SELinux


text:
Q: Limit User Control of JTextField I've got a game where you create words using letters in a letter bank. Every time a letter is typed, I want the letter icon to disappear, and reappear when it is erased. I have most of the functionality done already, but there are a few bugs I cannot fix. Right now I am using a KeyListener and filtering input/taking action based on key events. However, complications arise when multiple keys are pressed at the same time.
The input filtering isn't my main problem, it's putting the letters back in the bank when they are erased. Is there a way to remove the caret entirely and only allow users to add input to / backspace from the end of the JTextField? Also, any tips about handling button mashing correctly would be greatly appreciated. Thanks!
Note: If you've ever played Super Text Twist, that's basically the type of guessing method that I'm going for.

A: You can extend PlainDocument (used in JTextField) and override insertString() and remove() methods. The yoou can check what's inserted or removed and adapt your interface.
Or (may be even better) use the DocumentFilter as suggested Hovercraft Full Of Eels


text:
Q: Batch: Close executable when batch file is terminated I have a batch file which continuously opens a game if it crashes. Im trying to make it so that if the batch file is closed the program will terminate.
@echo off

if "%1" equ "loop" goto %1
start "" /WAIT /B "%~F0" loop
Taskkill /f /im "Crossy Road.exe" >nul
goto :EOF

:loop
tasklist /FI "IMAGENAME eq Crossy Road.exe" 2>NUL | find /I /N "Crossy Road.exe">NUL
if "%ERRORLEVEL%"=="1" explorer.exe shell:appsFolder\Yodo1Ltd.CrossyRoad_s3s3f300emkze!App
goto loop
pause
exit

A: You can create a companion vbs from within a batch script that monitors the cmd.exe process and calls another batch script to end the desired processes. (that companion batch script can also be created from within your main batch program)

@ECHO OFF

::: Creates a VBS script to monitor the Cmd Process
:CreateMonitor
(
ECHO Set objWMIService = GetObject ("winmgmts:"^) 'Defines winmgmts service
ECHO Set proc = objWMIService.ExecQuery("select * from Win32_Process Where Name='cmd.exe'"^) 'Gets Current Process Count
ECHO DO while proc.count ^> 0 'Establishes Loop that ends when no cmd.exe windows or bat programs are open
ECHO Set proc = objWMIService.ExecQuery("select * from Win32_Process Where Name='cmd.exe'"^) 'Gets Current Process Count
ECHO if proc.count ^< 1 then exit do 'exits while loop once bat program is closed
ECHO wscript.sleep 2500 'Delays loop by 2.5 seconds to reduce CPU usage
ECHO loop 'Returns to get new process Count
ECHO Set WshShell=createobject("wscript.shell"^) 'Creates Shell to
ECHO WshShell.run "INSERT PATH TO TASK-KILL .BAT HERE", 0, false 'Launches hidden .bat to close desired programs
) >"%TEMP%\myprogramMonitor.vbs"

::: Starts the VBS to monitor if cmd.exe is open

Start "" "%TEMP%\myprogramMonitor.vbs"

GOTO :EOF

It's also prudent to include a taskill for the WScript process in the companion batch:
taskkill /pid WScript.exe /f /t >nul


text:
Q: Basic Java Program : String objects won't even input I'm a C++ programmer new to Java and have trouble with Strings as fields(or attribute or whatever) of classes.
import java.util.Scanner;
class Student{
    String name;
    static int count=0;
    int regno;
    double marks;
    Student(){
        count++;
    }
    static void getCount(){
        System.out.println("Count is "+count);
    }
    void setName(String n1){
        name=n1;
    }
    void setMarks(double m1){
        marks=m1;
    }
    void setRegNo(int rno){
        regno=rno;
    }
    String getName(){
        return name;
    }
    int getRegNo(){
        return regno;
    }
    double getMarks(){
        return marks;
    }
}
class Demo{
    int i;
    Student s[]=new Student[3];
    Scanner in=new Scanner(System.in);
    Demo(){
        for(i=0;i<3;i++){
            s[i]=new Student();
            System.out.println("Enter name of student "+(i+1)+" :");
            s[i].setName(in.nextLine());
            System.out.println("Enter Reg. No. of student "+(i+1)+" :");
            s[i].setRegNo(in.nextInt());
            System.out.println("Enter marks of student "+(i+1)+" :");
            s[i].setMarks(in.nextDouble());
        }
    }
    public void Display(){
        System.out.println("Students with marks >70 : ");
        System.out.println("RegNo\tName\tMarks\t");
        for(i=0;i<3;i++){
            System.out.println(s[i].getRegNo()+"\t"+s[i].getName()+"\t"+s[i].getMarks());
        }
    }
}
class P4{
    public static void main(String args[]){
        Demo d=new Demo();
        d.Display();
    }
}

Output:
Enter name of student 1 :
1
Enter Reg. No. of student 1 :
1
Enter marks of student 1 :
100
Enter name of student 2 :
Enter Reg. No. of student 2 :
2
Enter marks of student 2 :
100
Enter name of student 3 :
Enter Reg. No. of student 3 :
3
Enter marks of student 3 :
100
Students with marks >70 :
RegNo   Name    Marks
1   1   100.0
2       100.0
3       100.0

The Trouble:
From the second iteration of the for loop, the program directly asks me to enter regno and marks skipping the name String.I don't understand how it works for the first iteration but not the others.Please explain me what went wrong here.

A: My guess is that it's the same problem as many have with e.g. scanf in C, namely that the ending newline from the previous input is still in the input buffer, and that leads to the nextLine function to see this newline as an empty line.
You need a way to discard leading whitespace before inputting strings.

A: Type in.nextLine() after s[i].setMarks(in.nextDouble());
What is happening :
for(i=0;i<3;i++){
            s[i]=new Student();
            System.out.println("Enter name of student "+(i+1)+" :");
            s[i].setName(in.nextLine()); // second time around, you read the newline character
            System.out.println("Enter Reg. No. of student "+(i+1)+" :");
            s[i].setRegNo(in.nextInt());// once you press "enter" here, the newline
            System.out.println("Enter marks of student "+(i+1)+" :");
            s[i].setMarks(in.nextDouble());// once you press "enter" here, the newline character is added to the input stream
        }

A: The problem is that you are mixing nextInt()/nextDouble() with nextLine().
When you enter your int/double, it will be followed by a new line, and when you call nextLine() in the next iteration, it will read this new line.
The solution is to call nextLine() (and discard the result) after calling nextInt()/nextDouble().
Here is a simple code that exhibit the problem (and the solution):
try (Scanner in = new Scanner(System.in)) {
    System.out.println("Int:");
    in.nextInt();
    // in.nextLine(); // uncomment to fix the problem
    System.out.println("Line:");
    in.nextLine();
}


text:
Q: Installing git on Windows: Git Bash Here or git-cheetah shell extension? I'm installing Git on Windows XP. During the setup, the installer asks whether I want:

1: Context menu entries: "Git Bash Here" (and the "Git GUI Here" option)

or

2: "git-cheetah shell extension (32-bit only)"

Basically, which should I do? I can't do both.
More specifically, what is the most commonly used version? Is the Git Bash tool the same as the shell extension?

A: git bash here will give you a console window with access to git commands, shell extension will give you right click menu access to git commands creating an environment similar to TortoiseSVN and such.


text:
Q: How to limit raft.log size in nats streaming server? I set up nats streaming server in cluster mode (according to instructions found here) and I noticed raft.log is growing really fast when I benchmark it with a load around 200msg/s where message size is ~1MB.
I use default channel settings:
---------- Store Limits ----------
Channels:                  100 *
--------- Channels Limits --------
Subscriptions:          1000 *
Messages     :       1000000 *
Bytes        :     976.56 MB *
Age          :     unlimited *
Inactivity   :     unlimited *

Are there any configuration parameters that could help limiting size or truncating the file?

A: We use go.etcd.io/boltdb for the RAFT log backend and this does not offer truncation/compaction. The log contains all data replicated in the NATS Streaming system, but when nodes are in sync, snapshots should occur at some random (but no less than 2 minutes) interval. This should allow RAFT to delete entries from its log, which mean that when adding new data, the free space should be reused and not result in growth of the main log file. Of course, if the rate/amount of data added surpass the free space from the previous snapshot, the raft.log file will grow.


text:
Q: masonry.js with infinite scroll - content is disappearing I'm new to javascript/jquery and will admit I'm not sure how it all works at the moment, I've been doing a lot of googling to get this far!   So I have a site that is using masonry.js to display items in a pinterest type way.   Now the first page loads fine and is laid out as expected.   When the user scrolls to the bottom of the page, my new content gets added in the right place on the screen BUT the old content is gone!   The new content is added in the right place but everything before it is blank!  This so nearly works, I just can't see why the scroll function is appending content but removing the original!

The code that loads the initial content is:
    <script type="text/javascript">
$(document).ready(function() {
    var $grid = $('.grid').masonry({
    // set itemSelector so .grid-sizer is not used in layout
    itemSelector: '.grid-item',
    // use element for option
    columnWidth: '.grid-sizer',
    gutter: 10
    })
});

    var track_load = 0; //total loaded record group(s)
    var loading  = false; //to prevents multiple ajax loads
    var total_groups = <?php echo $total_groups; ?>; //total record group(s)
    var leagueid = <?php echo "1";?>;
    var content = $('.grid').load("league_news1.php", {'group_no':track_load,'leagueid':leagueid}, function() {track_load++;
    $(".grid").imagesLoaded(function() {
    $(".grid").append(content).masonry("appended", content);
});

});
</script>

And then this is what I use to add more content when the user scrolls:
    <script type='text/javascript'>
        $(window).scroll(function() { //detect page scroll

        if ($(window).scrollTop() >= $(document).height() - $(window).height() - 60) {

            if(track_load <= total_groups && loading==false) //theres more data to load
            {

                loading = true; //prevent further ajax loading

                $('.animation_image').show(); //show loading image
                    //load data from the server using a HTTP POST request

                    var new_content = $('.grid').load("league_news1.php", {'group_no':track_load,'leagueid':leagueid}, function() {
                    $(".grid").imagesLoaded(function() {
                    $(".grid").append(new_content).masonry("appended",new_content);

                    //hide loading image
                    $('.animation_image').hide(); //hide loading image once data is received

                    track_load++; //loaded group increment
                    loading = false;

                }).fail(function(xhr, ajaxOptions, thrownError) { //any errors?

                    alert(thrownError); //alert with HTTP error
                    $('.animation_image').hide(); //hide loading image
                    loading = false;

                });

            });
        }
    }
});
</script>

A: After speaking with the developer of the plugin (although it was my jquery that was at fault, not his excellent plugin) the answer was to wrap content in a jquery object like so:
$.get("league_news.php", {'group_no':track_load,'leagueid':leagueid}, function(data) {
        track_load++;
        var $content=$(data);
        $content.imagesLoaded(function() {
        $(".grid").append($content).masonry("appended", $content);
    });

    });


text:
Q: LuaDec for LuaJIT? Подскажите, как адаптировать декомпилятор LuaDec к скриптам LuaJIT
Один парень каким-то образом декомпилирует LuaJIT скрипты, используя этот декомпилятор, но не хочет говорить, как
LuaJIT 2.1.0-бета3
>luadec Fram.luac
luadec: Fram.luac: not a precompiled chunk

A: Похоже, что LuaDec из коробки не умеет декомпилировать скрипты LuaJIT, не смотря на то, что в вики и приведено описание байткода.
Но хорошая новость в том, что для LuaJIT есть свой рабочий декомпилятор: https://gitlab.com/znixian/luajit-decompiler
Чтобы декомпилировать скрипт, нужно установить python3 и выполнить в консоли команду:
python3 ./main.py -f Fram.luac > Fram.lua

С вашим скриптом справляется на ура:
script_name("\\xd2\\xe5\\xeb\\xe5\\xef\\xee\\xf0\\xf2 \\xed\\xe0 \\xec\\xe5\\xf2\\xea\\xf3: Evolve-Rp")
script_version("Latest Version")
script_author("Ded_Fedot")
require("lib.moonloader")
require("lib.sampfuncs")

function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then
        return
    end

    while not isSampAvailable() do
        wait(200)
    end

    sampRegisterChatCommand("dedtp", teleport)
    sampAddChatMessage("{00D5FF}[Evolve-Rp] {FFFFFF}\\xd2\\xe5\\xeb\\xe5\\xef\\xee\\xf0\\xf2 \\xed\\xe0 {FFE741}\\xec\\xe5\\xf2\\xea\\xf3", 54783)
    sampAddChatMessage("{00D5FF}[Evolve-Rp] {FFFFFF}\\xc0\\xe2\\xf2\\xee\\xf0: {EE0047}Ded_Fedot", 54783)

    while true do
        wait(0)

        if activ == true then
            tpoot = true
            stpoot = true

            wait(1000)
            requestCollision(posX, posY)
            loadScene(posX, posY, posZ)

            posZ = getGroundZFor3dCoord(posX, posY, 500)

            setCharCoordinates(playerPed, posX, posY, posZ)
            wait(2000)

            tpoot = false

            wait(1000)

            stpoot = false
            activ = false

            addOneOffSound(0, 0, 0, 1139)
            printStringNow("~w~Teleport ~g~Successful~n~~y~by ~p~Ded_Fedot", 3000)
        end
    end
end

function teleport()
    metka, posX, posY, posZ = getTargetBlipCoordinates()

    if metka then
        activ = true
        tpoot = true
        stpoot = true
    else
        sampAddChatMessage("\\xcf\\xee\\xf1\\xf2\\xe0\\xe2\\xfc \\xec\\xe5\\xf2\\xea\\xf3... {EE0047}\\xcc\\xf3\\xe4\\xe8\\xeb\\xe0", -1)
        addOneOffSound(0, 0, 0, 1138)
    end
end

function onSendPacket(slot0)
    if slot0 == 207 and tpoot == true then
        return false
    end
end

function onReceiveRpc(slot0)
    if slot0 == 12 and stpoot == true then
        return false
    end
end


text:
Q: How to unit test an kotlin extenion function that has a generic type kotlin 1.2.51

I have the following shared preferences that uses a generic extension function.
class SharedUserPreferencesImp(private val context: Context,
                               private val sharedPreferenceName: String): SharedUserPreferences {

    private val sharedPreferences: SharedPreferences by lazy {
        context.getSharedPreferences(sharedPreferenceName, Context.MODE_PRIVATE)
    }

    override fun <T : Any> T.getValue(key: String): T {
        with(sharedPreferences) {
            val result: Any = when (this@getValue) {
                is String -> getString(key, this@getValue)
                is Boolean -> getBoolean(key, this@getValue)
                is Int -> getInt(key, this@getValue)
                is Long -> getLong(key, this@getValue)
                is Float -> getFloat(key, this@getValue)
                else -> {
                    throw UnsupportedOperationException("Cannot find preference casting error")
                }
            }
            @Suppress("unchecked_cast")
            return result as T
        }
    }
}

I am trying to write a unit test for this method. As you can see in my test method the testName.getValue("key") the getValue is not recognized.
class SharedUserPreferencesImpTest {
    private lateinit var sharedUserPreferences: SharedUserPreferences
    private val context: Context = mock()

    @Before
    fun setUp() {
        sharedUserPreferences = SharedUserPreferencesImp(context, "sharedPreferenceName")
        assertThat(sharedUserPreferences).isNotNull
    }

    @Test
    fun `should get a string value from shared preferences`() {
        val testName = "this is a test"

        testName.getValue("key")
    }
}

What is the best way to test a extension function that has a generic type?
Many thanks for any suggestions,

A: There is a conflict between T.getValue(key: String) being a extension function and SharedUserPreferencesImp member function.
You can make T.getValue(key: String) high-level function and this solves a problem. Here is example code:
fun <T : Any> T.getValue(key: String, sharedPreferences: SharedUserPreferencesImp): T {
    with(sharedPreferences.sharedPreferences) {
        val result: Any = when (this@getValue) {
            is String -> getString(key, this@getValue)
            is Boolean -> getBoolean(key, this@getValue)
            is Int -> getInt(key, this@getValue)
            is Long -> getLong(key, this@getValue)
            is Float -> getFloat(key, this@getValue)
            else -> {
                throw UnsupportedOperationException("Cannot find preference casting error")
            }
        }
        @Suppress("unchecked_cast")
        return result as T
    }
}

class SharedUserPreferencesImp(private val context: Context,
                               private val sharedPreferenceName: String): SharedUserPreferences {

    val sharedPreferences: SharedPreferences by lazy {
        context.getSharedPreferences(sharedPreferenceName, Context.MODE_PRIVATE)
    }
}

You can also take a look at this two great libraries:
https://github.com/chibatching/Kotpref
https://github.com/MarcinMoskala/PreferenceHolder


text:
Q: Panel Data with time gap, How to create lag variable I am dealing with panel data with a time gap. but not the same time gap.
Year variable has 1980, 1990, 2000, 2010, 2015, and 2020.
As you can see it has a 10 year time gap up to 2010, but five-years between 2010 and 2020.
After setting up for panel data structure in Stata (using xtset command), I wanted to use the time (lag) operator for my main variable interest and outcome variable. However, when I use L. in front of the variable name, Stata tells me no observations.
Isn't it automatically taking the previous time period?
Or do I create manually the lag variables?

A: What we need to know, but can't see, is exactly what code you used, specifically xtset. But it's possible to guess. Here I fabricate one panel; a structure with more panels doesn't show different problems.
clear
input Y Year
1  1980
2  1990
3  2000
4  2010
5  2015
6  2020
end

gen ID = 42

If you just specify panel and year variables, Stata expects unit spacing, so lag 1 with yearly data means "the previous year". Asking for a lag 1 variable is legal, but all values are missing.
xtset ID Year
gen lag1 = L1.Y

If you specify delta(5) then a lag 1 variable is missing in all but two observations.
xtset ID Year, delta(5)
gen lag5 = L1.Y

If you try delta(10) that won't work (unless you drop 2015).
xtset ID Year, delta(10)

You can also do this:
bysort ID (Year) : gen prev = Y[_n-1]

Bringing your results together
list , sep(0)

     +------------------------------------+
     | Y   Year   ID   lag1   lag5   prev |
     |------------------------------------|
  1. | 1   1980   42      .      .      . |
  2. | 2   1990   42      .      .      1 |
  3. | 3   2000   42      .      .      2 |
  4. | 4   2010   42      .      .      3 |
  5. | 5   2015   42      .      4      4 |
  6. | 6   2020   42      .      5      5 |
     +------------------------------------+

The no observations error message presumably comes from some other command.


text:
Q: Determine the relative complement of two IEnumerable sets in .NET Is there an easy way to get the relative complement of two sets?  Perhaps using LINQ?
I have to find the relative compliment of a set A relative to B.  Both A and B are of type HashSet<T> but I think the algorithm could be made more general (IEnumerable<T> or even ISet<T>)?
I could use a solution in either VB.NET or C#.

A: Have you tried Enumerable.Except?
setB.Except(setA)

Example:
HashSet<int> setB = new HashSet<int> { 1, 2, 3, 4, 5 };
HashSet<int> setA = new HashSet<int> { 1, 3, 5, 7 };
HashSet<int> result = new HashSet<int>(setB.Except(setA));

foreach (int x in result)
    Console.WriteLine(x);

Result:

2
4


text:
Q: Creating Retention Flags For Users Using Date_Diff in Bigquery I'm trying to create a query that creates retention flags for users in BigQuery and my results are not matching what I'm seeing in firebase. I'm want to query tables only later than 2020-12-27. Current Query is:
 SELECT
distinct user_pseudo_id,
date(timestamp_micros(user_first_touch_timestamp)) as installdate,
max(case when date_diff(date(timestamp_micros(event_timestamp)), date(timestamp_micros(user_first_touch_timestamp)), DAY) = 1 then 1 else 0 end) as d1,
max(case when date_diff(date(timestamp_micros(event_timestamp)), date(timestamp_micros(user_first_touch_timestamp)), DAY) = 3 then 1 else 0 end) as d3,
max(case when date_diff(date(timestamp_micros(event_timestamp)), date(timestamp_micros(user_first_touch_timestamp)), DAY) = 7 then 1 else 0 end) as d7,
max(case when date_diff(date(timestamp_micros(event_timestamp)), date(timestamp_micros(user_first_touch_timestamp)), DAY) = 14 then 1 else 0 end) as d14,
FROM `events_table.analytics_xxxx.events_*`
where (_table_suffix > '20201227')
group by 1,2,3,4

Standard Bigquery Table looks like:
user_pseudo_id  event_timestamp      user_first_touch_timestamp
abc123           1616240916183001       1616240916183000
abc123            1716240916183001      1616240916183000
afg543           1718240916183020     1716240916183005

Where timestamps are unix_micros.
Data Output is currently formatted correctly, but retention appears to be higher in the query than what is in firebase
user_pseudo_id   installdate     d1  d3 d7
    abc123           2020-01-20   1  0  0
    afg543           2021-02-01   0  0  0
    trw423           2021-03-14   0  1  0

Where a '1' appears if a user had an event fire 1 day, 3 day, 7 day after install.
Any help would be appreciated!


text:
Q: Prestashop v.1.4.8.2 Accessing Context Fatal Error PHP I'm trying to populate an AdWords tag from Google in the Prestashop shopping-cart. On my mirror stage server this line worked fine; on the live server it fails.
$context = new Context();
$cart = new Cart($context->cookie->id_cart);

in /var/www/override/classes/FrontController.php
fails with:

Fatal error: Class 'Context' not found in
  /var/www/override/classes/FrontController.php on line 67

I also tried $context = Context::getContext(); but also no success.
I need all the Products in the shopping cart in order to set their ids in the tag.
Could someone point me in the right direction?

A: The Context class was introduced in Prestashop 1.5 so with the 1.4 you won't be able to use it. You need to find another way!
Not tested but this should work
global $cookie;

$cart = new Cart((int)$cookie->id_cart);


text:
Q: Intelligent spell checking I'm using NHunspell to check a string for spelling errors like so:
var words = content.Split(' ');
string[] incorrect;
using (var spellChecker = new Hunspell(affixFile, dictionaryFile))
{
    incorrect = words.Where(x => !spellChecker.Spell(x))
        .ToArray();
}

This generally works, but it has some problems. For example, if I'm checking the sentence "This is a (very good) example", it will report "(very" and "good)" as being misspelled. Or if the string contains a time such as "8:30", it will report that as a misspelled word. It also has problems with commas, etc.
Microsoft Word is smart enough to recognize a time, fraction, or comma-delimited list of words. It knows when not to use an English dictionary, and it knows when to ignore symbols. How can I get a similar, more intelligent spell check in my software? Are there any libraries that provide a little more intelligence?
EDIT:
I don't want to force users to have Microsoft Word installed on their machine, so using COM interop is not an option.

A: If your spell checker is really that stupid, you should pre-tokenize its input to get the words out and feed those one at a time (or as a string joined with spaces). I'm not familiar with C#/.NET, but in Python, you'd use a simple RE like \w+ for that:
>>> s = "This is a (very good) example"
>>> re.findall(r"\w+", s)
['This', 'is', 'a', 'very', 'good', 'example']

and I bet .NET has something very similar. In fact, according to the .NET docs, \w is supported, so you just have to find out how re.findall is called there.

A: using System.Text.RegularExpressions;
...
// any occurence of ( and ) (maybe needs escaping)
string pattern = "( (\\.? | )\\.? )";
foreach(string i in incorrect){
  Regex.Replace(i, pattern, String.Empty) // replace with String.Empty
}

More information about regex here.
After I have been reading this I think Hunspell is one of the best choices :)

A: in C#, you could do something like this.
public static class ExtensionHelper
{
    public static string[] GetWords(this string input)
    {
        MatchCollection matches = Regex.Matches(input, @"\b[\w']*\b");

        var words = from m in matches.Cast<Match>()
                    where !string.IsNullOrEmpty(m.Value)
                    select TrimSuffix(m.Value);

        return words.ToArray();
    }

    public static string TrimSuffix(this string word)
    {
        int apostropheLocation = word.IndexOf('\'');
        if (apostropheLocation != -1)
        {
            word = word.Substring(0, apostropheLocation);
        }

        return word;
    }
}

var NumberOfMistakes = content.GetWords().Where(x => !hunspell.Spell(x)).Count();


text:
Q: How to calculate the area of a generalized ellipse in form $\frac{|x|^c}{a^c} + \frac{|y|^c}{b^c} = 1$? I have a generalized ellipse (ref. Eq(1) in Athanassoula, et al. "The shape of bars in early-type barred galaxies." (via harvard.edu) (1990) )
$$
\frac{|x|^c}{a^c} + \frac{|y|^c}{b^c} = 1
$$
where $a$, $b$ are semi-axis, and $c$ a free parameter in a range $(0,4)$, which is enough for me in my problem; when $c=2$, it returns to normal ellipse.
How to calculate its area?
Thanks!

A: The cartesian version of the equation of your function is
$$y=\pm b\left(1-\dfrac{|x|^c}{a^c}\right)^{1/c}$$
which represents in fact two functions (resp. the upper and lower parts of the curve according to the choice between signs $+$ or $-$).
But, due to the symmetry of the curve with respect to $x$ and $y$ axes (see figure below), it is sufficient to consider the $+$ case on its $[0,a]$ part, and compute the quarter of this area (situated in the first quadrant) by the following integral :
$$b\int_{x=0}^{a}\left(1-\dfrac{x^c}{a^c}\right)^{1/c}dx=ab\int_{X=0}^{1}\left(1-X^c\right)^{1/c}dX=ab\dfrac{\Gamma(1+\tfrac1c)^2}{\Gamma(1+\tfrac2c)}\tag{1}$$
the second part resulting from the change of variable $X:=\dfrac{x}{a}$, the last part being obtained using Wolfram Alpha (in fact, @Will Jagy has given in a comment below a reference where this result is proved).
with, of course, a final multiplication by $4$.
In the particular case $c=2$ (ordinary ellipse), (1) becomes:
$$ab\dfrac{\Gamma(\tfrac32)^2}{\Gamma(2)}=ab\dfrac{(\tfrac12\Gamma(\tfrac12))^2}{1}=ab\tfrac14 (\sqrt{\pi})^2=ab\tfrac{\pi}{4}$$
as awaited for the quarter of the area of an ellipse with semiaxes $a$ and $b$.

Fig. 1: For $a=3$ and $b=2$. Cases $c=0.5$ (starlike), $c=1$ (lozenge) ... to $c=4$ (almost rectangular).


text:
Q: Row rank and column rank of a matrix It is very basic and fundamental theorem in linear algebra or matrix theory that the row rank and column rank of a matrix are same. Several people gave interesting elementary proofs of it. At the first time, it seems not so straight-forward to prove this theorem.
I initially thought in the following way: let $A$ be an $m\times n$ matrix. By elementary row operations, row rank of $A$ doesn't change, and the matrix can be reduced to a row-echelon form. However, there are some subtle points moving in this direction: it doesn't seem obvious/easy to show that
1) row operations do not change column rank of $A$
2) for a matrix in reduced row-echelon form, its row rank and column rank are same.
So, since these two statements I couldn't prove in some natural arguments, I went in the following way:
Think of $\mathbb{R}^n$ as vector space of column vectors over $\mathbb{R}$ of dimension $n$ (i.e. space of $n\times 1$ matrices). Then $A$ can be considered as a linear map from $\mathbb{R}^n$ to $\mathbb{R}^m$. In this setup, the row rank of $A$ is simply the dimension of image space of map $A$. Then the question arises is

Q. Can we show that the dimension of $\mathbb{R}^n/\ker A$ is the column rank of $A$?

My aim in the question is not to understand some well-known proof of the theorem under consideration; but I want to see the obstacles and how to remove them if we proceed in some natural arguments, as stated above.


text:
Q: yii compare date and time in model I have model with rules
public function rules() {
        return array(
            array('user_id, name, start_date, timezones, start_hours, return_date, return_hours, location_start, location_end, trip_activity, trip_mean, status', 'required'),
            array('user_id, return_hours, sign_off, saved, advise, time_notification, status', 'numerical', 'integerOnly'=>true),
            array('name, going_with, start_hours, location_start, location_end, location_return, trip_activity, trip_mean', 'length', 'max'=>255),
            array('created, modified, advise, notify_best_friend, notify_now, notify_returning, send_notification, sign_off', 'safe'),
            array('going_with, location_return, time_notification, created, modified', 'default', 'setOnEmpty' => true, 'value' => null),
            array('id, user_id, name, going_with, start_date, start_hours, return_date, return_hours, location_start, location_end, location_return, trip_activity, trip_mean, saved, advise, time_notification, status, created, modified', 'safe', 'on'=>'search'),
            array(
                  'return_date',
                  'compare',
                  'compareAttribute'=>'start_date',
                  'operator'=>'>=',
                  'allowEmpty'=>false ,
                  'message'=>'{attribute} must be greater than "{compareValue}".'
                ),

            array(
                  'return_hours',
                  'compare',
                  'compareAttribute'=>'start_hours',
                  'operator'=>'>',
                  'allowEmpty'=>false ,
                  'message'=>'{attribute} must be greater than "{compareValue}".'
                ),
            );
    }

I want to compare date and time...
In case: 'return_date' >= 'start_date'... it's ok.
In case 'return_date' == 'start_date', so 'return_hours > 'start_hours' but with rules above I can't compare them.
What's solution? thanks!

A: You can achieve this using a custom validator.
public function comparedates($attribute,$params)
        {
            $message=Yii::t('yii','{attribute} must be greater than "{compareValue}".');
            if(CDateTimeParser::parse($this->return_date, "yyyy-MM-dd") < CDateTimeParser::parse($this->start_date, "yyyy-MM-dd"))
            {
                $params=array('{attribute}'=>$this->getAttributeLabel('return_date'),'{compareValue}'=>$this->getAttributeLabel('start_date'));
                $this->addError($attribute,strtr($message,$params));
            }
            else if(CDateTimeParser::parse($this->return_date, "yyyy-MM-dd") === CDateTimeParser::parse($this->start_date, "yyyy-MM-dd"))
            {
                if(CDateTimeParser::parse($this->return_hours, "hh") < CDateTimeParser::parse($this->start_hours, "hh")//change hh according to the format of return_hours and start_hours
                {
                    $params=array('{attribute}'=>$this->getAttributeLabel('return_hours'),'{compareValue}'=>$this->getAttributeLabel('start_hours'));
                    $this->addError('return_hours',strtr($message,$params));
                }
            }
        }

And in your rules
public function rules() {
return array(
 //your previous rules
     array('return_date','comparedates'),
    );

}
Remember change the the patternparameter of CDateTimeParser::parse() from hh according to the format of your return_hours and start_hours


text:
Q: Comparing list elements to a predicate I need to construct a a predicate compare_to_predicate/3. It takes in a given predicate and list of numbers and proceeds to compare every element in the list using that predicate.
The given predicates are
- is_odd
- is_even
- greater_than(X)
For example:
?- compare_to_predicate([8,13,1,500], [is_odd], X).
X = [13, 1].
?- compare_to_predicate([8,13,1,500], [greater_than, 10], X).
X = [13, 500].

What I have come up with thus far is:
is_odd(X):- 1 is mod(X,2).
is_even(X):- 0 is mod(X,2).
greater_than(X,Y):- X<Y.
compare_to_predicate([],_,[]).
compare_to_predicate([H|Tail],Functor,[H|X]):- Term =.. [Functor,H], Term, compare_to_predicate(Tail,Functor,X).

I have a number of issues:
1)
?- compare_to_predicate([2,10,8,300],is_even,X).

will produce
X = [2, 10, 8, 300].

but
compare_to_predicate([2,10,8,301],is_even,X).

will produce
false.

I assume it has to do with the predicate encountering a number that will not return true on is_even and then terminating the whole compare_to_predicate with a false. In that case is the solution to somehow make it ignore odd numbers instead of evaluating them? If so, how would I do that?
2)
It seems that the given predicate I pass into compare_to_predicate has to have the type List as seen in
?- compare_to_predicate([8,13,1,500], [is_odd], X).

and
?- compare_to_predicate([8,13,1,500], [greater_than, 10], X).

I am currently simply passing a normal predicate into the Term. I'm not quite sure on how I'm supposed to do that.
It seems that compare_to_predicate([H|Tail],[Functor],[H|X]):- Term =.. [Functor,H], Term, compare_to_predicate(Tail,[Functor],X)
did the trick here. Finally:
3)
?- compare_to_predicate([8,13,1,500], [greater_than, 10], X).

It seems I need to make compare_to_predicate able to take in predicates with different arity as shown here. Is the solution supposed to be something like this?
(Term =.. [Functor,A]; Term=.. [Functor,A,B]).

Any help will be appreciated.

A: You kind of need to decide what compare_to_predicate/3 is supposed to do with values that fail the goal. I see basically three ways this can go:

*

*It can behave as a filter, and the third argument is unified with the values in the first argument that pass.

*It can behave as a for-all, and the third argument is unified with the whole list if they all pass and fails otherwise (your current behavior)

*It can behave like an for-each that just applies the predicate to each item in the list and discards the result. There is no meaningful value for the third parameter in this case.

By the way, the term surgery you're doing with =../2 is not necessary; call/N will do the right thing if you do something like call(greater(10), 20), so you can just allow the user to call your predicate like this: compare_to_predicate([1,2,3,4], greater(2), X) and use call to build the goal.
Doing the first one is pretty straightforward:
filter([], _, []).
filter([X|Xs], P, Result) :-
    filter(Xs, P, Xs1),
    (call(P, X) -> Result = [X|Xs1] ; Result = Xs1).

Doing the second one is also pretty straightforward:
forall([], _, []).
forall([X|Xs], P, [X|Xs]) :- call(P, X), forall(Xs, P, Xs).

Doing the third one is not terribly hard:
foreach([], _).
foreach([X|Xs], G) :- once(call(G, X) ; true), foreach(Xs, G).


text:
Q: Map ctrl to super in GNOME i'm running Ubuntu Precise, and I want to perform the following remapping, preferably through Gnome's "System Settings > Keyboard > Layout > Options" menu (though if that's not possible I could fall back to xmodmap):

*

*Remap Caps Lock to CTRL (done)

*Remap Left Ctrl to Super (doesn't seem to be an option for it in the menu, though there is a "remap left ctrl to meta")

Ideally, I'm trying not to bypass Gnome's configurations, so if there is some way to accomplish step 2 above using gconfeditor rather than disabling gnome's keyboard remapping and just doing the whole thing through xmodmap, I'd like to know it.

A: Are you using Gnome on Ubuntu Precise, or are you perhaps using Unity (the default) on Ubuntu Precise, and mistakenly calling it Gnome?
Either way (I think), I believe Xmodmap will be your best bet. See  my answer on AskUbuntu.


text:
Q: Is network access logged any where on windows by default I accidentally shared my C drive – what should I be worried about?
and would like to know who may have accessed my files. Is this information stored any where?

A: By default on Windows 7 there is no logging of network activity.  It may be enabled, you can check.  If it isn't enabled, then can enable it.
To enable auditing do the following:

*

*Open Control panel

*Administrative Tools

*Local Security Policy

*Open Local Policies

*Audit Policy

From there you can enable auditing events.
If auditing is enabled then you can view the events in the Security Event log.
To view events:

*

*Open Control panel

*Administrative Tools

*Event Viewer

*Security

A: You have little to nothing to worry about.  Even if you gave people read/write permission thought the share, the file systems security takes a higher precedence and no one without appropriate permissions would be able to do anything.
In other words, they could not do anything they could not have already done before the share.


text:
Q: Checkbox checked property got ruined by the conditionals? a beginner coder here (and also my first post).
I was trying to make function that will change the value of a previously defined variable when the checkbox is checked or unchecked. I tried to write this code to see if the checked property of my checkbox is working.
function calc5() {
  var check5Object = document.getElementById("check5");
  stat5 = check5Object.checked;
  console.log(stat5);
}

When i checked the console, it works out like expected. When the checkbox is checked it logs true and when the checkbox is unchecked it logs false on the console like this.
I thought it was working smoothly... until i added the conditionals. The code looks like this:
function calc5() {
  var check5Object = document.getElementById("check5");
  stat5 = check5Object.checked;
  if ((stat5 = true)) {
    bobux5 = 10000;
  } else {
    bobux5 = 0;
  }
  console.log(stat5);
}

And the result on the console looks like
this
Everytime I click the checkbox, it just logs as "true" all the time. Can someone help me figure it out what went wrong in my code? It will be very helpful!
(btw im making a robux "scam" website that will rickroll you at the end, its harmless)

A: You need to use == and rather use =
From:
if (stat5 = true) {
    bobux5 = 10000;
}

to:
if (stat5 == true) {
    bobux5 = 10000;
}

A: Use this code:
function calc5() {
  var check5Object = document.getElementById("check5");
  var bobux5 = 0;
  stat5 = check5Object.checked;
  if (stat5 == true) {
    bobux5 = 10000;
  }
  console.log(stat5);
}

in fact you should use == in conditions. => (if == X TURE) and (if = X FALSE)