text:
Q: Single producer, multiple parallel consumers implemented with boost fibers I'm trying to write a single producer, multiple consumer pipeline, where the consumers run in parallel threads. Or to find or share a simple example of that sort. With relatively easy code in Go, the output clearly shows the consumers work in parallel. I thought it might be similar with Boost 1.73 fibers, but I can't get beyond this code which (unsurprisingly) works sequentially:
#include <boost/fiber/buffered_channel.hpp>
#include <boost/fiber/fiber.hpp>

static void process(int item) {
    std::cout << "consumer processing " << item << std::endl;
    auto wasteOfTime = 0.;
    for (auto s = 0.; s < item; s += 1e-7) {
        wasteOfTime += sin(s);
    }
    if (wasteOfTime != 42) {
        std::cout << "consumer processed " << item << std::endl;
    }
}

static const std::uint32_t workers = 3;

int main() {
    boost::fibers::buffered_channel<int> channel { 2 };

    boost::fibers::fiber consumer[workers];
    for (int i = 0; i < workers; ++i) {
        consumer[i] = boost::fibers::fiber([&channel]() {
            for (auto item : channel) {
                process(item);
            }
        });
    }

    auto producer = boost::fibers::fiber([&channel]() {
        std::cout << "producer starting" << std::endl;
        channel.push(1);
        channel.push(2);
        channel.push(3);
        channel.close();
        std::cout << "producer ending" << std::endl;
    });

    producer.join();
    for (int i = 0; i < workers; ++i) {
        consumer[i].join();
    }
    return 0;
}

I tried to insert many variations of code fragments to get worker threads to schedule the fibers, but they always execute sequentially or not at all. The code from a question about the inverse problem seems a step in the right direction, though much more complicated than Go, but (when compiled with -DM_1_PI=3.14) that program also just sits idle for me.

A: Turns out I misinterpreted boost's code fragment for scheduling fibers. It does seem to work for me like this:
#include <boost/fiber/barrier.hpp>
#include <boost/fiber/buffered_channel.hpp>
#include <boost/fiber/fiber.hpp>
#include <boost/fiber/operations.hpp>
#include <boost/fiber/algo/work_stealing.hpp>
#include <optional>

static void process(int item) {
    std::cout << "processing " << item << std::endl;
    auto wasteOfTime = 0.;
    for (auto s = 0.; s < 1; s += 3e-9) {
        wasteOfTime += sin(s);
    }
    if (wasteOfTime != 42) {
        std::cout << "processed " << item << std::endl;
    }
}

static const std::uint32_t N_CONSUMING_FIBERS = 3;

void task() {
    boost::fibers::buffered_channel<int> channel{ 2 };

    boost::fibers::fiber fibers[1 + N_CONSUMING_FIBERS];
    fibers[0] = boost::fibers::fiber([&channel]() {
        std::cout << "producer starting" << std::endl;
        channel.push(1);
        channel.push(2);
        channel.push(3);
        channel.push(4);
        channel.push(5);
        channel.close();
        std::cout << "producer ending" << std::endl;
        });

    auto start = boost::fibers::barrier(N_CONSUMING_FIBERS);
    for (int i = 1; i <= N_CONSUMING_FIBERS; ++i) {
        fibers[i] = boost::fibers::fiber([&start, &channel]() {
            start.wait();
            for (auto item : channel) {
                process(item);
            }
            });
    }

    for (int i = 0; i <= N_CONSUMING_FIBERS; ++i) {
        fibers[i].join();
    }
}

class FiberExecutor {
    static std::vector<std::thread > extra_threads;
    static std::optional<boost::fibers::barrier> barrier;

public:
    static void init() {
        auto const N_THREADS = std::thread::hardware_concurrency();
        barrier.emplace(N_THREADS);
        extra_threads.reserve(N_THREADS - 1);
        for (auto i = decltype(N_THREADS){0}; i < N_THREADS - 1; ++i) {
            extra_threads.emplace_back([N_THREADS]() {
                boost::fibers::use_scheduling_algorithm<boost::fibers::algo::work_stealing>(N_THREADS);
                barrier->wait(); // start only after everyone has scheduled
                barrier->wait(); // end after main thread says to
                });
        }
        boost::fibers::use_scheduling_algorithm<boost::fibers::algo::work_stealing>(N_THREADS);
        barrier->wait(); // start only after everyone has scheduled
    }

    static void exit() {
        barrier->wait();
        for (auto& thread : extra_threads) {
            thread.join();
        }
    }
};

std::vector<std::thread> FiberExecutor::extra_threads;
std::optional<boost::fibers::barrier> FiberExecutor::barrier;

int Main() {
    FiberExecutor::init();

    std::cout << "Going once\n";
    task();
    std::cout << "Going twice\n";
    task();

    FiberExecutor::exit();
    return 0;
}

Beware that this might not be correct. It also does not schedule reliable onto all threads (at least on Windows).
It is in fact pretty much the same as the code in a question about the inverse problem, but that needed an update. Also, I find that using a condition variable instead of barriers isn't reliable, because the main thread may run ahead of the other threads.
I didn't model the initialization and cleanup as a class, to avoid the illusion you could instantiate it multiple times (in sequence or in parallel). work_stealing's constructor uses global variables. You cannot end the fiber-based task cleanly, and then start another fiber-based task, not even if coding everything in temporary threads and not tainting the main thread in any way.


text:
Q: Background color and GTK Look and Feel I'm having troubles setting the background color for JButtons.
For example I get this when I do button.setBackground(Color.ORANGE)

But when I disable the GTK Look and Feel it's ok.
Another way to set the background?
Thanks.

A: GTK Look and Feel defines its own way to visually present the button, so when you use "button.setBackground(Color.ORANGE)" it only changes button underlying background and then the GTK Look and Feel draws its own (gray) representation of the button atop of the background.
In case you want a simple orange-colored button you can change button's UI for your own one, for example:
public static void main ( String[] args )
{
    JButton orangeButton = new JButton ( "X" );
    orangeButton.setUI ( new MyButtonUI ());
}

private static class MyButtonUI extends BasicButtonUI
{
    public void paint ( Graphics g, JComponent c )
    {
        JButton myButton = ( JButton ) c;
        ButtonModel buttonModel = myButton.getModel ();

        if ( buttonModel.isPressed () || buttonModel.isSelected () )
        {
            g.setColor ( Color.GRAY );
        }
        else
        {
            g.setColor ( Color.ORANGE );
        }
        g.fillRect ( 0, 0, c.getWidth (), c.getHeight () );

        super.paint ( g, c );
    }
}

This code sample will create a button that is gray on press and orange when its not pessed.
Ofcourse you can style the painting as you like and change the button view.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Code block spacing within an html list item I am nesting code in an ordered list as a set of instructions for some teammates. However, when I nest a code block within a list item, the spacing is totally off. The code in my code block starts halfway through width of the page. Here is some sample code:

Test

 This is a test list item.

            def my_function(a):
                return a

Element 2

A: It's because you're indenting the code in the markup, try this

 This is a test list item.

 def my_function(a):
   return a

Element 2


text:
Q: Group by multiple columns as if it was one column Is there a way to group by multiple columns as if the columns were united in C# using Linq?
Let's say I have an object that represents a message sent from one user to another:
public class Message
{
    public Int32 SenderId { get; set; }
    public Int32 RecipientId { get; set; }
    public String Text { get; set; }
    public DateTime SentAt { get; set; }
}

I get a set of these from repository and then I have to order them by sent date and filter out by pair SenderId, RecipientId. But I want to get back only the very last message from a given dialog between two users. The direction doesn't matter, so
(SenderId == 1 && RecipientId == 2)

should be treated as
(SenderId == 2 && RecipientId == 1)

So far I got this:
Messages
    .GroupBy(m => new { m.SenderId, m.RecipientId })
    .Select(gm => gm.OrderByDescending(m => m.SentAt).FirstOrDefault());

But the problem with this approach is when I have a message sent from user 1 to user 2 and vice versa 2 => 1, both will be returned. Because Key (1,2) isn't the same as (2,1).
Any suggestions would be great. Thank you!
UPD: I should've added that I'm using the expression with IQueryable expression. So it's LINQ to Entity.

A: Even though you tagged your question entity-framework, not everyone seemed to understand that many in-memory solutions fail because they don't have a SQL equivalent. Here's a query that will translate into SQL for many different IQueryable implementations and query providers:
Messages
    .GroupBy(m => new
    {
        MinId = m.SenderId <= m.RecipientId ? m.SenderId : m.RecipientId,
        MaxId = m.SenderId > m.RecipientId ? m.SenderId : m.RecipientId
    })
    .Select(gm => gm.OrderByDescending(m => m.SentAt).FirstOrDefault());

Using Math.Min / Math.Max will only work in Entity Framework core 2, because this is the only EF version that auto-switches to client-side evaluation for any part of the query that doesn't translate into SQL. This was abandoned in EF core 3. EF core 3 only applies client-side evaluation in the final projection (Select), if necessary. So the GroupBy will fail in EF core 3, which you're going to use sooner or later.
However, I have to warn you that currently, this won't work in EF core 3, because they don't support GroupBy fully yet. But I'm sure that's a matter of time.

A: GroupBy accepts a custom equality comparer. You could implement your specific matching logic there like so:
class MessageComparer : IEqualityComparer<Message>
{
    public bool Equals(Message x, Message y)
    {
        return (x.SenderId == y.SenderId || x.SenderId == y.RecipientId)
        && (x.RecipientId == y.RecipientId || x.RecipientId == y.SenderId); // i guess you can go as specific as you like here, depending on your requirements
    }

    public int GetHashCode(Message obj)
    {
        return (obj.SenderId ^ obj.RecipientId).GetHashCode();
    }
}

in your calling method, do something like so, with a custom comparer:
    Messages.GroupBy(m => m, new MessageComparer())
    .Select(gm => gm.OrderByDescending(m => m.SentAt).FirstOrDefault());
UPD: using LINQ to Entities will change the solution quite a bit then. You are right, custom functions and equality comparers will not be supported by EF as it needs to translate this to SQL somehow (even if you manage to do it, your query performance will likely take a nosedive due to lack of functional indexes). I see a couple of avenues to explore:

*

*select all messages for both users with no grouping and apply grouping in C# (where you've got your custom comparers and can do pretty much anything like so: Messages.Select(gm => gm.OrderByDescending(m => m.SentAt).ToList(/*DB call happens here */).GroupBy(m => m, new MessageComparer()).FirstOrDefault() - this however potentially fetches a lot of data from the DB so you will need to consider filtering

*change your database schema to introduce a SequenceNumber column that will be shared between sender and recipient and you can use that in SQL will all indexes you like

*write a stored proc that does some sort of trickery on your two columns and gives you desired output (for example you could sort two integers and concatenate them to produce one value that you then rely on).

