Q:

Migrate gitlab to gogs

Recently, i found a Gitlab alternative called Gogs.
Any suggestion for migrating repo in Gitlab to Gogs? I m not expecting all of it of course, just as much as possible.

A:

The correct steps for mirroring a repo is:

$ git clone --mirror git@example.com/upstream-repository.git
  $ cd upstream-repository.git
  $ git push --mirror git@example.com/new-location.git

Note: Do not use git push --mirror if you did not clone the repo with git clone --mirror. Also, git clone --mirror is preferred over git clone --bare as it will clone all git notes and attributes as well.
Reference: http://blog.plataformatec.com.br/2013/05/how-to-properly-mirror-a-git-repository/

A:

Clone localy the bare git repo (=server side repo)  and push it as a mirror to new repo:
git clone --bare http://my.gitlab.project.git
cd project.git
git push --mirror http://my.gogs.project.git

This will push all your commits, branches, tags etc. This will work for any git repo, whatever it's hosted on gitlab, gog, github, etc.


Q:

NHL Trades: Can one find the exact language of every trade?

The question says it all, but to be more specific, I've scoured the internet for the specifics of the conditional pick traded from the Wild to the Coyotes in the Hanzal-White trade. Neither team's news or transaction logs describe the conditions of this pick, and the many NHL trade trackers I've found simply call it a "4th-round conditional pick in 2019". What levels must the Wild reach this season to advance the pick to earlier rounds?
But more generally, are the specifics of all NHL trades made public?

A:

What levels must the Wild reach this season to advance the pick to earlier rounds?

From ProSportsTransactions.com, the Minnesota Wild relinquished, among other things, a 2019 conditional pick (second round if Wild advance to third round of 2017 playoffs and Hanzal plays in at least 50% of games, third round if Wild advance to second round of 2017 playoffs and Hanzal plays in at least 50% of games, else fourth round).

But more generally, are the specifics of all NHL trades made public?

I emailed Frank Marousek, the webmaster for ProSportsTransactions.com, asking where and how the NHL releases official trade information. The short answer to this question is No, the specifics of each official trade are not released to the general public.
From our correspondence: There is a thing called the "central registry" where all the specifics are supposed to be kept. I don't have access to that. But it's usually out there if you dig deep enough. If it's not specified in the official release, a lot of time a local beat reporter will dig for it and report it. For example, the Hanzel trade conditions were eventually reported here. Still, you'll see quite a few trades that have conditions where I have no better alternative than to say "conditions are unconfirmed."
The NHL does not require that the details of any trade be released publicly, but some reporters may be granted access to the central registry (the official NHL database) or obtain details in interviews with team employees. The details spread by word-of-mouth from then on.


Q:

Implementing a KVO/Bindings-Compliant Bridge-Pattern in Cocoa

I'm trying to implement a simple object bridge in cocoa where the bridge object acts as a kvo/bindings-compliant drop in for some arbitrary other NSObject instance.
Here is my problem (more details in the code below):
A bridge object acts as a drop in for a Person-Object, with an NSString* property called name and an Address* property address. Binding to the keyPath "name" or "address" of the Bridge works nicely. Trouble starts when  binding some object to the keyPath "address.street" of the bridge and a new Address-Object is set for Person's address property. That results in KVO-related exceptions that look like this:

Cannot remove an observer <NSKeyValueObservance 0x126b00> for the key path "street" from <Address 0x12f1d0> because it is not registered as an observer

This happens even though the bridge notices the change in the "address"-Property and emits a willChangeValueForKeyPath/didChangeValueForKeyPath tuple.
The code below produces the the problem. It's self-contained objective-c code that can be saved in a file "BridgeDemo.m" and compiled run with
gcc -o test BridgeDemo.m -framework AppKit -framework Foundation; ./test

If you know a solution to this problem or can offer me a better approach solving the same problem you make me a very happy programmer!
BridgeDemo.m:
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>

/* --- Address ----------------------------------------- */

@interface Address : NSObject {
    NSString* street;
    NSNumber* zipCode;
    NSString* city;
}

@property(retain) NSString* street;
@property(retain) NSNumber* zipCode;
@property(retain) NSString* city;

@end

@implementation Address

@synthesize street, zipCode, city;

-(id)init {
    if( !( self = [super init] ) ) { return nil; }

    self.street  = @"Elm Street";
    self.zipCode = @"12345";
    self.city    = @"Crashington";

    return self;
}

-(void) modifyStreet {
    self.street = @"Main Street";
}

-(void)dealloc {
    [street release]; [zipCode release]; [city release];
    [super dealloc];
}
@end

/* --- Person ----------------------------------------- */

@interface Person : NSObject {
    NSString* name;
    Address* address;
}
@property(retain) NSString* name;
@property(retain) Address* address;
@end

@implementation Person

@synthesize address, name;

-(id)init {
    if( !( self = [super init] ) ) { return nil; }

    self.name = @"Tom";
    self.address = [[Address new] autorelease];

    return self;
}

- (void)modifyAddress {
    Address* a = [[Address new] autorelease];
    a.street  = @"Jump Street";
    a.zipCode = @"54321";
    a.city    = @"Memleakville";
    self.address = a;
}

- (void)dealloc { [address release]; [name release]; [super dealloc]; }

@end

/* --- Bridge ----------------------------------------- */

@interface Bridge : NSObject {
    NSMutableDictionary* observedKeys;
    NSObject* obj;
}

@property(retain) NSObject* obj;

@end

@implementation Bridge

@synthesize obj;

- (id)init {
    if( !( self = [super init] ) ) { return nil; }
    observedKeys = [NSMutableDictionary new];
    return self;
}
- (void)forwardInvocation:(NSInvocation*)inv {
    [inv invokeWithTarget:obj];
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    return [obj methodSignatureForSelector:aSelector];
}

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog( @">>>> Detected Change in keyPath: %@", keyPath );
    [self willChangeValueForKey:keyPath];
    [self didChangeValueForKey:keyPath];
}

-(id)valueForUndefinedKey:(NSString*)key {
    /* Register an observer for the key, if not already done */
    if( ![observedKeys objectForKey:key] ) {
        [observedKeys setObject:[NSNumber numberWithBool:YES] forKey:key];
        [obj addObserver:self forKeyPath:key options:NSKeyValueObservingOptionNew context:nil];
    }
    return [obj valueForKey:key];
}

- (void)dealloc {
    for( NSString* key in [observedKeys allKeys] ) {
        [obj removeObserver:self forKeyPath:key];
    }
    [obj release];
    [observedKeys release];
    [super dealloc];
}

@end

/* --- MyObserver ------------------------------------ */

@interface MyObserver : NSObject {
    Address* address;
    NSString* street;
}

@property(retain) Address* address;
@property(retain) NSString* street;
@end

@implementation MyObserver

@synthesize street, address;

-(void)dealloc { [street release]; [super dealloc]; }

@end

/* This works fine */
void testBindingToAddress() {
    NSLog( @"Testing Binding to 'address' --------------" );
     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    Bridge* b = [[Bridge new] autorelease];
    b.obj = [Person new];
    MyObserver* o = [[MyObserver new] autorelease];
    [o bind:@"address" toObject:b withKeyPath:@"address"
        options:nil];
    NSLog( @"Before modifyStreet: %@", o.address.street );
    [[b valueForKey:@"address"] performSelector:@selector(modifyStreet)];
    NSLog( @"After modifyStreet: %@", o.address.street );

    [b performSelector:@selector(modifyAddress)];
    NSLog( @"After modifyAdress:  %@", o.address.street );

    [pool drain];
}

/* This produces an exception */
void testBindingToStreet() {
    NSLog( @"Testing Binding to 'address.street' --------------" );
     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    Bridge* b = [[Bridge new] autorelease];
    b.obj = [Person new];
    MyObserver* o = [[MyObserver new] autorelease];
    [o bind:@"street" toObject:b withKeyPath:@"address.street"
        options:nil];

    NSLog( @"Before modifyStreet: %@", o.street );
    [[b valueForKey:@"address"] performSelector:@selector(modifyStreet)];
    NSLog( @"After modifyStreet: %@", o.street );

    [b performSelector:@selector(modifyAddress)];
    NSLog( @"After modifyAdress:  %@", o.street );

    [pool drain];
}

/* --- main() ------------------------------------ */
int main (int argc, const char * argv[]) {
    testBindingToAddress();
    testBindingToStreet();
    return 0;
}

A:

Here is the problem:
[self willChangeValueForKey:keyPath]; <--- At this point in time the actual observer needs to unsubscribe to street
 [self didChangeValueForKey:keyPath];  <--- and add itself to the new value.
By not providing the new value you are denying the observer the opportunity to unsubscribe.
Here is a hacked version that works and demonstrates the problem.
/* --- Bridge ----------------------------------------- */
....
.....

@interface Bridge : NSObject {
    NSMutableDictionary* observedKeys;
    NSObject* obj;

    //**** Dictionary for old values just before we send the didChangeValue notification.
    NSMutableDictionary * oldValues;
}

...
.....

- (id)init {
    if( !( self = [super init] ) ) { return nil; }
    observedKeys = [NSMutableDictionary new];
    //************* Initialize the new dictionary
    oldValues = [NSMutableDictionary new];
    return self;
}
....
.....

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog( @">>>> Detected Change in keyPath: %@", keyPath );
    // ****  Cache the old value before telling everyone its going to change.
    [oldValues setValue:[change valueForKey:NSKeyValueChangeOldKey] forKey:keyPath];
    [self willChangeValueForKey:keyPath];
    // **** Simulate the change by removing the old value.
    [oldValues removeObjectForKey:keyPath];
    // **** Now when we say we did change the value, we are not lying.
    [self didChangeValueForKey:keyPath];
}

