text:
Q: ipconntrack suddenly became toooo large My server just had a 2 minute downtime. It was serving around 400requests/second. The only odd thing I found in the munin reports was:
http://monitor.wingify.com/munin/visualwebsiteoptimizer.com/lb1.visualwebsiteoptimizer.com-fw_forwarded_local.html
How should I interpret it and what exactly was the issue and how to make sure this doesnt happen again.
There is nothing unusual in the logs. What and how should I debug.

A: In your syslog do you see:
ip_conntrack: table full, dropping packet.

If so, your conntrack table is full. You can also check the current number of connections tracked using this command:
username@localmachine:~$ cat /proc/slabinfo|grep conntrack
nf_conntrack_expect      0      0    248   16    1 : tunables    0    0    0 :   slabdata      0      0      0
nf_conntrack_ffffffff81d11da0   1499   1536    320   12    1 : tunables    0    0    0 : slabdata    128    128      0

The first/second number is the value that the system is currently tracking (active/total). You can check the current max number of connections your kernel can watch using this command:
sysctl net.netfilter.nf_conntrack_max

For CentOS/Redhat, it is called ip_conntrack. If you don't see nf_conntrack_max check this:
sysctl net.ipv4.netfilter.ip_conntrack_max

You can increase using the sysctl -w command:
sysctl -w net.netfilter.nf_conntrack_max=131072

For example. The number is dependent on how much memory you have in the machine and whether the kernel can store the connection informations. The above setting doubles the default Ubuntu setting of 65536.
When you find a good value, add it to your /etc/sysctl.conf file to apply it on reboots:
# increase the number of conntrack max
net.netfilter.nf_conntrack_max=131072

As long as your machine and the upstream network equipment can handle the traffic, you should be good. As you had mentioned it is good to see what caused this increase in traffic. If you are being DDOSed you should try to figure out an anti-DDOS solution which could involve a combination of a software firewall or an appliance depending on your application and financial motivations.


text:
Q: REST API PATCH request I'm trying to send requests and get responses from MailChimp API . . so far, GET, POST and DELETE are working good however, PATCH always results to Bad Request can you identify the error in this code?
string data = "{\"name\": \"TestListTWOTWOTWO\"}";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Headers[HttpRequestHeader.Authorization] = accessToken;
request.Method = "PATCH";
request.ContentType = "text/plain;charset=utf-8";

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(data);
request.ContentLength = bytes.Length;

    using (Stream requestStream = request.GetRequestStream())
    {
        // Send the data.
        requestStream.Write(bytes, 0, bytes.Length);
    }
    var response = (HttpWebResponse)request.GetResponse();
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

the error occus on the line with request.GetResponse();
it is an unhandled WebException saying The remote server returned an error: (400) Bad Request
after checking the error response, here's the what it says
"Your request doesn't appear to be valid JSON:

