Q:

Reverse string in C - What am I doing wrong?

I have done the following function to reverse a string:
char* reverseString(char *original_string)
{
    int length = strlen(original_string);
    char *end_of_string = original_string + (length - 1);
    char *reversed_string = malloc(sizeof(char) * length);

    int count = 0;
    int top_limit = length;

    while (count < length) {
        reversed_string[count] = end_of_string[top_limit];
        top_limit--;
        count++;
    }

    return reversed_string;
}

The strategy that I was planning is to put a pointer at the end of the original string and go backwards copying into a new string.  I am not sure what am I doing wrong here, but when doing:
char* prova = "hello";
char* reversed_string;
reversed_string = reverseString(prova);
printf("%d", strlen(reversed_string));

It doesn't show me the correct length, and in compile time I get the following warning:
test.c:46: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘size_t’

A:

You need one char more for the '\0', and also copy it at the end:
char* reverseString(char *original_string)
{
    int length = strlen(original_string);
    int top_limit = length-1;
    //char *end_of_string = original_string + top_limit;
    char *reversed_string = malloc(sizeof(char) * (1+length));

    int count = 0;

    while (count < length) {
        reversed_string[count] = original_string[top_limit];
      //reversed_string[count] = *(end_of_string--) ;
        top_limit--;
        count++;
    }
    reversed_string[count] = '\0';
    return reversed_string;
}

A:

The type returned by strlen is size_t, which is an unsigned type. Using %d format to print it is in an undefined behavior. You can either use %zu in C99, or use %u and cast to unsigned int in C89.
#include <string.h>

/* C89 */ printf("%u\n", (unsigned int)strlen(reversed_string));
/* C99 */ printf("%zu\n", strlen(reversed_string));

C11 (n1570), § 7.19 Common definitions <stddef.h>
size_t, which is the unsigned integer type of the result of the sizeof operator [...].

Your algorithm is also wrong, because you use both end_of_string and top_limit. You should choose one of the two solutions.
#include <string.h>

char *reverseString(char *original_string)
{
    size_t length = strlen(original_string);
    char *reversed_string = malloc(length + 1);
    size_t start;
    size_t end;

    for (start = 0, end = length - 1; start < length; start++, end--)
    {
      reversed_string[start] = original_string[end];
    }

    reversed_string[start] = '\0';

    return reversed_string;
}


Q:

Why is my XSLT formatting not working correctly in Microsoft Edge on the Windows 10 OS?

I have been working on a webpage developed in a CMS through a combination of XSLT 1.0, JS and XML and have come across a page rendering problem specifically when accessing the (ASP.NET) webpage on the Windows 10 operating system through the Microsoft Edge (37.14316.1000.0) browser (Microsoft EdgeHTML 14.14316).
The Problem:

(Screenshot Captured from a Virtual Machine, using the before-mentioned conditions)
As you can clearly see, when you access my webpage using the before-mentioned conditions, the course page structure is broken up. It appears as though my XSLT file isn't being executed properly and a conflict is going on somewhere? This is majorly frustrating as the XSLT/JS/XML page works perfectly in all the previous Internet Explorer browser versions (all the way down to 7) plus the other leading modern browsers such as Chrome, Firefox, Opera and Safari.
Maddeningly, the page actually works on Windows 10 version 10.0.10240 Build 10240 Edge 20.10240.16384.0, but I believe this was the previous Edge browser release, so somewhere between the last browser version and this one, this rendering problem has suddenly surfaced?
The JS file which calls my XSLT/XML files using the XSLT/XML on the Client method is obviously working, as data is appearing within the page, but something is not right and I'm struggling to identify what is causing the issue?
I have tried playing about with the main CSS file but have ruled this out as the underlying cause.
Interestingly when going into the source code of my page through the in-built Edge development tools, I managed to identify that if I removed the form1 reference on line 55, just inside the opening <body> tag (i.e. <form method="post" action="/aatp/courses/crops/resource-capture-by-crops.aspx" id="form1">), the page instantly fixes itself and renders out properly, as experienced on all the other internet browsers.

Crazy??
Perhaps this POST <form1> call is in direct conflict with the GET request made by my JS file? The form1 call is a consequence of our CMS architecture, since our web pages are effectively one big form, so I can't get rid of this 'CMS produced code'.
Any suggestions or ideas for a fix would be greatly appreciated and welcomed!

A:

Try to convince Edge that the stylesheet creates HTML elements by putting <xsl:output method="html"/> into your XSLT stylesheet.


Q:

When should I consider using Plastic Round Cap Roofing Nails?

I'm getting ready to shingle a roof for a shed/outdoor office and I'm confused on if/when I should use plastic round cap roofing nails:

I haven't seen these used in any instructions (including the instructions that came with my shingles) or videos.  Are these nails a gimmick?  Or are there clear advantages to using them?

A:

Those nails are used only for holding down the roofing underlayment. They excel at doing so whether it be old school tar paper, or the newer more durable, hi tech roof underlayments.


Q:

Is there a limit on the size of image drawable in android?

I am trying to load a 3MB image using getDrawable() for testing purposes, but I get an out of memory leak exception. Is there any limit on the size of image drawable you can use in android ?
java.lang.OutOfMemoryError
            at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
            at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:594)
            at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:429)
            at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:840)
            at android.content.res.Resources.loadDrawable(Resources.java:2113)
            at android.content.res.Resources.getDrawable(Resources.java:700)
            at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:321)
            at com.testleak.MainActivity.onCreate(MainActivity.java:22)
            at android.app.Activity.performCreate(Activity.java:5248)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
            at android.app.ActivityThread.access$800(ActivityThread.java:139)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5097)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)

A:

Is there any limit on the size of image drawable you can use in android ?

Yes. It has to fit in available memory when decoded. A 3MB PNG or JPEG file will be much larger when decoded, as the decoded memory usage is width x height x 4 bytes/pixel.
"Available memory" depends on:

The heap limit imposed by your device, based on installed system RAM (see ActivityManager and getMemoryClass())
The largest single block of free memory within your heap, which will depend on a lot of factors at runtime


Q:

After Effects - images get corrupted / ruined picture

As shown in the picture, the image got corrupted: flipped vertically, and damaged...
Sometimes I get just a black picture, sometimes other image distortions.

A:

I don't know why it happened, but I've found out what causes it -
it's the frame blending interpolation, which was set to pixel-motion.


Q:

How can I set campaign with Google Analytics using setCampaignParamsFromUrl()

Update
This was caused by a bug that Google have fixed in "Release Version 4.5 - Google Play Services 7.3 (May 1, 2015)". When using Google Play Services 7.3 or later it should be possible to call setCampaignParametersFromUrl() with a full URL as expected.

Original question
I'm using Google Analytics V4 in my Android app. On startup I send a screen view hit to Google Analytics and I set the campaign parameters on my HitBuilders.ScreenViewBuilder by calling setCampaignParamsFromUrl() like this:
String url = "http://example.com/?referrer=utm_source%3Down-build%26utm_campaign%3Dinternal-testing";
builder.setCampaignParamsFromUrl(url);

It seems like this is working because I can see that the campaign is included in the logs from Google Analytics:
V/GAV4﹕ Thread[GAThread,5,main]: Sending hit to service ...,  cn=internal-testing...