-(id)valueForUndefinedKey:(NSString*)key {
    // **** Important part, return oldvalue if it exists
    id oldValue;
    if(oldValue = [oldValues valueForKey:key]){
        return oldValue;
    }
    /* Register an observer for the key, if not already done */
    if( ![observedKeys objectForKey:key] ) {
        [observedKeys setObject:[NSNumber numberWithBool:YES] forKey:key];
        NSLog(@"adding observer for:%@", key);
        [obj addObserver:self forKeyPath:key options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    }
    return [obj valueForKey:key];
}
....
......


Q:

Video.js Unable to pause video when SeekBar is clicked

Am trying to create a video where if a user clicks on the SeekBar it records the current time and also to pause the video on click event.
The issue is that when i click on the seekbar player.pause() is always undefined. How is it possible to include this in the below code?

<!DOCTYPE html>
<html>

<head>
    <title>JS Bin</title>
</head>

<body>
    <video id="player" class="video-js" controls preload="auto" width="640" height="264" poster="https://vjs.zencdn.net/v/oceans.png" data-setup="{}">
        <source src="https://vjs.zencdn.net/v/oceans.mp4" type='video/mp4'>
    </video>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.1.0/video-js.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.1.0/video.js"></script>

    <script>
        videojs('player').ready(function() {
            var player = this;
            player.controlBar.progressControl.seekBar.on('mouseup', function(event) {
                var seekBarEl = this.el();
                var seekBarRect = videojs.dom.getBoundingClientRect(seekBarEl);
                var seekBarPoint = videojs.dom.getPointerPosition(seekBarEl, event).x;
                var duration = player.duration();
                var seekBarClickedTime = videojs.formatTime(seekBarPoint * duration, duration);
                console.log('Seekbar clicked time: ', seekBarClickedTime);
               player.pause();
              console.log(player.pause());
            });
        });
    </script>

</body>

</html>

JSBIN Link

A:

There's nothing wrong about undefined when logging player.pause(). It simply means that pause method does not return anything. To make .pause() work you could invoke it from inside of the setTimeout function. Doing this will add your function to event queue and it will be invoked after players original mouseup handler:

<!DOCTYPE html>
<html>

<head>
    <title>JS Bin</title>
</head>

<body>
    <video id="player" class="video-js" controls preload="auto" width="640" height="264" poster="https://vjs.zencdn.net/v/oceans.png" data-setup="{}">
        <source src="https://vjs.zencdn.net/v/oceans.mp4" type='video/mp4'>
    </video>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.1.0/video-js.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.1.0/video.js"></script>

    <script>
        videojs('player').ready(function() {
            var player = this;
            player.controlBar.progressControl.seekBar.on('mouseup', function(event) {
                var seekBarEl = this.el();
                var seekBarRect = videojs.dom.getBoundingClientRect(seekBarEl);
                var seekBarPoint = videojs.dom.getPointerPosition(seekBarEl, event).x;
                var duration = player.duration();
                var seekBarClickedTime = videojs.formatTime(seekBarPoint * duration, duration);
                console.log('Seekbar clicked time: ', seekBarClickedTime);

                setTimeout(() => player.pause(), 0);

                console.log(player.pause());
            });
        });
    </script>

</body>

</html>

And here's some simple example to get more understanding of what's going on:

const elem1 = document.querySelector('.test1');
const elem2 = document.querySelector('.test2');

elem1.addEventListener('click', () => {
  elem1.classList.add('clicked')
})

elem1.addEventListener('click', () => {
  elem1.classList.remove('clicked')
})

elem2.addEventListener('click', () => {
  setTimeout(() => elem2.classList.add('clicked'), 0)
})

elem2.addEventListener('click', () => {
  elem2.classList.remove('clicked')
})
.clicked {
  background: #000;
  color: #fff;
}
<button class="test1">test1</button>
<button class="test2">test2</button>


Q:

Autorun Exterminator type alternatives for Ubuntu 14.04

Autorun Exterminator is a tool available for Windows that blocks virus-infected pen drives from automatically executing viruses through autorun.inf. Though most of the viruses encountered are .exe's and won't execute by default on a Linux machine, still is there any other software available for Ubuntu that can block viruses from automatically executing from a pen drive.

A:

Ubuntu comes with autorun blocking straight from the get-go.
Navigate to System Settings > Details (near the bottom) > Removable Media.
From there, select the dropdown next to Software. To disable autoruns, just set that value to Do Nothing:

Your system will no longer autorun anything that it sees on a USB stick. It's also worth noting, however, that even leaving this option on Run Software isn't exactly dangerous. The system will prompt you before running anything first:

Sourced partially from this answer on AskUbuntu


Q:

code for equal to '=' in oracle forms calculator?

I have multiple buttons 0 to 9 and other calculation methods like plus, minus, etc
There are two display items, Memory and Display; Memory item is hidden.
When click on 1 button then display value 1 in Display item. When click on + button then store value 1 in Memory item.  When click on = button then add Memory + Display values and show answer on Display item.
Question is how to code multiple calculation in equal to = button?

A:

You have three registers: the button clicked, the display value and the memory value. So the calculation string 2+3=5 looks something like this:
button Display Memory
     2       2
     +       2      2
     3       3      2
     =       5      5

As I understand your question, you want to handle a longer calculation, when the user types in several steps without pressing =, for instance 2+3+7/4*5=. There are several ways to do this, but the most intuitive one for the user is to treat the arithmetic operators as having an implicit = operation, calculating the running sum and displaying that value.
button Display Memory
     2       2
     +       2      2
     3       3      2
     +       5      5
     7       7      5
     /      12     12
     4       4     12
     *       3      3
     5       5      3
     =      15     15

To make this work you need another register item to track the current operator.
button Display Memory Operator
     2       2
     +       2      2        +
     3       3      2        +
     +       5      5        +
     7       7      5        +
     /      12     12        /
     4       4     12        /
     *       3      3        *
     5       5      3        *
     =      15     15        =

So when the user clicks a triggering button you execute something like this:
if :operator = '+' then
    :memory := :memory + :display;
elsif :operator = '-' then
    :memory := :memory - :display;
elsif :operator = '/' then
    :memory := :memory / :display;
elsif :operator = '*' then
    :memory := :memory * :display;
end if;
:display := :memory;
:operator := :button_value;

You will need to decide how to handle the situation when the user types two operations in a row e.g. +/. But probably you need to track previous button press too.
So what is the purpose of =? Well, it depends on what the user types next. If they follow = with another operator then it's just a subtotal and the sum continues....
button Display Memory
     2       2
     +       2      2
     3       3      2
     =       5      5
     +       2      5  <-- continue with existing sum
     =       7      7

... but if they follow it with a number then we're starting a new sum and we reset the memory:
button Display Memory
     2       2
     +       2      2
     3       3      2
     =       5      5
     2       2         <-- start a new sum
     +       2      2
     2       2      2
     =       4      4


Q:

Java 8 - Trying to convert String to LocalDateTime

I am trying to convert the below String to LocalDateTime, but somehow its not working.
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss.SSS");
val dateTime = LocalDateTime.parse("2016-09-21 13:43:27.000", formatter);

It seems there is a problem in Pattern.

A:

You have a problem with your pattern. You should use 'H' for hours (0-23). The type for formatter and dateTime is wrong.
This would work correctly:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime dateTime = LocalDateTime.parse("2016-09-21 13:43:27.000", formatter);


Q:

Finding a range of values for each feature that contribute to positive classification

Consider a classification problem(lets say 2 classes, 'good' and 'bad), where all features are continuous.
what I need is a range of values for each feature that contributes to 'good' classification.
What I thought was simply partitioning the feature values based on good or bad label, problem is all values don't equally contribute for good/bad classification.
So what methods can be applied to find such range for each feature ?

A:

It's impossible in general, simply because a particular value or range for feature A might correspond to class 'good' if feature B has a certain value/range but correspond to class 'bad' otherwise. In other words, the features are inter-dependent so there's no way to be sure that a certain range for a particular feature is always associated with a particular class.
That being said, it's possible to simplify the problem and assume that the features are independent: that's exactly what Naive Bayes classification does. So if you train a NB classifier and look at the estimated probabilities for every feature, you should obtain more or less the information you're looking for.
Another option which takes into account the dependency between variables is to train a simple decision tree model: by looking at the conditions in the tree you should see which combinations of features/ranges lead to which class.


Q:

Facebook orkut style date in android application

In my application I am showing a list of posts with its creator name, text of post and post date.
I want to show date in the format which is used in facebook or orkut like if a post is added before 3 sec then I want to show date as "added 3 sec ago"
Can any one please guide me how to achieve this in android.

A:

Take a look at the PrettyTime library.


Q:

How to change textbox background color whenever error occurs?

I get an email id in a text box.So whenever i enter the wrong formatted email then the text box's background color should change.
This is my code for jquery:
$(function() {
    $(':text').hover(function () {
        this.style.backgroundColor="black"},
        function() {
            this.style.backgroundColor = "transparent"});
});

This is my html code :

    <input type="text" placeholder="enter email" ng-blur="visitedEmail = true" name="email" />

Invalid email!

In the above code i have used ng-blur so when i lost focus the action has to be done.
Now i need to change the text box's background color when i lost focus(case of wrong email format).
Whats wrong with my code and give some tips to solve this..

A:

Try

        <input id="EmailTextBox" type="text" placeholder="enter email" name="email" onblur="ValidateEmail();" />


Q:

ID this 90's animated children's film about alien invasion to forest

Probably an animated children film from the 90's.
Small aliens invade earth and land in the forest and evntually defeated by the animals I think or maybe some small other creatures. (the humans never knew they were invaded lol)
I remember the first secne with the aliens, they were flying above a soccer staduim or watch the game on the screen in the space ship and they were wondering why all these people are chasing this ball.... they thought it was very valuable.
(maybe they kidnaped and impersonated one of the animals)
TNX

A:

It's Katy and the Katerpillar Kids!!! I'd also been looking for this for years, and I found the answer buried deep in another forum.
The scene opens with the aliens watching a screen where several scenes flash by and are discussed. One of which is a soccer game. They speculate as to why they are fighting over the ball, and decide the ball must be valuable. I've been searching for this same film, based on different criteria, as I didn't have a memory of the soccer scene at the beginning, but upon finding and watching the movie, I found it fits my memory, and the memory stated above.


Q:

Can stats regarding the Coronavirus outbreak tell us anything at all?

Everywhere in the news we hear about numbers of corona-virus infections, deaths and recoveries.
In lots of the publications the numbers (especially the infections) are compared with previous days. Mostly the presented numbers are 'growth' of new infections in per cent and the total number of infections so far. Then the numbers of different countries are shown.
I tried to get something out of these numbers (of infections) and realized that some important information is not told: the amount of tests done. And even further, who is tested? Which criteria? And this varies a lot between countries. Then there is the accuracy of tests.
The number and kind of tests done everyday change as well as more capacity is created or less capacity is available due to overloads or work restrictions.
I told myself the amount of deaths, as horrible as it sounds, is a good indicator of stabilization or regression. But no, people are not effected the same way regarding their previous medical condition. At some point in time, people at risk will "disappear" (again sorry for the word-choice).
I have the feeling that there so many variables and factors we are not able to gather regarding this pandemic (at least currently) that statistics are at their limit. Announced trends are most likely wrong.
How sure can we be about statistics in the current situation? Are trends viable? What can be compared what not? Is all current information foundationless?

A:

Don't let the perfect be the enemy of the good
Many of the issues you have raised are perfectly reasonable concerns.  Having said that, it is important to distinguish between cases where reported data is wrong, versus cases where reported data is correct, but is limited in its usage due to the omission of other relevant information.  The latter case is really quite ubiquitous in statistical analysis, since it is very rare that we have all the data we would ideally like to have.  In such circumstances, it is also important not to make the perfect the enemy of the good by presuming that the absence of a comprehensive dataset on every variable we would like to know about precludes any reasonable inferences being made from the data we have.
The main comprehensive public dataset we have available for the COVID-19 virus is the data held and updated by the John Hopkins Coronavirus Resource Centre at John Hopkins University.  This is the repository of data that is being used for the vast majority of media reports and data visualisations on the spread of COVID-19.  The database has data on confirmed infections, recoveries, and deaths, plus GIS data on where these occurred.  The data is sourced from the WHO and various national health departments, and it is being updated frequently.
It is certainly true that there are a lot of other things we would ideally like to have data about, to assist in understanding the path and severity of the virus.  As you have suggested, it would be wonderful if we could also obtaina comprehensive dataset on all the tests that have actually been conducted (including the negative results), and the characteristics of all the affected patients, including their age, sex, and health factors.   At this early stage it is probably overly ambitious to expect all of this data to have been collected and collated, but hopefully the various health departments of the world will eventually be able to bring some of this data together.  Health departments cannot legally disclose health information on particular patients in a way that would make them identifiable, so it is an extremely complex task to collate this type of data if the goal is to make it available for public analysis.  No doubt there will be some efforts to obtain and collate more detailed data, but it will be a difficult task.
When interpreting limited data, it is desirable to describe that data in a way that makes it clear how it was collected, and this collection mechanism forms a caveat on analysis.  Thus, we can refer to the reported numbers of infections, recoveries, deaths, etc., from each of the reporting countries, while noting that there may be disparities from these figures to the actual true numbers.  Most health departments around the world are set up so that they can obtain these figures with reasonable accuracy, so that large diparities between reported figures and the true values are unlikely, except in the case of countries that make a deliberate effort to suppress this information.  Notwithstanding the lack of the ideal data you would like, from the reported data there are certainly some things that we can reasonably infer.  For most countries, the data is likely to be a reasonably representation of the number of infected, recovered, and dead patients out of those who have been properly tested.  (Of course, I take some of the data, such as the recent numbers from China, with a large degree of scepticism.)  It is also likely that there are other infected and recovered people who have not been tested, and who therefore do not form part of the reported statistics.  Even so, this data gives us a pretty good look at growth rates for the infection in various cities and countries around the world, which allows us to see where the virus has progresssed most rapidly, and where it has been relatively contained.  These numbers also allow some attempt at extrapolation, which allows health authorities to make predictions on the likely number of cases at future dates, and the health burden this will create in different places.
Your question appears to assert that most of these trends are likely to be "wrong" due to the absence of data on other factors such as total testing and patient health.  In my view, that is not the correct way to look at it.  Rather, the reported trends may be correct, in the limited descriptive sense, but there may still be underlying non-reported factors that would give reason to anticipate future changes in those trends.  Personally, I am extremely impressed at how rapidly these various organisations have coordinated a large data collation and made public online platforms reporting on the infection and updating it frequently.  I can log on every day and see updated graphical information showing the progression of the infection in virtually any city or country in the world!  The data may not be perfect, but I would think it would bear enough of a resemblance to reality to be valuable information.  I think the effort is quite amazing, and it far past what we could do even ten years ago.


Q:

Incoming and outgoing traffic when NOTHING is running

In a system with nothing running (at least nothing I know of). Listening of incoming and outgoing traffic prints this output:
192.168.1.1              => all-systems.mcast.net             0b     26b     19b
                         <=                                   0b      0b      0b
192.168.1.2              => 224.0.0.251                     128b     26b     19b
                         <=                                   0b      0b      0b

(sometimes it doesn't show just 26b or 128b, but instead jumps to big numbers like there's actual information being sent)
What is the meaning of this?
192.168.1.1 is the gateway, my router
192.168.1.2 is me, my machine
But who is all-systems.mcast.net?? Also who is 224.0.0.251?? And more importantly, why there are packets being sent?
Found this:
https://davidsimpson.me/2015/11/16/why-is-my-machine-contacting-all-systems-mcast-net/
But I'm running no DLNA server. So who am I broadcasting to?
One last (and also important question) is: I can understand 192.168.1.2 contacting with something, and I can understand 192.168.1.1 contacting with me, but I can't understand why I am seeing 192.168.1.1 in contact with all-systems.mcast.net, so how is it possible that monitoring my machine shows traffic from my router that is not being sent to me? I shouldn't be able to see that, right?
The utility I am using is:
   iftop - display bandwidth usage on an interface by host

Utilities tcptrack and netstat show nothing at all. Therefore the only plausible explanation is that this utility is the one responsible of that traffic??

Question UPDATE
So there's this multicast stuff apparently integrated in the kernel of my system and also in my router with a very rudimentary system of question&answer, a timer, once every 60 seconds. I don't quite understand why, and after some good people has tried to explain it to me, I don't think I ever will. So I would like to turn it off. Is it possible?

A:

Those packets you are seeing are regular multicast services (and while the process is similar to broadcast packets, they are not broadcasts per se); their output traffic in the network is also (usually) negligible.
Actually not only you see traffic generated by yourself, you also see traffic for those addresses generated by other machines on your network.

224.0.0.1   is all-systems.mcast.net

By default, all (Linux) servers announce themselves in the network multicasting to 224.0.0.1 regularly, for reporting to nearby routers they are able to talk multicast. These packets should be the Linux kernel sending them.

224.0.0.251 is mDNS

As for 224.0.0.251, it is used by Avahi/zeroconf for service announcement and discovery.

Avahi is a free zero-configuration networking (zeroconf)
  implementation, including a system for multicast DNS/DNS-SD service
  discovery.

see Cisco - Introduction to multicast
see also TLDP - Multicast over TCP/IP HOWTO

Class D Address - Multicast address / 224.0.0.0 - 239.255.255.255
o  224.0.0.1 is the all-hosts group. If you ping that group, all
       multicast capable hosts on the network should answer, as every
       multicast capable host must join that group at start-up on all it's
       multicast capable interfaces.

As for seeing packets that are not for you, you are supposed to listen to broadcasts and multicast packets/announcements as they are (normally) sent to all stations. There are nuances, which I will not delve here. See the introductions I am linking.
Lastly, while iftop sees the traffic, it is not the responsible for generating it.
You can also see the multicast groups the server belongs to with:
netstat -g

Lastly, not having regular users/your user running programs does not mean the system is doing nothing. Linux is a multi-user/multi-tasking system, and there is a lot of housekeeping functions happening on the background.


Q:

Does Array.sort changes references in C#?

In my C# code, I have a array of objects. And many of these objects are referenced in another class. If Array.sort method is used to somehow sort this array of objects, then will it affect those references? Is it same for the arrays and lists?

A:

No it won't affect anything. The important thing to realise is that you don't actually have an array of objects. You have an array of references. So if you have objects A and B, then the array may contain references to A and B. When you sort the array, those references may change order - but the objects themselves don't get changed. Anything else which had a reference to the objects won't see any change just because you're shuffling the references.
To put it another way: suppose you have a shopping list of items you want to get. You can sort the shopping list to put it in some efficient order for shopping. That doesn't change where the items are, and it doesn't change anyone else's shopping list.

A:

No, it will not affect references in other classes.  Same for lists.


Q:

⊢ in contrast to implication

so I have read some topics on this but I am still in doubt. I am trying to solve some natural deduction exercices and I am not quite sure what is the difference in how I approach them and the difference in notation, in pratical terms is having ⊢ the same as implication?
For example I have this exercise ⊢ (p => q) => (r + p => r + q) which I resolved like this:
p => q

--assume r + p

------assume r

------r + q

------therefore r => r + q

------assume p

------q

------r + q

------therefore p=> r + q

--r + q

--r + p => r + q

(p => q) => r + p => r + q
Hopefully thats not too hard to understand since I dont know how to properly format here, anyways so I did that one like that and then I have these kinds of exercises :  p => q ⊢ ((p => (p & q)) & ((p & q) => q) and that one but from the second expression to the first so  ((p => (p & q)) & ((p & q) => q) ⊢ p => q, my question is can I work with these as if the  ⊢ is an implication, are they different? what's the approach here.

A:

Unfortunately, implication is an ambiguous word...
The connective $\to$ into $p \to q$ is read : " if $p$, then $q$ ".
The symbol $⊢ \varphi$ means that we have proved (in the calculus) the formula $\varphi$.
In your proof, up to the last but one line, you have produced the derivation :

$p \to q \vdash r \lor p$

because the derivation has the open assumption $p \to q$.
In the last step you have used the rule $\to$-intro to perform the last step :

$\vdash (p \to q) \to (r \lor p)$.

Thus, we have a "strong link" between the two, but they are different : $\to$ is a connective used in the calculus with sentences (i.e. with sentence letters standing for sentences) to generate "more complex" sentences, while $\vdash$ is a symbol (followed by the name of a formula) used in the theory to describe the basic property of the calculus : the existence of a derivation ending with the said formula.


Q:

exit terminal after execution

I have a shell script that runs an applescript. The applescript is executed from a terminal and I want that terminal to close after its done.
In my shell script I execute my applescript with this line. It opens a terminal, runs and then the terminal just sits there even though the applescript is done. I have other terminals open that I use all the time so I don't want to close all of them, just that one.
 osascript -e 'Tell application "Terminal" to do script "osascript ~/Scripts/reset_simulator.applescript"'

Thanks

A:

In your shell script, you executing the
osascript -e 'Tell application "Terminal" to do script "osascript ~/Scripts/reset_simulator.applescript"'

what really opens an new Terminal.app window.
Have you some special reason to open an new terminal window? Why just not running the
osascript ~/Scripts/reset_simulator.applescript

from your shell script and in the current window.
But if you want such thing (sounds to me strange) always can use the next:
osascript -e 'Tell application "Terminal" to do script "osascript ~/Scripts/reset_simulator.applescript;exit"'
#note the "exit" here ---------------------------------------------------------------------------------^^^^^

and change the Preferences to "close window" when the shell exits.
Reading your comments above, sounds me than you want run some applescript in the "background".
So you can do the next:
a.) from your shell script
osascript ~/Scripts/reset_simulator.applescript &

2.) if you want still open the another terminal window
osascript -e 'Tell application "Terminal" to do script "osascript ~/Scripts/reset_simulator.applescript&exit"'
#note the & here --------------------------------------------------------------------------------------^


Q:

How to look if a char is equal to a new line

I have a string, the string contains for example "Hello\nThis is a test.\n".
I want to split the whole string on every \n in the string. I made this code already:
vector<string> inData = "Hello\nThis is a test.\n";

for ( int i = 0; i < (int)inData.length(); i++ )
{
    if(inData.at(i) == "\n")
    {
    }
}

But when I complite this, then I get an error:
(\n as a string)
binary '==' : no operator found which takes a left-hand operand of type 'char' (or there is no acceptable conversion)

(above code)
'==' : no conversion from 'const char *' to 'int'

'==' : 'int' differs in levels of indirection from 'const char [2]'

The problem is that I can't look if a char is equal to "new line". How can I do this?

A:

"\n" is a const char[2]. Use '\n' instead.
And actually, your code won't even compile anyway.
You probably meant:
string inData = "Hello\nThis is a test.\n";

for ( size_t i = 0; i < inData.length(); i++ )
{
    if(inData.at(i) == '\n')
    {
    }
}

I removed the vector from your code because you apparently don't want to use that (you were trying to initialize a vector<string> from a const char[], which will not work).
Also notice the use of size_t instead of the conversion of inData.length() to int.

A:

You may want to try == '\n' instead of "\n".


Q:

Return json from web api controller

I have web api controller:
[HttpPost]
    public String UploadFile()
    {//do some logic
       String jsResult="{\"success\":\"false\", \"msg\":\"No file or user ID!\"}";
       return jsResult;
    }

Returned string to the client is like this:  "{\"success\":\"false\", \"msg\":\"No file or user ID!\"}";
I compose json string manually but client doesn't parse it(I guess because returned string is escaped with "\".
What would be the proper way to return json string to the clinet from this controller method?

A:

Try auto serialize webapi:
Create a Model:
public class UploadResult
{
    public UploadResult()
    {

    }
    public bool Success  { get; set; }
    public string Msg { get; set; }
}

And return
public UploadResult UploadFile()
{
    var r = new UploadResult(){ Success = false, Msg = "No file or user ID!" };
    return r;
}

In your example, you are explicitly serializing, and the result ends up serialized twice. Because WebApi already has the Json serializer in the pipeline.
To go async:
public async Task<IHttpActionResult> UploadFile()
{
    var r = new UploadResult(){ Success = false, Msg = "No file or user ID!" };
    // some "await" logic
    return Ok(r);
}

Adding  using System.Web.Mvc fails because
[System.Web.Http.HttpPost]  != [System.Web.Mvc.HttpPost]

And [HttpPost] is ambiguous. Anyway, the Mvc ref is not necessary . Remove it and add again [HttpPost]


Q:

Add newline to VBA or Visual Basic 6

I want to concatenate two strings with a linebreak between them.
st = "Line 1" + newline + "Line2"

How do I add a newline to VBA or Visual Basic 6?

A:

Visual Basic has built-in constants for newlines:
vbCr = Chr$(13) = CR (carriage-return character) - used by Mac OS and Apple II family
vbLf = Chr$(10) = LF (line-feed character) - used by Linux and Mac OS X
vbCrLf = Chr$(13) & Chr$(10) = CRLF (carriage-return followed by line-feed) - used by Windows
vbNewLine = the same as vbCrLf

A:

Use this code between two words:
& vbCrLf &

Using this, the next word displays on the next line.


Q:

Font used as stripe.com logo

I am trying to find out, but I am having a hard time. I would like to know what the font type used to create the logo at http://stripe.com is? Does anyone happen to know?

A:

FF Fago, they sent me an email with the font name


Q:

Add views and set layout_toRightOf programatically - first view not showing up

I am adding a few custom views in RelativeLayout in java using the code below and addRule to align it to right of previously added view but the view added at 1st iteration is now showing up (Rest of the views appear fine).
RelativeLayout.LayoutParams params;
int pegIds[] = {Peg.BLUE, Peg.GREEN, Peg.RED, Peg.WHITE, Peg.YELLOW, Peg.PURPLE};
Peg peg;

for (int i = 0; i < pegIds.length; i++) {
    peg = new Peg(context, null);
    peg.setId(i);
    peg.setTag("hotbar_" + i);
    peg.setDrawableID(pegIds[i]);
    params = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    if (i > 0)
        params.addRule(RelativeLayout.RIGHT_OF, i-1);
    hotbar.addView(peg, params);
}

RelativeLayout XML:
<RelativeLayout android:id="@+id/hotbar"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:gravity="center"
    android:paddingTop="10dp"
    android:paddingBottom="10dp" ></RelativeLayout>

A:

I dont think a view can have an Id of 0
try
for (int i = 1000; i < 1000 + pegIds.length; i++) {


Q:

what is syntax for mongodb query for boolean values?

the values for the key is_agent is TRUE or blank.  I have the following query:
db.users.find( { $not: {is_agent:TRUE} }, {email:1} )

I get the following error:
ReferenceError: TRUE is not defined

when I used "TRUE" I got the following error:
"$err" : "Can't canonicalize query: BadValue unknown top level operator: $not",
"code" : 17287

What is the correct syntax?

A:

$eq Matches values that are equal to a specified value.
$ne Matches all values that are not equal to a specified value.

Documentation on mongodb operators
Example:
db.users.find({is_agent: {$ne: true}})

or
db.users.find({is_agent: {$eq: true}})


Q:

SAP Smartforms layout trouble with packed numbers

I'm currently trying to fill a smartform with some information. I have a simple text element and read the data fields via &name&. The data itself gets read perfectly fine, however the layout is incorrect. Some fields are just plain text, and others are defined as packed numbers with 2 decimals. These packed number fields for some reason are out of alignment, always showing one line below everything else that is supposed to be in this line. That looks like that:

How can I get the 121,08 in this example on the same height as the rest? The text element looks like the following:
test               &field1&     &field2& &field3&

Only field 2 is a packed number, therefore I think it might have something to do with that.

A:

Use as below. C will remove extra space.
&field2(C)& &field2(C)& &field3(C)&


Q:

how to stop javascript function after running once?

can someone please show me how i can stop this javascript function after it has ran once?
At the moment it just repeats again and again and i only want it to run the once.
I'm still learning javascript, so sorry if its not great.
thanks
<script>
$(function() {
    $(".search_prompt").hide();

    $("#text").focusin(function() {
        $(".search_prompt").show();
    }).focusout(function () {
        $(".search_prompt").hide();
    });
});
</script>

A:

<script>
$(function() {
    $(".search_prompt").hide();

    $("#text").one('focusin', function() {
        $(".search_prompt").show();
    }).one('focusout', function () {
        $(".search_prompt").hide();
    });
});
</script>

http://api.jquery.com/one/


Q:

How to Iterate to output data to Google Sheets with App-Script

Using Google App Script, when I used Logger.log() the for loop iterates properly and I get results for each value. When I try to output this to a google sheet only the last value for each variable is output over and over again for the number of goals.length.
Any help is very much appreciated!
function listGoals() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var filterList = Analytics.Management.Goals.list(accountId, webPropertyId, profileId)
      var goals = filterList.items;
        for (var i = 0, goal; goal = goals[i]; i++) {
            var accountId = goal.accountId;
            var propertyId = goal.webPropertyId;
            var goalNumber = goal.id;
            var goalName = goal.name;

            Logger.log('accountId: ' + accountId);
            Logger.log('profileId: ' + propertyId);
            Logger.log('goal number: ' + goalNumber);
            Logger.log('goal name: ' + goalName);
            //Logger.log prints for each result

            sheet.getRange(1,1,goals.length).setValue(goalNumber);
            sheet.getRange(1,2,goals.length).setValue(goalName);
            //this only prints out the last value of goalNumber and goalName to the sheet

        }
    }

A:

It doesn't only print the last results, it just keeps overwriting the old result with the new one.
goals.length only helps if you then supply an array of arrays containing the values looking as such:
[[1, "Goal 1"],
 [2, "Goal 2"]]

If you want to print out a list of goalNumber and goalName you need to offset the cell to write in every time.
something like
sheet.getRange(1+i,1).setValue(goalNumber);
sheet.getRange(1+i,2).setValue(goalName);

To speed up the process a bit and not do two calls for every goal you can store the id name pairs as arrays within an array and do one final setValues call after the loop finishes executing.
function listGoals() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var filterList = Analytics.Management.Goals.list(accountId, webPropertyId, profileId)
  var goals = filterList.items;
  var goalsToWrite = [];

  for (var i = 0, goal; goal = goals[i]; i++) {
    goalsToWrite.push([goal.id, goal.name]);
  }

  sheet.getRange(1, 1, goals.length, 2).setValues(goalsToWrite);
}


Q:

flutter make raised button change after future return value

I have a raised button that kicks off my fingerprint authentication, when the Future returns I want to be able to change the Raised Button to new text and new onPressed method to complete the required authentication. I have given the Raised Button a key but can not find how to act upon that button to change it.  Is it possible?  Anyone have examples of it?
I tried to create new Raised Button with same key based on if the user is authenticated, but it did not change anything.
Any help would be great.

A:

I would recommend reviewing the Flutter Interactivity Tutorial.
Once the Future completes you can call setState to tell Flutter to rebuild your StatefulWidget. And in your build() method, you can use the authenticated status of the user to construct a different RaisedButton.
Here's some example code that does this:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Local Auth Demo',
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _authenticated = false;

  Future<Null> _authenticate() async {
    final LocalAuthentication auth = new LocalAuthentication();
    bool authenticated = false;
    try {
      authenticated = await auth.authenticateWithBiometrics(
        localizedReason: 'Scan your fingerprint to authenticate',
        useErrorDialogs: true);
    } on PlatformException catch (e) {
      print(e);
    }
    if (!mounted) return;
    setState(() {
      _authenticated = authenticated;
    });
  }

  Widget _buildAuthButton() {
    assert(!_authenticated);
    return new RaisedButton(
      child: new Text('Authenticate'),
      onPressed: _authenticate,
    );
  }

  Widget _buildContinueButton() {
    assert(_authenticated);
    return new RaisedButton(
      child: new Text('Continue'),
      onPressed: () {
        // Do something now that the user is authenticated
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Interactivity Tutoral'),
      ),
      body: new Center(
        child: _authenticated ? _buildContinueButton() : _buildAuthButton(),
      ),
    );
  }
}