A: Since both Id's are integers, you can order them in your group by:
Messages
    .GroupBy(m => new { Math.Min(m.SenderId, m.RecipientId), Math.Max(m.SenderId, m.RecipientId)})
    .Select(gm => gm.OrderByDescending(m => m.SentAt).FirstOrDefault());


text:
Q: Reading static files from public folder in play framework in production I'm trying to make a route to a specific static file.
It is working when running in local but when I run it using docker I'm getting an error.
The file is present at:
public/robots.txt

I am accessing it using:
http://localhost:9000/robots.txt

Expectation - It should have no error and load properly.
The error I get:
[error] a.a.OneForOneStrategy - null
java.lang.NullPointerException: null
    at kamon.instrumentation.akka.instrumentations.akka_26.InstrumentNewExecutorServiceOnAkka26$.around(DispatcherInstrumentation.scala:109)
    at akka.dispatch.ThreadPoolConfig$ThreadPoolExecutorServiceFactory.createExecutorService(ThreadPoolBuilder.scala)
    at akka.dispatch.Dispatcher$LazyExecutorServiceDelegate.executor$lzycompute(Dispatcher.scala:44)
    at akka.dispatch.Dispatcher$LazyExecutorServiceDelegate.executor(Dispatcher.scala:44)
    at akka.dispatch.ExecutorServiceDelegate.execute(ThreadPoolBuilder.scala:219)
    at akka.dispatch.ExecutorServiceDelegate.execute$(ThreadPoolBuilder.scala:219)
    at akka.dispatch.Dispatcher$LazyExecutorServiceDelegate.execute(Dispatcher.scala:43)
    at akka.dispatch.Dispatcher.registerForExecution(Dispatcher.scala:127)
    at akka.dispatch.MessageDispatcher.attach(AbstractDispatcher.scala:152)
    at akka.actor.dungeon.Dispatch.start(Dispatch.scala:121)
[error] p.c.s.n.PlayRequestHandler - Cannot invoke the action
akka.stream.AbruptTerminationException: Processor actor [Actor[akka://application/system/Materializers/StreamSupervisor-0/flow-1-0-headSink#-440110538]] terminated abruptly

In conf/routes
GET     /robots.txt        controllers.Assets.at(path="/public", file="robots.txt")


text:
Q: Does Swift have a null coalescing operator and if not, what is an example of a custom operator? A common feature in many languages, the Null Coalescing Operator, is a binary operator often used to shorten expressions of the type:
x = possiblyNullValue NCO valueIfNull

…where NCO is a placeholder for the language's null coalescing operator.
Objective C's Null Coalescing Operator is ?:, so the expression would be:
x = possiblyNullValue ?: valueIfNull

The above expression is also equivalent to the use of tertiary operator:
 x =  someTestForNotNull( possiblyNullValue ) ? possiblyNullValue : valueIfNull

Advantages of a Null Coalescing Operator

*

*More readable code (especially with long, descriptive variable names)

*Reduced possibility of typographic errors (tested var is typed only once)

*No double evaluation of the tested variable where the tested variable is a getter, since its accessed once (or the need to cache it to intentionally avoid double evaluation).

A: What Venkat says is correct: there is none but you can define one.
His implementation however is not ideal because he forgot to use @auto_closure.
Also I believe you can overload || without needing to define a new operator.
I do not have the compiler here, but I'll try to give you the code from memory:
func |||<T> (maybe: Optional<T>, defaultValue: @auto_closure () -> T) -> T {
    if let some = maybe {
      return some
    }
    return defaultValue()
}

Edit: Thanks to Martin R for testing this with the compiler. See the comments. Apparently overloading || is possible but may not work as expected because of the way Swift handles resolution of overloaded operators (which is undocumented and therefore I have no idea if it can be worked around or not). I've changed the function above to use |||.

A: As of Swift 2.2 (Xcode 6, beta 5) it's ??
var x: Int?
var y: Int? = 8

var z: Int = x ?? 9000
// z == 9000

z = y ?? 9001
// z == 8

a ?? b is equivalent to the following code:
a != nil ? a! : b

And as of Beta 6, you can do this:
x ?? y ?? 1 == 8

A: I blogged about a custom operator function that provides nil-coalescing here:
http://ijoshsmith.com/2014/07/24/nil-coalescing-operator-in-swift/
My choice of operator was !! which combines the logical not operator (!) and the unwrap operator (!) for a "if cannot unwrap" semantic. Seems I was late to the party, given this thread is already over a month old. Either way, here's my implementation in case you're interested...
operator infix !! {}

@infix func !! <T> (
    value: T?,
    defaultValue: @auto_closure () -> T)
    -> T
{
    return value ? value! : defaultValue()
}

A: (Also see blog post)
No, Swift doesn't currently support a null coalescing operator.
Defining Custom Null Coalescing Operator for Swift
A custom operator can be defined for Swift, with the following considerations regarding the Swift language:
Swift and Nil
Swift supports a null concept through its Optional type (a Discriminated Union of sorts) which either holds a value of the underlying type or no value (indicated by nil) and must be explicitly defined as being optional:
var a : String?

A non-optional type can never be nil, or assigned nil. Therefore a custom infix binary NCO can be expected to take an optional as its first parameter.
Available Characters for Custom Operators in Swift
In Swift, custom operators can be comprised of the following characters only:
/ = - + * % < > ! & | ^ . ~

The Operator
Given the choice of available characters, ||| (three pipes, no spacing) isn't terrible (similar to the double pipe OR in Javascript which is used like a NCO):
Using the Operator
var a = String?
var z = a ||| "it's nil!"
println(z) //Output: it's nil!

Defining the Operator
operator infix ||| {}

@infix func |||<T> (left: T?, right: T) -> T  {
  if let l = left { return l }
  return right
}

A: hope this will help you

*

*yes , Now it is added in swift

*little Explanation
       var anumber:Int? = someValue
       var banumber = 2
       anumber =   ( anumber != nil) ? anumber : banumber ------- (a)
       println(anumber!)

now instead of writing all (a) this we can just use this ->
        anumber = anumber ?? banumber

and
The operator can also be used multiple times in the same expression.
like
     firstNumber ?? secondNumber ?? thirdNumber.

A: You can check with playground code below.
import UIKit
var personalSite : String?
let defaultSite = "http://www.google.com"

var website = personalSite ?? defaultSite


text:
Q: Total number of comments of a post Facebook returns empty data I am trying to get the total number of comments of a post using graph api
https://graph.facebook.com/post_id/comments?summary=true&limit=25&access_token=myaccesstoken

It has actually 2 comments but returns empty data set
{
   "data": [

   ],
   "summary": {
      "order": "chronological",
      "total_count": 0
   }
}

can anyone suggest me what is wrong


text:
Q: Why is my node.js etcd client getting html My etcd instance is running locally and I can perform get and set using the cli
// set
etcdctl set /services/myservice "{\"hostname\": \"127.0.0.1\", \"port\": 3000}"

//get
etcdctl get services/myservice
// results in -> {"hostname": "127.0.0.1", "port": 3000}

but when I use the node-etc module
var Etcd = require('node-etcd');
var etcd = new Etcd(['http://localhost:2379', 'http://localhost:4001']);
etc.get('services/myservice', { wait: true}, function (err, value){
    console.log(err, value);
});

I get value is HTML (see below) instead of the same result as the cli. This was working a few weeks ago so I am not sure if I have
I also find that when I don't include hosts and just use new Etcd() I get an internal HTML page with references to proxy issues: "The requested website is blocked by [insert company name] Proxy due to potential malicious activity or other security reasons."
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <title>http.com</title>
    <meta http-equiv="Content-Type" content="text/html; charset=">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable = no">

        <meta http-equiv="refresh" content="0;url=http://www.http.com/rg-erdr.php?_rpo=t ntZzFFI&_rdm=9f1NJXf43BJvmfNf4.JvV&p=J1c4gcvmfN9ffFGoFgXoYVa%7C%40%7CbzGzTE%2C5f95zbT%2C5f95Et%7C%40%7CX55g.JvV%7C%40%7C%7C%40%7C%7C%40%7CZzbHzEZHE%7C%40%7CzHZZFTH%7C%40%7CK-%7C%40%7C19c4NW4cGFHzTEtTEGZGzTbT%7C%40%7Ct+nh8llbj%7C%40%7Ct+7zFZKFH&ga=5rKI1sSSBwFmmNY4RDXg%2BB7VS0yzNgnQ9JpHpsLHSsvFu0NyshpFxWu0exObFAo5IdFZQrTZujcZjrXONxp3PxtPV7ezER14zh7kWG69e5lf08niAgSfUKiyBSByBIQgw92X314XjQy5h09a65wi7JIhzrLV0PReUb%2F7SMvquCNLeg70qvVfr7kkYTx9Z4NO&t=gnojs" />

For search results please <a href="http://www.http.com/rg-erdr.php?_rpo=t ntZzFFI&_rdm=9f1NJXf43BJvmfNf4.JvV&p=J1c4gcvmfN9ffFGoFgXoYVa%7C%40%7CbzGzTE%2C5f95zbT%2C5f95Et%7C%40%7CX55g.JvV%7C%40%7C%7C%40%7C%7C%40%7CZzbHzEZHE%7C%40%7CzHZZFTH%7C%40%7CK-%7C%40%7C19c4NW4cGFHzTEtTEGZGzTbT%7C%40%7Ct+nh8llbj%7C%40%7Ct+7zFZKFH&ga=5rKI1sSSBwFmmNY4RDXg%2BB7VS0yzNgnQ9JpHpsLHSsvFu0NyshpFxWu0exObFAo5IdFZQrTZujcZjrXONxp3PxtPV7ezER14zh7kWG69e5lf08niAgSfUKiyBSByBIQgw92X314XjQy5h09a65wi7JIhzrLV0PReUb%2F7SMvquCNLeg70qvVfr7kkYTx9Z4NO&t=gnojs" style="text-decoration:underline; color:#0000EE;">CLICK HERE.

http.com

            Privacy Policy


text:
Q: Not able to get values in console.log in Angular 8 I am trying to get every skill value, so that i can put it in my const body for api calling,
const firstEmployeeSkills = this.empForm.value.employees[0].skills.map(x => x.skill).value;
return firstEmployeeSkills;

i have written this in the body but it still does not show in console....i want the skill value to be displayed in the console
here's my demo with errors for that
https://stackblitz.com/edit/angular-a29jfx
this is the body i need to pass
submit(){
    const body = {
        firstName: Rakshanda,
        lastName: Bhure,
        skills: [
            {
                skill: java,
                exp: python,
            },

            {
                skill: php,
                exp: angular,
            }
            ..
        ]
    }
}

so i put this...to get values, but not able to get skill and exp values
submit() {
    const body = {
        firstName: this.employeeFirstName(empIndex).value,
        lastName: this.employeeLastName(empIndex).value,
        skills: [
            {
                skill: this.empForm.value.employees[0].skills.map(x => x.skill),
                exp: this.empForm.value.employees[0].skills.map(x => x.exp),
            }
        ]
    }
}

A: You can get the skills of first employee with below peace of code:
onSubmit() {
  let body = {
    firstName: this.empForm.value.employees[0].firstName,
    lastName: this.empForm.value.employees[0].lastName,
    skills: this.empForm.value.employees[0].skills
  }
  console.log(body);
  return body;
}

Now you can use the local variable body for the API calls.

Hope this will help you.


text:
Q: How can I import a .TSV file using the "Get Data" command using SPSS syntax? I'm importing a .TSV file, with the first row being the variable name and the first column as IDs, into SPSS using a syntax but I keep getting a Failure opening file error in my output. This is my code so far:
GET DATA
/TYPE=TXT
/FILE=\filelocation\filename.tsv
/DELCASE=LINE
/DELIMTERS="/t"
/QUALIFIER=''
/ARRANGEMENT=DELIMITED
/FIRSTCASE=2
/IMPORTCASE=ALL
/VARIABLES=
/MAP
RESTORE.
CACHE.
EXECUTE.
SAVE OUTFILE = "newfile.sav"

I think I'm having an issue in the delimters or qualifiers subcommand. Wondering if I should also include the variables under the variables subcommand. Any advice would be helpful. Thanks!

A: The GET DATA command you cite above has an empty /VARIABLES= subcommand.
If you used the "File -> Import Data -> Text Data' wizard, it would have populated this subcommand for you.  If you are writing the GET DATA command syntax yourself, then you'd have to supply that list of field names yourself.


text:
Q: Spring and Spring Data JPA are not working in conjunction I am using Spring Data JPA (1.3.0.RELEASE) with Spring (3.2.2.RELEASE ) in one project and facing a weird problem. I am using xml based configuration as mentioned below.
<context:annotation-config/>
<context:component-scan base-package="x.y.z.services"/>

Using this configuration to scan the classes decorated with @Component, @Service and @Named annotations.
<jpa:repositories base-package="x.y.z.repo"/>

Using this configuration to scan all interfaces extending JpaRepository. These interfaces are injected in Service classes in the following way.
@Service
public class UserServiceImpl implements UserService {

    private UserRepository userRepository;

    @Inject
    public void setUserRepository(UserRepository userRepository) {
            this.userRepository = userRepository;
    }

    @Override
    public List<User> listUsers() {
            return userRepository.findAll();
    }
 }

This configuration works as expected without any issue. But when I add the following configuration I get the BeanCreationException for UserRepository.
    <bean id="securityRealm" class="x.y.z.Realm">
        <property name="userService">
            <bean class="x.y.z.services.UserServiceImpl"/>
        </property>
    </bean>

And, here is the Java code for Realm and UserRepository.
public class Realm extends AuthorizingRealm implements IRealm {

    private UserService userService;

    @Inject
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
    AuthenticationToken token) throws AuthenticationException {
       return null;
    }

}

public interface UserRepository extends JpaRepository<User, String> {

}

As per above configuration, Spring is able to create the bean for userService but not able to create the UserRepository bean.
I can get this error away by scanning x.y.z.Realm and decorating it with @Service annotation. But it will be a very big constraint and design issue to my application.
AFAICT, Spring is not able to create the bean for UserRepository as it's implementation class is not available and has to be provided by jpa:repositories configuration. I can see that Spring and Spring Data JPA are not working in conjunction.
Can somebody please help me to solve this problem. Below is stacktrace of the exeception.
    2013-04-30 21:44:04.745:INFO:/web:Initializing Spring root WebApplicationContext
    2013-04-30 21:44:07,009 [ERROR] [main] [org.springframework.web.context.ContextLoader] - Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shiroFilter' defined in class path resource [META-INF/Test-web/security-config.xml]: Cannot resolve reference to bean 'securityManager' while setting bean property 'securityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testShiroRealm': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: x.y.z.core.service.UserService x.y.z.core.security.testShiroRealm.userService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void x.y.z.core.service.internal.UserServiceImpl.setUserRepository(x.y.z.repo.UserRepository); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [x.y.z.repo.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
        at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1393)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1134)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
        at org.springframework.context.support.AbstractApplicationContext.registerBeantesttProcessors(AbstractApplicationContext.java:753)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
        at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
        at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:764)
        at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:406)
        at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:756)
        at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:242)
        at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1221)
        at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:699)
        at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:454)
        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
        at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:90)
        at org.eclipse.jetty.server.Server.doStart(Server.java:263)
        at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
        at runjettyrun.Bootstrap.main(Bootstrap.java:80)
    ... 34 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void x.y.z.core.service.UserServiceImpl.setUserRepository(x.y.z.repo.UserRepository); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [x.y.z.repo.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:601)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
    ... 45 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [x.y.z.repo.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:558)
    ... 47 more

