text:
Q: Python pandas timeseries resample giving unexpected results The data here is for a bank account with a running balance. I want to resample the data to only use the end of day balance, so the last value given for a day. There can be multiple data points for a day, representing multiple transactions.
In [1]: from StringIO import StringIO

In [2]: import pandas as pd

In [3]: import numpy as np

In [4]: print "Pandas version", pd.__version__
Pandas version 0.12.0

In [5]: print "Numpy version", np.__version__
Numpy version 1.7.1

In [6]: data_string = StringIO(""""Date","Balance"
   ...: "08/09/2013","1000"
   ...: "08/09/2013","950"
   ...: "08/09/2013","930"
   ...: "08/06/2013","910"
   ...: "08/02/2013","900"
   ...: "08/01/2013","88"
   ...: "08/01/2013","87"
   ...: """)

In [7]: ts = pd.read_csv(data_string, parse_dates=[0], index_col=0)

In [8]: print ts
            Balance
Date
2013-08-09     1000
2013-08-09      950
2013-08-09      930
2013-08-06      910
2013-08-02      900
2013-08-01       88
2013-08-01       87

I expect "2013-08-09" to be 1000, but definitely not the 'middle' number 950.
In [10]: ts.Balance.resample('D', how='last')
Out[10]:
Date
2013-08-01     88
2013-08-02    900
2013-08-03    NaN
2013-08-04    NaN
2013-08-05    NaN
2013-08-06    910
2013-08-07    NaN
2013-08-08    NaN
2013-08-09    950
Freq: D, dtype: float64

I expect "2013-08-09" to be 930, or "2013-08-01" to be 88.
In [12]: ts.Balance.resample('D', how='first')
Out[12]:
Date
2013-08-01      87
2013-08-02     900
2013-08-03     NaN
2013-08-04     NaN
2013-08-05     NaN
2013-08-06     910
2013-08-07     NaN
2013-08-08     NaN
2013-08-09    1000
Freq: D, dtype: float64

Am I missing something here? Does resampling with 'first' and 'last' not work the way I'm expecting it to?

A: To be able to resample your data Pandas first have to sort it. So if you load your data and sort it by index you get the following thing:
>>> pd.read_csv(data_string, parse_dates=[0], index_col=0).sort_index()
            Balance
Date
2013-08-01       87
2013-08-01       88
2013-08-02      900
2013-08-06      910
2013-08-09     1000
2013-08-09      930
2013-08-09      950

Which explains why you got the results you got. @Jeff explained why the order is "arbitrary" and according to your comment the solution is to use mergesort algorithm on the data before the operations...
>>> df = pd.read_csv(data_string, parse_dates=[0],
                     index_col=0).sort_index(kind='mergesort')
>>> df.Balance.resample('D',how='last')
2013-08-01      88
2013-08-02     900
2013-08-03     NaN
2013-08-04     NaN
2013-08-05     NaN
2013-08-06     910
2013-08-07     NaN
2013-08-08     NaN
2013-08-09    1000
>>> df.Balance.resample('D', how='first')
2013-08-01     87
2013-08-02    900
2013-08-03    NaN
2013-08-04    NaN
2013-08-05    NaN
2013-08-06    910
2013-08-07    NaN
2013-08-08    NaN
2013-08-09    930

A: The problem is since your dates are dups there can effectively be an arbitrary order; ordering with dups is not guaranteed.
In [24]: ts.Balance.resample('D',how='last')
Out[24]:
Date
2013-08-01     87
2013-08-02    900
2013-08-03    NaN
2013-08-04    NaN
2013-08-05    NaN
2013-08-06    910
2013-08-07    NaN
2013-08-08    NaN
2013-08-09    930
Freq: D, dtype: float64

In [25]: ts.Balance.order().resample('D',how='last')
Out[25]:
Date
2013-08-01      88
2013-08-02     900
2013-08-03     NaN
2013-08-04     NaN
2013-08-05     NaN
2013-08-06     910
2013-08-07     NaN
2013-08-08     NaN
2013-08-09    1000
Freq: D, dtype: float64

Easiest way is to sort the data, but it is not clear what the ordering actually is (e.g. you need an exogenous parameter here to decide it).
pass sort=False to a groupby (you can't do this with resample though)
In [29]: ts.groupby(ts.index,sort=False).last().reindex(date_range(ts.index.min(),ts.index.max()))
Out[29]:
            Balance
2013-08-01       87
2013-08-02      900
2013-08-03      NaN
2013-08-04      NaN
2013-08-05      NaN
2013-08-06      910
2013-08-07      NaN
2013-08-08      NaN
2013-08-09      930

You can do it this way to get exactly what you are after
In [52]: df = DataFrame(ts.values,index=ts.index,columns=['values']).reset_index()

In [53]: df
Out[53]:
                 Date  values
0 2013-08-09 00:00:00    1000
1 2013-08-09 00:00:00     950
2 2013-08-09 00:00:00     930
3 2013-08-06 00:00:00     910
4 2013-08-02 00:00:00     900
5 2013-08-01 00:00:00      88
6 2013-08-01 00:00:00      87

In [54]: df.groupby('Date').apply(lambda x: x.iloc[-1]['values']).reindex(date_range(ts.index.min(),ts.index.max()))

Out[54]:
2013-08-01     87
2013-08-02    900
2013-08-03    NaN
2013-08-04    NaN
2013-08-05    NaN
2013-08-06    910
2013-08-07    NaN
2013-08-08    NaN
2013-08-09    930
Freq: D, dtype: float64


text:
Q: $\frac{xy}{z+1}+\frac{yz}{x+1}+\frac{zx}{y+1}$ is an integer Let $x$ be a positive integer. Does there always exist integers $y,z$ such that the sum
$$\frac{xy}{z+1}+\frac{yz}{x+1}+\frac{zx}{y+1}$$
is an integer, but none of the three terms of the sum is an integer?
For instance: Take $x=1$. Then we need the sum $$\frac{y}{z+1}+\frac{yz}{2}+\frac{z}{y+1}$$ to be an integer, with $y,z$ odd and $\frac{y}{z+1},\frac{z}{y+1}$ non-integers. We can take $y=z=3$.
For $x=2$ this becomes $\frac{2y}{z+1}+\frac{yz}{3}+\frac{2z}{y+1}$, and we can take $y=z=2$.
In general, if we take $y=z$ we have the sum $$\frac{2xy}{y+1}+\frac{y^2}{x+1}.$$

A: Let $y=z=2x(x+1)-1$. Then
$$
  \frac{xy}{z+1}=\frac{zx}{y+1}=x-\frac{1}{2(x+1)}
$$
and
$$
  \frac{yz}{x+1}=4x^2(x+1)-4x+\frac{1}{x+1}.
$$
Since $x+1\geq2$, neither of these are integers, but
$$
  \frac{xy}{z+1}+\frac{yz}{x+1}+\frac{zx}{y+1}=4x^2(x+1)-2x
$$
is an integer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proving Cauchy's condensation test by Cauchy-Schwarz inequality Using the Cauchy-Schwarz inequality, I was trying to prove Cauchy's condensation test which states that $\displaystyle\sum_{n=1}^{\infty}a_n$ converges iff $\displaystyle\sum_{n=1}^{\infty}2^na_{2^n}$ converges where $a_n$ is a non-negative, non-increasing sequence of real numbers.
Is the following approach viable:
Suppose $\displaystyle\sum_{n=1}^{\infty}2^na_{2^n}$ converges. By the C-S inequality, we have:
$\displaystyle\Bigg(\sum_{k=1}^{n} \dfrac{a_k \sqrt{2^{k}a_{2^k}}}{\sqrt{2^{k}a_{2^k}}}\Bigg)^2 \leq \displaystyle\Bigg(\sum_{k=1}^{n} \dfrac{a_k^2}{{2^{k}a_{2^k}}}\Bigg)\Bigg($$\displaystyle\sum_{k=1}^{n}2^ka_{2^k}\Bigg)$
$\Rightarrow \displaystyle \sum_{k=1}^{n}a_k \leq  \sqrt{ \displaystyle\Bigg(\sum_{k=1}^{n} \dfrac{a_k^2}{{2^{k}a_{2^k}}}\Bigg)\Bigg(\displaystyle\sum_{k=1}^{n}2^ka_{2^k}\Bigg)}$
The latter partial sum on the RHS is bounded but can we say anything about the boundedness of the former partial sum? Or is this approach too contrived? Any advice would be helpful. Thanks in advance.


text:
Q: CvRect error C2661: 'CvRect::CvRect' : no overloaded function takes 4 arguments opencv I create a:
CvRect aaaaa=CvRect(0,0,10,10);

but I got this error:

error C2661: 'CvRect::CvRect' : no overloaded function takes 4 arguments

I don't undestand why i got this since it takes 4 arguments.
I'm using c++ and Opencv 2.1

A: From reading the reference guide for CvRect it seems that it is a struct with no constructor. But there is a helper method named cvRect() that can be used to create a CvRect:
CvRect aaaaa = cvRect(0, 0, 10, 10);

A: the error message is clear, there is no constructor function 'CvRect::CvRect' takes 4 arguments. and in fact the constructor is no arguments.
and also, it is better
CvRect aaaa;

instead of
CvRect aaaa = CvRect();

the last one will takes one more copy constructor call.


text:
Q: Which is the behavior of @DirtiesContext when used together with KafkaEmbedded in unit tests? I am developing some tests of an application that uses Kafka-streams that also uses Spring Boot 1.5, which imports version 1.2 of spring-kafka. In details, I am using KafkaEmbedded to avoid using a real running instance of Kafka.
In many examples on the net, I found that the configuration of such kind of tests uses the annotation @DirtiesContext, like in the following  (found here)
@RunWith(SpringRunner.class)
@SpringBootTest
@DirtiesContext
public class SpringKafkaReceiverTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(SpringKafkaReceiverTest.class);

    private static String RECEIVER_TOPIC = "receiver.t";

    @Autowired
    private Receiver receiver;

    private KafkaTemplate<String, String> template;

    @Autowired
    private KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;

    @ClassRule
    public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, RECEIVER_TOPIC);

    // Rest of tests body
}

I googled a little, but I cannot find which is the aim to use @DirtiesContext. Can someone clarify me this point?
Thanks a lot.

A: When used with a @ClassRule embedded kafka, @DirtiesContext does not affect the broker; the broker is stopped via @AfterClass.
We generally recommend using @DirtiesContext at the class level because we don't want the test framework to cache the application context, since it is likely to have active components (@KafkaListener etc). We want them to stop since the broker will be killed when the class exits.
If a method is marked @DirtiesContext in this case, it has no effect.
If the embedded kafka is defined as a bean instead of a @ClassRule, its lifecycle is controlled by the application context instead of JUnit. In this case, method level @DirtiesContext will stop the broker as well as a class level annotation.

A: From Spring docs:

@DirtiesContext indicates that the underlying Spring ApplicationContext has been dirtied during the execution of a test (i.e., modified or corrupted in some manner — for example, by changing the state of a singleton bean) and should be closed. When an application context is marked dirty, it is removed from the testing framework's cache and closed. As a consequence, the underlying Spring container will be rebuilt for any subsequent test that requires a context with the same configuration metadata.

