text:
Q: what is more performant equal or instanceof? Which method is performanter to use?
equals:
public boolean hasSellByDate(Object item) {
  if ("Pear".equals(item.getClass().getSimpleName())) {
    return true;
  }
  return false;
}

instanceof:
public boolean hasSellByDate(Object item) {
   if (item instanceof food.Pear) {
     return true;
   }
   return false;
 }

What differences do these two methods have and what disadvantages are there in each case?

A: The second one if far superior because the first can be broken by refactoring, and the type-system will not let you know.
You should also be aware that the first method will not work for subclasses of Pear, should you have any. Even worse, it might be confused if you have multiple classes called "Pear" in different namespaces.
As for performance, you will need to benchmark, but I would expect the second to also be faster, since instanceof is a single opcode on the JVM (https://en.wikipedia.org/wiki/Java_bytecode_instruction_listings).

A: I would like to add other two snippets to your list. So four options would look like below.
Please mind that all four options are functionally different!
#1
public boolean hasSellByDate(Object item) {
  if ("Pear".equals(item.getClass().getSimpleName())) {
    return true;
  }
  return false;
}

#2
public boolean hasSellByDate(Object item) {
  if (item instanceof food.Pear) {
    return true;
  }
  return false;
}

#3
public boolean hasSellByDate(Object item) {
  if ("food.Pear".equals(item.getClass().getName())) {
    return true;
  }
  return false;
}

#4
public boolean hasSellByDate(Object item) {
  if (item.class == food.Pear) {
    return true;
  }
  return false;
}

Performancewise (at least in OpenJDK HotSpot JVM):

*

*#4 is the fastest

*#2 and #3 would be close, #2 is likely to be fastest after round of JIT compilation

*#1 could be real performance bottleneck especially in multi threaded environment

Class.getSimpleName() could be unreasonable slow due to global critical section and string manipulation. I've seen it once being a real performance bottleneck. Method was used for formatting log messages.
Stylewise, I would recommend #2 and #4 dependent on functional needs.
And to stress one more time, all four options are functionally different!


text:
Q: Найти середину отрезка Polyline Есть ломаная Polyline, известны координаты её начала и конца.
Стоит задача разделить ломаную на 2 равные части, каждую из которых сделать разным цветом.
Пробовал решить геометрически по Формуле вычисления координат середины отрезка, но при больших расстояниях вычисляемая точка отклоняется от изначального отрезка.
Есть ли варианты решения?

A: Яндекс использует для карты проекцию Меркатора, поэтому всегда координаты центра надо считать, используя глобальные пиксельные координаты линии, а для отрисовки переводить обратно.
//Пикельные координаты линии:
var linePixelGeo = myPolyline1.geometry.getPixelGeometry().getCoordinates(),
//Пиксельные координаты центра:
lineCenter = [(linePixelGeo[0][0]+linePixelGeo[1][0])/2,(linePixelGeo[0][1]+linePixelGeo[1][1])/2]
//Геокоординаты центра:
var geoLineCenter = myMap.options.get('projection').fromGlobalPixels(lineCenter, myMap.getZoom());

Не лучший пример, но результат виден: https://jsfiddle.net/Coroner1st/ze3jkwgb/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass payload using HttpOutboundAdapter in Spring-Integration We are trying to pass a payload to a POST call that is being made using HttpOutboundGateway. A file is read and the content is stored in the channel. In order to retrieve the content of the channel, we are setting the extractPayload to true. We are using Spring-Integration along with DSL and not the XML approach. Any guidance would be appreciated.
return IntegrationFlows.from("FileContentChannel")
                .channel("FileContentChannel")
                .enrichHeaders(h -> h.header("xxx", "xxx")
                        .header("xxx", "xxx"))
                .handle(Http.outboundGateway("http://payment/gateway")
                        .charset("UTF-8")
                        .httpMethod(HttpMethod.POST)
                        .extractPayload(true)
                        .mappedRequestHeaders("pay*")
                        .headerMapper(headerMapper())
                        .expectedResponseType(String.class))
                .channel(MessageChannels.queue("paymentResponseChannel"))
                .get();

Error log :
2016-10-26 16:34:22.343 ERROR 1584 --- [ask-scheduler-6] o.s.integration.handler.LoggingHandler   : org.springframework.messaging.MessageHandlingException: HTTP request execution failed for URI [http://payment/gateway]; nested exception is org.springframework.web.client.HttpClientErrorException: 404 Not Found
at org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler.handleRequestMessage(HttpRequestExecutingMessageHandler.java:409)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:148)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:121)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:423)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:115)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:45)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:105)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutput(AbstractMessageProducingHandler.java:292)
at org.springframework.integration.handler.AbstractMessageProducingHandler.produceOutput(AbstractMessageProducingHandler.java:212)
at org.springframework.integration.handler.AbstractMessageProducingHandler.sendOutputs(AbstractMessageProducingHandler.java:129)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:115)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
at org.springframework.integration.endpoint.PollingConsumer.handleMessage(PollingConsumer.java:129)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.doPoll(AbstractPollingEndpoint.java:272)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.access$000(AbstractPollingEndpoint.java:58)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:190)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:186)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller$1.run(AbstractPollingEndpoint.java:353)
at org.springframework.integration.util.ErrorHandlingTaskExecutor$1.run(ErrorHandlingTaskExecutor.java:55)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:51)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.run(AbstractPollingEndpoint.java:344)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.web.client.HttpClientErrorException: 404 Not Found
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:667)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:620)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:595)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:516)
at org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler.handleRequestMessage(HttpRequestExecutingMessageHandler.java:382)
... 35 more

A: The .handle() is for Service Activator EI pattern. And exactly its responsibility to deliver payload from the input channel to the target service. In your case it is RestTemplate underneath and an HTTP body is built from the payload.
Your configuration looks fully correct. I don't understand where is the problem...
EDIT
Caused by: org.springframework.web.client.HttpClientErrorException: 404 Not Found

Not, sure what makes you think that there is something wrong with payload. Looks like you are missing some HTTP header or use them with wrong value.
You should consult with the server to determine what should be done else.
There is no any clue in your StackTrace that there is something wrong with payload.
OTOH, since we get  404 Not Found that means that the payload is passed from the channel to the Http.outboundGateway().


text:
Q: Subsets and Supersets when evaluating null sets In tryin to evaluate whether the following is true am I expanding these sets correctly:
{{$\emptyset$}} = { $\emptyset$, {$\emptyset$}} therefore {$\emptyset$} $\in$ {{$\emptyset$}} $\equiv$ T
But I'm not sure if the following is equivalent due to the nature of the empty set..
{{$\emptyset$}, {$\emptyset$}} = {$\emptyset$ ,{$\emptyset$}} ?

A: The equation: $\{\{\emptyset\}\} = \{\emptyset,\{\emptyset\}\} $ is false. You have just added another element (the empty set) arbitrarily. The equation $\{\emptyset\}\in\{\{\emptyset\}\}$ is true, however it is irrelevant to the equation written before it. Just look at the one term in the set, it is exactly $\{\emptyset\}$.
The final equation is again false, because $\{\emptyset\} \neq \emptyset$. Also the first set there has a repeated term which is not allowed.


text:
Q: Deferring size calculations until ui rendered Here is my markup:

        This content generated dynamically using ng-include and other directives inside

The second div (.b) changes it's height (elements added inside it dynamically). I wrote a directive that should update the first div (.a)according to the available height:
'use strict';
myModule.directive('resizer', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {

            function updateSizes(event) {
                var a = element.find('.a');
                var b = element.find('.b');

                var bHeight = b.outerHeight();
                var totalHeight = element.height();
                a.height(totalHeight - bHeight);
            }

            element.on('some-event', updateSizes);
            $timeout(updateSizes);
        }
    };
}]);

When I start my app, sometimes, my divs get height equal to zero (height: 0) because b.outerHeight(); and element.height(); return zero.
Why is that? I used $timeout so the browser has time to render the views.
Any idea?

A: You have two possible options (see ngInclude docs here):

*

*use ngInclude onload event

*listen to the $includeContentLoaded event emitted by ngInclude when the content is loaded

I would suggest to use the second option, since will save you to specify the onload event everytime you want to use your directive.
You can specify the listener inside your link function like this:
function link(scope, element, attrs) {
    scope.$on('$includeContentLoaded', function(){
        console.log('Template included');
        // you can add all your height calculation and DOM manipulation here
    });
}

Have a look at this demo Plunker (I hope the content is quite self-explanatory).
Your code should indeed look like this:
'use strict';
myModule.directive('resizer', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {

            function updateSizes(event) {
                var a = element.find('.a');
                var b = element.find('.b');

                var bHeight = b.outerHeight();
                var totalHeight = element.height();
                a.height(totalHeight - bHeight);
            }

            scope.$on('$includeContentLoaded', updateSizes);

        }
    };
}]);

A: Your problem seems to be having an ng-include in your directives template.
ng-include is itself a directive and its creating a new scope. Your resizer directives link function however is executed as soon as the HTML is rendered, so the ng-include-d template is already there, but its content is not yet loaded (its even a seperate HTTP/GET request if the template was not loaded before).
I'm sure there are more fixes, but one would be to use the onload parameter of the ng-include tag:
// ... your directive ...
link: function (scope, element, attrs) {
  function updateSizes(event) {
    console.log (element.find('.b').outerHeight());
  }

  scope.ngOnload = updateSizes;
}

So now into your html template:

This did the trick for me and the div.b elements outerHeight was not 0 anymore in the console log.

I see, that you've played around with $timeout to wait for the browser. If my solution does not work for you, there must be something weird loaded in those div, probably more details needed for a solution. However a debugger statement with chrome debugger in the updateSizes function could help a lot.

A: Approach
A common pattern with angular is to have a nested directive require a parent directive and register itself with the parent. You can use this pattern to solve your problem. I've added the nested directives resizer-source and resizer-dest to your markup:

        This content generated dynamically using ng-include and other directives inside

resizer-source
myModule.directive('resizerSource', function () {
    return {
        require: '^resizer',
        link: function (scope, element, attrs, ctrl) {
          ctrl.registerSource(element);
        }
    };
});