\nParse error on line 1:\nPATCH /3.0/lists/9bb\n^\n
Expected one of: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['"

A: Many C# libraries seem to try to use the Expect: 100-Continue header, which MailChimp/Akamai has a problem with when combined with PATCH. You have two options.

*

*Turn off Expect: 100-Continue in your HTTP library. In one C# library, you do that with a line of code like Client.DefaultRequestHeaders.ExpectContinue = False

*Tunnel the PATCH request through HTTP POST using the X-Http-Method-Override header. Here's more details on that header.

A: Cause PATCH is a quite new RFC, so you would not expect that more then a few services support it at all. You'd better check that if the service supports it.
You send request using json format, but set content type to "text/plain" is that OK?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Having dual boot working, is it possible to boot an OS or another based on date/time? First of all, this is my first question here. I took a look but didn't find a similar question. Also I don't know if this is the right place. Correct me if anything is wrong.
My question is a "how-to-do".
If a have a working dual boot environment in which I can select what I want to start during boot. Suppose Im using GRUB to create the boot menu. Can I make it automatically select one or another base on the date/time? For instance, start windows everyday but Sunday, when i wish to start linux on power on.
How do I do this?
Complementary info:
The linux distro is Ubuntu 14.
The windows version of my first attempt is windows 7 (MBR).
If success, I'll try in my laptop's windows 10 (UEFI)
The PE could be anything (the better and easier one) including GRUB.
Thanks for any help.

A: No you will not be able to achieve that as this would have to be programmed inside the boot loader before any one OS is started, so I don't think that's possible unless you're a BIOS programmer.


text:
Q: java servlet questions:One singleton class for all requests or create instances for each request? I have now created a java servlet program,the servlet class which extends HttpServlet is named com.servlet.Main. As we all know , every servlet class  has two functions: doGet() and doPost(),one for http get request and the other for http post request. My question is,JVM will create a new com.servlet.Main instance for each coming request or just maintain a singleton instance for all requests?

A: A Servlet container will only ever create one instance of your Servlet implementation for each declaration in the deployment descriptor. This is not a true singleton, only effectively a singleton relative to the ServletContext. Nothing prevents you from creating more instances.
Note, that the entry point of all Servlet applications is the Servlet#service(ServletRequest, ServletResponse) method. HttpServlet, an sub type of Servlet, implements this method to delegate to a number of methods which custom implementations should override. These are doGet, doPost, doPut, doDelete, doHead, etc.

A: The servletcontainer reuses the same servlet instance for every request.
See this stackoverflow post


text:
Q: jQuery.data() returns 'undefined' when retrieving data from dynamic elements My case is very simple, I just tried to store data into an element which appended in the DOM dynamically. My problem is, whenever I tried to retrieve the data through the immediate appended object, the value is returning fine, but through the object returned from the click event through on function it is returning undefined. I searched about this earlier, but people in stackoverflow were just suggested about removing the camel casing etc. That did not help me out in my case. Any suggestions or fix will be more helpful.
My code:
$(document).ready(function(){

    xElement = $('
click this (because this contains data)
').appendTo('ul');

    jQuery.data(xElement,"val","value1");

    alert(jQuery.data(xElement,'val'));

    $(document).on('click','ul li',function(){ alert(jQuery.data($(this),'val')); });
     });

A Fiddle :
Here

A: jQuery.data() takes a raw DOM element, not a jQuery object.
You need to either pass this directly, or call the instance method ($(this).data())

A: $(document).ready(function(){
    xElement = $('
click this (because this contains data)
').appendTo('ul');
    xElement.data("val","value1");
    //retrieving data from immediate object
    alert(xElement.data('val'));
    $(document).on('click','ul li',function(){
        //retrieving data through object from 'on'
        alert($(this).data('val'));
    });
});

Very strange, but if you do it this way, it seems to work fine.
FIDDLEMETHIS

A: Thank you DevlshOne, this was starting to cause me a bit of a headache - I cant vote you up or comment as I dont have enough reputation.
But if anyone is working with datatables this solves the problem of any hidden values (as the default table only shows 1- 10 ) and you can not access the data attr from 11 + as they get dynamically generated afterwards.
old code
$('.userId').on('click', function(){
  var userId = $(this).data('id');
new code
$(document).on('click', 'td', function(){
  var userId = $(this).data('id');
Thanks


text:
Q: Instruments gives me 'SessionInactive', when trying to measure MemoryAllocations or MemoryLeaks on an MT app when trying to analyze an MonoTouch app using Apple "Instruments", it
gives me almost always after 4 seconds:
"Device Connection Failed"
"Failed to start Instruments daemon for 'iOS' on 'XYZ' (v4.3.3)' (SessionInactive)
"Please reconnect the device"
What am i doing wrong?
Is it, that my app takes too long to start up.
Or do i need an special build type to allow Instruments to connect?
One time i was able to have "MemoryAllocation" running stable for more than 4 seconds.
Thanks for any hints

A: I am having the same problem. It happens when I try to run the Leaks instrument, which requires the Allocations instrument, I guess. I can run the Leaks instrument without the Allocations instrument without any problems, but then I can't get the the information that Allocations provides like from what method the leak originates.
I haven't been able to find much about it.
EDIT: I don't know if this is what fixed it, but I killed the app instance that was running on my iPad and then ran instruments again. I did not get the failure with "SessionInactive" and it seems to be running fine now.
I also found a similar topic on the Apple Dev Forums. It didn't really help me, but it might help you.
EDIT 2: It's not perfect. It only runs for a few minutes, but it's better than not at all.


text:
Q: Error while running a servlet (apache tomcat cannot find .properties file) Any other servlet is running fine on eclipse-apache/tomcat integration.
But when I add a properties file in one of the classes, i get this error-
HTTP Status 500 - type Exception report
MessageDescription:
  The server encountered an internal error () that prevented it from fulfilling this request.
exception

java.io.FileNotFoundException: xyz.properties(The system cannot find the      file specified)
  java.io.FileInputStream.open(Native Method)
  java.io.FileInputStream.(Unknown Source)
  java.io.FileInputStream.(Unknown Source)
  xyz.DatabaseConnection(DatabaseAccess.java:23)
  xyz.HelloServlet.doGet(HelloServlet.java:22)
  javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
  javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

Do I have to do some kind of modification in the web.xml file to let it know where the xyz.properties file exists ?
P.S - file and package name has been censored with "xyz".

A: You don not need to edit the web.xml.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Properties properties = new Properties();
properties.load(classLoader.getResourceAsStream("xyz.properties"));

This assumes that the xyz.properties file is inside the classes folder.

A: I think the property file is not in the classpath. Please try putting the properties file WEIB-INF/classes folder and see if this resolves this issue.


text:
Q: How to return multiple objects in django I am working on an e-commerce app and want customers to be able to order several items. Currently they can only order one and i am having a hard time figuring out how i can achieve this.
in my menu template i return all the items in their category as follows:
{% for category in categories %}

 {{ category.title }}

  {% for item in category.item.all %}

{{item.name}} {{item.price}}frw

OnClick, each item redirects to a form where you can order the quantity. here is the view:
def show_item(request,id):
    # need to evaluate the HTTP method
    if request.method == 'POST':
        a = Item.objects.get(pk=id)
        form = forms.PartialOrderItemForm(request.POST,instance=a)
        # check validation of posted data
        if form.is_valid():
            order.add_to_order(request)
            # if test cookie worked, get rid of it
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            url =urlresolvers.reverse('order_index')
            # redirect to order page
            return HttpResponseRedirect(url)
    else:
        # it's a GET, create the unbound from. Note request as a Kwarg
        form = forms.PartialOrderItemForm(request.GET)
    # set the test cookie on our first GET request
    request.session.set_test_cookie()
    context={
#       'categories':categories,
        'form':form,
#       'menu':menu,

    }
    return render_to_response('item.html',context,context_instance=RequestContext(request))

At some point, the above view calls the following view, that is after validating the form order.add_to_order(request)
add an item to order
def add_to_order(request):
    postdata = request.POST.copy()
    # get item slug from post data, return blank if empty
#   item_slug = postdata.get('item_slug','')
    #get quantity added, return 0 if empty
    quantity = postdata.get('quantity',0)
    # fetch the item or return  missing page error_message
    i = get_object_or_404(Item,pk=1)
    i.orderitem_set.all()
    # get items in order
    order_items = get_order_items(request)
    item_in_orders = False
    # check to see if item is already in order
    for order_item in order_items:
        if order_item.item.id == i.id:
            #update the quantity if found
            order_item.augment_quantity(quantity)
            item_in_orders = True
    if not item_in_orders:
        # creat and save a new order item
        oi = OrderItem()
        oi.order_id = _order_id(request)
        oi.quantity = quantity
        oi.item = i
        oi.save()

Once the form is validated, the order is shown in the order page. here is the view that does this
def show_order(request):
    if request.method == 'POST':
        postdata = request.POST.copy()
        if postdata['submit'] == 'Remove':
            order.remove_from_order(request)
        if postdata['submit'] == 'Update':
            order.update_order(request)
    order_items = order.get_order_items(request)
#   page_title  = 'F4L order'
    order_subtotal = order.order_subtotal(request)

    context = {
        'order_items':order_items,
        'order_subtotal':order_subtotal,
    }
    return render_to_response('public/order.html',context,context_instance=RequestContext(request))

here is part of the template for the order page.

    {% if order_items %}
     {% for item in order_items %}

       {{ item.item.name }}

     {{ item.item.price }} frw

      <form method="post" action="." class="order">
       {% csrf_token %}
       Quantity:
       <input type="text" name="quantity" value="{{ item.quantity }}" id="quantity" size="2" class="quantity" max_length="5" />
       <input type="hidden" name="item_id" value="{{ item.id }}" />

      <input type="submit" name="submit" value="Update" />
      </form>

Here is what is happening, when i order the first item with pk=1 it works out properly, but then when i order the second item or any other and fill in the form, instead the order page returns the first item always.
 How do you think i should go about this.


text:
Q: How much swap space for a 32GB ubuntu virtualization server? I looked at many other questions on here regarding swap space, but none that I found really addressed my particular situation.
I have an Ubuntu 9.10 64-bit server with 32GB of RAM running as a KVM host system. I'm using LVM on top of RAID1.
The "old-school" swap recommendations suggests 2xRAM or 2xRAM+1GB, or even if MEM < 2GB then SWAP = MEM*2 else SWAP = MEM+2GB.  But I just can't see allocating 66GB of disk space for swap, that seems crazy!  I'm thinking 4GB or maybe 8GB would be plenty.
This system is going to be running a number of KVM virtual servers. How does swap work in this situation? Should I have a swap partition for the host server, and then each virtual server gets its own LVM root and LVM swap partition?  Or do the virtual servers share the host's swap?

A: Strictly, Linux does not need any swap at all - especially when you have gobs of RAM. In the case of KVM, you will need to have enough memory to support all your machines. So, if you have 20 VMs with 1GB RAM each, you will need to have 20GB RAM on the host available. However, each individual VM can be configured with its own swap, such as having 2GB of swap each. That way, each VM can manage its own swap. You can configure swappiness separately for each.

A: A 4GB amount will be sufficient. I'm not entirely sure how swap works for virtual servers, but I'm assuming each of them have their own swap.
In such situations, you should leave around 2GB of RAM for the host system, or just 1GB, depending on how much you see is being used on a machine with most of the memory allocated. Swap is very slow, and on your RAID-1 system, with such a high-end machine you would never want to swap.
On a side note, you may want to consider having 4 disks running in RAID-10, preferably SAS drives to have sufficient I/O for all the virtual servers on the node, though depending on what you're running this may not be necessary.


text:
Q: Genymotion Invalid path: VBoxManage and Initialize Engine: failed I use:

*

*Windows 7

*Android Studio 1.3.2

*Genymotion 2.5.4

*VirtualBox 5.0.4r

Yesterday, it run correctly. However my C disk is run out of space so i decided to uninstall Andriod Studio, Genymotion and VB. Now I installed it in disk E and i show problem

Genymotion: Genymotion directory: E:\Program
  Files\Genymobile\Genymotion
Genymotion: Trying to initialize engine
Genymotion: Invalid path: VBoxManage
Genymotion: Initialize Engine: failed

I already tried some solutions from same topic but not work so far, seem like my case is different. Any one have same issue? Any suggestion? Thanks

A: Using Windows 10 here, same issue, added the VirtualBox binary directory to the system path and it still failed, so it's not obvious what exactly it's looking for. But I do have Android Studio in a non-standard location too -- I think it's likely that there's a hardcoded relative path in there that's cracking on use. May not be a fix except to reinstall Android Studio where it wants to go...
However, per another answer, if you can start the image in Genymotion the Debug button will be able to see it and connect to it and you can maybe live without the integrated Genymotion device manager until they fix this.

A: Maybe the file "reg.exe"(in X:\Genymotion) lose, you must get it from genymotion-2.5.3-vbox.exe

A: I am having the same issue, and while searching I come across this post here that says the plugin (at least for eclipse) doesn't work with Virtual Box version newer than 4.2. I am not sure if this will help but it is worth looking in to.
EDIT:: There was an update to Android Studio to 1.4 and an update to the Genymotion plugin to 1.0.6. It fixes this issue. I updated yesterday and it works like a charm.


text:
Q: Conditional select statement using 3 tables I am trying to do a conditional case statement and am not sure if sql can perform this.
I need to select the ID from Table A, and the Name from the corresponding ID in table B. If the Name in Table B is NULL, i need to select the Name from Table C. I am not sure how to do this using a CASE or if it is possible, any help is greatly appriciated.
Table A      Table B         Table C
ID   ID2     ID2    Name      ID2    Name
________     ___________      ___________
1     3      1      bill      1     NULL
2     2      2      steve     2     NULL
3     1      3       NULL     3     george

A: Use IFNULL() to select the appropriate column from B or C.
SELECT a.id, IFNULL(b.name, c.name) AS name
FROM a
JOIN b ON a.id = b.id2
JOIN c ON a.id = c.id2

If the matching rows could be missing from B or C, use LEFT JOIN instead of JOIN.

A: Try the following query:
select IFNULL(TableB.name, TableC.name) as name
from TableA
left join TableB TableA.ID2=TableB.ID2
left join TableC TableA.ID2=TableC.ID2

A: I was too slow :p
Here is a fiddle, if it might help someone: http://sqlfiddle.com/#!9/b28c5/2
I assumed that each ID2 value is present in either both or none of TableB/TableC.


text:
Q: modify standard usage of HttpURLConnection to make POST request to form containing captcha, in java At http://code.google.com/appengine/docs/java/urlfetch/usingjavanet.html some code is provided  which makes POST request to a form where comments are submitted to that form.
I want to use similar code to make a POST request to a form that accepts data...But one major requirement is that when the form at "http://domain.com/submit.php" is to be submitted, it has a text field named "CAPTCHA" for which the relevant captcha is actually generated by "http://domain.com/captcha.php".
My question is, how to use HttpURLConnection to make a request to a form with 3 fields- "UserID"  and "Password" and finally "Captcha" (which is generated by captcha.php)? I am particularly confused here with ref to the captcha, since each time a different captcha is generated... How do we know the value of this captcha, i.e. how do we display this captcha on screen, and then submit the form. Can we also track the response to such a submission?
I am new to Java, plus a total newbie to App Engine, so any help would be appreciated :)

A: Captchas are specifically designed to prevent people from doing the sort of thing you seem to be attempting to do.


text:
Q: Python `for` loop doesn't update `numpy` array values I'm trying to make a simple numerical gradient function and part of it is a for loop updating parameter values that would later be evaluated. The code is as follows:
import numpy as np

def target_gradient(theta):
    e = 10

    for i in range(theta.shape[0]):
        theta_upper = theta
        theta_lower = theta
        theta_upper[i] = theta[i] + e
        theta_lower[i] = theta[i] - e
        print(f"theta_upper {theta_upper}")
        print(f"theta_lower {theta_lower}")

    return theta_upper, theta_lower

u, l = target_gradient(np.array([1, 1, 1, 1, 1]))

However, instead of the anticipated output, I get [1 1 1 1 1] for both arrays. Print statements are there for monitoring and they show that throughout the loop the arrays didn't change (i.e. were [1 1 1 1 1]).e=10 is so that the effect is more pronounced. I also tried the enumerate() approach, but get the same result.
The full gradient funtion would look something like this
def target_gradient(theta, x, y):
    e = 0.01
    gradient = np.zeros(theta.shape[0])

    for i in range(theta.shape[0]):
        theta_upper = theta
        theta_lower = theta
        theta_upper[i] = theta[i] + e
        theta_lower[i] = theta[i] - e

        gradient[i] = (
            foo(theta=theta_upper, x=x, y=y) - foo(theta=theta_lower, x=x, y=y)
        ) / (2 * e)

    return gradient

Therefore, I am intentionally declaring theta_upper = theta inside the loop because I want to calculate the gradient for which I need partial (numerical) derivatives.

A: The best approach depends on what foo is:
If foo can take vector arguments and return vector values, e.g.
def foo(theta, x, y):
    return x * y * np.sin(theta)

Then you can simply do:
def target_gradient(theta, x, y, e=0.01):
    foo_upper = foo(theta + e, x, y) # Add e to the entire theta vector, and call foo
    foo_lower = foo(theta - e, x, y) # Subtract e from the entire theta vector, and call foo
    return (foo_upper - foo_lower) / (2 * e)

Based on your code, where you pass a vector theta_upper to foo, I suspect this is the case.
If foo can't take vector arguments and return vector values, e.g.
def foo(theta, x, y):
    return x * y * math.sin(theta)

then you need to iterate over theta, and call foo for each value.
def target_gradient(theta, x, y, e=0.01):
    gradient = np.zeros(theta.shape[0])

    for i in range(theta.shape[0]):
        foo_upper = foo(theta[i] + e, x[i], y[i]) # Take a single value of theta, and add e
        foo_lower = foo(theta[i] - e, x[i], y[i]) # Take a single value of theta, and subtract e
        gradient[i] = (foo_upper - foo_lower) / (2 * e)

    return gradient

A: The reason why theta_upper and theta_lower are not changing inside the loop is because you are creating copies of theta and assigning them to theta_upper and theta_lower. Therefore, when you modify theta_upper[i] or theta_lower[i], you are not modifying the original theta array.
To fix this, you can use the copy() method to create a copy of theta that you can modify inside the loop, like this:
def target_gradient(theta):
    e = 10

    for i in range(theta.shape[0]):
        theta_upper = theta.copy()
        theta_lower = theta.copy()
        theta_upper[i] = theta[i] + e
        theta_lower[i] = theta[i] - e
        print(f"theta_upper {theta_upper}")
        print(f"theta_lower {theta_lower}")

    return theta_upper, theta_lower


text:
Q: LOESS confidence intervals depend on the number of points Let's construct a linear trend with some "noise" as follows:
X <- seq(0,20,1); Y <- X/4 + sin(X); plot(X,Y)

Now I smooth the dataset with loess and plot "95% confidence intervals" with qt and the loess standard error:
X.pred <- seq(0, 20, length.out = 1000)   # To have smooth lines
Fit    <- predict(loess(Y ~ X, span = 0.75), newdata = X.pred, se = TRUE)
lines(X.pred, Fit$fit)
lines(X.pred, Fit$fit + qt(0.975, Fit$df) * Fit$se.fit, lty = 3)
lines(X.pred, Fit$fit - qt(0.975, Fit$df) * Fit$se.fit, lty = 3)

The result is very intuitive, as the subjacent trend is clearly shown and the "band" covers almost all points (as expected in a 95% confidence interval).
The problem arises when we have many points to be fitted. Let's increase the number of points by a factor of 10:
X <- seq(0, 20, 0.1); Y <- X/4 + sin(X); plot(X, Y)

When I run the same script as above, the band is now very narrow and clearly does not cover 95% of the points. How can I obtain "intuitive" loess 95% bands, irrespective of the number of fitted points?

A: This is a misunderstanding of the behaviour of confidence bands; for any reasonable form of estimation, the confidence intervals will shrink to zero as the sample size increases (even if the residual variance stays the same). You seem to be looking for prediction intervals. You can get these, approximately, by adding the residual variance (e.g. resid.sd <- loess(Y ~ X, span = 0.75)$s; resid.var <- resid.sd^2) to the squared standard error of the fit, and using the square root of the sum as the standard deviation in qnorm().  (It's not easy to combine a t-distributed distribution of parameter error and a Gaussian distribution of residual error ...)


text:
Q: Django admin : show records for respective user only I have a simple model, say Resources. And I have fewer than 20 users and model admin serves the purpose to record requests.
Problem is that all users can see all records in model admin site.
Can this behaviour be changed to only show records created by same user only ?
Thank you in anticipation.

A: The django doc has an example that does almost exactly what you want:
https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset
The idea is to override the get_queryset() method in the model admin view:
# admin.py
from django.contrib import admin

class YourModelAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super(MyModelAdmin, self).get_queryset(request)
        return qs.filter(author=request.user)

admin.site.register(YourModel, YourModelAdmin)

You can adapt the queryset filter to even more specific needs at will.

A: UPDATE 2020:
Anyone who is curious as to what is the author field, then that is established in the models.py file of your app. For the admin.py part, you can visit the docs.
Step 1:
Make sure in your permissions you give access to the apps you want your users to have CRUD functionality over.
Step 2:
Admin.py
class MyModelAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(author=request.user)

Models.py
from django.contrib.auth import get_user_model

class Lecture(models.Model):
    author = models.ForeignKey(get_user_model(), null=True, on_delete=models.CASCADE)


text:
Q: NSTimer selector calling Can someone explain to me how exactly the NSTimer behavior is?
Basically I want to know if there is a way to always have the NSTimer event happen. Event if there is currently something executing.
For example, in:
NSTimer* testTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(testMethod) userInfo:nil repeats: NO];
for (int i=0; i<9999; i++) {
    NSLog(@"%i", i);
}

testMethod will never be executed since the for loop is being executed when the event fires.

A: When the timer fires, it's selector is added to the run loop to be executed as soon as possible.
However, you're creating a loop so the run loop never gets a change to do the timer's selector resulting in what you're seeing - the app waits for the loop to finish before running your timer's selector.
If you have a long running task, it's best to put it into a new thread - try looking at performSelectorInBackground and reading up on threading in objective-c.


text:
Q: How to create a unique random key name using API gateway as S3 proxy? If using API gateway as S3 proxy, I would like to generate the filenames / key-names as random strings.
Referring the following answer, I understood that $context.requestId can be used to generate random keys. But, I am not able to use $context in the URL path parameters of integration request.

A: ok, found a way to solve this issue myself.
$context can be used context in URL path parameters of integration request.
So for random keynames in S3, we can add context.requestid as key-name into the integration request of S3 proxy.


text:
Q: Take screenshot of whole WebView in swift 4 iOS I really hope you can help me.
In my project I have a WebView opening a specific page and a button, what I need to do is taking a screenshot of the whole web page and export it as image or pdf when user press the button.
Here is what I have in my ViewCnotroller:
import UIKit

class ViewController: UIViewController {

@IBOutlet weak var WebView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL (string: "https://www.google.com")
    QuizView.loadRequest(URLRequest(url: url!))

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func ShotBtn(_ sender: Any) {

    let activityVC = UIActivityViewController(activityItems: [self.WebView.image], applicationActivities: nil)

}
}

Now I know that value of type UIWebView has no member image, but the only example I found was using an UIImage insted WebView.
I saw this answer Get UIWebView content and convert it to image but I was looking for something in swft 4
How can I do it?
Thankyou


text:
Q: Jquery Setting id by loop doesn't work I'd like to set id by for loop.This is coffee script.
for boxWidth in[0..15]
  for boxLength in[0..15]
    boxWidth=String(boxWidth)
    boxLength=String(boxLength)
    boxId    =boxWidth+boxLength
    $ ->
        $('div').append("")

I'm expecting span to be

However I've gottenn

What is the problem?

A: If you are bound on using coffeescript, have you tried this:
for boxWidth in[0..15]
  for boxLength in[0..15]
    boxWidth=String(boxWidth)
    boxLength=String(boxLength)
    boxId    =boxWidth+boxLength
    $('div').append("")

no need to return the div during the loop.
also you might want to check out: http://js2coffee.org


text:
Q: Trouble to find the solution to a linear system where a matrix is not invertible Hello community I am new here and I have a question which might be pretty basic.
So I am trying to solve an equation. I have 3 matrices
A =  \begin{pmatrix}1&0&0&0&0&0&0&0\\0&1&1&0&0&0&0&0\end{pmatrix}
B = \begin{pmatrix}0&0&0&0&0&0&1&0\\0&0&0&0&0&0&0&1\end{pmatrix}
and
K = \begin{pmatrix}1&0&0&0&0&0&0&0\\0&1&1&0&0&0&0&0\\0&0&0&0&0&0&1&0\end{pmatrix}
H = \begin{pmatrix}A\\B\end{pmatrix}
and Z = \begin{pmatrix}z1\\z2\\z3\end{pmatrix}
And I have linear system
$\begin{pmatrix}H\\K\end{pmatrix} v = \begin{pmatrix}0\\Z\end{pmatrix}$
It says that solution for determined system is
$ v = \begin{bmatrix}\begin{pmatrix}H\\K\end{pmatrix}^T \begin{pmatrix}H\\K\end{pmatrix} \end{bmatrix} ^{-1}\begin{pmatrix}H\\K\end{pmatrix}^T \begin{pmatrix}0\\Z\end{pmatrix} $
Okay when I put this system of matrices in python it shows that matrix inside [] can't be inverse. I am presumping that
H = \begin{pmatrix}A\\B\end{pmatrix}
just means that
H is
\begin{pmatrix}1&0&0&0&0&0&0&0\\0&1&1&0&0&0&0&0\\0&0&0&0&0&0&1&0\\0&0&0&0&0&0&0&1\end{pmatrix}
Two matrices put together. Same I presume for \begin{pmatrix}H\\K\end{pmatrix}
Where am I wrong?
Ps: sorry im new here hope I wrote everything correctly and understandable. Happy holidays everyone.

A: For the sake of simpler notations, let us rename $$L:=\begin{pmatrix}H\\K\end{pmatrix} \ \ \text{and} \ \ P:=\begin{pmatrix}0\\Z\end{pmatrix} $$
giving :
$$Lv=P \tag{1}$$
which is a $7 \times 8$ system (thus an underdetermined system : less constraints than the number of unknowns).
Instead of your $$ v = (L^T L)^{-1}L^T P $$
which is a formula valid for overdetermined systems, one must take for an underdetermined system :
$$  v = L^T(L L^T)^{-1} P \tag{2}$$
(see https://see.stanford.edu/materials/lsoeldsee263/08-min-norm.pdf for the difference of formulas between under- and over-determined systems ; in this document, a matrix like $L$ with more columns than lines is called "fat").
This will give you a so-called "mean-squares" solution.
Proof of (1) : Plug (2) into (1), you will get :
$$\underbrace{L L^T(L L^T)^{-1}}_{\text{identity matrix} \ I} P=P...$$


text:
Q: How can I find the number of possible states of this complex system? I have a fairly complex system that I would like to analyze and be able to figure out how many possible states exist for it.
Here is the system:
Say I have a group of n cells.  This group is essentially a circuit board, or breadboard.  Each cell can be connected with any number of other cells, in any possible connection.  How many possible states exist for values of n?
Increasing Values of n
Say that each cell is assigned a letter.  For n = 1, there is only cell A so there is obviously 1 possible state.
For n = 2, the states are {A/B}, or {AB}.  The / represents different groups of connections, so there are always n number of possible groups as well.
Now for n = 3, there are {A/B/C}, {ABC}, {A/BC}, {B/AC}, or {C/AB}, so 5 states.
Things quickly become exceedingly complex.
You can tell it quickly becomes far more difficult, because the number of cell increases, the number of "groupings" increases (1 group, 2 groups, 3 groups..up to n), and also the number of way to form a group increases (for instance if n = 5, for 3 groups, there are combinations of (1, 1, 3) cells or (1, 2, 2) cells.
I haven't a clue of figuring out how to calculate the number of states, so any help is appreciated.
Just to summarize, this basically boils down to how many possible ways can I connect a grid of n x n cells, if the cells can be connected in any way to any number of other cells, and there is no limit to the number of cell groupings except obviously up to n, the number of cells?
I've hand calculated the values for n = 1 to 6, they are 1, 2, 5, 11, 42, and 147.  Which obviously doesn't correspond to a simple sequence.

A: You've got n nodes, say 2, each node can connect to any other node, and all connections are 2 ways. thus A can connect to B. 1 connection. but the connection can either be on or off, thus 2 states of the system.
So we take the number of nodes (n) and run it through this to get the maximum number of connections the system can have. n*(n-1)/2 the n-1 is because it can't connect to itself, the /2 is because each connection is a 2 way connection (a-b is the same a b-a).
That gives us number of connections (c). Since every connection can either be on or off the connections themselves can be thought of as bits. And to get the number of states of the system you take the number of states for each bit (or connection - which is 2, on or off) to the number of bits in the system (c).
Thus number of states in the system is:
2^(c) = s
which is:
2^(n*(n-1)/2) = s
n    |    c    |    s

1          0         1
2          1         2
3          3        8
4          6
        64
5          10
      1024
6          15
      32,768
7          21
       2,097,152
8          28
      268,435,456
9          36
      68,719,476,736
10        45
      35,184,372,088,832
You may have noticed that by your estimation 3 nodes should have 5 states. By my estimation you're wrong.
Let's say there are 3 nodes: 1, 2, and 3. We'll call connections between 1 and 2 A, connections between 2 and 3 B, connections between 1 and 3 C. So number of connections is c = 3.
the following states are possible:

*

*(blank, no connections are on)

*A (connection A is on, so 1 is connected to 2)

*B (2-3)

*C (1-3)

*AB (1-2,2-3)

*AC (1-2,1-3)

*BC (2-3,1-3)

*ABC (1-2,2-3,1-3) (all possible connections exist)


text:
Q: Test Automation for Android & iOS I would like to build a test agent for testing Mobile SDKs (for both iOS & Android).
I thought about writing the agent in Python (run on Win Host machine), and the app for the mobile.
I need help with the app itself, it should consider the following for start:

*

*Performance: It must not not overload the mobile phone.

*How to execute app API: Should I use the adb command? Any other way?

Any BKMs? Recommendations?
Thanks a lot

A: Try as follows (start activity)
import os
cmd = 'adb shell am startservice -n packageName/.ServiceClass'
os.system(cmd)


text:
Q: MongoDB - Get highest value of child I'm trying to get the highest value of a child value. If I have two documents like this
{
    "_id" : ObjectId("5585b8359557d21f44e1d857"),
    "test" : {
        "number" : 1,
        "number2" : 1
    }
}

{
    "_id" : ObjectId("5585b8569557d21f44e1d858"),
    "test" : {
        "number" : 2,
        "number2" : 1
    }
}

How would I get the highest value of key "number"?

A: Using dot notation:
db.testSOF.find().sort({'test.number': -1}).limit(1)

A:
max() does not work the way you would expect it to in SQL for Mongo.
  This is perhaps going to change in future versions but as of now,
  max,min are to be used with indexed keys primarily internally for
  sharding.
see http://www.mongodb.org/display/DOCS/min+and+max+Query+Specifiers
Unfortunately for now the only way to get the max value is to sort the
  collection desc on that value and take the first.
db.collection.find("_id" => x).sort({"test.number" => -1}).limit(1).first()

quoted from: Getting the highest value of a column in MongoDB

A: To get the highest value of the key "number" you could use two approaches here. You could use the aggregation framework where the pipeline would look like this
db.collection.aggregate([
    {
        "$group": {
            "_id": 0,
            "max_number": {
                "$max": "$test.number"
            }
        }
    }
])

Result:
/* 0 */
{
    "result" : [
        {
            "_id" : 0,
            "max_number" : 2
        }
    ],
    "ok" : 1
}

or you could use the find() cursor as follows
db.collection.find().sort({"test.number": -1}).limit(1)


text:
Q: Download large files in Dartlang I need to download largish files from a browser using dartlang.
I've been using the "data:uri" thing to download, but have hit the size limitations of that method.
Wondering what the best method for this is, I looked into using the HTML5 filesystem API but that is deprecated (without ever really being implemented in most browsers apparently.

A: Download

import 'dart:html';

void main() {
  var data = new Blob(['Hello World!\n'*1000000]);
  querySelector("#downloadLink")
      ..setAttribute('href', Url.createObjectUrl(data));
}


text:
Q: Replace Devexpress XPO to Entity Framework I am working on an ASP.NET MVC web application that was built with DevExpress 12.1 tools including DevExpress XPO.
Due to licensing issue, I have task in which I want to remove Devexpress components entirely from that web application.
After r&d, I found at the first step of removing, I need to change datalayer to Entity-Framework (currently using XPO).
I know the manual process, but can anybody suggest how to do this? Is this any online tool or suggestion which achieve my work speedily?

A: I use XPO in one application and EF Core in another. I would happily move away from XPO forever, EF Core is a much better experience - the linq to entities is way better than linq to xpo, and while there are lots of other reasons, the most important thing is that you can change properties by ID with EF Core - in XPO you have to load the object first and then change the object reference. I have begun to truly loathe working with my project that is dependent on XPO so I have been looking for an answer for this for a long time.
I have sadly come to the conclusion that the best way is a gradual migration. You can run the models side by side and just change components over on a progressive basis. This way you can keep the application functional while moving between ORMs. There is sadly no esy way to do this.


text:
Q: Graph isomorphism by invariants Graph isomorphism is known to be a difficult computational problem. The problem get even worst if we want to find non-isomorphic graphs in a large family of graphs.
Let us call a (numerical) invariant $\alpha$ is good if it is, roughly speaking,

*

*simple to compute,

*fast to compute, and

*when applied to a family of graphs, say the family $\mathcal{G}_n$ of all graphs of order $\leq n$, the graphs fall into relatively small classes with different $\alpha$-values, that is,
$$\lim_{n\ \longmapsto\ \infty}\frac{\max(\text{class sizes})}{\#\mathcal{G}_n}\longrightarrow0.$$
For example, the size of graphs are good invariants as it satisfies the conditions (1), (2), and (3) in the family $\mathcal{G}_n$ of all graphs of order $\leq n$. However, this is not true for the order of graphs in this family. The spectrum can be a candidates in this family, but it is not good in the family of trees.
One technique to overcome the isomorphism problem in large family of graphs is to use good invariants to put graphs into non-isomorphic classes and then try isomorphism check inside each class.
The question is what are best good invariants?

A: Let me start my answer by noting that this is fundamentally the wrong approach to the problem of reducing a large set of graphs by isomorphism type. The best software (nauty, Bliss, Traces) can put a graph into canonical form in an amount of time similar to what testing two graphs for isomorphism takes. After canonical labelling, you can use a sorting algorithm (or a hash table if it fits in memory) to remove isomorphs quickly.  The costly step (canonical labelling) is needed only once per graph, instead of isomorphism testing multiple times per graph.
The advantage of canonical labelling is even more stark if you have a large database of graphs, and you want to determine whether a new graph is already in the database.
Getting back to your question, there is no uniform answer that applies for all classes of graphs. Lorenzo mentioned vertex degrees and you can make that even much stronger by counting the neighbours of each vertex according to their degrees. But as soon as you need to process a large number of regular graphs, this invariant is completely useless. An invariant based on the number of vertices at each distance from each vertex will work well on random regular graphs, but fail completely on strongly regular graphs or incidence geometries. And so on.
There is also the question of how the cost scales. An invariant that takes $n^3$ time to compute might be great when $n=20$, but when $n=10,000$ (well within range of modern programs except for very difficult graph classes) $n^3$ is too much.
The usual use of invariants is not to divide a file of graphs into parts, but to quickly distinguish vertices of each graph from each other as an aid to canonical labelling. But here again there are no known invariants that are efficient and effective for all graph classes.


text:
Q: Add Microsoft.Office.InterOp.Word using reference C# I'm trying to add the Microsoft Office InterOperability  reference to my header but I cannot find it.
I went here: http://msdn.microsoft.com/en-us/library/kh3965hw.aspx
I installed the PIAs but I cannot find the reference still. There is a registry entry in the Add and Remove Programs but for some reason Visual Studio 2010 is not seeing it.
Edit: I have Visual C# 2010 Express

A: Visual Studio will install these Office PIA files as well to the following:

When you install Visual Studio, the PIAs are automatically installed to a location in the file system, outside of the global assembly cache. When you create a new project, Visual Studio automatically adds references to these copies of the PIAs to your project. Visual Studio uses these copies of the PIAs, instead of the assemblies in the global assembly cache, to resolve type references when you develop and build your project.
These copies of the PIAs help Visual Studio avoid several development issues that can occur when different versions of the PIAs are registered in the global assembly cache.
Visual Studio installs these copies of PIAs to the following locations on the development computer:

*

*%ProgramFiles%\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office14

*

*(or %ProgramFiles(x86)%\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office14 on 64-bit operating systems)

*%ProgramFiles%\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office15

*

*(or %ProgramFiles(x86)%\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office15 on 64-bit operating systems)

Did you include the Office files when installing Visual Studio?
If not, then run Visual Studio setup again and choose to Add Options and choose the Office PIA relevant pieces.


text:
Q: Large table with automatic font resize + cols and rows resize? I am user really the first steps in the TeX world.
I have a very large table which is 10 x 11 (10 cols x 11 lines). I would like to have a single page and that Latex takes completely care about the cells/rows size + font size, in order to make it fit well.
I am using PDFLATEX on Ubuntu.
Here a my code.
    \begin{tabular}{|*{10}{c|}}
\hline
1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
 \end{tabular}

A: I would use a resizebox from the adjustbox package, defining the width as long as the textwidth. This puts the table inside this box. I copied your code and added two things: the \usepackage{adjustbox} in the preamble, and a \resizebox{\textwidth}{!}{ before the \begin{tabular}. Note that there is an open bracket, which we will close } only after the \end{tabular}. This will resize your table to match the width of your text.
\documentclass{article}
\noindent
\usepackage{adjustbox}
\begin{document}
\resizebox{\textwidth}{!}{%
\begin{tabular}{|*{10}{c|}}
    \hline
    1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
    1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
    1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
    1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
    1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
    1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
    1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
    1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
    1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
    1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
    1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 & 1.00000000000000 \\ \hline
\end{tabular}
}
\end{document}

(red lines shoe page layout, code for them are not included in above mwe)


text:
Q: Google Apps Script - Failed to send a request I need a help.
I have a Flask API running like this:
from flask import Flask
from flask import jsonify

app = Flask(__name__)

@app.route('/rules/<payload>', methods=['GET', 'POST'])
def add_none(payload):
    return jsonify({'result': payload})

if __name__ == '__main__':
    app.run(debug=False)

My Google code is trying to send a post request, but always I got an invalid request.
I ran the same request using Postman and I didn't get the error. I don't understand what's happening.
rulesArray = [{'column_a': 35.0, 'column_b': 100.0, 'column_c': 105.0}, {'column_a': 38.0, 'column_b': 50.0, 'column_c': 80.0}];

var payload = {'content': rulesArray};
var params = { method: "POST", payload: payload, muteHttpExceptions: true, contentType: "application/json" };

var URL = 'http://127.0.0.1:5000/rules';
var response = UrlFetchApp.fetch(URL, params);

Any ideas what I can do to fix this? Thanks.


text:
Q: Fiber to copper switching - small network requiring robust solution I have a simple setup which appears to require a clever solution; hoping someone has some ideas.
Network:

*

*4 data generating computers, each with a copper->fiber media converter

*2 data analyzing computers

*SM fiber runs from all four data generating computers to the room containing the data analyzing computers

*1Gb Cat-5 NICS in all computers

I have a team of people who do data analysis on the analyzing computers.  At any given time they need to specify which (singular) data generating computer they need to receive data from (TCP socket connections).  Thus, there needs to be a simple way for them to select, either on a physical device or using a custom, read fool-proof, UI which data generating computer is connected to that particular data analyzing computer.
My predecessor's solution is to use two media converters and have the operators plug in the correct fiber pair.  This is abhorrent for obvious reasons.
Apparently, the solution before that was to use a manual fiber switch of some sort but it was too unreliable given SM tolerances.
One idea is to just get an unmanaged switch with sufficient SFP and Copper ports and hope that both data analysis computers don't try to connect to the same data generating computer.
Maybe more robust would be to get a managed switch and write the UI such that the software could modify the port isolation settings or port settings on four VLANs (one for each data generating computer).
Any votes or other ideas?
I will also note that the current setup has all of the data generating computers using the same IP address and all of the data analyzing computers using the same IP address -- which works because the operator is just setting up a P2P network by switching the fibers in the media converters.  I'm already hearing belly-aching from the data analysis software developer about having to track different IP addresses in my new switch scheme, but I don't see how it can be avoided?

A: I would use the KISS principle, add a third box and have the 2 data generating servers send their data to it, and use ELK (or similar) to parse it from the other 2 or any other PC on your network. Give them all different IP's and make this a standard network stack setup.


text:
Q: Make Update with select statement in Mysql I am trying to update for some products their category in Database. But I get an error and I don't understand where my statement is wrong. Please help. I want to find products that have in their name a specific word and after that I what to update the category for this products.
I want to select IDs from sho_posts where sho_posts.post_title contain this part of word '%Audio CD%' and after that to update the sho_term_relationships.term_taxonomy_id with value 2 where sho_term_relationships.object_id=sho_posts.id
UPDATE sho_term_relationships
   SET term_taxonomy_id = 2
 WHERE object_id = (SELECT `id` FROM `1876522_shoping`.`sho_posts` WHERE CONVERT(`post_title` USING utf8) LIKE '%Audio CD%')

A: In your WHERE clause, to find the ids to update based on the subquery results, use IN instead of =
UPDATE sho_term_relationships
   SET term_taxonomy_id = 2
   WHERE object_id IN (
      SELECT `id` FROM `1876522_shoping`.`sho_posts`
      WHERE CONVERT(`post_title` USING utf8) LIKE '%Audio CD%')

You would use = only if you were certain the subquery would return a single row, it won't work if the subquery returns multiple rows. Using IN tests whether the object id is included in the subquery results.

A: You just need to use 'in' instead of '=' when updating multiple rows.
UPDATE sho_term_relationships
   SET term_taxonomy_id = 2
 WHERE object_id in (SELECT id FROM 1876522_shoping.sho_posts WHERE CONVERT(post_title USING utf8) LIKE '%Audio CD%')


text:
Q: python: create wheel from existing c extension Our build pipeline spits out an *.so / *.pyb python extension through pybind11. As a step in the pipeline I need to package the extension as a wheel for easy distribution through pip. I am trying to come up with a setup.py that takes the existing library and does not rely on re-compiling the binaries through the setup.py (so I really don't want this). It would require a major rewrite of the devops scripts.
When having a folder structure such as:
setup.py
my_module.cpython-39-darwin.so

A very basic setup.py can create a functioning wheel (python setup.py bdist_wheel):
setup(
    name = 'my_module',
    version='0.9.102',
    packages=["."],
    package_data={'': ['*.so', '*.pyi']},
)

Unfortunately, the wheel is missing the important python tag and platform name, etc: my_module-0.9.102-py3-none-any.whl vs. my_module-0.9.102-cp39-cp39-macosx_10_13_x86_64.whl
Setting --python-tag  and --plat-name works, setting --py-limited-api does not, however.
Through research I found that overwriting the distclass adds the correct tag again, but the Root-Is-Purelib is set back to false. This, unfortunately, creates a broken wheel when installing through pip as it puts the binary in a my_module-0.9.102.data/purelib folder...
Overwriting the is_pure seems to be ignored also:
from setuptools import setup, find_packages, Distribution

class BinaryDistribution(Distribution):
    def is_pure(self):
        return True

    def has_ext_modules(foo):
        return True

setup(
    name = 'my_module',
    version='0.9.102',
    packages=["."],
    package_data={'': ['*.so', '*.pyi']},
    distclass=BinaryDistribution
)

What else can I do to wrap my pre-compiled python libraries to wheels for distribution without rewriting lots of the build pipeline?

A: Not a perfect solution but a functional wheel is created when using the wheel module instead:
from setuptools import setup

setup(name='my_module',
      packages=['my_module'],
      package_data={'': ['*.so', '*.pyi']},
      )

create wheel with:
pip install wheel
pip wheel .


text:
Q: A code generator task in a multi-project gradle build I have studied thousand similar questions on SO and I am still lost. I have a simple multiproject build:
rootProject.name = 'mwe'
include ":Generator"
include ":projectB"
include ":projectC"

with a top level build.gradle as follows (settings.gradle):
plugins { id "java" }
allprojects { repositories { jcenter() } }

and with two kinds of project build.gradle files.  The first one (Generator) exposes a run command that runs the generator taking the command line argument:
plugins {
  id "application"
  id "scala"
}

dependencies { compile "org.scala-lang:scala-library:2.12.3" }
mainClassName = "Main"
ext { cmdlineargs = "" }
run { args cmdlineargs }

The code generator is to be called from projectB (and an analogous projectC, and many others). I am trying to do this as follows (projectB/build.gradle):
task TEST {
  project (":Generator").ext.cmdlineargs = "Hurray!"
  println ("Value set:" + project(":Generator").ext.cmdlineargs )
  dependsOn (":Generator:run")
}

Whatever I try to do (a gradle newbie here) I am not getting what I need.  I have two problems:

*

*The property cmdlineargs is not set at the point that task :projectB:TEST is run.  The println sees the right value but the argument passed to the executed main method is the one configured in Generator/build.gradle, not the one in projectB/build.gradle. As pointed out in responses this can be work around using lazy property evaluation, but this does not solve the second problem.

*The generator is only run once, even if I build both projectB and projectC. I need to run Generator:run for each of projectB and projectC  separately (to generate different sources for each dependent project).

How can I get this to work? I suppose a completely different strategy is needed.  I don't have to use command line and run; I can also try to run the main class of the generator more directly and pass arguments to it, but I do find the run task quite convenient (the complex classpath is set up automatically, etc.). The generator is a Java/Scala project itself that is compiled within the same multi-project build.

A: Note: tasks aren't like methods in java. A task will execute either 0 or 1 times per gradle invocation. A task will never execute twice (or more) in a single Gradle invocation
I think you want two or more tasks. Eg:
task run1(type:xxx) {
    args 'foo'
}
task run2(type:xxx) {
    args 'bar'
}

Then you can depend on run1 or run2 in your other projects.


text:
Q: Failed to log into Docker mongo db What's weird is this is identical to what I've done in other microservices, so I am confused.
So here's my docker-compose.yaml
version: '4.12.0'

services:

  mongo:
    container_name: mongodb
    image: mongo:4.4.16
    environment:
      MODE: SINGLE
      MONGO_USER: mongoadmin
      MONGO_PASS: mongoadmin1234
    ports:
      - "27017:27017"

and my application.properties
# MongoDB Config
spring.data.mongodb.uri=mongodb://mongoadmin:mongadmin1234@localhost:27017
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.database=database-demo

when i go to start up spring boot i'm getting an authentication failed:
Caused by: com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed"}
    at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:175) ~[mongodb-driver-core-4.2.3.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:358) ~[mongodb-driver-core-4.2.3.jar:na]
    at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:279) ~[mongodb-driver-core-4.2.3.jar:na]
    at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83) ~[mongodb-driver-core-4.2.3.jar:na]
    at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33) ~[mongodb-driver-core-4.2.3.jar:na]
    at com.mongodb.internal.connection.SaslAuthenticator.sendSaslStart(SaslAuthenticator.java:227) ~[mongodb-driver-core-4.2.3.jar:na]
    at com.mongodb.internal.connection.SaslAuthenticator.getNextSaslResponse(SaslAuthenticator.java:134) ~[mongodb-driver-core-4.2.3.jar:na]

Additionally, with mongo DB compass, i can't log in with that user/pass either. This connection string works:
mongodb://localhost:27017

But this doesn't.
mongodb://mongoadmin:mongoadmin1234@localhost:27017

A: try to replace MONGO_USER with MONGO_INITDB_ROOT_USERNAME and MONGO_PASS with MONGO_INITDB_ROOT_PASSWORD


text:
Q: Corrupt VBA Project Module Not Found Error I have a workbook that was saved yesterday afternoon, and was working perfectly. I have opened it this morning, and none of the modules in the VBE are 'found'. Visually I can see them all sitting there.

When trying to open any of these modules to edit the code, the windows are greyed out, as below.

When I try exporting the code modules, I get the 'Module Not Found' errror.

Does anyone know a) why this has happened, and b) how can I fix this?
I thought initially it was the instance of my Excel, so have restarted the PC.
Any help is appreciated!

A: I managed to find a workaround to this problem, so sharing the solution in the event that someone else comes across a similar problem.
It seems that the VBA Project got corrupt somehow. Below, find some suggestions and workarounds in trying to solve something similar in the future.

*

*This is what worked for me. Convert the .xlsm file to a .xls file. You can do this by changing the file extension when renaming the file.

*You can also try to convert to .zip file type, and then convert back to .xlsm. Note: convert COPIES of your original, just in case.

Other suggestions (as Chris Nelisen suggested) are:

*

*Export your VBA modules regularly

*Save different versions as you are building

A: My workaround, works perfectly:

*

*Open Excel in safe mode (pressing and holding Ctrl while you start
the program, or by using the /safe switch (excel.exe /safe) when you
start the program from the command line)

*Open corrupted workbook (from safe mode, File->Open-> navigate)

*Do not enable macro if asked

*Make sure macro is present (Alt+F11) - not necessary

*Save as new workbook

*Close safe mode excel

*Open saved workbook as usual

A: This is a well-described issue, and it exactly matches what I have just experienced (even including the fact that I haven't been versioning recently).
My file has an xlsb suffix.  Resaving with a different suffix did not work for me on the same PC, but I emailed the file to another PC, opened it, saved as xlsm, sent it back to the original machine and it now works fine again.  I can even re-save with my preferred xlsb suffix and it still works.
I've also run this script to make a backup of my modules:
Sub ExportVbaModules()

'Acknowledgements to Andy Pope [ozgrid thread 60787]

    Dim objMyProj As VBProject 'if error, go to VBA editor - tools - References - Microsoft Visual Basic-Extensibility5.3
    Dim objVBComp As VBComponent

    Set objMyProj = Application.ActiveWorkbook.VBProject

    For Each objVBComp In objMyProj.VBComponents
        If objVBComp.Type = vbext_ct_StdModule And objVBComp.Name <> "" Then
            objVBComp.Export "C:\Users\MyName\VbaBackups\" & objVBComp.Name & ".txt"
        End If
    Next

End Sub

The And objVBComp.Name <> ""  stops it from erroring when it encounters a corrupted module but turned out not to be necessary as the 'fixed' file contained no corrupted modules.
Since that export routine is so fast (40 modules / 100kb saved in <1s) I will be assigning it to a button on the ribbon with a better naming convention for the files it creates.

A: I copied my .xslm file from my PC to my OneDrive account.
I open the file on my iPad OneDrive account and then export to Excel for iOS. The file opens and says links and macros are disabled. I then save a copy of the file back to the OneDrive account. I go back to my PC and open the file from OneDrive. I re-establish the links.
The macros are from a backup. This is an issue if you aren't backing up your macros.

A: Do you have this file on OneDrive?
If yes, I was facing that issue, and resolved restoring the last save. If you open OneDrive site (onedrive.live.com), find the file, and select Version History. Download the penultimate.

A: When this happens on 64 bit Excel, I simply open the exact same file in 32 bit Excel and the macros re-appear.
When this happens on 32 bit Excel, I simply open the exact file in 64 bit Excel and the macros re-appear.

A: Try to open the excel file in repair mode and save as the file one more time.
Open and Repair

A: I tried everything suggested and nothing worked. I could only see the module when I opened my VB editor.  It was not available through the view macros ribbon shortcut. I was unable to export the module or copy it to a new workbook.
What finally worked for me was emailing it to myself, downloading it through my 365 outlook account via a web browser, and then the code was there.


text:
Q: Set SpringJoint2D anchor point via script in Unity I'm trying to set the position of the connected anchor of a 2d spring joint via script. I'm using
SpringJoint2D springJoint = GetComponent<SpringJoint2d>();
springJoint.connectedAnchor.Set(somex, somey);

which isn't working. I can't imagine any other way to do this. Any ideas?

A: A little late, but for the future:
Your code must include:
springJoint.connectedBody.WakeUp();

as this wakes up the rigidbody. The reason Set() did not work is because this was not called, and the rigidbody was still asleep.

A: Never mind, just used
springJoint.connectedAnchor = new Vector2(somex, somey);

Can't believe I didn't think of that, although I don't know why Set() doesn't work.


text:
Q: Kotlin : Copy File from Res directory to internal storage I want to Copy a file from my res directory to internal storage  and delete that file after closing my application with Kotlin.
There are some code in Java but my goal is reaching that with Kotlin programing.
How can I do that?
I searched The web but there are not Good tutorial for this.

A: Read the file content from resources like:
val fileContent = MySpec::class.java.getResource("/myFiles/file.html").readText()

You can use this copyTo in Kotlin like:
 fun InputStream.copyTo(
    out: OutputStream,
    bufferSize: Int = DEFAULT_BUFFER_SIZE
): Long

This will Copies this stream to the given output stream, returning the number of bytes copied
Note: It is the caller's responsibility to close both of these resources.
Source: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-input-stream/copy-to.html
Delete it using:
val file = File(yourFIlePath)
file.absoluteFile.delete()


text:
Q: Why isn't this click event being fired? Why isn't the myMouseClick event being fired?
myMC:TestMC = new TestMC();
myMC.addEventListener(MouseEvent.CLICK, myMouseClick);
addChild(myMC);

function myMouseClick(e:MouseEvent):void {
    trace("clicked");
}

As far as I can tell from the tutorials I've seen, that should work. For a moment, I thought that since I was adding the event listener to myMC, I needed to have the event function inside the myMC class, but that didn't work. Just gave an error about accessing an undefined property.
If it helps any, TestMC is a seperate .as file that extends movie clip.
I'm just trying to make it so when the movie clip itself is clicked, it does something. The movie clip itself will be following the mouse.

A: The object I was trying to click was made up on vertical lines. Apparently the whole movie clip isn't a collider... just the pixels in it, so when I was clicking, I wouldn't hitting enough of it. Changing it to a box worked. I could probably nest it if I wanted the same design, but that's fine.


text:
Q: Dynamically set the VALUE of an text-INPUT element to default by clicking SELECT option Ok, here is the first thing that what I want to do:
1) Lets say a user has been adding text to one or to both of the input fields. Now, if the user is either selecting option value 'Name1' or option value 'Name2' of the select field the input fields value have to be reseted. How can this be done?

    <input id='vlastname' name='ulastname' type='text' value=''></input>
    <input id='vfirstname' name='ufirstname' type='text' value=''></input>

<select>
    <option selected='true' value=''>Choose</option>
    <option value='Name1'></option>
    <option value='Name2'></option>
</select>

2) Now the other way round: If either option value 'Name1' or option value 'Name2' is selected: How can this value be reseted to the 1st option with value '' if the user adds text to an input field?

A: 1. For the first question.

If the user is either selecting option value 'Name1' or option value 'Name2' of the select field the input fields value have to be reseted

You can use change event to handle the user change and reset input using val('') :
$('#customerIsInDatabase select').change(function(){
     if ( $(this).val() != '' )
     {
         $('#vlastname').val('');
         $('#vfirstname').val('');
     }
});

2. For the second question.

If either option value 'Name1' or option value 'Name2' is selected: How can this value be reseted to the 1st option with value '' if the user adds text to an input field?

You can use keyup event to detect user action when any key presed in input field :
$('#CustomerIsNotInDatabase input').keyup(function()
{
      $('#customerIsInDatabase select').val('').change();
});

Hope this helps.

Full Example :

$('#customerIsInDatabase select').change(function()
{
     if ( $(this).val() != '' )
     {
         $('#vlastname').val('');
         $('#vfirstname').val('');
     }
});

$('#CustomerIsNotInDatabase input').keyup(function()
{
      $('#customerIsInDatabase select').val('').change();
});

    <input id='vlastname' name='ulastname' type='text' value=''></input>
    <input id='vfirstname' name='ufirstname' type='text' value=''></input>

<select>
    <option selected='true' value=''>Choose</option>
    <option value='Name1'>Name1</option>
    <option value='Name2'>Name2</option>
</select>

A: $('#customerIsInDatabase select').on('change', function(){
    $('#CustomerIsNotInDatabase').find('input:text').val('');
});

$('#CustomerIsNotInDatabase input').on('keypress', function(){
    $('#customerIsInDatabase select').val('');
});

Fiddle
EDIT (solution based on comment to update the 'selected' attribute)
$('#customerIsInDatabase select').on('change', function(){
    var selectedVal = $(this).val();
    setSelected(selectedVal);
    $('#CustomerIsNotInDatabase').find('input:text').val('');
});

$('#CustomerIsNotInDatabase input').on('keypress', function(){
    $('#customerIsInDatabase select').val('');
    setSelected('');
});

function setSelected(selVal) {
    $("select option").attr("selected",false);
    $("select option[value='" + selVal +"']").attr("selected",true);
}

Updated Fiddle


text:
Q: Minutes difference between concecutive rows based empid wise in SQL Server I have a question about SQL Server: how to calculate minutes difference between current and previous row?
Sample data: table step1:
CREATE TABLE [dbo].[step1]
(
    [Emp ID] [float] NULL,
    [time] [datetime] NULL,
    [gr] [int] NOT NULL,
    [group_] [int] NULL
) ON [PRIMARY]
GO

INSERT [dbo].[step1] ([Emp ID], [time], [gr], [group_])
VALUES (1, CAST(N'2017-08-02T09:00:00.000' AS DateTime), 1, 1),
       (1, CAST(N'2017-08-02T10:30:00.000' AS DateTime), 0, 1),
       (1, CAST(N'2017-08-02T11:00:00.000' AS DateTime), 0, 1),
       (1, CAST(N'2017-08-02T12:00:00.000' AS DateTime), 0, 1),
       (1, CAST(N'2017-08-02T13:00:00.000' AS DateTime), 0, 1),
       (1, CAST(N'2017-08-03T06:30:00.000' AS DateTime), 1, 2),
       (1, CAST(N'2017-08-03T08:30:00.000' AS DateTime), 0, 2),
       (1, CAST(N'2017-08-03T09:30:00.000' AS DateTime), 0, 2),
       (1, CAST(N'2017-08-03T12:30:00.000' AS DateTime), 0, 2),
       (1, CAST(N'2017-08-03T12:40:00.000' AS DateTime), 0, 2),
       (1, CAST(N'2017-08-03T17:10:00.000' AS DateTime), 0, 2),
       (1, CAST(N'2017-08-05T23:30:00.000' AS DateTime), 1, 3),
       (1, CAST(N'2017-08-06T01:55:00.000' AS DateTime), 0, 3),
       (1, CAST(N'2017-08-06T02:15:00.000' AS DateTime), 0, 3),
       (1, CAST(N'2017-08-06T06:10:00.000' AS DateTime), 0, 3),
       (1, CAST(N'2017-08-06T14:01:00.000' AS DateTime), 1, 4),
       (1, CAST(N'2017-08-06T15:01:00.000' AS DateTime), 0, 4),
       (1, CAST(N'2017-08-06T15:20:00.000' AS DateTime), 0, 4),
       (1, CAST(N'2017-08-06T20:01:00.000' AS DateTime), 0, 4),
       (5, CAST(N'2017-08-02T23:30:00.000' AS DateTime), 1, 1),
       (5, CAST(N'2017-08-03T01:30:00.000' AS DateTime), 0, 1),
       (5, CAST(N'2017-08-03T01:40:00.000' AS DateTime), 0, 1),
       (5, CAST(N'2017-08-03T04:00:00.000' AS DateTime), 0, 1),
       (5, CAST(N'2017-08-03T04:30:00.000' AS DateTime), 0, 1),
       (5, CAST(N'2017-08-03T06:00:00.000' AS DateTime), 0, 1);

Based on above data I want output like below:
Emp ID | Time                    | gr | group_ | diffminutes
-------+-------------------------+----+--------+-------------
    1  | 2017-08-02 09:00:00.000 | 1  |   1    |  90
    1  | 2017-08-02 10:30:00.000 | 0  |   1    |  30
    1  | 2017-08-02 11:00:00.000 | 0  |   1    |  60
    1  | 2017-08-02 12:00:00.000 | 0  |   1    |  60
    1  | 2017-08-02 13:00:00.000 | 0  |   1    | NULL
    1  | 2017-08-03 06:30:00.000 | 1  |   2    | 120
    1  | 2017-08-03 08:30:00.000 | 0  |   2    |  60
    1  | 2017-08-03 09:30:00.000 | 0  |   2    | 180
    1  | 2017-08-03 12:30:00.000 | 0  |   2    |  10
    1  | 2017-08-03 12:40:00.000 | 0  |   2    | 270
    1  | 2017-08-03 17:10:00.000 | 0  |   2    | NULL
    1  | 2017-08-05 23:30:00.000 | 1  |   3    | 145
    1  | 2017-08-06 01:55:00.000 | 0  |   3    |  20
    1  | 2017-08-06 02:15:00.000 | 0  |   3    | 235
    1  | 2017-08-06 06:10:00.000 | 0  |   3    | NULL
    1  | 2017-08-06 14:01:00.000 | 1  |   4    |  60
    1  | 2017-08-06 15:01:00.000 | 0  |   4    |  19
    1  | 2017-08-06 15:20:00.000 | 0  |   4    | 281
    1  | 2017-08-06 20:01:00.000 | 0  |   4    | NULL
    5  | 2017-08-02 23:30:00.000 | 1  |   1    | 120
    5  | 2017-08-03 01:30:00.000 | 0  |   1    |  10
    5  | 2017-08-03 01:40:00.000 | 0  |   1    | 140
    5  | 2017-08-03 04:00:00.000 | 0  |   1    |  30
    5  | 2017-08-03 04:30:00.000 | 0  |   1    |  90
    5  | 2017-08-03 06:00:00.000 | 0  |   1    | NULL

I tried like below query :
select
    a.[Emp ID], a.Time,
    datediff(mi, a.Time, b.Time) diffminutes
from
    (select
         *,
         row_number() over (partition by [Emp ID], group_ order by time) as rn
     from
         step1) a
left join
    (select
         *,
         row_number() over (partition by [Emp ID], group_ order by time) as rn
     from
         step1) b on a.[Emp ID] = b.[Emp ID]
                  and a.rn = b.rn + 1
order by
    a.Time

but it's not returning the expected result.
Can you please tell me how to achieve this task in SQL Server?

A: Try this for SQL Server 2008:
;with cte as
(select *,ROW_NUMBER() OVER (PARTITION BY GROUP_ ORDER BY [time]) as rownumber
 from step1

 )
 select c1.* ,abs(datediff(minute,c2.[time],c1.[time]))
 from cte c1
 left join
 cte c2
 on c1.[emp id]=c2.[emp id]
 and c1.group_=c2.group_
 and c1.rownumber+1=c2.rownumber
 order by c1.[emp id],c1.[time]

From SQL Server 2012 version onwards, this became much simpler:
select
    *,
    abs(datediff(minute,
        lead([time]) over (partition by [emp id], group_ order by [time]), time)) as diff
from step1


text:
Q: Bootstrap 3 stack image in the same row I'm trying to stack the image on top of all the text, with the image on the same row with some text.

<!DOCTYPE html>

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">

    <link rel="stylesheet" href="style.css">

        Bob

bob@example.com

23

Contact

Party

Start Term	2016.01.01

End Term	2016.01.01

Term	today

Office	here

State	CA

Fax	here

Birthday	today

Social Links	here

Please see my code in action at:
https://plnkr.co/edit/YgcNPhX8hc4HnNgZALBr?p=preview
The tricky part is the image is in the row:

wich takes 6 tds into one, and I want to stack it on top of everything using bootstrap3.
Please refer to the pictures to see what I'm talking about:
Before:

After:

Thank you guys in advance!

A: I don't know what is going on with your tables in your html above, that's not bootstrap at all. Nevertheless, here is what you need to implement this layout in it's simplest form:
https://plnkr.co/edit/yK4MSDMA63P1n0roSgAW?p=preview
The html looks like this. it is essentially 2 rows of content. The first row is split in 2 divs, both of which will take up 12 (full width) grid places when the viewport of the browser is small, and 6 when it is medium or greater (that's what the col-md-6 class does).  The 2nd row has a div with a column of class col-xs-12, meaning it will take up full width even on the smallest (phone) sizes. That should get you started.

Bacon ipsum dolor amet pancetta jowl filet mignon capicola ball tip jerky. Capicola t-bone filet mignon ball tip pork loin beef ribs bresaola pancetta shank biltong andouille porchetta ham hock short loin pastrami. Meatball frankfurter leberkas tenderloin brisket sausage salami ribeye ham ham hock andouille rump venison bacon. Drumstick tri-tip shoulder pork chop kielbasa tenderloin sausage prosciutto short ribs frankfurter hamburger t-bone chuck. Turducken pig meatloaf, meatball swine short ribs t-bone jerky. Strip steak cow boudin, sirloin leberkas pork chop frankfurter t-bone jowl rump tri-tip alcatra. Prosciutto meatball salami picanha pig.

Bacon ipsum dolor amet pancetta jowl filet mignon capicola ball tip jerky. Capicola t-bone filet mignon ball tip pork loin beef ribs bresaola pancetta shank biltong andouille porchetta ham hock short loin pastrami. Meatball frankfurter leberkas tenderloin brisket sausage salami ribeye ham ham hock andouille rump venison bacon. Drumstick tri-tip shoulder pork chop kielbasa tenderloin sausage prosciutto short ribs frankfurter hamburger t-bone chuck. Turducken pig meatloaf, meatball swine short ribs t-bone jerky. Strip steak cow boudin, sirloin leberkas pork chop frankfurter t-bone jowl rump tri-tip alcatra. Prosciutto meatball salami picanha pig.

A: I edited the plunker link as per your requirements. I don't have an account on plunker so my code will not be saved on the link. Here is the code for your reference:
    <!DOCTYPE html>

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">

    <link rel="stylesheet" href="style.css">

Bob

bob@example.com

23

Contact

Party

Start Term	2016.01.01

End Term	2016.01.01

Term	today

Office	here

State	CA

Fax	here

Birthday	today

Social Links	here

I added css style selectors to get the effect. Also removed rowspan attribute from the img td. You should not need 6 tds to get the desired effect from your image. You can put it in one td in a row, and apply the background-size:cover property to stretch the image proportionally into a row.


text:
Q: Record voice from html page and convert it to text using JS? this code bellow just can record voice and give u button for download it any help to record voice then convert it to text in frensh thx
<script>
    navigator.mediaDevices.getUserMedia({audio:true})
        .then(stream => {
            rec = new MediaRecorder(stream);
            rec.ondataavailable = e => {
                audioChunks.push(e.data);
                if (rec.state == "inactive"){
            let blob = new Blob(audioChunks,{type:'audio/x-mpeg-3'});
            recordedAudio.src = URL.createObjectURL(blob);
            recordedAudio.controls=true;
            recordedAudio.autoplay=true;
            audioDownload.href = recordedAudio.src;
            audioDownload.download = 'mp3';
            audioDownload.innerHTML = 'download';
         }
            }
        })
        .catch(e=>console.log(e));

    startRecord.onclick = e => {
      startRecord.disabled = true;
      stopRecord.disabled=false;
      audioChunks = [];
      rec.start();
    }
    stopRecord.onclick = e => {
      startRecord.disabled = false;
      stopRecord.disabled=true;
      rec.stop();
 }
</script>


text:
Q: How to wait for LESS JS to load the .less file? My webpage includes a less file instead of css. This is parsed by the less js script. My site's js script fires on dom ready and based on different dom dimensions layouts the page.
The problem is, over slow network my js file can fire before less js is able to download the  less file. Since this is an unknown file type so the browser is not obliged to wait for this file to download and then fire dom ready, even when it is in the <head> section. In this scenario my js reads incorrect dimensions since no CSS rules have been applied yet.
So, my query is, how do I know when the less file have been downloaded. So that my js code can get fired after less has been downloaded and dom is ready.

A: Check out the answer to this similar question - sounds like you just need to fire a less.refreshStyles() event which will re-compile <style> tags with type="text/less".


text:
Q: How do I sync 2 objects based on the change of a checkbox? I'm at the very beginning stage of learning Angularjs, so please bear with me for asking this stupid question. I basically want to do it the right way from the start instead of just making it work.
Anyhow, I have 1 Order Checkout form which contains 2 sets of addresses: shipping and billing. I have a checkbox which says "Shipping address is the same as billing address", which if checked should sync the 2 addresses.
My approach is that 2 addresses will be treated as 2 objects, and if the checkbox is checked then I will have something like scope.shippingAddress = scope.billingAddress.
I wonder if the above is a good way to do it?
Also, what is a good way to trigger the above syncing upon checkbox change? Should I use ng-checked or perhaps should I use $watch?

A: I would use a watch:
$scope.$watch('shippingIsSameAsBilling', function(value) {
  if(value) {
    $scope.shippingAddress = $scope.billingAddress;
  } else {
    $scope.shippingAddress = angular.copy($scope.shippingAddress);
  }
});

You need to "unsync" the two addresses if the user unchecks the checkbox again by assigning each its own object (using angular.copy).
See this Plunker for a working example.
Note that you'll be sending two identical addresses to your back-end. Are you sure you want to do it that way?


text:
Q: Google Cloud Print service for Windows Server Currently I have my Android tablet set up to print through Chrome's Cloud Print service on my PC. This works, but requires that my PC be on whenever I want to print. Since the point of having the tablet is to be able to use network services when I'm away my PC is usually off when I'm not using it.
I'd like to set up Cloud Print on my Windows server (which is always on) and configure my tablet to use a printer there instead. (As it happens, it's the same printer, but that's by-the-by). Google have a Windows service I could use, but it requires that I install Chrome on my server, which I don't want to do if I can avoid it.
So my question is: is there a non-Chrome Windows service I can use to share my printer through GCP?
I did find one for Linux which I could use (I have a Fedora server too), but Linux print drivers for my printer are hard to come by.


text:
Q: Can I reposition and/or split android keyboard? I am writing a custom android IME, and would like the keyboard on the side of the display rather than the bottom (actually, I want the user to have options). If possible, I would like to split the keyboard into 2 or more parts, located around the display edges.
I have reviewed various complicated solutions which may need extensive cross-device testing.
Is there a simple (and reliable) way to do this, with say, XML layout?  I know Java, but not much about android layout.

A: Answering my own question, after much digging I think the answer is no, there is no simple way of moving the keyboard from the bottom of the display.  I have settled on a very small "keyboard" along the bottom, and then creating a mostly transparent popup view.  Not nearly as simple as what I was hoping for, but I think I can eventually get it to look the way I want.


text:
Q: Blocking request to port 80 on gateway on Ubuntu I want to block access to the gateway (192.168.1.1) on port 80, to prevent network user from trying to access the router setup.  I'm using Ubuntu 9.10

A: iptables -A INPUT -j DROP -p tcp --to-destination 192.168.1.1:80 -i eth0

Change --to-destination 192.168.1.1:80 to the IP address of the gateway.
Change -i eth0 to the interface that you need the rule on.
Note that this will completely block all access to that IP/port combination unless you create a specific rule to allow traffic from one IP, like perhaps an administrative workstation.


text:
Q: R-Missing Data Analysis-interpretation of plot made by extracat::visna I just used visna() function in extracat package to visualize missing data, but I don't know what does the blue cells mean? And how to interpret the bar chart on the right?
df <- data.frame(replicate(25,sample(0:1,1000,rep=TRUE)))
df2 <- as.data.frame(lapply(df, function(cc) cc[ sample(c(TRUE, NA), prob = c(0.85, 0.15), size = length(cc), replace = TRUE) ]))
# visualise the number of missings in cases using visna from extracat
extracat::visna(df2)

A: The blue cells represent the missing values.
For your data frame this means:
variable x1 has all it's missing values at the end of your data.frame.
For variable X25 the missing values are distributed all over the data frame
The red bar below is the amount of missing values for this variable.
I think the bar char on the right is the amount of complete rows for the respective bin of data.
For nice missing data visualizations also take a look at the naniar package.
( https://cran.r-project.org/web/packages/naniar/vignettes/getting-started-w-naniar.html )


text:
Q: Why tailwind utilities and components does not work for me? I've installed tailwind using npm install tailwindcss and I wrote
@tailwind base;
@tailwind components;
@tailwind utilities;

in input.css file, but it does not recognize @tailwind command and it gives error. When I run build command output.css file has only 500 lines of css code.
I use VSCode, and tailwind v3.
I configured everything according to the official tailwind docs.


text:
Q: discordpy 2.0 interaction is a required argument that is missing @client.command(brief="Send a message with a button!")
async def button(ctx,interaction: discord.Interaction):
    view = discord.ui.View()
    style = discord.ButtonStyle.gray
    item = discord.ui.Button(style=style, label="Read the docs!", url="https://discordpy.readthedocs.io/en/master")
    view.add_item(item=item)
    await interaction.response.send_message("This message has buttons!", view=view)
    await interaction.response.send_message(content="Hi", ephemeral=True)

discord.ext.commands.errors.MissingRequiredArgument: interaction is a required argument that is missing.

Actually i just want to send a message by intraction, but seem itwasn't work :(

A: I think you are confused about the basic concepts since your code is mixed up command and interaction stuffs.
If you want to create button, you cannot write in the older command way like @client.command. You need to either use application command or hybrid command (which is a mix of interaction and command)
So, you should never have something like (ctx: Context, interaction: Interaction) together.
Also, classically, you need to create a view class and create a button inside this view class. Then you can attach this view to your message or embed when you send this to the user.
And, if you want to respond to user multiple times in a application command, you cannot do that through interaction.response (only once). You can use interaction.followup() for later responses. link
For view examples, see file example under this
For slash command (application command) example, see this


text:
Q: There is no sound in the video I created ffmpeg -i intro.mp4 -i video.mp4 -i watermark.jpg -filter_complex "[0:v]scale=854x480[intro];[1:v][2:v] overlay=x=10:y=10,drawtext=text=TEXT':box=1:boxborderw=5:boxcolor=black:x=(w-text_w)/2:y=h-th:fontsize=30:fontcolor=white:enable='between(t,0,15)'[main];[intro][main]concat=n=2:v=1:a=0[out]" -map "[out]" -pix_fmt yuv420p -c:a copy out.mp4

I want the video to work properly with the sound problem fixed.
I'm waiting for your help


text:
Q: Changed limits: max_connections: 214 I am using  MySQL version 5.7.15 , ubuntu0.16.04.1. When I start the MySQL, I am getting below log,
2016-11-06T13:44:56.838233Z 0 [Warning] option 'table_open_cache': unsigned value 33554432 adjusted to 524288
2016-11-06T13:44:56.839061Z 0 [Warning] Changed limits: max_open_files: 1024 (requested 1049386)
2016-11-06T13:44:56.839078Z 0 [Warning] Changed limits: max_connections: 214 (requested 800)
2016-11-06T13:44:56.839082Z 0 [Warning] Changed limits: table_open_cache: 400 (requested 524288)

$ ulimit -Sa | grep "open files"
open files                      (-n) 1024

In google, It is specified like open_files_limit value need to be increased to have more max_connections.
Will it be enough to set below values on the /etc/mysql/mysql.conf.d/mysqld.cnf and restarting the MySQl server ?
open_files_limit = 2048

max_connections = 800

table_open_cache = 600

Is there any other way to change the values without restarting the MySQL server ?
Is setting the open_files_limit on the MySQL configuration file enough ?

A: You can always check if a variable is dynamic or not with on http://dev.mysql.com/doc/refman/5.7/en/dynamic-system-variables.html
Or looking at the parameter directly:
http://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_open_files_limit
If it is dynamic you can:
set global <variable_name> = <value>;

Just don't forget to change in your my.cnf also otherwise next restart will override it.

If it is not then you have to restart MySQL to make it happen. Oracle is working on getting more and more variable dynamic and you can see the trend going through 5.5 -> 5.6 -> 5.7. Unfortunately though there's always going to be parameters which require restart.

A: First, you have to make an OS change to increase open files (-n) 1024.  MySQL's value only reflects that.
max_connections = 214 is a generous number.  Let's discuss whether you really need more.
24 connections from one server is potentially excessive.  If there are that many, they may be stumbling over each other.  The end result is increased latency without increased throughput.  I have seen cases like this; the best remedy is to throttle things earlier, not later.
The units of table_open_cache is tables, not bytes.  And it is a cache, so it is usually OK to have a smallish number.  (There are STATUS values that indicate whether it is 'too small'.)
Bottom line:  Decrease the number of client threads until you can restart mysqld.


text:
Q: Insert today's date at the end of a text file - using bash I have a text files that is generated through daily running bash script - I want to append a date field into that text file - how can I achieve it ?
Name   NUM_OF_USERS

A------10

B------20

**date--29/05/2019**

The --- is just to represent the question well (showcase table)

A: Just add
 date +"date--%d/%m/%Y" >> file.txt

to the report generation script.


text:
Q: Socket.io + nodejs chat system alongside PHP: validating data before emitting through node I have a PHP application that is already up and running and we have to implement a chat messaging system in it. We chose to do this with nodejs and socket.io as it seems the most effective and one of the best documented. I have PHP handling all the DB stuff and node just doing what it's most effective at: nonblocking io to update the client side when a message is received real time (through rooms). I also have a token based authentication going on using jsonwebtokens.
Everything is actually running well now:
When someone sends a message
 1. JS send an ajax request to PHP
 2. PHP saves the message to the database
 3. PHP returns a response
 4. JS receives the ajax response and then emits an event to signal to the node to update the appropriate clients
 5. Node emits an event to the appropriate clients to update their views: notif icons, creates a silly sound and what not.

What I'm worried about are in steps 4 and 5. Since the data that will be passed to node in these steps are in the client side, any rogue user can effectively make modifications to these data and potentially be able to trigger an update of a view of another user even if he is not the intended receiver. The obvious solution I that I can think of is to allow node to have access to the database and validate that only the legitimate recipient will receive the event trigger, but that defeats the purpose of separating the concerns of the PHP app and node. What is the standard way of handling such a situation?

A: After a bit of reading  I've decided on using Redis because of its PubSub capability. Refer to this for anyone who has the same concern: Redis sub/pub and php/nodejs


text:
Q: Include only required font icons in prod I would like to use Font Awesome, but only few icons will be needed. The project is in Angular 10 and I'm using SCSS.
Is it possible to install Font Awesome as dev dependency and then only import the icons that I'll need in my _vendors.scss stylesheet? (I'm following 7.1 pattern with SCSS structure). I have done something similar with bootstrap, where I only imported grid and necessary variables and mixins.


text:
Q: How to duplicate the full screen on a second monitor, but hide a specific window? I want to duplicate my screen on a projector attached to my laptop (which I know how to do).
I've also a small text-editor window (with my notes) that I'd like to be always-on-top on my laptop, but hide completely on the second display.
One solution I got proposed was to set up the screens in extended-mode. And then capture the window I do want to project using VLC or OBS, and preview it on the second screen. However, I will be switching between multiple apps (such as browsers, slides, code-editors...), all of which I want to project. So I am looking for a way to specify the window I don't want to project.


text:
Q: How to zoom in out with the Google cardboard I'm working in a project with the cardboard from Google. I'm asking if there is someone who have the possibility to help with understanding and creating a script for the zoom in and out with the magnet tool on the cardboard. Thanks a lot for your help.

A:  Used this code
@Override
public void onCardboardTrigger() {
if (xyz) {
 //Create a function
zoom();
    ...
} else {

}
// Always give user feedback
  mVibrator.vibrate(50);
}