I don't have experience with spring-kafka, but I guess they are using it to clean messages generated by the test. But that would be very wasteful for test suite to have a lot of @DirtiesContext tests, because Spring context is not cached. In bigger projects it can take minutes to spin up Spring context, thus such annotated test can take so much time.
Therefore I fallback to @DitriesContext only if there is no other option. In case of KafkaEmbedded I would bet there is the way to throw away all the messages in @AfterClass test hook.


text:
Q: Compare current post Category in select menu I have done this many times but not via a form so i am getting a weird issues when trying to assign a "selected"  based on the current post term id...
Maybe the use of _the_category and then get_categories creates a conflict? Any one has any idea as to why this might happen?
No matter what the selected item is the last one and not the
Current post (get the post id via an outside form) category
Here is my code:
<?php
$postId = $_POST['postid']; // the value is recieved properly
$currentCategory = get_the_category($postId);  // the value is recieved properly
$currentCategoryId = $currentCategory[0]->term_id; // the value is assigned properly

$categories = get_categories('hide_empty=0'); // the value is recieved properly
$optionname = "postcats"; // the value is recieved properly
$emptyvalue = "";

// SELECET DROP DOWN TERMS
echo '<select name="'.$optionname.'" class="clientList"><option selected="'.$selected.'" value="'.$emptyvalue.'">'.__('Choose a category','sagive').'</option>';
foreach($categories as $category){
    // next line seem to not work!
    if($currentCategoryId == $category->term_id) {$selected = 'selected="selected"';}
    echo '<option name="'.$category->term_id.'" value="'.$category->term_id.'" '.$selected.'>'.$category->name.'</option>';
}

echo '</select>';
?>

if i try to echo the $currentCategoryId outside the foreach it works
but not inside it.. kinda weird!

A: OMG - i falied to clean "$selected" value... hope this helps someone
if you get confused for a moment like i did
<?php
$postId = $_POST['postid']; // the value is recieved properly
$currentCategory = get_the_category($postId);  // the value is recieved properly
$currentCategoryId = $currentCategory[0]->term_id; // the value is assigned properly

$categories = get_categories('hide_empty=0'); // the value is recieved properly
$optionname = "postcats"; // the value is recieved properly
$emptyvalue = "";

// SELECET DROP DOWN TERMS
echo '<select name="'.$optionname.'" class="clientList"><option selected="'.$selected.'" value="'.$emptyvalue.'">'.__('Choose a category','sagive').'</option>';
foreach($categories as $category){

    // HERE I ENTERED AN ELSE THAT WOULD CLEAN
    // THE VALUE OF $SELECTED

    if($currentCategoryId == $category->term_id) {$selected = 'selected="selected"';} else {$selected = ''}
    echo '<option name="'.$category->term_id.'" value="'.$category->term_id.'" '.$selected.'>'.$category->name.'</option>';
}

echo '</select>';
?>


text:
Q: Creating fields in database I am making a quiz portal and for that I am having a quiz table. Here I am saving the quiz id , quiz questions and quiz answers.
Now I am confused in the quiz answers part.
My question has 4 options so should I make 4 columns for four options, or should I make a comma separated list of 4 options and save in one column? Which will be the better choice?

A: Never store multiple values in a single column!
One way would be
questions table
---------------
id
quiz_id
title

answers table
-------------
id
question_id
answer_text

That way a question can have as many answers as you like.


text:
Q: Create Note object in ivanti HEAT using the the API in C# I've been tasked with creating a 'Note Business Object' using Ivanti HEAT API in C# This is what I tried to create:

*

*Make CreateNote method with this body:

        public Note CreateNote(ServiceRequest parent, string category, string summary, string notes)
        {
            Logger.Verbose($"Heat.CreateNote({parent}, {category}, {summary}, {notes}");

            String type = "Journal#Note";

            List<ObjectCommandDataFieldValue> dataFields = new List<ObjectCommandDataFieldValue>()
            {
                new ObjectCommandDataFieldValue()
                {
                    Name = "Category",
                    Value = category,
                },
                new ObjectCommandDataFieldValue()
                {
                    Name = "Summary",
                    Value = summary,
                },
                new ObjectCommandDataFieldValue()
                {
                    Name = "Notes",
                    Value = notes
                },
                new ObjectCommandDataFieldValue()
                {
                    Name = "ParentLink_Category",
                    Value = "ServiceReq"
                },
                new ObjectCommandDataFieldValue()
                {
                    Name = "ParentLink_RecID",
                    Value = parent.RecID
                },
                new ObjectCommandDataFieldValue()
                {
                    Name = "Status",
                    Value = "Logged"
                },
                new ObjectCommandDataFieldValue()
                {
                    Name = "CreatedDateTime",
                    Value = DateTime.UtcNow.ToString("MM/dd/yyyy HH:mm:ss")
                },
                new ObjectCommandDataFieldValue()
                {
                    Name = "LastModDateTime",
                    Value = DateTime.UtcNow.ToString("MM/dd/yyyy HH:mm:ss")
                },
            };

            return new Note(CreateObject(type, parent, dataFields), this);
        }

*Make the CreateObject method to create a Business Object:

        private WebServiceBusinessObject CreateObject(String type, WebServiceBusinessObject Parent, List<ObjectCommandDataFieldValue> variables)
        {
            Logger.Verbose($"Entered Heat.CreateObject({Parent}, {variables})");
            ObjectCommandData data = new ObjectCommandData();

            data.ObjectType = type;

            data.Fields = variables.ToArray();

            FRSHEATIntegrationCreateBOResponse response = Client.CreateObject(SessionKey, TenantId, data);
            Logger.Verbose($"Soap response status: {response.status}");
            Logger.Verbose($"Soap response Exception: {response.exceptionReason}");
            Logger.Verbose($"Soap response recId:{response.recId}");
            Logger.Verbose($"Soap response obj:{response.obj}");

            Logger.Verbose($"Exited Heat.CreateObject() => {response.obj}");
            return response.obj;
        }

*Test it by using following call in program

        Note newNote = Heat.CreateNote(SR, $"TestNote - {DateTime.Now.ToString("dd/MM/yy - HH:mm")}", "Test Note", "This test note has been created through the API");

        Console.WriteLine(newNote.RecID);

But then I get this exception:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
obj was null.
I'm really not that familiar with the Ivanti HEAT API and there's next to no clear information around it.
There's an example of creating a Task in the library and this one works completely.
EDIT:
This is the stack trace:

This is the method where it fails (in WebServiceBusiness):
        public WebServiceBusinessObjectExtented(WebServiceBusinessObject obj, Heat Heat)
        {
            this.Alias = obj.Alias; <-- null ref ex
            this.BusinessObjectName = obj.BusinessObjectName;
            this.FieldValues = obj.FieldValues;
            this.RecID = obj.RecID;
            this.TableRef = obj.RecID;
            this.Heat = Heat;

            InitializeCommandDate();
        }


text:
Q: Post request gives error on submitting forms data to server I have a form whose data I am submitting to server through post request. Here is my request code in controller:
        $scope.submitFormData = function (obj, html) {

        var posOptions = {timeout: 10000, enableHighAccuracy: false};
        $cordovaGeolocation
            .getCurrentPosition(posOptions)
            .then(function (position) {
                var lat = position.coords.latitude;
                var long = position.coords.longitude;
                var formId = html.Id;
                var url = base_url+"put/putFormFilledRawData.php?userid="+window.localStorage.userid+"&token="+window.localStorage.token+"&formid="+formId+"&lat="+lat+"&long="+long;
                var data = $(obj.target).serialize();
                $http.post(url, data).
                    success(function(data, status, headers, config) {
                        if(data.alert == 'SUCCESS'){
                            var myPopup = $ionicPopup.show({
                                title: 'Confirmation',
                                subTitle: 'Your data has been submitted successfully',
                                scope: $scope,
                                buttons: [
                                    {
                                        text: 'Ok',
                                        type: 'button-calm',
                                        onTap: function(e) {
                                            $(this).hide();
                                        }
                                    },
                                ]
                            });
                        }
                    }).
                    error(function(data, status, headers, config) {
                        var myPopup = $ionicPopup.show({
                            title: 'Error',
                            subTitle: 'An error has been occured try again later!',
                            scope: $scope,
                            buttons: [
                                {
                                    text: 'Ok',
                                    type: 'button-calm',
                                    onTap: function(e) {
                                        $(this).hide();
                                    }
                                },
                            ]
                        });
                    });

            }, function (err) {
                var myPopup = $ionicPopup.show({
                    title: 'Location Error',
                    subTitle: 'Not able to get the current location!!!',
                    scope: $scope,
                    buttons: [
                        {
                            text: 'Ok',
                            type: 'button-calm',
                            onTap: function(e) {
                                $(this).hide();
                            }
                        },
                    ]
                });
            });
    }
})

When I run this on my web browser and submit the form data, the date is getting submitted with lat and longs, and I get a response with alert as SUCCESS. But when I build the app and try it on my Android mobile the request does not submit instead it executes the error branch and shows me a custom message in popup that An error has been occurred try again later! So the request does not getting submit from mobile device.
The app I am building uses Cordova with Ionic framework and AngularJS.

A: It is best to display / log the errors from the callback somewhere in your code like JB Nizet says in the comment.
Change:
title: 'Error',
subTitle: 'An error has been occured try again later!',

To:
title: 'HTTP Error: '+status,
subTitle: data,

In your error callback you can see these variables data and status are available.


text:
Q: SQL WHERE Help: how do i pull data from multiple rows in one single query? I am not sure if this is supposed to use a subquery, or multiple temp tables...but any assistance would be great! i am trying to do the following in one query pull.
I want to pull, say, all rows where a User has Color=blue and Color=red. I am interested in pulling these multiple rows to determine which users CHANGED their Color from blue to red, or from red to blue.
The general query i have now is this. What is wrong and how can i improve it? thank you!

*

*Does this return Zero results because I am asking that the row's value has BOTH blue and red at the same time? (which is impossible)

*my other worry, is that if I use OR instead of AND, that i will include rows for users that are color blue, or color red, but did NOT change between the two colors.

SELECT *
FROM Table a
WHERE a.color='blue'
AND a.color='red'

A: I'm assuming userId as the id which defines user, you can replace with whatever you have in the table.  The problem is called Relational Division. Hope this helps!
    select * from table where color in ('blue','red') and userId in(select a.userId
    from Table a
    where a.color in ('blue','red')
    group by a.userid  //whatever defines user uniquely
    having count(distinct a.color)=2)

A: MySQL does not store history like what you are wanting it to do. What you need to do is to have another table for color history and log entries every time the user changes colors. I would post code with table structure but there are so many different ways that this could be done... So a question without table structure does not get an answer with table structure proposal.


text:
Q: For every unique value in column find the min 4 dates I am trying to find the min 4 dates for every unique value in a column and take the average of those 4.
For example
ID      Date      Value
aa1    1/1/2006    5
aa1    2/1/2007    4
aa1    3/2/2005    7
aa1    1/20/1998   10
aa1    5/3/2001    9
aa1    7/4/2010    10
aa2n   4/3/2002    5
aa2n   4/5/2002    6
aa2n   6/30/2011   7
aa2n   6/21/2012   5
aa2n   1/5/1998    3

I would like to output to be
ID     Avg Value
aa1      7.75
aa2n     5.25

A: We convert the 'Date' to Date class, arrange by 'Date' and get the mean of first 4 'Value' grouped by 'ID'
library(dplyr)
library(lubridate)
df1 %>%
  group_by(ID) %>%
  arrange(mdy(Date)) %>%
  summarise(Value = mean(head(Value, 4)))