A: This was the bug in Spring Data JPA and has been fixed. Please have a look at JIRA issue for resolution.
https://jira.springsource.org/browse/DATAJPA-335


text:
Q: anonymize IP with GTM using angular app I am using GTM in my Angular 4 app and it works fine, expect for one issue. I want to anonymize user IP, the piece of code I found says to add this to your code
ga('create', 'UA-********-1', '*****.com');
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');

However GTM provided me with the following code which doesn't have that bit, plus as I use angular as it is a SPA   ga('send', 'pageview'); isn't useful. How can I anonymizeIP in the following code?
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-xxxxxx');</script>
<!-- End Google Tag Manager -->

A: Sign in to GTM, edit your universal analytics tag and find "fields to set", you can set it there.


text:
Q: Warnings about built-in functions in cross-compiled c Code:
#include <string.h>
//Return copy of str string from index position and len length
char *StrCpy2(char *str, unsigned short index, unsigned char len)
{
    char *text;
    text = (char *)malloc(sizeof(char)*(len+1));
    if (text == NULL) return text;
    strncpy(text, str + index, len);
    text[len] = '\0';
    return text;
}

Console output respecting this file and lines:
Compiling file: String.c
arm-none-eabi-gcc -c -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 -ffast-math -O0 -ffunction-sections -fdata-sections -Wall -Wstrict-prototypes -Wextra -std=gnu99 -g -ggdb3 -fverbose-asm -Wa,-ahlms=out/String.lst  -DSTM32F40_41xxx  -DUSE_STM324x7I_EVAL  -MD -MP -MF out/String.d -I.  -IBACnet/inc  -IBACnet/inc/objects  -Iinc  -Ilib/drivers/inc  -Ilib/eval  -IUI/inc  -IuIP/inc String.c -o out/String.o
String.c: In function 'StrCpy2':
String.c:39:2: warning: implicit declaration of function 'strncpy' [-Wimplicit-function-declaration]
  strncpy(text, str + index, len);
  ^
String.c:39:2: warning: incompatible implicit declaration of built-in function 'strncpy'
String.c:39:2: note: include '<string.h>' or provide a declaration of 'strncpy'

I feel lost because something went wrong during porting from stm32f1 to stm32f4, and codesourcery toolchain to bleeding-edge-toolchain (this one). As you can see I already include . Maybe some #defines are not correct? Maybe some paths in eclipse or system are wrong?

A: I'm almost certain, that you have a file named String.h in your project. Because you compile that on Windows, which is not smart enough to notice a difference between your String.h and toolchain's string.h, the line #include <string.h> actually includes your String.h, where you most likely don't have that declaration.
If you'd compile that on Linux, it would most likely work, because the case of file names matters there. For Windows you have no other solution than to name your file (especially the header) differently. Personally I'd propose to have a single global function per module (header + source) and then you can name the module after the function. So in above case you'd have StrCpy2.h and StrCpy2.c.


text:
Q: SharedPreferences - запретить удаление При первом запуске, приложение создает определенные SharedPreferences. Вместе с этим, пользователю выдаётся некий бонус. Если удалить данные приложения в настройках самого устройства - приложение будет считать что его только что установили, и выдаст бонусы как для первого посещения. Как можно защититься от этого? Можно ли как-то запретить пользователю удалять их?
И еще такой вопрос - можно ли как-то "узнать" приложению было ли оно установлено ранее, чтобы при установке\удалении\установке - приложение понимало, что пользователь уже устанавливал его и бонус он не получит? )
A: Может сделать что-то типа бесплатного In App Purchase? А в Google Play проверять, был ли он куплен хоть когда-нибудь. Я бы копал в эту сторону.
A: Регистрируйте юзера на своем вебсервисе. При любом запуске - приложение проверяет, зареган ли юзер, если нет - то регает и дает бонус. Других способов обойти то, о чем вы говорите нет.


text:
Q: Tate modules of commutative group schemes over finite field Let $G$ be a finite type commutative group scheme over a finite field $k=\Bbb F_q$ with $\Gamma=Gal(\bar k/k)$ and $l$ be a prime such that $(l,q)=1$, we can also define the Tate module $T_lG =\varprojlim_nG[l^n](\bar k)$. Then we can also consider the natural map
$Hom_k(G_1,G_2) \otimes \Bbb Z_l \rightarrow Hom_\Gamma(T_lG_1,T_lG_2)$
for any two commutative group scheme over $k$, or more generally the map
$\text{Ext}^i_k(G_1,G_2) \otimes \Bbb Z_l \rightarrow \text{Ext}^i_\Gamma(T_lG_1,T_lG_2)$ for every natural number $i$ at least when the extension groups are well-defined (This question may be related).
My first question is: when is this map surjective, injective or an isomorphism? If $G_i$ are abelian varieties and $i=0$, it's well-known that this map is an isomorphism. If $G_2=\Bbb G_m$ and $G_1$ is an abelian variety, this is also true for $i=0$ as both sides are zero, and is true for $i=1$ and $\text{dim}G_1=1$ as $\text{Ext}^1(A,\Bbb G_m)$ is the dual of $A$ and one can compute both sides explicitly (see this master thesis). However, this map can fail to be injective for trivial reasons (For instance, right side could be zero for some finite abelian groups).
So my second question is: how to describe extension groups between commutative group schemes using linear algebra datas in a systematic way? For instance, how to describe extension groups of finite group schemes like $\alpha_p$, $\mu_p$?
The last question is about growth of $\#G[l^n]$ for commutative group schemes (in order to study the Tate module). Let $k$ be any field, $G$ be a commutative group scheme over a field $k$ (not necessarily finite type) and $p$ be a prime. Assume $G[p^n]$ is a finite group scheme for every $n$, does there always exist $C >0,h \geq 0$ such that $\#G[p^n]=Cp^{nh}$ for $n >> 0$? Here the order of a finite group scheme means the dimension of its global section ring. I know the result holds for etale group schemes and abelian varieties. For example, if $G$ is constant i.e an abstract abelian group and $\#G[p^n]$ is finite for every $n$, then we know $G[p^\infty]\cong (\Bbb Q_p/\Bbb Z_p)^h\oplus T$ for some $h \geq 0$ and finite $p$-group $T$ (this result is used when studying Tate-Shafarevich group of elliptic curves).
Edit: there are good theory for commutative linear algebraic groups over complex number, for example every connected one is a product of $\Bbb G_a$ and $\Bbb G_m$, see here. Here is some discussion for higher extension groups. I am more interested in higher extension groups or non-reduced case.