resizer-dest
myModule.directive('resizerDest', function () {
    return {
        require: '^resizer',
        link: function (scope, element, attrs, ctrl) {
          ctrl.registerDest(element);
        }
    };
});

resizer
myModule.directive('resizer', ['$timeout', function ($timeout) {
    return {
        controller: function($scope) {
            var a,b;
            function update() {
              if (a && b) {
                var bHeight = b.outerHeight();
                var totalHeight = element.height();
                a.height(totalHeight - bHeight);
              }
            }
            this.registerSource = function(elm) {
                b = elm;
                update();
            }
            this.registerDest = function(elm) {
                a = elm;
                update();
            }
        }
    };
}]);

Even More Flexibility
If for some reason the height of b isn't available even by the time b's link function runs, you can make this even more flexible by setting a $watch on b's height and registering b only when the watch evaluates to a positive number. Afterwards, cancel the watcher unless you expect the element's height to continue changing.
Additional Info

if I'll $watch b's size, I'll have to cause a digest cycle (by calling $apply() or $digest). I am informing resizer to update using dom events. What do you think about that?

(1) $watching the size is an expensive operation because it will force a reflow every time you check the height. So cancel the $watch asap. (2) There is no guarantee that angular will trigger a digest cycle at the right time so using dom events as you've mentioned may be necessary.
For these reasons using a $watch may not be the best approach at all but it really depends on your particular situation.

Isn't it a good practice to use the elements inside a link function?

There's nothing un-angular about using the controller instead of the link function. They have different orders of invocation, but that doesn't come into play here.

you don't have an access to 'element' in the controller.. Is putting the resizer code inside the link function safe? I mean, I have to put registerSource and registerDest on the controller

You can inject $element into the controller if you need it. Alternatively, you can add a directive's own controller to the require property to access it from the link function. Whether you choose to put code in the controller or link function will usually come down to organization, so don't be afraid to use the controller instead of the link function if it simplifies your code.

A: I suspect the issue may be caused by the delay in loading the ng-include resources.  You can pre-load the cache:
$templateCache.put('template.html', 'Template');

Or if the contents are from an $http call:
$http.get('template.html', {cache:$templateCache});

A: I know this is not the answer that you are looking for, but why do you go so far to make that simple things to work?
The best programming is, no programming
I would just recommend you css only solution for this purpose

Foo

        This content generated dynamically using ng-include and other directives inside

example: http://plnkr.co/edit/H81p2yu0jG8OuB8paFpM?p=preview


text:
Q: C#/.NET: Detect whether program is being run as a service or a console application I have a C#/.NET program that can run both as a console application and as a service.
Currently I give it a command-line option to start as a console application, but I would like to avoid that.
Is it possible to programmatically detect whether my program is being started as a service?
If it was pure Win32, I could try starting as a service with StartServiceCtrlDispatcher and fall back to console if it returned ERROR_FAILED_SERVICE_CONTROLLER_CONNECT, but System.ServiceProcess.ServiceBase.Run() pops up an errordialog if it fails and then just returns without signaling an error to the program.
Any ideas?

A: Rasmus,  this is the earlier question.
From the answers it seems the most popular way is to use a simple command line option, or try accessing the Console object in a try catch block (in a Service the Console is not attached to the process and trying to access it throws an exception).
Or if you're having trouble testing/debugging the service, move code into a separate dll assembly and create a seprate test harness (winforms/console etc).
(Just noticed that Jonathan has added his solution to the end of the question.)

A: Might want to try SessionId property of the Process object.  In my experience SessionId is set to 0 if the process is running a service.

A: Environment.UserInteractive will do the magic.

A: I haven't tried it, but it's possible that Process.GetCurrentProcess will help - under console mode the process name would be the same as the executable, whereas I'd expect (and again, please check!) that when running as a service it would be different.

A: [DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
const int STD_OUTPUT_HANDLE = -11;

IntPtr iStdOut = GetStdHandle(STD_OUTPUT_HANDLE);

if (iStdOut == IntPtr.Zero)

{
    app.RunAsWindowsService = true;

}

// Run as Service
if (runAsWindowsService)
{
     // .....
     ServiceBase.Run(myService);
}
else
{
    // Run as Console
    // Register Ctrl+C Handler...
}

A: Using the ParentProcessUtilities struct from this answer about finding a parent process, you can do this:
static bool RunningAsService() {
    var p = ParentProcessUtilities.GetParentProcess();
    return ( p != null && p.ProcessName == "services" );
}

Note that the process name for the parent process does not include the extension ".exe".

A: I don't know if this will work, but you may want to try using PInvoke with this code and checking if the parent is "services.exe".

A: I ended up detecting whether or not I was in a console application by checking Console.IsErrorRedirected.  It returned "false" for console apps, and "true" for the non-console apps I tested.  I could have also used IsOutputRedirected.
I imagine there are circumstances where these will not be accurate, but this worked well for me.


text:
Q: How can a third-party site know your identity on other sites (e.g. Off-Facebook Activity)? I'm a software engineer by trade, yet I am shocked and fascinated by something I learned just recently. For example, I found out Facebook has businesses and sites share information about my activity on their sites with Facebook. Many sites do this including ones I would not expect. Sidestepping all other types of moral, legal or social questions surrounding this, how do they even do it?
Even if I'm logged into Facebook on a given device or in a given tab, if I visit say foo.bar on another tab, and foo.bar has an agreement to share my activity with Facebook, and granting that Facebook probably never exposes my actual name, but only an account reference, how could they expose even that much on a different site? I'm sure there's not global browser state that any website can write to, right? Standards and implementations prevent that, right? Therefore they must find ways to skirt and circumvent that, right?
How has Facebook leaked or exposed my identity (or an account reference) to said third party site? I thought all such means of sharing information and communicating were (like cookies) were blocked off and quarantined by official web-standards. If I visit one site, say blue.com, is it able to store something so that every other site I visit can read what it has stored and know I visited it (if they share that info)? Or does Facebook get access to it's own cookies set when I was on Facebook.com, if the business websites I visit load a Facebook Iframe or call an XHR request to Facebook for a button or something insignificant, and that Iframe or XHR allows them to get the cookies they once planted on my device, which can also be viewed by the main site I went to visit (i.e. notblue.com) to do with as they please?
If so it's really the business site that's exposing me, by the infrastructure and willingness to do this and my beef should be with them. I'm sure it is done with numerous other sites besides FB and I just used them as an example, because that's how I discovered it, but is this how the technology works? Come to think of it, there's been a lot of internet magic I haven't been able to explain, like how google knows its me across domains like drive and YouTube and Gmail. I assume they use the same mechanism as Off-Facebook activity and I should learn how this works.
I don't mind reading very technical information to understand this- RFCs and such. It's really crazy how so much data can be traded that I didn't even think was possible. It seems that all that's required for two businesses to talk is an an agreement and an implementation, and then what you do on one will be known by other, without you even knowing. Is there a way to turn this off, and is this what the Brave Browser accomplishes? Maybe that's its raison d'etre.

A: "I'm sure there's not global browser state that any website can write to, right"
Yes and no. Say I own the domain "genericadverts.com". I goto various companies with websites and say "If you put my ads on your site I will give you money. Just add a script tag with https://genericadverts.com/getAdverts"
Now I get multiple websites to sign up to the deal. the script is loaded from the same domain on all the sites, so it can write and read the same cookie across all those pages. The JS has access to the DOM of the page it loads in and can communicate back home.
If there is no cookie I will generate a new one with a GUID. I will send the name of the site with whatever other info I collect back home with that GUID. I will show adverts based on that collected information, did you browse to sites that sell product X? do users of site Y fit a certain demographic etc etc
If you are facebook you can do the same thing with those little "share on facebook/youtube/whatever" buttons that people used to slap everywhere for free.


text:
Q: show for every homomorphism $\varphi$, there is a pointed map that induces it. Im trying to show that:
For every homomorphism $\varphi:\Pi_1(S^1,1)\rightarrow\Pi_1(S^1,1)$ there is a pointed map $f:(S^1,1)\rightarrow{(S^1,1)}$ so that $\varphi=f_*$. Namely, $f$ induces $\varphi$.
Im not too sure were to start with this. We know from the homomorphism property that $\varphi([f*g])=\varphi([f]\bullet[g]])=\varphi([f])\bullet\varphi([g])$.

A: A group homomorphism $\varphi:\Bbb Z\to\Bbb Z$ is determined by its value $n=\varphi(1)$, and must be of the form $\varphi=x\mapsto nx$.
Now consider $S^1$ as the set of unit complex numbers, with $1$ as the distinguished point, and verify that
$$f=x\mapsto x^n$$
induces $\varphi$ on the homotopy group.


text:
Q: Avoiding code repetition on multischema database I have a legacy application with a database that splits up the data into multiple schemas on the same physical database.  The schemas are identical in structure.
I use a microservice using Spring Boot Data JPA to do work on a single schema.  Then to avoid code repetition, I created a router service that forwards the request to the single schema microservice replica each with a different database connection.  But I found that a bit overkill (but works)
I am trying to reduce it back down to a single microservice.  I haven't been successful yet, but I set up the tables with the schema property.
@Table(
    name = "alerts",
    schema = "ca"
)

However, it gets confused when I try to do inheritance and @MappedSuperclass to reduce the code duplication.
In addition the @OneToMany breaks apart because of the inheritance getting errors like X references an unknown entity: Y
Basically is there a way of using inheritance on JPA that uses the same table structure with the difference being just the schema without copy and pasting too much code.  Ideally I'd like to just pass a "schema" parameter to a DAO and it somehow does it for me.

A: In the end, we just need a data source that would route according to the situation.  To do this a @Component that extends AbstractRoutingDataSource is used and a ThreadLocal to store the request context.
The ThreadLocal would be something like this (examples are using Lombok)
@AllArgsConstructor
public class UserContext {
    private static final ThreadLocal<UserContext> context =
        new ThreadLocal<>();
    private final String schema;

    public static String getSchema() {
        return context.get().schema;
    }

    public static void setFromXXX(...) {
        context.set(new UserContext(
            ...
        ));
    }
}