# A tibble: 2 x 2
#  ID    Value
#   <chr> <dbl>
#1 aa1    7.75
#2 aa2n   5.25

Or we can do this with data.table
library(data.table)
setDT(df1)[order(mdy(Date)),.(Value = mean(head(Value, 4))), ID]
#     ID Value
#1: aa2n  5.25
#2:  aa1  7.75

A: You can use dplyr::top_n with n=-4 to select records for minimum 4 dates. The use dplyr::summarise to calculate mean for Value.
library(dplyr)
library(lubridate)

df %>% mutate(Date = mdy(Date)) %>%
  group_by(ID) %>%
  top_n(-4, Date) %>%    #Last 4 records, ordered by Date
  summarise(AvgVal = mean(Value))

# A tibble: 2 x 2
#  ID    AvgVal
#  <chr>  <dbl>
#1 aa1     7.75
#2 aa2n    5.25

Data:
df <- read.table(text =
"ID      Date      Value
aa1    1/1/2006    5
aa1    2/1/2007    4
aa1    3/2/2005    7
aa1    1/20/1998   10
aa1    5/3/2001    9
aa1    7/4/2010    10
aa2n   4/3/2002    5
aa2n   4/5/2002    6
aa2n   6/30/2011   7
aa2n   6/21/2012   5
aa2n   1/5/1998    3",
stringsAsFactors = FALSE, header = TRUE)


text:
Q: Copy with Find Creates Duplicate Files I'm trying to copy the latest files and directories from one location to another. I'm using the find command with a reference file. Any files newer than the reference file get copied.
find  /root/test/BACKUP/   -newer /root/test/BACKUP//reference -exec cp -r  '{}' /root/test/backup_170213_0328 ';'

The issue is if the /root/test/BACKUP/ has an sub directories these get copied separately in addition to getting copied as a sub directory. This creates duplicate files in the destination.
[root@localhost S3_Backup]# tree /root/test/BACKUP/
/root/test/BACKUP/
├── Chrysanthemum.jpg
├── Desert.jpg
├── Hydrangeas.jpg
├── Jellyfish.jpg
├── level2
│   ├── Lighthouse.jpg
│   ├── Penguins.jpg
│   ├── teddy.jpg
│   └── Tulips.jpg
└── reference

1 directory, 9 files
[root@localhost S3_Backup]# tree /root/test/backup_170213_0328
/root/test/backup_170213_0328
├── BACKUP
│   ├── Chrysanthemum.jpg
│   ├── Desert.jpg
│   ├── Hydrangeas.jpg
│   ├── Jellyfish.jpg
│   ├── level2
│   │   ├── Lighthouse.jpg
│   │   ├── Penguins.jpg
│   │   ├── teddy.jpg
│   │   └── Tulips.jpg
│   └── reference
└── level2
    ├── Lighthouse.jpg
    ├── Penguins.jpg
    ├── teddy.jpg
    └── Tulips.jpg

3 directories, 13 files

A: If you're on non-embedded Linux, or more generally if your cp command is from GNU coreutils, then you can use cp -u to copy only files that are newer than the destination. If you don't already have files under /root/test/backup_170213_0328 that are more recent than the files under /root/test/BACKUP/, then this is equivalent to what you're doing now, except that files won't be copied twice.
You should also pass the -p option to cp. Most of the time, and especially when making backups, you should preserve permissions. And you should pass -d if you want to copy symbolic links as such, rather than copy their targets. -rdp can be abbreviated as -a.
find  /root/test/BACKUP/   -newer /root/test/BACKUP//reference -exec cp -a  {} /root/test/backup_170213_0328 ';'

However, it's unclear to me why you would want to copy a whole directory tree if its root has been modified. For example, creating a file directly under /root/test/BACKUP would cause the whole tree to be copied. You should probably not copy directories.
find  /root/test/BACKUP/ ! -type d -newer /root/test/BACKUP//reference -exec cp -RPp {} /root/test/backup_170213_0328 ';'

Furthermore all files are getting copied under the root directory, instead of reproducing the directory tree. You can fix that by using a tool whose main purpose is to copy directory trees, rather than a tool whose main purpose is to copy individual files. For example, with pax:
find  /root/test/BACKUP/ ! -type d -newer /root/test/BACKUP//reference -exec pax -rw -pe {} /root/test/backup_170213_0328 ';'

Or with rsync:
find  /root/test/BACKUP/ ! -type d -newer /root/test/BACKUP//reference -exec rsync -a {} /root/test/backup_170213_0328 ';'

But if you want to make incremental backups, I suspect that what you're really after is rsync's --link-dest. Point it at your previous backup, and it'll make a backup where files that already existed are hard-linked to the previous backup.
rsync -a --link-dest=/root/test/backup_170213_0228 /root/test/BACKUP /root/test/backup_170213_0328


text:
Q: Copy multiple rows from one table to another table in oracle Table 1
Item  ----  Qauntity  ---- Code
123 1 ---    10       ---  123
123 2 ---    20       ---  123
123 3 ---    30       ---  123
653 3 ---    60       ---  345
653 2 ---    30       ---  345
653 4 ---    20       ---  345
967 3 ---    10       ---  967
967 2 ---    20       ---  967
967 1 ---    30       ---  967

Table 2:
Code --   Qauntity
123  --     40
345  --     30
444  --     10
234  --     20
653  --     60

I need to get sum(Quantity) with group by code from table 1 and update in table 2 if Code exists else insert a new row. Remaining rows leave as it is in Table 2. How can I write a oracle plsql query for the following scenario.
Thanks

A: Using MERGE you can do that
merge into table2 t2 using (select code, quantity from table1) t1 on (t2.code = t1.code)
when not matched then insert (code,quantity) values (t1.code,t1.qty)
when matched then update set quantity = quantity+t1.quantity;

A: You can use merge to "upsert" a row (update or insert.)  The merge source can be a subquery where you can group by Code and calculate the sum of Quantity:
merge   into Table2 t2
using   (
        select  Code
        ,       sum(Quantity) as SumQuantity
        from    Table1
        group by
                Code
        ) t1
on      (t1.Code = t2.Code)
when    not matched then
        insert  (Code, Quantity)
        values  (t1.Code, t1.SumQuantity)
when    matched then
        update  set Quantity = t1.SumQuantity;

Example at SQL Fiddle.


text:
Q: Drupal user authentication check I have been trying to write a function to check if user is authenticated and then call a google analytics script for custom report. This has been a big hassle and I believe Drupal is not that difficult. Is there anyone who can help or take up the project?
It should be a simple and straight forward thing to do but being able to check user authentication has not been easy
I've tried to use a php function to check if user is logged in but I was not able to call javascript function from it.
I wrote a script function with jquery calling the script on page load but I was not able to check if user is logged in using javascript

A: Maybe it's not the best option, but...

*

*What do you think about calling, from your JS function, a custom module's controller, that return true if...
$currentUser = \Drupal::currentUser(); $uid = $currentUser->id(); returns a numeric value higher than 0 or false if the value returned is 0 (anonymous user)? This controller only should had to return the UID of the current user in a JSON format, readable afterwards from your JS.

*Another try would be to write a YOURTHEMENAME_preprocess_page() function in your theme's .theme file that implement the above check, and send the value to the template, in order to render the value in a 'data-attribute' in some DOM element. Once rendered, you could access the value from your JS.
None of these approachs are 'Drupal way' of doing the stuff, but... hope these help you.
Cheers.


text:
Q: Extract value from an XMLfile using python based on a specific keyword I want to extract values of different nodes if the keyword "cardiovascular" exists in one of the node. Here is my code:
import xml.etree.ElementTree as ET
tree=ET.parse(r'G:\My Drive\dru.xml')
for channel in tree.findall('.//drug'):
    if channel.find('indication') is not None:
        comment = channel.find('indication')
        if comment.text is not None:
            if "cardiovascular" in comment.text:
                print(channel.find('indication').text)
                print (channel.find('name').text)

I  do not see any errors but I don't see any outcome, either. Although in the xml files I can see the keyword "cardiovascular".
Here is a part of the XMl file:
<?xml version="1.0" encoding="UTF-8"?>
<drugbank xmlns="http://www.drugbank.ca" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.drugbank.ca http://www.dru.xsd" version="5.1" exported-on="2018-07-03">
<drug type="biotech" created="2005-06-13" updated="2018-07-02">
  <drugbank-id primary="true">DB00001</drugbank-id>
  <drugbank-id>BTD00024</drugbank-id>
  <drugbank-id>BIOD00024</drugbank-id>
  <name>Lepirudin</name>
  <description>Lepirudi.</description>
  <cas-number>138068-37-8</cas-number>
  <unii>Y43GF64R34</unii>
  <state>liquid</state>
  <groups>
    <group>approved</group>
  </groups>
  <general-references>
    <articles>

        <pubmed-id>16244762</pubmed-id>
        <citation>Smythe</citation>

        <pubmed-id>16690967</pubmed-id>
        <citation>Tardy B,</citation>

        <pubmed-id>16241940</pubmed-id>
        <citation>ggg</citation>

    </articles>
    <textbooks/>
    <links>
      <link>
        <title>Google books</title>
        <url>http://books.google.com/books?id=iadLoXoQkWEC&pg=PA440</url>
      </link>
    </links>
  </general-references>
  <synthesis-reference/>
  <indication>For cardiovascular</indication>
  <pharmacodynamics>Lepirudin </pharmacodynamics>
  <mechanism-of-action>Lepirudin</mechanism-of-action>
  <toxicity>In ca</toxicity>
  <metabolism>Lepirudi</metabolism>
  <absorption>Bioavailability is 100% following injection.</absorption>
  <half-life>Approximately 1.3 hours</half-life>
  <protein-binding/>
  <route-of-elimination>Lepir</route-of-elimination>
  <volume-of-distribution>*</volume-of-distribution>
  <clearance>* 164 ml/min [Healthy 18-60 yrs]
* 139 ml/min [Healthy 65-80 yrs]
* 61 ml/min [renal impaired]
* 114 ml/min [HIT (Heparin-induced thrombocytopenia)]</clearance>
  <classification>......

Also, I have to mention that there are multiple <drug> nodes in the XML file, and there are multiple <indication> nodes in each <drug> node

A: Something that might help would be to use some library that supports xpath contains queries (seems like you can do it with lxml but etree I think only supports limited xpath queries?), then navigate the tree to whichever node you want to return/access some other value of. Here's an example on line 45 of something someone posted on github here: https://gist.github.com/IanHopkinson/ad45831a2fb73f537a79


text:
Q: Why doesn't "strip(,.)" also strip ","s? I'm doing this python tutorial on kaggle.com. This is my current task:
"A researcher has gathered thousands of news articles. But she wants to focus her attention on articles including a specific word. Complete the function below to help her filter her list of articles.
Your function should meet the following criteria

*

*Do not include documents where the keyword string shows up only as a part of a larger word. For example, if she were looking for the keyword "closed", you would not include the string "enclosed."

*She does not want you to distinguish upper case from lower case letters. So the phrase "Closed the case." would be included when the keyword is "closed"

*Do not let periods or commas affect what is matched. "It is closed." would be included when the keyword is "closed". But you can assume there are no other types of punctuation."

