text:
Q: Mann-Whitney null hypothesis under unequal variance I'm just curious about the null hypothesis of a Mann-Whitney U test. I often see it stated that the null hypothesis is that two populations have equal distributions. But I'm thinking - if I had two normal populations with the same mean but extremely unequal variance, the Mann-Whitney test would probably not detect this difference.
I have also seen it stated that the null hypothesis of the Mann-Whitney test is $\Pr(X>Y)=0.5$ or  the probability of an observation from one population ($X$) exceeding an observation from the second population ($Y$) (after exclusion of ties) is equal to 0.5. This seems to make a bit more sense but does not seem equivalent to the first null hypothesis I stated.
I'm hoping to get a bit of help untangling this. Thanks!

A: The Mann-Whitney test is a special case of a permutation test (the distribution under the null is derived by looking at all the possible permutations of the data) and permutation tests have the null as identical distributions, so that is technically correct.
One way of thinking of the Mann-Whitney test statistic is a measure of the number of times a randomly chosen value from one group exceeds a randomly chosen value from the other group.  So the P(X>Y)=0.5 also makes sense and this is technically a property of the equal distributions null (assuming continuous distributions where the probability of a tie is 0).  If the 2 distributions are the same then the probability of X being Greater than Y is 0.5 since they are both drawn from the same distribution.
The stated case of 2 distributions having the same mean but widely different variances matches with the 2nd null hypothesis, but not the 1st of identical distributions.  We can do some simulation to see what happens with the p-values in this case (in theory they should be uniformly distributed):
> out <- replicate( 100000, wilcox.test( rnorm(25, 0, 2), rnorm(25,0,10) )$p.value )
> hist(out)
> mean(out < 0.05)
[1] 0.07991
> prop.test( sum(out<0.05), length(out), p=0.05 )

        1-sample proportions test with continuity correction

data:  sum(out < 0.05) out of length(out), null probability 0.05
X-squared = 1882.756, df = 1, p-value < 2.2e-16
alternative hypothesis: true p is not equal to 0.05
95 percent confidence interval:
 0.07824054 0.08161183
sample estimates:
      p
0.07991

So clearly this is rejecting more often than it should and the null hypothesis is false (this matches equality of distributions, but not prob=0.5).
Thinking in terms of probability of X > Y also runs into some interesting problems if you ever compare populations that are based on Efron's Dice.

A: Mann-Whitney isn't sensitive to changes in variance with equal mean, but it can - as you see with the $P(X>Y)=0.5$ form, detect differences that lead $P(X>Y)$ to deviate from $0.5$ (e.g. where both mean and variance increase together). Quite clearly if you had two normals with equal mean, their differences are symmetric about zero. Therefore $P(X>Y) = P(X-Y>0) = \frac{1}{2}$, which is the null situation.
For example, if you have the distribution of $Y$ being exponential with mean $1$ while $X$ has an exponential distribution with mean $k$ (a scale change), the Mann-Whitney is sensitive to that (indeed, taking logs of both sides, its just a location-shift, and the Mann-Whitney is unaffected by monotonic transformation).
--
If you're interested in tests which are conceptually very similar to the Mann-Whitney that are sensitive to differences in spread under equality of medians, there are several such tests.
There's the Siegel-Tukey test and the Ansari-Bradley test, for example, both closely related to the Mann-Whitney-Wilcoxon two sample test.
They are both based on the basic idea of ranking in from the ends.
If you use R, the Ansari-Bradley test is built in ... ?ansari.test
The Siegel-Tukey in effect just does a Mann-Whitney-Wilcoxon test on ranks computed from the sample differently; if you rank the data yourself, you don't really need a separate function for the p-values. Nevertheless, you can find some, as here:
http://www.r-statistics.com/2010/02/siegel-tukey-a-non-parametric-test-for-equality-in-variability-r-code/
--
(in relation to ttnphns' comment under my original answer)
You would be over-interpreting my response to read it as disagreeing with @GregSnow in any particularly substantive sense. There's certainly a difference in emphasis and to some extent in what we're talking about, but I'd be very surprised if there was much real disagreement behind it.
Let's quote Mann and Whitney: "A statistic $U$ depending on the relative ranks of the $x$'s and $y$'s is proposed for testing the hypothesis $f=g$." That's unequivocal; it utterly supports @GregSnow's position.
Now, let's see how the statistic is constructed: "Let $U$ count the number of times a $y$ precedes an $x$." Now if their null is true, the probability of that event is $\frac{1}{2}$ ... but there are other ways to get a probability of 0.5, and in that sense one might construe that the test can work in other circumstances. To the extent that they're estimating a (re-scaled) probability that $Y$>$X$, it supports what I said.
However, for the significance levels to be guaranteed to be exactly correct, you'd need the distribution of $U$ to match the null distribution. That's derived on the assumption that all the permutations of the $X$ and $Y$ group-labels labels to the combined observations under the null were equally likely. This is certainly the case under $f=g$. Exactly as @GregSnow said.
The question is the extent to which this is the case (i.e. that the distribution of the test statistic matches the one derived under the assumption that $f=g$, or approximately so), for the more generally expressed null.
I believe that in many situations that it does; in particular for situations including but more general than the one you describe (two normal populations with the same mean but extremely unequal variance can be generalized quite a bit without altering the resulting distribution based on ranks), I believe that the distribution of the test statistic turns out to have the same distribution under which it was derived and so should be valid there. I did some simulations that seem to support this. However, it won't always be a very useful test (it may have poor power).
I offer no proof that this is the case. I've applied some intuition/hand-wavy argument and also done some basic simulations that suggest it's true -- that the Mann-Whitney works (in that it has the 'right' distribution under the null) much more broadly than when $f=g$.
Make of it what you will, but I don't construe this as substantive disagreement with @GregSnow
Reference - Mann&Whitney's original paper


text:
Q: How to migrate sql changes with the latest build installation using jenkins I'm a beginner to Jenkins.I have a DotNet program on my local system, I make changes and push the changes to GitHub repo. Then I go to a remote machine and there I use Jenkins to trigger a build and copy that build program(.msi installer file) to my local then install it, but now I want that db changes(Sql) should also reflect in my local SSMS once I install the build.(The Github repo has all the db scripts under DB folder.)
I tried to go through Powershell Cmdlets but not getting any clear idea on it.
Neither got any good resource on this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why doesn't my created DB show up when I doe show databases in mongo? I tried going into a mongo shell and creating a DB, and it seems to have worked, its saying I'm in the db i created but when I run show databases; it doesnt show in the list.
Here is what terminal shows:
> show databases;
admin   0.000GB
config  0.000GB
local   0.000GB
> use sr-dev
switched to db sr-dev
> show databases;
admin   0.000GB
config  0.000GB
local   0.000GB
> db
sr-dev
>

A: Mongo only creates databases and collections as needed, as lazily as possible. You didn't "create" sr-dev, you're merely "using" it at the moment. Think of it as "being in the namespace sr-dev". Once you insert your first data the actual database will be created. Before you do that, there's no need for it to exist.

Create a Database
If a database does not exist, MongoDB creates the database when you first store data for that database. As such, you can switch to a non-existent database and perform the following operation in the mongo shell: [..]
https://docs.mongodb.com/manual/core/databases-and-collections/#create-a-database

A: When you create a database in MongoDb shell, it won't show up until there are some collections in your database.
Please try adding some collections in your newly created database and run show databases command again, It will show up.
db.createCollection('collection_name',{...})
Here the 2nd parameter is optional.
Please read MongoDb createCollection documentation for more info, on 2nd parameter options.

A: You will have to create collection inside your db.
MongoDB works this way.


text:
Q: Adding new themes in VSCode doesn't work I just downloaded version 0.9.1 as I've been waiting for better theme support. I followed the instructions from here, but nothing happens. I see the theme show up in the Color Theme list, but selecting it changes non of the keywords, tags, ect to the theme's colors. I downloaded the Twilight theme from ColorSublime as an example. Anyone else getting this to work?

A: It seems there's a fix on the way from the VSCode team.


text:
Q: jQuery append content increase Here is a sample code:
var i1 = $("content1");
var i2 = $("content2");
var i3 = $("content3");
var i4 = $("content4");
var i5 = $("content5");
b.append(i1);

This is the desired effect:

*

*When the first +1 button is clicked, b.append(i1) should be called and content1 shown;

*When the second +1 button is clicked, b.append(i2) should be called and content2 shown;

*When the third+1 button is clicked, b.append(i3) should be called and content3 shown;

*When the fourth +1 button is clicked, b.append(i4) should be called and content4 shown;

*When the fifth +1 button is clicked, b.append(i5) should be called and content5 shown;

So far this is what I have been able to achieve: working fiddle

A: not sure if this is what you want..
added a var clickedcount in your codes , used switch() and likewise displayed the content..
you don't need different variable .. i managed it with the same variable i1
check this fiddle..

A: See this updated fiddle:  http://jsfiddle.net/huZzq/7/
Since you are having a count in cur variable, it can be used with eval() function as follows :
b.append(eval('i' + cur));

For removing :
var index = c.attr("value").replace("-","");
(eval('i' + (index))).remove();


text:
Q: I forgot to activate Track Changes in a Word document. How to highlight my edits? After I saved the document and closed Word, I realised that I forgot to activate Track Changes. I have a copy of the previous revision.
How can I highlight my (too many) edits before sending the document back to a colleague who is not computer literate enough to use the common "diff" tools?

A: Since you have a copy of the previous revision, you can use Word's "Compare documents" functionality to create a new Word document highlighting the changes you made.
For versions of Word with the ribbon, this option can be found on the Review tab, in the Compare group.
https://support.office.com/en-us/article/Compare-documents-with-the-legal-blackline-option-dbfc7351-4022-43a2-a0c4-54d1898702a0


text:
Q: C# List Of Orders Made I'm quite new to C# and still learning, my apologies if this is a simple question.
When a user orders an item(s), the items are assigned an OrderId which is then related to an Order using this OrderId. Now however I need to link both of these and display them so only the user ordering them can view them(Based on the Username which is stored in Orders Class)
How would I do this in my ViewOrdersController?
Current Classes:
Order
[Bind(Exclude = "OrderId")]
    public partial class Order
    {
        [ScaffoldColumn(false)]
        public int OrderId { get; set; }

        [ScaffoldColumn(false)]
        public System.DateTime OrderDate { get; set; }

        [ScaffoldColumn(false)]
        [Remote("CheckUserName", "Account")]
        public string Username { get; set; }

        [Required]
        [StringLength(16, ErrorMessage = "Your name is too long")]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Your last name is required.")]
        [StringLength(16, ErrorMessage = "Last name is too long.")]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Required(ErrorMessage = "Address is required.")]
        public string Address { get; set; }

        [Required(ErrorMessage = "City is required.")]
        public string City { get; set; }

        [Required(ErrorMessage = "Postcode is required.")]
        [Display(Name = "Post Code")]
        public string PostalCode { get; set; }

        [Required(ErrorMessage = "Country is required.")]
        public string Country { get; set; }

        [Required(ErrorMessage = "Phone number is required.")]
        public string Phone { get; set; }

        [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "Email doesn't look like a valid email address.")]
        public string Email { get; set; }

        [System.ComponentModel.DataAnnotations.Compare("Email")]
        [Display(Name = "Confirm your email address")]
        public string EmailConfirm { get; set; }

        [ScaffoldColumn(false)]
        public string PaymentTransactionId { get; set; }

        public bool HasBeenShipped { get; set; }

        [ScaffoldColumn(false)]
        [ReadOnly(true)]
        public decimal Total { get; set; }

        public List<OrderDetail> OrderDetails { get; set; }
    }

