text:
Q: Differential functional equation I'm struggling to solve this problem:
Let $f$ be a continuous function defined on $[0,+\infty[$, derivable in every point such that
$$
f'(x)=2f(2x)-f(x), \ \ \ \ \ \ \forall x>0,
$$
and
$$
M_n=\int_{0}^{\infty}x^nf(x)dx<+\infty, \ \ \ \ \ \ \forall n\in\Bbb{N}.
$$
Prova that exists a non zero function that satisfies this conditions. For which sequences of real numbers $\{a_n\}$ it's true that $a_n=M_n, \ \ \forall n\in\Bbb{N}$.
All I managed to get is that
$$
M_n=n!\prod_{i=1}^{n}\frac{2^i}{2^i-1}M_0=n!\prod_{i=1}^{n}\frac{2^i}{2^i-1}\int_{0}^{\infty}f(x)dx.
$$


text:
Q: Resizing and rearranging component controls using code/ IB Is it possible to resize and rearrange UI components (say segmented controls, buttons, labels, etc) when these are created using IB?
I need to rearrange/resize few UI components on a button click on iPad screen.
Any idea?

A: It is possible.
You will need to create IBOutlets for the UI components you are interested in, then you can adjust the properties you are interested in (UIView's frame property)
IBOutlet's are created in the *.h file for you View controller.
IBOutlet UIView * view;

Then you can control click and drag from the file owner (in xib) to the UI element. (or right click and drag)

A: Yes it is.  Implement the viewDidLoad method in your controller and set the frame to whatever you wish for your views and controls so long as you've attached them to an outlet.
Example:
self.myCustomView.frame = CGRectMake(x,y,width,height);

A: You may also access them by their tag.
If you assign them unique tag numbers in IB, then in your code, you can search within subviews of your view and find them by viewWithTag method.

A: You can set the initial position of the components in IB, hook up the elements with IBOutlets and on the button click move them in code. I don't think you can rearrange them in IB.
For a cool effect you can use [UIView animateWithDuration:animations:] to move whatever components you need

redpajama_set_name: RedPajamaStackExchange


text:
Q: Custom Logic on Paypal button I want my paypal button to capture information from my custom form so all users need to do after pressing it is to make a payment. My custom form has only 2 fields: amount and email address. Is it even possible?
Anybody knows how to do that using php? thanks

A: If I understood your question right, then this example should be what your looking for:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Paypal</title>
</head>
<body>
    <form action="https://www.paypal.com/cgi-bin/webscr" method="post">
        <input type="hidden" name="cmd" value="_xclick">
        <!-- Change the email -->
        <input type="hidden" name="business" value="email@email.com">
        <!-- Change the return email after payment -->
        <input type="hidden" name="return" value="http://google.com">
        <!-- Change the description of the item -->
        <input type="hidden" name="item_name" value="Item name"/>
        <input type="text" name="user_email" placeholder="Please enter email" value=""/>
        <input type="hidden" name="no_shipping" value="1">
        <input type="text" name="user_amount" placeholder="Please enter amount" value="">
        <input type="hidden" name="no_note" value="1">
        <input type="hidden" name="currency_code" value="USD">
        <input type="hidden" name="bn" value="PP-BuyNowBF">
        <button type="submit" alt="PayPal - The safer, easier way to pay online!">Pay now</button>
    </form>
</body>
</html>

A: remove inputs with name="email" and name="amount" and mark visible inputs user_email and user_amount, fill it and send form


text:
Q: Short circuit logic in PHP and effect of parallel processing issues Short ciruit question is asked already I know. But i want to know why it dont work here. Does short circuit has some effects due to parallel processing or pipelining.
I faced very strange situation with my code. The code looks like this
foreach($feeds as $k=>$feed)
{
foreach($filtered as $item)
{
 if(($feed['object'] == $item['object']) && (($feed['time']-$item['time'])<10))
   {
   Code....
   }
  }
 }

When i put both condition just like above in same If() block they both get compared.
But when i put them in nested blocks they take much lesser time to excute.
Question:
Does && work as a short circuit operator. Which mean
if  $feed['object'] == $item['object'] fails
($feed['time']-$item['time'] < FEED_TIME) will not be evaluated.
It looks like PHP evaluate cond2 even when cond1 failed.
Can you explain how && actually works in PHP.
Benchmarks
With code as above the if execute for approx 61000 time. taking 27 sec to execute for whole website.
With nested conditions approx 10000 executions for condtion2
$feeds are about 1700 entries where $filtered is 392 entries.
Thanks

A: && and || are short-circuit operators in PHP. You can see it with the following test:
if (0 > 1 && func()) {
    echo "If is true\n";
} else {
    echo "If is false\n";
}

function func() {
    echo "Function called\n";
    return true;
}

If you run this, you should see "If is false", but not "Function called". If you change > to <, you will see "Function called" and "If is true".
I'm not sure how you're determining that your expressions are or aren't being evaluated, since they have no obvious side effects.


text:
Q: Google Geocoder Problems I am trying to geocode an address given by the user in the text field, however my JavaScript function does not execute from the line "geocoder.geocode ({'address':address......" onwards.
I am stuck here not sure why it doesn't work. It throws thee first alert box showing the address field pulled over to the client script but does not work after that. It just stays without any action. Please let me know where i need to correct. Here is the client side code.
var map;
var geocoder;
function initialize()
{
    geocoder = new google.maps.Geocoder();
}
function getgeocode() {
    var address = document.advpollsrch.txtaddress.value;
    alert(address);
    geocoder.geocode( {'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            alert("Geocode was successful");
            var latlng = results[0].geometry.location;
            document.advpollsrch.hidlatitude.value = latlng.lat();
            document.advpollsrch.hidlongitude.value = latlng.lng();
            alert("Geocode split was successful");
            return true;
        } else {
            alert("Geocode was not successful for the following reason: " + status);
            return false;
        }
    });
}

    <form  name="advpollsrch">
        <input type="hidden" name="hidlatitude" id="hidlatitude"></input>
        <input type="hidden" name="hidlongitude" id="hidlongitude"></input>

STEP 1 -

                        Street Address

                        <input type="text" width="300" name="txtaddress" id="txtaddress" value=""></input>

                        City

                        <input type="text" width="150" name="txtcity" id="txtcity" value=""></input>

Or

                        Town / RM/ Village / First Nation

                        <input type="text" width="300" name="txtplace" id="txtplace" value=""></input>

STEP 2 -

                        Select the distance

                        <select id="radius" name="radius">
                            <option value="0">Choose Distance:</option>
                            <option value="2">2 kilometers</option>
                            <option value="4">4 kilometers</option>
                            <option value="6">6 kilometers</option>
                            <option value="8">8 kilometers</option>
                        </select>

STEP 3 -

            <input type="button" value="Find Advance Poll locations" onclick="getgeocode()"></input>

    </form>


text:
Q: Is $\lim_{n\to\infty}\frac{n(a_n-a_{n+1})}{a_{n+1}}=0$ if $\sum_{n\geq 1} a_n/n$ diverges? Consider a sequence $(a_ n)$ of positive and monotonically decreasing terms for which $\sum_{n\geq 1} a_n/n$ diverges and $a_ n\to 0$. I claim that that $$\lim_{n\to\infty}\frac{n(a_n-a_{n+1})}{a_{n+1}}=0.$$
I suspect that it's true (at least I can't find a counterexample) but I can't find a clean proof. Is there some theorem or test that might help out?

A: Try $a_n=\frac{1}{\log (n+1) \prod_{k^2\le n}\left(1+\frac{1}{k^2}\right)}$. Note that:

*

*$a_n$ is monotonically decreasing to $0$

*$a_n$ is bounded below by $\frac{1}{\log (n+1) \prod_{k\ge1}\left(1+\frac{1}{k^2}\right)}=\frac{\pi}{\sinh\pi}\frac{1}{\log(n+1)}$

*$\sum_n\frac{a_n}{n}=\infty$ by comparison with, say, $\int_2^t\frac{1}{x\log x}dx$

Now, note that for $n=k^2$, $\frac{a_n}{a_{n-1}}=\frac{\log(n)}{\log(n+1)(1+\frac{1}{n})}$, whence the listed ratio at $(n-1)$ is:
$$(n-1)(\frac{a_{n-1}}{a_n}-1)=(n-1)\left(\frac{\log(n+1)(1+\frac{1}{n})}{\log(n)}-1\right)$$
Now, notice $\frac{\log(n+1)}{\log(n)}=1+\frac{1}{n\log(n)}+O(\frac{1}{n^2})$, giving the ratio as:
$$\left(n-1\right)\left(\left(1+\frac{1}{n\log(n)}+O(\frac{1}{n^2})\right)\left(1+\frac{1}{n}\right)-1\right)=(n-1)(\frac{1}{n}+O(\frac{1}{n\log(n)}))\to1$$
which offers a counterexample to the claim.
One can also note that for other $n$, the ratio is $n\left(\frac{\log(n+2)}{\log(n+1)}-1\right)=O\left(\frac{1}{\log (n)}\right)\to0$.


text:
Q: Why are DateTime.Now DateTime.UtcNow so slow/expensive I realize this is way too far into the micro-optimization area, but I am curious to understand why Calls to DateTime.Now and DateTime.UtcNow are so "expensive". I have a sample program that runs a couple of scenarios of doing some "work" (adding to a counter) and attempts to do this for 1 second. I have several approached of making it do the work for a limited quantity of time. The examples show that DateTime.Now and DateTime.UtcNow are significantly slower than Environment.TickCount, but even that is slow compared to just letting a separate thread sleep for 1 second and then setting a value to indicate the worker thread to stop.
So my questions are these:

*

*I know that UtcNow is faster because it does not have time zone information, why is it still so much slower than TickCount?

*Why is reading a boolean faster than an int?

*What is the ideal way of dealing with these types of scenarios where you need to allow something to run for a limited amount of time, but you do not want to waste more time checking the time than actually doing the work?

Please pardon the verbosity of the example:
class Program
{
    private static volatile bool done = false;
    private static volatile int doneInt = 0;
    private static UInt64 doneLong = 0;

    private static ManualResetEvent readyEvent = new ManualResetEvent(false);

    static void Main(string[] args)
    {
        MethodA_PrecalcEndTime();
        MethodB_CalcEndTimeEachTime();
        MethodC_PrecalcEndTimeUsingUtcNow();

        MethodD_EnvironmentTickCount();

        MethodX_SeperateThreadBool();
        MethodY_SeperateThreadInt();
        MethodZ_SeperateThreadLong();

        Console.WriteLine("Done...");
        Console.ReadLine();
    }

    private static void MethodA_PrecalcEndTime()
    {
        int cnt = 0;
        var doneTime = DateTime.Now.AddSeconds(1);
        var startDT = DateTime.Now;
        while (DateTime.Now <= doneTime)
        {
            cnt++;
        }
        var endDT = DateTime.Now;
        Console.WriteLine("Time Taken: {0,30} Total Counted: {1,20}", endDT.Subtract(startDT), cnt);
    }

    private static void MethodB_CalcEndTimeEachTime()
    {
        int cnt = 0;
        var startDT = DateTime.Now;
        while (DateTime.Now <= startDT.AddSeconds(1))
        {
            cnt++;
        }
        var endDT = DateTime.Now;
        Console.WriteLine("Time Taken: {0,30} Total Counted: {1,20}", endDT.Subtract(startDT), cnt);
    }

    private static void MethodC_PrecalcEndTimeUsingUtcNow()
    {
        int cnt = 0;
        var doneTime = DateTime.UtcNow.AddSeconds(1);
        var startDT = DateTime.Now;
        while (DateTime.UtcNow <= doneTime)
        {
            cnt++;
        }
        var endDT = DateTime.Now;
        Console.WriteLine("Time Taken: {0,30} Total Counted: {1,20}", endDT.Subtract(startDT), cnt);
    }

    private static void MethodD_EnvironmentTickCount()
    {
        int cnt = 0;
        int doneTick = Environment.TickCount + 1000; // <-- should be sane near where the counter clocks...
        var startDT = DateTime.Now;
        while (Environment.TickCount <= doneTick)
        {
            cnt++;
        }
        var endDT = DateTime.Now;
        Console.WriteLine("Time Taken: {0,30} Total Counted: {1,20}", endDT.Subtract(startDT), cnt);
    }

    private static void MethodX_SeperateThreadBool()
    {
        readyEvent.Reset();
        Thread counter = new Thread(CountBool);
        Thread waiter = new Thread(WaitBool);
        counter.Start();
        waiter.Start();
        waiter.Join();
        counter.Join();
    }

    private static void CountBool()
    {
        int cnt = 0;
        readyEvent.WaitOne();
        var startDT = DateTime.Now;
        while (!done)
        {
            cnt++;
        }
        var endDT = DateTime.Now;
        Console.WriteLine("Time Taken: {0,30} Total Counted: {1,20}", endDT.Subtract(startDT), cnt);
    }

    private static void WaitBool()
    {
        readyEvent.Set();
        Thread.Sleep(TimeSpan.FromSeconds(1));
        done = true;
    }

    private static void MethodY_SeperateThreadInt()
    {
        readyEvent.Reset();
        Thread counter = new Thread(CountInt);
        Thread waiter = new Thread(WaitInt);
        counter.Start();
        waiter.Start();
        waiter.Join();
        counter.Join();
    }

    private static void CountInt()
    {
        int cnt = 0;
        readyEvent.WaitOne();
        var startDT = DateTime.Now;
        while (doneInt<1)
        {
            cnt++;
        }
        var endDT = DateTime.Now;
        Console.WriteLine("Time Taken: {0,30} Total Counted: {1,20}", endDT.Subtract(startDT), cnt);
    }

    private static void WaitInt()
    {
        readyEvent.Set();
        Thread.Sleep(TimeSpan.FromSeconds(1));
        doneInt = 1;
    }

    private static void MethodZ_SeperateThreadLong()
    {
        readyEvent.Reset();
        Thread counter = new Thread(CountLong);
        Thread waiter = new Thread(WaitLong);
        counter.Start();
        waiter.Start();
        waiter.Join();
        counter.Join();
    }

    private static void CountLong()
    {
        int cnt = 0;
        readyEvent.WaitOne();
        var startDT = DateTime.Now;
        while (doneLong < 1)
        {
            cnt++;
        }
        var endDT = DateTime.Now;
        Console.WriteLine("Time Taken: {0,30} Total Counted: {1,20}", endDT.Subtract(startDT), cnt);
    }

    private static void WaitLong()
    {
        readyEvent.Set();
        Thread.Sleep(TimeSpan.FromSeconds(1));
        doneLong = 1;
    }

}

A: As far as I can tell, DateTime.UtcNow (not to be confused with DateTime.Now, which is much slower) is the fastest way you can get time.
In fact, caching it the way @wageoghe proposes decreases performance signifficantly (in my tests, that were 3.5 times).
In ILSpy, UtcNow looks like this:
[__DynamicallyInvokable]
public static DateTime UtcNow
{
    [__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), SecuritySafeCritical]
    get
    {
        long systemTimeAsFileTime = DateTime.GetSystemTimeAsFileTime();
        return new DateTime((ulong)(systemTimeAsFileTime + 504911232000000000L | 4611686018427387904L));
    }
}