This is what I tried:
def word_search(doc_list, keyword):
    mylist = []

    for ele in doc_list:
        if len([ele for ele in ele.lower().strip(".,").split() if ele == keyword.lower()]) > 0:
            mylist.append(doc_list.index(ele))

    return mylist

But this example
doc_list=['The Learn Python Challenge Casino.', 'They bought a car, and a horse', 'Casinoville?']
word_search(doc_list, 'car')

gives me [] instead of the expected [1] (as 'car' is included in the second string).
For debugging, I altered my code to
def word_search(doc_list, keyword):
for ele in doc_list:
    print([ele for ele in ele.lower().rstrip('.,').split()])

and I get
['the', 'learn', 'python', 'challenge', 'casino']
['they', 'bought', 'a', 'car,', 'and', 'a', 'horse']
['casinoville?']

As you can see, the "," with "car," remains although I tried to strip(".,") it. Any ideas about why this is the case?
If I try "car,".strip(".,") I get the expected 'car'.
Thanks!

Edit: Thanks for the help - I didn't know that it strips only on the edges. Here are two solutions for future readers:
def word_search(doc_list, keyword):
    mylist = []

    for ele in doc_list:
        tmp = [ele.lower().strip(".,") for ele in ele.split()]
        if len([ele for ele in tmp if ele == keyword]) > 0:
            mylist.append(doc_list.index(ele))

#         if len([ele.strip(".,") for ele in ele.lower().split() if ele.strip(".,") == keyword.lower()]) > 0:
#             mylist.append(doc_list.index(ele))
    return mylist

A: You are stripping the whole sentence, not each word individually. car, is in the middle of the sentence, so it won't get stripped. Change to:
    if len([ele for ele in ele.lower().split()
            if ele.strip(".,") == keyword.lower()]
          ) > 0:


text:
Q: How many 5 digit numbers can be formed out of {1,2,3...,9} where a digit can repeat at most twice? The question is: How many different numbers of 5 digits can be generated out of {1,2,3,4,5,6,7,8,9} such that no digit can appear more than twice ? That is a number like 11213 is not allowed. but 12345, 11224 etc are allowed.
For 3 digit numbers,I argued as follows: without any restriction on repetition, there are 9^3 possibilities, which is equal to 9x8x7 + 9xC(3,2)*8 + 9(where C(3,2) is 3 choose 2). In this case the answer is 9^3-9. [Note: 9x8x7 is where no repetitions are allowed, 9xC(3,2)*8 is where 1 digit can repeat exactly twice, 9 is where all digits are repeated]
However, for the 5 digit case, I argued similarly but getting wrong answer. Here is what I did.
for no repetitions: 9x8x7x6x5; only one digit repeats exactly twice: 9xC(5,2)x[8x7x6 + 8xC(3,2)x7 ] ; only one digit repeats exactly thrice: 9xC(5,3)x8x8 ; similarly 9xC(5,4)x8 and finally just 9 (for all repetitions).
So if this is correct, then 9^5 = 9x8x7x6x5 + 9xC(5,2)x[8x7x6 + 8xC(3,2)x7] + 9xC(5,3)x8x8 + 9xC(5,4)x8 + 9 and my answer should be: 9^5 - [9 + 9xC(5,4)x8 + 9xC(5,3)x8x8]
Unfortunately, L.H.S is far less than R.H.S
I am over counting somewhere but couldn't figure it out.
Any explanation or correct answer would be greatly appreciated.
Thanks

A: Your cases approach will work. For no repetitions, the number is clearly $9\cdot 8\cdot 7\cdot 6\cdot 5$.
For a single repetition, the repeated digit can be chosen in $9$ ways. For each way, its locations can be chosen in $\binom{5}{2}$ ways, and for every such way the empty spots can be filled in $8\cdot 7\cdot 6$ ways.
Double repetition is a little trickier. The two fortunate digits can be chosen in $\binom{9}{2}$ ways. For each such way, the locations of the larger digit can be chosen in $\binom{5}{2}$ ways, and then the locations of the smaller one can be chosen in $\binom{3}{2}$ ways. The remaining empty spot can be filled in $7$ ways.
Remark: We can alternately count the complement. This avoids the trickiness of the double repetition count, where it is all too easy to overcount by a factor of $2$. There are $9$ sequences with all entries the same. For $4$ the same and $1$ different, we have $9\cdot \binom{5}{4}\cdot 8$ choices. For $3$ the same and $2$ different, we have $9\cdot \binom{5}{3}\cdot 8\cdot 7$. And finally for $3$ the same and $2$ the same we have $9\cdot \binom{5}{3}\cdot 8$.

A: $9\times C(5,2)\times (8\times 7\times 6 + 8\times C(3,2)\times 7)$ should be
$9\times C(5,2)\times (8\times 7\times 6 + 8\times C(3,2)\times 7/2)$ because we count numbers $aabbc$ twice -- one for $a$ first and another for $b$ first, so 52920 is the right answer (I mean "first" corresponding to $9\times C(5,2)$).

A: The way I did it was to count the compliment like some one did before but I set it up as follows:  9( C(5,3)*81 + C(5,4)*9 + C(5,5))
Then I did the total 9^5 minus that.   That basically let there be at least three of a number which is required for a fail.


text:
Q: Why does my SDL window close when i return from an initializing function? I have been working on a simple game engine (i know, i know, i've heard "Write games not engines" before, this is just to understand the concepts). I have been using SDL2, since it works well with OpenGL.  However for some reason, the program closes once the initializing function is completed.
Screen.cpp:
Screen::Screen(int width, int height, const std::string& title)
    {

        //Initialize SDL
        SDL_Init(SDL_INIT_EVERYTHING);
        //Setting OpenGL Attributes
        SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
        SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
        SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
        SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
        SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32);
        SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

        //Create the Window
        m_window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL);
        l.writeToDebugLog("Created SDL_Window!");
        //Create OpenGL context from within SDL
        m_glContext = SDL_GL_CreateContext(m_window);
        l.writeToDebugLog("Created SDL GL Context!");

        //Initializing GLEW
        GLenum status = glewInit();
        l.writeToDebugLog( "Initializing GLEW");
        if (status != GLEW_OK)
        {
                l.writeToGLEWELog(" Glew Failed to Initialize!");
        }

        //setting the windowSurface to the m_window's surface
        windowSurface = SDL_GetWindowSurface(m_window);
        m_isClosed = false;
    }

This is where i create the screen object and initialize all of the SDL functions and OpenGL functions
Engine.cpp:
        void Engine::initialize(){

        //Console Detecting platform
        c.initialize();
        //Printing Operating System to screen
        std::cout << "Loaded on : " << platformToString(c.os) << " OS " << std::endl;
        //Constructing a new Screen to be referenced too
        graphics::Screen temp(800,600,"ClimLib 0.0.05");

        //setting all the variables
        m_window = &temp;
        m_EntityManager = nullptr;
        m_isRunning = temp.isClosed();
        m_renderer = SDL_GetRenderer(m_window->getWindow());

    }
    void Engine::update(){
        do{
            //Check whether entities have been created and placed in the manager
            if (m_EntityManager != nullptr){
                for each(core::Entity *e in *m_EntityManager){
                    for each(core::Component *c in e->getComponentList()){
                        c->Update();
                    }
                }
            }

            //Update Logic Here
            m_window->Update();
            if (m_window->isClosed()){
                m_isRunning = false;
                return;
            }

            }while (isRunning());
        }

This initialize function is the last function my window executes before it deletes itself, maybe i need to call it from the main function of the program?
main.cpp:
int main(int argc, char *argv[]){
    clim::system::Engine game;
game.initialize();
while (game.isRunning()){
    game.update();
    }
return 0;
}

That is how i have my main set up at the moment.
EDIT:  I believe the reason was because i am creating a variable and storing it as a reference, when the function returns the temp variable is thrown away?

A: You are creating your screen as a temporary value and then assigning the address of that value to a pointer whose lifetime actually exceeds the lifetime of the value it's pointing to that is very likely a stack value as well. Short of your immediate issue with the window dying, this will cause one or both of the following when used later:

*

*Crashes (illegal memory access)

*Undefined behavior (from reading random values on the stack that are sitting at this address later in execution)

While perhaps not applicable now, this is a real good way to cause headaches for yourself in pretty much everything.
You should just assign like this:
 m_window = new graphics::Screen(800,600,"ClimLib 0.0.05");

The way you initialized it means that it will destroy itself when the function exits as it was declared and initialized in the function.
Using new will guarantee it exists until you delete it because it will sit somewhere on the heap unmolested unless your code does.
Just make sure you call delete m_window in the destructor of the class containing it to properly clean up the window when you're done using it when using new to create it. You can also declare m_window to be a graphics::Screen instead of a graphics::Screen* and just assign m_window like:
m_window = graphics::Screen(800,600,"ClimLib 0.0.05");

This way you don't have to worry about deleting it yourself later as it will delete itself when the containing class is deleted.


text:
Q: X stopped working on Debian 11 all.
I had Debian set up to my liking with the capacity to run apps on the dedicated Nvidia graphics card except for two things I changed:

*

*Installing primus using sudo apt install nvidia-optimus. This was necessary to use primusrun with UCSF Chimera, which defaulted to the integrated Intel graphics card and threw an error when attempting to "Launch with dedicated graphics card"

*Attempting re-installation of Nvidia drivers and bumblebee following realization that xrandr --listproviders did not list the Nvidia card nor the Intel card. This all was in response to xrandr --setprovideroutputsource NVIDIA-G0 modesetting && xrandr --auto returning that NVIDIA-G0 doesn't exist.

In this process, I ran sudo apt reinstall nvidia-driver bumblebee, and nvidia-xconfig. I then restarted because xrandr --setprovideroutputsource NVIDIA-G0 modesetting && xrandr --auto returned the same error.
Since restarting, the screen is black after booting. I can switch to other sessions (using Ctrl+Alt+F3), but using startx makes that session another unresponsive black screen. I was hoping Debian 11 had some way of repairing the OS, and https://www.debian.org/releases/stretch/amd64/ch08s07.html.en suggested a rescue/enable=true boot command, which I added by pressing e in GRUB. The other approach I tried was suggested by https://www.makeuseof.com/how-to-find-and-fix-broken-packages-on-linux/. I tried this in recover mode, and sudo apt --fix-missing update returns "N: Failed to fetch ... Could not resolve " for every repository, including http://deb.debian.org/debian/dists/bullseye/InRelease. So, as suggested by https://askubuntu.com/questions/29071/apt-get-update-cannot-find-ubuntu-servers, I used sudo nano /etc/resolv.conf to add Google's DNS servers. I turned:

# Generated by NordVPN
nameserver 103.86.96.100
nameserver 103.86.99.100

into:

# Generated by NordVPN
nameserver 8.8.8.8
nameserver 8.8.4.4
nameserver 103.86.96.100
nameserver 103.86.99.100

The heading made me wonder if NordVPN is the problem, but I am unable to change its settings as nordvpn set killswitch 0 returns "Whoops! /run/nordvpn/nordvpnd.sock not found"
Clearly I've tried a lot of options, and decided I ought to seek advice since I may only be making an even bigger mess. There may be steps I attempted that I couldn't recall. I did not write anything down, like I typically do when making system changes.
**Edit: I also booted from a Live install, beginning the installer but stopping before partitioning drives once I realized there is not repair option.
Thank you!
I am grateful for the GNU/Linux community. It has made it a blast to switch from Windows/Mac to Debian.