OrderDetail
 public class OrderDetail
    {
        public int OrderDetailId { get; set; }
        public int OrderId { get; set; }
        public int ProductId { get; set; }
        public int Quantity { get; set; }
        public decimal UnitPrice { get; set; }
        public virtual Product Product { get; set; }
        public virtual Order Order { get; set; }
    }

Im trying to create a controller that allows the user that has made the order to view his order

A: int orderId = // The orderId you want to use
Items.Where(item => item.OrderId == orderId)

This example is done with Linq (the .Where function) and expression trees with lambdas (the =>). hope this helps. I would recommend reading into linq since its one of the, if not the most, powerful aspect of .Net/C# compared to Java/Other languages.

A: By seeing your class structure, Here is simple code example which simply provides you the collection of OrderDetails object for an orderId and username:
   var orderDetails = Orders.Select(x => x.OrderId = orderId && x.username="yourusename");

Now iterate through these items using foreach.


text:
Q: Can I do Date calculation in React? Say, I just retrieved an object called "food" from the database. "food" has an attribute called "created_at" and it is created automatically when food was created. "food" also has an attribute called "shelf_life" Now, in a react frontend, I want to do a conditional rendering based on whether the food is expired or not. So, I need to do some calculations.
For example,
created_at = 2022-04-20T03:25:53.763+00:00
shelf_life = 30 (days)
Is there a way to do a calculation like created_at + shelf_life and compare the result to the current time?
Thanks a lot

A: you can use the library moment
https://momentjs.com/
and declare your two dates
let date1 = moment('2022-04-20T03:25:53.763+00:00');
let date2 = moment('2022-04-11T03:25:53.763+00:00');

then get the difference in days using
var difference = date2.diff(date1, 'days');


text:
Q: How to use jsFiddle code on Notepad Php file jsFiddle