I think, this suggests that the function is inlined by the compiler to achieve maximum speed. There might be faster ways to get time, but so far, I haven't seen one

A: TickCount just reads a constantly increasing counter. It's just about the simplest thing you can do.
DateTime.UtcNow needs to query the system time - and don't forget that while TickCount is blissfully ignorant of things like the user changing the clock, or NTP, UtcNow has to take this into account.
Now you've expressed a performance concern - but in the examples you've given, all you're doing is incrementing a counter. I would expect that in your real code, you'll be doing rather more work than that. If you're doing a significant amount of work, that's likely to dwarf the time taken by UtcNow. Before doing anything else, you should measure that to find out whether you're actually trying to solve a problem which doesn't exist.
If you do need to improve things, then:

*

*You can use a timer rather than creating a new thread explicitly. There are various kinds of timers in the framework, and without knowing your exact situation, I can't advise on which would be most sensible to use - but it feels like a better solution than starting a thread.

*You can measure a few iterations of your task, then guess how many will actually be required. You might want to then execute half that many iterations, take stock of how long that's taken, then adjust the number of remaining cycles accordingly. Of course, this doesn't work if the time take per iteration can vary wildly.

A: FWIW here is some code that NLog uses to get the timestamp for each log message.  In this case, the "work" is the actual retrieval of the current time (granted, it happens in the context of probably a much more expensive bit of "work", the logging of a message).  NLog minimizes the cost of getting the current time by only getting the "real" time (via DateTime.Now) if the current tick count is different than the previous tick count.  This does not really apply directly to your question, but it is an interesting way to "speed up" current time retrieval.
internal class CurrentTimeGetter
{
  private static int lastTicks = -1;
  private static DateTime lastDateTime = DateTime.MinValue;

  /// <summary>
  /// Gets the current time in an optimized fashion.
  /// </summary>
  /// <value>Current time.</value>

  public static DateTime Now
  {
    get
    {
      int tickCount = Environment.TickCount;
      if (tickCount == lastTicks)
      {
        return lastDateTime;
      }
      DateTime dt = DateTime.Now;
      lastTicks = tickCount;
      lastDateTime = dt;
      return dt;
    }
  }
}

// It would be used like this:
DateTime timeToLog = CurrentTimeGetter.Now;

In the context of your question, you could probably "improve" the performance of your time looping code like this:
private static void MethodA_PrecalcEndTime()
{
  int cnt = 0;
  var doneTime = DateTime.Now.AddSeconds(1);
  var startDT = CurrentTimeGetter.Now;
  while (CurrentTimeGetter.Now <= doneTime)
  {
    cnt++;
  }
  var endDT = DateTime.Now;
  Console.WriteLine("Time Taken: {0,30} Total Counted: {1,20}", endDT.Subtract(startDT), cnt);                        }
}

If CurrentTimeGetter.Now is called so frequently that the returned time would be the same many times in a row, only the cost of Environment.TickCount must be paid.  I can't say if it really helps with performance of NLog logging such that you would notice or not.
I don't know that it really helps on your question, or if you even need any help anymore, but I thought that it would serve as an interesting example of leveraging a faster operation (Environment.Ticks) to potentially speed up a relatively slow operation (DateTime.Now) in some circumstances.

A: For an up-to-date look on the profiled speed of DateTime.UtcNow / DateTimeOffset.UtcNow, see this dotnet thread, where BenchmarkDotNet was used to profile.
There was unfortunately a perf regression with the jump to .NET (Core) 3 compared to 2.2, but even reporting with the regressed value, DateTime.UtcNow is coming in at a pretty rocking time of 71 ns (it had been 25 ns), i.e. 71 billionths of a second.
To put that in perspective, even at the slower speed of 71ns, it means:
You can call DateTime.UtcNow ~ 14,000 times for a cost of only 1 millisecond!
At the previously faster time of 25 ns (hopefully they will get this performance back), you can call DateTime.UtcNow ~ 40,000 times for a cost of 1 millisecond.
I'm not looking at old .NET Framework times here, but at least with the newer bits, I think it can safely be stated that it is at least no longer accurate to say that DateTime.UtcNow is "slow/expensive" (I appreciate that the question was asked however!).