However when I'm looking at my data at the Google Analytics web interface the next day this campaign does not show up. I only have users with campaign "(not set)".
I've uninstalled my app, cleared the advertising id and re-installed the app and I see this installation as a new user in the Google Analytics web interface so I know the data is sent there. But the campaign I use does not show up.
Am I using setCampaignParamsFromUrl() wrongly or have I missed something else? Do I have to configure the campaigns I have somewhere or should Google Analytics pick up values it hasn't seen before as new campaigns automatically?
(As for why I'm not listening to the install referrer event see: What is the scope of the utm_campaign dimension in Google Analytics v4 on Android?)

A:

Update: issue 596 have been fixed by Google, it is now possible to call setCampaignParamsFromUrl() with a URL when using the latest version of Google Play Services (7.3 released May 1st 2015)
After some testing I managed to figure out what is going on and exactly what format the URL passed to setCampaignParamsFromUrl() should have.
TL;DR: Generate an URL using the Google Play URL Builder, but pass only the referrer string (part after referrer=) to setCampaignParamsFromUrl().
When setCampaignParamsFromUrl() is called it starts by taking everything after the '?' and splitting it on each '&' to get a list of all parameters it should send to GA.
For each parameter it then splits on '=' and takes the first substring as parameter and the second as value for that parameter.
Normally this works good, but it does not work for URLs generated by the Google Play URL builder. After un-escaping the parameter string of the URL used in the original question we get the string:
referrer=utm_source=own-build&utm_campaign=internal-testing

After splitting on '&' we get the following two strings
1. referrer=utm_source=own-build
2. utm_campaign=internal-testing

The second can be handled nicely where utm_campaign gets assigned the value "internal-testing", but the first is problematic. There we get the parameter referrer with the value "utm_source". Since referrer is not a valid campaign parameter it is not reported to GA, and since utm_source is a required parameter GA will treat this campaign data as invalid and ignore all the other parameters reported at the same time.
So to get setCampaignParamsFromUrl() to work you can pass in only the referrer string, that is everything after referrer= in the URL generated by the Google Play URL Builder. So the URL used in the original question should be
utm_source%3Down-build%26utm_campaign%3Dinternal-testing

The package name that is part of the URL generated by the URL builder is not needed at all since the GA SDK picks up the package automatically.
Since this behavior feels like a bug to me this has been reported as issue 596 in the GA bug tracker.


Q:

Ordering the Counter keys by month

So I have an answer that looks like:
Counter({'APR': 76, 'MAR': 67, 'MAY': 51, 'JUN': 28, 'FEB': 17, 'JAN': 4, 'JUL': 3, 'DEC': 1, 'AUG': 1})

but would like it to be in month order including months with 0 counts:
Counter({'JAN': 4, 'FEB': 17, 'MAR': 67, 'APR': 76, 'MAY': 51, 'JUN': 28, 'JUL': 3, 'AUG': 1, 'SEP': 0, 'OCT': 0, 'NOV': 0, 'DEC': 1})

My project imports a .csv file with a list of values (there are about 1400 but here are a few examples) and returns how many times the month occurs:
year,month,age,sex
2013,JUN,20,M
2011,MAR,29,F
2011,JUL,26,M
2011,APR,20,M

and my current code looks like this (I'm just seeing what year10 returns for now)
def parse_data(filename):
    with open('case_list.csv', 'r') as f:
        temp_read = csv.reader(f)
        month = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
        year = ['2010', '2011', '2012', '2013', '2014']
        read, year10, year11, year12, year13, year14 = [], [], [], [], [], []
        for i in temp_read:
            if i[0] in year and i[1] in month:
                read.append(i[0:2])
        for j in read:
            if j[0].startswith('2010'):
                year10.append(j[1])
            if j[0].startswith('2011'):
                year11.append(j[1])
            if j[0].startswith('2012'):
                year12.append(j[1])
            if j[0].startswith('2013'):
                year13.append(j[1])
            if j[0].startswith('2014'):
                year14.append(j[1])
        return Counter(year10)

Question for context:
You can assume that the file is correctly formatted (ie, begins with a header row as in the above example).
You can assume that each record is correctly formatted, but your function should only count valid records. A valid record is a record that has valid values for year and month.
Valid years are : 2010, 2011, 2012, 2013, 2014
Valid months are: JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
Invalid records should be ignored

A:

Unfortunately, Counter objects do not maintain order. However, OrderedDicts do. You can convert you Counter into an OrderedDict using a generator comprehension and passing it to the constructor.
month = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN',
         'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']

o = OrderedDict((m, c[m]) for m in month if c[m] > 0)
print(o)
OrderedDict([('JAN', 4),
             ('FEB', 17),
             ('MAR', 67),
             ('APR', 76),
             ('MAY', 51),
             ('JUN', 28),
             ('JUL', 3),
             ('AUG', 1),
             ('DEC', 1)])

I've added a condition to ignore months for which counts are 0. If you want those, your code simplifies with the use of a map:
o = OrderedDict(map(lambda m: (m, c[m]), month))
print(o)
OrderedDict([('JAN', 4),
             ('FEB', 17),
             ('MAR', 67),
             ('APR', 76),
             ('MAY', 51),
             ('JUN', 28),
             ('JUL', 3),
             ('AUG', 1),
             ('SEP', 0),
             ('OCT', 0),
             ('NOV', 0),
             ('DEC', 1)])


Q:

Applying languages / locale selectively: is it possible?

I am a Dutch user and prefer the my local date & time format, system wide. I have no trouble speaking or understanding English and find it very useful to have the rest of my system configured in English to make my life easier when I need to Google a term, for example.
Is it possible to apply the a local date/time/currency/etc. format to the system, while maintaining English menu & dialog captions?

A:

Abolutely,

go to System → Administration → Language Support
at Language, select English as your default language:

And in the Text tab, choose Dutch as your preffered Locale for numbers, dates and currency.

I've been using this setting for a long time, and it's a bit weird sometimes, you may see something like "This file was modified on Maandag...", but it works very well with most apps.
After a bit of troubleshooting, it turns out you also have to:

Click 'Apply System-Wide'
Reboot


Q:

Reduce not making full use of list of assumptions?

I have the following inequality, with conditions:
Reduce[
  {-(a + b) > Sqrt[(a + b)^2 - 4 (a b - c d)],
  Element[{a, b, c, d}, Reals], a + b < 0,
  a b - c d > 0, (a + b)^2 > 4 (a b - c d)},
  {a, b}
  ]

However, the very first line of the output gives c ∈ Reals && .... In itself, it is rather inconsequential, but it made me wonder if Mathematica doesn't make full use of the given conditions? Another pointer in this direction is that if I remove all the conditions, the output is actually slightly shorter, which doesn't make sense to me.
What is going on here? Thanks.

A:

What I believe is the issue here is what a statement in your Reduce like c ∈ Reals actually means. You say it's a condition (and I feel you mean assumption), I say it's an expression, a Boolean expression. An expression like x>0 doesn't state that x is greater than 0. It's an undetermined claim about x that is True when x is indeed greater than 0, and False if it is not.
So, as long the truth cannot be determined, the output is the expression itself:
Reduce[x > 0, {x}]
(* x > 0 *)

and
Reduce[x > 0, {x}] /. x -> 5
(* True *)

Similarly,
Reduce[x ∈ Reals, x]
(* x ∈ Reals *)

and
Reduce[x ∈ Reals, x] /. x -> 5
(* True *)

In inequalities Reduce automatically assumes the variables to be Real. It reduces them to the minimum set of expressions that have the same Boolean value. Compare:
Reduce[a > 0, {a}]
(* a > 0 *)

Reduce[a + b > 0, {a, b}]
(* a ∈ Reals && b > -a *)

Reduce[a + b + c > 0, {a, b, c}]
(* (a | b) ∈ Reals && c > -a - b *)

In your case, most of the generated Boolean conditions that must hold for your expression to be true contain inequalities that already imply that the variables contained in them must be real. c is an exception:
Reduce[{
   -(a + b) > Sqrt[(a + b)^2 - 4 (a b - c d)],
   (a | b | c | d) ∈ Reals,
   a + b < 0, a b - c d > 0,
   (a + b)^2 > 4 (a b - c d)},
   {a, b}
] // LogicalExpand // Reduce

In the yellow expressions you see no inequality containing c, so its status as real must be made explicit.
Your expression could be better written using a domain specification at the end as:
Reduce[{
  -(a + b) > Sqrt[(a + b)^2 - 4 (a b - c d)],
  a + b < 0,
  a b - c d > 0,
  (a + b)^2 > 4 (a b - c d)},
  {a, b}, Reals
]

A:

Try this:
FullSimplify[
 Reduce[Assuming[
   a + b < 0 && a b - c d > 0 && (a + b)^2 > 4 (a b - c d), -(a + b) >
     Sqrt[(a + b)^2 - 4 (a b - c d)]], {a, b}, Reals]]


Q:

Behavior of "round" function in Python

Could anyone explain me this pice of code:
>>> round(0.45, 1)
0.5
>>> round(1.45, 1)
1.4
>>> round(2.45, 1)
2.5
>>> round(3.45, 1)
3.5
>>> round(4.45, 1)
4.5
>>> round(5.45, 1)
5.5
>>> round(6.45, 1)
6.5
>>> round(7.45, 1)
7.5
>>> round(8.45, 1)
8.4
>>> round(9.45, 1)
9.4

Updated
I guess it is because of floating representation. Am I right?

A:

You are right. None of the numbers can be represented exactly. In some cases the fractional part is strictly greater than 0.45 and in some it is strictly less:
In [4]: ['%.20f' % val for val in (0.45, 1.45, 2.45, 3.45, 4.45, 5.45, 6.45, 7.45, 8.45, 9.45)]
Out[4]:
['0.45000000000000001110',
 '1.44999999999999995559',
 '2.45000000000000017764',
 '3.45000000000000017764',
 '4.45000000000000017764',
 '5.45000000000000017764',
 '6.45000000000000017764',
 '7.45000000000000017764',
 '8.44999999999999928946',
 '9.44999999999999928946']

This explains the seemingly inconsistent rounding.


Q:

Unique Customers with Duplicate Order Numbers

It seems a dataset I've been given has multiple customer IDs with the same Order Numbers.  How would I go about identifying those customer who have been effected?
I did try the usual but then realised some Order Numbers are duplicated but with the same Cus ID?
SELECT Cus ID, Ord Num, COUNT(*)
FROM OUTPUT
GROUP BY Cus ID, Order Num, Amount
HAVING COUNT(*) > 1

A:

You can find the orders using a subquery:
  SELECT OrdNum, COUNT(DISTINCT CustId)
  FROM OUTPUT
  GROUP BY OrdNum
  HAVING COUNT(DISTINCT CustId) > 1

You can get the details by joining the information back in:
SELECT o.*
FROM (SELECT OrdNum, COUNT(DISTINCT CustId)
      FROM OUTPUT
      GROUP BY OrdNum
      HAVING COUNT(DISTINCT CustId) > 1
     ) as oc INNER JOIN
     OUTPUT as o
     on oc.OrdNum = o.OrdNum

EDIT:
In Access, you can do:
SELECT o.*
FROM (SELECT OrdNum
      FROM OUTPUT
      GROUP BY OrdNum
      HAVING MIN(CustId) <> MAX(CustId)
     ) as oc INNER JOIN
     OUTPUT as o
     on oc.OrdNum = o.OrdNum;


Q:

Video tag throwing off css-grid layout

So I have a snippet demonstrating the layout of a page I'm creating using CSS grid. In the first example, I have the grid exactly as I want it. In the second example, I have the exact same layout, but I've included a video in the "promo" cell. But adding the video throws out the grid layout.  Note how in the first example, the "promo" cell and the "login" cell are divided 50 50 - that's what I want. But in the seconds example, the video makes the "promo" cell wider than the "login" cell. In fact, it appears that the video is being interpreted as being its own cell in the row. What I want is to have the "promo" cell take up 50% with the video content, and for the "login" cell to remain 50%. Any help with this would be appreciated.

.gridWrap {
  display: grid;
  grid-template-areas: 'header header''promo login''footer footer';
  grid-template-rows: 40% auto 10%;
  grid-gap: 10px;
  min-height: 100vh;
}

.header {
  background-color: indianred;
  grid-area: header;
}

.promo {
  background-color: aquamarine;
  grid-area: promo;
}

.login {
  background-color: coral;
  grid-area: login;
}

.footer {
  background-color: teal;
  grid-area: footer;
}

First example

Second example

    <video autoplay muted loop width="178px" height="100px">
     <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
     Your browser does not support HTML5 video.
    </video>

A:

You need to add grid-auto-columns: 1fr; to class .gridWrap
Here is the updated snippet:

.gridWrap {
  display: grid;
  grid-template-areas: 'header header''promo login''footer footer';
  grid-template-rows: 40% auto 10%;
  grid-gap: 10px;
  min-height: 100vh;
  grid-auto-columns: 1fr;
}

.header {
  background-color: indianred;
  grid-area: header;
}

.promo {
  background-color: aquamarine;
  grid-area: promo;
}

.login {
  background-color: coral;
  grid-area: login;
}

.footer {
  background-color: teal;
  grid-area: footer;
}

</style>

First example

Second example

    <video autoplay muted loop width="178px" height="100px">
     <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
     Your browser does not support HTML5 video.
    </video>


Q:

Correct order for closing various JDBC objects

I have the following code sample:
try {
    conn = this.jdbcTemplate.getDataSource().getConnection();
    stm = conn.prepareCall("{? =" + query + "}");
    stm.registerOutParameter(1, OracleTypes.CURSOR);
    if (params != null) {
        for (int i = 0; i < params.length; i++)
            stm.setString(i + 2, params[i]);
    }
    //getting result set from cursor
    stm.execute();
    res = (ResultSet) stm.getObject(1);
    return DatabaseLayerUtils.getResultSetData(res);
} finally {
    //closing cursor
    if (res != null) res.close();
    if (stm != null) stm.close();
    if (conn != null) conn.close();
}

Is the elements order in finally section important or not?
Is the following code:
 if (res != null) res.close();
 if (stm != null) stm.close();

equal to:
 if (stm != null) stm.close();
 if (res != null) res.close();

or not?
In a project being worked on by my colleague there are a lot of constructions like:
 if (stm != null) stm.close();
 if (res != null) res.close();

I need to understand if this is the right syntax or if I need to fix as shown:
 if (res != null) res.close();
 if (stm != null) stm.close();

Thanks.

A:

You do not need to explicitly close ResultSet and Statement if you close Connection. From what I know all JDBC drivers handle this properly now.
If you want to explicitly close them in a row then you need to close them in the reverse order of creation: ResultSet, Statement, Connection.
Also you need to wrap each close into try/catch, since they throw an exception as far as I remember.
Better, if you have some utlity class with close(ResultSet rs), close(Statement stmnt) and close(Connection cnn) methods.
UPD
There is one more new (two years old already, heh) method to close JDBC (not limited to JDBC) stuff now.
Java7 introduces new feature called "try-with-resources" http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
The tutorial (link above) is quite self-explanatory so I think noticing this feature is enough for now.
For the JDBC resources purpose, you can register Statement in try-with-resources and skip closing ResultSet (declare it as usual after try .. {) because that will happen automatically as I described in the first part.


Q:

How can I draw a rectangle that has a single concave face?

I wanted to draw this using Photoshop:

However as you can see the dark green rectangle is not a perfect rectangle. It's rounded at the bottom but I don't know how to do this.

I drew a normal rectangle then subtracted an ellipse from it, but I wanted to know if that's the correct way to do things or not... Subtracting forms with Photoshop CS6 isn't precise, or I used it wrong. I looked on the web and didn't find anything.

A:

Use the rectangle tool U.
Draw the shape.  Get the pen tool out and "add anchor point tool" under the pen tool options P.
Place it in the bottom center of the rectangle.
Get the direct selection tool A and click on the new anchor point and drag upwards.


Q:

How to draw grid lines that scale?

I have a canvas, and I want to give it grid lines as a background, but I want there to be a constant number of grid lines that divide the canvas into equally-sized sections, rather than just have equally-spaced grid-lines. I want this to be preserved when the canvas is resized by the user.
How should I do this?

A:

Here is a solution which is based in two wpf ListView controls behind the canvas(one for rows and second for columns). The content of the columns related ListView control is a rectangle.
Updated version - Managed Grid Lines Control. Here you can manage the number of grid lines and their visibility.
Xaml code - grid lines control:
<UserControl x:Class="CAnvasWithGrid.GridLineControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:canvasWithGrid="clr-namespace:CAnvasWithGrid"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300" x:Name="This">

<Grid x:Name="LayoutRoot">
    <Grid.Resources>
        <Style TargetType="ListView">
            <Setter Property="Background" Value="Transparent"/>
        </Style>
        <Style x:Key="ListViewItemStyle" TargetType="ListViewItem">
            <Setter Property="Background" Value="Transparent"/>
        </Style>
        <DataTemplate x:Key="InnerListviewDataTemplate" DataType="{x:Type canvasWithGrid:CellModel}">
            <Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
                       Margin="0" StrokeDashArray="4" Stroke="Black" StrokeThickness="0.5" Fill="Transparent"/>
        </DataTemplate>
        <DataTemplate x:Key="ListviewDataTemplate" DataType="{x:Type canvasWithGrid:RowModel}">
            <ListView ItemsSource="{Binding CellModels}" BorderBrush="#00FFFFFF" BorderThickness="0" Margin="0"
                                      HorizontalContentAlignment="Stretch"
                                      VerticalContentAlignment="Stretch"
                                      VerticalAlignment="Stretch"
                                      HorizontalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Hidden" ScrollViewer.VerticalScrollBarVisibility="Hidden">
                <ListView.ItemsPanel>
                    <ItemsPanelTemplate>
                        <UniformGrid Columns="{Binding CellModels, Converter={canvasWithGrid:CollectionLength2NumberConverter}}"></UniformGrid>
                    </ItemsPanelTemplate>
                </ListView.ItemsPanel>
                <ListView.ItemContainerStyle>
                    <Style TargetType="ListViewItem" BasedOn="{StaticResource ListViewItemStyle}">
                        <Setter Property="Margin" Value="0"></Setter>
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="ListViewItem">
                                    <ContentPresenter Content="{TemplateBinding Content}" Margin="0"
                                              ContentTemplate="{StaticResource InnerListviewDataTemplate}" />
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                        <Setter Property="ContentTemplate" Value="{StaticResource InnerListviewDataTemplate}"/>
                    </Style>
                </ListView.ItemContainerStyle>
            </ListView>
        </DataTemplate>
    </Grid.Resources>
    <ListView ItemsSource="{Binding ElementName=This, Path=RowModels}" ScrollViewer.HorizontalScrollBarVisibility="Hidden" ScrollViewer.VerticalScrollBarVisibility="Hidden">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Rows="{Binding ElementName=This, Path=RowModels, Converter={canvasWithGrid:CollectionLength2NumberConverter}}"/>
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem" BasedOn="{StaticResource ListViewItemStyle}">
                <Setter Property="Margin" Value="0"></Setter>
                <Setter Property="HorizontalAlignment" Value="Stretch"/>
                <Setter Property="VerticalAlignment" Value="Stretch"/>
                <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                <Setter Property="VerticalContentAlignment" Value="Stretch"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListViewItem">
                            <ContentPresenter Content="{TemplateBinding Content}" Margin="-1"
                                              ContentTemplate="{StaticResource ListviewDataTemplate}" />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Setter Property="ContentTemplate" Value="{StaticResource ListviewDataTemplate}"/>
            </Style>
        </ListView.ItemContainerStyle>
    </ListView>
</Grid>

Grid lines control - code behind
    /// <summary>
/// Interaction logic for GridLineControl.xaml
/// </summary>
public partial class GridLineControl : UserControl
{
    public GridLineControl()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty NumberOfColumnsProperty = DependencyProperty.Register(
        "NumberOfColumns", typeof (int), typeof (GridLineControl), new PropertyMetadata(default(int), NumberOfColumnsChangedCallback));

    private static void NumberOfColumnsChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
    {
        var numberOfRows = (int)dependencyObject.GetValue(NumberOfRowsProperty);
        var numberOfColumns = (int)args.NewValue;
        if (numberOfColumns == 0 || numberOfRows == 0) return;
        var rowModelsCollection = GetRowModelsCollection(numberOfRows, numberOfColumns);
        dependencyObject.SetValue(RowModelsProperty, rowModelsCollection);
    }

    public int NumberOfColumns
    {
        get { return (int) GetValue(NumberOfColumnsProperty); }
        set { SetValue(NumberOfColumnsProperty, value); }
    }

    public static readonly DependencyProperty NumberOfRowsProperty = DependencyProperty.Register(
        "NumberOfRows", typeof (int), typeof (GridLineControl), new PropertyMetadata(default(int), NumberOfRowsChangedCallback));

    private static void NumberOfRowsChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
    {
        var numberOfRows = (int)args.NewValue;
        var numberOfColumns = (int)dependencyObject.GetValue(NumberOfColumnsProperty);
        if(numberOfColumns == 0 || numberOfRows == 0) return;
        var rowModelsCollection = GetRowModelsCollection(numberOfRows, numberOfColumns);
        dependencyObject.SetValue(RowModelsProperty, rowModelsCollection);
    }

    private static ObservableCollection<RowModel> GetRowModelsCollection(int numberOfRows, int numberOfColumns)
    {
        var rowModelsCollection = new ObservableCollection<RowModel>();
        for (var i = 0; i < numberOfRows; i++)
        {
            rowModelsCollection.Add(new RowModel(numberOfColumns) {Position = (i + 1).ToString()});
        }
        return rowModelsCollection;
    }

    public int NumberOfRows
    {
        get { return (int) GetValue(NumberOfRowsProperty); }
        set { SetValue(NumberOfRowsProperty, value); }
    }

    public static readonly DependencyProperty RowModelsProperty = DependencyProperty.Register("RowModels",
        typeof(ObservableCollection<RowModel>), typeof(GridLineControl),
        new PropertyMetadata(default(ObservableCollection<RowModel>)));

    public ObservableCollection<RowModel> RowModels
    {
        get { return (ObservableCollection<RowModel>)GetValue(RowModelsProperty); }
        private set { SetValue(RowModelsProperty, value); }
    }
}

Models:
public class RowModel:BaseGridMember
{
    public RowModel(int numberOfCellsInRow)
    {
        CellModels = new ObservableCollection<CellModel>();
        for (int i = 0; i < numberOfCellsInRow; i++)
        {
            CellModels.Add(new CellModel{Position = (i+1).ToString()});
        }
    }
    public ObservableCollection<CellModel>  CellModels { get; set; }
}

public class CellModel:BaseGridMember
{

}

public class BaseGridMember:BaseObservableObject
{
    private string _position;

    public string Position
    {
        get { return _position; }
        set
        {
            _position = value;
            OnPropertyChanged();
        }
    }
}

Main window xaml code - as you can see here is a ImageContol instead of Canvas but you can replace it:
<Window x:Class="CAnvasWithGrid.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:canvasWithGrid="clr-namespace:CAnvasWithGrid"
    Title="MainWindow" Height="525" Width="525" x:Name="This">

<Grid Tag="{Binding ElementName=This}">
    <Grid.Resources>
        <BooleanToVisibilityConverter x:Key="Bool2VisConvKey" />
    </Grid.Resources>
    <Grid.ContextMenu>
        <ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
            <MenuItem Header="Show Grid Lines" Command="{Binding ShowGridLinesCommand}"/>
        </ContextMenu>
    </Grid.ContextMenu>
    <Image Source="Resources/Koala.jpg" Stretch="Uniform" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MouseDown="UIElement_OnMouseDown"/>
    <canvasWithGrid:GridLineControl NumberOfRows="50" NumberOfColumns="50"
                                    IsHitTestVisible="False" Visibility="{Binding ElementName=This, Path=AreGridLineVisible, Converter={StaticResource Bool2VisConvKey}, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>

Main window code behind:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        ShowGridLinesCommand = new RelayCommand(ShowGridLineManageCommand);
        AreGridLineVisible = true;
    }

    private void ShowGridLineManageCommand()
    {
        AreGridLineVisible = !AreGridLineVisible;
    }

    public static readonly DependencyProperty AreGridLineVisibleProperty = DependencyProperty.Register(
        "AreGridLineVisible", typeof (bool), typeof (MainWindow), new PropertyMetadata(default(bool)));

    public bool AreGridLineVisible
    {
        get { return (bool) GetValue(AreGridLineVisibleProperty); }
        set { SetValue(AreGridLineVisibleProperty, value); }
    }

    public static readonly DependencyProperty ShowGridLinesCommandProperty = DependencyProperty.Register(
        "ShowGridLinesCommand", typeof (ICommand), typeof (MainWindow), new PropertyMetadata(default(ICommand)));

    public ICommand ShowGridLinesCommand
    {
        get { return (ICommand) GetValue(ShowGridLinesCommandProperty); }
        set { SetValue(ShowGridLinesCommandProperty, value); }
    }

    private void UIElement_OnMouseDown(object sender, MouseButtonEventArgs e)
    {

    }
}