A: I'll try to answer your last question on the order of $\#G[\ell^n]$ for $(\ell,p) = 1$.

Assumption: $G$ a commutative connected group scheme locally of finite type over $k$.

Since you're interested in the order of the group scheme $G[\ell^n]$, it is harmless to pass to $k = \overline{k}$ (a connected group scheme locally of finite type over $k$ is geometrically connected). Then $G_{\text{red}}$ is a closed reduced subgroup scheme of $G$ with $G_{\text{red}}[\ell^n] = G[\ell^n]$ as the latter is \'{e}tale over $k$. Therefore we may assume that $G$ is reduced, a fortiori smooth. By Chevalley's Theorem, we have an exact sequence
$$0 \to H \to G \to A \to 0$$
where $H$ is a closed linear algebraic subgroup and $A$ an abelian variety.

Lemma: For every $n > 0$, the sequence
    $$0 \to H[\ell^n] \to G[\ell^n] \to A[\ell^n] \to 0$$
    is still exact.
Proof: We have to show that $H/\ell^n H = 0$. Since $(\ell,p) = 1$ the multiplication by $\ell^n$ map is \'{e}tale and therefore open. However a homomorphism of group schemes always has closed image, and so by connectedness of $H$ we conclude the result.

Since you know the answer to your last question in the case of an abelian variety $A$, I'll just treat the case of $H$. Now $k$ is algebraically closed, in particular perfect so we know that
$$ H \cong D \times U$$
where $D$ is a diagonalizable group and $U$ is unipotent. Any unipotent $U$ group over a perfect field has a filtration with successive quotients isomorphic to $\mathbf{G}_a$. Therefore if $(\ell,p) = 1$ (as is the case here), $U[\ell^n] = 0$ and so
$$H[\ell^n] \cong D[\ell^n].$$
In particular, we may assume that $H$ is connected diagonalizable and therefore isomorphic to $\mathbf{G}_m^q$ for some $q \in \mathbf{N}$ (there are no forms of $\mathbf{G}_m^q$ over an algebraically closed field). Hence
$$\mathbf{G}_m^q[\ell^n] \cong (\mu_{\ell^n})^q$$
which has order $\ell^{nq}$.


text:
Q: Where to call restartLoader in ListView Fragment using ActionBarSherlock and SQLiteCursorLoader I'm doing a ListView in a fragment using loaders, ActionBarSherlock and SqliteCursorLoader.  The ListView basically shows a list of dates and GPS coordinates. I can load the inital ListView just fine.  I want to be able to reload the ListView upon clicking of a button to go forward and back in time and show the relevant data.
My problem is that I must not be calling restartLoader() in the right place, Eclipse is giving me a compile error when I try and call it using "this" as the third parameter.  It is saying that "this" is of type View, and it needs to be of type LoaderCallbacks.  How do I get the third parameter?   I tried to use all variations of getSherlockActivity().getSupportLoaderManager().getLoader(LOADER_ID) and tried to cast to LoaderCallbacks and no luck.
This is my first attempt using a Loader.
Here is my onActivityCreated:
@Override
public void onActivityCreated(Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);
    gps = new GPSTracker(getActivity());
    mGPSDC = new GPSDateCoordinates();
    Log.d(TAG, "onActivityCreated");
    CalcDate();
    //enables buttons for next and previous months
    GetPreviousFollowingMonths();
    adapter= new SimpleCursorAdapter(getActivity(), R.layout.row, null, new String[] {
            myDbHelper.COLUMN_DISTANCE, myDbHelper.COLUMN_FORMATTEDSTART },
            new int[] { R.id.title, R.id.value },0);
    lvReports.setAdapter(adapter);

    btnDate.setText(getMonth(BaseMonth) + " " + String.valueOf(BaseYear));
    getSherlockActivity().getSupportLoaderManager().initLoader(LOADER_ID, null, this);

    // show next month's data
    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
                getSherlockActivity().getSupportLoaderManager().restartLoader(LOADER_ID, null, this);
                getSherlockActivity().getSupportLoaderManager().getLoader(LOADER_ID).forceLoad();

        }
    });

}

and here is the Loader code:
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {

    loader = new SQLiteCursorLoader(getActivity().getApplicationContext(), myDbHelper,
            myDbHelper.getSQLArrayOfDatesDistances(BaseYear,BaseMonth),null);
    return loader;

}

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
    adapter.changeCursor(cursor);

}

@Override
public void onLoaderReset(Loader<Cursor> arg0) {
    adapter.changeCursor(null);

}

A: You'll want to use YourActivityClassName.this rather than this (which is the View.OnClickListener class instance) in order to refer to the Activity's instance.


text:
Q: Drawing bipartite graph I want to draw graphs with white and black vertices, such as square-octagon graph. Someone knows the easy way to draw in Latex? Thanks a lot!

A: The answer depends in part on how much time and effort you're willing to put into it. Definitely start by looking at tikz along with the tkz-graph package here and the tkz-berge package here. This site and this page are a good place to start looking at for examples which you like best. Make sure you read Altermundus' "Gallery of Named Graphs"; you can download it here. Note that the computer algebra system Sage supports tikz and Altermundus' packages as well as LaTeX. The relevant page is here. Robert Beezer has used Sage combined with LaTeX to produce graphs; see here for example.


text:
Q: Android Live Streaming issue in IP CAMERA example? I am new to android. I'm looking for live streaming from android mobile to remote server. I searched and tried lot of examples in internet. But mostly i have some issues in placing the codes in server side to get the live streaming from mobile. I worked on IP CAMERA example and tested in ICS version in android. The camera starts recording but i can't see output in browser. The player shows the error of
I cleared the errors and placed the raw folder in http server but i didn't got right output.
Thanks in advance and I want to know

*

*Am i want to install any media servers or Is http server enough to get running ip camera example.

*where to place the raw folder of the ip camera example in the server.

*They specified libjingle, am i want to any extra step with ip camera.

A: You could try https://github.com/bytedeco/javacv javacv i have it working on Android device streaming live to a server , instead of your ipcamera example it gets complicated have tried that one before. https://github.com/fyhertz/spydroid-ipcamera is a better example for an ip camera.


text:
Q: jsPDF, Add text after another dynamic text I need to create a PDF with dynamic fields. Sometimes a text can be 2 lines, sometimes 3 lines. How can I do to insert directly after the first dynamic text another element without hardcode a static Y coordinate ?
This is my code :
const pdf = new window.jspdf.jsPDF();

pdf.text(`DYNAMIC TEXT THAT CAN HAVE 1 TO X LINES`, 5, 10);

//The next text which must be under the first, but without hardcode Y:20, because sometime, this is too much
pdf.text(`DYNAMIC TEXT THAT CAN HAVE 1 TO X LINES`, 5, 20);

I'm using jsPDF 2.3.0 from CDN link
Thank You !

A: I had the same issue with jsPDF and i couldn't find any answer.
If you can change the library you're using, i found this post that suggest to try with pdfMake. Maybe it can help you ...

A:   didDrawPage: function (data) {
    doc.text(
     "first title,
      data.settings.margin.left,
      22
    );
    doc.text("Second title", data.settings.margin.top, 50);
  }

This tweak worked for me


text:
Q: Find rows that match between two unequal matrices (one is subset of anotherusing two columns of data) I have tried the code below to find matches, but I have gotten the error that matrix dimensions must agree.
mat = [ 8 5; 4 3; 3 5]
mat2 = [2 3; 2 3; 4 3; 4 3]

for i=1:size(mat,1)
    idx= find(mat2(:,1) == mat(i,1)& mat2(:,2) == mat(i,2));
end
idx= find(mat2(:,1) == mat(:,1))

I need to find rows that match between two unequal matrices using two columns of data (x&y coordinates for example) in order to append a column of data to the correct rows in the larger matrix. I basically need to find the rows in the larger matrix where values match those values in the smaller matrix so that the column of data from the smaller matrix can be appended to the correct row.

A: I think you want:
>> [c,imat,imat2] = intersect( mat, mat2, 'rows')
c =
     4     3
imat =
     2
imat2 =
     4

c are the rows that match.
imat are the indices of the matching rows in mat
imat2 are the indices of the matching rows in mat2


text:
Q: Waiting for a virtualbox automated guest login to complete Is there way to tell if an automated logon to a virtualbox windows guest has completed?
I'm currently using virtualbox machines as part of a test process on windows, but at the moment I have to manually wait for login to complete. Is there a way to script this? Perhaps a command I could use in association with VBoxManage guestcontrol?

A: Note: I haven't tried this myself.
Could you not have a logon script in the guest that does VBoxControl guestproperty set LogonCompleted true and then do VBoxManage guestproperty MyVM wait LogonCompleted on the host to detect when this has run?


text:
Q: Scala type inference with function types Consider the following piece of code : (see below for the actual code that needs solving)
def applyAll[T,S, U <: Seq[T => S]](l : U, x: T) = l.map(f => f(x))
val u = List((i: Int) => i + 1, (i: Int) => i + 2)
println(applyAll(u,1))

(given a Seq of T => S and a value, we expect to get the funtions applied on this value).
Although applyAll compiles fine, calling it on u gives the following error :
Error:(35, 13) inferred type arguments [Int,Nothing,List[Int => Int]] do not conform to method applyAll's type parameter bounds [T,S,U <: Seq[T => S]]
println(applyAll(u,1))
        ^

Which indicates that the compiler can't infer the type parameter S, which I'm guessing is because it is 'nested' inside a function type T => S.

Edit:
The actual code I'm trying to fix is similar (albeit complicated), and can't be fixed by removing the U parameter. Here goes :
def applyNatural[T, S, Repr <: TraversableLike[T => S, Repr], That]
(data: T, jobs: Repr)
(implicit bf: CanBuildFrom[Repr, S, That]): That = {
  jobs.map(f => f(data))
}
val u = List((i: Int) => i + 1, (i: Int) => i + 2)
val v = applyNatural(1, u)
println(v)

A: The U is simply useless. Just write
  def applyAll[T,S](l :  Seq[T => S], x: T) = l.map(f => f(x))
  val u = List((i: Int) => i + 1, (i: Int) => i + 2)
  println(applyAll(u,1))