text:
Q: Join many tables with one select I have some tables of different type of orders

*

*Table orderA
idA - int, idCustomer - int, propertieA1 - string, propertieA2 - int
...

*Table orderB
idB - int, idCustomer - int, propertieB1 - real, propertieB2 - int ...

*Table orderC
idC - int, idCustomer - int, propertieC1 - string, propertieC2 - string...
and a table of cutomers

*

*Table customer
idCustomer - int, name string, address - string...
Now I want to select all the orders of a particular customer. How can I do it?
I thought to do a select like this:
SELECT * FROM customer
INNER JOIN orderA ON orderA.idCustomer = customer.idCustomer
INNER JOIN orderB ON orderB.idCustomer = customer.idCustomer
INNER JOIN orderC ON orderC.idCustomer = customer.idCustomer
WHERE customer.idCustomer = 235

But it's giving me all the "orderA" with the first "oredrB", an again all the "orderA" with the second "orderB", and so on.
So if he had 100 orderA, 100 orderB and 100 orderC - the resulf is 100*100*100 rows - a million rows for 300 orders!
How can I fix it? (I can change the structure of the tables if it's necessary)
Thanks

A: If you can change the structure of the tables . . . then do it!  Put all the orders into a single table, even if you have NULL columns because the values do not apply.
If you want all the orders in one table, then you need to carefully choose the columns, and using union all. The general structure is:
SELECT *
FROM customer c INNER JOIN
     ((SELECT idCustomer, col1, col2, . . .
       FROM orderA
      ) UNION ALL
      (SELECT idCustomer, col1, col2, . . .
       FROM orderB
      ) UNION ALL
      (SELECT idCustomer, col1, col2, . . .
       FROM orderC
      )
     ) o
     ON o.idCustomer = c.idCustomer
WHERE c.idCustomer = 235;

You need to decide which columns you want and be sure that each subquery has a value for the column (even if the value is NULL).


text:
Q: CSS advanced shape (heart cut out of background) Basically I want to create a shape in CSS only (so no images) that is the opposite of a heart shape. I don't know how to explain it properly so here is an image:

The blue is the background, as you can see, but the shape that I want to create is not a heart, it is the shape of the black rectangle.
If I would have the following shape (THE GRAY NOT THE BLACK)

I could duplicate it and then rotate it, that would give me the shape I am looking for.

A: Heart shape cut out using box-shadow
Let's create this — the blue is the background color of

The pieces
Feel free to skip directly to the complete demo at the bottom of this answer :)
1 - The rounded corners
The rounded top left and top right corners are created with box-shadow on the two pseudo elements with border-radius: 50% — .heart:before and .heart:after — They form two crescent shapes that look like this:

2 - The angle
The angled shape is created by the box-shadow on .heart. Combined with the two circles, it looks like this:

3 - The filler
We now need to fill in the gaps. This is done by the pseudo elements of the .box-shape container — .shape-box:before and .shape-box:after. The excess is cut-off neatly with overflow: hidden on the .shape-box. Combined with our pieces above, they look like this:

The Complete Example
Combine it all together and we get this nicely cut out heart shape. It is all contained in .shape-box.

body {
  background: #00A2F6;
}
.shape-box {
  height: 504px;
  width: 504px;
  position: relative;
  margin: 100px;
  overflow: hidden;
}
.shape-box:before,
.shape-box:after {
  content: '';
  display: block;
  height: 100px;
  width: 120px;
  background: #2B2B2B;
  transform: rotate(45deg);
  left: 190px;
  position: absolute;
  top: 40px;
}
.shape-box:after {
  width: 760px;
  height: 750px;
  box-shadow: inset 0 0 0 220px #2B2B2B;
  top: -150px;
  left: -130px;
  background: none;
}
.heart {
  transform: rotate(45deg);
  height: 357px;
  width: 356px;
  box-shadow: inset 0 0 0 50px #2B2B2B;
  position: absolute;
  left: 74px;
  top: 34px;
}
.heart:before,
.heart:after {
  content: '';
  display: block;
  width: 151px;
  height: 151px;
  border-radius: 50%;
  box-shadow: -40px -15px 0 20px #2B2B2B;
  position: absolute;
  left: 50px;
  top: 157px;
}
.heart:after {
  box-shadow: -15px -40px 0 21px #2B2B2B;
  left: 156px;
  top: 51px;
}

A: This can be done with a combination of svg gradients, multiple backgrounds, and a little creative tiling/placement. Sample CSS from my working jsfiddle (without vendor prefixes, i.e. -webkit and -moz):
height: 400px;
width: 400px;
background-image:
  radial-gradient(75% 85.5%, circle, transparent 25%, black 26%),
  radial-gradient(25% 85.5%, circle, transparent 25%, black 26%),
  linear-gradient(225deg, transparent 25%, black 25%),
  linear-gradient(135deg, transparent 25%, black 25%);
background-size: 200px 200px;
background-position: top left, top right, bottom left, bottom right;
background-repeat: no-repeat;

This makes a heart-shaped cutout in the middle of a 400px square element. It can be modified to fit whatever size element you want.
Update: here's a more complex fiddle that uses six gradients instead of four, but looks a bit nicer.

A: Based on the work that Mark Hubbart did I was able to push this to a slightly more advanced form in this fiddle
This is not 100% complete yet as it will need some media queries to work across more browsers but it does show the start of a much more flexible working for the same goal.
#backgrounder {
z-index: 2;
background-image:
   radial-gradient(68% 100%, circle, transparent 48%, white 30%),
   radial-gradient(32% 100%, circle, transparent 48%, white 30%),
   radial-gradient(110% 1%, circle, transparent 65%, white 30%),
   radial-gradient(-8.5% 1%, circle, transparent 65%, white 30%),
   linear-gradient(220deg, transparent 41%, white 30%),
   linear-gradient(139deg, transparent 41%, white 30%);

 background-image:
    -webkit-radial-gradient(68% 100%, circle, transparent 48%, white 30%),
    -webkit-radial-gradient(32% 100%, circle, transparent 48%, white 30%),
    -webkit-radial-gradient(110% 1%, circle, transparent 65%, white 30%),
    -webkit-radial-gradient(-8.5% 1%, circle, transparent 65%, white 30%),
    linear-gradient(220deg, transparent 41%, white 30%),
    linear-gradient(139deg, transparent 41%, white 30%);

 background-size: 51% 31%, 50% 31%, 51% 50%, 50% 50%, 51% 51%, 50% 51%;
 background-position: top left, top right, 0% 30%, 100% 30%, bottom left, bottom right;
 background-repeat: no-repeat;
 position: absolute;
 top: 0; right: 0; bottom: 0; left: 0;
}


text:
Q: Is "git checkout --patch" incompatible with autocrlf=true? On my windows machine I'm considering setting autocrlf = true in my .gitconfig. Others on my team have it set this way and we've ended up with a mix of lf & crlf in the repo. I've considered a few options and this seems like the path of least resistance...
One thing I've noticed is that git checkout -p fails with the error patch does not apply when autocrlf = true. If I change it back to false it works as expected.
Is autcrlf = true incompatible with checkout --patch or is do I need to set some other option to get it to work?
Interestingly git add --patch works as expected with autocrlf = true.

A: Yes, git checkout --patch works properly with line ending translation.  The patch almost certainly isn't applying because you have mismatched configuration.
Everybody on your team needs to use the same line ending configuration.  core.autocrlf=true isn't an option that one person on a team can enable; everybody needs the same settings.  That's because if you have core.autocrlf=false, then you're telling Git that the contents on disk are identical to the contents in the repository.  If you're on Windows, that means that you're checking in files with Windows-style line endings (\r\n).  If you have a colleague who enables core.autocrlf=true, then you're telling Git that the contents on disk have Windows-style line endings while the contents in the repository have Unix style line endings (\n).
But your colleague has told git a lie, since the repository contents actually have \r\n in them.
A variety of strange things can occur when these settings are mismatched, including things like patches failing to apply.
You should instead:

*

*Set * text=auto in your .gitattributes file.  This ensures that everybody working in the repository has the same settings, since the configuration is actually checked in and not something that everybody has to remember to configure properly.

*Renormalize the repository, so that the repository contents actually match what you've claimed.  You can do this by git add --renormalize . and checking the contents in.
Once you've done this (and everybody has updated your local working folders), your git apply --patch should behave correctly.


text:
Q: Mysqli Statement: Blank Result Need help with my mysqli statement. I get no errors on the page but my if statement does not print out anything either....
//$dbConnection works.