Q:

Olympic medalist in both the Summer and Winter Olympics

Has anyone ever won Olympic medals in both the Summer and Winter Olympics?

A:

There are six people that have won medals in both the Summer and Winter Olympic Games.

Gillis Grafström of Sweden is the most successful figure skater in Olympic history, having won 3 gold medals and 1 silver medal in 1920-1932.  However, he is only on this list because in 1920, there was no Winter Olympics, and figure skating was an event in the Summer Games.  The first Winter Games was in 1924, where he got his second gold.
Eddie Eagan was an American gold medalist in boxing in 1920.  He failed to medal in 1924, but in 1932 he was a member of the bobsleigh team which took gold, making him the first person to win a medal in Summer and Winter for different events.
Jacob Tullin Thams of Norway won the first Olympic gold medal for ski jumping in 1924.  In 1936, he was on the sailing team that won silver in the 8-metre class.
Christa Luding of Germany is a speed skater and cyclist.  She won medals in skating from 1984-1992, and in 1988 with her silver medal in track cycling became the only person to win a medal in the Winter and Summer Games in the same year.
Clara Hughes of Canada is also a cyclist and speed skater.  She won two bronze medals for cycling in 1996, and won four medals for skating between 2002-2010.  She has the distinction of being the only person to have won multiple medals in both the Summer and Winter Games.
Lauryn Williams of the USA won a silver medal at Athens 2004 and gold in London 2012 as a sprinter.  This year at Sochi 2014, she won silver in bobsleigh.