A source for the data sources would be needed:
@Configuration
public class DataSources {

    @Bean
    public DataSource schema1() {
        return build("schema1");
    }

    @Bean
    public DataSource schema2() {
        return build("schema2");
    }

    private DataSource buildDataSource(String schema) {
        ...
        return new DriverManagerDataSource(url, username, password);
    }
}

And finally the router which is marked as the @Primary data source to make sure it is the one that gets used by JPA.
@Component
@Primary
public class RoutingDatasource extends AbstractRoutingDataSource {
    @Autowired
    @Qualifier("schema1")
    private DataSource schema1;

    @Autowired
    @Qualifier("schema2")
    private DataSource schema2;

    @Override
    public void afterPropertiesSet() {
        setTargetDataSources(
            Map.of(
                "schema1", schema1,
                "schema2", schema2
            )
        );
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return UserContext.getSchema();
    }
}

This avoids the code duplication when all that is different is a schema or even a data source.


text:
Q: PHP - Over-commenting? I recently started working on a small CMS.  I usually develop .NET applications in C#, and I'm very used to commenting my fields and methods.  My friend told me earler that having comments in PHP scripts is quite bad, since PHP is dynamic and parsed when requested, so having to parse the comments will take longer.
Does this statement apply to my situation, which is commenting every method and field?
Example of one of my classes:
<?php
/*
 *     jWeb
 *     Copyright (C) 2010 AJ Ravindiran
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/**
 * Controls database connections.
 *
 * @author AJ Ravindiran
 * @version 1.0.0 Jan-02-2010
 */
class database {
    /**
     * The database connection ip address.
     * @var string
     */
    private $host = "";

    /**
     * The database user's name.
     * @var string
     */
    private $username = "";
    /**
     * The database user's password.
     * @var string
     */
    private $password = "";

    /**
     * The database that this instance will write to, and read from.
     * @var string
     */
    private $database = "";

    /**
     * Holds the mysql connection instance.
     * @var resource
     */
    private $connection = null;

    /**
     * Whether the instance is connected to the specified database.
     * @var bool
     */
    private $connected = false;

    /**
     * Constructs a new database instance.
     * @param string $host The database server host.
     * @param string $port The database server port.
     * @param string $username The database's username authentication.
     * @param string $password The username's specified password.
     */
    public function __construct($host = "localhost", $username = "root", $password = "") {
        $this->host = $host;
        $this->username = $username;
        $this->password = $password;
    }

    /**
     * Connects to the given database.
     * @param string $database
     */
    public function connect($database) {
        $this->database = $database;

        // TODO: handle errors.
        $this->connection = @mysql_connect($this->host, $this->username, $this->password) or die();
        @mysql_select_db($this->database, $this->connection) or die();

        /*
         * If the connection was successful, we can now
         * identify that the connection is sustained.
         */
        if ($this->connect != null) {
            $this->connected = true;
        }
    }

    /**
     * Gets the specified connection details from this instance.
     * @param boolean $show_details
     * @return string The connection string.
     */
    public function getConnectionString($show_details = false) {
        if ($show_details) {
            return "database[host=" . $this->host
                    . ", port=" . $this->port
                    . ", user=" . $this->username
                    . ", pass=" . $this->password
                    . ", database=" . $this->database . "]";
        } else {
            return "database[host=" . $this->host
                    . ", port=" . $this->port . "]";
        }
    }
}
?>

A: That's b*llshit, the amount of comments has nothing or very little to do with actual processing times, as the comments aren't parsed.
The more meaningful comments you have in your code, the better it will be for the next who has to maintain it.
The commenting style presented in your code sample is exemplary as you are using comments where comments are needed and you are using the phpdoc syntax, which will make creation of documentation a breeze.
Some might critizise the commenting of every class variable, but in my opinion, that's the point of using phpdoc syntax that every meaningful variable, method and class has an explanation.

A: Comment as much as you need to, to make the meaning of your code clear.  The time you gain, if any, by not parsing comments is overwhelmed by the pain of maintaining opaque code.
That said, comments should be meaningful, and you have a bit more than is strictly necessary.  For example:
/**
 * The database that this instance will write to, and read from.
 * @var string
 */
private $database = "";

I question whether the large comment here adds anything to your code.

A: You have commenting and commenting. Especially starters like to translate every single line of code into a "human readable language".
// Assign "a" to x.
$x = "a";

// Do stuff with x and get y.
$y = do_stuff($x);

// Return y.
return $y;

While experts (bit) more experienced programmers often just do:
// Do stuff with "a" and return it.
$x = "a";
$y = do_stuff($x);
return $y;

or even
// Do stuff with "a" and return it.
return do_stuff("a");

Needless to say that the first is an example of "over-commenting". Those kind of comments can however also perfectly be placed as a function-comment. Just write self-explaining code, e.g. do not use variables like $x, but give it a noun name, like $speed or so and give functions a verb name, like increment_speed() or so. This way you can just leave all comments inside the function away which are already explained by the code itself.
"Over-commenting" however doesn't harmfully impact performance. Unless it's a zillion of comment lines on a single line of code, especially if it is an interpreting language. Compiled languages such as Java doesn't suffer from this; comments are already removed after compilation.
Update: you included a code example; it is indeed overdone to comment private properties, especially if they already have a self-explaining name. The comments on the functions are okay.