$extensionAdd_query_domain_extension = mysqli_query($dbConnection, "
    SELECT *
    FROM domain
    WHERE extensions='$extensionAdd_extension'
    LIMIT 1");
$extensionAdd_query_domain_row = mysqli_fetch_array($extensionAdd_query_domain_extension, MYSQLI_NUM);
$extensionAdd_query_domain_id = sanitizeInt($extensionAdd_query_domain_row[0],$dbConnection);
$extensionAdd_query_domain_votes = sanitizeInt($extensionAdd_query_domain_row[2],$dbConnection);

//If domain id found in Db update votes otherwise add to list
if($extensionAdd_query_domain_id!='' && $extensionAdd_query_domain_votes!='')
    {
        echo 'Found in DB. Update Votes.'.$extensionAdd_extension;
    }
else
    {
        echo 'Not Found in DB. Enter in DB'.$extensionAdd_extension;
    }

A: Check the connection of your database and check your result with var_dump.
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

var_dump($extensionAdd_query_domain_row);


text:
Q: Ant: NoClassDefFound exception I am developing a java project. My instructor wants us to strictly use apache ant for compilation. I knew nothing about it, and don't know about apache ant either. I have generated an ant buildfile and edited that for target "run", so that program will run after ant run command.
I am getting following error,
Exception in thread "main" java.lang.NoClassDefFoundError: src/Client
     [java] Caused by: java.lang.ClassNotFoundException: src.Client
     [java]     at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
     [java]     at java.security.AccessController.doPrivileged(Native Method)
     [java]     at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
     [java]     at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
     [java]     at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
     [java]     at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
     [java] Could not find the main class: src.Client. Program will exit.

I think I have resolved all the target dependencies. But still this error persists.
Can somebody help me? This is my ant build.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- WARNING: Eclipse auto-generated file.
              Any modifications will be overwritten.
              To include a user specific buildfile here, simply create one in the same
              directory with the processing instruction <?eclipse.ant.import?>
              as the first entry and export the buildfile again. -->
<project basedir="." default="build" name="client">
    <property environment="env"/>
    <property name="ECLIPSE_HOME" value="../../../../usr/lib/eclipse"/>
    <property name="debuglevel" value="source,lines,vars"/>
    <property name="target" value="1.6"/>
    <property name="source" value="1.6"/>
    <path id="client.classpath">
        <pathelement location="bin"/>
        <pathelement location="libthrift-1.0.0-javadoc.jar"/>
        <pathelement location="libthrift-1.0.0.jar"/>
        <pathelement location="log4j-1.2.14.jar"/>
        <pathelement location="slf4j-api-1.5.8.jar"/>
        <pathelement location="slf4j-log4j12-1.5.8.jar"/>
    </path>
    <target name="init">
        <mkdir dir="bin"/>
    <mkdir dir="build"/>
        <copy includeemptydirs="false" todir="bin">
            <fileset dir="src">
                <exclude name="**/*.java"/>
            </fileset>
        </copy>
    </target>
    <target name="clean">
        <delete dir="bin"/>
    </target>
    <target depends="clean" name="cleanall"/>
    <target depends="build-subprojects,build-project" name="build"/>
    <target name="build-subprojects"/>
    <target depends="init" name="build-project">
        <echo message="${ant.project.name}: ${ant.file}"/>
        <javac debug="true" debuglevel="${debuglevel}" destdir="bin" source="${source}" target="${target}">
            <src path="src"/>
            <classpath refid="client.classpath"/>
        </javac>
    </target>
    <target name="jar" depends="init">
        <mkdir dir="build/jar" />
        <jar destfile="client.jar" basedir="bin">
            <manifest>
                <attribute name="Main-Class" value="src.Client" />
            </manifest>
        </jar>
    </target>
    <target description="Build all projects which reference this project. Useful to propagate changes." name="build-refprojects"/>
    <target description="copy Eclipse compiler jars to ant lib directory" name="init-eclipse-compiler">
        <copy todir="${ant.library.dir}">
            <fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar"/>
        </copy>
        <unzip dest="${ant.library.dir}">
            <patternset includes="jdtCompilerAdapter.jar"/>
            <fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar"/>
        </unzip>
    </target>
    <target description="compile project with Eclipse compiler" name="build-eclipse-compiler">
        <property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
        <antcall target="build"/>
    </target>
    <target name="Client">
        <java classname="Client" failonerror="true" fork="yes">
            <classpath refid="client.classpath"/>
        </java>
    </target>
    <target name="run" depends="jar">
        <java jar="client.jar" fork="true">
        </java>
    </target>
</project>

Can anybody spot the mistake for me?

A: Exception java.lang.NoClassDefFoundError occurs when some class, yours or in a library your code depends on, try to use a symbol not already loaded. The class loader use the java path package_aa.package_bb.SomeClass as a key into the set of of classes it knows, specified by -classpath or -cp. In your case this "repository is bin, libthrift-1.0.0-javadoc.jar, libthrift-1.0.0.jar, log4j-1.2.14.jar, slf4j-api-1.5.8.jar, slf4j-log4j12-1.5.8.jar.
In your context, when the class p1.p2.Client is about to be loaded, the classloader looks for bin/p1/p2/Client.class, look for /p1/p2/Client.class into each jar and when all the search paths are exhausted, the exception is thrown.
In this part of your build.xml :
<target name="jar" depends="init">
    <mkdir dir="build/jar" />
    <jar destfile="client.jar" basedir="bin">
        <manifest>
            <attribute name="Main-Class" value="src.Client" />
        </manifest>
    </jar>
</target>

value="src.Client" is wrong, it should be the logical java path i.e. the package + the class name. src is a directory not a package. If you haven't any package, it's just classname.
I presume
<attribute name="Main-Class" value="Client" />

That should do the trick.
Reference:

*

*Apache ANT Manual for Jar task.

*Oracle Jar Tools Manual (entry point)
EDIT after first debug, the second error appears:
<target name="run" depends="jar">
    <java jar="client.jar" fork="true">
    </java>
</target>

Can't work because Client.jar is not autonomous, it requires a lot of depndencies, which aren't specified here. You should use the classpath ref defined on top of your build.xml.
It may be wrote as:
<target name="run" depends="jar">
    <java classpathref="client.classpath" fork="true" classname="Client" />
</target>


text:
Q: store json response in array list error:value passed: ("contact") not found.
given code is to get json format data in array list.i'm doing this task in android studio. when i run the below code, i could see the json format data with error that "contact" not found.i have change that with obj and other declared variable,but still facing same problem.
any suggestion to resolve this?
here is the code:
 private String TAG = MainActivity.class.getSimpleName();

private ProgressDialog pDialog;
private ListView lv;

// URL to get contacts JSON
private static String url = "http://services.groupkt.com/state/get/IND/all";

List<JsonBean> listobj = new ArrayList<>();

//  ArrayList<HashMap<String, String>> contactList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

  //lv = (ListView) findViewById(R.id.list);

    new GetContacts().execute();
}

private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        Httphanlder sh = new Httphanlder();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {

            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray contacts = jsonObj.getJSONArray("contacts");

               JsonBean jsonbeanobj=new JsonBean();

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    jsonbeanobj.setCountry(c.getString("country"));
                    jsonbeanobj.setName(c.getString("name"));
                    jsonbeanobj.setAbbr(c.getString("abbr"));
                    jsonbeanobj.setArea(c.getString("area"));
                    jsonbeanobj.setCapital(c.getString("capital"));

                    listobj.add(jsonbeanobj);
                  }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();

    }

}

A: This might not be an answer to that problem, but usually when I see people using JSONObject..etc they are new to programming. I used to do the same :)
Have a look at Gson or Jackson Library, it will deserialise the json to a java object for you.
Then in that example you can do this using Jackson:
List contacts = Array.asList(mapper.readValue(json, Contact[].class));

public class Contact {
    @JsonCreator
    public Contact(@JsonProperty("name") name...etc)
      this.name = name;
    }
}

A: You need to use json array "result"
update this line
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("result");


text:
Q: Creating a sequence of has_many: :through objects in Rails I am building an application that allows users to create a custom diet for their dogs for a given number of days.  Users should be able to pick the order of the diet, i.e. dogbone first, steak next, then kibble, etc.  So far I have this:
class Dog < ...
  has_many :regimes
  has_many meals, through: :regimes
end
class Regime < ...
  belongs_to :dog
  belongs_to :meal
end
So how do I define a particular sequence for the regime?  I figure this feature will reside in the Regime class but I'm not sure how to proceed.  Any input much appreciated.

A: You would probably want to use conditions in your association (or customize the query), as follows:
#app/models/dog.rb
Class Dog < ActiveRecord::Base
   has_many :regimes, -> { order :meal_order }
end


text:
Q: How to get clicked image inside target div from source div which contain some images Q: How to get clicked image inside target div(id="p1") from source div(id="p2") which contain some images.
current result: Only the last image is displayed.Please suggest other logic, if I am Wrong.
P.S only javascript is required.
Some logic is required before {document.getElementById("p1").innerHTML="";}i.e the last line of the script code. So that exact clicked image is displayed rather than the last image,which is according to the current logic
Below is the code snippet:
<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>

 <input type="image" class="images"  id="obj0" name="obj" onclick="myFunction()" src="http://www.picgifs.com/clip-art/flowers-and-plants/flowers/clip-art-flowers-511058.jpg"/>

 <input type="image" class="images" id="obj1" name="obj" onclick="myFunction()" src="http://www.picgifs.com/clip-art/flowers-and-plants/flowers/clip-art-flowers-380016.jpg"/>

 <input type="image" class="images" id="obj2" name="obj" onclick="myFunction()" src="http://www.picgifs.com/clip-art/flowers-and-plants/flowers/clip-art-flowers-293063.jpg"/>

 <input type="image" class="images" id="obj3" name="obj" onclick="myFunction()" src="http://www.picgifs.com/clip-art/flowers-and-plants/flowers/clip-art-flowers-611834.jpg"/>

Thanks in advance !

A: You need to have an argument that passes the ID of something that was just clicked. Then you need to get the attribute of that ID that has been passed.
Here you go:
<!doctype html>

    <meta charset="utf-8">
    <title>Untitled Document</title>

            <input type="image" class="images" id="obj0" name="obj" onclick="myFunction(this)" src="http://www.picgifs.com/clip-art/flowers-and-plants/flowers/clip-art-flowers-511058.jpg" />

            <input type="image" class="images" id="obj1" name="obj" onclick="myFunction(this)" src="http://www.picgifs.com/clip-art/flowers-and-plants/flowers/clip-art-flowers-380016.jpg" />

            <input type="image" class="images" id="obj2" name="obj" onclick="myFunction(this)" src="http://www.picgifs.com/clip-art/flowers-and-plants/flowers/clip-art-flowers-293063.jpg" />

            <input type="image" class="images" id="obj3" name="obj" onclick="myFunction(this)" src="http://www.picgifs.com/clip-art/flowers-and-plants/flowers/clip-art-flowers-611834.jpg" />


text:
Q: ios http-request with provider proxy - site is always online I got a piece of code, that returns the header information from a website. If I shut down the service on port 80 and the website is offline, the app still returns the header information to me. This is due to the proxy of some providers.
The first three times it works correctly. It responds to online or offine. After the requests, the website is constantly online for the app.
This is my code:
- (IBAction)fastCheckButton:(id)sender {
    NSLog(@"TextfieldURL ist: %@", _textFieldUrl);
    NSError *error = nil;

    NSString* userAgent = @"Desktop";
    NSHTTPURLResponse *response = nil;
    NSInteger statusCode = [response statusCode];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:_textFieldUrl cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0];
    [request addValue:userAgent forHTTPHeaderField:@"User-Agent"];

    //NSData *conn = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSData* conn = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];

    [self connection:conn didReceiveResponse:response];

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    NSInteger statusCode = [httpResponse statusCode];
    NSDictionary* headers = [httpResponse allHeaderFields];

    NSLog(@"\n \n DELEGATE STATUS -->: \n \n %d \n  \n HEADERS -->: \n \n \n %@", statusCode, headers);
}

And this is a sample output with my apache running on port 80. Done over Wi-Fi
DELEGATE STATUS -->:

 200

 HEADERS -->:

{
    "Accept-Ranges" = bytes;
    Connection = "Keep-Alive";
    "Content-Length" = 38;
    "Content-Type" = "text/html";
    Date = "Wed, 29 May 2013 13:42:34 GMT";
    Etag = "\"b1fcde-26-4dc47bfd46880\"";
    "Keep-Alive" = "timeout=5, max=80";
    "Last-Modified" = "Thu, 09 May 2013 11:57:06 GMT";
    Server = "Apache/2.2.14 (Unix) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l PHP/5.3.1 mod_perl/2.0.4 Perl/v5.10.1"; }

If i did that over 3g with T-Mobile I also gat a "Age = X" field in the header.
The problem is now, even if i shut down the service on port 80, that app still says that it's online and the age still counts foreward.
Over Wifi everything works perfectly. When the site is down I got the right status code and the error message. If the site doen't exist I got a 0.
I only have these problems over mobile network.
How can I pass the proxy to get the correct status from the site?