Q:

Нарисовать изображение на весь Canvas

Я работаю с загрузкой фотографий, пытаюсь отображать миниатюры этих фото. Для изменения размера фотографий использую canvas. Проблема в том, что canvas рисует фотографии меньшего размера, хотя для фотографии я задаю размеры такие-же как и сам canvas.
Проблема, как мне кажется, кроется в самой отрисовке ctx.drawImage(img, 0, 0, width, height);, но не знаю как это победить.

Цель данных телодвижений - облегчить работу браузеру, так как пользователи(Они же тетки) будут грузить фотки прямо с фотика, тоесть ситуация, когда отображается штук 500 фоток размером 5к пикселей - обычное дело.

//Готовим шаблон
let template = document.getElementById('file-template');
let cTemplate = Handlebars.compile(template.innerHTML);

let input = document.getElementById('file-input');

input.onchange = function() {
  let container = document.getElementById('photos');
  let files = this.files;

  //Перебираем файлы в мультиинпуте
  for(let i in files) {
    if(!files.hasOwnProperty(i))
      continue;

    let file = files[i];

    if (!file.type.match(/image.*/))
      continue;

    let reader = new FileReader();

    //Когда картинка прочиталась
    reader.onload = function(e) {
      let img = new Image();
      img.src = e.target.result;

      //Вставляем из шаблона
      container.insertAdjacentHTML( 'beforeend', cTemplate() );

      let canvas = container.querySelector('.file:last-of-type .canvas');
      let ctx = canvas.getContext('2d');

      let height = 100;   //Высота превьюх 100
      let width = img.width * height / img.height; //Посчитаем их длину

      canvas.style['width'] = width + 'px';   //Канвас хотим длиной с картинку
      ctx.drawImage(img, 0, 0, width, height);  //Тут почему-то неправильно отрабатывает
    };

    reader.readAsDataURL(file);
  }
};
#photos {
  display: flex;
  margin-top: 20px;
}
.file {
  position: relative;
  margin: 0 5px 5px 0;
}
.file-delete {
  position: absolute;
  top: 0;
  right: 0;
  background: #fff;
  width: 18px;
  color: #f00;
  text-align: center;
  text-decoration: none;
}
canvas {
  background: #ccc;
  width: 0px;
  height: 100px;
}