How it looks like:


Q:

users disappear from options menu when given uids under 1000

I wanted to stop particular user names appearing in the list of names at the log in screen. I remembered reading that this could be achieved by changing the user id of the account to something less than 1000 (I think I made it 990). So I did this. That worked fine, but now when I wanted to change it back, the name is not appearing in the list of user accounts in the users and groups menu under administration.
How do I modify the phantom account?

A:

You can change the userid with sudo usermod -u <new id> <username>.
Btw: to hide users from log in screen: How to hide users from the GDM login screen?

A:

gdm uses UID_MIN from /etc/login.defs to determine which user IDs are system users and which are regular users. If you adjust it to match your system's user range, gdm will show them at the login screen again.
For example, since users on my network have their uid start at 500, I changed /etc/login.defs so they could log in:
$ grep UID_MIN /etc/login.defs
UID_MIN          500


Q:

How do I create a non-recursive calculation of factorial using iterators and ranges?

I ran into a Rustlings exercise that keeps bugging me:
pub fn factorial(num: u64) -> u64 {
    // Complete this function to return factorial of num
    // Do not use:
    // - return
    // For extra fun don't use:
    // - imperative style loops (for, while)
    // - additional variables
    // For the most fun don't use:
    // - recursion
    // Execute `rustlings hint iterators4` for hints.
}