A: You can make Repr a higher-kinded type Repr[_], and make the jobs argument have the type Repr[T => S]:
def applyNatural[T, S, Repr[A] <: TraversableLike[A, Repr[A]], That]
  (data: T, jobs: Repr[T => S])
  (implicit bf: CanBuildFrom[Repr[T => S], S, That]
): That = {
  jobs.map(f => f(data))
}


text:
Q: LINQ equivalent for a T-SQL query I have table with columns:
ID(int), Ano(varchar), Bno(varchar), StartTime(DateTime), EndTime(DateTime)

What is the equivalent LINQ statement of this SQL query:
 SELECT
    StartTime, EndTime, Ano, Bno,
    datediff(s, StartTime, EndTime) as duration
 FROM
    TABLENAME
 where
    StartTime >= 'value Input by user'
    and StartTime <= 'value INPUT by user'
 order by
    StartTime desc

Here, how can I select duration converting to value to minutes. calculate the total of duration of all records in minute and seconds

A: DateTime startTime = <Startime given by user>;
DateTime endTime = <Endtime given by user>;

var result =
yourSource
  .Where (m => m.StartTime >= startTime && m.StartTime<= endTime)
  .OrderByDescending(m => m.StartTime)
  .Select(m => new {
     startTime = m.StartTime,
     endTime = m.EndTime,
     ano = m.Ano,
     bno = m.Bno,
     duration = SqlFunctions.DateDiff("mi", m.StartTime, m.EndTime)
});

By the way, you  could also get the result without the duration, and calculate it after retrieving the results (to avoid the anon)
Something like :
var duration = (EndTime - StartTime).Minutes;

A: Match following code:
var result = from Entityname in EntityListName
    where Entityname.StartTime >= 'value Input by user' etc ...
    orderby Entityname.StartTime descending
    select Entityname;


text:
Q: No SSH access after accidentally denied ssh in ufw/iptables on Snappy Ubuntu Core I´m running Snappy Ubuntu Core 18.04 on Intel Nuc, located on other location then where I live permanently.
Now I have accidentally denied SSH in iptables with use of ufw and SSH connection is not possible anymore and I get error ssh: connect to host mydomain.com port 22: Operation timed out

*

*Are there any options to fix the issue remotely?

*Is it possible on some way to do a fix by using Docker container running on Nuc? I have Web Access to an Docker management tool, which I can use to spin up new containers and execute commands. But then I need to get access to host commands such as iptable, ufw and reboot

*Are there any options to fix the issue when I´m on site? With other words, can I get access to Ubuntu Core without using SSH when on site?

A: If you have a monitor, keyboard and mouse connected to your NUC you can log into it directly and use the commands mentioned in user68186's comment to remove the offending rule.
sudo ufw status numbered
sudo ufw delete [offending rule number]

Logging directly into the machine itself does not require SSH access. SSH is only used when trying to access the computer remotely over network (hence why firewall affects it).
NOTE: Enabling UFW will block incoming SSH connections by default. If there are no rules listed using the sudo ufw status command, or none that explicitly block port 22 (SSH) then use one of the commands below to allow SSH through your firewall.
To allow any PC to connect:
sudo ufw allow ssh

To allow a specific PC to connect: (Requires the PC you want to allow to have a static IP.)
sudo ufw allow from XXX.XXX.XXX.XXX to any port 22 proto tcp

where XXX.XXX.XXX.XXX is the IP of the PC you want to allow.
Hope this helps.


text:
Q: How are DigitalOcean's one-click apps maintained? DigitalOcean has a lot of one-click apps available. They help you create a droplet with pre-installed software. But I haven't found any technical documentation on them.
Specifically:

*

*who maintains those apps? (Can the community help upgrade them, for instance?)

*what's the workflow of creating such an application?

A: I am a Community Manager at DigitalOcean and our team maintains these images.  While we do sometimes work directly with open source projects to build and maintain images generally these are build completely in-house. We choose images to build based on feedback on our uservoice.
As for the workflow, these images are created using Fabric scripts.  We will create a new droplet using a base image (Usually the latest Ubuntu LTS release) and use fabric to configure the droplet.  A snapshot is then created and tested.  The snapshot image is then converted to a public image by way of some database changes and is then available in the control panel.
A user can use this same procedure to create custom snapshots on their account.


text:
Q: Flex or Flash Builder, etc. What are the differences? I just downloaded Flex. Do I also need an IDE to compile my .as files? I don't see any executable files in the Flex SDK that I can load an .as into. Can someone sort me out?

A: I will explain the differences:
Flex or Flex SDK: Is a set of components and UI controls for creating desktop, web and mobile applications, inside the Flex SDK there's a bin folder which contains executable files for compiling your .as code to .swf files.
Flash Builder and Flex Builder: Is an IDE based on the Eclipse platform, it comes bundled with the Flex SDK. Flex Builder was the name until version 4.x when it was renamed to Flash Builder. It is the IDE developed by Adobe and it's a good product to get started with ActionScript development.
Adobe Animate is fine for making Flash apps and games, the problem is that it lacks a powerful code editor.
If you are on Windows you can use Flash Develop which is free. If you are on OSX you can try Powerflasher FDT, its free tier allows you to make web and desktop apps.
Regardless of your choice, always keep in mind that you need to download the latest AIR SDK and Flex SDK (both free) to ensure maximum compatibility with the latest versions of Android, iOS, Windows and OSX.


text:
Q: "Кракозябры" при чтении сайта Читаем главную страницу сайта на русском языке, с кодировкой UTF-8:
import requests

url = 'http://kasta.ua'
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:45.0) Gecko/20100101 Firefox/45.0'
}
r = requests.get(url, headers = headers)

with open('test.html', 'wb') as output_file:
    output_file.write(r.text.encode('UTF8'))

В выходном файле "кракозябры". Что я делаю не так?

A: Вы открываете файл в 'wb' моде и он ожидает данные в бинарном виде.
r.text это строковые данные, когда r.content это собственно бинарная информация.
Так же метод .encoding возвращает кодировку ответа.
Попробуйте
with open('test.html', 'wb') as output_file:
    output_file.write(r.content)

A: Кодировка возвращаемого HTML на самом деле ISO-8859-1. Перед записью Вам необходимо перекодировать его в UTF-8.
Пример:
import requests

URL = 'http://kasta.ua/'

def main():
    html = requests.get(URL).text.encode('ISO-8859-1').decode('UTF-8')
    with open('test.html', 'w', encoding='utf-8') as f:
        f.write(html)

if __name__ == '__main__':
    main()


text:
Q: Burnside's Lemma, applications
A relation $\sim$ on $C$ is equivalence if it is:

*

*reflexive: $c\sim c$ for all colorings $c$ belonging to $C$

*symmetric: $c_1\sim c_2$ implies $c_2\sim c_1$

*transitive: $c_1\sim c_2$  and $c_2\sim c_3$ implies $c_1\sim c_3$

  A set of objects $S$, a set of colorings of these objects $C$ and a group of permutations $G$ representing symmetries possessed by configurations of the objects. Two colorings in $C$ are equivalent if there is a permutation in $G$ that transforms a coloring into the other.

Show that $\sim$ is an equivalence relation on $C$. How do you prove that?
As well as that, prove that $G_c$ is a subgroup of $G$.

A: It's pretty straightforward; everything follows from the definition of group of permutations.

*

*Reflexivity: Since $G$ is a group, it contains the identity permutation, which transforms any coloring into itself.

*Symmetry: If there is a permutation $g\in G$ transforming a coloring $c_1$ into $c_2$, the inverse permutation $g^{-1}$, which must be in $G$, transforms $c_2$ to $c_1$.

*Transitivity: If there are permutations $g,h\in G$ transforming $c_1$ to $c_2$ and $c_2$ to $c_3$, respectively, they their group product $hg$, which necessarily belongs to $G$, transforms $c_1$ to $c_3$: it's just a composition of functions.

A: You have a group $G$ (here the symmetric group of permutations) acting on a set $C$. The relation in question is defined as $c_1\sim c_2\iff \exists g\in G\colon c_1=gc_2$. Such is always an equivalence relation because $G$ is a group (neutral element gives reflexivity, inverse gives symmetry, the group operation gives transitivity). Remark: The equivalence classes in such a case are called orbits of an element under the group action.
If $c\in C$ we call $G_c:=\{g\in G\mid gc=c\}$ the stabilizer or fixgroup of $c$.
It is a group because the neutral element fixes $c$, the inverse of $g$ fixes $c$ if $g$ fixes $c$ and if both  $g_1 $ and $g_2$ fix $c$ then so does theit composition $g_1g_2$.


text:
Q: PHP: Form submission asnwer as a part of the email subject So i am fairly new to PHP (worked with it a little, not much though). I have a form submission that sends to my email. The thing is, i want to have one of the answers in my subject line. example: they choose bug, i want my subject to be "Site: Bug", or "Site: Other" depending on what they pick for the subject in the form.
<?php
if(isset($_POST['email'])) {

    $email_to = "email@email.com";
    $email_subject = "Site: Submission";

    function died($error) {
        // your error code can go here
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.

";
        echo $error."

";
        echo "Please go back and fix these errors.

";
        die();
    }

    // validation expected data exists
    if(!isset($_POST['name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['subject']) ||
        !isset($_POST['comments'])) {
        died('We are sorry, but there appears to be a problem with the form you submitted.');
    }

    $name = $_POST['name']; // required
    $email_from = $_POST['email']; // required
    $subject = $_POST['subject']; // drop down menu
    $comments = $_POST['comments']; // required

    $error_message = "";
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.
';
  }
    $string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$name)) {
    $error_message .= 'The Name you entered does not appear to be valid.
';
  }
  if(strlen($comments) < 2) {
    $error_message .= 'The Comments you entered do not appear to be valid.
';
  }
  if(strlen($error_message) > 0) {
    died($error_message);
  }

    $email_message = "Form details below.\n\n";

    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }

    $email_message .= "Name: ".clean_string($name)."\n";
    $email_message .= "Email: ".clean_string($email_from)."\n";
    $email_message .= "Subject: ".clean_string($subject)."\n";
    $email_message .= "Comments: ".clean_string($comments)."\n";

// create email headers
    $headers = 'From: '.$email_from."\r\n".
    'Reply-To: '.$email_from."\r\n" .
    'X-Mailer: PHP/' . phpversion();
    @mail($email_to, $email_subject, $email_message, $headers);
    ?>

    Thank you for you submission.

    <?php
    }
    die();
    ?>

Any help is appreciated. Sorry if this is a easy question, but i couldnt find an answer using google.

A: if i understood you correctly - just add it to the subject:
 $subject = $_POST['subject']; // drop down menu
 $email_subject = "Site: ".$subject;