<input id="file-input" type="file" multiple="multiple">

A:

//Готовим шаблон
let template = document.getElementById('file-template');
let cTemplate = Handlebars.compile(template.innerHTML);

let input = document.getElementById('file-input');

input.onchange = function() {
  let container = document.getElementById('photos');
  let files = this.files;

  //Перебираем файлы в мультиинпуте
  for (let i in files) {
    if (!files.hasOwnProperty(i))
      continue;

    let file = files[i];

    if (!file.type.match(/image.*/))
      continue;

    let reader = new FileReader();

    //Когда картинка прочиталась
    reader.onload = function(e) {
      let img = new Image();
      img.src = e.target.result;

      //Вставляем из шаблона
      container.insertAdjacentHTML('beforeend', cTemplate());

      let canvas = container.querySelector('.file:last-of-type').querySelector('.canvas');
      canvas.width = img.naturalWidth;
      canvas.height = img.naturalHeight;
      var ctx = canvas.getContext("2d").drawImage(img, 0, 0);
      canvas.style['width'] = img.naturalWidth / 4 + 'px';
      canvas.style['height'] = img.naturalHeight / 4 + 'px';
    };

    reader.readAsDataURL(file);
  }
};
#photos {
  display: flex;
  margin-top: 20px;
}
.file {
  position: relative;
  margin: 0 5px 5px 0;
}
.file-delete {
  position: absolute;
  top: 0;
  right: 0;
  background: #fff;
  width: 18px;
  color: #f00;
  text-align: center;
  text-decoration: none;
}
canvas {
  background: #ccc;
  width: 0px;
  height: 100px;
}

<input id="file-input" type="file" multiple="multiple">


Q:

how to use ktc pure coconut oil?

I bought a bottle of ktc pure coconut oil but as far as I can tell, it is in solid form and not liquid as I sort of expected. How can I use it?
In case anyone has used it, is the oil going to cause the food to impart a coconut flavour?
This is the bottle I have at home:
http://ecx.images-amazon.com/images/I/31evWfwu6-L._SL500_AA300_.jpg

A:

Coconut oil is a saturated fat, which makes it solid at room temperature. Above room temperature, it behaves exactly like any other oil and has a very high smoke point. You don't need to treat it in any special way.
I personally just use a knife or spoon to dig a little bit out of the container.
Coconut oil is considered to have a neutral flavour (with the exception of some "virgin" coconut oils). It's much weaker than, say, olive oil. You'll most likely not be able to detect any coconut flavour from oil alone - you have to use something like creamed coconut (a common ingredient in satays) for that.
P.S. Although it might appear to be similar to butter or margarine, keep in mind that it is actually a cooking oil, unlike butter which has milk solids that burn, or margarine which is hydrogenated to make it solid. Coconut oil is just barely solid and won't always work as a substitute for those other things.


Q:

When i call the controller method in which i write this code to send email. My webpage does not load . and it does not show any error

When i call the controller method in which i write this code
 $config = array(
        'protocol' => 'smtp',
        'smtp_host' => 'ssl://smtp.googlemail.com',
        'smtp_port' => 465,
        'smtp_user' => 'me.atiq32@gmail.com',
        'smtp_pass' => '********'
    );
    $this->load->library('email', $config);
    $this->email->from('me.atiq32@gmail.com', 'Atiq');
    $this->email->to('***@yahoo.com');
    $this->email->subject('Email Test');
    $this->email->message('Testing the email class.');

    if ($this->email->send()) {
        echo 'Email will be Sent';
    } else {
        echo $this->email->print_debugger();
    }
} '

to send email.
 My webpage does not load (in loading ....).
and even does not show any error.

A:

are those stray characters at the very end? if yes they might be messing it up.
otherwise -- its hard to tell because we can't see all the code. what i do in situations like this is echo out a check before the method is called like
 echo " before email " ;
 $this->sendemail() ;
 echo " after email " ;

that gives you a sanity check to see where in the chain its breaking down. otherwise if you can't figure it out post more of your code.


Q:

Is It Possible To Use Heroku Scheduler To Automatically Generate A New Blog Post Everyday?

I'm making a blog like application which I want to automatically generate a new post every day, starting from a user-defined start-date. So for example, if I set it to the 25th of June, from that day and every day afterward it would start generating posts. These automatically generated posts would then be able to be edited by the user.
I've heard of other gems such as Whenever and Rufus-Scheduler which could potentially do this but I've also heard they have issues when deployed to Heroku. Would the Heroku Scheduler be able to automatically generate a new blog post for a user?
Thanks!

A:

Yes, Heroku scheduler can do that. I recommend you create a rake task that creates a blog post, e.g.:
STARTING_DATE = Date.new(2017, 6, 25)

task :create_post => :environment do
  Post.create!(title: "Draft created on #{Date.today.strftime('%d %b %Y')") if Date.today >= STARTING_DATE
end

Then just create a scheduler entry that runs rake create_post every day.


Q:

Crystal Report- how to round decimal in crystal report?

I am currently trying to round up the figure in my crystal report but the round function in crystal report does not change it to correct figure.
If the amount is 32,000, I want to convert it to 40,000 by rounding.
If the amount is 24,000, I want to convert it to 30,000,
Is there any way to do this such rounding?

A:

You can do something like:
int num = 32000;
string textNum  = num.ToString();
//count number of zero
int countZero = textNum.Length - textNum.TrimEnd('0').Length;
//get a divisor to get a fraction
double divisor = (int)Math.Pow(10, (countZero + 1));
double firstDiv = num / divisor;
int val = (int)(Math.Ceiling(firstDiv) * divisor);

Hope that will help :)


Q:

TypeError by writing data structure to XML file in python

I would like to write a data structure into a XML file using Python with etree library. However, I got a TypeError with following message:
If I print the data structure in the command line, it looks fine. I'm not sure if this error is related to my XML file. I already executed the script with python2 and python3.
root = ET.parse(args.filename).getroot()
taxi_root = ET.Element("routes")

for trip_tag in root.iter('trip'):
    ET.SubElement(taxi_root, trip_tag)
    logging.warning(trip_tag, trip_tag.attrib)
    print(trip_tag, trip_tag.attrib)

taxi_tree = ET.ElementTree(taxi_root)
taxi_tree.write("taxi_trips.xml",xml_declaration=True)

The given XML file looks as follows:
<routes>
<trip id="randUni1151:1" type="random" depart="97.00" departPos="34.32" arrivalPos="45.48" arrivalSpeed="0.00" from="-319544709#1" to="25430299#5"/>
<trip id="randUni1922:1" type="random" depart="193.00" departPos="54.02" arrivalPos="134.49" arrivalSpeed="0.00" from="-166643442#0" to="60233456"/>
</routes>

I just want to write the data structure to a file, but I got this message.
Traceback (most recent call last):
  File "filter_Throughput_Traffic.py", line 40, in <module>
    print(ET.tostring(taxi_root, encoding='utf8').decode('utf8'))
  File "/Users/marius/.pyenv/versions/2.7.16/lib/python2.7/xml/etree/ElementTree.py", line 1126, in tostring
    ElementTree(element).write(file, encoding, method=method)
  File "/Users/marius/.pyenv/versions/2.7.16/lib/python2.7/xml/etree/ElementTree.py", line 817, in write
    self._root, encoding, default_namespace
  File "/Users/marius/.pyenv/versions/2.7.16/lib/python2.7/xml/etree/ElementTree.py", line 886, in _namespaces
    _raise_serialization_error(tag)
  File "/Users/marius/.pyenv/versions/2.7.16/lib/python2.7/xml/etree/ElementTree.py", line 1052, in _raise_serialization_error
    "cannot serialize %r (type %s)" % (text, type(text).__name__)