A hint to solution tells me...

In an imperative language you might write a for loop to iterate
  through multiply the values into a mutable variable. Or you might
  write code more functionally with recursion and a match clause. But
  you can also use ranges and iterators to solve this in rust.

I tried this approach, but I am missing something:
if num > 1 {
    (2..=num).map(|n| n * ( n - 1 ) ??? ).???
} else {
    1
}

Do I have to use something like .take_while instead of if?

A:

The factorial is defined as the product of all the numbers from a starting number down to 1. We use that definition and Iterator::product:
fn factorial(num: u64) -> u64 {
    (1..=num).product()
}

If you look at the implementation of Product for the integers, you'll see that it uses Iterator::fold under the hood:

impl Product for $a {
    fn product<I: Iterator<Item=Self>>(iter: I) -> Self {
        iter.fold($one, Mul::mul)
    }
}

You could hard-code this yourself:
fn factorial(num: u64) -> u64 {
    (1..=num).fold(1, |acc, v| acc * v)
}

See also:

How to sum the values in an array, slice, or Vec in Rust?
How do I sum a vector using fold?


Q:

How can I get a total count of a model's related objects and the model's children's related objects?

In Django, I've got a Checkout model, which is a ticket for somebody checking out equipment. I've also got an OrganizationalUnit model that the Checkout model relates to (via ForeignKey), as the person on the checkout belongs to an OrganizationalUnit on our campus.
The OrganizationalUnit has a self relation, so several OUs can be the children of a certain OU, and those children can have children, and so on. Here are the models, somewhat simplified.
class OrganizationalUnit(models.Model):
    name = models.CharField(max_length=100)
    parent = models.ForeignKey(
        'self',
        blank=True, null=True,
        related_name='children',
)