A: Don't listen to your friend. You shouldn't worry about micro-performance optimizations unless you have profiled your application and found that it spends most of its time parsing comments in your PHP files (and most likely it's not there.... you would need many, many megabytes of comments for it to be noticable).
There are many other ways that you can make your application run slowly, such as using the wrong data structures or incorrectly configuring your database. Removing all the comments just confuses other programmers makes performance hurting errors (and more importantly: logical errors) more likely to happen.

A: I'd consider that a case of absurdly counterproductive premature micro-optimization:

*

*Ignoring the comments is just about the least complex and time-consuming part of parsing

*If performance is important, you'll want to use a server that caches the PHP bytecode anyway, making the parsing overhead irrelevant

*Never trade of maintainability for performance unless you have hard data that proves you have a performance problem and where exactly it lies

A: The other commenters here are exactly right regarding performance. Performance should not be a consideration when commenting in code.
However, to comment on your specific example, I believe your class does have too many comments in it. For example, take a look at this field:
/**
 * The database user's name.
 * @var string
 */
private $username = "";

There's a lot of "visual noise" there and the comment doesn't really explain anything anyway. You have 4 lines worth of comments that don't tell the reader any interesting details. If you want to put a comment there it should explain something interesting about the code, not just repeat what the code does. For example:
/**
 * The database user's name. This field has to be 5 to 10 characters long. It
 * is not required if the connection security is disabled.
 * @var string
 */
private $username = "";

To pick on another example, take a look at this comment:
/**
 * Gets the specified connection details from this instance.
 * @param boolean $show_details
 * @return string The connection string.
 */
public function getConnectionString($show_details = false) {
    ...

This comment is a good start, but it's missing some crucial information: What exactly does the show_details parameter do? What details will be missing if it is not enabled? Or what will be included when it is enabled?
Comments are not fundamentally bad, and more comments is not always worse than fewer comments. It's important to have the right comments!

A: Your friend speaks silliness.
PHP is dynamic and must parse scripts as requested, but the time it takes to parse comments is negligible (because as soon as it encounters a comment it drops to the next relevant line; it's probably only slightly more overhead than whitespace) and the value of the comments to yourself and future maintainers of the system is much, much greater than any potential performance hit.
Feel free to comment liberally.
You can speed up PHP quite a lot by using an opcode caching mechanism like APC or eCache, though. Invest your effort and time into real solutions like that, not presumed silliness like omitting comments.

A: If performance is a priority for your PHP code, you should use a bytecode cache such as:

*

*APC

*eAccelerator

*XCache

*Zend Server

*Windows Cache Extension for PHP
Bytecode caches store code that has been parsed and compiled to bytecode.  Subsequent execution of the same PHP page doesn't have to parse the code, let alone the comments.
Therefore, code comments impact performance only in application deployments that don't care about performance.


text:
Q: Why does only Silverlight for WP7 have a compositor thread? Last week I learned that Silverlight on the Windows Phone uses a "compositor" thread to cache bitmaps and animations and run them independent of the UI thread. This allows animations to run smoothly even if the UI thread becomes blocked.
My question is: why was this introduced only for WP7, and not Silverlight (web) or WPF?

A: A lot of Microsoft's recent focus has been on Silverlight for Windows Phone 7 (make or break time), so they have added essential features to the phone now that would be in the next version of Silverlight. Basically anything to make the phone look fast/smooth/good.
I heard specific mention of an upcoming feature in Silverlight (browser version) being: "running animation storyboards on a background thread". That was in a recent video (sorry lost the link).

A: The compositor (render) thread runs the GPU on Windows Phone 7 devices.
As a resource constrained device, it's necessary to do all the cool animations to have this stuff running on the GPU with bitmap cached images. I would imagine this was an unavoidable design choice for the Windows Phone 7 platform team to accomplish the kind of visuals that are possible on Windows Phone 7 devices.
Sure, perhaps it will also be relevant to do for WPF and Silverlight in general in due course.
So it's not so much about providing another thread to alleviate load from the CPU. It's a thread to manage the GPU. The UI thread runs on the CPU, handling general UI interaction and all other non-GPU code.

A: To have the compositor thread specifically run on a GPU requires that the hardware running the software has a GPU and that it is sufficicently powerful for the task.
WP7 devices are the first place that they can guarantee that every piece of hardware running Silverlight has a baseline hardware requirement.
If Silverlight tried to do this it would have to move the compositor on to the CPU if the hardware it was running on didn't have a GPU. If that CPU was a single core then on some machines the underlying code would just have become more complicated for no performance gain.


text:
Q: How can I fit a folder of images into one matrix in R? I have a folder of letter images. it contains 182 image, each image can be represented in a 12 by 12 matrix. I'm performing a fuzzy c means algorithm. I want to create a loop to fit all images into one matrix or create a loop to fit each image into one matrix. what is the most easy way to do it ?!

A: If get_mat() is your function to convert image to matrix.
For fit each image in an individual matrix
## Set working directory to where images are located
setwd("folder location")

## List files
img_list <- list.files()

## Read files into a list of matrix
img_mat_list <- lapply(img_list,get_mat())

## To join all those matrix rowbind or columnbind
do.call(rbind,img_mat_list)
do.call(cbind,img_mat_list)


text:
Q: I feel that this sentence has a missing word? I feel that this sentence has a missing word. Am I right?

Eating a healthy diet may take some getting used to, but it has many benefits for your health.

I think it must be

take some time getting used to


text:
Q: case insensitive regex returning original pattern If I am looking for a small list of words (these words change dynamically) in a paragraph and want a case insensitive search, I use a pattern like:
words = ['Cat', 'Dog', 'Horse']
reg = re.compile(r"(?i)(\b)(?P<word>" + "|".join(words) + r")(\b)")

which turns into this pattern string:
r"(?i)(\b)(?P<word>Cat|Dog|Horse)(\b)"

This works to find a match in text like the following using re.search():
reg.search('I own a black cat named Sally.')
# Returns one match on 'cat'

How do I return the actual word in the original match pattern? In this case the word "Cat" with a capital C and not the word in the search text with a lowercase c.
Thanks

A: import re

words = ['Cat', 'Dog', 'Horse']
reg = re.compile(r"\b(?:(" + ")|(".join(words) + r"))\b", flags=re.I)

match = reg.search('My grandma owned no cats, only a black doG named Morli.'
                   ' Oh, and no horse, of course.')
if match:
    print(words[match.lastindex - 1])

prints
Dog

This builds a regex like \b(?:(Cat)|(Dog)|(Horse))\b, i.e., a non-capturing group (this is the meaning of ?:) surrounded by word boundaries (the \bs), which is an alternation of capturing groups. The index of the last (and only, if any) matching capturing group is returned in match.lastindex, but this is also the index in the words list (because of how the regex was constructed), except it is offset by 1 because group 0 is the full match.
The set of words found in the text is easily constructed by
words_found = {words[match.lastindex - 1] for match in reg.finditer(text)}

The following is an edit by Patrick Artner, of which I don't think it's an improvement - but I'll leave it here because it is food for thought.
Edit - pls, incorporate:
all_matches = reg.findall('My grandma owned no cat, only a black doG named Morli.A cat named tinker came by.'
                          ' Oh, and no horse, of course.')
found = [ words[idx] for k in all_matches for idx,m in enumerate(k) if m.strip()  ]

print(found) # ['Cat', 'Dog', 'Cat', 'Horse']

A: Somewhat clumsy with a workaround-dict that maps back from the regex-group-match to your original keyword - but should help you out:
import re

def getWordsFromText(text,keywords = ['Cat', 'Dog', 'Horse']):
    """Builds a dict for keywords, returns the original spelling if something is found
    case insensitivly in the given text.

    Returns a (potentially empty) generator with results."""
    d = {w.lower():w for w in keywords}

    # pattern inspired by  Wiktor Stribiżew
    reg = re.compile(rf"\b(?:{'|'.join(d)}\b)", flags=re.I)
    for m in reg.finditer(text):
        yield d[m.group().lower()]

print(list(getWordsFromText('I own a black cat named Sally. And a dOg called Jack.')))
print(list(getWordsFromText('I own a blue whale named Sally.')))

Output:
['Cat', 'Dog']
[]


text:
Q: How to open .bat file in new tab instead of new window in the new Windows Terminal? With the new Windows Terminal (WT), it has a lot of potential being the best terminal on Windows. By modifying the registry for .bat to be opened with WT,
ftype batfile="%LOCALAPPDATA%\Microsoft\WindowsApps\wt.exe" -d . -p "Command Prompt" "%1" %*

it could execute the script on WT. But it has one issue, where executing another .bat file will open another WT window. I would like open the new .bat in new tab, is it possible? From Microsoft's doc, new tab could be opened by,
wt -d . ; new-tab -d C:\ pwsh.exe

but how do I set it to the registry? The code below doesn't seems to work:
ftype batfile="%LOCALAPPDATA%\Microsoft\WindowsApps\wt.exe" -d . new-tab -p "Command Prompt" "%1" %*

A: Have you tried with the ; in the command?
Edit:  Sorry not to be clear.  You dropped the ; from your working example when entering it in the registry.
ftype batfile="%LOCALAPPDATA%\Microsoft\WindowsApps\wt.exe" -d . ; new-tab -p "Command Prompt" "%1" %*


text:
Q: Inserting both Key and value of a multi-dimensional array into mysql table I have an array that looks like this
Array
(
    [0] => Array
        (
            [post_id] => 5410
            [Issue] => 201
            [volume] => 2
            [pages] => 105-9
            [authors] => Onger, M., Jaluth, K.
            [publication_date] => 17 January 2016
            [journals] => Nature Medicine
            [link_to_pubmed] => http://www.ncbi.nlm.nih.gov/pubmed/1
        )
    [1] => Array
        (
            [post_id] => 5411
            [Issue] => 301
            [volume] => 7
            [pages] => 32-9
            [authors] => Onger, M., Jaluth, K.
            [publication_date] => March 30
            [journals] => Lancet
            [link_to_pubmed] => http://www.ncbi.nlm.nih.gov/pubmed/2
        )
        )

I have been cracking my head the whole day trying to figure out how i can insert both the key and the value to get something that looks like this
+---------+---------+-------------------+-----------------------+
| meta_id | post_id | meta_key          | meta_value            |
+---------+---------+-------------------+-----------------------+
|  190143 |    5410 |Issue              | 201                   |
|  190141 |    5410 |volume             | 2                     |
|  190140 |    5410 |pages              | 105-109               |
|  190139 |    5410 |authors            | Onger, M., Jaluth, K. |
|  190144 |    5410 |publication_date   | 17 January 2016       |
|  190136 |    5410 |journals           | Nature Medicine       |
|  190135 |    5410 |link_to_pubmed     |                       |
|         |         |                   |                       |
+---------+---------+-------------------+-----------------------+

The code i have used is very similar as the one described here and can be seen below
    $metadata = implode(', ', array_shift($publications));
foreach($publications as $publication){
    foreach ($publication as $key => $metadata){
        $key = array_keys($publication);
        //$publication[$key];
        }
 $new_metadata[] = "(" . implode(', ', $publication) . ")";

}

how do i get the key and values?

A: If meta_id is an autoincrement field, then
foreach($publications as $publication) {
    // Get post_id and remive it from array
    $post_id = $publication['post_id'];
    unset($publication['post_id']);
    foreach ($publication as $key => $metadata) {
       // Below a query. I only print it, you need to execute it
       echo $query = 'insert into table (post_id, meta_key, meta_value)
                      values ($post_id, "' . $key . '",  "' . $metadata . '")';
        }
}

A: You can't do it with 1 query.
You have to run the loop of the array, and in each line run INSERT mysql.


text:
Q: "$15 for two beers seems a little excessive" or "two beers for $15 seems a little excessive"? Which one is correct?

*

*$15 for two beers seems a little excessive.

*Two beers for $15 seems a little excessive.

The price is supposed to be excessive. It's too pricy.

A: The first one makes more sense. As you say, it's the price that's excessive. The second one could sound as though you think you should have got less beer for your money!

A: They both mean the same thing and no one will notice any difference when you say either.
I'm not sure why people think that the order of X for X has any influence on the intended meaning.  The meaning is always supplied via context not by the order of those words.
For example -

Two horses for $20,000!
Forty thousand dollars for two horses!

Which means which?  Without context we do not know.
If I were relaying this information to someone, I would use my voice to indicate whether I thought this was a good deal or not.
For example consider the italicized text below as being said in a tone that is questioning (my voice rises at the end) and disdainful (I change my tone to something that sounds a bit more disapproving).

Two horses for twenty thousand dollars?

I've let you know that I think $20,000 is too much for two horses.  As long as I keep my questioning, disdainful tone on the money the meaning remains the same even when I switch the clauses.

Twenty thousand dollars for two horses?

If it's a good deal, I will exclaim one or both parts of the sentence.  Consider the italicized text below to be said with excited anticipation.  Maybe I even emphasize the word two, meaning that paying that much for one would be expected but acquiring two at that price is an extraordinary circumstance.

Two Lipizzaners for $20,000?

As long as I maintain the excited, exclamatory tone, switching the order has no effect on the meaning.

Twenty thousand for two Lipizzaners?


text:
Q: How to define piecewise function for joint CDF Suppose I have $X,Y$, which are continuous random variables, with a joint PDF:
$$
f_{X,Y}(x,y)=
\begin{cases}
    24xy & 0 \leq x \text{ and } 0 \leq y \text{ and } x+y \leq 1 \\
    0 & \text{otherwise} \\
\end{cases}
$$
I want to find the joint CDF, which I have calculated to be $6x^2y^2 $. However, I'm not sure how to define the piecewise function for the joint CDF.
I wrote out the CDF below, but I'm not sure if the cases of $x$ and $y$ are correct for all $x,y \in \mathbb{R}$.
$$F_{X,Y}(x,y)=
\begin{cases}
0 & x < 0 \text { or } y < 0\\
6x^2y^2 & 0 \leq x \leq 1 \text{ and } 0 \leq y \leq 1 \text{ and } x+y \leq 1\\
1 & x > 0 \text{ and } y > 0 \text{ and } x+y > 1\\
\end{cases}$$

A: Look at the following drawing:

Thus the CDF is the following:
$$F_{XY}(x,y)=6x^2y^2\mathbb{1}_{(0;1)}(x)\mathbb{1}_{(0;1-x)}(y)+\mathbb{1}_{(0;1)}(x)\mathbb{1}_{(1-x;\infty)}(y)+\mathbb{1}_{(1;\infty)}(x)\mathbb{1}_{(0;\infty)}(y)$$


text:
Q: Global convergence of ray cast against convex object In Gino Van Den Bergen's 2004 paper Ray Casting against General Convex Objects with Application to Continuous Collision Detection, he first presents a naive iterative method to prep his discussion:
Algorithm 1 An iterative method for performing a ray cast of a ray s+λr against
a convex object C. For positive results, this algorithm terminates with λ being the
hit parameter, x, the hit spot, and n, the normal at x.

λ ← 0;
x ← s;
n ← 0;
c ← "the point of C closest to x";
while not "x is close enough to c" do
begin
    n ← x − c;
    if n · r ≥ 0 then return false
    else
    begin
        λ ← λ − (n · n)/(n · r);
        x ← s + λr;
        c ← "the point of C closest to x"
    end
end;
return true

He then states:

The property λi < λi+1 ≤ λhit is a necessary yet not sufficient
  condition for global convergence. In order to show that, in case of a
  hit, xi indeed approaches the hit spot for i → ∞, we need to show that
  the mapping from λi to λi+1 is continuous at all λ<λhit.

However, for real numbers at least, the fact the sequence of λ's is monotonically increasing and bounded above is a sufficient condition for convergence. I am unsure why he needs to prove continuity?

A: If there's a singularity at some point, it might be the case that λi+1 will asymptotically approach it, but will never be able to get past it. With limited-precision numbers it'll just mean that λ will stop increasing.
EDIT: ok I think I came up with an example of how a similar algorithm may fail to converge. Let's imagine our advancement strategy is a bit more cautious: once we find the closest point c, we advance λ halfway towards the point on the ray that's closest to c, i.e. λi+1 = λi - (n·r)/2, and additionally the object is not entirely convex but has a hole:

AB=AC, so there's a singularity at A. Our new algorithm will approach A, but will never reach it and be able to jump to C (since it only moves halfway each time), and yet λ will steadily increase at any point.
EDIT 2: Since A is a singularity point, n·r will actually get to 0 there, so I'm not sure if it ruins the argument:) Perhaps not if we define that exactly at A, C will be chosen as the closest point instead of B


text:
Q: Get Installer Log File Path InstallShield I need to know the InstallShield Log file path which is setup in command line parameters when an install is invoked.
I hope there should be some property setup in installsheild which handles the log file path where msi installation logs are to be written.
I need to handle that in code, so If I get any kind of property which is set to maintain installation log file path, I can use that property through custom action and can use it in my code..
Thanks in Advance
Mohit

A: The property MsiLogFileLocation has this information at run time (once the MSI begins logging) in Windows Installer 4.0 and later, but there are very few reasons to use it directly.
In particular, if you are trying to add a message to the log, you should prefer to use MsiProcessMessage with INSTALLMESSAGE_INFO, one of its wrappers such as the VB Session.Message, or a workaround such as changing a property (if you are trying to log from a ControlEvent DoAction).


text:
Q: Metabox Wordpress plugin Thickbox jQuery error- Uncaught TypeError: Cannot read property 'replace' of undefined I'm using Metabox Plugin in Wordpress that comes with thickbox option in it.
All works fine, except for when trying to create/edit a gallery with the multiple image upload.
When I click on the 'insert gallery' button, nothing happens and I notice in the chrome console:
Uncaught TypeError: Cannot read property 'replace' of undefined

The file contents are as follows
jQuery( function ( $ )
{
    'use strict';

    $( 'body' ).on( 'click', '.rwmb-thickbox-upload', function ()
    {
        var $this = $( this ),
            $holder = $this.siblings( '.rwmb-images' ),
            post_id = $( '#post_ID' ).val(),
            field_id = $this.data( 'field_id' ),
            backup = window.send_to_editor;

        window.send_to_editor = function ( html )
        {
            var $img = $( '
' ).append( html ).find( 'img' ),
                url = $img.attr( 'src' ),
                img_class = $img.attr( 'class' ),
                id = parseInt( img_class.replace( /\D/g, '' ), 10 );

            html = '
';
            html += '';
            html += '
';
            html += '×';
            html += '
';
            html += '<input type="hidden" name="' + field_id + '[]" value="' + id + '">';
            html += '
';

            $holder.append( $( html ) ).removeClass( 'hidden' );

            tb_remove();
            window.send_to_editor = backup;
        };
        tb_show( '', 'media-upload.php?post_id=' + post_id + '&TB_iframe=true' );

        return false;
    } );
} );

and here is the line which gives the error
id = parseInt( img_class.replace( /\D/g, '' ), 10 );

A: This error happens because the html doesn`t have img tag...
Change your code to :
var $img = $( '
' ).append( html ).find( 'i' );
url = $img.attr( 'src' ),
img_class = $img.attr( 'class' ),
id = parseInt( img_class.replace( /\D/g, '' ), 10 );


text:
Q: Algorithm: Picking several items of different weights so that the sum of them remains as close to some value as possible I have 3 folders, each of them contains different number of files.
Folder_#1: audio files with the maximum duration 170 ms.
Folder_#2: audio files with the min duration 170 ms and max duration 460 ms.
Folder_#3: audio files with the minimum duration 460 ms.
Now I need to pick files from three of them so that the sum of their duration would make up 720 ms, or as close as possible to it.
There is a requirement that all audio files from 3 folders should be used.
What is a good algorithm for this?

A: Try brute force, computers are fast:
(this is just pseudocode)
best = float("inf")
res = None
for f1 in Folder_1:
    for f2 in Folder_2:
        for f3 in Folder_3:
            dist = abs(f1.size + f2.size + f3.size - 720)
            if dist < best:
                best = dist
                res = (f1, f2, f3)
return res

If and only if that's not fast enough, try being smart.

A: This can be solved using very simple dynamic programming. Try to allocate an array of 720+170 cells (corresponding to the total combined file duration), then iterate over the files in each folder (in order) and mark the cells which can be reached. If a cell can be reached using the files from all 3 folders, it is a candidate solution. The closest one to 720 wins.


text:
Q: Detect the vein pattern in leaves? My aim is to detect the vein pattern in leaves which characterize various species of plants
I have already done the following:
Original image:

After Adaptive thresholding:

However the veins aren't that clear and get distorted , Is there any way i could get a better output
EDIT:
I tried color thresholding my results are still unsatisfactory i get the following image

Please help

A: The fact that its a JPEG image is going to give the "block" artifacts, which in the example you posted causes most square areas around the veins to have lots of noise, so ideally work on an image that's not been through lossy compression. If that's not possible then try filtering the image to remove some of the noise.
The veins you are wanting to extract have a different colour from the background, leaf and shadow so some sort of colour based threshold might be a good idea. There was a recent S.O. question with some code that might help here.
After that some sort of adaptive normalisation would help increase the contrast before you threshold it.
[edit]
Maybe thresholding isn't an intermediate step that you want to do. I made the following by filtering to remove jpeg artifacts, doing some CMYK channel math (more cyan and black) then applying adaptive equalisation. I'm pretty sure you could then go on to produce (subpixel maybe) edge points using image gradients and non-maxima supression, and maybe use the brightness at each point and the properties of the vein structure (mostly joining at a tangent) to join the points into lines.

A: In the past I made good experiences with the Edge detecting algorithm difference of Gaussian. Which basically works like this:
You blur the image twice with the gaussian blurr algorithm but with differenct blur radii.
Then you calculate the difference between both images.
Pixel with same color beneath each other will creating a same blured color.
Pixel with different colors beneath each other wil reate a gradient which is depending on the blur radius. For bigger radius the gradient will stretch more far. For smaller ones it wont.
So basically this is bandpass filter. If the selected radii are to small a vain vill create 2 "parallel" lines. But since the veins of leaves are small compared with the extends of the Image you mostly find radii, where a vein results in 1 line.
Here I added th processed picture.
Steps I did on this picture:

*

*desaturate (grayscaled)

*difference of Gaussian. Here I blured the first Image with a radius of 10px and the second image with a radius of 2px. The result you can see below.

This is only a quickly created result. I would guess that by optimizing the parametes, you can even get better ones.

A: This sounds like something I did back in college with neural networks. The neural network stuff is a bit hard so I won't go there. Anyways, patterns are perfect candidates for the 2D Fourier transform! Here is a possible scheme:

*

*You have training data and input data

*Your data is represented as a the 2D Fourier transform

*If your database is large you should run PCA on the transform results to convert a 2D spectrogram to a 1D spectrogram

*Compare the hamming distance by testing the spectrum (after PCA) of 1 image with all of the images in your dataset.

You should expect ~70% recognition with such primitive methods as long as the images are of approximately the same rotation. If the images are not of the same rotation.you may have to use SIFT. To get better recognition you will need more intelligent training sets such as a Hidden Markov Model or a neural net. The truth is to getting good results for this kind of problem may be quite a lot of work.
Check out: https://theiszm.wordpress.com/2010/07/20/7-properties-of-the-2d-fourier-transform/


text:
Q: SKScene with bindings in a SpriteView I've created a SpriteKit Scene file and the corresponding SKScene object. That scene object includes an @Binding property.
When I use SpriteView in my SwiftUI file, I can't figure out how to initialize the scene so that it loads from the sks file and also assigns a binding.
I'm wanting something like this:
class MyScene: SKScene {
    @Binding var foo: CGFloat

    init(foo: Binding<CGFloat>) {
      _foo = foo
      super.init(fileNamed: "MyScene")
    }
}

That doesn't work though because init(fileNamed:) is a convenience initializer, not a designated initializer.

A: A possible workaround using ObservableObject to subscribe to foo. I pass a fileName so I have an excuse to invoke my convenience initializer.
class MyScene: SKScene, ObservableObject {
    @Published var foo: CGFloat = 0

    convenience init(fileName: String) {
      self.init(fileNamed: fileName)!
    }
}

And then hold a reference to it on your view (or elsewhere).
struct MyView: View {

    @ObservedObject var scene = MyScene(fileName: "MyScene")

    var body: some View {
        VStack {
            FooView($scene.foo)
            SpriteView(scene: scene)
        }
    }
}


text:
Q: Freemarker not loading remote template I am using Spring MVC, and freemarker as my view resolver, (not that that matters)  I have multiple template loaders defined like this:
    <bean id="urlTemplateLoader" class="com.URLTemplateLoader">
        <property name="baseUrl" value="http://xxxx:8080/ftl/"/>
    </bean>

    <bean id="defaultTemplateLoader" class="com.WebappTemplateLoader">
        <property name="templateLoaderPath" value="/WEB-INF/ftl/" />
    </bean>

    <bean id="multiTemplateLoader" class="freemarker.cache.MultiTemplateLoader">
        <constructor-arg>
          <list>
            <ref bean="urlTemplateLoader"/>
            <ref bean="defaultTemplateLoader"/>
          </list>
        </constructor-arg>
    </bean>

this is designed to check a CMS server first, then use the local file.  The view resolver is defined like this:
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="preTemplateLoaders" ref="multiTemplateLoader"/>
        <property name="freemarkerSettings">
            <props>
                <prop key="default_encoding">UTF-8</prop>
                <prop key="localized_lookup">false</prop>
                <prop key="date_format">yyyy-MM-dd</prop>
                <prop key="template_update_delay">0</prop>
            </props>
        </property>
    </bean>

Now the problem is that if the file is NOT on the remote server when it firsts looks for it,  it never checks again until the server is re-started. I set the template_update_delay to 0, so once it is there, any time I update it, it automatically pulls the new one, which is great, -- but how do I get it to check again if it is not there in the first place?

A: As the JavaDoc of MultiTemplateLoader says:

On every request, loaders are queried in the order of their appearance in the array of loaders provided to the constructor. However, if a request for some template name was already satisfied in the past by one of the loaders, that Loader is queried first (a soft affinity).

I will add a sticky property to it (which enables/disables "soft affinity") in 2.3.24 (expected in early March), but I can't change its default until 3.0.0 or something like that. Meanwhile, you can do that in a custom TemplateLoader (copy-paste the source code of MultiTemplateLoader and just drop the affinity part from it... should be easy).


text:
Q: Modin[dask] on Apple M1 chip I have successfully installed modin[dask] with conda on my Apple M1 chip MacBook Pro, but when I run the code, I got the below errors:

AttributeError: 'NoneType' object has no attribute 'ncores'.

The below is pip list(Python 3.10.4):
dask                          2022.5.0
distributed                   2022.5.0
modin                         0.11.3
pandas                        1.3.4

Thanks for any help.

A: It's hard to diagnose what's going on without seeing what code you ran and exactly how you installed everything.
Here's a blog post about setting up an M1-based Mac with dask:
https://coiled.io/blog/apple-arm64-mambaforge/
The key points are:

*

*start fresh with mambaforge

*conda should be ok if mamba's not an options

*install everything into a fresh environment and everything should come from the conda-forge channel.

mamba create --name=dask-env python=3.9 dask dask-labextension --channel=conda-forge


text:
Q: Prove that there exist infinite number of solutions to an integer equation Prove that there exist infinitely many pairs  $(x,y)$, where $x$ and $y$ are positive integers, such that $(x-y)^7=x^3 y^3$
I've already got the solution in comment, but is there detailed procedure and detailed method to get that solution?

A: Well, here is what I did to get the same answer:
Define the positive integer $d=x-y$. We can rewrite the equation $(x-y)^7=x^3y^3$ as:
$$ d^7 = (d+y)^3y^3 $$
From this we can see that $y$ must be a multiple of $d$ (since the right-hand-side must be a multiple of $d$). So we can write $y=ad$ for some positive integer $a$.  From that we get:
$$ d^7 = (d+ad)^3a^3d^3 $$
Simplifying gives $d=a^3(1+a)^3$. So we can choose $a$ to be any positive integer we like, and then define $d=a^3(1+a)^3$.  The result is the same as your answer.  This also proves that it is the only possible answer.


text:
Q: How to implement a simple Google Checkout callback function with Django? I have a simple 'Buy Now' Google Checkout button on my Django site (very simple; no basket or anything more fancy). What I want is for Google to send a notification to a URL on my server once a new order has been processed. The notification should tell me the customer's email address and name (preferably as simple POST params). Then I can take this info and set up a user account, send out a confirmation email, etc.
This sounds simple. However, all I can find by way of documentation on Google's site is a dense and impenetrable thicket of competing versions, protocols, and APIs with no clear tutorials or example code. It is a nightmare.
Furthermore, I can see no obvious way of testing out the functionality. I continually see references to a 'sandbox', but I can find no concrete information on what this is or how to set it up. The URL 'sandbox.google.com' returns a 503 error.
Can anybody give me a pointer?
Thanks in advance.
Tom

A: Take a look at how Satchmo handles notifications in: payment.modules.google


text:
Q: Playing array of audio in sequence not working even if I have ended function I'm trying to play all my audio files in sequence with the duration between each audio. Right now, I can play the first audio, but I have to click the play button again in order to play the second audio. ended function should handle this, shouldn't it? Appreciate your kindness and help.
var playList = [{
        "duration": 1000,
        "value": "0_silence"
    }, {
        "duration": 4000,
        "value": "1_hello"
    }, {
        "duration": 6000,
        "value": "2_how_old"
    }];

$(document).ready(function() {
  var audioElement = document.createElement('audio');

        var i = 0;
        $("#play").on("click", function(){

            audioElement.addEventListener("ended", playAudio(playList));
                function playAudio() {
                    if(i < playList.length) {
                        audioElement.setAttribute('src', 'sound/' + playList[i].value + '.wav');

                        setTimeout(function (){audioElement.play(); playAudio, playList[i].duration;});

                        i++;
                    } else {
                        i = 0;
                    }
                }
        });

   //         playAudio(playList);
   //         });
   //
   //         function playAudio() {
   //         var audioElement = document.createElement('audio');
   //         audioElement.addEventListener("ended", playAudio(playList));
   //         if (i < playList.length) {
   //
   //         var audioElement = document.createElement('audio');
   //         audioElement.addEventListener("ended", playAudio(playList));

   //         audioElement.setAttribute('src', 'sound/' + playList[i].value + '.wav');
   //         audioElement.play();
   //         setTimeout(playAudio, playList[i].duration);
   //         i++;
   //         } else {
   //         i = 0; // reset i to zero to start over if button clicked again
   //         }
   //         }
}

A: The first error is in this line:
audioElement.addEventListener("ended", playAudio(playList));

Here the function playAudio() is called and the result from it (undefined in this case) is handed to the addEventListener() as argument, which of course won't work. If the playList is global simply change it to:
audioElement.addEventListener("ended", playAudio);  // function is now referenced

In addition, the handler is called every time the play button is clicked. Only add it once when the element is created.
There is also an error in the setTimeout() call, as shown in the post, as it misses a time argument and contains invalid statements inside the function block.
However, it shouldn't be necessary to use this call as calling play() on the element will, in newer browsers, cue up the call. For older browsers you may need to use the canplay event. setTimeout() is not recommended here in either case.
You should also call load() before play() to reset and cleanup the element, and to start loading the new source.
And finally, if the intention is to play the list in a loop the list will fail when last track has been played as i is reset in a separate else-block which does not invoke play.
You might want to consider how the play button behaves in order to prevent it from loading samples while playing (ie. toggle pause/play). I wrapped up the fixes above except from the play-button (I rewired it to share the playAudio() function) here using random short samples:

var playList = [{
  "duration": 1000,
  "value": "http://sampleswap.org/samples-ghost/SFX%20and%20UNUSUAL%20SOUNDS/ELECTRO%20and%20SYNTHETIC/257[kb]50s_space_telemetry.aif.mp3"
}, {
  "duration": 4000,
  "value": "http://sampleswap.org/samples-ghost/SFX%20and%20UNUSUAL%20SOUNDS/ELECTRO%20and%20SYNTHETIC/85[kb]analog_alarm_up.aif.mp3"
}, {
  "duration": 6000,
  "value": "http://sampleswap.org/samples-ghost/SFX%20and%20UNUSUAL%20SOUNDS/ELECTRO%20and%20SYNTHETIC/42[kb]alien_alarm.aif.mp3"
}];

$(document).ready(function() {
  var audioElement = document.createElement('audio');

  // reference function instead of calling it. Also, only set it once.
  audioElement.addEventListener("ended", playAudio);

  var i = 0;
  $("#play").on("click", playAudio); // rewired to share playAudio()

  function playAudio() {
    var entry = playList[i++];       // get current entry, increment i
    if (i >= playList.length) i = 0; // if i=> length, reset

    audioElement.src = entry.value;  // <- for demo samples only. 'sound/' + entry.value + '.wav';
    audioElement.load();             // cleanup old fun, invoke loading of new
    audioElement.play();             // cue up play
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id=play>Play</button>


text:
Q: PowerShell file comparison across multiple servers I'm new to PowerShell so forgive the noob question.  I'm trying to compare a directory across multiple servers to make sure they are in synch.  I'm reading the servers from a servers.txt file and setting the first server in the list as the source server.
# sets the source server as the FIRST server in the list
$sourceSRV = (Get-Content ./servers.txt -totalcount 1)
$servers = Get-Content ./servers.txt

#Variables for code directories
$code_src01 = Get-ChildItem -Recurse -path "E$\appdirectory"

Foreach ($server in $servers) {
    Compare-Object -ReferenceObject $sourceSRV$code_src01 -
DifferenceObject $server$code_src01
}

I'm running into the issue on the Compare-Object call, I'm not sure what to pass as the -ReferenceObject and -DifferenceObject properties.  I want the ReferenceObject to be the path of the sourceserver and the file path so (server1\e$\appdirectory) and the -DifferenceObject to the the other servers in the list (server2\e$\appdirectory, server3\e$\appdirectory)

A: You were very close, but your comparison is wrong:
$ServerList = Get-Content -Path .\servers.txt
$Reference = (Get-ChildItem -Path "\\$($ServerList[0])\E$\appdirectory" -Recurse).FullName.Replace("\\$($ServerList[0])",'')

ForEach ($Server in $ServerList)
{
    $CompareArgs = @{
        ReferenceObject = $Reference
        DifferenceObject = (Get-ChildItem -Path "\\$Server\E$\appdirectory" -Recurse).FullName.Replace("\\$Server",'')
    }
    Compare-Object @CompareArgs
}

To go further, I'd actually utilize Get-FileHash on the reference server's file list with the rest of the distribution, but that's outside the scope of my answer.


text:
Q: Targeting multiple buttons and get different value by clicking different button I want to target multiple buttons and get different value by clicking different button.
Suppose there are 3 buttons: "button01", "button02, "button03".
This is my code:
var targetArr:Array = ["button01","button02","button03"];
for (var i:int = 0; i < targetArr.length; i++)
{
    var target = getChildByName(targetArr[i]);
    target.addEventListener(MouseEvent.CLICK, targetFunc);
    function targetFunc(event:MouseEvent):void
    {
        trace(i);
    }
}

Instead of getting different value by clicking different button, I constantly get "3" as the value.
I want: clicking "button01" will get "0" as the value, clicking "button02" will get "1" as the value, and clicking "button03" will get "2" as the value. How to do it?

A: You are almost there! What is happening is that the reference to i is being shared by all of  your event handlers. What you want is a distinctive copy of the value of i when the event handler is registered.
To do this, you can create a new closure for each iteration of your loop.
var targetArr:Array = ["button01","button02","button03"];
for (var i:int = 0; i < targetArr.length; i++)
{
    var target = getChildByName(targetArr[i]);
    target.addEventListener(MouseEvent.CLICK, getTargetFunc(i));
    function getTargetFunc(value:Number):Function {
        return function(event:MouseEvent):void {
            trace(value);
        }
    }
}

What is happening now is that we are passing the particular value of i to a helper function that then returns the event handler function. This way we are using a closure to close over the particular value of i at the time we register the handler.
EDIT: Here is another slightly different way of arranging things. For each iteration of your loop, you could call a function that registers the handler:
addHandler(i);
function addHandler(value:Number):void {
    target.addEventListener(MouseEvent.CLICK, targetFunc);
    function targetFunc(event:MouseEvent):void
    {
        trace(value);
    }
}


text:
Q: C# application crashes before start I come to you because I'm desperate. I've developed a GTK# application in C# with the latest MonoDevelop. It's built for .NET framework 4.0 / x86, and the only external library it uses is the official Mysql .Net connector. It's meant to run under Windows XP.
It's the first application I make with this IDE. I was very happy with the results and the development time, but the deployment is a real headache.
It works perfectly on the development machine. The debug is clean. Everything's okay.
Then, as I couldn't find any information about the deployment, I installed a clean XP to try it and see what do I should install on the client's machine.
I've installed the SP3, .NET 4.0 and copied the release package with all the DLLs mentioned in the build log (that made it work outside the MonoDevelop in the development machine). But I'm getting a "the application has encountered a problem and needs to close" error, with no exception, in kernel32.dll, offset 0012aeb.
I've tried to install the .NET 3.5 before the 4.0, updated IE (just in case...), copied more GTK# and Monodevelop DLLs to the exe's folder, installed the Mysql .NET connector, installed Mono 2.8... But nothing. Still getting that unexplained error.
Google and StackOverflow searches didn't help me. I've researched and tried a lot of things in the last twelve hours or more without moving from this machine.
Do you have any advice? What can be causing it? Is there any way to debug the exe (without installing VS...)? Does anyone know what are all the dependencies of this kind of executable?

A: WinDbg can help you figuring some JIT trouble...
Even though it aint intuitive and require skills, Worth a try. might pop something up.

A: If it's meant to run under Windows, then you should probably compile it with the Visual C# compiler.
However, more related to your problem - get a debugger in your deployment machine and run the application on it. This is the best way to figure out the problem because we really can't guess it.
Mono Application Deployment Guidelines

A: There are several options to installing Visual Studio on your production machine, one of them is the Remote Debugging Monitor. It does not require a Visual Studio installation. You can copy the files from your development machine to your server. I've got them under C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Remote Debugger.
You can also use it for Remote Debugging of a Project Built Locally.


text:
Q: How can I check whether my Perl installation is 32 or 64 bit? On Windows, how can I check whether my Perl installation is 32 or 64 bit?

A: log(~0 +1)/log(2) works because :

*

*~0 is "bitwise not zero" -> UINT_MAX

*UINT_MAX is either 2^32-1 or 2^64-1, depending on the architecture (or compile options)

*log(2^32)/log(2) = 32 and log(2^64)/log(2) = 64, by design.

So basically this command order perl to say how many bits have its UINT_MAX.
$ perl -e "print log(~0 +1)/log(2)"
32
 $ perl -V:archname
archname='MSWin32-x86-multi-thread';

A: If you want to check if it uses 32-bit integers or 64-bit integers, use the following:
perl -V:ivsize      # use Config; say $Config{ivsize}

*

*If the returned value is 4, your Perl uses 32-bit integers.

*If the returned value is 8, your Perl uses 64-bit integers.

See also: Answer to "What is the perl equivalent of MAX_INT?"

If you want to check if it uses 32-bit pointers or 64-bit pointers, use the following:
perl -V:ptrsize     # use Config; say $Config{ptrsize}

*

*If the returned value is 4, your Perl can address 4 GiB of RAM.

*If the returned value is 8, your Perl can address "unlimited" RAM.

If you want to check if it's a 32-bit program or a 64-bit program, use the following:
perl -V:archname    # use Config; say $Config{archname}

*

*If the returned value includes x86_64, it's a 64-bit process.

*If the returned value includes x86 (but not x86_64), it's a 32-bit process.

This value is also included in the output of perl -v.

Note: You shouldn't be checking use64bitint or use64bitall as these indicate what parameters were passed to Configure rather than provide information about what is actually being used.

A: I'm reading the question to ask if Perl is compiled 64 bit, not if Windows or the CPU is.
Perl can be configured to use varying degrees of 64 bit-ness.  You can look this up using the Config module.
To check if Perl is compiled to use 64 bit integers, you can look at the use64bitint entry in Config.
use Config;
print $Config{use64bitint};

define indicates yes.
There is also...

*

*use64bitall meaning perl will be compiled to use all the 64 bit-ness it can, including 64 bit pointers allowing you to access more than 2 gigs of memory.

*ivsize indicating how many bytes Perl will use to store an integer, 8 indicates 64 bit.

*ptrsize is how many bits Perl will use to store pointers which allows you to use more than 2 gigs of memory per process, 8 indicates 64 bit.

Common Config variables and their values can be seen in perl -V (note the capital V).  Their definitions can be found with perldoc Config.
Note, you can compile Perl to use 64 bit integers regardless of whether your operating system or CPU is 32 or 64 bit.  On a 32 bit CPU, Perl will use a type other than "integer" to store numbers, probably "long integer".

A: Just check the version/build:
perl -v

And I got:
This is perl, v5.8.8 built for msys-64int

Copyright 1987-2006, Larry Wall

...

A: Just use
log(~0 +1)/log(2)

....


text:
Q: Kernel Oops on a QNAP TS-639 from a custom module I have run into a very weird scenario, I am writing a custom kernel module for my QNAP 639 Pro.
The module was successfully running under the same kernel version in Ubuntu 12.04:

Linux ubuntu 3.4.6-030406-generic #201207191609 SMP i686 i686 i386
  GNU/Linux

However after many hours of compilation on my qnap, i get a kernel oops with a pointer dereference, here is a dmesg dump:
[ 1491.062409] Got pinode dentry
[ 1491.062434] BUG: unable to handle kernel NULL pointer dereference at   (null)
[ 1491.063351] IP: [<c0605e48>] memcpy+0x18/0x2c
[ 1491.063351] *pde = 00000000
[ 1491.063351] Oops: 0000 [#1] SMP
[ 1491.063351] Modules linked in: nocansee(O+) iscsi_tcp(O) libiscsi_tcp(O) libiscsi(O) scsi_transport_iscsi(O) fbdisk(O) bridge stp ipv6 8021q uvcvideo videobuf2_vmalloc videobuf2_memops videobuf2_core v4l2_common videodev v4l2_int_device snd_usb_caiaq snd_usb_audio hid_logitech snd_usbmidi_lib snd_hwdep snd_seq_midi snd_rawmidi fnotify(PO) xhci_hcd udf isofs ufsd(PO) jnl(O) e1000e(O) usblp iTCO_wdt iTCO_vendor_support rtcmod(O) usbhid cryptodev(O) hal_netlink(O) usb_storage uhci_hcd ehci_hcd usbcore usb_common mv_sata(O) [last unloaded: nocansee]
[ 1491.063351]
[ 1491.063351] Pid: 17279, comm: insmod Tainted: P           O 3.4.6 #1 ICP / iEi ATOM NAS /ATOM NAS (QE05)
[ 1491.063351] EIP: 0060:[<c0605e48>] EFLAGS: 00210286 CPU: 0
[ 1491.063351] EIP is at memcpy+0x18/0x2c
[ 1491.063351] EAX: 0000001a EBX: f8e60978 ECX: 0000001a EDX: 00000068
[ 1491.063351] ESI: 00000000 EDI: f8e60978 EBP: d38a7e64 ESP: d38a7e50
[ 1491.063351]  DS: 007b ES: 007b FS: 00d8 GS: 00e0 SS: 0068
[ 1491.063351] CR0: 8005003b CR2: 00000000 CR3: 35ecd000 CR4: 000007c0
[ 1491.063351] DR0: 00000000 DR1: 00000000 DR2: 00000000 DR3: 00000000
[ 1491.063351] DR6: ffff0ff0 DR7: 00000400
[ 1491.063351] Process insmod (pid: 17279, ti=d38a6000 task=f651c000 task.ti=d38a6000)
[ 1491.063351] Stack:
[ 1491.063351]  d38a7e64 c042588f 00000000 00000013 f8e604b4 d38a7e7c f8e60324 f8e603fd
[ 1491.063351]  d7e39850 d5809400 f8e5daf8 d38a7e8c f8e62060 f8e608a8 00000000 d38a7ea8
[ 1491.063351]  c0401151 f8e62000 00000000 f8e5daf8 00000013 f8e604b4 d38a7fac c04598a6
[ 1491.063351] Call Trace:
[ 1491.063351]  [<c042588f>] ? printk+0x15/0x17
[ 1491.063351]  [<f8e60324>] hook_proc+0x4f/0x65 [nocansee]
[ 1491.063351]  [<f8e62060>] module_init_proc+0x60/0x7a [nocansee]
[ 1491.063351]  [<c0401151>] do_one_initcall+0x71/0x113
[ 1491.063351]  [<f8e62000>] ? 0xf8e61fff
[ 1491.063351]  [<c04598a6>] sys_init_module+0x1060/0x128e
[ 1491.063351]  [<c0422251>] ? kmap_atomic_prot+0x23/0x9c
[ 1491.063351]  [<c0863b64>] syscall_call+0x7/0xb
[ 1491.063351] Code: 08 89 73 50 89 73 54 c6 43 4c 04 88 43 4d 5b 5e 5f 5d c3 55 89 e5 57 56 89 d6 53 89 c3 89 c8 89 ca c1 e8 02 83 ec 08 89 c1 89 df <f3> a5 89 d1 83 e1 03 74 02 f3 a4 5a 89 d8 59 5b 5e 5f 5d c3 55
[ 1491.063351] EIP: [<c0605e48>] memcpy+0x18/0x2c SS:ESP 0068:d38a7e50
[ 1491.063351] CR2: 0000000000000000
[ 1491.314433] ---[ end trace 97a00886892de9ee ]---

The QNAP is running

Linux 3.4.6 #1 SMP i686 unknown.

This is the mod info:
$ modinfo nocansee.ko
filename:       nocansee.ko
license:        GPL
depends:
vermagic:       3.4.6 SMP mod_unload ATOM
parm:           rc_name:charp
parm:           rc_dir:charp
parm:           mod_name:charp
parm:           mod_dir:charp

This is the relevant part of the source code, which causes the Oops:
struct path p;
if(kern_path("/myfolder", 0, &p))
    return;
pinode = p.dentry->d_inode;

if(!pinode)
    return;
printk(KERN_DEBUG "Got pinode dentry");
// hook folder
proc_fops = *pinode->i_fop; //Line which causes kernel Oops
proc_original = pinode->i_fop;
proc_fops.readdir = do_readdir_proc;
pinode->i_fop = &proc_fops;

Any help would be most welcome! thank you very much!

A: You got an inode with NULL file_operations. Just add check before the line where you dereference the pointer to the file_operations:
if (!pinode->i_fop)
    return;
proc_fops = *pinode->i_fop;


text:
Q: Faster way of obtaining a property from an element contained in a dictionary of dynamics? Right now I have this interface called IMessageConfiguration<T> that implements a property called Label (of type byte). I have a map of labels to their relative message configurations in the following structure:
Dictionary<byte, dynamic> configurationMap = new Dictionary<byte, dynamic>();
Now, although the dictionary is dynamic I am only filling it with either IMessageConfiguration<double> or IMessageConfiguration<uint>. Regardless of which type is at each dictionary entry, the entry will have the property Label because all entries will ultimately have the IMessageConfiguration<T> base type. I do however understand that the compiler will have no knowledge of this.
I am writing a routine to go through the dictionary and obtain the Label property for each of the IMessageConfiguration<T> entries. Here is my current attempt at doing this:
public IList<byte> GetLabels()
{
    IList<byte> labels = new List<byte>();

    // obtain all of the labels
    foreach (var configuration in this.configurationMap)
    {
        if (configuration.Value is IMessageConfiguration<double>)
        {
            labels.Add((configuration.Value as IMessageConfiguration<double>).Label);
        }
        else if (configuration.Value is IMessageConfiguration<uint>)
        {
            labels.Add((configuration.Value as IMessageConfiguration<uint>).Label);
        }
    }

    return labels;
}

Is there a way to more cleanly obtain all of the Label properties for each of the message configurations?
As asked in the comments, here is the full definition for the IMessageConfiguration<T> interface.
public interface IMessageConfiguration<T>
{
    string Description { get; }
    byte Label { get; }
    ushort LSB { get; }
    ushort MSB { get; }
    double Resolution { get; }
    int SignBit { get; }
    string Title { get; }
    string Units { get; }
    uint Encode(T data);
    T Decode(uint message);
}

A: I'd say that you should avoid dynamic whenever possible. In your case you can put all non-T related properties to parent interface:
public interface IMessageConfiguration
{
    string Description { get; }
    byte Label { get; }
    ushort LSB { get; }
    ushort MSB { get; }
    double Resolution { get; }
    int SignBit { get; }
    string Title { get; }
    string Units { get; }
}

public interface IMessageConfiguration<T> : IMessageConfiguration {
    uint Encode(T data);
    T Decode(uint message);
}

And use Dictionary<byte, IMessageConfiguration> instead. Even if you insist on using dynamic for some reason - you can do yourDict.OfType<IMessageConfiguration>().Select(c => c.Label).ToList() to get those labels.


text:
Q: Telegram account needs to be confirmed every time when using Telethon I have some troubles with my client app in telegram. When I run my code, I have to confirm my account everytime (in the telegram itself, I need to enter the phone number and the code that came to the mail). The most interesting moment, that my code doesn't contain anything criminal. Just for testing
import asyncio
import configparser

from telethon.sync import TelegramClient

config = configparser.ConfigParser()
config.read("config.ini")

api_id = config['Telegram']['api_id']
api_hash = config['Telegram']['api_hash']
username = config['Telegram']['username']

client = TelegramClient(username, api_id, api_hash)

client.start()

async def main():
    await asyncio.sleep(3)

with client:
    client.loop.run_until_complete(main())

Month ago, everything was working fine. Then I was doing a small chat scraper for checking swear words. I would like to know, why such a problem has appeared now

A: Make sure the script is not terminating abruptly. If it is, the library won't have a chance to properly save the information. I would also recommend checking the active sessions from a different client, to learn whether Telethon's session is somehow "disappearing" on its own. And lastly, logging.DEBUG logs may have some hints.


text:
Q: Remove item from Array, with item that doesn't provide equality How would I remove an item from an array, provided that it does not have equality?
For example, for an item with equality, I could do the following:
Array.filter (fun x -> x <> itemToRemove) array

Unfortunately, that does not work since in my case, I have a tuple in which the third item is a curried function (to which I provide the last argument later), and this does not have equality.
EDIT:
Here is the exact example I am having problems with:
let arrayWithoutReq = Array.filter (fun (req:(string * Port<'a> * ('a -> bool) option * int * DateTime)) -> req <> fullfilableReq) (originalFifoRequests.toArray())

A: Since you are talking about identity comparison, use the build in reference comparison
let arrayWithoutReq =
    originalFifoRequests
    |> Seq.filter (fun req ->
           Object.ReferenceEquals(req, fullfilableReq) |> not)
    |> Seq.toArry


text:
Q: Parse: Merge existing user with facebook account I have registered as normal signup with email test@test.com. Later I'm trying to login with Facebook with same email id test@test.com. This is creating new user in Parse.
How should I merge this Facebook User to the old account that have same email?

A: Merging is probably going to be very difficult, because the 2 accounts have different login mechanisms. You would either need to delete one account and update all references to that user in the database or create your own 'user group' class so each user is associated with a group and that group represents the user. A group can have many users attached (the many logins for the individual e-mail address) and is used in all relationships where you would usually use the user.


text:
Q: Calling method of object created in embedded block on click I am beginner in ASP.NET and after lot of searching I've decided to ask you guys.
So, I have object created in embedded block in my Page.aspx in following way:
<% Invoice invoice = InvoiceGateway.get(1); %>

Implementation of these is in different files Invoice.cs and InvoiceGateway.cs
I am using it to fill webelements right where I need it in this way:

<%= invoice.getCreator().getAddress() %>

But now I've started to create buttons and I am trying to call method of this object when I click the button e.g.
<a class="btn btn-danger" runat="server" onServerClick="<% invoice.delete() %>">
     delete

I know this is not correct, its just for illustration of what I am trying to achieve.
I am not sure how (or even if) I can do that. I know I can define some function in .aspx.cs page and call it onServerClick, or just redirect to Page.aspx?delete={id} and perform something on load.
My question is... Is there a way how to call method of such created object, after I click some hyperlink/button/etc? I've come up with some alternatives, but nothing that would use this already created object and its method.


text:
Q: How to disable auto focus (select) nb-select first option? When open nb-option-list first option is selected (or focused). I must be disable this function

A: In HTML5 you can select a disabled option
<option selected disabled>Selected and disabled</option>

Or you can add a hidden option in first position
<option hidden>First item</option>


text:
Q: Don't work Rewrite Rule Apache I need to create apache rewrite url :
Replace " ' " and " " symbols with dash
Replace .aspx with .html
For example
/forum/category/category name 1/category name 2/category name with '/.../{category name N}.aspx

to
/category_name_1/category_name_2/category_name_with__/.../{category_name_N}.html

I have created rule :
RewriteCond %{THE_REQUEST} (.*)[\'\ ](.*)
RewriteRule (.*)[\'\ ](.*) $1-$2 [N]

RewriteCond %{THE_REQUEST} (.*)\.aspx
RewriteRule ^forum/category/(.*)\.aspx$  index.php/$1.html [L]

This code is looped . I don't understand why.
Help me please

A: Try:
RewriteRule (.*)[\'\ ](.*) /$1-$2 [L,R]
RewriteRule ^forum/category/(.*)\.aspx$  /index.php/$1.html [L,R]

Without the conditions (since they don't change) and using the R flag.


text:
Q: How to get all values of a repeated property in a query with a projection on GAE I have a ndb model which has a ComputedProperty that lists multiple values.
sku_name = ndb.ComputedProperty(lambda self: makekeys(self.sku, self.name), indexed=True, repeated=True)

makekeys creates a list of the two parameters, so nothing special.
doing the following:
query = cls.query()
data = query.fetch(projection=[Pricelist.sku_name])
for d in data:
    logging.info(d.sku_name)

gets only the first value in d.sku_name and not all values of the list of the ComputedProperty.
# result with projection
[u'0300022']

Doing the same without the projection all values of sku_name are available as a list.
# result without projection but the full data record
[u'0300022', u'sbrpgznplus100']

What am I doing wrong?

A: From the docs https://cloud.google.com/appengine/docs/standard/python/ndb/projectionqueries:

Projecting a property with multiple values will not populate all
  values for that property. Instead, a separate entity will be returned
  for each unique combination of projected values matching the query.