TypeError: cannot serialize <Element 'trip' at 0x103d4c750> (type Element)

A:

The code below works.
Look for the difference.
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import ElementTree

xml = '''<routes>
<trip id="randUni1151:1" type="random" depart="97.00" departPos="34.32" arrivalPos="45.48" arrivalSpeed="0.00" from="-319544709#1" to="25430299#5"/>
<trip id="randUni1922:1" type="random" depart="193.00" departPos="54.02" arrivalPos="134.49" arrivalSpeed="0.00" from="-166643442#0" to="60233456"/>
</routes>'''

root = ET.fromstring(xml)
tree = ElementTree(root)
tree.write('routes.xml')


Q:

Using enums in a class as a parameter

Basically I have a DataManager singleton as follows:
class DataManager {
    static let shared = DataManager()

    private init() {}

    static func set(_ object: String, forKey defaultName: String) {
        let defaults: UserDefaults = UserDefaults.standard
        defaults.set(object, forKey:defaultName)
        defaults.synchronize()
    }

    static func object(forKey key: String) -> String {
        let defaults: UserDefaults = UserDefaults.standard
        return defaults.object(forKey: key) as! String
    }
}

What I want to achieve it as follows, when setting or retrieving saved objects:
DataManager.set("some hash", forKey: .hash)

instead of:
DataManager.set("some hash", forKey: "hash")

Also, what's the technical term for the functionality I'm looking for?

A:

You can have an enum, simply DefaultKey
enum DefaultKey: String {
  case hash = "hash"
  case secondKey = "secondKey"
  case thirdKey = "thirdKey"
}

Now what you have to do is
static func set(_ object: String, forKey keyType: DefaultKey) {
  let defaults: UserDefaults = UserDefaults.standard
  let key = keyType.rawValue // rawvalue for keyType .hash will actually return you "hash".
  defaults.set(object, forKey: key)
  defaults.synchronize()
}

Now you will be able to call function like
DataManager.set("some hash", forKey: .hash)


Q:

"date -d" command fails on Docker Alpine Linux container