first get $subject then add it to $email_subject

A: Assuming you want the contents of $subject in the email subject, put something like this just before email headers:
[...]
if ( isset( $subject ) ) {
    $email_subject = 'Site: '.$subject;
}

// create email headers
[...]

A: Add something like this to your form.
<select name="subject">
    <option value="Site: Bug">Bug</option>
    <option value="Site: Other">Other</option>
</select>


text:
Q: .NET Framework 3.5 and HttpResponseMessage not found I have a .Net framework 3.5 project which currently need REST service implementation. I am using Visual Studio 2008 for development. I am currently returning the class object as JSON. Below is the code sample,
IRestService.cs
[OperationContract]
[WebInvoke(Method = "GET",
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Bare,
    UriTemplate = "get_product/?producer_id={producerID}")]
Products getProducts(int producerID);

RestService.svc.cs
public Products getProducts(int producerID)
{
    var allProduct = GetAllProduct(producerID);
    var serializedProduct = new Products();

    foreach (var product in allProduct)
    {
        serializedProduct.products.Add(product.productName);
    }
    return serializedProduct;
}

The method above is returning the Product details for the Id provided. But if no product exists for the Id provided, it is return the null JSON value.
In .Net 4.0 we can use HttpResponseMessage as return type to fix this. I also use HttpResponseMessage as return type, but i am getting the following error "The type or namespace name 'HttpResponseMessage' could not be found (are you missing a using directive or an assembly reference?)".
Can any one tell me what is the equivalent of HttpResponseMessage in .Net 3.5 (VS2008).
Please help me.


text:
Q: Prove $f$ is continuous if $f(\overline{A}) \subset \overline{f(A)}$ for all subsets $A$. Let $X$ and $Y$ be topological spaces. Suppose that $f: X \rightarrow Y$ is a function satisfying: For every $A \subset X$, $f(\overline{A}) \subset \overline{f(A)}$.
Prove $f$ is continuous.
$\textbf{Proof:}$ Let $X$ and $Y$ be topological spaces. Suppose $f: X \rightarrow Y$ is a function satisfying $\forall A \subset X$, $f(\overline{A}) \subset \overline{f(A)}$.
Let $a \in \overline{A}$ and then $f(a) \in \overline{f(a)}$.
Let $V \subset Y$ be open with $f(a) \in V$.
By way of contradiction, suppose $\forall \, \text{open} \, U \subset X$ with $a \in U$, $f(U) \not \subset V$.
So, $\forall a \in U$, $b \in X \backslash f^{-1}(V)$ is also $b \in U$.
Then, $a \in \overline{X \backslash f^{-1}(V)} \subset \overline{Y \backslash V}$ $\rightarrow \leftarrow$ (contradiction!) because $V \cap Y \backslash V = \emptyset$.
$\therefore f$ is continuous. $\,\, \blacksquare$

A: Your idea basically amounts to showing that $f$ is continuous at each point of $X$, but to carry it out properly, you really should start with an arbitrary $x\in X$. Now you need an $A\subseteq X$ such that $x\in\operatorname{cl}A$. That's easy: let $A=\operatorname{cl}\{x\}$. (Of course if $X$ is $T_1$, $A$ will just be the singleton $\{x\}$, but we don't really care what it is as long as it contains $x$.)
Now suppose that $f$ is not continuous at $x$. Then there is an open nbhd $U$ of $f(x)$ such that $f[V]\nsubseteq U$ for every open nbhd $V$ of $x$. Thus, for each open nbhd $V$ of $x$ there is a point $x_V\in V$ such that $f(x_V)\notin U$. Let $S=f^{-1}[Y\setminus U]$. Then for each open nbhd $V$ of $x$ we have $x_V\in V\cap S$, so $x\in\operatorname{cl}S$, and therefore
$$f(x)\in\operatorname{cl}f[S]\subseteq Y\setminus U\,,$$
which is absurd, since $f(x)\in U$. Thus, $f$ is continuous at $x$ and therefore is continuous.
And when we get to this point, we see that it was really $S$ that we wanted: we never actually used $A$ at all.


text:
Q: Why do we need LinkedHashMap if keySet() maintains order for a HashMap? public class HashMapKeySet {

public static void main(String[] args) {
    Map<HashCodeSame,Boolean> map=new HashMap();

    map.put(new HashCodeSame(10),true);
    map.put(new HashCodeSame(2),false);

    for(HashCodeSame i:map.keySet())
        System.out.println("Key: "+i+"\t Key Value: "+i.getA()+"\t Value: "+map.get(i)+"\t Hashcode: "+i
                .hashCode());

    System.out.println("\nEntry Set******");
    for(Map.Entry<HashCodeSame, Boolean> i:map.entrySet())
        System.out.println("Key: "+i.getKey().getA()+"\t Value: "+i.getValue()+"\t Hashcode: "+i.hashCode());

    System.out.println("\nValues******");
    for(Boolean i:map.values())
        System.out.println("Key: "+i+"\t Value: "+map.get(i)+"\t Hashcode: "+i.hashCode());

}

static class HashCodeSame{

    private int a;

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

    HashCodeSame(int a){
        this.a=a;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        HashCodeSame that = (HashCodeSame) o;

        return a == that.a;

    }

    @Override
    public int hashCode() {
        return 1;
    }
}

}
If you could see in above example, I have explicitly made the hashcode() return 1 in all cases, to check what happens, when there is a collision of key.hashcode() in hashmap. What happens, a linked list is maintained for these Map.Entry objects such as

1(key.hashcode()) will link to <2,false> will link to <10,true>

(as false value is entered after true value, as I understand).
But when I do keySet(), true is returned first and then false, instead of false returning first.
So , what I am assuming here, since keySet() is a set and set maintains order, we get true and false while iteration. But, then again, why don't we say hashmap maintains order, as the only way to retrieve is by order. Or Why do we use LinkedHashMap?
 Key: DS.HashMapKeySet$HashCodeSame@1    Key Value: 10   Value: true     Hashcode: 1
Key: DS.HashMapKeySet$HashCodeSame@1     Key Value: 2    Value: false    Hashcode: 1

Entry Set******
Key: 10  Value: true     Hashcode: 1230
Key: 2   Value: false    Hashcode: 1236

Values******
Key: true    Value: null     Hashcode: 1231
Key: false   Value: null     Hashcode: 1237

Now , when I add chsnge the hashcode method to return a like
@Override
    public int hashCode() {
        return a;
    }

I get reverse order. Plus on addition of
    map.put(new HashCodeSame(10),true);
    map.put(new HashCodeSame(2),false);
    map.put(new HashCodeSame(7),false);
    map.put(new HashCodeSame(3),true);
    map.put(new HashCodeSame(9),true);

output received is,
    Key: DS.HashMapKeySet$HashCodeSame@2     Key Value: 2    Value: false    Hashcode: 2
Key: DS.HashMapKeySet$HashCodeSame@3     Key Value: 3    Value: false    Hashcode: 3
Key: DS.HashMapKeySet$HashCodeSame@7     Key Value: 7    Value: false    Hashcode: 7
Key: DS.HashMapKeySet$HashCodeSame@9     Key Value: 9    Value: true     Hashcode: 9
Key: DS.HashMapKeySet$HashCodeSame@a     Key Value: 10   Value: true     Hashcode: 10

Entry Set******
Key: 2   Value: false    Hashcode: 1239
Key: 3   Value: false    Hashcode: 1238
Key: 7   Value: false    Hashcode: 1234
Key: 9   Value: true     Hashcode: 1222
Key: 10  Value: true     Hashcode: 1221

Values******
Key: false   Value: null     Hashcode: 1237
Key: false   Value: null     Hashcode: 1237
Key: false   Value: null     Hashcode: 1237
Key: true    Value: null     Hashcode: 1231
Key: true    Value: null     Hashcode: 1231

Now it again makes me wonder, why is the order coming in sorted way.? Can anyone explain me in detail how does keySet(), entrySet() methods of hashmap works?

A: HashMap does not have a defined iteration order, and LinkedHashMap does have a specified iteration order.
The difficulty with HashMap is that it's easy to construct simple examples where the iteration order is quite predictable and is fairly stable, even though this is not guaranteed.
Suppose for example that you did this:
    Map<String, Boolean> map = new HashMap<>();
    String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (int i = 0; i < str.length(); i++) {
        map.put(str.substring(i, i+1), true);
    }
    System.out.println(map.keySet());

The result is
[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]

Hey! Those are in order! Well, the reason is that String's hashCode() function is pretty lousy, and it's exceptionally lousy for single-character strings. Here is String's hashCode() specification. Essentially it's a sum-and-multiply, but for a single-character string it's just the Unicode value of that char. So the hashcodes of the single-character strings above are 65, 66, ... 90. The internal table of HashMap is always a power of two, and in this case it's 64 entries long. The table entry used is the key's hashCode() value right-shifted by 16 bits and XORed with itself, modulo the table size. (See the code here.) Thus, these single-character strings end up in sequential buckets in the HashMap table, in array positions 1, 2, ... 26.
Key iteration proceeds sequentially through the buckets, so the keys end up coming out in the same order they were put in. Again, this isn't guaranteed, it just so happens to work this way because of the characteristics of the various pieces of implementation as described above.
Now consider HashCodeSame where the hashCode() function returns 1 every time. Adding a few of these objects to a HashMap will cause them all to end up in the same bucket, and since iteration traverses sequentially down the linked list, they'll come out in order:
    Map<HashCodeSame, Boolean> map = new HashMap<>();
    for (int i = 0; i < 8; i++) {
        map.put(new HashCodeSame(i), true);
    }
    System.out.println(map.keySet());