text:
Q: Using MathJax in ClojureScript I want to use MathJax in a ClojureScript program to typeset some math in
a DOM element, not the whole page (which works), just this one particular DOM element. (It's the live preview pane of a Markdown editor that also formats math in the Latex format.)
According to this documentation page on the MathJax site, you can use something
like this in JavaScript.
MathJax.Hub.Queue(["Typeset", MathJax.Hub, latex-node]);

I've been using trial and error and have not gotten it right. Something like this:
(defn typeset-latex
  [latex-node]
  (.Queue js/MathJax.Hub ["TypeSet" (.-Hub js/MathJax) latex-node]))

compiles and does not produce any errors when run, but does not yield any output either.
Using the js* macro to try to reproduce the method on the documentation page:
(js* "MathJax.Hub.Queue([\"TypeSet\", MathJax.Hub, \"mde-preview-id\"]);")

produces an error message in the browser stating that "Error: Can't make callback from given data".
ALSO: Assuming I can get the syntax right to get typesetting working in figwheel, any guidance on how to setup the externs file for use with an optimized build would be appreciated.

A: You're close. I think you just need to make the Clojure vector into a JavaScript list. You can use the #js reader macro:
(defn typeset-latex
  [latex-node]
  (.Queue js/MathJax.Hub #js ["Typeset" (.-Hub js/MathJax) latex-node]))

Here is a line of code in one of my own projects that's equivalent, though it uses slightly different syntax.
Update: change TypeSet to Typeset.

A: I don't know about MathJax, but this template CLJS project has examples of 3 different ways of performing native JS interop from ClojureScript:

*

*https://github.com/cloojure/cljs-template

Looking at the MathJax example:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>MathJax example</title>
  <script type="text/javascript" async
  src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/latest.js?config=TeX-MML-AM_CHTML" async>
</script>
</head>
<body>
<p>
  When \(a \ne 0\), there are two solutions to \(ax^2 + bx + c = 0\) and they are
  $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
</p>
</body>
</html>

it seems straightforward. Can you give an example of what you're trying to do?


text:
Q: Button not put to the right place I use bootstrap 4, thymeleaf and datatable
On top of the table to the right i try to put a button

         <button id="newUsers" type="button" th:onclick="@{/newusers}" class="btn btn-primary" th:text="#{user.new}">Nouveau utilisateur</button>

I used col-sm-12 to take all space

            Id
            Login
            Firstname
            LastName
            Roles

Like you can see, button is not the right
Edit: add code to init table
    $(document).ready(function() {
    var url = "/users";
    $('#usersTable').DataTable({
        "bLengthChange": false, //hide 'show entries dropdown
        'processing': true,
        'serverSide': true,
        'pagingType': 'simple_numbers',
        'ajax': {
            type: 'get',
            'url': url,
            'data': function(d) {
                var current = $('#usersTable').DataTable();
                d.page = (current != undefined) ? current.page.info().page : 0;
                d.size = (current != undefined) ? current.page.info().length : 5;
                d.sort = d.columns[d.order[0].column].data + ',' + d.order[0].dir;
                //return JSON.stringify( d );
            }
        },
        "columns": [{
                "data": "id"
            },
            {
                "data": "username"
            },
            {
                "data": "firstname"
            },
            {
                "data": "lastname"
            },
            {
                "data": "username"
            }
        ]
    });
});

Anyway with proposed solution, buton is not aligner with the text box, will need to check with datatable
Edit 2
to add better integration, this extensions could be an solution
https://datatables.net/extensions/buttons/examples/initialisation/custom.html

A: The float-right should be on the button...

     <button id="newUsers" type="button" class="btn btn-primary float-right">Nouveau utilisateur</button>

A: If you give it 100% width like you said and align it right it should go to the far right of the screen example:

.col-sm-12 {
  width: 100%;
  text-align: right;
}

    <button id="newUsers" type="button" th:onclick="@{/newusers}" class="btn btn-primary" th:text="#{user.new}">Nouveau utilisateur</button>

      Id
      Login
      Firstname
      LastName
      Roles


text:
Q: how can i save data, retrieved from a url into my database I want to save the data of cities retrieved by a url into my sqlite database in django.
i want to store data of all cities for every state of a country.
i want to write a script so that all data can be parsed from the url and get stored into my database.
i have paste a url for a state which has id= 5,
http://lab.iamrohit.in/php_ajax_country_state_city_dropdown/api.php?type=getCities&stateId=5
data showing by this url is
{"status":"success","tp":1,"msg":"Cities fetched successfully.","result":{"448":"Amarpur","449":"Ara","450":"Araria","451":"Areraj","452":"Asarganj","453":"Aurangabad","454":"Bagaha","455":"Bahadurganj","456":"Bairgania","457":"Bakhtiyarpur","458":"Banka","459":"Banmankhi","460":"Bar Bigha","461":"Barauli","462":"Barauni Oil Township","463":"Barh","464":"Barhiya","465":"Bariapur","466":"Baruni","467":"Begusarai","468":"Behea","469":"Belsand","470":"Bettiah","471":"Bhabua","472":"Bhagalpur","473":"Bhimnagar","474":"Bhojpur","475":"Bihar","476":"Bihar Sharif","477":"Bihariganj","478":"Bikramganj","479":"Birpur","480":"Bodh Gaya","481":"Buxar","482":"Chakia","483":"Chanpatia","484":"Chhapra","485":"Chhatapur","486":"Colgong","487":"Dalsingh

this is dictionary type data
i have written this code
def save(self, *args, **kwargs):
        r=requests.get('http://lab.iamrohit.in/php_ajax_country_state_city_dropdown/api.php?type=getCities&stateId=5')
        data=r.json()
        print "data is here",data['stateid']
        super(Country, self).save(*args, **kwargs)

Thanks in advance

A: Because you didn't provide model for city, I wrote it myself:
class State(models.Model):
    name = models.CharField(max_length=255)
    # id from external source, e.g. 5 from your example
    external_id = models.IntegerField()

    def fetch_cities_from_network(self):
        # Fetching data
        resp = requests.get(
            'http://lab.iamrohit.in/php_ajax_country_state_city_dropdown/'
            'api.php?type=getCities&stateId=%d' % self.external_id
        )

        # Get dictionary with cities
        cities_dict = resp.json()['result']

        # Get dictionary values (city names) and save them into the db
        for city in cities_dict.values():
            City.objects.create(state=self, name=city)

class City(models.Model):
    state = models.ForeignKey(State)
    name = models.CharField(max_length=255)

And this is how you can use it:
state = State.objects.create(name='Some state', external_id=5)
state.fetch_cities_from_network()


text:
Q: Regex to remove prefix and suffix in a string Java I want to remove prefix and suffix in a String and extract the middle portion of the string.
For eg: Consider the Strings - "www.hello.com" and "www.test.com"
Here prefix - "www." and suffix - ".com". I want to extract the middle words - hello and test.
Currently i have achieved this using String.replace() method in Java.
str.replace("www.","").replace(".com","");
I want know is there any regular expression available to achieve it in a single method in java.

A: You could use a regex for that, it would work in the same way. Your regex would simply contain a capture group with both the prefix and the suffix in an OR operation.
(www\.|\.com)

You could then use this like you did with the replace.
String test = "www.test.com";
String output = test.replaceAll("(www\\.|\\.com)","")

P.S. this code is untested. Please don't just copy and paste it expecting everything to work.

A: (?<=www.)(.*)(?=.com)
This uses the lookbehind and lookahead feature of regex


text:
Q: mysql select records where begin and end is within 2 business days I have a single table requests

| ID | Opened              | Closed              |
| 1  | 2012-08-21 16:11:22 | 2012-10-31 11:48:58 |
| 2  | 2012-08-15 16:17:19 | 2012-09-18 09:31:32 |

And want to write a query that will check the table for all records that were closed within 2 business days
I was thinking something like
SELECT *
FROM requests
WHERE Closed <= (Opened+TWO BUSINESS DAYS)
But cannot figure out the logic for the TWO BUSINESS DAYS part.

A: I actually found that using a calendar table was best. (As much as I didn't want to)
http://www.brianshowalter.com/calendar_tables has a great tool for doing this!

A: Use Between:
SELECT * FROM requests
WHERE Opened BETWEEN '06-Jan-1999' AND '10-Jan-1999'
AND Closed BETWEEN '06-Jan-1999' AND '10-Jan-1999'
http://www.1keydata.com/es/sql/sql-between.php
http://www.w3schools.com/sql/sql_between.asp

A: I think this is what you mean: You want to select all the records in which the closed date is between the opened date and opened date + 2
    SELECT *
  FROM requests
 WHERE closed BETWEEN opened AND opened + 2


text:
Q: SilverStripe 'None of these templates can be found in theme 'default' I have a widget which has two templates. EligibilityWidget.ss and EligibilityWidget_ShortForm.ss .
I am running this code
public function init() {
    $cookie = (Cookie::get('__utmz'));

    if (isset($cookie)) {
        return $this->renderWith('EligibilityWidget_ShortForm');
    } else {
        return $this->renderWith('EligibilityWidget');
    }
}

This should identify if the cookie exists and render the information with the correct template. However, when I run this I get the error message:

[User Warning] None of these templates can be found in theme
  'default': Widget.ss, DataObject.ss, ViewableData.ss, Object.ss

I have also tried changing a line of code to
return $this->renderWith(array('EligibilityWidget_ShortForm', 'Widget'));

However this also returned the same error. Any help would be appreciated, thank you.


text:
Q: Can I use parameters in django template tag I want to send base template I am extending as a parameter.
Currently, my template first tag is like this
{% extends "rent_base.html" %}

I want it to be like this
{% extends {{base}} %}

Can I achieve it with Django templates?


text:
Q: How to get PR Curves for Tensorflow object detection API? I want to evaluate model of my object detection API by using PR curves? can any one please help me with this?
I used same code
https://www.edureka.co/blog/tensorflow-object-detection-tutorial/
need Precission and recall curves for tensor flow object detection API
build on SSD coco model


text:
Q: Django - Where to write code for easy-thumnails custom THUMBNAIL_NAMER? I am working on a Django project using the wonderful easy-thumbnails plugin to generate thumbnails for images. I don't like how the thumbnails have the format of:
source.jpg.100x100_q80_crop_upscale.jpg
If my image is named source.jpg, I'd much rather have something like:
source_thumb.jpg.
Upon reading the plugin's docs (http://easy-thumbnails.readthedocs.org/en/latest/ref/settings/), I have discovered that there is a setting where I can set a custom THUMBNAIL_NAMER, which is essentially a function that returns the desired thumbnail string.
My Question:
Where is the proper place to define this function in my project? I want to maintain a logical and clean project structure, and am unsure where to place this function.
Thank you so much for any help :)

A: THUMBNAIL_NAMER is a setting, and the default is
THUMBNAIL_NAMER = 'easy_thumbnails.namers.default'

which means, in the easy_thumbnails packages, a method named default in namers.py
Source code: https://github.com/SmileyChris/easy-thumbnails/blob/master/easy_thumbnails/namers.py#L7
So, if you wish to override it, in your settings.py
THUMBNAIL_HELPER = '<myapp>.namers.default'

and then have the overriden definition of this method in the package myapp (any app that is in INSTALLED_APPS that would make most sense), in namers.py (well, it could be anything - just an example)
Since it is the thumbnail, if it is thumbnail associated with user's avatar, I would put it in the userprofile app.


text:
Q: Relationship between switching pattern and the harmonics generated Is there any relationship between the switching pattern of a power converter and the harmonics generated (amplitude & phase) ?
i want to predict the generated harmonics based on the switching pattern.
NB : i need also any kind of documentation about that topic

A: Yes. The switching pattern is the essential factor that determines the amplitude and phase of the harmonic components. The switching pattern determines the waveform of the current and/or voltage produced. The fourier analysis of the waveform provides the amplitudes and phase of the harmonic components. Usually only the amplitude is of interest, so the fourier analysis is simplified to give only the amplitude, but both the amplitude and phase can be obtained. You should be able to find extensive information on fourier analysis. Here is a link a PDF textbook chapter that seems to have the relevant information: LINK
Note that switching pattern is not the only factor. In many situations, the switching pattern determines the voltage waveform, but the voltage waveform must be applied to a complex loop impedance to determine the current waveform.


text:
Q: How to generalize fast matrix multiplication on GPU using numba Lately I've been trying to get into programming for GPUs in Python using the Numba library. I have been reading up on it on their website using the tutorial there and currently I'm stuck on their example, which can be found here: https://numba.pydata.org/numba-doc/latest/cuda/examples.html. I'm attempting to generalize the example for the fast matrix multiplication a bit (which is of the form A*B=C). When testing I noticed that matrices with dimensions that are not perfectly divisible by the number of threads per block (TPB) do not yield a correct answer.
I copied the code below from the example at https://numba.pydata.org/numba-doc/latest/cuda/examples.html and created a very small test case with 4 by 4 matrices. If I choose TPB=2 everything is fine, but when I set TPB=3 it goes wrong. I understand that the code goes out of the bounds of the matrices, but I am unable to prevent this from happening (I tried some if statements on ty + i * TPB and tx + i * TPB, but these did not work.
from numba import cuda, float32
import numpy as np
import math

@cuda.jit
def fast_matmul(A, B, C):
    # Define an array in the shared memory
    # The size and type of the arrays must be known at compile time
    sA = cuda.shared.array(shape=(TPB, TPB), dtype=float32)
    sB = cuda.shared.array(shape=(TPB, TPB), dtype=float32)

    x, y = cuda.grid(2)

    tx = cuda.threadIdx.x
    ty = cuda.threadIdx.y
    bpg = cuda.gridDim.x    # blocks per grid

    if x >= C.shape[0] and y >= C.shape[1]:
        # Quit if (x, y) is outside of valid C boundary
        return

    # Each thread computes one element in the result matrix.
    # The dot product is chunked into dot products of TPB-long vectors.
    tmp = 0.
    for i in range(bpg):
        # Preload data into shared memory
        sA[tx, ty] = A[x, ty + i * TPB]
        sB[tx, ty] = B[tx + i * TPB, y]

        # Wait until all threads finish preloading
        cuda.syncthreads()

        # Computes partial product on the shared memory
        for j in range(TPB):
            tmp += sA[tx, j] * sB[j, ty]

        # Wait until all threads finish computing
        cuda.syncthreads()

    C[x, y] = tmp

#%%

x_h = np.arange(16).reshape([4,4])
y_h = np.ones([4,4])
z_h = np.zeros([4,4])

x_d = cuda.to_device(x_h)
y_d = cuda.to_device(y_h)
z_d = cuda.to_device(z_h)

TPB = 3
threadsperblock = (TPB, TPB)
blockspergrid_x = math.ceil(z_h.shape[0] / threadsperblock[0])
blockspergrid_y = math.ceil(z_h.shape[1] / threadsperblock[1])
blockspergrid = (blockspergrid_x, blockspergrid_y)

fast_matmul[blockspergrid, threadsperblock](x_d, y_d, z_d)
z_h = z_d.copy_to_host()
print(z_h)

I would like to write some code that is not dependent on the matrices A, B, and C having dimensions that are perfectly divisible by the TPB, as these are sometimes out of my control. I understand that GPUs are only faster with matrix multiplication for very large matrices, but I wanted to use small examples to be able to check whether the answer is correct before applying it to actual data.

A: There are arguably at least two errors in that posted code:

*

*This can't possibly be a correct range check:
if x >= C.shape[0] and y >= C.shape[1]:

In order for us to decide that a particular thread in the grid not do any loading activity, we require either that x is out of range or that y is out of range.  The and should have been an or.

*It is illegal to use cuda.syncthreads() in conditional code, if all the threads in the block cannot participate in that statement.  The previous return statement in item 1 above (even if corrected from and to or) pretty much guarantees this illegal behavior for problem sizes not whole-number-divisible by the threadblock size.
Therefore, to fix these issues, we cannot use just a simple return statement for an out-of-bounds thread.  Instead, at the point of load, we must only allow threads to load from global to shared memory, if the computed global load indices (for A or B) are in-bounds (the shared indices are in-bounds, by definition).  Furthermore, when writing a result, we must only write computed results that are in-bounds for C.
The following code has those items fixed.  It seems to work correctly for your given test case:
$ cat t49.py
from numba import cuda, float32
import numpy as np
import math

@cuda.jit
def fast_matmul(A, B, C):
    # Define an array in the shared memory
    # The size and type of the arrays must be known at compile time
    sA = cuda.shared.array(shape=(TPB, TPB), dtype=float32)
    sB = cuda.shared.array(shape=(TPB, TPB), dtype=float32)

    x, y = cuda.grid(2)

    tx = cuda.threadIdx.x
    ty = cuda.threadIdx.y
    bpg = cuda.gridDim.x    # blocks per grid

    # Each thread computes one element in the result matrix.
    # The dot product is chunked into dot products of TPB-long vectors.
    tmp = float32(0.)
    for i in range(bpg):
        # Preload data into shared memory
        sA[tx, ty] = 0
        sB[tx, ty] = 0
        if x < A.shape[0] and (ty+i*TPB) < A.shape[1]:
          sA[tx, ty] = A[x, ty + i * TPB]
        if y < B.shape[1] and (tx+i*TPB) < B.shape[0]:
          sB[tx, ty] = B[tx + i * TPB, y]

        # Wait until all threads finish preloading
        cuda.syncthreads()

        # Computes partial product on the shared memory
        for j in range(TPB):
            tmp += sA[tx, j] * sB[j, ty]

        # Wait until all threads finish computing
        cuda.syncthreads()
    if x < C.shape[0] and y < C.shape[1]:
        C[x, y] = tmp

#%%

x_h = np.arange(16).reshape([4,4])
y_h = np.ones([4,4])
z_h = np.zeros([4,4])

x_d = cuda.to_device(x_h)
y_d = cuda.to_device(y_h)
z_d = cuda.to_device(z_h)

TPB = 3
threadsperblock = (TPB, TPB)
blockspergrid_x = math.ceil(z_h.shape[0] / threadsperblock[0])
blockspergrid_y = math.ceil(z_h.shape[1] / threadsperblock[1])
blockspergrid = (blockspergrid_x, blockspergrid_y)

fast_matmul[blockspergrid, threadsperblock](x_d, y_d, z_d)
z_h = z_d.copy_to_host()
print(z_h)
print(x_h@y_h)
$ cuda-memcheck python t49.py
========= CUDA-MEMCHECK
[[ 6.  6.  6.  6.]
 [22. 22. 22. 22.]
 [38. 38. 38. 38.]
 [54. 54. 54. 54.]]
[[ 6.  6.  6.  6.]
 [22. 22. 22. 22.]
 [38. 38. 38. 38.]
 [54. 54. 54. 54.]]
========= ERROR SUMMARY: 0 errors
$

(Note the use of and here in the bounds tests is correct.  Testing whether a set of indices are in-bound is different in a boolean sense compared to testing whether a set of indices is out-of-bounds.  In the in-bounds test, we require both to be in-bounds.  In the out-of-bounds test, either index out-of-bounds is disqualifying).
I'm not suggesting the above code is defect-free or suitable for any particular purpose.  It is offered to demonstrate possible fixes for the issues I identified.  Getting a shared-memory tiled matrix multiply to work in every imaginable configuration is non-trivial, as you have discovered, and I've not tested it beyond what is shown here.  (For example, if you decided to make TPB larger than 32, you would run into other problems.  Also, the original posted code is advertised only for square matrix multiplication, and this will not work in the general non-square case.)
As noted above, the posted code and the above code with "fixes" will not correctly handle the general non-square case. I believe some straightforward modifications will allow us to handle the non-square case.  In a nutshell, we must size the grid large enough to handle the dimensions of both input matrices, while still only writing results for the in-bounds values of the output matrix.  Here is a lightly tested example:
$ cat t49.py
from numba import cuda, float32
import numpy as np
import math

@cuda.jit
def fast_matmul(A, B, C):
    # Define an array in the shared memory
    # The size and type of the arrays must be known at compile time
    sA = cuda.shared.array(shape=(TPB, TPB), dtype=float32)
    sB = cuda.shared.array(shape=(TPB, TPB), dtype=float32)

    x, y = cuda.grid(2)

    tx = cuda.threadIdx.x
    ty = cuda.threadIdx.y
    bpg = cuda.gridDim.x    # blocks per grid

    # Each thread computes one element in the result matrix.
    # The dot product is chunked into dot products of TPB-long vectors.
    tmp = float32(0.)
    for i in range(bpg):
        # Preload data into shared memory
        sA[ty, tx] = 0
        sB[ty, tx] = 0
        if y < A.shape[0] and (tx+i*TPB) < A.shape[1]:
          sA[ty, tx] = A[y, tx + i * TPB]
        if x < B.shape[1] and (ty+i*TPB) < B.shape[0]:
          sB[ty, tx] = B[ty + i * TPB, x]

        # Wait until all threads finish preloading
        cuda.syncthreads()

        # Computes partial product on the shared memory
        for j in range(TPB):
            tmp += sA[ty, j] * sB[j, tx]

        # Wait until all threads finish computing
        cuda.syncthreads()
    if y < C.shape[0] and x < C.shape[1]:
        C[y, x] = tmp

#%%

x_h = np.arange(115).reshape([5,23])
y_h = np.ones([23,7])
z_h = np.zeros([5,7])

x_d = cuda.to_device(x_h)
y_d = cuda.to_device(y_h)
z_d = cuda.to_device(z_h)

#TPB must be an integer between 1 and 32
TPB = 32
threadsperblock = (TPB, TPB)
grid_y_max = max(x_h.shape[0],y_h.shape[0])
grid_x_max = max(x_h.shape[1],y_h.shape[1])
blockspergrid_x = math.ceil(grid_x_max / threadsperblock[0])
blockspergrid_y = math.ceil(grid_y_max / threadsperblock[1])
blockspergrid = (blockspergrid_x, blockspergrid_y)

fast_matmul[blockspergrid, threadsperblock](x_d, y_d, z_d)
z_h = z_d.copy_to_host()
print(z_h)
print(x_h@y_h)
$ cuda-memcheck python t49.py
========= CUDA-MEMCHECK
[[ 253.  253.  253.  253.  253.  253.  253.]
 [ 782.  782.  782.  782.  782.  782.  782.]
 [1311. 1311. 1311. 1311. 1311. 1311. 1311.]
 [1840. 1840. 1840. 1840. 1840. 1840. 1840.]
 [2369. 2369. 2369. 2369. 2369. 2369. 2369.]]
[[ 253.  253.  253.  253.  253.  253.  253.]
 [ 782.  782.  782.  782.  782.  782.  782.]
 [1311. 1311. 1311. 1311. 1311. 1311. 1311.]
 [1840. 1840. 1840. 1840. 1840. 1840. 1840.]
 [2369. 2369. 2369. 2369. 2369. 2369. 2369.]]
========= ERROR SUMMARY: 0 errors
$

I've also reordered the sense of x and y (and usage of tx and ty) to fix a performance issue in the above code.  The same performance issue was present in the original posted doc code as well.
Again, no claims of defect free. Furthermore I'm sure "more optimal" code could be arrived at.  However optimizing matrix multiplication is an exercise that should fairly quickly lead to using a library implementation.  Using cupy here for the GPU approach should be a fairly straightforward way to tap into a high-quality matrix multiply routine on the GPU.
EDIT: As discussed here OP's code (and, it seems, the doc example) also had a performance issue around the setup of the tmp variable.  Changing that to a proper 32-bit float variable makes an important performance difference.