I built Alpine Linux in a Docker container with the following Dockerfile:
FROM alpine:3.2
RUN apk add --update jq curl && rm -rf /var/cache/apk/*

the build run successfully:
$ docker build -t collector .
Sending build context to Docker daemon 2.048 kB
Sending build context to Docker daemon
Step 0 : FROM alpine:3.2
3.2: Pulling from alpine
8697b6cc1f48: Already exists
alpine:3.2: The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security.
Digest: sha256:eb84cc74347e4d7c484d566dec8a5eef82bab1b78308b92cda559bcff29c27cc
Status: Downloaded newer image for alpine:3.2
 ---> 8697b6cc1f48
Step 1 : RUN apk add --update jq curl && rm -rf /var/cache/apk/*
 ---> Running in 888571296e79
fetch http://dl-4.alpinelinux.org/alpine/v3.2/main/x86_64/APKINDEX.tar.gz
(1/11) Installing run-parts (4.4-r0)
(2/11) Installing openssl (1.0.2a-r1)
(3/11) Installing lua5.2-libs (5.2.4-r0)
(4/11) Installing lua5.2 (5.2.4-r0)
(5/11) Installing ncurses-terminfo-base (5.9-r3)
(6/11) Installing ncurses-widec-libs (5.9-r3)
(7/11) Installing lua5.2-posix (33.3.1-r2)
(8/11) Installing ca-certificates (20141019-r2)
(9/11) Installing libssh2 (1.5.0-r0)
(10/11) Installing curl (7.42.1-r0)
(11/11) Installing jq (1.4-r0)
Executing busybox-1.23.2-r0.trigger
Executing ca-certificates-20141019-r2.trigger
OK: 9 MiB in 26 packages
 ---> 7625779b773d
Removing intermediate container 888571296e79
Successfully built 7625779b773d

anyway when I run date -d it fails:
$ docker run -i -t collector sh
/ # date -d yesterday
date: invalid date 'yesterday'
/ # date -d now
date: invalid date 'now'
/ # date -d next-month
date: invalid date 'next-month'

while the rest of the options seem running ok:
/ # date
Sat May 30 18:57:24 UTC 2015
/ # date +"%A"
Saturday
/ # date +"%Y-%m-%dT%H:%M:%SZ"
2015-05-30T19:00:38Z

A:

BusyBox/Alpine version of date doesn't support -d options, even if the help is exatly the same in the Ubuntu version as well as in others more fat distros.
Also the "containerization" doesn't miss anything here.
To work with -d options you just need to add coreutils package:
$ cat Dockerfile.alpine-coreutils
FROM alpine:3.2
RUN apk add --update coreutils && rm -rf /var/cache/apk/*

$ docker build -t alpine-coreutils - <  Dockerfile.alpine-coreutils
Sending build context to Docker daemon 2.048 kB
Sending build context to Docker daemon
Step 0 : FROM alpine:3.2
3.2: Pulling from alpine
8697b6cc1f48: Already exists
alpine:3.2: The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security.
Digest: sha256:eb84cc74347e4d7c484d566dec8a5eef82bab1b78308b92cda559bcff29c27cc
Status: Downloaded newer image for alpine:3.2
 ---> 8697b6cc1f48
Step 1 : RUN apk add --update coreutils && rm -rf /var/cache/apk/*
 ---> Running in 694fa5cb271c
fetch http://dl-4.alpinelinux.org/alpine/v3.2/main/x86_64/APKINDEX.tar.gz
(1/3) Installing libattr (2.4.47-r3)
(2/3) Installing libacl (2.2.52-r2)
(3/3) Installing coreutils (8.23-r0)
Executing busybox-1.23.2-r0.trigger
OK: 12 MiB in 18 packages
 ---> a7d9116a00ee
Removing intermediate container 694fa5cb271c
Successfully built a7d9116a00ee

$ docker run -i -t alpine-coreutils sh
/ # date -d last-week
Sun May 24 09:19:34 UTC 2015
/ # date -d yesterday
Sat May 30 09:19:46 UTC 2015
/ # date
Sun May 31 09:19:50 UTC 2015

The image size will double but is till 11.47 MB, more than an order of siZe less, compared to Debian standard :
$ docker images
REPOSITORY                 TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
alpine-coreutils           latest              a7d9116a00ee        2 minutes ago       11.47 MB
alpine                     3.2                 8697b6cc1f48        2 days ago          5.242 MB
debian                     latest              df2a0347c9d0        11 days ago         125.2 MB

Thanks to Andy Shinn:       https://github.com/gliderlabs/docker-alpine/issues/40#issuecomment-107122371
And to Christopher Horrell: https://github.com/docker-library/official-images/issues/771#issuecomment-107101595

A:

busybox date supports a -D option which (like zsh's strftime but contrary to GNU date) gives you an interface to strptime() where you can parse dates (though not relative dates) in any format (ast-open date and ksh93's printf also have ways to customize the input format).
Where busybox is built against a C library implementation whose strptime() and strftime() support the non-standard %s flag, you could do:
date -D %s -d "$(($(date +%s) - 86400))"

In the musl C library which alpine Linux uses however, strftime() does support %s but strptime() doesn't. It's OK though as busybox date, like GNU date supports the @epochtime date specification, so you can do:
date -d "@$(($(date +%s) - 86400))"

Which will give you the date 86400 seconds ago, without the ambiguity of GNU date's yesterday (is it 86400 ago, or is it yesterday at the same time of the day? What if there was no such time of the day yesterday because the clock changed for DST?).
That syntax should also work with GNU date.
With ast-open's date (or ksh93's printf '%(%c)T'), you'd use:
date -d "#$(($(date +%s) - 86400))"

instead.
Note that if you want to report UTC (Zulu) time, you should use TZ=UTC0 date or date -u as otherwise, you'd get the time in the system's/user's timezone.


Q:

closing http session from other thread

I've implemented a Web application using Spring MVC. The Web application is integrated in a system that has a desktop user interface. I would like to allow users to close Web application's sessions from the destkop GUI.
I tried implementing a non very elegant solution: invoke httpsession's invalidate but it breaks sometimes when the session being invalidated is used within a running http request. It throws an IllegalStateException at DispatcherServlet when it is trying to invoke render (specifically at WebUtil.getSessionAttribute) because it is trying to access a session attribute and the session is already invalid.
So my question is: is there any way to kick a user from its session from a non-http-request thread without having conflicts with running http requests? Or at least a conflict that I can manage.
Thanks,
Jorge

A:

You could hand-roll a mechanism involving a static set of sessions that you want to expire, and a servlet filter that checks this set for the current session, then calls session.invalidate and redirects the user cleanly. Your desktop API would simply add a session to this set, and the user would become invalidated cleanly (in an HTTP request thread) upon the following request.
In order to prevent memory leaks, you would also need a listener to remove a session from this set upon invalidation- thus ensuring that this set only contains valid sessions.


Q:

Assert and require response error message

I have one sentence in my code that is evaluating a condition. If the evaluation fail´s I throw a execption with assert and require. In my case I think that require is the indicated election for a boolean condition.
The exception is collected but testing between assert anf require the EVM return me two cain of message.
My problem is that I cant understand why return me this message.
It´s some mechanism to return a simple string with a error message?
**Assert response

**Require response

A:

Those message are not related to assert or require by themselves. May be you have some different problems, like gas limit setting too low or whatsoever.
Try to assess this replacing the assert/require conditions with something stable and work to obtain the desired results. Then put in your conditions.
In short use:
require(true);     // never reverts
require(false);    // always reverts
assert(true);       // never reverts
assert(false);     // always reverts

-> be sure to switch off any optimization!!!
until your contract compile and deploy as required, after that you can work on those require and assert you need.
By the way: you should use require when your condition can be met or not depending on data and runtime conditions, assert when your condition must be always true (or false), whichever be the general situation.


Q:

Can strings be 'late bound' as if they were words in the same positions?

When you LOAD a string, it biases to the user context by default:
>> f: 3

>> outside: object [
    f: 4
    getter: does [
        print reduce compose [(load "f")]
    ]
]

>> outside/getter
3

This turns out to be an artifact of LOAD's implementation, which uses intern to "Import (internalize) words and their values from the lib into the user context."
To get around this, I can save myself the inefficiency of creating a potentially-useless binding via LOAD, use TO-WORD instead, then use the object's self to rebind it:
>> m: 10

>> inside: object [
    m: 20
    getter: does [
        print reduce [(bind to-word "m" self)]
    ]
]

>> inside/getter
20

Now my question:
Given the way that definitional "scoping" works, is there simply no way--present or future--for this pattern's getter-code and getter-text to both output 4 20:
>> f: 0

>> m: 0

>> ctx: context [
    f: 4

    m: 10

    both: object [
        m: 20
        getter-code: does [print [f m]]
        getter-text: does [impossible-print ["f" "m"]]
    ]
]

E.g. there is something fundamentally missing to where impossible-print can't be written?

A:

As you quite rightly point out, LOAD biases to the user context.
Without access to the contexts you want to bind the words (that will be loaded from "f" and "m") to, your function would indeed be impossible.
Fortunately, contexts are first-class objects in Rebol, so an answer might look like this:
f: m: 0 ctx: context [
    f: 4
    m: 10
    both: object [
        m: 20
        getter-code: does [print [f m]]
        getter-text: does [impossible-print reduce ["f" ctx "m" self]]
    ]
]
impossible-print: func [vars /local r][
    r: copy []
    foreach [v c] vars [append r bind to-word v c]
    print r
]


Q:

Selectively retrieve data from tables when one record in first table is linked to multiple records in second table

I have 2 tables:
1.  Tbl_Master: columns:
     a. SEQ_id
     b. M_Email_id
     c. M_location_id
     d. Del_flag

2.  Tbl_User: columns
     a. U_email_id
     b. Last_logged_date
     c. User_id

First table Is master table it has unique rows i.e. single record of all users in the system.
Each User can be uniquely identified by the email_id in each table.
One user can have multiple profile, which means for one us_email_id field in the tblUser table, there can be many user_id in tbl_User,
i.e there can be multiple entries in second table for each user.
Now I have to select only those users who have logged in for last time before, lets say '2012', i.e before 1-Jan-2012.
But if one user has 2 or more user_id and one user_id has last_logged_date less than 2012
But other user_id has greater than 2012 then such user should be ignored.
In the last all all the result user will be marked for deletion by setting DEL_flag in master table to ‘Yes’
For eg:
    Record in Tbl_Master:
    A123 ram@abc.com D234 No
    A123 john@abc.com D256 No

    Record in tbl_User can be Like:
    ram@abc.com  '11-Dec-2011'   Ram1
    ram@abc.com  '05-Apr-2014'   Ram2
    john@abc.com '15-Dec-2010'  John1

In such case only John's Record should be selected not of Ram whose one profile has last_logged_date>1-Jan-2012

A:

Another possibility was
SELECT
    m.M_Email_id,
    MAX(u.Last_logged_date) AS last_login
FROM
    Tbl_Master m
INNER JOIN
    Tbl_User u on u.U_email_id = m.M_Email_id
GROUP BY m.M_Email_id
HAVING
    -- Year(MAX(u.Last_logged_date)) < 2012   -- use the appropriate function of your DBMS
    EXTRACT(YEAR FROM(MAX(u.Last_logged_date))) < 2012 -- should be the version for oracle
 -- see http://docs.oracle.com/cd/B14117_01/server.101/b10759/functions045.htm#i1017161

Your UPDATE operation can use this select in the WHERE clause.


Q:

Как сделать push определенных файлов в git?

Вот изменил я проект и сделал сначала git add ., затем все закомител git commit -m "..." и затем пушнул в репозиторий в мастер ветку. А теперь мне нужно некоторые файлы пушнуть в другую ветку. Но как это сделать?

A:

После вашего пуша в мастер надо переключиться на нужную ветку git checkout branch_name (либо же git checkout -b branch_name если ветка ещё не создана), закоммитить нужные файлы git commit file.jpg (для каждого файла) и делать пуш нужных этих файлов git push origin branch_name в ветку


Q:

How to create file using script task in ssis with format YYYYMMDDHHMMSS.txt

how to create a text file of the format Employee_YYYYMMDDHHMMSS.txt using script task and everytime we run that task the seconds should increment

A:

    string Filename = "Employee_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
    StreamWriter Writer = new StreamWriter(Filename);
    Writer.WriteLine("Line");
    Writer.Close();


Q:

Regexp match optional group unless it's got something inside it

I'm playing around with this regexp: http://regex101.com/r/dL3qX1
!\[(.*?)\](?:\(\)|\[\])?

All the below strings should match. However, should the second set of brackets, that is optional, contain anything within it, the regexp should match nothing.
// Match
![]
![caption]
![]()
![caption]()
![][]
![caption][]

// No match
![][No match]
![caption][No match]
![](No match)
![caption](No match)

I should still be able to match examples that have text at the end of the line.
![] hello
![caption][] hi there

In other words, I only want a match if there is no optional group, or if there is, I only want a match if the optional group is empty (nothing between the brackets).
Is what I'm after possible?

A:

I personally prefer using negated class when it comes to brackets:
^!\[([^\[\]]*)\](?:\(\)|\[\])?$

regex101 demo
I substituted (.*?) to [^\[\]]*, added ^ and $ at the beginning and end respectively.
That is, if I understood what you're looking for correctly, only the first set is matching.


Q:

How to modify javascript code to keep values from multiple html drop down menus

I have 3 html drop down menu's and I try to keep the values selected after submitting the form
 <select name="select_zone" id="select_zone">
     <option value="a">A</option>
     <option value="b">B</option>
     <option value="c">C</option>
 </select>

this is the javascript:
<script>
     document.getElementById("select_zone").onchange = function() {
        localStorage['select_zone'] = document.getElementById("select_zone").value;
       }
       window.onload= function(){
           if(localStorage['select_zone'])
               document.getElementById("select_zone").value = localStorage['select_zone'];
       }
   </script>

This works, but the problem is that if I copy the code 2 more times for the other drop down menus, only 1 menu at a time keep the values.
How would you change the js code so that all menu's keep the values?

A:

You have to give 3 different ids, something like that (not tested):
 <select name="select_zone_1" id="select_zone_1">
     <option value="a">A</option>
     <option value="b">B</option>
     <option value="c">C</option>
 </select>
 <select name="select_zone_2" id="select_zone_2">
     <option value="a">A</option>
     <option value="b">B</option>
     <option value="c">C</option>
 </select>
 <select name="select_zone_3" id="select_zone_3">
     <option value="a">A</option>
     <option value="b">B</option>
     <option value="c">C</option>
 </select>

Javascript:
for (let i = 1; i <= 3; i++) {
    let id = `select_zone_${i}`;
    document.getElementById(id).onchange = function() {
        localStorage[id] = document.getElementById(id).value;
    }
    window.onload = function() {
        if (localStorage[id]) {
            document.getElementById(id).value = localStorage[id];
        }
    }
}

You can remove the name attribute if you don't need it elsewhere.
EDIT
In order to be more reliable, you can try this:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
 <select class="storable" id="select_zone_1">
     <option value="a">A</option>
     <option value="b">B</option>
     <option value="c">C</option>
 </select>
 <select class="storable" id="select_zone_2">
     <option value="a">A</option>
     <option value="b">B</option>
     <option value="c">C</option>
 </select>
 <select class="storable" id="select_zone_3">
     <option value="a">A</option>
     <option value="b">B</option>
     <option value="c">C</option>
 </select>

 <script>
     function getStorableElements() {
         return document.querySelectorAll('.storable');
     }

     for (const element of getStorableElements()) {
         element.onchange = () => localStorage[element.id] = element.value;
     }

     window.onload = () => {
         for (const element of getStorableElements()) {
             const id = element.id;
             if (localStorage[id]) {
                 element.value = localStorage[id];
             }
         }
     }
 </script>
</body>
</html>


Q:

Custom rewrite rule is breaking pagination

I have been working on a WordPress website where all blog posts are shown on a custom page called /blog/ using a custom page template with a custom query.
With that in mind, I needed to modify the default post URL to include an additional slug in the URL.  E.g. "example.com/post-name/" would become "example.com/blog/post-name/".
Doing it via the standard "permalinks" page was not an option for this particular website, so I did it via custom rewrite rule in my theme function.php file.
function add_rewrite_rules( $wp_rewrite ){
    $new_rules = array(
        'blog/(.+?)/?$' => 'index.php?post_type=post&name='. $wp_rewrite->preg_index(1),
    );

    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'add_rewrite_rules');

This worked fine, but it broke pagination on my /blog/ page. The page works fine, but the pagination on the page does not work with this rewrite rule in place, so when going to "example.com/blog/page/2/" I get a 404 error.
I figured out that I need to update my rewrite rule to EXCLUDE instances where the URL is "/blog/page/x/" because at the moment, my re-write rule is being applied to anything that is "/blog/x".
That being said, I cannot figure out how to modify my re-write rule as needed.  I tried:
function add_rewrite_rules( $wp_rewrite ){
    $new_rules = array(
        'blog/(.+?)/?$' => 'index.php?post_type=post&name='. $wp_rewrite->preg_index(1),
        'blog/page/([^/]+)/?' => 'index.php?pagename=blog&paged=$matches[1]',
    );

    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'add_rewrite_rules');

I thought that if I defined a second rule that applies to instances where the incoming url is "/blog/page/xxx" then it would override the original rule and allow everything to work properly, but it didn't work out this way.
Would appreciate if someone could help me figure this out!
EDIT 1:
Tried to implement a solution found on WordPress Rewrite Rule to exclude specific slug
function add_rewrite_rules( $wp_rewrite )
{
    $new_rules = array(
        'blog/(?!page)(.+?)/?$' => 'index.php?post_type=post&name='. $wp_rewrite->preg_index(1),
    );

    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'add_rewrite_rules');

This did not work. Perhaps I implemented it in the wrong place....not sure.

A:

Managed to get it working now with the following code in my function:
'^blog/(?!.*page)([a-z-_]+)/?' => 'index.php?post_type=post&name='. $wp_rewrite->preg_index(1),


Q:

Why I can't bypass function()'s inside hover()?

This is my code:
$(".link").hover(
    function () {
        FunctionA($(this));
    },
    function () {
        FunctionB();
    }
);

why I can't just write:
$(".link").hover(
    FunctionA($(this)),
    FunctionB()
);

will fast the code...

A:

$(".link").hover(
    FunctionA($(this)),
    FunctionB()
);

Passing $(this) is totally useless. Infact, if you call (and you can) hover in this way:
$(".link").hover(FunctionA, FunctionB);

In FunctionA you can access to the caller:
var FunctionA = function() {
    console.log($(this));
    /* will print $(".link") */
}

Example here.
Basically, as you can see in the api documentation, hover expects two handler functions (handlerIn and handlerOut), both without parameters.


Q:

mktime() overwrite time_t in C

I have a problem with mktime in c:
time_t t_fim;
time(&t_fim);

struct tm* p_fim;
struct tm* c_fim;
p_fim = localtime(&t_fim);
c_fim = localtime(&t_fim);

......

p_fim->tm_year = ano-1900;
p_fim->tm_mon = mes-1;
p_fim->tm_mday = dia;
//here the p_fim date is good

c_fim->tm_mday -=47;
mktime(c_fim);