$(document).ready(function() {
    $('select').change(function() {
        $('option[value=' + $(this).val() + ']').attr('disabled', 'disabled');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<select id="1">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
</select>

<select id="2">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
</select>

I want to apply this code in my php file and i haven't studied jQuery so i copy pasted the code on my notepad saved it with .php extension and ran it on localhost but only html part is running and the script is not working. Please help i know its a childish question but i am trying to learn.

A: add this code to php or html file
and run
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<select id="1">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
</select>

<select id="2">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
</select>
<script>
$(document).ready(function() {
    $('select').change(function() {
    console.log($(this).val())
        $('option[value=' + $(this).val() + ']').attr('disabled', 'disabled');
    });
});
</script>

This will work

A: In which php file did you copy the code ? .
First , you need to include jQuery. For example  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> ( which is the latest ) in footer.php just before the closing <body> tag
Then you can put the javascript/jquery code either in a separate file with .js extension and then call it in footer.php before the closing of body tag. ( after the jQuery call )  Something like so <script type="text/javascript" src="yourScripts.js"></script> // i suggest this approach for cleaner and easier to use/manage/change code
Or you can put it in header.php inside the <head> tag , but you need to wrap it inside <script> .... </script> So it will look something like
<script>
 $(document).ready(function(){
       your code here
 });
</script>

A: Just add:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

and try and use js extension and include it in your php


text:
Q: C code not running while using include libraries on windows I'm trying to run this code on visual studio code and it is not working. If I am not using anything from string.h and just print a string, it works find but once I use a method such as strtok, the file compiles but does not show anything when running and/or when running the .exe, I get an error message that it has stopped working. I have already installed the base mingw package for C.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
    char* string = "Visual Studio Code";
    strtok(string, " ");
    printf(string);

    return 0;
}

This is my c_cpp_properties.json file where I include the libraries such as string.h, etc.
    {
        "name": "Win32",
        "includePath": [
            "${workspaceRoot}",
            "C:\\MinGW\\lib\\gcc\\mingw32\\6.3.0\\include",
            "C:\\MinGW\\lib\\gcc\\mingw32\\6.3.0\\include-fixed",
            "C:\\MinGW\\include"

    ],

A: The pointer string points to a string literal.  These are not writable, and in fact typically live in a read-only section of memory.  The strtok function modifies the string passed to it.  Because it is attempting to modify a string literal, you invoke undefined behavior, which in this case causes the application crashes.
You need to create an array which can be modified.
char string[] = "Visual Studio Code";

A: From standard 7.24.5.8

The strtok function then searches from there for a character that is
contained in the current separator string. If no such character is
found, the current token extends to the end of the string pointed to
by s1, and subsequent searches for a token will return a null pointer.
If such a character is found, it is overwritten by a null character,
which terminates the current token. The strtok function saves a
pointer to the following character, from which the next search for a
token will start.

A string literal is non-modifiable and you pass it to strok which tries to modify it. This is undefined behavior. In your case you got segmentation fault.
Solution:
char string[] = "Visual Studio Code";


text:
Q: Advice on using SearchView, ListView, an API, Adapters and SQLite together I was wondering if there is a better way of going about things than the way I am doing it now, any help would be greatly appreciated.
Currently, I am working on a Search Fragment for my app, the idea being that they search (it shows their previous searches whilst they type), then they press enter or click one of their previous searches and results from their search are returned from the API (displaying a list of valid users in the listview) to which the user can then click on the one they want to access.
In total,
Search - > API -> JSONAdapter -> DB/Objects -> Display to User via ListView -> On click in ListView display New Fragment or an overlay.
Currently, I was a bit confused on how to implement it, I made a JSONAdapter that works for the API and submitting the SearchView returns the correct response from the API (However it is not displayed in the ListView). I also have a ListViewAdapter that works with a hardcoded list but doesn't seem to work using the JSONAdapter.
I also made a lot of classes to store the data from the JSONAdapter, I'm not sure if I should be using SQLite to store the values they select after searching (I think I probably should).
I'm sorry this question is such a mess, I'm just a bit lost at the moment.
I can clarify any confusions.
In Summary (TL;DR): Should I just be using the default google suggestions provider for history, should I even be thinking about SQLite or will the API be fast enough, can I use the same listview for previous history & search results?
Thank You.

A: I think there's no need to store data in Sqlite db, about th list view I think it is better if you used a RecycleView.


text:
Q: Value for each checkbox in jQuery I would like to know how I can set values for each checkboxs. For example: I have 2 checkboxes, and their values will be:
Checkbox One: 1
Checkbox two: 16

If I select Checkbox One + Two I'll update my input value for: 17. But If I uncheck checkbox two, the value will update to 1 and vice-versa.
I made this, months ago...But I lot when I format my computer, I already do something like in C#, but i need to do the same in Web.
I don't want a full source-code, I just want tips that how I can handle this.

A: just set the value attribute of each checkbox to the value you want, use a jquery selector to get all the checked checkboxes, and use a $.each to sum the checked values.


text:
Q: Celery task not working in Django framework I tried code to send_email 5 times to user as Asynchronous task using Celery and Redis Broker in Django Framework. My Celery server is working and it is responding to the celery cli interface even it is receiving task from Django but after that I am getting Error like:
Traceback (most recent call last):
  File "c:\users\vipin\appdata\local\programs\python\python3
es\billiard\pool.py", line 358, in workloop
    result = (True, prepare_result(fun(*args, **kwargs)))
  File "c:\users\vipin\appdata\local\programs\python\python3
es\celery\app\trace.py", line 544, in _fast_trace_task
    tasks, accept, hostname = _loc
ValueError: not enough values to unpack (expected 3, got 0)

task.py -
from celery.decorators import task
from django.core.mail import EmailMessage
import time

@task(name="Sending_Emails")
def send_email(to_email,message):
    time1 = 1
    while(time1 != 5):
        print("Sending Email")
        email = EmailMessage('Checking Asynchronous Task', message+str(time1), to=[to_email])
        email.send()
        time.sleep(1)
        time1 += 1

views.py -
print("sending for Queue")
send_email.delay(request.user.email,"Email sent : ")
print("sent for Queue")

settings.py -
# CELERY STUFF
BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/India'

celery.py -
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ECartApplication.settings')
app = Celery('ECartApplication')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

I expect Email should be sent 5 times but getting error:
[tasks]
  . ECartApplication.celery.debug_task
  . Sending_Emails

[2019-05-19 12:41:27,695: INFO/SpawnPoolWorker-2] child process 3628 calling sel
f.run()
[2019-05-19 12:41:27,696: INFO/SpawnPoolWorker-1] child process 5748 calling sel
f.run()
[2019-05-19 12:41:28,560: INFO/MainProcess] Connected to redis://localhost:6379/
/
[2019-05-19 12:41:30,599: INFO/MainProcess] mingle: searching for neighbors
[2019-05-19 12:41:35,035: INFO/MainProcess] mingle: all alone
[2019-05-19 12:41:39,069: WARNING/MainProcess] c:\users\vipin\appdata\local\prog
rams\python\python37-32\lib\site-packages\celery\fixups\django.py:202: UserWarni
ng: Using settings.DEBUG leads to a memory leak, never use this setting in produ
ction environments!
  warnings.warn('Using settings.DEBUG leads to a memory leak, never '
[2019-05-19 12:41:39,070: INFO/MainProcess] celery@vipin-PC ready.
[2019-05-19 12:41:46,448: INFO/MainProcess] Received task: Sending_Emails[db10da
d4-a8ec-4ad2-98a6-60e8c3183dd1]
[2019-05-19 12:41:47,455: ERROR/MainProcess] Task handler raised error: ValueErr
or('not enough values to unpack (expected 3, got 0)')
Traceback (most recent call last):
  File "c:\users\vipin\appdata\local\programs\python\python37-32\lib\site-packag
es\billiard\pool.py", line 358, in workloop
    result = (True, prepare_result(fun(*args, **kwargs)))
  File "c:\users\vipin\appdata\local\programs\python\python37-32\lib\site-packag
es\celery\app\trace.py", line 544, in _fast_trace_task
    tasks, accept, hostname = _loc
ValueError: not enough values to unpack (expected 3, got 0)

A: This is an issue when you running Python over Windows 7/10.
There are a workaround, you just need to use the module eventlet that you can install using pip:

pip install eventlet

After that execute your worker with -P eventlet at the end of the command:

celery -A MyWorker worker -l info -P eventlet

A: This command below also works on Windows 11:
celery -A core worker --pool=solo -l info


text:
Q: PHP/HTML: require_once(config.php): failed to open stream: No such file or directory just simple question here.
I placed dashboard.php at folder
pages/dashboard/dashboard.php.

But the error appears just like my question. Can I know how to solve this problem ?

A: The error pretty much explains what the problem is: you are trying to include a file that is not there.
you have to use this at dashboard.php page :-
require_once("../../dbconn.php");


text:
Q: Warning: file_exists() expects parameter 1 to be a valid path, array given in C:\ I'm getting this Warning for some strange reason...
this is the complete warning:
Warning: file_exists() expects parameter 1 to be a valid path, array given in C:\wamp64\www\Petrogas NCR applicatie\Insert.php on line 84

This is my code:
for($i = 0; $i < count($_FILES['attachments']['name']); $i++)
    {
        function resize_image($file,$max_resolution) {
            if (file_exists($file)) {

                $original_image = imagecreatefromjpeg($file);

                $original_width = imagesx($original_image);
                $original_height = imagesy($original_image);

                $ratio = $max_resolution / $original_width;
                $new_width = $max_resolution;
                $new_height = $original_height * $ratio;

                if ($new_height > $max_resolution) {
                    $ratio = $max_resolution / $original_height;
                    $new_height = $max_resolution;
                    $new_width = $original_width * $ratio;
                }

                if ($original_image) {
                    $new_image = imagecreatetruecolor($new_width, $new_height);
                    imagecopyresampled($new_image,$original_image,0,0,0,0,$new_width,$new_height,$original_width,$original_height);
                    imagejpeg($new_image,$file,90);
                }
            }
        }
        $filetmp = $_FILES["attachments"]["tmp_name"][$i];
        $filename = $_FILES["attachments"]["name"][$i];
        $filepath = "images/".$filename;
        if (move_uploaded_file($filetmp,$filepath)) {
            $file = $_FILES['attachments']['name'];
            resize_image($file, '50');
            $querypictureupload = "INSERT INTO file_upload(ncrnummer,filename) VALUES ('$ncrnummer','$filename')";
            $result = mysqli_query($conn, $querypictureupload);
        }
    }

I was trying to upload an image and resize it. But got this strange warning...

A: Change your script as you should not create function inside for loop
for($i = 0; $i < count($_FILES['attachments']['name']); $i++)
{
    $filetmp = $_FILES["attachments"]["tmp_name"][$i];
    $filename = $_FILES["attachments"]["name"][$i];
    $filepath = "images/".$filename;
    if (move_uploaded_file($filetmp,$filepath)) {
        $file = $_FILES['attachments']['name'];
        resize_image($file, '50', $filepath);
        $querypictureupload = "INSERT INTO file_upload(ncrnummer,filename) VALUES ('$ncrnummer','$filename')";
        $result = mysqli_query($conn, $querypictureupload);
    }
}

Create function outside of the scope of for loop function
And you need to pass file path in file_exists function to check whether the file exists or not
 function resize_image($file,$max_resolution, $filepath) {
        if (file_exists($filepath)) {

            $original_image = imagecreatefromjpeg($file);

            $original_width = imagesx($original_image);
            $original_height = imagesy($original_image);

            $ratio = $max_resolution / $original_width;
            $new_width = $max_resolution;
            $new_height = $original_height * $ratio;

            if ($new_height > $max_resolution) {
                $ratio = $max_resolution / $original_height;
                $new_height = $max_resolution;
                $new_width = $original_width * $ratio;
            }

            if ($original_image) {
                $new_image = imagecreatetruecolor($new_width, $new_height);
                imagecopyresampled($new_image,$original_image,0,0,0,0,$new_width,$new_height,$original_width,$original_height);
                imagejpeg($new_image,$file,90);
            }
        }
    }


text:
Q: How to check if number is a decimal and run function laravel I use Ajax to search my data and when it runs it removes price formatting from 49.99 to 4999. I can solve the problem by using ${{number_format($product->price / 100, 2)}}  in the view file but the problem is if the price is displaying correctly as 49.99 and the function runs then it now displays as 0.50. How can I run a check so that this function only attempts to format price if it doesn't have decimal, only if its a int like 4999
I tried
            if(is_float($product->price)){
                echo $product->price;
            } else {
                echo number_format($product->price / 100, 2);
            }

A: This worked for me
if (is_numeric($product->price) && floor($product->price) != $product->price) {
                echo $product->price;
            } else {
                echo number_format($product->price / 100, 2);
            }


text:
Q: what is the best approach to run many gulp watch tasks simultaneously? Is it better call multiple watchers or combine them into one?
I have different tasks for different file types and currently I do this:
...

gulp.task('watch', function () {
    watch(paths.sass, batch(function (done) {
        gulp.start('sass');
        done();
    }));

    watch(paths.templates, batch(function (done) {
        gulp.start('templates');
        done();
    }));

    watch(paths.scripts, batch(function (done) {
        gulp.start('inject');
        done();
    }));
});

...

( the full gulpfile.js: https://gist.github.com/asfktz/2166e1b58c552f4db6cd )
It feels wrong right now and I thinks its better the have one watch stream and separate the stream into different streams, one for each task.
am I right?


text:
Q: require/typed for mrlib/path-dialog error message I am trying to use path-dialog% from mrlib/path-dialog in a typed/racket program, but it is complaining that I need to use require/typed to import it.
I'm sure this is an easy one for someone familiar with require/typed, but I am not that person. The main gui library and the main db library are available in typed versions, but it seems that the mrlib extensions are not available in typed versions.
Could someone please be so kind as to explain how to fix this error?
Thank you.
The exact error message is:
Type Checker: missing type for identifier;
 consider using `require/typed' to import it
  identifier: path-dialog%
  from module: mrlib/path-dialog in: path-dialog%


text:
Q: is there anyway to apply two transform property to same element

The functionality i want is when i hover one of the image i want that image to scale(1.1) and other image to scale(0.9) only using css.
The code that i tried was:
.gallery {
  &__img:hover {
    transform: scale(1.1);
  }

  &__img:hover &__img:not(:hover) {
    transform: scale(0.9);
  }
}

but it's not working.

A: Maybe this ?

figure {
  display : inline-block;
  margin  : 0;
  padding : 1em;
  }
.gallery:hover img {
  transform: scale(.9);
  }
.gallery figure:hover  img {
  transform: scale(1.1);
  }


text:
Q: Mongo Scaling - Too Many Connections - Linear Horizontal Scaling with 100s of App Servers I have a Mongo Cluster. It's sharded on 6 servers, with 6 replica sets, each replica set having one Primary, and two Secondaries.  Additionally, there are 3 config servers. Though, I think the Mongo Cluster configuration is irrelevant to this question.
I have many application servers (currently 100), with the intention of having many more as my volume grows.  On each application server, I have a mongos process, 8 http servers (node.js) each bound to a port (using HAProxy as a reverse proxy to route traffic from port 80).  Each http server connects to the local mongos process using connection pooling with a poolSize of 3.  Pretty simple so far.
The issue is that the number of connections seems to quite simply be:
(number of servers) * (number of http processes) * (poolSize)

In my current case that would be:
100 * 8 * 3 = 2400 total connections

So it would seem that the number of connections scales linearly with the number of servers I'm running.  If I scale up 5x, then the number of connections goes to 9,600 which is dangerously close to the 10,000 limit (as well as seeming unnecessarily wasteful).  What about a 10x or 100x scale up?
It is stated that "any connection count greater than 1000 – 1500 connections should raise an eyebrow".  How can I possibly maintain that number of connections with 100s of application servers? Is a mongos process per application server at this size still appropriate?

A: The hard connection limit was actually 20,000 but it was removed in version 2.6 and you are now only limited by memory or open file descriptors (whichever you run out of first).  That being said, with connections running into the thousands, even if you can manage it you will be using a lot of memory (1MB per connection for the stack).
At that point you start to evaluate other options for mongos deployment.  You can have a dedicated set of mongos hosts and take advantage of some of the nice HA options built into the drivers and pass in an list of possible mongos processes to use.  If you are concerned about latency, you could potentially collocate (some of) the mongos processes on your shard hosts.
Basically you've started to hit the number of nodes where you are into more advanced design decisions and it really depends on several factors as to what is right for you now, and what is right for you in the future.  If you have some money to throw at it, this is perfect fodder for the type of consulting MongoDB offer (disclosure: I was once one of the people delivering such consulting).  If not, you are asking the right questions, so keep an eye on resource utilisation and see what makes sense for your deployment as you grow.


text:
Q: Associate custom client certificate to Azure Self-hosted Gateway I am working with Azure API management.
I have deployed a self-hosted gateway on my local machine, and I want to associate custom client certificates for security.
I have successfully uploaded a custom certificate to Azure API Management in the Portal and associated it with the API.
Now I need to associate this certificate with the self-hosted gateway. I cannot find any clear material on the internet.
How I can do this step?

A: This is covered in Microsoft's document Add a custom CA certificate - Azure API Management:

Create custom CA for self-hosted gateway
If you use a self-hosted gateway,
validation of server and client certificates using CA root
certificates uploaded to API Management service is not supported. To
establish trust, configure a specific client certificate so that it's
trusted by the gateway as a custom certificate authority.
Use the Gateway Certificate Authority
REST APIs to create and manage custom CAs for a self-hosted gateway.
To create a custom CA:

*

*Add a certificate
.pfx file to your API Management instance.

*Use the Gateway Certificate Authority - Create Or Update REST API to associate the certificate with the self-managed gateway.


text:
Q: function parameters is getting undefined Whenever I'm hitting the enter button, the console.log is printing but (socketId, msg) is showing undefined. what i'm doing wrong here please help me thanks in advance
const callComponent = ({
  handleSendMessage
}) => {

  function handleMessage(socketId, msg) {
    console.log('chat open clicked', socketId, msg)
    handleSendMessage(socketId, msg)
  }

  useEffect(() => {
    const listener = event => {
      if (event.code === "Enter" || event.code === "NumpadEnter") {
        console.log("Enter key was pressed. Run your function.");
        event.preventDefault();
        handleMessage(socketId, msg)
      }
    };
    document.addEventListener("keydown", listener);
    return () => {
      document.removeEventListener("keydown", listener);
    };
  }, []);
  //...
}

A: handleMessage function inside useEffect has no access to sockedId and msg. Function parameters are passed, thus must be within the scope that calls the function.


text:
Q: JasperReports How to do pagination in Excel I am trying to put page numbers/breaks at the bottom of each page and columns headers at the top, so when printed from Excel all pages are numbered and headed. It should not be such a big deal, right? But unfortunately it is, no matter what approach I tried I just cannot get the page number and page break at the bottom of the pages - they are anywhere else but at the bottom. I put "Page X of Y" in the Page Footer section, the Ignore Pagination is NOT checked, and when I generate the report I have Page X or Y after every 4 lines of data. I extended the page Height to 3-4 times of the standard height of Letter Landscape format, and that changed the footer to be printed after 18-20 lines of data - this is not a reliable way of adjusting it.
Also I tried putting the Page Break with Print When expression set to print it every 20 lines, but that still it is not accurate, since on the first page I have less lines of data because of the Report Title - if I adjust it to be correct on the 1st page - it will print it somewhere in the middle on the next pages.
Am I missing something obvious in the design how to put footer with page #s? Any help will be greatly appreciated.

A: I've solved this issue with help of net.sf.jasperreports.export.xls.fit.height parameter.
I set the report's height and net.sf.jasperreports.export.xls.fit.height report's property with the same value.
The sample:
<jasperReport ... pageWidth="595" pageHeight="800" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    ...
    <parameter name="net.sf.jasperreports.export.xls.fit.height" class="java.lang.String" isForPrompting="false">
        <defaultValueExpression><![CDATA[800]]></defaultValueExpression>
    </parameter>
    ...
    <detail>
        <band height="20" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="100" height="20"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{field1}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="100" y="0" width="100" height="20"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{field2}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <pageFooter>
        <band height="20" splitType="Stretch">
            <textField>
                <reportElement x="433" y="0" width="80" height="20"/>
                <textElement textAlignment="Right"/>
                <textFieldExpression><![CDATA["Page "+$V{PAGE_NUMBER}+" of"]]></textFieldExpression>
            </textField>
            <textField evaluationTime="Report">
                <reportElement x="513" y="0" width="40" height="20"/>
                <textElement/>
                <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
            </textField>
        </band>
    </pageFooter>
</jasperReport>

The result (preview in MS Excel):

A: Some years ago I tried the same and could not resolve it. If there hadn't been a drastic change in between (and I delete this answer instantly if one in provided) then you are lost.
I'm sorry.


text:
Q: Angular FlexLayout - Child Div over extends parent div I have an Ng FlexLayout and the child div over extends out of parent div.
I need it to to stay within maximum height of parent div, and then display a scrollbar if height is larger than parent div.
I cannot seem to get this to work with Ng FlexLayout :-(
I have a super simple plunkr here. As you can see the messages (which are wrapped in their own parent div) extend out of the green parent div.
html

Display:

Test

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

message

css
#console {

  background-color: green;
}

div#console_toolbar {
  min-height: 30px;
  width: 100%;

  background-color: blue;
}
div#console_output{
  height: 200px;
}
div#console_msg_wrapper{
  height: 100%;
  // overflow: hidden;
}

A: You should be using overflow: scroll when dimension of your content exceeds the dimension of the container element, this will ensure that your content is visible when scrolled.
Using overflow: hidden will cause the overflowing content to be hidden.


text:
Q: Wordpress Target Blank I'm working a wordpress theme versatile and I have a price table that has "Order Now" button but the button does not link in a new tab and I want to change that.
I'm not to familiar with php but I know I will have to place a target="_blank" code in the php file but I'm not sure where.
Does anyone know where I can place this little bugger at?
Thanks in advance.
// price table item
if( !function_exists('gdlr_get_price_table_item') ){
    function gdlr_get_price_table_item( $settings ){
        $item_id = empty($settings['page-item-id'])? '': ' id="' . $settings['page-item-id'] . '" ';

        global $gdlr_spaces;
        $margin = (!empty($settings['margin-bottom']) &&
            $settings['margin-bottom'] != $gdlr_spaces['bottom-item'])? 'margin-bottom: ' . $settings['margin-bottom'] . ';': '';
        $margin_style = (!empty($margin))? ' style="' . $margin . '" ': '';

        $settings['price-table'] = empty($settings['price-table'])? array(): $settings['price-table'];
        $list = is_array($settings['price-table'])? $settings['price-table']: json_decode($settings['price-table'], true);
        $ret  = '
';
        foreach( $list as $tab ){
            $best_price = ($tab['gdl-tab-active'] == 'yes')? ' best-price ': '';

            $ret .= '
';
            $ret .= '
';

            $ret .= '
';
            $ret .= '
' . gdlr_text_filter($tab['gdl-tab-title']) . '
';
            $ret .= '
' . gdlr_text_filter($tab['gdl-tab-price']) . '
';
            $ret .= '
';

            $ret .= '
' . gdlr_content_filter($tab['gdl-tab-content']) . '
';

            if(!empty($tab['gdl-tab-link'])){
                $ret .= '
';
                $ret .= '' . __('Order Now', 'gdlr_translate') . '';
                $ret .= '
';
            }

            $ret .= '
'; // gdlr-price-inner-item
            $ret .= '
'; // gdlr-price-item
        }
        $ret .= '

';
        $ret .= '
';

        return $ret;
    }
}

A: Its gonna be in this line:
$ret .= '' . __('Order Now', 'gdlr_translate') . '';
Should be changed to:
$ret .= '' . __('Order Now', 'gdlr_translate') . 'target="_blank" ';


text:
Q: Using Python, how can I multiply all matching integers in a list and then add the remaining integers I am working to recreate a dice game known as Knucklebones in Python as a fun personal project.
For the game logic, I need to multiply all matching values in a list and then add the remaining values.
Example 1:
numbers = [3, 3, 2]

This list should multiply both 3 and 3 together then add 2 for a total of 11.
Example 2:
numbers2 = [4, 4, 4]

This list should multiply 4 by 4 by 4 for a total of 64
Example 3:
numbers3 = [2, 4, 6]

Nothing should be multiplied in this list. All numbers should be added for a total of 12.
Can someone please help me with the logic surrounding this?

A: I think this should work
I will advise to use a modified Counter from the built in module collections.
The counter by default will count just the entries of all the list
them as it works similar to a dictionary is fairly simple to multiply all entries and sum them up
here you have more info:
https://docs.python.org/3/library/collections.html
https://realpython.com/python-counter/
from collections import Counter

class MyCounter(Counter):
    def __ini__(*arg, **kwargs):
        super().__init__(*arg, **kwargs)

    def sum_entries(self):
        total = 0
        for key, val in self.items():
            total += key**val
        return total

out = MyCounter([3, 3, 2])
output = out.sum_entries()

output
out = MyCounter([3, 3, 2])
output = out.sum_entries()
print(output)

11

out = MyCounter([4, 4, 4])
output = out.sum_entries()
print(output)

64

out = MyCounter([2, 4, 6])
output = out.sum_entries()
print(output)

12

EDIT
As suggested in the comments
To avoid having a class if it seems to complicated
from collections import Counter

out = Counter([3, 3, 2])
total = 0
for key, val in out.items():
    total += key**val

A: Built-in approach. Used dict.fromkeys to initialize to zero the counter (and remove duplicates). Then fix the frequency of the outcomes with the loop and apply the "Knucklebones" rule.
numbers = [3, 3, 2]

d = dict.fromkeys(numbers, 0)
for n in numbers:
    d[n] += 1

res = sum(k**frequency for k, frequency in d.items())
print(res)


text:
Q: Double linked list in Fortran (type is not judged correctly) I would like to implement a generic double linked list in Fortran for saving codes, using PGI Fortran compiler version 12.10-0 in Mac OS X 10.8.2. Here is my prototype, including 3 files:
---> File 1:
! ----------------------------------------------------------------------------
! Description:
!
!   This module provides several basic data structures, e.g. double linked list.
!
! Authors:
!
!   Li Dong <dongli@lasg.iap.ac.cn> - 2012-11-11
! ----------------------------------------------------------------------------

module basic_data_structure

    implicit none

    private

    public list_elem_t, list_t

    type list_elem_t
        class(list_elem_t), pointer :: prev, next
    end type list_elem_t

    type list_t
        integer :: num_elem = 0
        class(list_elem_t), pointer :: head, tail
    contains
        procedure :: append => list_append
        procedure :: insert => list_insert
        procedure :: final => list_final
    end type list_t

contains

    ! ------------------------------------------------------------------------
    ! Description:
    !
    !   The following list_* are the type-bound procedures of double linked
    !   list data structure.
    !
    ! Authors:
    !
    !   Li Dong - <dongli@lasg.iap.ac.cn> - 2012-11-11
    ! ------------------------------------------------------------------------

    subroutine list_append(this, elem)

        class(list_t), intent(inout) :: this
        class(list_elem_t), intent(out), pointer :: elem

        character(50), parameter :: sub_name = "list_append"

        allocate(elem)
        if (this%num_elem == 0) then
            this%head => elem
            nullify(this%head%prev)
            this%tail => this%head
        else
            this%tail%next => elem
            elem%prev => this%tail
            this%tail => elem
        end if
        nullify(this%tail%next)
        this%num_elem = this%num_elem+1

    end subroutine list_append

    subroutine list_insert(this, existed_elem, elem)

        class(list_t), intent(inout) :: this
        class(list_elem_t), intent(inout), pointer :: existed_elem
        class(list_elem_t), intent(out), pointer :: elem

        character(50), parameter :: sub_name = "list_insert"

        ! TODO: Check existed_elem is allocated.
        ! TODO: Check existed_elem is one element of this.

        allocate(elem)
        elem%prev => existed_elem
        elem%next => existed_elem%next
        if (associated(existed_elem%next)) then
            existed_elem%next%prev => elem
            existed_elem%next => elem
        end if
        this%num_elem = this%num_elem+1

    end subroutine list_insert

    subroutine list_final(this)

        class(list_t), intent(inout) :: this

        class(list_elem_t), pointer :: elem
        integer i

        elem => this%head
        do i = 1, this%num_elem-1
            elem => elem%next
            if (associated(elem%prev)) deallocate(elem%prev)
        end do
        deallocate(this%tail)

    end subroutine list_final

end module basic_data_structure

---> File 2
! ----------------------------------------------------------------------------
! Description:
!
!   This module manages the model variables.
!
! Authors:
!
!   Li Dong <dongli@lasg.iap.ac.cn> - 2012-11-11
! ----------------------------------------------------------------------------

module variable

    use basic_data_structure

    implicit none

    private

    public variable_register
    public variable_final

    public var_t, var_1d_t

    integer, parameter :: A_GRID = 1
    integer, parameter :: B_GRID = 2
    integer, parameter :: C_GRID = 3

    type, extends(list_elem_t) :: var_t
        character(10) name
        character(50) long_name
        character(20) units
        integer grid_type
    end type var_t

    type, extends(var_t) :: var_1d_t
        real(8), allocatable :: array(:)
    end type var_1d_t

    type, extends(var_t) :: var_2d_t
        real(8), allocatable :: array(:,:)
    end type var_2d_t

    type(list_t) var_list

contains

    ! ------------------------------------------------------------------------
    ! Description:
    !
    !   Register a variable.
    !
    ! Authors:
    !
    !   Li Dong <dongli@lasg.iap.ac.cn> - 2012-11-11
    ! ------------------------------------------------------------------------

    subroutine variable_register(name, var)

        character(*), intent(in) :: name
        class(var_t), intent(inout), pointer :: var

        character(50), parameter :: sub_name = "variable_register"

        select type (var)
        type is (var_1d_t)
            print *, "---> Register a 1D variable """//trim(name)//"""."
        type is (var_2d_t)
            print *, "---> Register a 2D variable """//trim(name)//"""."
        type is (var_t)
            print *, "---> Oh, no!"
        class default
            print *, "---> Unknown variable type """//trim(name)//"""."
        end select

        call var_list%append(var)

        ! -------------------------------> PROBLEM IS HERE
        select type (var)
        type is (var_1d_t)
            print *, "---> Register a 1D variable """//trim(name)//"""."
        type is (var_2d_t)
            print *, "---> Register a 2D variable """//trim(name)//"""."
        type is (var_t)
            print *, "---> Oh, no!"
        class default
            print *, "---> Unknown variable type """//trim(name)//"""."
        end select

    end subroutine variable_register

    ! ------------------------------------------------------------------------
    ! Description:
    !
    !   Clean the registered variables.
    !
    ! Authors:
    !
    !   Li Dong <dongli@lasg.iap.ac.cn> - 2012-11-11
    ! ------------------------------------------------------------------------

    subroutine variable_final()

        character(50), parameter :: sub_name = "variable_final"

        call var_list%final()

    end subroutine variable_final

end module variable

---> File 3:
program test_variable

    use variable

    implicit none

    type(var_1d_t), pointer :: a

    call variable_register("a", a)
    call variable_final()

end program test_variable

The running result is:
MacBook-Pro:sandbox dongli$ ./test_variable
 ---> Register a 1D variable "a".
 ---> Unknown variable type "a".

Why after appending a list, the type of var is changed into a type that is unknown, and how could I achieve the expected functionality?

A: F2008 12.5.2.5 p2 says in terms of pointer and allocatable dummy arguments: "The actual argument shall be polymorphic if and only if the associated dummy argument is polymorphic...".
The dummy argument var in variable_register is a polymorphic pointer.  The actual argument a in the main program is not.  Your program is in error and the Fortran processor is not required to diagnose this error (though it should be easy enough for it to detect this in this particular case).
The same paragraph in F2008 12.5.2.5 then goes on to say "...the declared type of the actual argument shall be the same as the declared type of the dummy argument." The dummy argument in list_append is a polymorphic pointer of declared type list_elem_t.  The actual argument is a polymorphic pointer of declared type var_t.  They are not the same - your program is even more in error.  Again, the Fortran processor is not required to diagnose this, but it should be easy enough for it to do so in this case.
Because your program is in error anything can happen, but on a related note - the elem argument to list_append is declared INTENT(OUT).  That means that at the start of that procedure, the pointer association status of elem is undefined - you don't know what it is pointing at (or its dynamic type).  The allocate statement in list_append then allocates an object of the declared type of elem, i.e. list_elem_t (the fact that the pointer that is the ultimate argument and the pointer that is the "intermediate" argument have now been pointed at a parent of their respective declared types is the reason that the restrictions quoted above in 12.5.2.5 exist - read Note 12.27 in F2008).  Your select type doesn't check for that option.


text:
Q: Co/Contra-Variance with input and output I have an issue with co/contra-variance.  I understand you can't have both input and output.  So here is a simple example:
public interface A<T>
{
    T Object {get;set;}
}

public interface B
{
    // Some stuff
}

public class BImplementor : B
{ }

public class Implementor : A<BImplementor> {}

Suppose you have these classes and I'm wanting to write a method like this
public void Command(B obj)
{
    var a = (A<B>)Unity.Resolve(typeof(A<>).MakeGenericType(obj.GetType());
    a.Object = obj;
}

I'm using Unity to resolve a A of the specifc implementor of B (specifically Implementor), but all I know about it is that it is an A<B>.  I don't know of a way to do this directly and I don't think it is actually possible, but does anyone know of a workaround to simulate what I'm trying to do.

A: As you said, you cannot have both input and output, so let's change A<T> to A<in T> so Command can assign obj to the Object property:
public interface A<in T>
{
    void SetObject(T obj);
}

public interface B { }

public class BImplementor : B { }

public class Implementor : A<BImplementor>
{
    public void SetObject(BImplementor t) { ... }
}

The Command method essentially does this:
public void Command(B obj)
{
    A<B> a = (A<B>)new Implementor();
    a.SetObject(obj);
}

But this cast can never succeed, because A<B>.SetObject must accept any B as input, while Implementor.SetObject accepts only BImplementor objects as input!

Since you now that you'll only ever pass a BImplementor to A<B>.SetObject, you can work around the problem using reflection.
Workaround 1:
public void Command1(B obj)
{
    object a = Unity.Resolve(typeof(A<>).MakeGenericType(obj.GetType());
    a.GetType().GetMethod("SetObject").Invoke(a, new object[] { obj });
}

Workaround 2:
public void Command(B obj)
{
    this.GetType()
        .GetMethod("Command2")
        .MakeGenericMethod(obj.GetType())
        .Invoke(this, new object[] { obj });
}

public void Command2<T>(T obj) where T : B
{
    A<T> a = Unity.Resolve<A<T>>();
    a.SetObject(obj);
}


text:
Q: Rewrite While Do loop statement as For Do loop in Pascal I am trying to rewrite a while do loop as a for do loop in Pascal, please is there a way to rewrite the below code into a for loop statement...
And determine which is better and why ?
Thanks in advance..
Here is the code
program Quadractics;
uses crt;

const n=10;

VAR
  a,b,c,d,e,x1,x2:real;
  k:Integer;

BEGIN
  k:= 0;

  while k<n DO

  begin

  writeln('Input the values for variables a,b,c');
  readln(a,b,c);
  e:=2*a;
  d:=sqr(b)-(4.0*a*c);

  if d>=0 then
    begin

  x1:=(-b+sqrt(d)) /e;

  x2:=(-b-sqrt(d)) /e;

  writeln('The resulting roots of the above equation are x1= ', x1 , ' and x2= ', x2);

    end

  else

  begin

  write('complex root values are  ');
  write('x1 = ', '(',-b, '+√',d,')','/',e ,', ');

  write('and',';  ');

  write('x2 = ', '(',-b, '-√',d,')','/',e ,', ');

  end;

  k:=k+1;

  end;

END.

A: As I don't want to spoil your homework, I give you the following clue:
The while loop in pseudocode
loopcounter = startvalue
while loopcounter < endvalue do // could also be loopcounter <= endvalue
begin
  code to perform on every loop
  loopcounter = loopcounter + 1
end

The for loop in pseudocode
for loopcounter = startvalue to endvalue // could also be to endvalue-1
begin
  code to perform on every loopcounter
end

Think about and compare the difference of how the endvalue is expressed.
And finally a tip to help you: Always follow the indentation rules, it's much easier to read the structure and functionality of the code.


text:
Q: Maxima: Rounding the entries of a list using Robert Dodier's excel_round.mac I want the entries of a Maxima list to be rounded in Excel style using Robert Dodier's excel_round.mac (see Maxima: Round like in Excel) on the fly.
I created a list, say the values of exp(0.5*x) over the range from [-2,2].
(%i1)  makelist(exp(0.5*x),x,-2,2)$
       soln: %
(%o1) [0.36788,0.60653,1,1.6487,2.7183]

The problem I'm having is how to get all the list entries into the x of below.
(%i1)  excel_round(x,2)$
       ev(%, x=?)

As trying the following
(%i2)  map(exel_round(x,2),soln);
(%o2)  [exel_round(x,2)(0.36788),exel_round(x,2)(0.60653),
       exel_round(x,2)(1),exel_round(x,2)(1.6487),exel_round(x,2)(2.7183)]

and
(%i12)  makelist(exp(0.5*x),x,-2,2);
        soln: %$
        excel_round(x,2)$
        ev(%, x=soln)
(%o12)  [0.36788,0.60653,1,1.6487,2.7183]
(%o15)  excel_round([0.36788,0.60653,1,1.6487,2.7183],2)

didn't yield the desired results I returned to semi-brute force:
(%i18)  excel_round(x,2)$
            ev(%, x=soln[1]);
        excel_round(x,2)$
            ev(%, x=soln[2]);
        excel_round(x,2)$
            ev(%, x=soln[3]);
        excel_round(x,2)$
            ev(%, x=soln[4]);
        excel_round(x,2)$
            ev(%, x=soln[5])
(%o19) 0.37
(%o21) 0.61
(%o23) 1.0
(%o25) 1.65
(%o27) 2.72

This is probably better than typing in all the list entries by hand. There surely must be a better and more elegant way.
Any help/suggestions welcome.


text:
Q: Fit four authors across on one row in "sigplanconf" style? Is there some hack out there to make it possible to fit four authors across in one row in the sigplanconf class?
No matter how short each author's name, affiliation, and email is, by default the style fits only 3 authors across in one row.
Having four authors results in a massive amount of wasted space.
Ideally, I'd like to have this:
                  Article Title

Fname Lname   Fname Lname   Fname Lname   Fname Lname
   dept           dept         dept          dept
  school         school       school        school
 email@edu     email@edu     email@edu     email@edu

     Abstract                .....................
....................         .....................
....................         .....................
....................         .....................

But this is what I have instead:
                  Article Title

Fname Lname        Fname Lname       Fname Lname
   dept               dept              dept
  school             school            school
 email@edu          email@edu         email@edu

                   Fname Lname
                      dept
                     school
                    email@edu

      Abstract               .....................
....................         .....................
....................         .....................
....................         .....................

Is there something I can do to \authorinfo to force them to be wider, or to squeeze 4 to a column?
My document looks like:
\documentclass[preprint,10pt]{sigplanconf}

\usepackage{amsmath}

\begin{document}

\title{My Title}

\authorinfo{Fname Lname}
           {school}
           {email@edu}
\authorinfo{Fname Lname}
           {school}
           {email@edu}
\authorinfo{Fname Lname}
           {school}
           {email@edu}
\authorinfo{Fname Lname}
           {school}
           {email@edu}

\maketitle

\begin{abstract}
...

A: By default, the class sigplanconf typesets the authors in rows and uses maximum three authors per row (this is done using the macro \@titleauthors); to change this behaviour, you need to redefine \maketitle and to define a command to allow typesetting four authors in a row (the command \@ivtitleauthors in my example, which was defined in a similar fashion to the default \@titleauthors command):
\documentclass[preprint,10pt]{sigplanconf}
\usepackage{amsmath}

\makeatletter
\def \@ivtitleauthors#1#2#3#4{%
  \if \@andp{\@emptyargp{#2}}{\@emptyargp{#3}}%
    \noindent \@setauthor{40pc}{#1}{\@false}\par
  \else\if \@emptyargp{#3}%
    \noindent \@setauthor{17pc}{#1}{\@false}\hspace{3pc}%
              \@setauthor{17pc}{#2}{\@false}\par
  \else\if \@emptyargp{#4}%
    \noindent \@setauthor{17pc}{#1}{\@false}\hspace{3pc}%
              \@setauthor{17pc}{#3}{\@false}\par
  \else
    \noindent \@setauthor{9.3333pc}{#1}{\@false}\hspace{1.5pc}%
              \@setauthor{9.3333pc}{#2}{\@false}\hspace{1.5pc}%
              \@setauthor{9.3333pc}{#3}{\@false}\hspace{1.5pc}%
              \@setauthor{9.3333pc}{#4}{\@true}\par
    \relax
  \fi\fi\fi
  \vspace{20pt}}
\def \@maketitle {%
  \begin{center}
  \@settitlebanner
  \let \thanks = \titlenote
  {\leftskip = 0pt plus 0.25\linewidth
   \rightskip = 0pt plus 0.25 \linewidth
   \parfillskip = 0pt
   \spaceskip = .7em
   \noindent \LARGE \bfseries \@titletext \par}
  \vskip 6pt
  \noindent \Large \@subtitletext \par
  \vskip 12pt
  \ifcase \@authorcount
    \@latex@error{No authors were specified for this paper}{}\or
    \@titleauthors{i}{}{}\or
    \@titleauthors{i}{ii}{}\or
    \@titleauthors{i}{ii}{iii}\or
    \@ivtitleauthors{i}{ii}{iii}{iv}\or
    \@titleauthors{i}{ii}{iii}\@titleauthors{iv}{v}{}\or
    \@titleauthors{i}{ii}{iii}\@titleauthors{iv}{v}{vi}\or
    \@titleauthors{i}{ii}{iii}\@titleauthors{iv}{v}{vi}%
                  \@titleauthors{vii}{}{}\or
    \@titleauthors{i}{ii}{iii}\@titleauthors{iv}{v}{vi}%
                  \@titleauthors{vii}{viii}{}\or
    \@titleauthors{i}{ii}{iii}\@titleauthors{iv}{v}{vi}%
                  \@titleauthors{vii}{viii}{ix}\or
    \@titleauthors{i}{ii}{iii}\@titleauthors{iv}{v}{vi}%
                  \@titleauthors{vii}{viii}{ix}\@titleauthors{x}{}{}\or
    \@titleauthors{i}{ii}{iii}\@titleauthors{iv}{v}{vi}%
                  \@titleauthors{vii}{viii}{ix}\@titleauthors{x}{xi}{}\or
    \@titleauthors{i}{ii}{iii}\@titleauthors{iv}{v}{vi}%
                  \@titleauthors{vii}{viii}{ix}\@titleauthors{x}{xi}{xii}%
  \else
    \@latex@error{Cannot handle more than 12 authors}{}%
  \fi
  \vspace{1.75pc}
  \end{center}}
\makeatother

\begin{document}

\title{My Title}

\authorinfo{Fname Lname}
           {school}
           {email@edu}
\authorinfo{Fname Lname}
           {school}
           {email@edu}
\authorinfo{Fname Lname}
           {school}
           {email@edu}
\authorinfo{Fname Lname}
           {school}
           {email@edu}

\maketitle

\begin{abstract}

\end{abstract}

\end{document}

If you are writing for a journal, make sure that this kind of change is accepted; otherwise, maintain the original layout.


text:
Q: Gparted funkiness - won't recognize 1TB, full-hdd /home partition, but recognizes ext4 and /home label I have a 1TB SATA hard disk from my old desktop, and the entire thing is an ext4 /home partition (/, /boot, and swap were all on another hdd).  It is now in a USB2 enclosure and I want to use it to back up my current laptop /home.
To do this I need to shrink the /home partition on the 1TB backup drive.  It only uses about 500GB so that shouldn't be a problem, I'll start the laptop with an Ubuntu live USB, plug in the 1TB drive, and use Gparted to shrink the 1TB /home partition to ~500GB.
Then I can create a second partition in the newly freed space, and cp -ax my laptop's /home over to it.
Unfortuntely, Ubuntu Live USB can detect and mount the external hdd, and Gparted can see it's there, but Gparted can't read it and hence can't resize it.  Disk Utility reports the drive is fine, no errors, so I'm not sure what's the problem.  See linked pics, worth a thousand words.
Anyone know what the problem is here?  Any pointers in the right direction much appreciated.

A: The disk is fine, but the partition's filesystem isn't.
Close gparted, and run this to check (and fix) the partition:
sudo fsck /dev/sdd1

After it fixes the errors, gparted will be able to resize it.
The is equivalent of using Disk Utilitiy's "Check Filesystem" button. I still prefer the command-line version to see all the messages and errors that may be, but I'm a control freak. If you're not, go ahead and use the GUI button, I agree it's much simpler :)


text:
Q: Clicking the navbar item using scripts What should i replace to click this navbar called security printing? Im new with laravel.
$('.anotha').on('click', function () {
if ($(this).on(':clicked')) {
    $('#secur').clicked();
   }
})

I know its wrong code. But I tried
$('.anotha').on('click', function () {
if ($(this).on(':clicked')) {
    $('#secur').click();
   }
})

Nothing happened too, still the current active navbar is the about us
$('.anotha').on('click', function () {
if ($(this).on(':clicked')) {
    $('#secur').show();
}
});

Nothing happened because the tab-item is already showed. same as
$('.anotha').on('click', function () {
if ($(this).on(':clicked')) {
    $('#secur').select();
   }
})

and
$('.anotha').on('click', function () {
if ($(this).on(':clicked')) {
    $('#secur').selected();
   }
})

UPDATE:
When I remove the if clause the code will look like this:
$('.anotha').on('click', function () {
    $('#secur').selected();
})

Same as other code but nothing happened still.

A: Every HTML element has a click() method that can be called to simulate a mouse click.
    document.getElementById('#secur').click();

jQuery provides it's own method that wraps this feature.
$('.anotha').on('click', function () {
    $('#secur').click();
})

By the way, this does not require jQuery to accomplish. The following code would be the equivalent in plain javascript.
let a = document.querySelectorAll('.anotha');
let s = document.querySelector('#secur');

a.forEach(x => {
    x.addEventListener('click', event => {
        s.click();
    });
});

s.addEventListener('click', event => {
    console.log('#secur was clicked');
});


text:
Q: How do I increment value in textfield? im new to iphone, i have a two button left and right when i click left button to decrease the value in textfield and then i click right button to increase the value in textfield in iphone.
please any one help me.
left button (num1.tag=10)
text1.text=[NSString stringwithformat:@"%d",num2.tag-1];

right button (num2.tag=11)
text1.text=[NSString stringwithformat:@"%d",num2.tag];

A: you can try this :
- (void) btnAction :(id) sender
 {
       if ([sender tag] == 10) //left button
       {
             int aNumber = [[text1 text] intValue];
             aNumber = aNumber - 1 ;
             text1.text=[NSString stringwithformat:@"%d",aNumber];
       }
       else if ([sender tag] == 11) //Right button
       {
            int aNumber = [[text1 text] intValue];
            aNumber = aNumber + 1 ;
            text1.text=[NSString stringwithformat:@"%d",aNumber];
       }
 }

A: convert the textValue to int and perform ur action
if(leftButton)
{
int newVal=[text1.text.text intValue]-1;
 text1.text=[NSString stringwithformat:@"%d",newVal];

}
else
{
int newVal=[text1.text.text intValue]+1;
 text1.text=[NSString stringwithformat:@"%d",newVal];
}


text:
Q: How to make input-field seem like regular text In an ASP.NET application I have a lot of textbox controls that are displayed as readonly input fields. I want them to look like plain text. I tried a few things with styling and I have no luck so far (for example the disable attribute makes the text gray as well, and I am not sure if this works well with the ASP.NET databinding).
Is there a way to use styling/jquery to make an input field look like a plain text field?

A: I'm not entirely sure what you are trying to achieve, you want an input field that is disabled look like plain text? I guess something like this should do:
HTML:
 <input type="text" value="This is an example." disabled="disabled"/>

CSS:
 input[type="text"]{
        border: none;
        background: transparent;
        color: #000;
    }

JSFIDDLE to check online.

A: Have you tried
background-color: #fff

?


text:
Q: Gson convert Object with ArrayList field to JSON and back I have a class with two fields.
public class Example {
    private String exampleString;
    private List<Example2> example2List;

    public Example(String exampleString, List<Example2> example2List) {
        this.exampleString = exampleString;
        this.example2List = example2List;
    }

    public String getString() {
        return exampleString;
    }

    public List<Example2> getExample2List() {
        return example2List;
    }
}

In another class I want to convert my Example.class to a JSON String with GSON and convert it back.
public class MainExample {

    public MainExample() {
        Gson mGson = new Gson();

        List<Example2> example2List = new ArrayList<>();
        example2List.add(new Example2());
        example2List.add(new Example2());

        Example example1 = new Example("hello", example2List);

        String resultToJSON = mGson.toJson(example1); //This works fine. The example2List is stored as a JSON Array.

        Example resultFromJSON = mGson.fromJson(resultToJSON, Example.class); // This gives me an error: "Expected BEGIN_OBJECT but was NUMBER at line 1 column 2 path $"
    }
}

I found some solutions on how to deal with JSON Arrays in GSON but I did not find any on how to deal with fields which are lists from an object which should be converted to JSON via Gson.
Any solutions to this? Thanks in advance!
EDITS:
public class Example2 {
    private String string;
    private int integer;

    public Example2(String string, int integer) {
        this.string = string;
        this.integer = integer;
    }

    public String getString() {
        return string;
    }

    public int getInt() {
        return integer;
    }
}

A: I have tried to recreate the error you have mentioned. The following is the code I have used.
Example.java class :
package co.mr_tpktrustcircle.testgson;

import java.util.List;

public class Example {
    private String exampleString;
    private List<Example2> example2List;

    public String getExampleString() {
        return exampleString;
    }

    public List<Example2> getExample2List() {
        return example2List;
    }

    public Example(String exampleString, List<Example2> example2List) {
        this.exampleString = exampleString;
        this.example2List = example2List;
    }
}

Example2.java class
package co.mr_tpktrustcircle.testgson;

public class Example2 {
    private String string;
    private int integer;

    public Example2(String string, int integer) {
        this.string = string;
        this.integer = integer;
    }

    public String getString() {
        return string;
    }

    public int getInt() {
        return integer;
    }
}

MainExample.java class :
package co.mr_tpktrustcircle.testgson;

import android.util.Log;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class MainExample {

    public MainExample() {
        Gson mGson = new Gson();
        List<Example2> example2List = new ArrayList<>();
        example2List.add(new Example2("example2.1", 2));
        example2List.add(new Example2("example2.2", 3));

        Example example1 = new Example("hello", example2List);

        String resultToJSON = mGson.toJson(example1); //This works fine. The example2List is stored as a JSON Array.
        Log.i("__json string : ", resultToJSON);
        Example resultFromJSON = mGson.fromJson(resultToJSON, Example.class); // This should give an error as you suggested: "Expected BEGIN_OBJECT but was NUMBER at line 1 column 2 path $"

        Log.i("__resultFromJSON.str : ", resultFromJSON.getExampleString());

        List<Example2> example2FromGson = resultFromJSON.getExample2List();
        for (Example2 example2Element : example2FromGson
                ) {
            Log.d("__example2 element : ",example2Element.getString() + " & " + example2Element.getInt());
        }
    }
}

MainActivity.java class :
package co.mr_tpktrustcircle.testgson;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        callSomething();
    }

    private void callSomething() {
        MainExample mainExample = new MainExample();
    }
}

gradle dependency :
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'com.google.code.gson:gson:2.4'

}

Log :
08-25 22:06:34.430 5906-5906/co.mr_tpktrustcircle.testgson I/__json string :: {"example2List":[{"integer":2,"string":"example2.1"},{"integer":3,"string":"example2.2"}],"exampleString":"hello"}

08-25 22:06:34.435 5906-5906/co.mr_tpktrustcircle.testgson I/__resultFromJSON.str :: hello

08-25 22:06:34.435 5906-5906/co.mr_tpktrustcircle.testgson D/__example2 element :: example2.1 & 2

08-25 22:06:34.435 5906-5906/co.mr_tpktrustcircle.testgson D/__example2 element :: example2.2 & 3

Result :
As you can clearly see from the output(log) there is no problem in your logic. I think you are missing something in your real project.

A: Although your code is working for me, I can suggest you one thing that might work for you because of difference in package structures.
In your Example class, your member variables are private. Gson is not able to create a pojo because of that. You should have getters and setters in the Example class because these are used by Gson to marshall/unmarshall the Pojo.


text:
Q: Tikzpicture as background I want to draw a tikzpicture and put it as background on one slide. So far I have this:
\documentclass{beamer}

\usepackage{tikz}

\begin{document}

\begin{frame}{Title}

% background
 \begin{figure}
 \centering
 \begin{tikzpicture}[overlay,scale=2.5]
 \pgftransformcm{1}{0.1}{0.2}{1}{\pgfpoint{0cm}{0cm}}
 % draw the grid
 \draw[step=.3cm,black!10,line width=0.01cm] (-3.9,-3.9) grid (3.9,3.9);
 \foreach \x in {-3.9,-3.6,...,3.9}
     \foreach \y in {-3.9,-3.6,...,3.9}
         \filldraw[black!10] (\x,\y) circle (0.4pt);
 \end{tikzpicture}
 \end{figure}

\begin{itemize}
\item<+-> First
\item<+-> Second
\item<+-> Third
\item<+-> Fourth
\end{itemize}

\end{frame}

\end{document}

but the background grid is covering also the title. How can I make so that the picture starts from just below the title bar of the frame?

A: If manual checking of needed values is OK, it remains to change transformation and translation:
\documentclass{beamer}

\usepackage{tikz}

\begin{document}

\begin{frame}{Title}

% background
 \begin{figure}
 \centering
 \begin{tikzpicture}[overlay,scale=2.5]
% \pgftransformcm{1}{0.1}{0.2}{1}{\pgfpoint{0cm}{0cm}}
\pgftransformcm{-1}{-0.1}{-0.2}{-1}{\pgfpoint{0cm}{-3cm}}
 % draw the grid
 \draw[step=.3cm,black!10,line width=0.01cm] (-3.9,-3.9) grid (3.9,3.9);
 \foreach \x in {-3.9,-3.6,...,3.9}
     \foreach \y in {-3.9,-3.6,...,3.9}
         \filldraw[black!10] (\x,\y) circle (0.4pt);
 \end{tikzpicture}
 \end{figure}

\begin{itemize}
\item<+-> First
\item<+-> Second
\item<+-> Third
\item<+-> Fourth
\end{itemize}

\end{frame}

\end{document}

A: Perhaps something like this?  Just add \earmark to any frame you want with this background.  Based on my answer at How to visually "earmark" certain slides?
\documentclass{beamer}
\usepackage{atbegshi}
\usepackage{lipsum,tikz}
\def\PageTopMargin{1in}
\def\PageLeftMargin{1in}
\newcommand\atxy[3]{%
 \AtBeginShipoutNext{\AtBeginShipoutAddToBoxForeground{%
  \smash{\hspace*{\dimexpr-\PageLeftMargin-\hoffset+#1\relax}%
  \raisebox{\dimexpr\PageTopMargin+\voffset-#2\relax}{#3}}}}}
\def\earmark{%
  \atxy{.5\paperwidth}{.5\paperheight}{\begin{tikzpicture}[opacity=.5,overlay,scale=2.5]
 \pgftransformcm{1}{0.1}{0.2}{1}{\pgfpoint{0cm}{0cm}}
 % draw the grid
 \draw[step=.3cm,black!10,line width=0.01cm] (-3.9,-3.9) grid (3.9,3.9);
 \foreach \x in {-3.9,-3.6,...,3.9}
     \foreach \y in {-3.9,-3.6,...,3.9}
         \filldraw[black!10] (\x,\y) circle (0.4pt);
 \end{tikzpicture}}
}
\begin{document}
\begin{frame}{Title}
\earmark
\begin{itemize}
\item<+-> First
\item<+-> Second
\item<+-> Third
\item<+-> Fourth
\end{itemize}

\end{frame}
\end{document}


text:
Q: drop duplicates based on two criteria My dataframe reads
** | Object ID | Top depth | Base Depth|**
 1 | obj1 | 1500 | 2000 |
 2 | obj1 | 1500 | 1800 |
 3 | obj1 | 1900 | 2000 |
 4 | obj2 | 900  | 1200 |
 5 | obj2 | 1000 | 1200 |
 6 | obj3 | 700  | 800  |

I want to drop duplicates but only if it is the same ID with a duplicate top and base depth. for instance, obj1(1) in the first row would be removed as obj1(2) has the same top depth and obj1(3) has the same base depth, obj2 would be left alone because only the base depth is a match.
I was trying to alter the drop duplicates command but I am not sure how to alter it for two true statements i.e. ID & Top Match  AND ID & bottom Match
One of my failed attempts:
new_df = old_df.drop_duplicates(subset=[('Object ID', 'Top depth') and ('Object ID', 'Base Depth')]).reset_index(drop=True)
Any help is greatly appreciated.
Edit for further clarification brought to my attention below:
The ones I want to drop are combinations of the two others, it encapsulates the depths. Shallowest is the top depth and deepest is the base depth.
Thanks!

A: Try it like this.
import pandas as pd
df = pd.DataFrame({'Object ID': ['obj1', 'obj1', 'obj1', 'obj2', 'obj2', 'obj3'],
                    'Top Depth': [1500, 1500, 1900, 900, 1000, 800],
                    'Base Depth':[2000, 1800, 2000, 1200, 1200, 800]})

df

df = df.sort_values('Object ID').drop_duplicates(subset=['Object ID','Top Depth'], keep='last')
df

A: I think this approach should work.
df = pd.DataFrame({'Object ID': ['obj1', 'obj1', 'obj1', 'obj2', 'obj2', 'obj2','obj2'],
                    'Top Depth': [1500, 1500, 1900, 900, 1000, 1000, 900],
                    'Base Depth':[2000, 1800, 2000, 1200, 1200, 800, 1200]})

  Object ID  Top Depth  Base Depth
0      obj1       1500        2000
1      obj1       1500        1800
2      obj1       1900        2000
3      obj2        900        1200
4      obj2       1000        1200
5      obj2       1000         800
6      obj2        900        1200

# drop complete duplicates first
df = df.drop_duplicates(subset=['Object ID','Top Depth','Base Depth'])

# get list of values for Top Depth and Base Depth within the same Object ID
df['Top Depth List'] = df['Object ID'].map(df.groupby('Object ID')['Top Depth'].agg(list).to_dict())
df['Base Depth List'] = df['Object ID'].map(df.groupby('Object ID')['Base Depth'].agg(list).to_dict())

# determine duplicates
df['Duplicate'] = df.apply(lambda x: (x['Base Depth List'].count(x['Base Depth']) > 1) & (x['Top Depth List'].count(x['Top Depth']) > 1), axis=1)

# keep only non-duplicates and the original columns
df = df.loc[~df['Duplicate'], ['Object ID','Top Depth','Base Depth']]

  Object ID  Top Depth  Base Depth
1      obj1       1500        1800
2      obj1       1900        2000
3      obj2        900        1200
5      obj2       1000         800

A: find duplicates in the first two columns, find duplicates in the first and the last columns. Any thing is duplicate in both of them should be dropped: (Note you should use keep = 'last')
df[~(df.duplicated(subset = ['Object ID','Top Depth'], keep = "last") & df.duplicated(subset = ['Object ID','Base Depth'], keep = "last"))]


text:
Q: поиск по строкам с помощью ajax+php Есть такой интересный вопрос, хочу сделать что бы инфа с базы(PostgreSQL) выгружалась на сайт и по данной информации я уже проводил поиск.
Вот что у меня уже есть (index.php)(добавил строки которые формируются с база, для примера пока что 2):
<!doctype html>

    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="assets/css/style.css">
    <title>Test</title>

        <input id="search" type="text" placeholder="search" autofocus>

    1
    Protect
    Ukraine
    Beer

    2
    Protect
    Chaina
    Gear

Далее мой main.js:
function clients() {
    $.ajax({
        type: 'GET',
        url: "../../clients.php",
        cache: false,
        success: function (clients) {
            $('#task').html(clients);
        }
    });
}

jQuery(document).ready(function () {
    jQuery('#search').on('change click keyup', function () {
        var value = jQuery(this).val();
        var comp = jQuery('.company').val();
        var count = jQuery('.country').val();
        var good = jQuery('.good').val();
        if ((comp || count || good) != value) {
            jQuery('.info-clients').css('display', 'none');
        } else {
            jQuery('.info-clients').css('display', 'table-row');
        }
    })
});

И вот тут у меня начинается косяк, логика тут такова что при добавлении любого текста в input он сразу должен проходить через логику и показывать только те строки которые имею данные значения, но у меня при пустой показываются все а только начинаю любое слово вводить сразу все пропадает как будто совпадений не найдено, помогите голову 3 сутки ломаю что не так((
Для того что бы понимать что находиться в clients.php:
<?php

$conn = mysqli_connect('127.0.0.1','mysql', 'mysql', 'tryself', '3306');

if (!$conn) {
    exit ('MySQL error');
}

$users = mysqli_query($conn, 'SELECT * FROM clients WHERE 1');
while ($row=mysqli_fetch_array($users))
{
    print "
".$row['id']."	".$row['email']."	".$row['company']."	".$row['country']."	".$row['good']."
";
}

?>

A: Значение тега получаете не правильно. Можно так:
var count = jQuery('.country').html();

второе как я понл функция clients();  должен запускатся при вводе символов значит его надо перенести в
if ((comp || count || good) != value) {
jQuery('.info-clients').css('display', 'none');
} else {
jQuery('.info-clients').css('display', 'table-row');
}
clients();

и ещё функция должна передавть value файлу "clients.php"
я бы немного изменил её:
function clients( value ) {
    $.ajax({
        url: "clients.php",
        method: "POST",
        data: { val : value },
        success: function (clients) {
            $('#task').html(clients);
        }
    });
}

ну и соответственно передавал бы аргумент в clients( value );


text:
Q: Remove object from NSMutableDictionary at Index I have a UITableView that is configured for a subtitle cell.  When I add a cell to the TableView I have two arrays.  One for the subtitle and the other for the main label.  I also have an NSMutableDictionary so that when I add the cell to the table it records an object and a key.  My problem is when I want to delete the cell from the UITableView I use this method:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
    [myArray removeObjectAtIndex:indexPath.row];
    [numberArray removeObjectAtIndex:indexPath.row];

    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}

This works great for removing the objects from their associated arrays, but I also want to remove the objects from the MutableDictionary I made.  I thought that you would use somethings  similar to what I used with the arrays.
[myArray removeObjectAtIndex:indexPath.row];

But I can't use
 [myDictionary removeObjectForKey:indexPath.row];

Does anyone know how I would write this?

A: Since indexPath.row is a primitive type, it cannot be used as a key in NSDictionary: you need to wrap it in NSNumber in order to do so.
[myDictionary removeObjectForKey:[NSNumber numberWithInt:indexPath.row]];

This would work only if you use NSNumber-wrapped integers as keys in your NSMutableDictionary. In general, since NSDictionary is an associative container, you need to use the same key in the calls of removeObjectForKey as you used in the calls of setObject:forKey:.

A: Use this code to delete the data from the NSMutableDictionary
//First get all the keys of dictionary into one array
 NSArray *sectionsArray = [mutaleDictionary allKeys];
//Get all the data of tapped section into one array by using indexpath.section
 NSMutableArray *objectsAtSection = [mutaleDictionary valueForKey:[sectionsArray objectAtIndex:indexPath.section]];
//remove the particular object by using indexPath.row from the array
 [objectsAtSection removeObjectAtIndex:indexPath.row];


text:
Q: Python linear least squares function not working Ok, so I'm writing a function for linear least squares in python and it's pretty much just one equation. Yet for some reason, I'm getting a ValueError. My best guess is it has something to do with the .reshape function, since in this question I had a very similar problem and reshaping was the solution. I've read up on it and from what I gather, w in my function is in format (n,) and the result would be in (n,1) as in my previously mentioned question. I tried reshaping x_train and y_train but I only got an error that I can't change the size of the array. I guess my parameters were set wrong. Right now I'm lost, and I have many more functions like these to go through -- I wish I could understand what am I missing in my code. The equation seems to be in order, so I suppose there's something I should be adding everytime - possibly the reshape function cause I'm still using the same models as in the last situation. I hope it's the right place to post this question, I don't know what else to do but I really want to understand so I won't have these problems in the future, thank you.
Code (np. stands for numpy):
def least_squares(x_train, y_train, M):
    '''
    :param x_train: training input vector  Nx1
    :param y_train: training output vector Nx1
    :param M: polynomial degree
    :return: tuple (w,err), where w are model parameters and err mean squared error of fitted polynomial
    '''
    w = np.linalg.inv(design_matrix(x_train, M). * design_matrix(x_train, M)) * design_matrix(x_train, M).T * y_train
    err = mean_squared_error(x_train, y_train, w)
    return (w, err)

design_matrix and mean_squared_error are working just fine.
Traceback:
ERROR: test_least_squares_err (test.TestLeastSquares)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "\content.py", line 48, in least_squares
    w = np.linalg.inv(design_matrix(x_train, M).T * design_matrix(x_train, M)) * design_matrix(x_train, M).T * y_train
ValueError: operands could not be broadcast together with shapes (7,20) (20,7)

A: Assuming that design_matrix returns a matrix, this code
design_matrix(x_train, M).T * design_matrix(x_train, M)

most likely does not do what is intended since * is performing element-wise multiplication (Hadamard product of two matrices). Because your matrices are not square, it thus complains about incompatible shape.
To obtain matrix-matrix product, one might do (assuming numpy was imported as import numpy as np):
np.dot(design_matrix(x_train, M).T, design_matrix(x_train, M))

Similar reasoning then applies to the rest of the statement * design_matrix(x_train, M).T * y_train...
Also, you might want to evaluate design_matrix only once, e.g., to put something like
mat = design_matrix(x_train, M)

before the line calculating w and then use merely mat.


text:
Q: How can I get ImageDatasetImportDataOp to update labels? In a Vertex AI pipeline I am updating an image dataset, thus:
    ds_op = gcc_aip.ImageDatasetImportDataOp(
        project=project,
        dataset=get_dataset_id_op.outputs['dataset'],
        gcs_source=DATASET_PATH,
        import_schema_uri=aiplatform.schema.dataset.ioformat.image.single_label_classification
    )

I have tried adding images, updating the csv file with their path and label and uploading this to GCS. Then I run the pipe, the images are uploaded to the dataset but their labels are ignored and they are classed as Unlabeled. What am I doing wrong? TIA!
UPDATE: I am trying to use 'data_item_labels (JsonObject): Labels that will be applied to newly imported DataItems.' but I don't know what format is expected. i have tried JSON, csv, json lines etc but keep getting
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)'

errors.
UPDATE 2: finally figured out I should be passing a JSON object not a file uri, but I have tried everything I can think of and I either get JSON errors or "Invalid data_item_labels.".


text:
Q: How to access the object hierarchy shown by a GWT CellTree from a custom SelectionEventManager? I'd like to make a custom CellTree that would use checkbox based cells (I would like to use tristate checkboxes so will have to write a custom cell). I would like to make the parent node selection to select all its children and also if all children is selected then the parent node's checkbox should become selected too. If not all children are selected only some of them, then the parent checkbox should be in the so called "third state".
To achieve this I made a custom public class TriStateSelectionEventManager extends DefaultSelectionEventManager<TopologyNodeRep> and wanted to override its
public void doMultiSelection(MultiSelectionModel<? super TopologyNodeRep> selectionModel,
                                 HasData<TopologyNodeRep> display,
                                 int row,
                                 TopologyNodeRep rowValue,
                                 DefaultSelectionEventManager.SelectAction action,
                                 boolean selectRange,
                                 boolean clearOthers)

method. I thought this is the most appropriate way to implement this requirement. My problem is that from this method I cannot access the tree data. The received display object contains all the necessary information, but it cannot be accessed as it is a CellTreeNodeView.NodeCellList instance that is a private inner class of a package access class.. :-(
Do you have any idea how to implement this requirement in GWT?

A: Does your TopologyNodeRep class have references to its childs and parents respectively?
In case it does you could retrieve the childs of a specific selected TopologyNodeRep instance and also select its childs automatically.
Something like this:
List<TopologyNodeRep> childs = rowValue.getChilds();
for (TopologyNodeRep child: childs) {
    selectionModel.setSelected(child,true);
}


text:
Q: Count number of top-level items in ZIP archive I'm looking for a terminal command to count the number of top-level items in a ZIP archive. I know that zip -l archive.zip will show the file count, but this shows all files, not just top-level items. If archive.zip will unzip to the following (* indicates top-level)
* Dir1
    File1
    File2
* Dir2
    File3
    File4
    File5
    File6
* Dir3
* File7
* File8

then I would like a program to output 5.

A: Took inspiration from AFH to use this solution
zipinfo -1 archive.zip |
    egrep '^[^/]+/?$' |
    egrep -v '__MACOSX' |
    wc -l |
    awk '{$1=$1};1'

What it does:
Get list of files in archive
Filter for top-level files or dirs; must either contain no '/' or end in '/'
Remove lines containing __MACOSX (for archives created on a Mac)
Get line count
Remove trailing whitespace; http://unix.stackexchange.com/a/205854/169465