text:
Q: How do I pass in values manually for swagger api calling in angular? {
  "swagger" : "2.0",
  "info" : {
    "description" : "Project API Swagger Documentation",
    "version" : "20-30",
    "title" : "Project API Swagger Documentation",
    "termsOfService" : "",
    "contact" : { }
  },
  "host" : "localhost:9080",
  "basePath" : "/home/project/rest",
  "schemes" : [ "http" ],
  "paths" : {
        "/kmh/dashboardAttributes" : {
          "get" : {
            "tags" : [ "kmh" ],
            "summary" : "Get kmhDashboard Attributes",
            "description" : "Returns attributes for kmh Dashboard",
            "produces" : [ "application/json" ],
            "parameters" : [ {
              "name" : "iv-user",
              "in" : "header",
              "description" : "ID of the user",
              "required" : true,
              "type" : "string"
            } ],

So basically I have a swagger API which references the ID of the user in the header automatically.
How do I manually pass in an ID of the user for the API? I am quite confused as to how can I pass in the values in angular so that when calling the API, I am passing in the correct parameters for the api.
** What do I have to do to pass the value in the get request to the api and for the api to take the value from the get request? ** Edit
I am using angular 2.
In my service in angular.
    public getID() : Observable<any> {
        let headers = new Headers({ 'Content-Type': 'application/json'} ); // ... Set content type to JSON
        let options = new RequestOptions({ headers: headers, withCredentials: true }); // Create a request option

        return this.http.get('/api/services/v1/home/project/kmh/dashboardAttributes' , options ) // ...using get request
            .map(this.extractData)
           .catch(this.handleError);
    }

A: In your Swagger documentation it states
"parameters" : [ {
  "name" : "iv-user",
  "in" : "header",

So in your header variable, you must add
let headers = new HttpHeaders({ 'Content-Type': 'application/json', "iv-user": "{{my-username}}" }); // ... Set content type to JSON

And replace {{my-username}} by the username of your user.
I also suggest you to switch from Headers (Fetch API) to HttpHeaders (Angular).
Headers is a class from the Fetch API (not from Angular). I'm not sure it will work correctly with the HttpClient of Angular. You do not need import to use Headers. Unlike HttpHeaders which needs @angular/common/http import and is designed to work with the HttpClient of Angular.


text:
Q: django issue with {% url '..' %} i don't know exactly how to explain this, but i will try...Something weird is going on with the linking of a tag...Basically when i link a
 tag or anything to go to another template tag, it doesn't work...it does change the url extension but it stays on the same template...
I will show you the files now...
This is the tree of the folder project:
tube/
├── main
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── __init__.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   ├── views.py
├── manage.py
├── models.py
├── templates
│   ├── base.html
│   └── main
│       ├── details.html
│       └── main.html
└── tube
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    ├── views.py
    ├── wsgi.py

main/views.py :
class Main(TemplateView):
    template_name = 'main/main.html'

    def get_context_data(self, **kwargs):
        context = super(Main, self).get_context_data(**kwargs)
        test = Test.objects.all().order_by('ps_name')
        # for i in range(200):
        #     lines.append('Line %s' % (i + 1))
        paginator = Paginator(test, 20)
        page = self.request.GET.get('page')
        try:
            show_lines = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            show_lines = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            show_lines = paginator.page(paginator.num_pages)
        context['test'] = show_lines
        return context

def details(request, pk):
    ps = Test.objects.get(id=pk)
    print ps
    return render(request, 'main/details.html', {'test': ps})

As you can see my first view goes to main.html and my second to details.html
main/urls.py :
urlpatterns = [
    url(r'$', views.Main.as_view(), name='main'),
    url(r'(?P<pk>\d+)/', views.details, name='details'),
]

this is my templates/main/main.html :
{% extends 'base.html' %}
{% load staticfiles %}
{% load static %}
{% load bootstrap4 %}
{% block content %}

                Name
                Rank

            {% for ps in test %}

                        {{ ps.ps_name }}

                    {{ ps.ps_rank }}

            {% endfor %}

        {% bootstrap_pagination test url="/test?page=1" size="small" %}

{% endblock %}

and this is just a test part of templates/main/details.html :

                Bio

            {% for ps in test %}

                    {{ ps.bio }}

            {% endfor %}

So my question is...when i click any link from main/main.html it doesn't show me the content of main/details.html it shows me the same content from main/main.html but it does change the url extention.
Does anyone know why? Cause on other projects i don't have a problem like this...it works fine.
Thank you
Versions:
Django==1.11.10
django-bootstrap4==0.0.6

UPDATE
Changing url extension:   main/main.html is on https://example.com/main ....and main/details.html  is on https://example.com/main/(pk.id) ....basically when i click a name on https://example.com/main  it goes to https://example.com/main/101...but the page doesn't change

A: You're missing the anchor from the main URL; currently it just means "any string that ends", which of course matches everything. It should be:
url(r'^$', ...

A: Your urls should be like below, you are missing ^
urlpatterns = [
    url(r'^$', views.Main.as_view(), name='main'),
    url(r'^(?P<pk>\d+)/$', views.details, name='details'),
]


text:
Q: C# namespace not generated because of using reflection (no type instantiated) I got the following issue:
I have a project / namespace ViewModels that containing several viewmodel classes described by a custom attribute that holds an interface type like:
[Register(typeof(IMyViewModel))]
public class MyViewModel : IMyViewModel

In another project I use Reflection to get all ViewModel-Types with this specific attribute and register them to an Autofac Inversion of Control - Container like
builder.RegisterType(type).As(interfaceType);

So far, it works correctly and the classes are registered as their interface types.
But now, if i call the Container.Resolve function of Autofac, there is an IO-Error saying some dlls have not been found. It looks like:
System.IO.FileNotFoundException: Could not load file or assembly '/storage/emulated/0/Android/data/MyProject/files/.__override__/de-CH/Autofac.resources.dll'

The issue seems to be because none of the types declared in the ViewModel project are instantiated anywhere directly. My program works like a charm if I create an empty class in the ViewModel project and simply instantiate it anywhere like
Class1 c1 = new Class1()

So my question is:
Is there a better way to make sure an assembly exists even if there is no direct instantiation of any type in it?
thank you very much :)


text:
Q: How do i set value attribute to a div tag? I have 3 boxes, when i click on each box i want to alert the attribute value of each box.
https://jsfiddle.net/aedzgu9v/

.box{
  height: 80px;
  width: 80px;
  border: 2px solid blue;
  margin: 5px;
}

$('.box').on('click', function(){
    var value = $(this).val();
  alert(value);
});

A: Try this instead:

$('.box').on('click', function(){
    var value = $(this).attr('name');
  alert(value);
});

Or if you want to use value attribute:
$('.box').on('click', function(){
    var value = $(this).attr('value');
  alert(value);
});

A: Only form controls have a legitimate property value that allows you to use val()... other elements do not
I suggest you switch to using a data- attribute and access it using either data() or attr()

JS
$('.box').on('click', function(){
    var value = $(this).data('value');
    alert(value);
});


text:
Q: Cannot exclude module from Gradle I'm trying to use Jersey on Android by adding
    compile org.glassfish.jersey.core:jersey-client:2.16
to my build.gradle file. It gives me an unexpected top-level exception, so I added multiDexEnabled true to it as well.
Now I get:
    Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: javax/inject/Qualifier.class

I figured out that Jersey is trying to import both javax.inject:1 and javax.inject:2.4.0-b09. Okay no problem, we'll exclude the older one as recommended here. So I tried:
compile ('org.glassfish.jersey.core:jersey-client:2.16') {
    exclude (module: 'javax.inject:1')
}

and
compile ('org.glassfish.jersey.core:jersey-client:2.16') {
    exclude (group: 'javax.inject:javax.inject:1')
}

But the module won't go away no matter what. I'm at the end of my rope here and have no idea why this isn't working.

A: compile ('org.glassfish.jersey.core:jersey-client:2.16') {
   exclude (group:'javax.inject', module:'javax.inject')
}

Worked. Thanks RaGe!


text:
Q: Como podria guardar el token generado en el campo de la base de datos Estoy generando un servicio de token con asmx en C# para la autenticación de usuarios de un sistema, el servicio ya lo tengo listo lo que necesito saber es como guardo el valor de ese token en el campo de la base de datos, esto es para validar que el usuario este activo dentro del sistema y pasado un tiempo predeterminado sea sacado para que vuelva a logearse
Este es el método que estoy usando para generar el token ya con la validación del usuario hecha
    public CabeceraSoapAcceso cabeceraSoapAcceso;
    public CabeceraSoapToken cabeceraSoapToken;

    [WebMethod]
    // INDICA QUE SE LE ASIGNARÁ A ESTE MÉTODO
    // EL OBJETO cabeceraSoapAcceso COMO  CABECERA SOAP.
    [SoapHeader("cabeceraSoapAcceso")]
    public TokenAcceso GetTokenAcceso()
    {
        string usuario;
        string password;
        string token = string.Empty;
        TokenAcceso tokenAcceso;

        // COMPRUEBA SI EXISTE UNA CABECERA EN LA PETICIÓN,
        // Y SI LA CABECERA CONTIENE EL USUARIO Y LA CONTRASEÑA
        // DEL CLIENTE DE LA PETICIÓN.
        if (cabeceraSoapAcceso == null ||
            string.IsNullOrEmpty(cabeceraSoapAcceso?.Usuario) ||
            string.IsNullOrEmpty(cabeceraSoapAcceso?.Password))
        {
            throw new SoapException("Acceso no autorizado", SoapException.ClientFaultCode,
                new Exception(@"Se requiere Usuario y Contraseña en la Cabecera de la petición."));
        }
        else
        {
            // LA CABECERA DE LA PETICIÓN ES CORRECTA,
            // OBTEBEMOS EL USUARIO Y LA CONTRASEÑA DEL CLIENTE.
            usuario = cabeceraSoapAcceso.Usuario;
            password = cabeceraSoapAcceso.Password;
        }

        // COMPRUEBA QUE EL USUARIO Y LA CONTRASEÑA
        // DE LA PETICIÓN SON VÁLIDOS.
        tokenAcceso = cabeceraSoapAcceso.ValidarUsuario(usuario, password);
        if (tokenAcceso != null)
        {
            // EL USUARIO Y CONTRASEÑA SON CORRECTOS,
            // SE CREA EL TOKEN DE ACCESO Y SE ALMACENA
            // EN LA CACHÉ DE LA PETICIÓN ANTES DE DEVOLVERLO.
            tokenAcceso.Token = Guid.NewGuid();

            HttpRuntime.Cache.Add(
                tokenAcceso.Token.ToString(),
                tokenAcceso,
                null,
                System.Web.Caching.Cache.NoAbsoluteExpiration,
                TimeSpan.FromMinutes(5), // 5 MINUTOS DE VIDA (PARA PRUEBAS)
                System.Web.Caching.CacheItemPriority.NotRemovable,
                null
            );
        }
        else
        {
            // EL USUARIO Y LA CONTRASEÑA NO SON VÁLIDOS.
            throw new SoapException("Acceso no autorizado", SoapException.ClientFaultCode,
                new Exception(@"EL Usuario y/o Contraseña no son válidos."));
        }

        // DEVOLVEMOS EL TOKEN DE ACCESO
        if (!string.IsNullOrEmpty(tokenAcceso.Token.ToString()))
        {

            return tokenAcceso;
        }
        else
        {
            throw new SoapException("Acceso no autorizado", SoapException.ClientFaultCode,
                new Exception(@"ERROR. No se ha podido generar el Token de acceso."));
        }
    }


text:
Q: Firebase subscribe to topics not working after reinstalling app I made an app which was working fine until I found that after deleting and reinstalling the app it doesn't receive messages anymore that are sent to a a topic, although it does receive a message that is sent to the id-token of the app.
Does anybody know what might be the problem? Firebase or my app?
Update:
After clearing cache and data of the app it can receive notifications again. If reinstalled there's a chance of not working. I have to do some more testing, but I think it is solved by setting android:allowBackup="false" in the app manifest.

A: After the uninstall and reinstall, your app on that device was assigned a new device token.  According to that documentation:

The registration token may change when:

*

*The app deletes Instance ID

*The app is restored on a new device

*The user uninstalls/reinstall the app

*The user clears app data.

That new token won't have all the same subscriptions that the old one had.  You'll have to re-subscribe to the topics that the user was interested in on that device.
It's not just reinstalls - your app should be ready to handle new tokens at any time, based on the criteria listed above.  The linked documentation illustrates how to listen to token changes.


text:
Q: There have any idea for this I have one task from my lecture which is Java. Lecturer ask us to draw a custom chess game which is something similar with the below picture. I was thinking from past few days but are not able to get at all.

Instruction :
Sorry, if I am asking question wrongly. I am expecting some ideas and any references for in able to do this.

A: we can write a code for you , but instead step to start will help you more to learn.
There can be many ways to write this one of is this.
Steps to start

*

*Create a JFrame.

*Set layout to border layout

*Create a JPanel -> set panel at the center of jframe

*Set panel layout to grid layout of  11 x 11

*Create jable objects in for loop and add in Jpanel components.

*Control background color of jlabel to form a structure shown in image.

*For pawn, knight,you can use jlabel images

*Build you logic to move or change jlabel to acive your requirement

Update and correction are invited


text:
Q: Is a function of admissible heuristics in A* search admissible? I don't understand how to approach this problem.
$h_1, h_2, h_3$
are three admissible heuristics for an optimisation problem to be solved using A* search. Is the heuristic defined by
$$h(n) = \frac{\sqrt{h_1(n)h_2(n)}+ 2h_3(n)}{3} $$
for any node n of the search graph, admissible?
This is all the information I have, I have no problem specifics or anything else. Any help would be great! Thanks

A: Let $f(n)$ be the optimal cost to node $n$. Suppose $h_1(n) \ldots h_3(n)$ are positive lower bounds for $f(n)$, i.e. admissible heuristics. Can you prove that $$\frac{\sqrt{h_1(n) h_2(n)} + 2 h_3(n)}{3}$$ is no more than $f(n)$? You might start by proving that $\sqrt{h_1(n) h_2(n)} \le f(n)$.


text:
Q: When to use fetch property in the core data with example in a cross-store scenario I am facing same problem as here
How to achieve relationships between entity in one store with other?
Kindly guide me through this.

A: It is indeed possible and makes total sense in some cases to split objects across stores
lets assume obj A in Store #1 and obj B in Store #2.
Each A has N Bs
easiest solution would maybe be a TRANSIENT property on A ... named 'allMyBs'
then implement the fetch in code:
- (NSArray*)allMyBs {
   NSFetchRequest *r == ... //setup to fetch Entity B
   [CoreDataHelper managedObjectContextForStore2] executeFetchRequest:r];
}

this isnt the fetched property yet but easy
see Cross-Store weak relationship with Fetched Properties? for a complicated way ^^

A: The short answer is that you can't. You can't have a relationship between managed objects that crosses persistent stores.
You can, however, implement a key or identifier in your model that YOU maintain across stores, and use that find 'related' objects in different stores.
If you have user records in one store, and application data in another, the application records might have a "belongsTo" property whose value is a user ID corresponding to a user record in the user store.
Apple's documentation is very specific about this:
From the Core Data Programming Guide:
"Core Data does not let you create relationships that cross stores. If you need to create a relationship from objects in one store to objects in another, you should consider using fetched properties."
Again, from the Core Data Programming Guide:
"You must be careful not to create relationships from instances in one persistent store to instances in another persistent store, as this is not supported by Core Data. If you need to create a relationship between entities in different stores, you typically use fetched properties (see "Fetched Properties")."
This is exactly what I am talking about above. If you implement fetched properties that way, it is up to you to maintain the integrity of the graph. The same document walks you through creating and using fetched properties. Perhaps you can be more specific in what you need answered.


text:
Q: Like button with added confirm Been adding a Like Button to all of my pages on my site, easy enough. Had a problem with the Text box that opened up being cut off at the bottom, so consequently was bug fixing that, the only was to see if I had fixed the errors was to like, check to text area wasn't cut off which it still was, then I would unlike so I could retest, my problem now is I have a confirm button in place.
I understand this is to stop like-jacking but is there anything I can do to stop it? Surely people have to test their stuff to make sure its all working.
any info appreciated.
Jon
nvm I see this will probably get closed, facebook is great in so many respects but try and find out who to talk to regarding issues is ridiculous.


text:
Q: How to understand the maxLik's result in r? --------------------------------------------
Maximum Likelihood estimation
BFGS maximization, 49 iterations
Return code 0: successful convergence
Log-Likelihood: -42669.88
4  free parameters
Estimates:
      Estimate Std. error t value Pr(> t)
[1,] -0.023648   0.001081  -21.87  <2e-16 ***
[2,]  0.129408   0.012860   10.06  <2e-16 ***
[3,] -0.650217   0.035436  -18.35  <2e-16 ***
[4,]  3.677548   0.046444   79.18  <2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
--------------------------------------------

Here is my result of Maximum Likelihood estimation, I want to know how the maxLik calculate the 't value' and 'Pr(> t)' or the equation of  't value' and 'Pr(> t)'.


text:
Q: while passing a comma separated string as a parameter to database i have a search field which search the data from back end sybase . if I pass one parameter .It search the data with calling stored procedure SYN_XYZ @param = "abc".
now if I pass two param It calls like SYN_XYZ @param = "abc,def"
Now consider a  situation , that back end data contain 'ab,c' instead of 'abc' . how can I search 'ab,c','def' As sybase will consider this param as three different param ie ab and c and def.
Thanks

A: Simple: Don't use String concatenation. Instead, use CallableStatement and setString().
Your solution is very, very dangerous. Imagine an attacker searching for "; DELETE FROM USER; COMMIT;


text:
Q: Angular digest apply when setValidation When I submit a form I do some backend validation to ensure that an email is unique as follows:
$http.post('/api/users.json', dataObj)
     .then (function() {
          // we are happy
      })
      .catch(function(response) {
           if(response.data.data.exception) {
                var emailNotUniqueException = 'App\\Http\\Exception\\EmailNotUniqueException';
                $scope.userRegister.email.$setValidity("unique", false);
                scrollToFirstError();
            }
      }
);

The scrollToFirstError does what is says on the tin:
function scrollToFirstError () {
     var invalidInputs = angular.element('input.ng-invalid, select.ng-invalid');
     return invalidInputs.first().focus();
}

The problem of course is that although I can see ng-valid has been applied to the input the binding is lost I believe. I read about scope digest and apply, if I add either I get a message:
angular.js:14328 Error: [$rootScope:inprog] $digest already in progress
What am I doing wrong?

A: After you set the validity of a field to invalid, you have to wait until the current digest cycle is applied. If you don't do so, the HTML might be not updated yet when you look for ng-invalid classes.
That being said, it is often a good idea to let the digests finish themselves and do not start or invoke them by hand, unless you really know you need this.
In this particular case, I would suggest you to call scrollToFirstError in the next digest cycle. It can be simply achieved with the $timeout service. Inject it first and then replace your scrollToFirstError() call with the following:
$timeout(scrollToFirstError);


text:
Q: yii2 grid filter type not working I am using kartik grid lib in yii2

*

*This works.
[
'attribute' => 'status',
'filterType' => GridView::FILTER_SELECT2,
'filter' => ['Active' => 'Active', 'In Active' => 'In Active'],
'filterWidgetOptions' => [
    'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Select'],
]

*But this doesn't
[
'attribute' => 'status',
'filterType' => '\kartik\widgets\Select2',
'filter' =>['Active' => 'Active', 'In Active' => 'In Active'],
'filterWidgetOptions' => [
    'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Select'],
]

Why ? I need to use the point 2 approach. But it is not working.

A: Changed filter type to '\kartik\select2\Select2' and it worked.

A: usa 'filterType' =>GridView::FILTER_SELECT2, el composer usado es use kartik\grid\GridView;
   'filterType' => GridView::FILTER_SELECT2,
   'filter' => ArrayHelper::map(Entidad::find()->asArray()->all(),'id', 'nombre'),
    filterWidgetOptions' => [
           'pluginOptions' => ['allowClear' => true],
    ],
    'filterInputOptions' => ['placeholder' => 'Selección'],


text:
Q: Creating stored procedure for multiple insert and alter table queries $link->query("DROP TABLE IF EXISTS table2");
$link->query("CREATE TABLE table2 (newcol BIGINT UNSIGNED  PRIMARY KEY)");
$result=$link->query("select col1 from table1");
while($data=$result->fetch_array(MYSQL_ASSOC))
{

    $link->query("insert into table2 (newcol) values($data['col1']);
    $link->query(""ALTER TABLE table2 ADD  `".$data['col1']."` BIGINT DEFAULT 0"");
  }

What Iam trying to do is

*

*Create a table "table2" with one column "newcol".

*select all the values of "col1" from  "table1" And

*for each value of col1 from table1
-insert the value into "newcol" of table2 And
-add a column named (value from col1 of table 1) into "table2"

The above code looks very neat and efficient in php , but the problem is it takes some amount of time .So I think its better to convert these into MySQL Stored procedure .Since I'm new to stored procedures , very much confused .Please help me guys.

A: Of course, I couldn't test it, but it is compiling fine on on my computer.
DELIMITER //

CREATE PROCEDURE `myProcedure` ()
BEGIN

    DECLARE _done BOOLEAN DEFAULT FALSE;
    DECLARE _myField BIGINT UNSIGNED DEFAULT 0;

    /* the cursor here is like your PDOStatement
    * it is used to fetch data */
    DEClARE _myReader CURSOR FOR
        SELECT `col1` FROM `table1`;

    /* it is not very elegant, but we need to throw an exception
    * to break the loop */
    DECLARE CONTINUE HANDLER
        FOR NOT FOUND SET _done = TRUE;

    DROP TABLE IF EXISTS `table2`;

    CREATE TABLE `table2` (
        `newcol` BIGINT UNSIGNED PRIMARY KEY
    );

    /* you open your PDOStatement */
    OPEN _myReader;

    /* myLoop is like a GOTO*/
    myLoop: LOOP

        /* $result->fetch_array(MYSQL_ASSOC)*/
        FETCH _myReader INTO _myField;

        /* if the no data exception had been thrown,
        * goto the end of the loop */
        IF _done = 1 THEN
            LEAVE myLoop;
        END IF;

        INSERT INTO `table2` (newcol) VALUES (_myField);

        ALTER TABLE `table2` ADD `_myField` BIGINT DEFAULT 0;

    END LOOP myLoop;

    /* close your PDO object */
    CLOSE _myReader;

END //

A: Jonathan Parent Lévesque  helped me a lot in figuring out how the looping inside stored procedures work and to get the overall structure for the stored procedure equivalent to the php code described in the question above.
Thanks Jonathan Parent Lévesque

But in his code Adding column name using a variable didn't work as expected.

Finally I figured it out

BEGIN

    DECLARE _done BOOLEAN DEFAULT FALSE;
    DECLARE _myField BIGINT DEFAULT 0;

    DEClARE _myReader CURSOR FOR
    SELECT id FROM `tags`;

    DECLARE CONTINUE HANDLER
        FOR NOT FOUND SET _done = TRUE;

    DROP TABLE IF EXISTS `tag_similarity`;

    CREATE TABLE `tag_similarity` (
        `tag` BIGINT UNSIGNED PRIMARY KEY
    );

    OPEN _myReader;

    myLoop: LOOP

        FETCH _myReader INTO _myField;

        IF _done = 1 THEN
            LEAVE myLoop;
        END IF;

        INSERT INTO `tag_similarity` (tag) VALUES (_myField);
        SET @sql = CONCAT('ALTER TABLE tag_similarity ADD `',_myfield,'` BIGINT DEFAULT 0');
      PREPARE stmt FROM @sql;
         EXECUTE stmt ;
         DEALLOCATE PREPARE stmt;
      END LOOP myLoop;

    CLOSE _myReader;

END


text:
Q: Issue with LIKE/OR operator in mysqli select statement in a prepared statement I'm creating a simple mysqli prepared statement that selects records from a database based on a search. I want to search two different columns in my database table using the same search term that was submitted to find any matches in either the heading or the content details. I was following the Accessing Databases with Object-Oriented PHP with David Powers video on Lynda.com and adapting that tutorial to fit my needs. I have most of it working, however I'm running into an issue when I add a second variable in my sql statement. The issue is that it is not returning any rows. . Here is my code:
$sql = "SELECT id, heading, details, layout FROM content WHERE ( details LIKE ? OR heading LIKE ? )";
    $stmt = $db->stmt_init();
    if (!$stmt->prepare($sql)) {
        $error = $stmt->error;
    } else {
        $stmt->bind_param('s', $var1, $var2);
        $var1 = '%' . $_GET['searchterm'] . '%';
        $var2 = '%' . $_GET['searchterm'] . '%';

If I remove the part in the SQL after the first placeholder, and remove "$var2" from $stmt->bind_param('s', $var1, $var2); then the query works fine. For example, the following returns the correct results:
    $sql = "SELECT id, heading, details, layout FROM content WHERE details LIKE ?";
    $stmt = $db->stmt_init();
    if (!$stmt->prepare($sql)) {
        $error = $stmt->error;
    } else {
        $stmt->bind_param('s', $var1);
        $var1 = '%' . $_GET['searchterm'] . '%';

Once I add in the second variable, I get no results returned. I have also tried the following but that returns 0 results as well:
    $stmt->bind_param('s', $var1, $var1);
    $var1 = '%' . $_GET['searchterm'] . '%';

I am brand new to prepared statements, so any suggestions or guidance would be appreciated. Thank you.

A: While I'm not very familiar with parameter binding, shouldn't you be specifying a type for each argument, i.e.
$stmt->bind_param('ss', $var1, $var2);


text:
Q: VSCode: Disable linting while typing Premise: When I use Visual Studio Code I want linting on save and I like intellisense.
Nonetheless I'm annoyed to no end by linting (aka error and warning messages in the form of "[ts/jshint]: here you're missing a semicolon") while I'm typing. They are absolutely useless (I never watch them), distracting, with all that flashy things appearing and disappearing at the bottom of the screen, and yesterday, when my pc was already slowed down for other reasons, it reduced the typing to a crawl.
Since I couldn't find a way to disable linting on typing, I went in the settings and disabled mostly of the typescript controls (since they were the worst offenders, useless to me, because I very rarely use a .ts, and anyway I use flow+jshint, which are more than enough). And, for some magical reasons, it even seemed to disable the linting while typing, leaving active only the one on save.
But then today, when I opened VSCode, the linting while typing restarted. The [ts] errors are very few now, but there are a few still produced by jshint. Flow, luckily, works as intended and only on save.
So, is there a way to disable the linting while typing, leaving active both intellisense, code completion suggestion and the linting on save?
Edit: I have enabled the following extensions:
HTML CSS Support 0.2.0,
html to javascript string 0.0.6,
JavaScript Booster 0.10.2,
jshint 0.10.20,
Sorting HTML and Jade attributes 2.1.0,
Todo Tree 0.0.116,
vscode-flow-ide 1.2.0
(momentarily I disabled intellisense, to see if it fixed the problem. It didn't)

A: As at Feb 2023, the jshint extension is deprecated:

This extension is deprecated. Use the ESLint extension instead.

ESLint has a setting that should achieve this:

eslint.run - run the linter onSave or onType, default is onType.


text:
Q: Spacy pattern exception case based on verb form I'm trying to make a spacy pattern that recognizes when a noun is followed by an adjective, which I have as follows:
pattern = [{'POS':'NOUN'}, {'POS':'ADJ'}]
however, I am trying to make a case exception where the adjective is not a participle form of a verb. My examples are in spanish, so I apologize.
For example, I want to find and retokenize things like 'institución educativa' but not 'institución comprometida', as 'comprometida' has the VerbForm_part=True in its tag.
I tried adding the following, but it only made the pattern stop working alltogether in cases like 'institución educativa':
pattern = [{'POS':'NOUN'}, {'OP':'!', 'TAG':'VerbForm_part'}, {'POS':'ADJ'}]
I also tried:
pattern = [{'POS':'NOUN'}, {'POS':'ADJ', 'TAG': not 'VerbForm_part'}]
In summary, I need to group together nouns followed by adjectives, but only SOME types of adjectives, and excluding others based on their TAG attribute 'VerbForm_part'
Is there any way to do this in Spacy? Does it support exceptions in its patterns?
Thank you!

A: I found a solution, which was by defining my own matcher and using it to retokenize when it found matches:
def my_matcher(doc):
    for i in range(0, len(doc)-1):
        if i < len(doc)-1:
            token = doc[i]
            token2 = doc[i+1]
            if token.pos_ == 'NOUN':
                if token2.pos_ == 'ADJ' and 'VerbForm_part' not in model.vocab.morphology.tag_map[token2.tag_].keys():
                    span = Span(doc, i, i+2)
                    print(span)
                    with doc.retokenize() as retokenizer:
                        retokenizer.merge(span)

my_matcher(doc)

If anyone can improve upoon this, or tell me if spacy supports this, it would be greatly appreciated!


text:
Q: Carrierwave delete file from controller The title says everything. I currently have a model concern with which I'm setting if a model can have attachments or not using include Attachable. So far so good.
Then, when I display the list of files attached to a particular model, I'm adding a link to delete it such as :
DELETE /posts/:post_id/attachments/:id(.:format)      attachments#destroy

For that purpose, I created an AttachmentsController with a destroy method. So I have 2 problems here. The first, how can I delete a file from this controller using Carrierwave (for delete the file itself and the table record)?
Second, since my attachable behavior gonna be plug in several model :
DELETE /posts/:post_id/attachments/:id(.:format)      attachments#destroy
DELETE /users/:user_id/attachments/:id(.:format)      attachments#destroy
...

How can I do in my AttachmentsController to delete a file depending on the associated model dynamically?
class Attachment < ActiveRecord::Base
  include Sluggable

  belongs_to :attachable, polymorphic: true
  mount_uploader :file, AttachmentUploader

  validates :name, presence: true, if: :file?
  validates :file, presence: true, if: :name?
end

class AttachmentsController < ApplicationController
  before_action :authenticate_user!

  def destroy
    // Don't know how to remove that file
    redirect_to :back
  rescue ActionController::RedirectBackError
    redirect_to root_path
  end
end

Hope I was clear.
Thanks
EDIT :
Ok I create a tweak on the params hash in order to get the associated object dynamically within AttachmentsController :
private
  def get_attachable_model
    params.each do |name, value|
      if name =~ /(.+)_id$/
        model = name.match(/([^\/.]*)_id$/)
        return model[1].classify.constantize
      end
    end
    nil
  end

A: Ok I finally found a solution myself. Here is my destroy method from AttachmentsController :
def destroy
  model, param = get_attachable_instance
  model_attach = model.find_by slug: params[param.to_sym]
  file         = model_attach.attachments.find_by slug: params[:id]
  file.destroy

  redirect_to :back
rescue ActionController::RedirectBackError
  redirect_to root_path
end

Not sure if it's the best way to go, but it does works


text:
Q: Re-linking external library when changing compiler in Qt I know this error has been addressed a lot, but until now I couldn't solve it for my project. I am doing a Qt application and want to compile it with the MSVC compiler instead of MinGW (here is the reason).
When I built the programm, I get loads of errors of this kind (just an excerpt):
error: LNK2019: unresolved external symbol sdot_ referenced in function "double __cdecl arma::blas::dot<double>(unsigned int,double const *,double const *)" (??$dot@N@blas@arma@@YANIPEBN0@Z)
error: LNK2019: unresolved external symbol sgemv_ referenced in function "void __cdecl arma::blas::gemv<double>(char const *,int const *,int const *,double const *,double const *,int const *,double const *,int const *,double const *,double *,int const *)" (??$gemv@N@blas@arma@@YAXPEBDPEBH1PEBN21212PEAN1@Z)

and this warning: LNK4272: library machine type 'x86' conflicts with target machine type 'x64'.
This thread suggests running qmake and re-building the project, but this didn't change anything.
From here and here and as the warning suggests, I figured I have to change the target machine for the linker. However, everything I found explained it in Visual Studio. How do I do this in Qt Creator?
I would be very thankful for any hints.
EDIT: So my program uses the armadillo library and this is the cause of the problems. When I change compilers, I need to compile or link this library in a new way (right?). This blog post summarized the problem in 2 points (the second point is the cause of the errors):

*

*MSVC cannot directly link to a dll -> we need a so-called "import library".

*Symbol Visibility: GCC/MinGW exports all symbols by default, MSVC exports no symbol by default.

So when using MSVC I have to link the import library (.lib) instead of the .dll in the case of MinGW. How can I do this in QtCreator?
This is my first time going deep with compilers and linkers, so I am very open for corrections, suggestions and solutions!


text:
Q: Progress bar exceeding max value Progress bar exceeds max value when using the ++ operate to increment the value. In the following code I have a record set which is 6004 in size when it comes round the loop it manages to get to 6006 even though I have put an if statment to trap when it reaches the value++ to reset the progress bar to zero and also hide the panel.
    invoiceRecord = (SageDataObject240.InvoiceRecord)_workSpace.CreateObject(Resources.InvoiceRecord);

    pnlProgress.Visible = true;
    progBarSelectInvoices.Value = 0;
    progBarSelectInvoices.Maximum = invoiceRecord.Count;

    List<EdiInvoice> selectedInvoices = new List<EdiInvoice>();
    EdiInvoice invoice;

    DateTime fromDate = chkEnableFromDatePicker.Checked ? dtpFrom.Value.Date : DateTime.MinValue;
    DateTime toDate = chkEnableToDatePicker.Checked ? dtpTo.Value.Date : DateTime.MaxValue;
    int invoiceCount = 0;
    int progressCount = 0;
  int progresbarValue = 0;
    int maxCount = invoiceRecord.Count + 1;
    while (invoiceRecord.MoveLast())
    {
        progresbarValue = progBarSelectInvoices.Value++;
        bool isPosted = (SDOHelper.Read<sbyte>(invoiceRecord, Resources.POSTED_CODE) == 1);

        if (isPosted)
        {
            int invoiceNo = SDOHelper.Read<int>(invoiceRecord, Resources.INVOICE_NUMBER);
            string invoiceCustomerReference = SDOHelper.Read<string>(invoiceRecord, Resources.ACCOUNT_REF);
            bool isValidCustomerReference = (invoiceCustomerReference == _selectedCustomer.Reference || _selectedCustomer.IncludeBranchInvoices && _selectedCustomer.BranchCodes.ContainsKey(invoiceCustomerReference));

            sbyte invoiceTypeCode = SDOHelper.Read<sbyte>(invoiceRecord, Resources.INVOICE_TYPE_CODE);
            bool isValidType = invoiceTypeCode >= 0 && invoiceTypeCode <= 5;

            string notes1 = SDOHelper.Read<string>(invoiceRecord, "NOTES_1");
            bool isExported = notes1.Length > 2 && notes1.Substring(0, 3).Equals("EDI", StringComparison.CurrentCultureIgnoreCase);

            DateTime invoiceDate = SDOHelper.Read<DateTime>(invoiceRecord, "INVOICE_DATE");
            bool isInDateRange = invoiceDate >= fromDate && invoiceDate <= toDate;

            if (isValidCustomerReference && isValidType && (!isExported || chkIncludeAlreadyExportedInvoices.Checked) && isInDateRange)
            {
                invoice = new EdiInvoice();
                invoice.Customer = string.Format("({0}), {1}", invoiceCustomerReference, SDOHelper.Read<string>(invoiceRecord, Resources.NAME));
                invoice.InvoiceNumber = invoiceNo;
                invoice.Date = SDOHelper.Read<DateTime>(invoiceRecord, "INVOICE_DATE").ToString("dd/MM/yyyy");
                invoice.Type = GetInvoiceOrCredit(invoiceTypeCode);
                invoice.DeliveryAddress = SDOHelper.Read<string>(invoiceRecord, Resources.DEL_ADDRESS_1);
                invoice.Nett = SDOHelper.Read<double>(invoiceRecord, Resources.BASE_TOT_NET) + SDOHelper.Read<double>(invoiceRecord, Resources.BASE_CARR_NET);
                invoice.Vat = SDOHelper.Read<double>(invoiceRecord, Resources.BASE_TOT_TAX) + SDOHelper.Read<double>(invoiceRecord, Resources.BASE_CARR_TAX);

                selectedInvoices.Add(invoice);
            }
        }
           invoiceCount = invoiceRecord.Count;
           progressCount = progBarSelectInvoices.Value;
        if (progressCount++ == maxCount || progressCount==invoiceCount )
        {
            progBarSelectInvoices.Value = 0;
            progressCount = 0;
            pnlProgress.Visible = false;
            Application.DoEvents();
        }
        else

        {
            progBarSelectInvoices.Value++;
            progressCount= progBarSelectInvoices.Value++;
        }
        Application.DoEvents();

A: Hopefully this will help you to figure this out if we walk through what is happening here. Let's examine what happens when you are entering the 6003rd loop.
I will assume that progBarSelectInvoices.Value == 6002 at this point:
What does this line do?
progresbarValue = progBarSelectInvoices.Value++;

At the end of it. progresbarValue == 6004 and progBarSelectInvoices == 6003
progresbarValue is never used again so it could probably just be dumped, but not sure
Then we skip down and do a bunch of other things and hit this line:
progressCount = progBarSelectInvoices.Value;

Here progressCount == 6003  and then we do this:
if (progressCount++ == maxCount || progressCount==invoiceCount)

So what happens here, if maxCount == 6004 than the first part of this if is false BUT now progessCount == 6004. We know that if maxCount is 6004, then invoiceCount == 6003 (from this line maxCount = invoiceRecord.Count + 1;), but now progressCount == 6004 so this is also false.  This means we execute the else part.
progBarSelectInvoices.Value++;
progressCount= progBarSelectInvoices.Value++;

What does this do?  Well, in the first line we increment progBarSelectInvoices.Value so that is now 6004.  Then we move to the second line where we set progressCount to 6004, but then we increment the value of the progress bar again, so it is now 6005.  Then we go back to the top of the loop and the first thing we do is increment the progress bar again, which brings us to 6006.
Personally, I try to avoid doing either pre or post increment statements in if statements as it can make the code hard to read.  In this case, I would definitely advise against it.
How to fix
One way to fix this - if you know for sure you only have 6004 records and so you will only execute that while loop 6004 times, then just do this (note, I am recommending that you move the increment to the end of the while loop so that you are actually done the work before indicating progress)
while (invoiceRecord.MoveLast())
{
    // All your other code here
    progBarSelectInvoices.Value++;

If you want to be sure you don't exceed the max value you could just add a quick check
while (invoiceRecord.MoveLast())
{
    // All your other code here
    if (progBarSelectInvoices.Value < progBarSelectInvoices.Maximum)
        progBarSelectInvoices.Value++;

You can then do away with the if/else business at the end of the loop that is checking the maxCount and either resetting the progress bar or incrementing it.
Side note
From the presence of the line Application.DoEvents() and the fact that you are not getting an exception when incrementing the progress bar value, I get the sneaky suspicion that you are executing this loop in the UI thread.  Whenever you find yourself needing to add Application.DoEvents() in your event handler code, it is a very good time to ask yourself "How can I move this work out of the UI thread?"  Calling Application.DoEvents() is almost never a good idea.  See here and here
You should move that code into a background thread.  The only thing to keep in mind is that you would need to use an invoke call to update the progress bar value.


text:
Q: How to design this sortable tree view in swiftui? I want to design this view in swiftui but i am unable to create the leading line bar.
I am using recursive call to call the child views but the line is not extending as per requirement.
Required
What i am getting


text:
Q: How to use Google fonts without internet connection Is there any way to download Google fonts and link them offline on localhost web page?

A: Try downloading the font folder and add this to your projectFolder and use font faces.
Check this https://answers.themler.io/articles/9064/how-to-use-google-fonts-locally

A: thanks for help
but i got it by help of this site https://transfonter.org/
then put all genereated woff files in same folder of css file then append font face to  my css file
then use font normally as described by transfonter.org


text:
Q: \marginpar trick: not considered as float I've found on the net a useful trick that does exactly what the title says. This is the code:
\newcommand{\mymarginpar}[1]{%
\vadjust{\smash{\llap{\parbox[t]{\marginparwidth}{#1}\kern\marginparsep}}}}

It works fine, the only problem is that the note is created in the left margin. Is it possible to put it in the right margin instead?

A: An equivalent definition for right-side margin paragraphs would be:
\newcommand{\lmarginpar}[1]{%
  \vadjust{\smash{\llap{\parbox[t]{\marginparwidth}{\strut#1}\kern\marginparsep}}}}
\newcommand{\rmarginpar}[1]{%
  \vadjust{\smash{\rlap{\hspace*{\dimexpr\linewidth+\marginparsep}\parbox[t]{\marginparwidth}{\strut#1}}}}}

\lmarginpar sets a left-overlap of a paragraph of width \marginparwidth plus a right-hand gap of \marginparsep. \rmarginpar sets a left-hand gap of \linewidth+\marginparsep followed by a paragraph of width \marginparwidth.


text:
Q: Is a spotify app always running once added by a user Once an app has been added by a user is it always running in the background once the user has opened Spotify? So are the event listeners being fired even if the app hasn't been clicked on since opening Spotify?
Many thanks
Matt

A: Your app is loaded when the user opens it. It doesn't matter if it is through the App Finder, by typing the apps' URI into the search box or reaching it through http://open.spotify.com/app/ (e.g. http://open.spotify.com/app/soundrop/).
It will stay loaded as long as it is open or has started playback. For example, if a user opens your app, starts playback using a List view component in the app, and switches app to Discover without starting to play music from there, your app will still be loaded and able to listen to events.
Your app will unload about 30 seconds after the user has navigated away from it without app playback, or 30 seconds after another app has taken over playback.


text:
Q: How to automatically inherit mixin generic type in self-types? How do I inherit generic type from parent mixin type? For example I have a trait Foo with one generic type A:
trait Foo[A] {
  def value: A
}

I have a class User that uses Foo[String], like:
class User extends Foo[String] {
  override def value: String = ???
}

Everything works fine. Now, I want to add a trait Bar[A] with self-type of Foo[A].
trait Bar[A] { self: Foo[A] =>
  def anotherValue: A
}

If I want to use Bar in User, I'll need to do:
class User extends Foo[String] with Bar[String] {
  override def value: String = ???
  override def anotherValue: String = ???
}

Is there anyway that I can simplify User to this? (Bar automatically infers type from corresponding Foo.)
class User extends Foo[String] with Bar

A: You can define intermediate trait
trait UserLike[A] extends Foo[A] with Bar[A]

class User extends UserLike[String] {
  override def value: String = ???
  override def anotherValue: String = ???
}

You can define a macro annotation but this would be an overkill
@extendsBar
class User extends Foo[String] {
  override def value: String = ???
  override def anotherValue: String = ???
}

//scalac: {
//  class User extends Foo[String] with Bar[String] {
//    def <init>() = {
//      super.<init>();
//      ()
//    };
//    override def value: String = $qmark$qmark$qmark;
//    override def anotherValue: String = $qmark$qmark$qmark
//  };
//  ()
//}

import scala.annotation.StaticAnnotation
import scala.language.experimental.macros
import scala.reflect.macros.blackbox

class extendsBar extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro ExtendsBarMacro.impl
}

object ExtendsBarMacro {
  def impl(c: blackbox.Context)(annottees: c.Tree*): c.Tree = {
    import c.universe._
    annottees match {
      case q"$mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self => ..$stats }" :: tail =>
        val fooArg = parents.collectFirst {
          case tq"Foo[$t]" => t
        }.getOrElse(c.abort(c.enclosingPosition, "class must extend Foo"))
        val parents1 = parents :+ tq"Bar[$fooArg]"
        q"""
           $mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents1 { $self => ..$stats }
           ..$tail
        """
      case _ =>
        c.abort(c.enclosingPosition, "annottee must be a class")
    }
  }
}

This would be more flexible if A were a type member rather than type parameter
trait Foo {
  type A
  def value: A
}

trait Bar { self: Foo =>
  def anotherValue: A
}

class User extends Foo with Bar {
  override type A = String
  override def value: String = ???
  override def anotherValue: String = ???
}


text:
Q: How to install jupyterlab extension behind corporate proxy? I am trying to install jupyterlab extension behind a corporate proxy.
I have manged to configure the npm config using following commands:
npm config set proxy http://username:password@host:port
npm config set https-proxy http://username:password@host:port

And it seems package has been downloaded however I am still getting following error:
Failed to fetch package metadata for 'jupyterlab-plotly': URLError(ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))
How to solve this issue?


text:
Q: How To Associate A Custom Value With Each Address Book Contact I want to have a boolean value associated with all of my contacts in the address book.  This boolean value will indicate whether a contact is part of my team or not.  If there is no boolean value associated with the contact, the value would default to 'false'.  I also want to show all my contacts in a list view with a check mark associated with the boolean value (defaulting to 'false' if there is no value).
Question: What would be a good approach to store the boolean value associated with each contact in a manner that I can create a cursor that has all the contacts and the boolean value associated with each contact.
Since there are a lot of contacts, I want to make sure that the time taken to create this cursor (to be shown in the list view) is as less as possible.  I have been looking at the Contacts content provider but so far I have not been able to come up with a good approach.
Thanks!
Prasanna


text:
Q: Configure Grafana datasource to use multiple ElasticSearch nodes In order to increase the availability of Grafana monitoring is there a way to configure multiple ElasticSearch nodes in one datasource and let Grafana 'load balance' between them, or configure explicit primary and failover nodes?
I'm using a 3-node ElasticSearch cluster to store monitoring data, however during a rolling update (or if a node fails) Grafana will error if it can't connect.  I have spread the config for different indexes across instances, however 1/3 of the dashboards will typically stop working if a node fails so its not ideal.

A: It is not possible to configure multiple elasticsearch nodes as a datasource on grafana, there is a feature request for it but it was not implemented yet.
One way to solve this is to start another elasticsearch node configured only as a coordinating node and then configure this node as the data source on grafana.


text:
Q: Sending a image to servlet in java how to get the image in servlet I am sending a image from android phone to server which is a servlet I am using the HttpClient and HttpPost for this and ByteArrayBody for storing the image before sending.
how do i extract the image from the post request in Servlet.
Here is my code for sending the post request
String postURL = //server url;

HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(postURL);

ByteArrayBody bab = new ByteArrayBody(imageBytes,"file_name_ignored");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("source", bab);
postRequest.setEntity(reqEntity);

HttpResponse response = httpClient.execute(postRequest);

A: Use something like commons fileupload.
There are examples in the Apache docs, and all over the web.

A: Servlet 3.0 has support for reading multipart data. MutlipartConfig support in Servlet 3.0
If a servelt is annotated using @MutlipartConfig annotation, the container is responsible for making the Multipart parts available through

*

*HttpServletRequest.getParts()

*HttpServletRequest.getPart("name");

A: use http://commons.apache.org/fileupload/using.html
private DiskFileItemFactory fif = new DiskFileItemFactory();

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

    if(!isMultipart)
        throw new ServletException("upload using multipart");

    ServletFileUpload upload = new ServletFileUpload(fif);
    upload.setSizeMax(1024 * 1024 * 10 /* 10 mb */);
    List<FileItem> items;
    try {
        items = upload.parseRequest(req);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }

    if(items == null || items.size() == 0)
        throw new ServletException("No items uploaded");

    FileItem item = items.get(0);
    // do something with file item...
}


text:
Q: How to maximize the expression $xy(1-2x-3y)$ when $\{x>0, y>0, 2x+3y<1\}$ Find the greatest value of the following expression $xy(1-2x-3y)$ when $x>0$,$y>0$,$2x+3y<1$ and also determine in each case the value of the variables for which the greatest value is attained.
I have tried to solve it using AM-GM inequality considering the positive real numbers $xy$,$(1-2x-3y)$. What should I do after that? Or suggest any other way of solving the problem.

A: We have a one-line solution that can be obtained using the AM - GM inequality :
$$\begin{align}&\left(1-2x-3y\right)+2x+3y\\
&\geq 3\sqrt [3]{6xy(1-2x-3y)}\\
\implies &xy\left(1-2x-3y\right)\leq\frac {1}{162}\thinspace .\end{align}$$
The equality occurs iff, when
$$\begin{align}&2x=3y=1-(2x+3y)\\
\implies &2x=1-4x\\
\implies &\left(x,y\right)=\left (\frac 16, \frac 19\right)\thinspace .\end{align}$$

In this answer, we provide a  alternative method that does not use some specific inequalities and known calculus tools.
Let $0<a=2x+3y<1$ and $y=\frac {a-2x}{3}$, then we have :
$$\begin{align}f(x,y):&=xy(1-2x-3y)\\
&=xy(1-a)\\
&=\frac {a-1}{24}\left(4x-a\right)^2+\frac {a^2-a^3}{24}\end{align}$$
Since $a-1<0$, the maximum occurs at $x=\frac a4,\thinspace y=\frac a6 \thinspace ,$ which makes $4x-a=0\thinspace.$ Thus, we need to find the $\max\{a^2-a^3\mid 0<a<1\}\thinspace.$
Using the method implemented here , we observe that :
$$\begin{align}\frac {4}{27}-\left(a^2-a^3\right)&=\frac {1}{27}(3a+1)(3a-2)^2\geq 0\end{align}$$
Therefore, we obtain :
$$\begin{align}xy(1-2x-3y)&\leq \frac {4}{27\cdot 24}\\
&=\frac {1}{162}\thinspace .\end{align}$$
where $\thinspace x,y>0$ and $2x+3y<1\thinspace .$
Equality holds iff, when $a=\frac 23\thinspace.$ This yields :
$$\begin{align}(x,y)=\left(\frac a4,\thinspace \frac a6\right)=\left (\frac 16, \frac 19\right)\thinspace .\end{align}$$
This completes the answer.


text:
Q: Replacing the values of a particular number of columns with zeroes I have a dataframe with 9 columns. I need to replace all values of columns 3-9 with zeroes and leave the values in other columns as they are. Any ideas?

A: you can simply use iloc which has following syntax:
dataframe_name.iloc[rows, columns]
As you want to replace all values of columns 3-9 with zeroes and leave the values in other columns as they are:
dataframe_name.iloc[: , 3:10] = 0

Here we have used slicing. for rows I have used ':' which means all the rows and for the columns I have used '3:10' which means all the columns from index 3 to 9 both inclusive


text:
Q: C# Synchronize two objects through events I have 2 objects. Foo and Bar in two different threads. Now I want to raise an event in Foo but in the thread of Bar.
and how can I use SynchronizationContext.Current for that?

A: Neither "Foo" nor "Bar" really have threads... you would need an external message-pump mechanism to push messages between threads, such as is provided in winforms (Control.Invoke) and WPF (Dispatcher). Alternatively, something like a (synchronized) producer/consumer queue would suffice if you don't mind one of the threads being devoted to waiting (passively) for messages.
Unless you have written your own sync-context, it is impossible for us to say what SynchronizationContext.Current will be; in many cases it is null.
Can you add more context to the problem?

A: Synchronization context is used more for Silverlight apps, isn't it?  If you need different operations to run in the same thread, launch each operation with SynchronizationContext.Send().
(hopefully that when you say you want to run it in the thread of Bar, that you're referring the the UI thread that the synchronization context will run any Send()d callbacks in.  If thats the case, only the event from Foo needs to be Send()d).

A: The only way I can think of is to use the InvokeRequired() and BeginInvoke() methods that are built in to UI elements to help you ensure that all code modifying a UI element is executed from the same thread used to create the element.
... Before Foo starts, in Bar, create an instance of some UI Element, say a label...  Then  When the event is raised in Foo,  in the event handler,  call BeginInvoke() on that UI element,  That will guarantee that the code that runs will be run on Bar...
But WHy do you want to do this ?


text:
Q: In Oracle 11g, what permissions would I need to `SELECT * FROM V$TRANSPORTABLE_PLATFORM;`? I am using AWS DMS to migrate an on-site Oracle 11g database to an Amazon RDS for Oracle DB instance of the same major version. I recently received this error:
2019-11-27T18:54:08 [SOURCE_CAPTURE ]E: Cannot execute SQL statement 'select tp.endian_format, tp.platform_name from v$database d, v$transportable_platform tp where d.platform_id = tp.platform_id'. OCI status '-1' [1020401] (oradcdc_redoutil.c:976)
2019-11-27T18:54:08 [TASK_MANAGER ]E: OCI error 'ORA-00942: table or view does not exist'; Cannot execute SQL statement 'select tp.endian_format, tp.platform_name from v$database d, v$transportable_platform tp where d.platform_id = tp.platform_id'. OCI status '-1'; Error executing source loop; Stream component failed at subtask 0, component st_0_XGQVEPQ6RSAXZT44XOZF7ERABI ; Stream component 's

My normal administrative schema can SELECT * FROM V$TRANSPORTABLE_PLATFORM; without issue, however, my new 'migration' schema cannot. Both have SELECT ANY TABLE privileges which, as described in Grant Select on All VIEWS [current and future] in Schema X, will allow the user to query any table or view in any schema in the database.
What permission am I missing in my migration schema? How does V$TRANSPORTABLE_PLATFORM differ from table/view objects in the database? What query could I run in order to obtain the type of V$TRANSPORTABLE_PLATFORM or any other database object?

A: A few things you may want to try:

*

*Grant SELECT_CATALOG_ROLE to allow SELECT on system views

*Add a manual GRANT to V_$TRANSPORTABLE_PLATFORM since V$TRANSPORTABLE_PLATFORM will reference that table

*Ensure the schema is not ambiguous by adding SYS.


text:
Q: How to redirect from subdomain to url in domain using AWS Route53 Need redirect from blog.example.com to www.example.com/blog using AWS Route53, preserving queries.
Also need to set up smart redirects i.e. blog.example.com/articles/slug to www.example.com/blog/slug
Need to avoid double redirects too.

A: This isn't possible with Route53.
I would recommend instead using an Application Load Balancer. You can create rules that match based on host and path, and route to specific target groups.

A: Managed to do this with pointing subdomain to Load Balancer in Route53 (A record) and Nginx configuration:
server {
    server_name blog.example.com;
    rewrite ^/articles/(.*) https://www.example.com/blog/$1 permanent;

    return 301 https://www.example.com/blog/blog$request_uri;
}


text:
Q: Meaning of lag parameter in PST? In the pmine() function in PST you can use lags. What is this lag? Does it mean that it ignores the lag first positions in the sequence? Or does it mean that you allow for lags within the subsequences? From the documentation it is hard to understand what is actually meant by lag.

A: The lag parameter when searching patterns with the pmine() function means that we look only for patterns that are preceded by at least lag elements, i.e., for patterns with a context of length at least equal to lag.  The lag first positions will not belong to find patterns, but they could belong to their context. So, they are not ignored.


text:
Q: How to install pip in RHEL6 to use "virualenv" with python 2.6.6 Background:
Robot scripts are developed on Python 3.* and they can only be executed in python3.
Problem:
We have RHEL6 machine which uses python 2.6.6 which cannot be updated.
Prepared Solution :
We are trying to enable the use of virtualenv in a RHEL6 machine so that we can execute the robot scripts in virtual environment with a different python version, We are facing issues with installation of pip in RHEL6 machine.

A: You need pip/setuptools from here: https://bootstrap.pypa.io/2.6/ and you need a very old version of virtualenv.
Download get-pip.py and run
sudo python2.6 get-pip.py

virtualenv 15.2.0 seems to be the last version that supports Python 2.6. Try
python2.6 -m pip install 'virtualenv==15.2.0'

or
python2.6 -m pip install 'virtualenv<16.0'

with you fresh pip.


text:
Q: Tensorflow does not follow the LEGB-rule of python? I am going through a tensorflow implementation of the inception network and come across the following implementation of the inception module. The first element of the inception module is the conv11 which will be stacked with conv33 and conv55 to form the output of the inception module. Prior to the conv33 and conv55 operations, the input of the inception module goes through a 1 x 1 filter operation (called conv_33_reduce and conv_55_reduce) to reduce the depth (bottleneck operation)
@add_arg_scope
def inception_layer(conv_11_size, conv_33_reduce_size, conv_33_size,
                    conv_55_reduce_size, conv_55_size, pool_size,
                    layer_dict, inputs=None,
                    bn=False, wd=0, init_w=None,
                    pretrained_dict=None, trainable=True, is_training=True,
                    name='inception'):

    if inputs is None:
        inputs = layer_dict['cur_input']
    layer_dict['cur_input'] = inputs

    arg_scope = tf.contrib.framework.arg_scope
    with arg_scope([L.conv], layer_dict=layer_dict, pretrained_dict=pretrained_dict,
                   bn=bn, nl=tf.nn.relu, init_w=init_w, trainable=trainable,
                   is_training=is_training, wd=wd, add_summary=False):

        conv_11 = L.conv(filter_size=1, out_dim=conv_11_size,
                         inputs=inputs, name='{}_1x1'.format(name))

        L.conv(filter_size=1, out_dim=conv_33_reduce_size,
               inputs=inputs, name='{}_3x3_reduce'.format(name))

The input of the conv_33 should be 'layer_dict' from the output of the above L.conv which is the bottleneck operation to reduce the depth of the tensor; however, the output of the above L.conv is not defined
        conv_33 = L.conv(filter_size=3, out_dim=conv_33_size,
                         name='{}_3x3'.format(name))

        L.conv(filter_size=1, out_dim=conv_55_reduce_size,
               inputs=inputs, name='{}_5x5_reduce'.format(name))

Similarly, the output of the above L.conv is not defined for conv_55 operation
        conv_55 = L.conv(filter_size=5, out_dim=conv_55_size,
                         name='{}_5x5'.format(name))

        L.max_pool(layer_dict=layer_dict, inputs=inputs, stride=1,
                   filter_size=3, padding='SAME', name='{}_pool'.format(name))
        convpool = L.conv(filter_size=1, out_dim=pool_size,
                          name='{}_pool_proj'.format(name))

        output = tf.concat([conv_11, conv_33, conv_55, convpool], 3,
                           name='{}_concat'.format(name))
        layer_dict['cur_input'] = output
        layer_dict[name] = output
    return output

And here is the code for the L.conv which defines the convolution operation. The output of the L.conv is a dictionary called 'layer_dict' which should be fed into the next L.conv as an input. However, in the above method of 'inception_layer', the output of the L.conv is not defined for both conv_33 and conv_55 operation. My question is since layer_dict is a local object, how does the following conv_33 and conv_55 get access to the updated layer_dict?
@add_arg_scope
def conv(filter_size,
         out_dim,
         layer_dict,
         inputs=None,
         pretrained_dict=None,
         stride=1,
         dilations=[1, 1, 1, 1],
         bn=False,
         nl=tf.identity,
         init_w=None,
         init_b=tf.zeros_initializer(),
         use_bias=True,
         padding='SAME',
         pad_type='ZERO',
         trainable=True,
         is_training=None,
         wd=0,
         name='conv',
         add_summary=False):
    if inputs is None:
        inputs = layer_dict['cur_input']
    stride = get_shape4D(stride)
    in_dim = inputs.get_shape().as_list()[-1]
    filter_shape = get_shape2D(filter_size) + [in_dim, out_dim]

    if padding == 'SAME' and pad_type == 'REFLECT':
        pad_size_1 = int((filter_shape[0] - 1) / 2)
        pad_size_2 = int((filter_shape[1] - 1) / 2)
        inputs = tf.pad(
            inputs,
            [[0, 0], [pad_size_1, pad_size_1], [pad_size_2, pad_size_2], [0, 0]],
            "REFLECT")
        padding = 'VALID'

    with tf.variable_scope(name):
        if wd > 0:
            regularizer = tf.contrib.layers.l2_regularizer(scale=wd)
        else:
            regularizer=None

        if pretrained_dict is not None and name in pretrained_dict:
            try:
                load_w = pretrained_dict[name][0]
            except KeyError:
                load_w = pretrained_dict[name]['weights']
            print('Load {} weights!'.format(name))

            load_w = np.reshape(load_w, filter_shape)
            init_w = tf.constant_initializer(load_w)

        weights = tf.get_variable('weights',
                                  filter_shape,
                                  initializer=init_w,
                                  trainable=trainable,
                                  regularizer=regularizer)
        if add_summary:
            tf.summary.histogram(
                'weights/{}'.format(name), weights, collections = ['train'])

        outputs = tf.nn.conv2d(inputs,
                               filter=weights,
                               strides=stride,
                               padding=padding,
                               use_cudnn_on_gpu=True,
                               data_format="NHWC",
                               dilations=dilations,
                               name='conv2d')

        if use_bias:
            if pretrained_dict is not None and name in pretrained_dict:
                try:
                    load_b = pretrained_dict[name][1]
                except KeyError:
                    load_b = pretrained_dict[name]['biases']
                print('Load {} biases!'.format(name))

                load_b = np.reshape(load_b, [out_dim])
                init_b = tf.constant_initializer(load_b)

            biases = tf.get_variable('biases',
                                 [out_dim],
                                 initializer=init_b,
                                 trainable=trainable)
            outputs += biases

        if bn is True:
            outputs = batch_norm(outputs, train=is_training, name='bn')

        layer_dict['cur_input'] = nl(outputs)
        layer_dict[name] = layer_dict['cur_input']
        return layer_dict['cur_input']


text:
Q: Ошибка: requests.exceptions.SSLError: HTTPSConnectionPool(host='elibrary.ru', port=443): Max retries exceeded with url: /title_about.asp?id=8720 Пытаюсь получить код страницы:
        response = requests.get('https://elibrary.ru/title_about.asp?id=8720', verify=certifi.where())
        try:
            doc = response.content.decode('utf-8', errors='ignore')
        except:
            doc = response.content.decode('cp1251', errors='ignore')

Но программа выдаёт ошибку:
Traceback (most recent call last):
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 343, in _make_request
    self._validate_conn(conn)
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 849, in _validate_conn
    conn.connect()
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connection.py", line 356, in connect
    ssl_context=context)
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\util\ssl_.py", line 359, in ssl_wrap_socket
    return context.wrap_socket(sock, server_hostname=server_hostname)
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\ssl.py", line 412, in wrap_socket
    session=session
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\ssl.py", line 850, in _create
    self.do_handshake()
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\ssl.py", line 1108, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\adapters.py", line 445, in send
    timeout=timeout
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 638, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\util\retry.py", line 398, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='elibrary.ru', port=443): Max retries exceeded with url: /title_about.asp?id=8720 (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)')))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/ISagitova/Desktop/Py/parsJurnArticle.py", line 17414, in <module>
    g = get_write()
  File "C:/Users/ISagitova/Desktop/Py/parsJurnArticle.py", line 497, in get_write
    response = requests.get('https://elibrary.ru/title_about.asp?id=8720', verify=certifi.where())
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\api.py", line 72, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\sessions.py", line 512, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\sessions.py", line 622, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\ISagitova\AppData\Local\Programs\Python\Python37-32\lib\site-packages\requests\adapters.py", line 511, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='elibrary.ru', port=443): Max retries exceeded with url: /title_about.asp?id=8720 (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)')))

Подскажите, пожалуйста, как решить проблему. Заранее благодарна за ответ


text:
Q: attaching windows service to skype Public Api I need to capture the Skype Event through Windows Service.Skype like Call etc.
I am trying to register the Skype Notification but it failing.
Whether Windows Service allows Registering Skype Event or not?If not how can we achieve this.

A: Windows service in general allows to register events from Skype but first you must define:
1) Are you going to use Skype4COM (Desktop API) to communicate with one of standard Skype clients.
2) OR are you going to build your own Skype client using SkypeKit SDK?
The case 1 allows exchanging data only if some Skype client is running
but case 2 can work even while no user is logged in but it requires much more effort.

A: it is not possible to have Skype4COM in windows service


text:
Q: Estéreo Visão no Matlab Olá!!
Estou tentando executar um algoritmo em Matlab que usa apenas funções próprias do Matlab. O programa deveria inicialmente fazer a calibração das câmeras, extrair os seus parâmetros e gerar um mapa de disparidade através de duas imagens retificadas com os parâmetros obtidos na calibração. Contudo quando eu executo o programa gera um erro que eu não sei como resolver. Eu uso a versão 2015a com a toolbox "Computer Vision System" instalada e para a calibração estou usando um tabuleiro quadriculado. Abaixo está o algoritmo que estou usando:
%Carrega os pares de imagens para calibração
ParesdeImagens = 11;
arquivoImagens1 = cell(1,ParesdeImagens);
arquivoImagens2 = cell(1,ParesdeImagens);
imagemDir = fullfile('C:','Users','carlo','Documents','Iniciacao','Matlab','Principal');
for i = 1:ParesdeImagens
   arquivoImagens1{i} = fullfile(imagemDir,  sprintf('left%02d.jpg', i));
   arquivoImagens2{i} = fullfile(imagemDir,  sprintf('right%02d.jpg', i));
end

%Realiza a detecção dos cantos no tabuleiro
[imagePoints, boardSize, pairsUsed] = detectCheckerboardPoints(arquivoImagens1, arquivoImagens2);

%Exibe os pontos identificados da camera esquerda
arquivoImagens1=arquivoImagens1(pairsUsed);
figure;
for i= 1:numel(arquivoImagens1)
   I= imread(arquivoImagens1{i});
   subplot(3,4,i);
   imshow(I);
   hold on;
   plot(imagePoints(:,1,i,1),imagePoints(:,2,i,1),'*-g');
end

%Exibe os pontos identificados da camera direita
arquivoImagens2=arquivoImagens2(pairsUsed);
figure;
for i= 1:numel(arquivoImagens2)
   I= imread(arquivoImagens2{i});
   subplot(3,4,i);
   imshow(I);
   hold on;
   plot(imagePoints(:,1,i,2),imagePoints(:,2,i,2),'*-g');
end

%Computa as coordenadas reais do tabuleiro
squareSize = 29; % milimetros
worldPoints = generateCheckerboardPoints(boardSize, squareSize);

%Computa os parâmetros estéreos
stereoParams = estimateCameraParameters(imagePoints, worldPoints);

%Avalia a precisão da calibração
figure;
showReprojectionErrors(stereoParams);

% Lê um par de imagens
I1 = imread('esquerda.jpg');
I2 = imread('direita.jpg');

%Retifica as imagens
[J1, J2] = rectifyStereoImages(I1, I2, stereoParams);

%Exibe as imagens antes da retificação
figure;
imshow(stereoAnaglyph(I1, I2));
title('Antes da Retificacao');

%Exibe as imagens depois da retificação
figure;
imshow(stereoAnaglyph(J1, J2));
title('Depois da Retificacao');

%Gera o mapa de disparidade
disparityMap = disparity(rgb2gray(J1), rgb2gray(J2));
figure;
imshow(disparityMap, [0, 64]);
colormap('jet');
colorbar;
title('Mapa de Disparidade');

Quando eu executo o programa recebo a seguinte mensagem de erro:
Operands to the || and && operators must be convertible to logical scalar values.

Error in vision.internal.calibration.CameraParametersImpl/getValidBounds (line 883)
        if isempty(coder.target) && (left > right || top > bot)

Error in vision.internal.calibration.CameraParametersImpl/computeUndistortBounds (line 785)
                [xBounds, yBounds] = getValidBounds(this, undistortedMask, ...

Error in vision.internal.calibration.StereoParametersImpl/computeOutputBounds (line 371)
        [xBoundsUndistort1, yBoundsUndistort1] = ...

Error in vision.internal.calibration.StereoParametersImpl/computeRectificationParameters (line 271)
        [xBounds, yBounds] = computeOutputBounds(this, imageSize, ...

Error in vision.internal.calibration.StereoParametersImpl/rectifyStereoImagesImpl (line 190)
            [H1, H2, Q, xBounds, yBounds] = ...

Error in rectifyStereoImages (line 99)
[rectifiedImage1, rectifiedImage2] = rectifyStereoImagesImpl(stereoParams, ...

Error in new_project (line 55)
[J1, J2] = rectifyStereoImages(I1, I2, stereoParams);

Neste caso, foram reconhecidos corretamente os cantos de todas as imagens de ambos os pares, e foi estimado um erro de 4 pixels. Para a aquisição de imagens eu usei uma distância de 10 cm entre as câmeras e me certifiquei que ambas estavam paralelas e alinhadas corretamente. Todas as imagens foram obtidas por uma câmera de celular ( Nokia Lumia 520 ).
Aqui está uma imagem do tabuleiro que usei para calibrar o par estéreo:

Se alguém tiver alguma idéia do que pode estar acontecendo e puder me auxiliar seria de grande ajuda!
Obrigado.


text:
Q: background color overflow out of border radius I was trying to make the border-radius: 20px; but I don't know why the background color overflowed out of the border. Please help me how to solve this one.
Here is the sample codes. Thank you.
.bar{
    padding: 20px;
}

.barContainer{
    width: 50%;
    background-color: #cccccc;
    border: 1px solid #111;
    border-radius: 20px
}

.per {
    text-align: right;
    padding: 10px 0;
    color: #111;

}

.html {width: 90%; background-color: #f44336;}
.css {width: 80%; background-color: #2196F3;}
.js {width: 65%; background-color: #FEF70F;}
.java {width: 60%; background-color: #808080;}
.php {width: 60%; background-color: #008631;}

HTML

90%

CSS

80%

JavaScript

50%

Java

50%

PHP and MySQL

50%

A: Add overflow: hidden to the .barContainer rule :

.bar{
    padding: 20px;
}

.barContainer{
    width: 50%;
    background-color: #cccccc;
    border: 1px solid #111;
    border-radius: 20px;
    overflow: hidden;
}

.per {
    text-align: right;
    padding: 10px 0;
    color: #111;

}

.html {width: 90%; background-color: #f44336;}
.css {width: 80%; background-color: #2196F3;}
.js {width: 65%; background-color: #FEF70F;}
.java {width: 60%; background-color: #808080;}
.php {width: 60%; background-color: #008631;}

HTML

90%

CSS

80%

JavaScript

50%

Java

50%

PHP and MySQL

50%

A: Try add in overflow: hidden in barContainer:
.barContainer{
    width: 50%;
    background-color: #cccccc;
    border: 1px solid #111;
    border-radius: 20px;
    overflow: hidden;
}