printf("Pascoa %d %d %d\n", p_fim->tm_mday, p_fim->tm_mon + 1, p_fim->tm_year + 1900);
printf("Carnaval %d %d %d\n", c_fim->tm_mday, c_fim->tm_mon+1, c_fim->tm_year + 1900);

//here the c_fim is good with -47 days but the `p_fim` is now equal with `c_fim`

The mktime is changing the value of p_fim, how to solve that?

A:

Try getting rid of the pointers
struct tm p_fim;
struct tm c_fim;
p_fim = *localtime(&t_fim);
c_fim = *localtime(&t_fim);

Or, if you're on a POSIX system, try localtime_r() instead


Q:

Response Interceptor in Angular2

I send many HTTP requests into a server, and the server returns each of them a response with a new access token (maybe in header or body).
Is there any way to handle all responses before or after it finishes, like middleware for a request in some back-end framework?

A:

If you are using Angular version 4+ you can look at HttpClientModule which provides support for interceptors.
eg
import { Observable } from 'rxjs';
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import { HttpErrorResponse } from "@angular/common/http";

@Injectable()
export class AngularInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(event => {}, err => {
        if(err instanceof HttpErrorResponse){
            console.log("Error Caught By Interceptor");
            //Observable.throw(err);
        }
    });
  }
}

Register to app.module
@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        HttpClientModule
    ],
    providers: [
        [ { provide: HTTP_INTERCEPTORS, useClass:
              AngularInterceptor, multi: true } ]
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

More on HttpClientModule
If you are not using angular v4 check this answer on SO link


Q:

How to write a "Not In" SQL query in LINQ?

How would I translate the following SQL query in to a comparable LINQ query?
select * from Dept
where Id not in (
    Select Id
    from Employee
    where Salary > 100);

A:

Try something like this:
var result = from d in Dept
             let expensiveEmployeeIds = (from e in Employee.Employees
                                       where e.Salary > 100
                                       select e.Id)
             where !expensiveEmployeeIds.Contains(d.Id)
             select d;


Q:

Can I use inheritance in remote/local interfaces? (EJB3)

An example:
@Remote
public interface SomeComponentRemote{

    public Something processStuff();

}

//--

@Local
public interface SomeComponentLocal extends SomeComponentRemote{

}

Is that allowed? Can i do this regularly?

A:

Your way is not allowed as you can not mark your interface with both @Local and @Remote annotations according to specification. And it is not a good idea from point of code reading.
Recommended solution is
public interface SomeComponent {
    public Something processStuff();
}

@Local
public interface SomeComponentLocal extends SomeComponent {
}

@Remote
public interface SomeComponentRemote extends SomeComponent {
}

A:

This code will work since @local/@remote annotations are not inherited. Is is also possible to set a no-interface-view on the bean itself with @LocalBean while implementing the remote interface (instead of a local interface).
The more important point is that every interface should only offer what is needed for the users of this class because every method you offer will be probably used and then you have to maintain this method.
The question is what you are going to do: will both interfaces offer the same methods all the time? Or is one interface a possible subset of the other (if you extend local from remote then it suggests that perhaps not every addition to local will be offered as remote).
The same for @LocalBean - are there public methods that are just accessed by the ejb-container and not conceived for other users?
The only bad thing you can do is designing an interface by laziness rather than intention. Neither excludes to write less code.


Q:

Best practices for runtime-only dependencies in OSGi

In line with the Open-Closed Principle, I typically design my Java packages and libraries in such a way that there is a generic "interface" or "API" package/library and one or more implementations (quite similar to many common APIs like JDBC or JAXP/SAX).
To locate an implementation (or sometimes multiple implementations) in the base API library without violating OCP, I commonly use Java's ServiceLoader mechanism, or occasionally classpath scanning via third-party libraries like ClassGraph or Reflections. From a Maven perspective, the implementations are brought in as runtime dependencies (as they're only needed at execution time, but not at compile time). Pretty standard stuff.
So, now, I want to make some of these packages available as OSGi bundles (with API and implementation in separate bundles), but since in OSGi each bundle has its own class loader, neither classpath scanning nor the ServiceLoader API will work for this purpose. At first glance, OSGi's "fragment" mechanism seems to be the closest equivalent to the plain-Java setup described above. In that scenario, the API bundle would be the "fragment host", and concrete implementations would attach as fragments to that host bundle. As the fragment host and all its attached fragments use the same class loader, the standard plain-Java mechanisms like ServiceLoader or ClassGraph would conceivably still work. This would also have the advantage that there would be no need to detect whether a library/bundle is running in an OSGi context or not, and no OSGi framework dependencies are needed.
So, in a nutshell, my question is: are fragments the correct way to implement runtime-only dependencies in OSGi or is there a better (or more standard) way? Preferably, I'm looking for a solution that works in an OSGi container but does not require a dependency on OSGi itself.

A:

No Fragments are almost always wrong outside the translations. The OSGi model is to use services.
The way to go then is to use DS. Using bnd (in maven, gradle, ant, sbt, or Bndtools) you can create components. A component is a Plain Old Java Object (POJO) that is annotated with injection and activation instructions. You could make those components to take all its dependencies in the constructor.
The bnd code uses the annotations to generate an XML file that is used in runtime to create, activate, inject, and register those components. This will then work out of the box in an OSGi Framework. The annotations are build time so they do not create dependencies in your runtime.
In your non-OSGi environment, you'd be responsible to call that constructor yourself. So you gather your dependencies using the Service Loader and then construct them in the right order.
@Component
public class MyComponent implements Foo {

      final Bar bar;

      @Activate
      public MyComponent( @Reference Bar bar ) {
        this.bar = bar;
      }
      ...
}


Q:

How do I create an AR marker for Vuforia / Unity?

This is a horribly basic question I know (!) but how do I create and import an AR marker into Unity? I know I am meant to do it through the Vuforia Marker Manager page. I have created a Target Database and I have downloaded the database, but how do I get the marker to display in Unity?
Also: what exactly is a Target Database? Is that another name for 'marker'?

A:

To answer your question specifically, yes your Marker is your Target.
So what you need to do is:

Go to License Manager. Add a License Key choosing None as your License plan.
Now go to Target Manager. Create a Database and add the license for it from the drop down.
Add Target, and select from your computer the Image that you want to be the Marker, and upload it.
Once the status of the Target changes to active you can click Download Database and make sure you click For UnityEditor. This downloads a .unitypackage
Now inside Unity, go to Assets>Import New Assets... and locate to the .unitypackage you downloaded

This is how you import your database.

If you haven't Imported the Vuforia package Unity Extension then you
  simply need to download it from the Downloads section and Import it
  through the Assets>Import Package> Custom Package

Now ideally to work with AR, you would use the AR Camera, which is located in your Assets Bar in Qualcomm Augmented Reality>Prefabs. Drag ARCamera onto your scene.
With the AR Camera selected in the Hierarchy look at the Inspector tab. You'll see Data Set Load Behavior. Under that you SHOULD see the name of the .unitypakage you imported ealier. Check the name as well as make it Active.
Now in Qualcomm Augmented Reality>Prefabs you should also see Image Target. Drag that onto the screen as well.
With the ImageTarget selected in Hierarchy look at the Inspectorthere should be Image Target Behaviour

Fill in as follows
Type: Predefined
Data Set: <Name of imported .unitypackage>
Image Target: <Name of Picture uploaded into the Database>

Now you may work around the Image Target as per your app requirement.

NOTE: In the License Manager, click on the Name of the License and
  you'll see a Alpha-numeric code. Copy that code, and within the
  Inspector of the AR Camera, under QCAR Behaviour>App License Key
  paste the code in. This must be done in order for your app to work on your > device.

Hope this helps you. Please feel free to ask me if anything.


Q:

Centering Items with Flexbox and Overflow

Problem Summary
My desired layout is to be able to center (both vertically and horizontally) an image of unknown size on the page. If the image is too big to fit in either direction, I want to show scroll bars so the user can scroll to see the full image. The issue I've run in to is that when the image is too big to fit, the top and left of the image (depending on what portion is cut off) will never be able to be scrolled to.
Attempted Solution
I am attempting to use flexbox to achieve the desired layout, but flexbox is not a requirement. Here is a small example that reproduces the problem (note that I haven't put any browser prefixes in the CSS, so you will want to view this in Chrome [or maybe Firefox, too?]):

.body {
  height: 600px;
}

.container {
  margin: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid red;
  height: 100%;
  overflow: auto;
}

img {
  border: 5px solid black;
}

You should be able to see the border completely around the image, but the left and/or top part of the image will get cut off as the window shrinks. More and more of the image will become un-viewable as the window continues to shrink.
Note that it doesn't seem to matter if there is an image in there. Here's a snippet just using plain-old divs to show the problem:

.body {
  height: 600px;
  margin-top: 80px;
}

.container {
  margin: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid red;
  height: 100%;
  overflow: auto;
}

.content {
  border: 5px solid black;
  width: 600px;
  height: 600px;
  background-color: gray;
}

Again the entire div should always be reachable by scrolling, but it is not.
Question
How can I achieve the desired layout described above using only HTML and CSS (JS answers not accepted)? Flexbox is not required to solve the problem, but it would be a nice-to-have.
Thanks!

A:

Just remove the justify-content from your .container and add a margin: auto to your image.

.body {
  height: 600px;
}

.container {
  margin: auto;
  display: flex;
  /* align-items: center; // no need for this anymore */
  /* justify-content: center; // remove this */
  border: 1px solid red;
  height: 100%;
  overflow: auto;
}

img {
  border: 5px solid black;
  margin: auto;  /* add this */
}


Q:

Error trying to get window of iFrame

I am attempting to get the window of an iFrame using the following code:
  var frameWindow = document.getElementById("loginframe");
  var iWindow = frameWindow.contentWindow;

Unfortunately, I keep getting the following error:
Property 'contentWindow' does not exist on type 'HTMLElement'.)

As you can see in the screenshot below, "contentWindow" is highlighted in red which is an error...

I have tried casting:
  let map = document.getElementById("loginframe") as HTMLObjectElement;
  let insideDoc = map.contentDocument;

But this does not work either...
Is this something to do with angular libraries that perhaps I need to include?

A:

First of all you shouldn't select a DOM element like that you should use a viewChild to do that.
<iframe src="urlHere" #loginframe ></iframe>

Then you can use it in your TypeScript code like this:
@ViewChild('loginframe') loginframe: ElementRef;

After that you can select the element like this: (Note: you should cast it to a HTMLIFrameElement)
const win = (<HTMLIFrameElement> this.loginframe).nativeElement.contentWindow;

Here is a fully working plnkr! (open your console to see the output)
https://embed.plnkr.co/kicS6o8QlOEcXyMKNjFi/