(I've added a toString() method that does the obvious thing.) The result is:
[HCS(0), HCS(1), HCS(2), HCS(3), HCS(4), HCS(5), HCS(6), HCS(7)]

Again, the keys come out in order, because of coincidence of implementation, but for different reasons than above.
But wait! In JDK 8, HashMap will convert a bucket from a linear linked list to a balanced tree if too many entries appear in the same bucket. This happens if more then 8 entries end up in the same bucket. Let's try that:
    Map<HashCodeSame, Boolean> map = new HashMap<>();
    for (int i = 0; i < 20; i++) {
        map.put(new HashCodeSame(i), true);
    }
    System.out.println(map.keySet());

The result is:
[HCS(5), HCS(0), HCS(1), HCS(2), HCS(3), HCS(4), HCS(6),
HCS(18), HCS(7), HCS(11), HCS(16), HCS(17), HCS(15), HCS(13),
HCS(14), HCS(8), HCS(12), HCS(9), HCS(10), HCS(19)]

The bottom line is that HashMap does not maintain a defined iteration order. If you want a specific iteration order, you must use LinkedHashMap or a sorted map such as TreeMap. Unfortunately, HashMap has an iteration order that is fairly stable and predictable, in fact, just predictable enough to lull people into thinking that its order is well-defined, when in fact it isn't.

To help combat this problem, in JDK 9, new hash-based collections implementations will randomize their iteration order from run to run. For example:
    Set<String> set = Set.of("A", "B", "C", "D", "E",
                             "F", "G", "H", "I", "J");
    System.out.println(set);

This printed out the following when run in different invocations of the JVM:
[I, H, J, A, C, B, E, D, G, F]
[C, B, A, G, F, E, D, J, I, H]
[A, B, C, H, I, J, D, E, F, G]

(The iteration order is stable within a single run of the JVM. Also, existing collections such as HashMap do not have their iteration order randomized.)

A: Answer for your question in Java doc for LinkedHashMap
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)
This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashMap (and Hashtable), without incurring the increased cost associated with TreeMap. It can be used to produce a copy of a map that has the same order as the original, regardless of the original map's implementation:
 void foo(Map m) {
     Map copy = new LinkedHashMap(m);
     ...
 }


text:
Q: Is there a library for promptForCredentials with firebase? I am trying to learn how to delete users from the Firebase Auth provided, but when I click on the delete button on my html it gives me Uncaught ReferenceError: promptForCredentials is not defined
I can't find any information on if I am suppose to import it anywhere. I'm using plain vanilla javascript.
Here is my code:
my html includes for scripts:
<script src="https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.7/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.7/firebase-database.js"></script>