class Checkout(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    department = models.ForeignKey(
        OrganizationalUnit,
        null=True,
        blank=True,
        related_name='checkouts',
)

I want to get a count of the Checkouts that are related to a certain OrganizationalUnit and all of its children. I know how to get the count of all the checkouts that are related to an OU.
ou = OrganizationalUnit.objects.get(pk=1)
count = ou.checkouts.all().count()

But how do I make that count reflect the checkouts of this OU's children and their children? Do I use some sort of iterative loop?

EDIT: I guess I still can't quite wrap my head around the while command to do this. The organizational units can go as deep as the user wants to nest them, but right now the most it goes in the DB is 5 deep. I've written this…
for kid in ou.children.all():
    child_checkout_count += kid.checkouts.all().count()
    for kid2 in kid.children.all():
        child_checkout_count += kid2.checkouts.all().count()
        for kid3 in kid2.children.all():
            child_checkout_count += kid3.checkouts.all().count()
            for kid4 in kid3.children.all():
                child_checkout_count += kid4.checkouts.all().count()
                for kid5 in kid4.children.all():
                    child_checkout_count += kid5.checkouts.all().count()

…which is total crap. And it takes a while to run because it pretty much traverses a major chunk of the database. Help! (I can't seem to think very well today.)

A:

What you need is a recursive function that traverse OrganizationalUnit relation tree and gets number of related Checkouts for each OrganizationalUnit. So your code will look like this:
def count_checkouts(ou):
   checkout_count = ou.checkouts.count()
   for kid in ou.children.all():
       checkout_count += count_checkouts(kid)
   return checkout_count

Also note, that to get a number of related checkouts I use:
checkout_count = ou.checkouts.count()

insted of:
count = ou.checkouts.all().count()

My variant is more efficient (see http://docs.djangoproject.com/en/1.1/ref/models/querysets/#count).

A:

I think the most efficient way of calculating this is at write time. You should modify OrganizationalUnit like this:
class OrganizationalUnit(models.Model):
    name = models.CharField(max_length=100)
    parent = models.ForeignKey(
        'self',
        blank=True, null=True,
        related_name='children',
    )
    checkout_number = models.IntegerField(default=0)

create the functions that will update the OrganizationalUnit and its parents at write time:
def pre_save_checkout(sender, instance, **kwargs):
    if isinstance(instance,Checkout) and instance.id and instance.department:
         substract_checkout(instance.department)

def post_save_checkout(sender, instance, **kwargs):
    if isinstance(instance,Checkout) and instance.department:
         add_checkout(instance.department)

def  substract_checkout(organizational_unit):
    organizational_unit.checkout_number-=1
    organizational_unit.save()
    if organizational_unit.parent:
        substract_checkout(organizational_unit.parent)

def  add_checkout(organizational_unit):
    organizational_unit.checkout_number+=1
    organizational_unit.save()
    if organizational_unit.parent:
        add_checkout(organizational_unit.parent)

now all you need is connect those functions to the pre_save, post_save and pre_delete signals:
from django.db.models.signals import post_save, pre_save, pre_delete

pre_save.connect(pre_save_checkout, Checkout)
pre_delete.connect(pre_save_checkout, Checkout)
post_save.connect(post_save_checkout, Checkout)

That should do it...


Q:

Can't delete files in directories I've renamed in Java?

I was messing around with the java.io.File methods today, and stumbled on something kind of weird.
When I rename a directory, I can't seem to ever delete the files or new directory.
    File dir = new File("dir");
    dir.mkdir();

    File file = new File(dir, "afile.txt");
    file.createNewFile();

    File newname = new File(dir, "newName.txt");
    file.renameTo(newname);

    File newdir = new File("newdir");
    dir.renameTo(newdir);

    System.out.println("file exists? " + file.exists());
    System.out.println("file deleted? " + file.delete());
    System.out.println("newname exists? " + newname.exists());
    System.out.println("deleted newname? " + newname.delete());
    System.out.println("dir exists? " + dir.exists());
    System.out.println("dir deleted? " + dir.delete());
    System.out.println("newdir exists? " + newdir.exists());
    System.out.println("deleted newdir? " + newdir.delete());

Yields the output:
    file exists? false
    file deleted? false
    newname exists? false
    deleted newname? false
    dir exists? false
    dir deleted? false
    newdir exists? true
    deleted newdir? false

In the filesystem, though, newdir and newname.txt both still exist!
However, if I comment out the renaming of the directory, the delete works fine.
Are there additional rules between delete() and rename() one needs to know about? There's not much in the javadoc.

A:

I don't see any problem with the output:

At the end of the renaming, only newdir/ and newdir/newName.txt exist. Therefore the first six lines of output should be false, and they are. (In particular, the newname variable still refers to dir/newName.txt, which no longer exists.)
newdir does exist; your output confirms this.
The final delete() doesn't work because the directory is not empty.

In summary, everything appears to work exactly as one would expect.


Q:

How to convert the objects in a query result to custom type

I think the same question must have been asked, but I just don't know how to describe it properly.
I am using Entity Framework, and I have a table called vendor, consisting of many columns:
[vendor]
 - [Id] [INT]
 - [Name] [NVARCHAR]
 - [ApiUrl] [NVARCHAR]
 - ...

I am writing a Web Api to expose the function which users can get vendor records by. However, I want to provide only three columns.
So I created a model class, as below:
public class OM_Vendor
{
    public int Id { set; get; }
    public string Name { set; get; }
    public string ApiUrl { set; get; }
}

After building the model classes with EF, the context object of EF has a property named vendors now. Then, in an API controller, I coded like this:
var vendors = this.objEntity.vendors
.Where<OM_Vendor>(v => v.Status == "1")
.OrderBy(v => v.Id)
.Skip(intSkip)
.Take(intLimit)
.ToList();

It doesn't work, neither does this:
    var vendors = this.objEntity.vendors
.Where(v => v.Status == "1")
.OrderBy(v => v.Id)
.Skip(intSkip)
.Take(intLimit)
.ToList<OM_Vendor>();

Is there a way to convert the objects returned by the methods like above to my custom type?
Thanks a lot.

In addition, I know that I can get it to work in this way:
var vendors = new List<OM_Vendor>();
vendors = objCont.ExecuteStoreQuery<OM_Vendor>("SELECT * FROM vendor").ToList();

And this way works too:
var vendors = this.objCont.vendors
                .Where(v => v.Status == "1")
                .OrderBy(v => v.Id)
                .Select(
                    row => new
                        {
                            Id= row.Id,
                            Name = row.Name,
                            ApiUrl = row.ApiUrl
                        }
                )
                .Skip(intSkip)
                .Take(intLimit)
                .ToList();

Update:
According to @Andrew's answer, I updated my code as below:
public class OM_Vendor
{
    public int Id { set; get; }
    public string Name { set; get; }
    public string ApiUrl { set; get; }

    public static implicit operator OM_Vendor(vendor vendor){
        return new OM_Vendor
        {
            Id = vendor.Id,
            Name = vendor.Name,
            ApiUrl = vendor.ApiUrl
        };
    }
}

And in my controller class:
List<OM_Vendor> vendors = this.objCont.vendors
                                        .Where(v => v.Status == "1")
                                        .OrderBy(v => v.Id)
                                        .Skip(intSkip)
                                        .Take(intLimit)
                                        .ToList();

I got error saying:

Cannot implicitly convert type
  'System.Collections.Generic.List' to
  'System.Collections.Generic.List'

What did I miss? As for the explicit cast, I will have to convert each instance explicitly in a loop?

A:

You basically have 3 methods to achieve what you are trying to accomplish.

Use the .Select() linq extension method to create a projection (as is demonstrated by your last example.)  Generally a good option, as this will create a SQL expression which only returns the fields which are needed by your Data Transfer Object.
Create a custom cast operator, e.g. public static implicit Operator OM_Vendor(Vendor vendor), which takes in a full Vendor object and assigns it to an instance of OM_Vendor.  The main drawback here is that you are essentially retrieving all fields through Entity Framework, only to Flatten the entity and discard many of these fields during the implicit cast.
Use a custom library such as Automapper to automate the process of converting the objects.  Suffers from most of the same issues as 2., but having it handled by a library can be helpful if you have many classes you are Flattening.

A more complete code example to demonstrate:
public class OM_Vendor {
    ...
    public static implicit Operator OM_Vendor(Vendor vendor){
        return new OM_Vendor {
            Id = vendor.Id;
            Name = vendor.Name;
            ApiUrl = vendor.ApiUrl;
    }
}

OM_Vendor om_Vendor = this.objEntity.vendors.Where(
...

List<OM_Vendor> vendors = this.objEntity.vendors.Where(
...

Either of these statements should execute correctly, using the implicit Operator as a Constructor when assigning a Vendor instance to an OM_Vendor.  However, it cannot be overstated, this is Flattening the object at the code level, and will result in a larger than necessary SQL query.
This actually should be an explicit operator, since data loss occurs during conversion.  Changing implicit Operator to explicit Operator will cause this conversion to require the cast, i.e. OM_Vendor omVendor = (OM_Vendor)vendor;.  This makes it much more clear that a conversion is occurring, but makes the code slightly more verbose.


Q:

Telerik radgird show column sum in footer in rad grid depend on other column

i just want to sum a column and show in footer but problem is that column sum is depend on other column value.
Example
in my grid i have two column
one for price and second for currency code
Price   CurrencyCode
100      Eur
54       GBP
65       GBP
89       USD
41       EUR

i wanted to sum a price according to currency code
show sum in footer Like this
Eur: 141
GBP: 119
USD: 89
how to do this help me..
thanks In Advance

A:

var sumEur = yourtable.compute("sum(Price)",CurrencyCode='GBP');
var sumGBP = yourtable.compute("sum(Price)",CurrencyCode='EUR');
var sumUSD = yourtable.compute("sum(Price)",CurrencyCode='USD');


Q:

Conversion of Strings to Datetime Pandas - tried everything

I know there are a lot of similar questions but I am pretty sure I have tried everything I found
Data:
    TimeStamp
    10:34:30
    10:35:30
    10:36:30
    10:37:30

I have two different .csv files and I am trying to compare the times from the two in order determine further action.
I want to use .dt.hour or .dt.min to compare the times. Here's what I tried:
The type always remains str or float and the .dt.hour or .dt.min does not work
    def csv_to_df(path, filename):
        dateparse = lambda x: pd.datetime.strptime(x, '%H:%M:%S')
        df = pd.read_csv(path + filename, skipinitialspace = True, parse_dates = True, date_parser = dateparse)
        return df

I also tried using pd.to_datetime later for conversion. That didn't work either.
    df_sr4500.TimeStamp=pd.to_datetime(df_sr4500.TimeStamp).dt.time
    print(df_sr4500.TimeStamp[1].dt.hour)

    ERROR: AttributeError: 'datetime.time' object has no attribute 'dt'

A:

IIUC
df.TimeStamp=pd.to_datetime(df.TimeStamp).dt.time

df.TimeStamp[1]
Out[115]: datetime.time(10, 35, 30)

df.TimeStamp[1].hour

Out[119]: 10

In case you need convert new column hour
df.TimeStamp.apply(lambda x : x.hour)
Out[122]:
0    10
1    10
2    10
3    10
Name: TimeStamp, dtype: int64


Q:

Generic iterator in c++

I am busy with a project and want to know what is Generic iterator class for arrays of type T and how do i write one. I have look in books and on websites and i cant find anything on it. Please help. But dont write code for me.

A:

Probably a class that has operators unary *, ++ and possibly -- defined, where the first one returns a reference to the underlying T object, the second advances the iterator to the next element in the container and the last one advances the iterator backwards.
Or, if you're using some standard container, just the return value of yourContainer.begin() or yourContainer.find().
If you elaborate on your question you can get a better answer. For example, what container are you using? What's expecting a generic iterator?


Q:

Is there a method to Pass the name of the sheet to Sheet.select function via a string Variable?

I'm having a Workbook in which all sheets are hidden except a Base sheet "CRM_Competencies_Dashboard"
As soon as the user logs in I will pull the user id with Environ("Username") function. Then I will store that value in a string variable "User_Name"
Now my goal is to Un-hide only that sheet.
And there are a list of users who will access this workbook.
Every-time they open only their respective sheet should be visible
I tried to Un-hide the sheet by using the below function but I didn't get a way to pass the sheet name as a variable as shown below
Sub Display_User_Specific_data()
Dim User_Name As String
User_Name = Environ("Username")
ActiveWorkbook.Sheets(User_Name).Select
ActiveSheet.Visible = xlSheetVisible
End Sub

Sheets(User_Name) should become un-hidden. And the value of variable User_Name can change for different users.

A:

You cannot select a sheet that is Hidden. So you have to un-hide it First.
Use this:
Sub Display_User_Specific_data()
    Dim User_Name As String
    User_Name = Environ("Username")
    ActiveWorkbook.Sheets(User_Name).Visible = xlSheetVisible
End Sub

Also, Keep in mind that the user name will be of the form mohit.bansal if the name is Mohit Bansal , so your sheet name should be mohit.bansal

Demo:

Addition by @Pulitian

To add to this, add the following to your 'this workbook' object to hide the sheet upon workbook close. Otherwise it will still be open when the next person uses the workbook.

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    ActiveWorkbook.Sheets(Environ("Username")).Visible = xlSheetVeryHidden
End Sub


Q:

Convert Lowercase Letters to Uppercase in C Language

I'm working on a simple piece of program to incorporate into a larger program. I'm following what my professor has already taught.
#include <stdio.h>

int main()
{
char letter;
printf("Please Enter a Lower Case Letter:");
scanf("%s", letter);

if (letter >= 'a' && letter <= 'z')
  letter = letter - 'a' + 'A';
printf("%s", letter);
return 0;
}

The initial 'Please Enter a Lowercase Letter:' appears but after inputting a letter the return is (null). Any help is appreciated.

A:

Maybe try getchar() instead of scanf(). Links to C reference for getchar() and scanf()
#include <stdio.h>
int main()
{
char letter;
printf("Please Enter a Lower Case Letter:");
letter = getchar();

if (letter >= 'a' && letter <= 'z')
  letter = letter - 'a' + 'A';
printf("%c", letter);
return 0;
}


Q:

Can you use NSDateformatter for creating dates with only month and year?

I have a data source that gives me dates
22017            // means: february 2017
122017           // december 2017
52018            // May 2018

i've tried parsing this with format String Myyyy, which does not get correct dates. I'm now adding a '-' dash before the last 4 letters to correctly separate year and month
5-2018
12-2018

But the NSDateformatter still does not give the correct format when setting M-yyyy, and i really don't understand why. Is it just too little information to create a date?

A:

It does indeed work, but you have to specify exactly if the month has one or two digits
let dateArray = ["22017", "122017", "52018"]

let dateFormatter = DateFormatter()

for string in dateArray {
    dateFormatter.dateFormat = string.characters.count == 5 ? "Myyyy" : "MMyyyy"
    let date = dateFormatter.date(from: string)
    print(date)
}


Q:

How to configure Laravel on remote server

I'm new on Laravel. Installed laravel on my remote server ubuntu14.04. I create a project on /www/html as blog. Then run
php artisan serve --host=10.x.x.12 --port=8010.
#Laravel development server started: <http://10.x.x.12:8010>

Its ok . I can access laravel from my local windows with that link.
The problem is I use putty for remote access. When I closed putty, I can't access anymore 10.x.x.12:8010.
How to use laravel server continuously from remote server.

A:

Use nohup (man page) so the program does not exit when the terminal session ends.
nohup php artisan serve --host=10.x.x.12 --port=8010 &


Q:

JQuery need to call data-rel="dialog" in the first page or opening page

I am new to JQuery i figured out that i can use JQuery for mobile web browser dev. I am doing a simple pop page for Browser. I went through some documents and got the answer i can use data-rel="dialog" for the modal window like page. But i want the modal like window as my opening page. (Page 1) This is my code. Please help me. I am new to this one. Thank You.

Page Content Header

This is page 1

Display Dialog

                        Apple

                Go

A:

Change the data-role to dialog. Then you can just get rid of the data-rel attribute. i.e.

Page Content Header

This is page 1

Display Dialog


Q:

Add multiple polylines to a single Array

I´m new working on Maps API V3, but I can´t find a way to put multiple polylines inside one array, so I can make them show/hide with a button (all at once). This is my code.
// Setup the click event listener: simply set the map to center on Bogota
var bogota = new google.maps.LatLng(4.697316, -74.044805);
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();

// FUNCION INICIALIZE
function initialize() {
   directionsDisplay = new google.maps.DirectionsRenderer();
   map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

    // passing in this DIV.
        var botonesDiv = document.createElement('div');
        var espacioControles = new Controles(botonesDiv, map);
                botonesDiv.index = 1;
        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(botonesDiv);

    // Ingresamos las lineas de la CICLORUTAS
    // Son de color rojo
          var ColorViaCR = "#FF0000";
          var OpacidadCR = 1.0;
          var GrosorCR = 2;
          var CRArray = [];

          var CiclorutasCoordinates116 = [
            new google.maps.LatLng(4.698555, -74.049835),
            new google.maps.LatLng(4.698437, -74.049004),
            new google.maps.LatLng(4.696328, -74.043339)
          ];
          var Cicloruta116 = new google.maps.Polyline({
            path: CiclorutasCoordinates116,
            strokeColor: ColorViaCR,
            strokeOpacity: OpacidadCR,
            strokeWeight: GrosorCR
          });
          CRArray.push(Cicloruta116);

          var CiclorutasCoordinates112 = [
            new google.maps.LatLng(4.696723396389598, -74.05013248790056),
            new google.maps.LatLng(4.696632507503862, -74.04982671607286),
            new google.maps.LatLng(4.696480134933544, -74.04946461785585),
            new google.maps.LatLng(4.687099216812973, -74.03546721674502),
            new google.maps.LatLng(4.687072484420475, -74.03525800444186)
          ];
          var Cicloruta112 = new google.maps.Polyline({
            path: CiclorutasCoordinates112,
            strokeColor: ColorViaCR,
            strokeOpacity: OpacidadCR,
            strokeWeight: GrosorCR
          });
          CRArray.push(Cicloruta112);

             directionsDisplay.setMap(map);

}

// FIN DE INITIALIZE
// SHOW/HIDE POLYLINES
function showCR() {
  for (var i=0; i< CRArray.length; i++) {
    if(CRArray[i].getMap(map)) {
    CRArray[i].setMap(null);
 } else {
    CRArray[i].setMap(map);
 }
  }
}

// CREATE BUTTON
function Controles(DivGeneral, mapa) {

    // Set CSS for the control border.
    var InfoUI = document.createElement('div');
    InfoUI.style.backgroundColor = 'white';
    InfoUI.style.borderStyle = 'solid';
    InfoUI.style.borderWidth = '1pt';
    InfoUI.style.borderColor = '#CCC';
    InfoUI.style.cursor = 'pointer';
    InfoUI.style.textAlign = 'left';
    InfoUI.title = 'Ver Ciclorutas';
    InfoUI.style.marginTop = '2px';
    DivGeneral.appendChild(InfoUI);

    // Set CSS for the control interior.
    var InfoText = document.createElement('div');
    InfoText.style.fontFamily = 'Arial,sans-serif';
    InfoText.style.color = '#000';
    InfoText.style.fontSize = '12px';
    InfoText.style.paddingLeft = '8px';
    InfoText.style.paddingRight = '8px';
    InfoText.style.paddingTop = '12px';
    InfoText.style.paddingBottom = '12px';
    InfoText.innerHTML = 'Ver Ciclorutas';
    InfoUI.appendChild(InfoText);

    google.maps.event.addDomListener(InfoUI, 'click', function() {
          showCR();
     });

}

google.maps.event.addDomListener(window, 'load', initialize);

</script>

A:

I think the answer lies in where you have defined CRArray.
By defining CRArray inside of initialize(), you've set the scope of the array to be inside of that function. To access CRArray inside of other functions, the easiest way is to define it in the global scope (move var CRArray outside of initialize().)
Try the following code instead:
var CRArray = new Array();

function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

// passing in this DIV.
    var botonesDiv = document.createElement('div');
    var espacioControles = new Controles(botonesDiv, map);
            botonesDiv.index = 1;
    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(botonesDiv);

// Ingresamos las lineas de la CICLORUTAS
// Son de color rojo
      var ColorViaCR = "#FF0000";
      var OpacidadCR = 1.0;
      var GrosorCR = 2;

      var CiclorutasCoordinates116 = [
        new google.maps.LatLng(4.698555, -74.049835),
        new google.maps.LatLng(4.698437, -74.049004),
        new google.maps.LatLng(4.696328, -74.043339)
      ];
      var Cicloruta116 = new google.maps.Polyline({
        path: CiclorutasCoordinates116,
        strokeColor: ColorViaCR,
        strokeOpacity: OpacidadCR,
        strokeWeight: GrosorCR
      });
      CRArray.push(Cicloruta116);

      var CiclorutasCoordinates112 = [
        new google.maps.LatLng(4.696723396389598, -74.05013248790056),
        new google.maps.LatLng(4.696632507503862, -74.04982671607286),
        new google.maps.LatLng(4.696480134933544, -74.04946461785585),
        new google.maps.LatLng(4.687099216812973, -74.03546721674502),
        new google.maps.LatLng(4.687072484420475, -74.03525800444186)
      ];
      var Cicloruta112 = new google.maps.Polyline({
        path: CiclorutasCoordinates112,
        strokeColor: ColorViaCR,
        strokeOpacity: OpacidadCR,
        strokeWeight: GrosorCR
      });
      CRArray.push(Cicloruta112);

         directionsDisplay.setMap(map);

}


Q:

Can someone tell me how to sum only some of items nested in my JavaScript array?

I am not very proud of this codeㅠㅠ I have 6000 objects in the array and would like to sum only 10 items from the array. Now I am putting ten coding blocks to the program.
Someone can tell me how to make it look like programing?
<Text style={styles.text}>[{Number((items.find( x => x.id === indexTwoId+101).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+102).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+103).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+104).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+105).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+106).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+107).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+108).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+109).as==='1'?'1':'0'))+Number((items.find( x => x.id === indexTwoId+110).as==='1'?'1':'0'))}/10]</Text>
My array is as follows;
    count: 1,
    categories: [
        {id:1,as:0},
        {id:2,as:0},
        {id:3,as:0},
        {id:4,as:0},
        {id:5,as:0},
        {id:6,as:0},
        {id:7,as:0},
        {id:8,as:0},
        {id:9,as:0},
        {id:10,as:0},
.
.
.
.]}```

A:

I don't have experience with React, but in "regular" JS you might do something like this:
let sum = items.reduce((item, total) => {
    if (item.id < indexTwoId + 101 || item.id > indexTwoId + 110) return total;
    if (item.as === '1') return total + 1;
    return total;
}, 0)

You can probably "translate" it to a single line with ternary operators.
EDIT:
If you just want to count items by criteria then:
items.filter(x => x.id >= indexTwoId + 101 && x.id <= indexTwoId + 110 && x.as === '1').length


Q:

Unable to show fancybox title in v2

... sorry, but i have a similar problem with no solution:
i use this code to open a fancybox from inside an iframe.
Here the head-part:

<link rel="stylesheet" href="fancybox/source/jquery.fancybox.css?v=2.1.5" type="text/css" media="screen" />

i attach fancyBox with this code:

the link on the body-part is the following:

But no title is displayed. :(
When i write the following line to the attach-code the title is showing up, but just statical and this helps nothing:
   title : 'just a static title',

Could someone please help me?

A:

Since you are firing fancybox using a manual method $('.fancybox').click() then title attribute is not picked up so you need to force it adding the API option
title: this.title

See JSFIDDLE
NOTE : title type: 'float' is the default and is ALWAYS at the bottom of fancybox so positioning it has no effect
helpers: {
    title: {
        // position: 'bottom', // <== useless if using "float"
        type: 'float' // this is default so you don't have to set it unless is different
    },
    ...


Q:

301 redirect from form action to URL with htaccess

I want to redirect an URL like this one:
/calculate?from=london&to=paris

to other like this one:
/difference-london-paris

I tried this on my .htaccess file, but it doesn't work :(
RewriteRule ^calculate?from=(.*)&to=(.*) ^difference-$1-$2 [R=301,L]

Thanks in advance for your help!

A:

Use this code:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+calculate\?from=([^&]*)&to=([^&\s]*) [NC]
RewriteRule ^ difference-%1-%2? [R=301,L]

RewriteRule ^difference-([^-]+)-([^-]+)/?$ calculate?from=$1&to=$2 [L,NC,QSA]


Q:

Does anyone know of a Firebug equivilant for Internet Explorer?

The question says it all. Inter Explorer's lack of standard compliance has struck, and driven me to the brink of madness. Does anyone know of a Firebug equivalent for IE8?

A:

Firebug Lite

Firebug is an extension for Firefox,
  but what happens when you need to test
  your pages in Internet Explorer,
  Opera, and Safari?
The solution is Firebug Lite, a
  JavaScript file you can insert into
  your pages to simulate some Firebug
  features in browsers that are not
  named "Firefox".
Firebug Lite creates the variable
  "firebug" and doesn't affect or
  interfere with HTML elements that
  aren't created by itself.

A:

Download the internet explorer  developer toolbar
http://www.microsoft.com/downloads/details.aspx?familyid=e59c3964-672d-4511-bb3e-2d5e1db91038&displaylang=en

A:

You may be surprised, but Visual Studio is a great tool for debugging Javascript (or JScript, as MS calls it). Just attach an IE process, view the running scripts and set breakpoints wherever you like. As for DOM inspection, it can't help you there. But it's how I debug in IE.


Q:

How to prevent FAB from scrolling with CoordinateLayout in Android

I've the below layout xml for my activity
<android.support.design.widget.CoordinatorLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:background="@color/white"
     android:fitsSystemWindows="true"
     tools:context=".HomeActivity">

     <android.support.design.widget.AppBarLayout
          xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:theme="@style/AppTheme.Dark.AppBarOverlay"
          app:elevation="0dp">

          <android.support.v7.widget.Toolbar
               android:id="@+id/toolbar"
               android:layout_width="match_parent"
               android:layout_height="?attr/actionBarSize"
               android:background="?attr/colorPrimary"
               app:layout_scrollFlags="scroll|enterAlways"
               app:popupTheme="@style/AppTheme.Dark.PopupOverlay">
     </android.support.design.widget.AppBarLayout>

     <RelativeLayout
        android:id="@+id/rl_updates"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/ll_footer"
        android:layout_below="@+id/ll_fibres_search">

        <android.support.v4.widget.SwipeRefreshLayout
              android:id="@+id/srl_updates"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

               <android.support.v7.widget.RecyclerView
                     android:id="@+id/rv_all_requirements"
                     android:layout_width="match_parent"
                     android:layout_height="match_parent"
                     android:divider="@color/iron"
                     android:dividerHeight="1px"/>
         </android.support.v4.widget.SwipeRefreshLayout>

         <android.support.design.widget.FloatingActionButton
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_alignParentBottom="true"
              android:layout_alignParentEnd="true"
              android:layout_alignParentRight="true"
              android:layout_marginBottom="@dimen/activity_horizontal_margin"
              android:layout_marginEnd="@dimen/activity_horizontal_margin"
              android:layout_marginRight="@dimen/activity_horizontal_margin"
              android:onClick="onRequirement"
              android:overScrollMode="never"
              android:src="@drawable/ic_playlist_add_white_24dp"
              app:backgroundTint="@color/pink"/>
    </RelativeLayout>
</android.support.design.widget.CoordinatorLayout>

When I scroll the Recycler View, the App Bar collapses just like I wanted it to be. But the problem is the FAB also shifts down a little bit. I set 16dp margin to the bottom but it sticks to the bottom of the screen.
How do I prevent the FAB from shifting down initially?
This is how it looks now

A:

Have you tried taking the FloatingActionButton outside the RelativeLayout and inside the CoordinatorLayout? You can do that and give it the attribute:
    android:layout_gravity="bottom|right|end"

instead of:
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"


Q:

CPU Registers and Computation

How exactly does the control unit in the CPU retrieves data from registers? Does it retrieve bit by bit?
For example if I'm adding two numbers, A+B, how does the computation takes place in memory level?

A:

Let’s say you have a processor with sixteen 32-bit registers and a unit that can add 32 bit integers. A very simplified way to add register x and register y and store the result in register z is this:
First, you build hardware that given a number x, can pick the first bit of register x and move it to the 1st bit of “operand1”. This is actually quite complicated because x could be one of 16 values, and the hardware must be capable to read the first bit of any of the 16 registers.
Second, you take this hardware and make 32 copies of it, one copy for each bit in a register. Now we have some quite complex hardware that can move 32 of 512 bits.
Third, we duplicate all of this with the appropriate changes to move register y to “operand2”.
Fourth, we build hardware that can add operand1 and operand2 and store the sum in a 32 bit location “output”
And fifth, we build the hardware that can take the value in “output”
and store it into register z.


Q:

Questions Lost in the Shuffle

Possible Duplicate:
How do I get attention for my old, unanswered questions?

I was just wondering if there is an acceptable way to prevent one's questions from getting lost in the shuffle.  I just asked a question on Stack Overflow 30 minutes ago, and it is now appearing on page 5 of the Questions.  Is there a way to bump one's questions?  Does commenting on or editing your question help get a question bumped?  I do not have the reputation yet to post a bounty, and I'm not sure if you can upvote your own questions...  Thanks.

A:

Using a good title and putting in the appropriate tags is one the best ways to get good answers to your question. Many Stack Overflow users subscribe to tag-specific RSS feeds, so even if your question is not on the front page it does not matter as users will read it from the feed and post an answer.
Please do not edit your post unless you have new material/content to add in your original question.


Q:

Parse error: syntax error, unexpected '<' in functions.php

I know this is a somewhat common error but I"m not sure what's wrong with my code. I get the error Parse error: syntax error, unexpected '<' in /home/content/56/11192256/html/wp-content/themes/Aggregate/functions.php on line 382
Any help would be really appreciated!
function et_delete_featured_ids_cache(){
    if ( false !==get_transient( 'et_featured_post_ids' ) )
        delete_transient('et_featured_post_ids' );
    }
}

if ( ! function_exists( 'et_list_pings' ) ){
    function et_list_pings($comment, $args, $depth) {
        $GLOBALS['comment'] = $comment; ?>
            <li id="comment-<?php comment_ID(); ?>">
            <?php comment_author_link(); ?> - <?php comment_excerpt(); ?> <?php ?>
    }
}
?>

<style type="text/css"> body { color: #<?php echo
esc_html(get_option($shortname.'_color_mainfont')); ?>; }
    #    content-area a { color: #<?php echo
    #esc_html(get_option($shortname.'_color_mainlink')); ?>; }
        ul.nav li a { color: #<?php echo
    esc_html(get_option($shortname.'_color_pagelink')); ?>
    !important; } ul.nav > li.current_page_item > a, ul#top-menu
    > li:hover > a, ul.nav > li.current-cat > a { color: #<?php
    echo
    esc_html(get_option($shortname.'_color_pagelink_active'));
    ?>; } h1, h2, h3, h4, h5, h6, h1 a, h2 a, h3 a, h4 a, h5 a,
    h6 a { color: #<?php echo
    esc_html(get_option($shortname.'_color_headings')); ?>; }

    #    sidebar a { color:#<?php echo
    #esc_html(get_option($shortname.'_color_sidebar_links')); ?>;
    #}
        .footer-widget { color:#<?php echo
    esc_html(get_option($shortname.'_footer_text')); ?> }
    #    footer a, ul#bottom-menu li a { color:#<?php echo
    #esc_html(get_option($shortname.'_color_footerlinks')); ?> }
    </style>

<?php }

A:

Looks like you are missing a { in
function et_delete_featured_ids_cache(){
    if ( false !==get_transient( 'et_featured_post_ids' ) ) {
    //                                                      ^ Here
        delete_transient('et_featured_post_ids' );
    }
}


Q:

Is it grammatically correct to use "who" for inanimate objects?

Is it grammatically correct to use "who" for non-persons such as organizations, animals?
Consider a question
Q1: "Who should I feed?" and the answer
A1: "Feed the hungry, your friends and your pets."
Would the answer be grammatically correct if it includes "pets", but the question had a pronoun "who"?
A similar example:
Q2: "Who should I donate money to?"
A2: "Donate the money to the poor and to the universities."
Would the example answer be grammatically correct if it mentions universities which are organizations rather than persons?

A:

Who or what are your basic choices here.  Pets can also be considered addressed by who.


Q:

Connecting signal to slot between classes in PyQt

Aim is to connect a signal of the top class TicTacToe with the QMainWindow class.
It throws an error: TicTacToe cannot be converted to PyQt5.QtCore.QObject in this context
#!/usr/bin/env python

from PyQt5.QtCore import (QLineF, QPointF, QRectF, pyqtSignal)
from PyQt5.QtGui import (QIcon, QBrush, QColor, QPainter, QPixmap)
from PyQt5.QtWidgets import (QAction, QMainWindow, QApplication, QGraphicsView, QGraphicsScene, QGraphicsItem,
                             QGridLayout, QVBoxLayout, QHBoxLayout,
                             QLabel, QLineEdit, QPushButton)

class TicTacToe(QGraphicsItem):
    def __init__(self):
        super(TicTacToe, self).__init__()

    def paintEvent(self, painter, option, widget):
        painter.setPen(Qt.black)
        painter.drawLine(0,100,300,100)

    def boundingRect(self):
        return QRectF(0,0,300,300)

    def mousePressEvent(self, event):
        pos = event.pos()
        self.select(int(pos.x()/100), int(pos.y()/100))
        self.update()
        super(TicTacToe, self).mousePressEvent(event)

    messageSignal = pyqtSignal(int)

class MyGraphicsView(QGraphicsView):
    def __init__(self):
        super(MyGraphicsView, self).__init__()
        scene = QGraphicsScene(self)
        self.tic_tac_toe = TicTacToe()
        scene.addItem(self.tic_tac_toe)

        scene.addPixmap(QPixmap("exit.png"))

        self.setScene(scene)

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_R:
            self.tic_tac_toe.reset()
        super(MyGraphicsView, self).keyPressEvent(event)

class Example(QMainWindow):
    def __init__(self):
        super(Example, self).__init__()

        self.y = MyGraphicsView()
        self.setCentralWidget(self.y)

        self.y.tic_tac_toe.messageSignal.connect (self.messageSlot)

        self.initUI()

    def messageSlot(self, val):
        self.statusBar().showMessage(val)

    def initUI(self):
        self.toolbar = self.addToolBar('Tools')

        self.setGeometry(30, 30, 30, 20)
        self.setWindowTitle('Menubar')
        self.show()

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    mainWindow = Example()

    mainWindow.showFullScreen()
    sys.exit(app.exec_())

A:

Only classes that inherit from QObject have the ability to create signals, for example QWidget, QMainWIndow, QGraphicsView inherit from QObject so they can have signals. But QGraphicsItem does not inherit from QObject because of efficiency issues so they do not have the ability to create signals. If you want an item that is a QObject you must use QGraphicsObject. In addition, the items have the paint() method, not paintEvent().
class TicTacToe(QGraphicsObject):
    def paint(self, painter, option, widget):
        painter.setPen(Qt.black)
        painter.drawLine(0,100,300,100)

    def boundingRect(self):
        return QRectF(0,0,300,300)

    def mousePressEvent(self, event):
        pos = event.pos()
        # self.select(int(pos.x()/100), int(pos.y()/100))
        self.update()
        super(TicTacToe, self).mousePressEvent(event)

    messageSignal = pyqtSignal(int)

If you still want to use QGraphicsItem, a possible work around is to create a class that is in charge of the communication and that inherits from QObject:
class Helper(QObject):
    messageSignal = pyqtSignal(int)

class TicTacToe(QGraphicsObject):
    def __init__(self, helper):
        super(TicTacToe, self).__init__()
        self.helper = helper

    def paint(self, painter, option, widget):
        painter.setPen(Qt.black)
        painter.drawLine(0,100,300,100)

    def boundingRect(self):
        return QRectF(0,0,300,300)

    def mousePressEvent(self, event):
        pos = event.pos()
        self.helper.emit(10)
        # self.select(int(pos.x()/100), int(pos.y()/100))
        self.update()
        super(TicTacToe, self).mousePressEvent(event)

class MyGraphicsView(QGraphicsView):
    def __init__(self):
        super(MyGraphicsView, self).__init__()
        scene = QGraphicsScene(self)
        self.helper = Helper(self)
        self.tic_tac_toe = TicTacToe(self.helper)
        scene.addItem(self.tic_tac_toe)
        scene.addPixmap(QPixmap("exit.png"))
        self.setScene(scene)

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_R:
            self.tic_tac_toe.reset()
        super(MyGraphicsView, self).keyPressEvent(event)

class Example(QMainWindow):
    def __init__(self):
        super(Example, self).__init__()

        self.y = MyGraphicsView()
        self.setCentralWidget(self.y)
        self.helper.messageSignal.connect(self.messageSlot)
        self.initUI()

    def messageSlot(self, val):
        self.statusBar().showMessage(val)

    def initUI(self):
        self.toolbar = self.addToolBar('Tools')
        self.setGeometry(30, 30, 30, 20)
        self.setWindowTitle('Menubar')
        self.show()


Q:

How can I fix these problems with a BlackBerry PhoneGap project and the simulator?

Based on the instructions here, I started a PhoneGap project in Eclipse that targets BlackBerry.  However, I'm running into two problems with this project:

If the simulator is not open, it will open but the application will not be installed properly.
If the simulator is already open, a message will appear with the text: The emulator is loading, please wait..., but nothing will happen.

What could be causing this, and how can I get my PhoneGap project working correctly with the simulator?

A:

i found that the problem in java-version
i used java7 - and it cause this problem
i tried java 6 update 25 and it works fine
thanks


Q:

How to add space between buttons in uiscrollview

I was trying so hard to add space between buttons array in UIScrollView but I couldn't make it. There is any way to make space between buttons array in UIScrollView ?
I have attached a picture explaining what I want.

This is my code :
 //MARK: - SETUP CATEGORIES BUTTONS
func setupCategoriesButtons() {
    var xCoord: CGFloat = 1
    let yCoord: CGFloat = 1
    let buttonHeight: CGFloat = 40
    let buttonwidth: CGFloat = 40
    let gap: CGFloat = 0

    // Counter for items
    var itemCount = 0

    // Loop for creating buttons
    for i in 0..<myArray.count {
        itemCount = i

        // Create a Button
        let catButt = UIButton(type: .custom)

        catButt.showsTouchWhenHighlighted = true
        catButt.setTitle("\(myArray[itemCount])", for: .normal)
        catButt.sizeToFit()

        catButt.frame = CGRect(x: xCoord, y: yCoord, width: catButt.frame.size.width + 30, height: buttonHeight)

        catButt.layer.cornerRadius = 8

        catButt.titleLabel?.font = UIFont(name: "Titillium-Semibold", size: 12)
      //  catButt.addTarget(self, action: #selector(categoryButt(_:)), for: UIControlEvents.touchUpInside)

        // Add Buttons & Labels based on xCood
        xCoord +=  catButt.frame.size.width + gap
        categoriesScrollView.addSubview(catButt)
        letterButtons.append(catButt)
    } // END LOOP --------------------------

    for i in 0..<letterButtons.count {
        letterButtons[i].tag = i
        letterButtons[i].backgroundColor = RandomColor()
        letterButtons[i].setTitleColor(UIColor.white, for: .normal)
    }

    // Place Buttons into the ScrollView
    categoriesScrollView.contentSize = CGSize(width: buttonwidth * CGFloat(itemCount+1), height: yCoord)
}

A:

let gap: CGFloat = 0

Looks wrong, if you want a gap. Shouldn't it be e.g. ... = 15?
Alternatives could include placing them in a UIStackView with a spacing set. This would also be simple using auto-layout, creating constraints between the buttons which provide the gaps.


Q:

Objective C: Terminating app due to uncaught exception 'NSInvalidArgumentException'

My app is crashing with the error  "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CALayer firstName]: unrecognized selector sent to instance 0x4d382c0'".
This is what I was trying to do.
1) I have created a 'Person' class to store information like firstName, lastName, email add and telephone number
Person.m file:
@implementation Person
@synthesize firstName, lastName, email, phoneNumber;

-(Person *)initWithfirstName:(NSString *)thisFirstName lastName:(NSString *)thisLastName email (NSString *)thisEmail phoneNumber:(NSString*)thisPhoneNumber
{
    if(self = [super init])
    {
        self.firstName = thisFirstName;
        self.lastName = thisLastName;
        self.email = thisEmail;
        self.phoneNumber = thisPhoneNumber;
    }
return self;
}
@end

2) Store a list of people in a mutable array
Person *firstPerson = [[Person alloc] initWithfirstName:@"Zen" lastName:@"Yong" email:@"" phoneNumber:@""];
person = firstPerson;

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:person, nil];

personArray = array;

[array release];

3) List the list of person's information in a table view
int row = [indexPath row];
Person *aPerson = (Person *)[self.personArray objectAtIndex:row];

cell.textLabel.text = aPerson.firstName;

Can you help to advise why I am getting the error listed at the beginning of the thread?
Appreciate your help on this!
Zhen

A:

You're crashing due to a dangling pointer.  You set personArray array to be the array you created, but then you release the array, leaving personArray as a dangling pointer.  From what you posted I'm assuming personArray is a property on the class.  If so, changing:
personArray = array;

to
self.personArray = array;

should fix the problem.  The way you have it now the array pointer is just being assigned to the personArray pointer.  You have to call set setter method for the property to get the proper memory management.


Q:

bash, search for usb storage devices. output location

I am looking for a way to list any usb connected devices or removable storage media.
I will be using this list for a gtk boot media writer, so a user can easily write an iso to a usb.
This creates a perfect list of ALL partitions:
ls /dev | grep "[sh]d[a-z][1-9]"

How can I get a similar looking list that is only removable media?

A:

On my system (Ubuntu 12.04), I can get a list of USB devices and partitions with
ls /dev/disk/by-path/*usb*

giving
/dev/disk/by-path/pci-0000:00:02.1-usb-0:1.1:1.0-scsi-0:0:0:0
/dev/disk/by-path/pci-0000:00:02.1-usb-0:1.1:1.0-scsi-0:0:0:0-part1

or partitions alone
ls /dev/disk/by-path/*usb*part*

These are symbolic links, pointing to the real device files, /dev/sdd and /dev/sdd1 for example.
I have tested this with a USB stick and an external USB hard disk only. I cannot say, whether or how this works with eSATA or Firewire disks.


Q:

Number of ways in which $5$ boys and $5$ girls can stand in a queue such that exactly $4$ girls can stand consecutively is

There are $5$ boys and $5$ girls. Number of ways in which $5$ boys and $5$ girls can stand in a queue such that exactly $4$ girls can stand consecutively is:
My attempt:
I first chose $4$ girls out of $5$ needed to be arranged in queue.
It can be done in $5C4$ ways. I bundle them separately.
Then I arrange them with remaining $5$ boys and a girl.
So total ways is $5C4×4!×7!$
Now we have to subtract those cases in which all $5$ girls are together.
So ways are $6!×5!$
Required ans is $5C4×4!×7!-6!×5!$.

Why this is wrong?

A:

There is double counting in $\binom54\times4!\times7!$ where you count the number of ways where at least $4$ girls are consecutive.
Suppose you have selected the girls $A,B,C,D$ to be consecutive.
Then we encounter the possibility: $$(A-B-C-D)-E-boys$$ where  $E$ is the other girl.
But if you have selected the girls $B,C,D,E$ we meet this possibility again in: $$A-(B-C-D-E)-boys$$

edit (solution)
First place the girls on a row.
Then by using stars and bars we find $2\binom62=15$ to place the boys in such a way that the girls are split up in a consecutive group of $4$ and a single girl. Here factor $2$ is there because the single girl can be on the left or on the right of the consecutive group.
That gives: $$2\binom625!5!=432000$$ possibilities in total


Q:

Mongo function to find if superstring exists in array. Nodejs,

A document in my mongo 'companies' collection looks like this:
{
    "companyName": "",
    "companyIcon": "",
    "domains": [
        "companyDomainA.com",
        "companyDomainB.dev"
    ],
    "allowSubDomains": true
}

In my application the user enters his/her email address.
Using the Nodejs native mongo driver (https://mongodb.github.io/node-mongodb-native), I want to query (find) which company the user belongs to.
The problem is when the user enters the email as name@dept.companyDomainA.com.
I want to be able to query and find the company document of the user based on his email (subdomained 0 or more levels), ie. if the superstring of a string exists in an array in mongo.
(Caveat, I cannot store all the subdomains of the company as they are dynamic and can change at will)
Is there a regular expression way/db schema change way, to achieve this?
Thanks in advance!!

A:

I would do it like this. First find the root domain from the email address. To do that I would split the email and fetch the domain first.
const email = "name@dept.companyDomainA.com";
const domain = email.split('@')[1]; // dept.companyDomainA.com

Now fetch the host (companyDomainA.com) from it. Follow this link.
So, I have found the root domain which is companyDomainA.com. Now run the find query.
db.collection('documents').find({"domains": "companyDomainA.com"});

I didn't test this code.


Q:

Buck Converter Voltage Fluctuation

Why the Voltage in output of Buck Converter fluctuates when there is a step change in load?

A:

That would be because the control loop can't follow fast enough, however this doesn't happen only in buck converters, it happens in all power supplies.
A solution to that is to put a big enough decoupling capacitor at the output, that can catch that transient without causing a significant drop, giving time to the control loop to respond. Also, if you have a long transmission line from the supply to the load, you may need to add a decoupling capacitor close to the load too, as the line inductance will also generate a voltage drop on the load.
Also, if the control loop of the supply is not properly compensated, you can get ringing at the output.


Q:

Why is EF treating a char property as an actual guid?

What I have actually is a property of type char which I use to store the string value of a guid.
My current setup:
- MySQL
- EF Code-First
- EF Migration
Model:
public class Employee
{
    public string Id { get; set; }
}

EF config
public class EmployeeConfiguration : EntityConfiguration<Employee>
{
    public EmployeeConfiguration()
    {
        HasKey(x => x.Id);
        Property(x => x.Id)
            .HasColumnType(“char”)
            .HasMaxLength(36)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    }
}

The problem:
System.FormatException is thrown if I do the following:
1. Insert with an Id that doesn’t follow the format of a guid.
2. Querying the above Employee class from database that contains an Id that doesn’t follow the format of a guid.
If I try to insert or query straight to the database using sql (without using EF), it’s all fine.
Can you please guide me how to work around this problem?
Edit 1:
Error message

Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).

Solution that worked for me
From "Jason Armstrong" suggestion, I used a different char length, I went with a char(37).

A:

EntityFramework automatically maps CHAR(36) TO GUID for MySQL per Entity Framework Data Type Mapping
Try adding old guids=true to your connection string per C# & MySQL Connector: Guid should contain 32 digits with 4 dashes


Q:

Working with databases in PHP

I am 100% self-taught, and so I try to read as much as I can about best practices, conventions, etc. However I freelance, and have been in a long-term contract position for the past little while with almost no peers to review my code. So I get nervous about developing bad habits.
Looking closely at this function I wrote (meant to give me a quick look over the db make sure nothing else is signed that ought to be unsigned):
$db = Database::instance();
$tables = array();
$result = $db->query('SHOW TABLES');
foreach($result as $table)
{
        $create = $db->query("SHOW CREATE TABLE `".current($table)."`");
        $tables[current($create->current())] = end($create->current());
}
echo var_dump($tables);

I see a couple things - $tables and $table are similar things, but $tables is not made up of every $table, so it could be confusing.
I tend to name all query results as $result unless there is a potential naming conflict.
Concatenating a function result within a query call seems more a quality of 'fast code' than 'good code'.
Am I being too nit-picky? Does this code look like it was written by an amateur/bad programmer?

A:

Your code looks like its good quality code. And yes, you’re right to be concerned. Most likely, after you’re gone, somebody else will (eventually) maintain, or change the code that you’ve written to date. I suggest that you comment and write the code so that a maintainer understands its purpose at first read.
For example ...
/*
 * Look quickly over the database to make sure nothing else is signed that ought to be unsigned.
 * TODO: Explain why unsigned is better than signed…
 */

$db = Database::instance();
$all_tables = array();
$result = $db->query('SHOW TABLES');
foreach($result as $unique_table)
{
   $show_created_table = $db->query("SHOW CREATE TABLE `".current($unique_table)."`");
   $all_tables[current($show_created_table->current())] = end($show_created_table->current());
}
echo var_dump($all_tables);

It's worth doing for yourself, for memory sake, if you haven't touched the code for a longtime.
It will also help the maintainer understand the intented purpose of the function. Now, if your project is large and complex, I'd recommend that you use phpdoc -- it's a good standard.


Q:

Unable to get Django object via primary key

I have an AJAX function that calls another function as such.
def update_votes(song_pk):
    song = Song.objects.get(pk=song_pk)
    song.votes += 1
    song.save()

@dajaxice_register
def update_disable(request, song_pk):
    update_votes(song_pk)
    dajax = Dajax()
    dajax.assign('.vote', 'disabled', 'disabled')
    return dajax.json()

The button disabling part works fine when used alone. But when I use the update_votes() function in the update_disable() function nothing works. The problem is with the song = Song.objects.get(pk=song_pk) line. What am I doing wrong?
This is how I am getting the primary key.
function update(){
    Dajaxice.hunt.update_disable(Dajax.process,{'song_pk':$('.song_pk').val()})
}

This is my HTML
{% for song in dj_song_list %}

{{ song.name }}

{{ song.id }}

            <button type="button" class="btn btn-default btn-custom" class='vote' onclick="update();">Vote as Favourite</button>

{% endfor %}

A:

This selector $('.song_pk') will select all of the elements with the .song_pk class in the page. The .val() will return the value of the first item in the selected elements, which is usually the top most one.
Secondly, instead of putting the pk in a hidden p tag, you probably want to put it into a hidden input tag instead. If you really want to put it into a p tag, you'll want to use .text() instead of .val().


Q:

How can I show whether the series $\sum\limits_{n=1}^\infty \frac{(-1)^n}{n(2+(-1)^n)} $ converges or diverges?

While revising for exams, I came across a question where at the end of it, we had to determine whether the below series was convergent or divergent:
$$\sum_{n=1}^\infty \frac{(-1)^n}{n(2+(-1)^n)} $$
Unfortunately, other than knowing that as the series $ \sum_{n=1}^\infty \frac{(-1)^n}{n} $ converges, this series will most likely converge as the $(2 + (-1)^n)$ terms are bounded, I can't see a way of using this to determine if it converges or not.
Here's a list of some of the other ideas I've tried, which don't seem to get me anywhere:

Generalising the series - By this, I mean replacing the $-1$ for $z$ and then try and use the ratio test to see whether $-1$ is inside or outside or on the boundary of the circle of convergence - however, when I did so, I believe that the ratio test is inconclusive for all values of $|z|$, which while disappointing, is an interesting feature of the series.
Summation by parts - While this is usually a nice tool to use for when dealing with awkward sums, I can't see any good choice of sequences $ (a_n) $ and $(b_n)$ to choose to use.
Summing consecutive terms - By this, I mean evaluating the series by looking at the sum of

$$\sum_{k=1}^\infty \frac{(-1)^{2k}}{2k(2+(-1)^{2k})} + \frac{(-1)^{2k-1}}{(2k-1)(2+(-1)^{2k-1})}$$
$$ \Rightarrow \sum_{k=1}^\infty \frac{1}{2k} - \frac{1}{3(2k-1)}$$
$\quad$ but then as we are left with parts of the harmonic series this doesn't seem like a nice way to  $\quad$evaluate it.
Other than that, I'm completely out of ideas, so any new ones (or ways to make my old ones work) would be much appreciated!

A:

Using the following proposition will help you resolve the problem:
If $a_n \longrightarrow_{n \to \infty} 0$ then $\sum_{n \ge 1} (-1)^n a_n$ and $\sum_{n \ge 1} (a_{2n}-a_{2n-1})$ either both converge or both diverge.