javascript:
const firebaseConfig = {//my app information}
firebase.initializeApp(firebaseConfig);

const auth = firebase.auth();
const database = firebase.database();
const fname = document.querySelector('#fname');
        const lname = document.querySelector('#lname');
        const email = document.querySelector('#email');
        const password = document.querySelector('#password');
        const confirm_password = document.querySelector('#confirmpassword');
        const deleteConfirmed = document.querySelector('.deleteConfirmed');
        const passConfirmed = document.querySelector('#deletePass');

        auth.onAuthStateChanged(user => {
            if(user) {
                const user = auth.currentUser
                const database_ref = database.ref('users/' + user.uid).on('value', (snapshot) => {
                    fname.value = snapshot.val().first_name;
                    lname.value = snapshot.val().last_name;
                    email.value = snapshot.val().email;
                });

                deleteConfirmed.addEventListener('click', () => {
                    const credential = promptForCredentials();
                    user.reauthenticateWithCredential(credential).then(() => {
                      // User re-authenticated.
                    }).catch((error) => {
                      // An error ocurred
                      // ...
                    });
                })

            } else {
                location.href = "/login";
            }

        });

A: It looks like you copied code from the Firebase documentation on re-authenticating a user, which shows:
const user = firebase.auth().currentUser;

// TODO(you): prompt the user to re-provide their sign-in credentials
const credential = promptForCredentials();

user.reauthenticateWithCredential(credential).then(() => {
  // User re-authenticated.
}).catch((error) => {
  // An error occurred
  // ...
});

That TODO there means that you have to implement the prompt for the credentials of the user in whatever way works for your app, and then pass them to the reauthenticateWithCredential API.


text:
Q: which PHP OAuth library? I see a number of PHP OAuth libraries with a quick web search:

*

*http://pear.php.net/package/HTTP_OAuth

*http://pear.php.net/pepr/pepr-proposal-show.php?id=512

*http://code.google.com/p/oauth-for-php/

*http://pecl.php.net/package/oauth
Which one is the most reliable and easy-to-use?

A: It's always nice to have choice, but I think you should stick with one of those, probably the pecl one as it's a compiled one.


text:
Q: converting audio file in java I have used below code for converting audio file to wav format with 8000 Hz, 16 bit and mono channel
using JAVE
File source = new File("file.mp3");
     File target = new File("soundfile\\file2.wav");
     AudioAttributes audio = new AudioAttributes();
     audio.setCodec("pcm_s16le");
     audio.setBitRate(new Integer(16));
     audio.setChannels(new Integer(1));
     audio.setSamplingRate(new Integer(8000));
     EncodingAttributes attrs = new EncodingAttributes();
     attrs.setFormat("wav");
     attrs.setAudioAttributes(audio);
     Encoder encoder = new Encoder();
     try {
        encoder.encode(source, target, attrs);
        System.out.println("Successfully created");
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InputFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (EncoderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

It converting but that file is not play in media player. can any one help me to detect the problem in my code.

A: I just tried your code with a random mp3 and the resulting wav played fine.
This is a shot in the dark but I've come across a scenario where the two channels of the source mp3 are inverse of each other. When this gets converted to a single channel, they cancel each other out resulting in a silent wav.
You can check this quickly by setting the conversion to keep 2 channels
audio.setChannels(new Integer(2));


text:
Q: Transparent solution for bypassing local outgoing firewalls for python scripts Here is the problem: I do have several python packages that do have unittest that do require access to different online services in order to run, like connecting to a postgresql database or a LDAP/AD server.
In many cases these are not going to execute successfully because local network is fire-walled, allowing only basic outgoing traffic on ports like 22, 80, 443, 8080 and 8443.
I know that first thing coming into your mind is: build a VPN. This is not the solution I am looking for, and that's due to two important issues: will affect other software running on the same machine probably breaking them.
Another solution I had in mind was SSH port forwarding, which I successfully used but also this is very hard to configure and worse it does require me to re-configure the addresses the python script is trying to connect to, and I do not want to go this way.
I am looking for a solution that could work like this:

*

*detect if there is a firewall preventing your access

*setup the bypassing strategy (proxy?)

*run the script

*restore settings.

Is there a way to setup this in a transparent way, one that would not require me to make changes to the executed script/app ?

A: Is it possible to have the script itself run through these steps? By this I mean have the setup phase of your unit tests probe for firewall, and if detected dynamically setup a proxy somehow, use it to run unit tests, then when done teardown proxy. That seems like it would achieve the transparency you're aiming for.


text:
Q: Uncaught TypeError: undefined is not a function(anonymous function) I'm trying to implement the SimpleModal (http://www.ericmmartin.com/projects/simplemodal/). However, I'm getting a strange error. Which I can't fix but hopefully you guys can. And if you can explain why, great.
I've did some debugging. And https://example.com/scripts/sm.js is correct and loaded. (exactly the same as: https://simplemodal.googlecode.com/files/jquery.simplemodal-1.4.4.js)
            $("body").append("");
            $("body").append("");
            $("body").append("

Basic Modal Dialog

For this demo, SimpleModal is using this \"hidden\" data for its content. You can also populate the modal dialog with an AJAX response, standard HTML or DOM element(s).

Examples:

$('#basicModalContent').modal();// jQuery object - this demo

$.modal(document.getElementById('basicModalContent'));// DOM

$.modal('<p><b>HTML</b>elements</p>');// HTML

$('<div></div>').load('page.html').modal();// AJAX

");

            $('#basic-modal-content').modal();

What am I doing wrong?

A: I'm guessing it means modal is not a function, so sm wasn't imported properly. What if you just write a regular script tag instead of that append?


text:
Q: Ros Dynamic Config file I am trying to perform a segmentation task with PCL/ROS. I am using the dynamic configuration option in ROS as the number of inputs to my segmentation task is large and would like to study the influence of each param. There is no problem with my C++ source code, however when I try to run the launch file my file publisher is not able to find the PCD files.
<launch>

<!-- Start segmentation analysis -->
<node pkg="segmentation_analysis" name="region_growing" type="region_growing" output="screen">
    <remap from="selected_file" to="/selected_file" />
</node>

    <node pkg="file_selection" name="file_publisher" type="file_publisher" args="/home/anirudh/getbot/ros/3d_scene_analysis/segmentation_analysis">
            <param name="extension" value="pcd"/>
            <remap from="~file" to="/selected_file"/>
    </node>

    <node pkg="rqt_reconfigure" name="rqt_reconfigure" type="rqt_reconfigure" >
    </node>

But when I run the launch file, I am getting the following error:
ERROR: cannot launch node of type [file_selection/file_publisher]: can't locate node [file_publisher] in package [file_selection]

Any help will be appreciated.

A: As far as I can tell, your error is not related to not finding PCD files.
It says
can't locate node [file_publisher] in package [file_selection]

So it cannot find the program file_publisher.
So check that:

*

*The package file_selection exists.

*The executable file file_publisher exists inside that package.

To check the first item:
If you type:
roscd file_selection

...does the current working directory switch to the file_selection package?
If that doesn't work, figure out why. If it does, try the next step:
To check the second item:
roscd file_selection
find . -executable

...and check if the output contains file_publisher.
Go from there.
Edit: Also note that for ROS related questions there is answers.ros.org


text:
Q: How to make a button look pressed after click in C#? I have a button to select a tool and I want to make it look pressed after the user clicks it. I am using winforms and I do not want to use Check Box with Button Appearance. How can I achieve that?

A: You can use a CheckBox with the Appearance property set to Button.


text:
Q: Android VM heap size I can't understand what is android app heap size.
Is it overall maxumum memory I can allocate both from java and frome native code? If yes then why on my google nexus S. this code
Runtime rt = Runtime.getRuntime();
long maxMemory = rt.maxMemory();
Log.v("onCreate", "maxMemory:" + Long.toString(maxMemory));

dysplays 50331648 = 48MB
but dumpsys meminfo displays
 Native       13       16       12    84028    83457       18
and I can easily allocate say 74MB
int size = 1024*1024*74;
char* s = new char[size];

A: Well, heap size is actually a programming concept, much more than it's an Android one. You can read about it here, but it's really (short story) how much memory the VM is using and it's allocated independently from your app.
The memory allocated to your app is allocated dynamically. So, if you ask your app to allocate more memory you will see it grow. But it can't grow indefinitely.

A: Heap size is that amount of RAM that can be allocated. Each app is on a tiny Dalvik Virtual Machine. Each VM will have some heap space allocated.
And, there is a pre-defined heap-size settings inside /system/build.prop file for each device.


text:
Q: Is $n+\frac {1}{2}$ in Kendall-Mann numbers and quantum harmonic oscillator related? It is known that quantum harmonic oscillator is connected to the symmetric group of infinite order which is isomorphic to the permutation group. According to Cayley's theorem any finite group is isomorphic to a subgroup of permutations of elements of this group.
Looking at Kendall-Mann numbers $M(n)$: the maximal number of inversions in a permutation on $n$ letters – we can see Kendall-Mann numbers' property $M(n)/M(n-1)=n+\frac {1}{2}$ as $n \to \infty$. The same structure is for energy level of the quantum harmonic oscillator.
How can  we explain this seemingly coincident based on mathematical approach?
What is behind Hamilton operator $H$ and it's $\frac {1}{2}$ expressed as $H=\left(N+\frac {1}{2}\right)\frac {h}{2\pi} \omega$?


text:
Q: wifi disconects freqently and more I've install Ubuntu mate 3 days ago and before that i was not getting this problem in unity.my wifi disconnects frequently and some message like this shows up
even when my wifi router is on it dose not show it in list oh available wifi connections.(i cant take screen shot of that cause when i click tack screen-shot button the list disappears)thus I've installed fing and shows following result
i am only able to connect wifi again after rebooting.
 my laptop is acer aspire 5742
 and router which provides the wifi is D-link and service provider is BSNL
output of command  lspci -knn | grep Net -A3
is
rahul@rahul-Aspire-5742:~$  lspci -knn | grep Net -A3
01:00.0 Ethernet controller [0200]: Broadcom Corporation NetLink BCM57780 Gigabit Ethernet PCIe [14e4:1692] (rev 01)
Subsystem: Acer Incorporated [ALI] NetLink BCM57780 Gigabit Ethernet PCIe [1025:036d]
Kernel driver in use: tg3
Kernel modules: tg3
02:00.0 Network controller [0280]: Qualcomm Atheros AR9287 Wireless Network Adapter (PCI-Express) [168c:002e] (rev 01)
Subsystem: Foxconn International, Inc. T77H167.00 [105b:e034]
Kernel driver in use: ath9k
Kernel modules: ath9k


text:
Q: Reference request for "higher order" adjoint functors? Assume all the categories here are abelian and the functors are additive. Given functors $F: \mathcal{C} \rightarrow \mathcal{D}$ and $G : \mathcal{D} \rightarrow \mathcal{D}$, we say that they are an adjoint pair if there is a natural bijection
$$
\text{Hom}(F(a), b) \simeq \text{Hom}(a, G(b)).
$$
Is there a term for when there is a natural bijection of Ext groups,
$$
\text{Ext}^{i}(F(a), b) \simeq \text{Ext}^{i}(a, G(b))?
$$
Further, since $F$ may fail to be left exact and $G$ may fail to be right exact, is there a term for when the derived functors are adjoint?
This has come up in a few topics I am studying, but results are generally just stated as known. I'm interested at looking at this in the general case, but I don't know what the terminology is to look for. Is there a standard reference that covers this, or even just a name for these functors?


text:
Q: Given how long many things were each running for; calculating the total number of of things that were running over time? I have a few machines that start operating at the same time. I have a vector of numbers vec_num representing for how many units of time each machine was running for since it was started (there are no zero values).
I'm trying to find a way to efficiently calculate how many machines were running over time by making a vector of length(max(vec_num)) where each element represents a unit of time, and its value represents how many machines were running.
# For instance, take
vec_num <- c(1,1,4,3,1,10)

The ideal output would be a vector as generated from:
vec_num <- lapply(vec_num, function(x) {
  vec_zero <- rep(0, max(vec_num))
  vec_zero[1:x] <- 1
  return(vec_zero)
})

Reduce(`+`, vec_num)

>> 6 3 3 2 1 1 1 1 1 1

Where 6 machines were running at the first unit of time, 3 machines were running at the second and third, 2 at the fourth, and only one machine ran for 10. Think of the first index representing how many machines were running at the first unit of time, second index being the second unit of time, third index being the third, and so fourth.
However, this way is computationally and memory inefficient, and doesn't scale when there are hundreds of thousands of machines that are running for several thousand units of time. Is there a more efficient way to go about calculating this?

A: Here is an option:
rev(cumsum(rev(tabulate(vec_num))))
#[1] 6 3 3 2 1 1 1 1 1 1

A: We can use sequence + table
as.integer(table(sequence(vec_num)))
#[1] 6 3 3 2 1 1 1 1 1 1


text:
Q: Quickly implement, deploy a Webservice in Java I have a large system written in a mixture of C++, Java, Python. I have to interface a very small subset of this system with a web portal using webservice technology. Webservice is not critical and it has to expose 3 or 4 methods.
What is today the quickest way to implement this in Java? I thoughted AXIS+Tomcat. Maybe is there any other newest library?

A:
What is today the quickest way to implement this in Java? I thoughted AXIS+Tomcat. Maybe is there any other newest library?

Yes, there is a much better way. Forget Axis and go for a JAX-WS stack such as JAX-WS RI (which is included in Java 6) or Apache CXF. Here is the usual HelloWorld service with a test method using the built-in HTTP server of the JDK:
package hello;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;

@WebService
public class Hello {
    @WebMethod
    public String sayHello(String name) {
        return "Hello, " + name + ".";
    }

    public static void main(String[] args) {
        Endpoint.publish("http://localhost:8080/WS/Hello", new Hello());
    }
}

Just run the main method and you're ready to play with the web service.
Of course, you'll want to deploy your web service on a real container for production use. You could go with  GlassFish and just deploy your service (GlassFish bundles a JAX-WS runtime). Or you could pick Jetty or Tomcat and install the chosen runtime on it (JAX-WS RI or Apache CXF). Refer to their respective instructions.
Resources

*

*Creating a Simple Web Service and Client with JAX-WS

*JAX-WS Five Minute Tutorial
Related question

*

*Getting started with JAX-WS...

A: there is also project "Jersey" the JSR-311 (JAX-RS) reference implementation. A Framework for Web Services implementing the REST principles, which in my opinion modern Web Services should adhere to.
It got lots of tutorials on the web to be found.

A: Apache Axis2, Apache CXF or Glassfish Metro 2.0 are all pretty up to date and will provide what you need. Spring-WS is probably easier to use than the previous 3, but only if you're already building in the Spring framework. For comparison see:

*

*https://stackoverflow.com/questions/519576/would-you-use-metro-instead-of-axis2

*https://stackoverflow.com/questions/1461921/axis2-versus-sun-metro


text:
Q: 404 Not Found but Route is defined Laravel Hello i am  trying to change 2 values from a table in DB,  using Laravel 8, but for some reason, when i press the button to update my data,  i get a 404 not found.  However i have the route defined,  and it appears on the list when i use   php artisan routes:list    I also tried clearing all cache , and it still doesn't work
My controller
public function confirmar_pedido_mentoria(Request $request){

        $user = User::findOrFail($request->mentorando_id);

        $user -> area_interesse = $request->area_interesse;
        $user -> pedido_mentoria = 1;
        $user -> update();

        return redirect('/admin/pedido_mentoria/{{$user->id}}')->with('msg', 'Pedido realizado com sucesso!');

    }

My routes
Route::get('/admin/pedido_mentoria/{id}', [UsersController::class, 'pedido_mentoria'])->middleware('auth');
Route::put('/admin/confirmar_pedido/{id}', [UsersController::class, 'confirmar_pedido_mentoria'])->middleware('auth');

I put here the get route, because that is the route i intend to user when i redirect after updating the values
My blade view
<?php
$inter = $user->interesses->pluck('id')->toArray();
?>

Efectuar Pedido de Nova Mentoria: {{$user->user}}

        <form action="/admin/confirmar_pedido/{{$user->id}}" method="POST" enctype="multipart/form-data" name="Form" onsubmit="return validateForm()">
        @csrf
        @method('PUT')

Escolha a Área de Interesse

            @foreach($interesses as $interesse)

             <input type="radio" name="area_interesse[]" class="area_interesse" value="{{$interesse->id}}" @if (in_array($interesse->id, $inter)) checked="checked" @endif > {{$interesse->area_interesse}}

            @endforeach

            <input type="submit" class="btn btn-primary" value="Escolher">
            </form>

A: You have to get your id parameter in controller function(confirmar_pedido_mentoria).
Edit your code  :
public function confirmar_pedido_mentoria(Request $request,$id){

        ....
    }


text:
Q: Sending data from WinForms to Website database I'm creating win forms application which has a database with some data. In application I'm generating new information which also goes to database.
I have an idea to put that data into website.
My question:  Is it possible to send new generated data to the website database by click one button from winforms application ? Can't find any info about it. Any suggestions ?
Regards.


text:
Q: Java code converting special char to junk char I am facing an issue that when I post a json message with special char from Java program, that special character ( say ' in O'Reilly) is replaced with ?.
If I post same message from POSTMAN, I get correct response.
Could you please suggest how to handle this issue ?
Thank You.
Below is the code and json I am using:

{ "lastName":"O'Reilly", "firstName":"Shaun"}

package rest_apis;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class IDQ_tranformation_cd {

    public static void main(String args[]){
        String json_req="{"lastName":"O'Reilly","firstName":"Shaun"}";

        try{
          CloseableHttpClient httpclient = HttpClients.createDefault();
          String instanceUrl = "https://my-end-point";
          URIBuilder builder = new URIBuilder(instanceUrl);

          StringEntity params =new StringEntity(json_req);
          HttpPost post_data = new HttpPost(builder.build());

          post_data.addHeader("Content-Type","application/json");
          post_data.addHeader("Accept", "application/json");

          post_data.setEntity(params);

          HttpResponse queryResponse = httpclient.execute(post_data);
                    int Out_RespCd = queryResponse.getStatusLine().getStatusCode();
          HttpEntity httpEntity = queryResponse.getEntity();

          System.out.println(Out_RespCd +":"+EntityUtils.toString(httpEntity));
        } catch (Exception e) {
          System.out.println("Exception :"+e.toString());
        }
    }
}

I expect correct output as (I am able to get this when I use postman):
{"lastName":"O'Reilly","firstName":"Shaun"}

But I am getting this when I use java code (' replaced with ?)
{"lastName":"O?Reilly","firstName":"Shaun"}

A: Try to change your  line:
post_data.addHeader("Content-Type","application/json");

to
post_data.addHeader("Content-Type","application/json; charset=utf-8");

Also, it may be that you get the data OK and only the display is incorrect. What helped me numerous times to diagnose similar problems is to convert the "problematic" string into a sequence of unicodes. There you can see if the data itself is correct and only the display is corrupted or the data itself is corrupted.
There is an Open Source java library MgntUtils that has a Utility that converts Strings to unicode sequence and vise versa:
result = "Hello World";
result = StringUnicodeEncoderDecoder.encodeStringToUnicodeSequence(result);
System.out.println(result);
result = StringUnicodeEncoderDecoder.decodeUnicodeSequenceToString(result);
System.out.println(result);

The output of this code is:
\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064
Hello World

The library can be found at Maven Central or at Github It comes as maven artifact and with sources and JavaDoc
Here is JavaDoc for the class StringUnicodeEncoderDecoder. Also in that library, there is a very simple Http client.

A: Thanks All for your help. It worked after changing below line in code:
StringEntity params =new StringEntity(json_req,"UTF-8");

The below article was very helpful.
HttpPost with StringEntity having special characters like ®, seeing ¿½` instead of ®