text:
Q: WPF ControlTemplate breaks style The stuff that does work
I need to style controls of a certain type that are children of a StackPanel. I'm using:
<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="{x:Type TextBlock}">...</Style>
    </StackPanel.Resources>
    <TextBlock ...>
    ...
</StackPanel>

And this works fine! Each TextBlock looks to the resources of it's parent (the StackPanel) to find out how it should be styled. It doesn't matter how far down you nest the TextBlock down a StackPanel... if it doesn't find a style in its direct parent, it will look at its parent's parent and so on, until it finds something (in this case, the style that was defined in ).
The stuff that doesn't work
I ran into a problem when I nested a TextBlock inside a ContentControl, which had a Template (see code below). The ControlTemplate seems to disrupt the way a TextBlock retrieves its style from its parents, grandparents,...
The use of a ControlTemplate effectively seems to knock out cold the TextBlock's means of finding its rightful style (the one in StackPanel.Resources). When it encounters a ControlTemplate, it stops looking for its style in the resources up the tree, and instead defaults to the style in MergedDictionaries of the Application itself.
<StackPanel Orientation="Vertical" Background="LightGray">
    <StackPanel.Resources>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="Foreground" Value="Green" />
        </Style>
    </StackPanel.Resources>

    <TextBlock Text="plain and simple in stackpanel, green" />
    <ContentControl>
        <TextBlock Text="inside ContentControl, still green" />
    </ContentControl>
    <ContentControl>
        <ContentControl.Template>
            <ControlTemplate TargetType="{x:Type ContentControl}">
                <StackPanel Orientation="Vertical">
                    <ContentPresenter />
                    <TextBlock Text="how come this one - placed in the template - is not green?" />
                </StackPanel>
            </ControlTemplate>
        </ContentControl.Template>
        <TextBlock Text="inside ContentControl with a template, this one is green as well" />
    </ContentControl>

</StackPanel>

Is there a way - besides duplicating the Style in StackPanel.Resources to ControlTemplate.Resources - to make the TextBlock inside that ControlTemplate find the defined style?
Thanks...

A: WPF considers ControlTemplates to be a boundry, and will not apply implicit styles (styles without an x:Key) inside of templates.
But there is one exception to this rule: anything that inherits from Control will apply implicit styles.
So you could use a Label instead of a TextBlock, and it would apply the implicit style defined further up your XAML hierarchy, however since TextBlock inherits from FrameworkElement instead of Control, it won't apply the implicit style automatically and you have to add it manually.
My most common way to get around this is to add an implicit style in the ControlTemplate.Resources that is BasedOn the existing implicit TextBlock style
    <ControlTemplate.Resources>
        <Style TargetType="{x:Type TextBlock}"
               BasedOn="{StaticResource {x:Type TextBlock}}" />
    <ControlTemplate.Resources>

Other common ways of getting around this are:

*

*Place the implicit style in <Application.Resources>. Styles placed here will apply to your entire application, regardless of template boundaries. Be careful with this though, as it will apply the style to TextBlocks inside of other controls as well, like Buttons or ComboBoxes
<Application.Resources>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Foreground" Value="Green" />
    </Style>
</Application.Resources>

*Use a Label instead of a TextBlock since it's inherited from Control, so will apply implicit Styles defined outside the ControlTemplate

*Give the base style an x:Key and use it as the base style for an implicit TextBlock styles inside the ControlTemplate. It's pretty much the same as the top solution, however it's used for base styles that have an x:Key attribute
<Style x:Key="BaseTextBlockStyle" TargetType="{x:Type TextBlock}">
    <Setter Property="Foreground" Value="Green" />
</Style>

...

<ControlTemplate.Resources>
    <Style TargetType="{x:Type TextBlock}"
        BasedOn="{StaticResource BaseTextBlockStyle}" />
<ControlTemplate.Resources>


text:
Q: Better egonomics for TypeScript union-narrowing typeguard function We have a utility in our codebase to generate a typeguard to narrow a discriminated union:
export type ExtractBranchFromUnion<
  UNION,
  DISCRIMINANT extends keyof UNION,
  BRANCH extends UNION[DISCRIMINANT],
> = UNION extends Record<DISCRIMINANT, BRANCH> ? UNION : never;

export function narrow<
  UNION,
  DISCRIMINANT extends keyof UNION,
  BRANCH extends UNION[DISCRIMINANT],
>(
  discriminate: DISCRIMINANT,
  branch: BRANCH,
): (
  item: UNION,
) => item is ExtractBranchFromUnion<UNION, DISCRIMINANT, BRANCH> {
  return (item): item is ExtractBranchFromUnion<UNION, DISCRIMINANT, BRANCH> =>
    item[discriminate] === branch;
}

It can be used easily in a filter call to narrow an array down to a specific union member, however it requires that you remember to add as const after a string literal branch argument, otherwise it infers the type incorrectly and gives you too wide of a result:
type A = {type: 'A'; a: string};
type B = {type: 'B'; b: string};
type SimpleUnion = A | B;
const arr: SimpleUnion[] = [];

// BAD: type is SimpleUnion[]
const badListOfBs = arr.filter(narrow('type', 'B'));

// GOOD: type is B[]
const goodListOfBs = arr.filter(narrow('type', 'B' as const));

While this issue can be partially alleviated with a premade constants,
const Types = {
  'A': 'A',
  'B': 'B',
} as const;

// OKAY: type is B[] but it requires a premade constant
const okayListOfBs = arr.filter(narrow('type', Types.B));

it still doesn't prevent the issue of people forgetting as const with a literal value and getting confused why things don't work (as well as the fact that as const just looks ugly in the example two codeblocks above).
Is there a way to get TS to automatically infer a narrower type when provided with a string literal in narrow as shown above? Or at least a way to get a nice error message to show up?
Playground link for all of the above code.

A: You just need to add extra restriction to Branch generic:
export type ExtractBranchFromUnion<
  Union,
  Discriminant extends keyof Union,
  Branch extends Union[Discriminant],
  > = Union extends Record<Discriminant, Branch> ? Union : never;

export function narrow<
  Union,
  Discriminant extends keyof Union,
  Branch extends Union[Discriminant] & PropertyKey, // <------ change is here
  >(
    discriminate: Discriminant,
    Branch: Branch,
): (
    item: Union,
  ) => item is ExtractBranchFromUnion<Union, Discriminant, Branch> {
  return (item): item is ExtractBranchFromUnion<Union, Discriminant, Branch> =>
    item[discriminate] === Branch;
}

type A = { type: 'A'; a: string };
type B = { type: 'B'; b: string };

type SimpleUnion = A | B;
const arr: SimpleUnion[] = [];

const badListOfBs = arr.filter(narrow('type', 'B')); // B[]
const goodListOfBs = arr.filter(narrow('type', 'A')); // A[]

Playground
I have added this: Branch extends Union[Discriminant] & PropertyKey.
I'd willing to bet that discriminator value should be string | number | symbol
As you might have noticed, I Capitalized all generic names because I found it hard to read. However this is the matter of preferences.

redpajama_set_name: RedPajamaStackExchange


text:
Q: parse.com / iOS - Is there a way to download the whole class object in json format? I am testing parse.com and I am creating an app that needs to work offline.
I would like to download the whole class object in json format in order to save it locally and access the data.
I cannot find any documentation on how to do it using Swift/iOS.
I successfully get the object with a specific ID using:
       var query = PFQuery(className:"TestObject")
       query.getObjectInBackgroundWithId("DuZIpSgjnt") {
            (TestObject: PFObject?, error: NSError?) -> Void in
            if error == nil && TestObject != nil {
                println(TestObject)
            } else {
                println(error)
            }
        }

but not the whole class.
What I would like to retrieve is the same json response that I get using REST Api from curl:
https://api.parse.com/1/classes/GameScore

that returns all my objects in json:

{"results":[{"cheatMode":false,"createdAt":"2015-05-15T15:55:17.782Z","objectId":"IKCmjRVet9","playerName":"Sean Plott","score":1337,"updatedAt":"2015-05-15T15:55:17.782Z"},{"cheatMode":false,"createdAt":"2015-05-15T16:05:51.688Z","objectId":"UOKOZkxaGl","playerName":"Marco xxx","score":9998,"updatedAt":"2015-05-15T16:05:51.688Z"}]}

any help appreciated.
Thank you!

A: If you want to store data persistently, I suggest that you first enable the local datastore, as described below:
Local datastore for Parse iOS
So the operation is basically a fetch then a pin. A fetch looks like:
PFQuery *query = [PFQuery queryWithClassName:@"YourCustomClassName"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *err) {
    if (!err) {
        // Do something with your objects, e.g. pin them for later access.
    }
}];

Pinning just means parse is now storing the pinned data for you locally. you can fetch them later locally by marking you query as such:
[query fromLocalDatastore];


text:
Q: Calculating the median for a data.frame column I have the below data.frame and I would like to identify the median value of the index.
For example, let's consider the below data.farme.
 index t1 t2 t3 t4
   10  1  4  7 10
   20  2  5  8 11
   30  3  6  9  0
   40  0  0  0  0

In the first step, I would like to add up by columns of the data.frame.
index t
10    22
20    26
30    18
40    0

In the second step I would like to identify the median of the index. In doing this I need to order t in increasing order and select the median.
index t
40    0
30    18
10    22
20    26

I know that there is a median function in R but I receive different results.
Sample data:
df<-structure(list(index=c (10,20,30,40),
                   t1 = c(1, 2, 3, 0),
                   t2 = c(4, 5, 6, 0),
                   t3 = c(7, 8,9,  0),
                   t4 = c(10, 11, 0, 0)), row.names = c(NA,4L), class = "data.frame")

df

A: I would try this :
library(data.table)
df <- setDT(df)
df_c <- df[,t:=t1+t2+t3+t4][, .(index, t)]
setorder(df_c, index)
median(df_c$index)

For the median I would actually use a function and apply to the index column.

A: Step 1: use the apply function
df$t<-apply(df[,c("t1","t2","t3","t4")],1,sum)
df
#          index t1 t2 t3 t4  t
#        1    10  1  4  7 10 22
#        2    20  2  5  8 11 26
#        3    30  3  6  9  0 18
#        4    40  0  0  0  0  0

Step 2: sort by column "t" using the order function
df<-df[order(df$t),]
df
  index t1 t2 t3 t4  t
# 4    40  0  0  0  0  0
# 3    30  3  6  9  0 18
# 1    10  1  4  7 10 22
# 2    20  2  5  8 11 26

Step 3 compute the median (I just saw Peter's answer and I agree with him, that the median should be 25):
median(df$index)
# [1] 25


text:
Q: WPF Synchronous animation and UI thread deadlock I'm writing a 3D wpf application using Viewport3D. When user push a button, I must start DoubleAnimation on AxisAngleRotation3D, but it must be done synchronous. I can't do it on animation.Completed, because this animation run the next one and the next one recursively.
ButtonHandler must work on UI thread, because to calculate animation I hardly use Viewport3D.
So I must in UI thread start synchronous animation and after it finished continoue work.
I tried this code, but it cause deadlock:
AxisAngleRotation3D axis;
DoubleAnimation animation;
DependencyProperty dp;

var worker = new Thread(() =>
{
      Dispatcher.CurrentDispatcher.InvokeShutdown();
      Dispatcher.Run();
});

worker.SetApartmentState(ApartmentState.STA);
worker.Start();

AutoResetEvent animationDone = new AutoResetEvent(false);
EventHandler handler = null;
handler = (sender, args) =>
{
     animation.Completed -= handler; // remove self
     animationDone.Set(); // signal completion
};

animation.Completed += handler;

Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
{
      axis.BeginAnimation(dp, animation);
}));

animationDone.WaitOne();

A: Ok, it's just an idea. Why don't you create this animations in few steps. First start first batch of animation and then, when they'll finish run another set of animations. You could synchronize it with some kind of timer.
You can first create list of animations and objects to run in each step and then just invoke them.


text:
Q: pandas printing maximum value found in a column with an f string If I have some made up data... How do I print just the index (date & time stamp) of the maximum value found in a column named Temperature?
import numpy as np
import pandas as pd
np.random.seed(11)

rows,cols = 50000,2
data = np.random.rand(rows,cols)
tidx = pd.date_range('2019-01-01', periods=rows, freq='H')
df = pd.DataFrame(data, columns=['Temperature','Value'], index=tidx)

maxy = df.Temperature.max()
maxDate = df.loc[df['Temperature'].idxmax()]

If I print maxDate there is alot of unwanted info..
print(maxy)
print(maxDate)

This outputs:
0.9999949674183947
Temperature    0.999995
Value          0.518413
Name: 2023-01-06 02:00:00, dtype: float64

Ultimately I am hoping to create an f string that just prints maximum temperature recorded in the dataset is 0.999995 found on 2023-01-06 02:00:00, Without the extra information such as Name: and , dtype: float64 and the Value          0.518413 column... Thanks for any tips & tricks

A: You f string could be:
f'maximum temperature recoded in the dataset is {maxy} found on {maxDate.name}'

Or without maxy:
f'maximum temperature recoded in the dataset is {maxDate.Temperature} found on {maxDate.name}'

Output:
'maximum temperature recoded in the dataset is 0.9999949674183947 found on 2023-01-06 02:00:00'

A: There can be more than 1 entry with the maximum temperature.
maxy = df.Temperature.max()
max_dates = df[df['Temperature'] == maxy].index.astype(str).to_list()
print(f'Max temperature recorded in dataset is {maxy} on {",".join(max_dates)}')

Output:
Max temperature recorded in dataset is 0.9999949674183947 on 2023-01-06 02:00:00


text:
Q: SlideDeck2 Slider stopped working goo.gl/8ib94
Slider at the top of the website is made by SlideDeck2 wordpress plugin. It stopped working suddenly. Anybody has any idea?
I thought;
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>

This might be doing it, but it is not. I took it out of the page, but it still did not work.

A: There are some Javascript errors in your page, and this is one of them.
You are using following script, before jQuery actually loads
jQuery(document).ready(function($){
  $("a[rel*=lightbox]").colorbox({opacity:0.8});
});

So better move below line of code (Google-jQuery library link) from bottom to <head> section
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>


text:
Q: how to resolve Error : for i in range(len(val)): TypeError: object of type 'NoneType' has no len() , it might be silly in my project i have to send a numpy board in Instagram dm , sendMessage() funtion works fine i can send str message but can not send that i have created by numpy , please help me
THANKS in advance
My Code
from time import sleep
import numpy as np
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\Users\\saksh\\Desktop\\codeing\\Projects\\Connect 4\\chrome profiles\\chrome profile - 1")
browser = webdriver.Chrome(options =  options , executable_path = r"C:\Users\saksh\Desktop\codeing\imported items\chromedriver v-90.exe")

ROW_COUNT = 6
COLUMN_COUNT = 7

def create_board():
    board = np.zeros((ROW_COUNT, COLUMN_COUNT))

    return board

def send_board(board):
    board = str(np.flip(board, 0))
    board  = board.replace("0", "")
    board = board.replace("1", "")
    board =  board.replace("2", "⚫")

board = create_board()

def sendMessage(message , browser):
    message_box = browser.find_element_by_css_selector(".ItkAi > textarea:nth-child(1)")
    message_box.send_keys(message)
    message_box.Keys.ENTER

# manually go u any instagram dm
# manually go u any instagram dm
print("manually go u any instagram dm , and press enter")

input("press enter !!")

sleep(5)

sendMessage(send_board(board) , browser)

ERROR
raceback (most recent call last):
File "c:\Users\saksh\Desktop\codeing\Projects\Connect 4\temp1.py", line 46, in
sendMessage(send_board(board) , browser)
File "c:\Users\saksh\Desktop\codeing\Projects\Connect 4\temp1.py", line 35, in sendMessage
message_box.send_keys(message)
File "C:\Users\saksh\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webelement.py", line 478, in send_keys
{'text': "".join(keys_to_typing(value)),
File "C:\Users\saksh\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\common\utils.py", line 150, in keys_to_typing
for i in range(len(val)):
TypeError: object of type 'NoneType' has no len()

A: From the error trace it's quite clear that in this block
def sendMessage(message , browser):
    message_box = browser.find_element_by_css_selector(".ItkAi > textarea:nth-child(1)")
    message_box.send_keys(message)
    message_box.Keys.ENTER

This line
message_box.send_keys(message)

fails since the message is of NoneType.
That means that you passing there a NoneType object.
This is because you are calling this method by
sendMessage(send_board(board) , browser)

but the send_board method doesn't return a value / object.
So you actually send nothing, NoneType object to sendMessage method as a message to be inserted into the message_box element.


text:
Q: Possible to create a dictionary type data structure in VHDL? Essentially what I would like to do, is I will have an std_logic_vector coming into my sub-module, and based upon the first 8 bits of that vector, I want to do certain things.
Essentially this is an opcode. However just feeding this into an ALU won't work, because I have variable length instructions, and also cycles.
For example, I have to different bytes that are jump instructions, one takes 3 cycles, the other 4.
I'd like a way of looking at the first byte of the input vector, and looking up exactly what the instruction is, so that I can set different values that go along with said instruction.
Essentially a dictionary, or a LUT with multiple answers.
So, for example if the first byte is
0x54 I want to look up and see that this is a jump, and takes 4 cycles,  its a direct addresss, and the total length of the instruction is 6 bytes.
Is there a way to do this using a dictionary type structure, or a LUT?
The instruction set I am attempting to incorporate is the 65C816, if that helps.

A: When the key is small, like in this case only 8 bits, then you can use the key directly as address to a memory, and then initialize the memory with whatever results you need from the lookup.  That lookup will only take 1 cycle, and is pretty simple to implement.
For long keys that can't be mapped to memory lookup, it is required to make a complex lookup machine, for example based on hash values of the key and final verification of key match.  That is a much larger design with longer latency.


text:
Q: DateTime - Something not right! Q: Has Salesforce broken away from datetime standards or did datetime standards change or get looser?
I ran this script in Execute Anon:
TimeZone tz =
  UserInfo.getTimeZone();
System.debug(
  'Display name: ' +
  tz.getDisplayName());
System.debug(
  'ID: ' +
  tz.getID());
Datetime zGMT = Datetime.Now();
date dT = zGMT.date();
time tM = zGMT.time();
System.Debug('zGMT: '+zGMT);
System.Debug('zGMT.format : '+zGMT.format());
System.Debug('dT : '+dt);
System.Debug('tM : '+tM);

I got this result:

*

*22:15:14:006 USER_DEBUG [3]|DEBUG|Display name: New Zealand Standard Time

*22:15:14:006 USER_DEBUG [6]|DEBUG|ID: Pacific/Auckland

*22:15:14:007 USER_DEBUG [12]|DEBUG|zGMT : 2017-01-15 09:15:14

*22:15:14:007 USER_DEBUG [13]|DEBUG|zGMT.format : 15/01/2017 10:15 PM

*22:15:14:007 USER_DEBUG [14]|DEBUG|dT : 2017-01-15 00:00:00

*22:15:14:007 USER_DEBUG [15]|DEBUG|tM : 22:15:14.174Z

All of the results returned by Salesforce are correct except line 6.
If the timestamp is going to represent a timezone ALPHA then it should be an "M" for "Mike" or X for Xray as that is the TimeZone I am in, not sure which due to daylight savings time but definately not Z for Zulu or GMT
EXTRA-
I remember about 6 years ago I could insert dates with this format and change the ALPHA at the end to represent my timezone and salesforce would adjust it to GMT for me.
2017-01-15T22:15:14.174M
Any ideas. I really feel like this is a bug.

A: The Date and Time objects are timezone agnostic; they neither carry nor honor timezone information. You can prove this with a simple script:
System.debug(
    DateTime.newInstance(
        Date.today(),
        Time.newInstance(0, 0, 0, 0)));
System.debug(
    DateTime.newInstanceGMT(
        Date.today(),
        Time.newInstance(0, 0, 0, 0)));

In my org, where I'm currently GMT-06:00, I get the following values:
11:04:18.1 (13606970)|USER_DEBUG|[1]|DEBUG|2017-01-15 06:00:00
11:04:18.1 (13646506)|USER_DEBUG|[5]|DEBUG|2017-01-15 00:00:00

As you can see, the first value shows that six hours were added, because I'm in GMT-06:00, and the default debug method outputs GMT all the time, while the second one shows midnight GMT.
You might say that there's a bug with the the system renders the output, because Time is timezone agnostic, but that's the extent of the damage. If you use a Time with newInstance, the time will be appropriate for your configured timezone, while if you use newInstanceGMT, it will be appropriate for the GMT timezone.
Similarly, if you use DateTime.time to get the Time fragment, the Time will be the appropriate hours-minutes-seconds-milliseconds for your configured time zone, while if you use DateTime.timeGMT to get the Time fragment, the Time will be appropriate for the GMT timezone. As a similar demonstration to above:
System.debug(
    DateTime.newInstance(
        Date.today(),
        Time.newInstance(0, 0, 0, 0)).time());
System.debug(
    DateTime.newInstance(
        Date.today(),
        Time.newInstance(0, 0, 0, 0)).timeGMT());

Outputs the following values:
11:14:27.1 (1758565)|USER_DEBUG|[1]|DEBUG|00:00:00.000Z
11:14:27.1 (1791286)|USER_DEBUG|[5]|DEBUG|06:00:00.000Z

As you can see, despite both Time values outputting "Z", the hours, minutes, and seconds are appropriate for the timezone. The first one shows midnight in my configured timezone, while the second shows what time it would be when it is midnight in my timezone in GMT. There's no inconsistency with the logic except for the displayed Z, which shouldn't be there.


text:
Q: UICollectionViewCell drawRect: issues I need to draw a circle in some UICollectionViewCell. Circle with different colored border and background color.
My code.
UICollectionViewController
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    CalendarCell *cell;

    firstDayInMonth = [self dayWeekStart:[self getDateFromItem:dateFromStart section:indexPath.section row:1]];

    if (indexPath.row < firstDayInMonth) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellCalendarEmpty" forIndexPath:indexPath];
    } else {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellCalendar" forIndexPath:indexPath];

    if ([self compareOnlyDate:[self getDateFromItem:dateFromStart section:indexPath.section row:indexPath.item-firstDayInMonth] date2:[self getDateLocaleTimeZone:[NSDate date]]] == 1) {

        cell.bgColor = [UIColor blueColor];
        cell.titleLabel.textColor = [UIColor whiteColor];
        cell.drawCircle = [NSNumber numberWithInt:1];
        toDaySection = indexPath.section;

    } else {

        cell.bgColor = [UIColor whiteColor];
        cell.drawCircle = [NSNumber numberWithInt:0];
        cell.titleLabel.textColor = [UIColor lightGrayColor];
    }

    cell.titleLabel.text = [NSString stringWithFormat:@"%i", indexPath.row-firstDayInMonth+1];

}

return cell;
}

UICollectionViewCell
- (void)drawRect:(CGRect)rect
{

    if ([self.drawCircle integerValue] == 1) {

        [self drawCircl:0.0 end:0.5 color:[UIColor blueColor] bgColor:self.bgColor];
        [self drawCircl:0.5 end:1.0 color:[UIColor redColor] bgColor:self.bgColor];

    }
}

- (void) drawCircl:(float)start end:(float)end color:(UIColor*)color bgColor:(UIColor*)bgColor{

    context = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(context, 0.8);

    CGFloat startAngle = start * 2 * M_PI - M_PI/2;
    CGFloat endAngle = end * 2 * M_PI - M_PI/2;

    CGContextAddArc(context, 15, 15, 14, startAngle, endAngle, NO);

    CGContextSetFillColorWithColor(context, bgColor.CGColor);
    CGContextSetStrokeColorWithColor(context, color.CGColor);
    CGContextDrawPath(context, kCGPathFillStroke);

}

When scrolling, the circle is drawn on different cells. cell.titleLabel is always displayed correctly. Why a circle drawn in the cells where it should not be?

A: The reason cell.titleLabel is always displayed correctly but the custom drawing isn't, is because you are updating the cell.titleLabel each time but the way you have the custom drawing setup, it will only effect newly created cells.
This is because under normal conditions, drawRect: is usually triggered when the view is first added to the screen and made visible. You are reusing cells, thus causing the drawing to remain on the views even when they are being used else where.
You need to add [cell setNeedsDisplay] after you change the cell.drawCircle value. This will cause the cell's drawRect: method to be triggered again.


text:
Q: 10-sized subset with maximal sum less than K Question:
Given an array of floats (size N < 100), find the subset (size M = 10) whose sum is maximal but less than value K.
Example (using ints for simplicity)
INPUT:
array = [1,2,3,4,5,6,7,8,9,10,11,12,13]
K = 60

OUTPUT:
subset = [1,2,3,4,5,6,7,8,10,13] # sum of 59

I've tried searching on G4G, but I haven't found anything that accounts for the subset size of M = 10. I'm trying to solve this with Python 3, but any references or sources would be much appreciated.

A: A good starting point would be to read up on the 0-1 knapsack problem: Given a set of items with corresponding values and weights, and a maximum weight allowance W, find the set of items of maximum value which is within the weight allowance W.
Your problem is the same as this problem, but with all the item values = their weights - so you can just use a solution to the knapsack problem, or maybe (probably) you can make something a bit more time-efficient exploiting this.
Good luck!


text:
Q: Android Eclipse How to display specific data from phpMySql database to list view Hello and good day all,
I have try android eclipse project connect to phpmysql with xampp server. For now i success to get and display all data from mysql database to listview.
But how to only get specific data only. Example :
Name :     Class:   CodeSubject:   SubjectName:
JOHN       2        TBE124
JOHN       2        TKE123
JOHN       2        TZE125
JOHN       2        TDE194
ADAM       2        TAE154
ADAM       2        TQE114
GORGE      2        TGE164
GORGE      2        TCE123
GORGE      2        TBE126
What i want is ListView will show All JOHN data/row/column if spinner select JOHN. If select ADAM then ListView will show All ADAM data/row/column. For my code now, it will show all the data from database. If any have tutorial related please share with me.
I used androidhive tutorial. http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

<?php

 /*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

//here the search value is what you send from the app
if(isset($_GET["matricID"])){

$string_input = $_GET['matricID'];

$result = mysql_query("SELECT * FROM tbl_semester WHERE matricID LIKE '%$matricID%'") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {

// looping through all results
// products node
$response["tbl_semester"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$semester = array();
$semester["pid"] = $row["pid"];
$semester["matricID"] = $row["matricID"];
$semester["code"] = $row["code"];
$semester["course"] = $row["course"];
$semester["point"] = $row["point"];
$semester["crdhour"] = $row["crdhour"];
$semester["grdpoint"] = $row["grdpoint"];
$semester["reattempt"] = $row["reattempt"];
$semester["grd"] = $row["grd"];

// push single product into final response array
array_push($response["tbl_semester"], $semester);
}

// success
$response["success"] = 1;

// echoing JSON response
echo json_encode($response);
} else {

// no products found
$response["success"] = 0;
$response["message"] = "No products found";

// echo no users JSON
echo json_encode($response);
}
}
?>

A: This can be done in two ways:

*

*By Querying mysql database on each spinner selection.

*

*on every selection of the spinner send the request to the database.

*server will return a JSON object, parse that json object and populate the listview

*by this way app load will be less bu the server load will be a bit more.

*By handling all stuff in java file only

*

*make a JSON object corresponding to the key="name": value={all fields related to the name}

*make a logic for looking into this JSON object on the basis of the name for each spinner selection and populate the list view with the value fields corresponding to the key name

*but this will load the app with the data which you may not be needing, because all the names will be loaded with their properties in the JSON object

I suggest you to implement the First method.

A: You need to write a webservice which will get the data from your mysql database and send it to your android app.
Write a php script on your server, get the data, encode it inside a JSON object and send it to your app.
The tutorial you have quoted well describes the way to do it. You can follow the same.
To handle the second part of your question, send the item selected on the spinner to the server via a POST or a GET. Create a query to retrieve the rows using the data sent to the server. Send the retrieved data back to the app the similar way you have done it earlier. Then populate the data received in your ListView.
The same tutorial shows this demonstration as well.
Hope it helps.
You sample php at the server could be something like this
//here the search value is what you send from the app
if(isset($_POST["searchvalue"])){

    $string_input = $_POST['searchvalue'];

    $result = mysql_query("SELECT * FROM TABLENAME WHERE NAME_COLUMN LIKE '%$string_input%'") or die(mysql_error());


text:
Q: How to inject the result of an IO action into a non-IO monadic computation I have a small bit of an architectural problem for which I'd like to see if there's a common pattern or abstraction that can help me. I'm writing a game engine where the user is able to specify a game loop as a monadic computation of the form:
gameLoop :: TimeStep -> a -> Game a

where the Game monad has a bunch of access points for drawing, transforming, and interfacing with the engine in general. Then, I also provide a function that the user calls to run the simulation
runGame :: (TimeStep -> a -> Game a) -> a -> IO a

One of the main design goals of the library was to not make Game an instance of the MonadIO typeclass. This is to prevent the user from shooting themselves in the foot by changing the state of the underlying graphics calls, or loading things when they're not expected. However, there are often use cases where the result of an IO a is useful after the game loop has already begun. In particular, spawning enemies with procedurally generated graphical elements comes to mind.
As a result, I'd like to allow the user to request resources using something similar to the following interface:
data ResourceRequestResult a
  = NotLoaded
  | Loaded a

newtype ResourceRequest a = ResourceRequest {
  getRequestResult :: Game (ResourceRequestResult a)
}

requestResource :: IO a -> Game (ResourceRequest a)

With this, I'd like to fork a thread to load the resource and pass the result to the context of the Game monad and back to the user. The main goal would be that I get to decide when the IO action takes place -- somewhere that I expect it to rather than in the middle of the game loop.
One idea that I had in mind was to place another user-defined monad transformer on top of the Game monad... something like
newtype ResourceT r m a = ResourceT (StateT [ResourceRequest r] m a)

However, I believe that then specifying things in terms of f :: ResourceT r Game a becomes an API nightmare, as I'd have to support any possible combination of monad transformer stacks. Ideally I'd also like to avoid making Game polymorphic in r, as it would increase the verbosity and portability of the underlying Game functions as well.
Does Haskell have any abstractions or idioms for something like this programming pattern? Is what I want not possible?

A: The simplest thing is to use module-level encapsulation. Something like this:
module Game (Game, loadResource) where

data GameState -- = ...
newtype Game = Game { runGame :: StateT GameState IO a }

io :: IO a -> Game a
io = Game . liftIO

loadResource :: IO a -> Game (Game a)
loadResource action = io $ do
    v <- newEmptyMVar
    forkIO (action >>= putMVar v)
    return . io $ takeMVar v

As seen here, you can use the fact that Game can do IO within the Game module without exposing this fact to the rest of the world, exposing only the bits of IO that you consider "safe". In particular, you would not make Game an instance of MonadIO (and it can't be made an instance of MonadTrans as it has the wrong kind). Moreover, the io function and Game constructor are not exported, so the user can't pull an end-run in that way.

A: Monads and especially monad transformers come from trying to build complicated programs out of simpler pieces. An additional transformer for the new responsibility is an idiomatic way of handling this problem in Haskell.
There's more than one way to deal with transformer stacks. Since you are already using mtl in your code, I'll assume you are comfortable with the choice of typeclasses for penetrating the transformer stack.
The examples given below are complete overkill for the toy problem. This whole example is huge - it shows how pieces can come together from monads defined in multiple different ways - in terms of IO, in terms of a transformer like RWST and in terms of free monad from a functor.
An interface
I like complete examples, so we'll start with a complete interface for a game engine. This will be a small collection of typeclasses each representing one responsibility of the game engine. The ultimate goal will be to provide a function with the following type
{-# LANGUAGE RankNTypes #-}

runGame :: (forall m. MonadGame m => m a) -> IO a

As long as MonadGame doesn't include MonadIO a user of runGame can't make use of IO in general. We can still export all of our underlying types and write instances like MonadIO and a user of the library can still be sure they didn't make a mistake as long as they enter the library through runGame. The typeclasses presented here are actually the same as a free monad, and you don't have to choose between them.
If you don't like either the rank 2 type or a free monad for some reason, you can instead make a new type with no MonadIO instance and not export the constructor as in Daniel Wagner's answer.
Our interface will consist of four type classes - MonadGameState for handling state, MonadGameResource for handling resources, MonadGameDraw for drawing, and an overarching MonadGame that includes all the other three for convenience.
The MonadGameState is a simpler version of MonadRWS from Control.Monad.RWS.Class. The only reason to define our own class is so that MonadRWS is still available for someone else to use. MonadGameState needs data types for the games configuration, how it outputs data to draw, and the state maintained.
import Data.Monoid

data GameConfig = GameConfig

newtype GameOutput = GameOutput (String -> String)
instance Monoid GameOutput where
    mempty = GameOutput id
    mappend (GameOutput a) (GameOutput b) = GameOutput (a . b)

data GameState = GameState {keys :: Maybe String}

class Monad m => MonadGameState m where
    getConfig :: m GameConfig
    output    :: GameOutput -> m ()
    getState  :: m GameState
    updateState :: (GameState -> (a, GameState)) -> m a

Resources are handled by returning an action that can be run later to get the resource if it was loaded.
class (Monad m) => MonadGameResource m where
    requestResource :: IO a -> m (m (Maybe a))

I'm going to add another concern to the game engine and eliminate the need for a (TimeStep -> a -> Game a). Instead of drawing by returning a value, my interface will draw by asking for it explicitly. The return of draw will tell us the TimeStep.
data TimeStep = TimeStep

class Monad m => MonadGameDraw m where
    draw :: m TimeStep

Finally, MonadGame will require instances for the other three type classes.
class (MonadGameState m, MonadGameDraw m, MonadGameResource m) => MonadGame m

Default definitions for transformers
It's easy to provide default definition of all four type classes for monad transformers. We'll add defaults to all three classes.
{-# LANGUAGE DefaultSignatures #-}

class Monad m => MonadGameState m where
    getConfig :: m GameConfig
    output    :: GameOutput -> m ()
    getState  :: m GameState
    updateState :: (GameState -> (a, GameState)) -> m a

    default getConfig :: (MonadTrans t, MonadGameState m) => t m GameConfig
    getConfig = lift getConfig

    default output :: (MonadTrans t, MonadGameState m) => GameOutput -> t m ()
    output = lift . output

    default getState :: (MonadTrans t, MonadGameState m) => t m GameState
    getState = lift getState

    default updateState :: (MonadTrans t, MonadGameState m) => (GameState -> (a, GameState)) -> t m a
    updateState = lift . updateState

class (Monad m) => MonadGameResource m where
    requestResource :: IO a -> m (m (Maybe a))

    default requestResource :: (Monad m, MonadTrans t, MonadGameResource m) => IO a -> t m (t m (Maybe a))
    requestResource = lift . liftM lift . requestResource
class Monad m => MonadGameDraw m where
    draw :: m TimeStep

    default draw :: (MonadTrans t, MonadGameDraw m) => t m TimeStep
    draw = lift draw

I know that I plan on using RWST for state, IdentityT for resources, and FreeT for drawing, so we'll provide instances for all of those transformers now.
import Control.Monad.RWS.Lazy
import Control.Monad.Trans.Free
import Control.Monad.Trans.Identity

instance (Monoid w, MonadGameState m) => MonadGameState (RWST r w s m)
instance (Monoid w, MonadGameDraw m) => MonadGameDraw (RWST r w s m)
instance (Monoid w, MonadGameResource m) => MonadGameResource (RWST r w s m)
instance (Monoid w, MonadGame m) => MonadGame (RWST r w s m)

instance (Functor f, MonadGameState m) => MonadGameState (FreeT f m)
instance (Functor f, MonadGameDraw m) => MonadGameDraw (FreeT f m)
instance (Functor f, MonadGameResource m) => MonadGameResource (FreeT f m)
instance (Functor f, MonadGame m) => MonadGame (FreeT f m)

instance (MonadGameState m) => MonadGameState (IdentityT m)
instance (MonadGameDraw m) => MonadGameDraw (IdentityT m)
instance (MonadGameResource m) => MonadGameResource (IdentityT m)
instance (MonadGame m) => MonadGame (IdentityT m)

Game state
We plan on building the game state from RWST, so we'll make GameT a newtype for RWST. This allows us to attach our own instances like MonadGameState. We'll derive as many classes as we can with GeneralizedNewtypeDeriving.
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

-- Monad typeclasses from base
import Control.Applicative
import Control.Monad
import Control.Monad.Fix
-- Monad typeclasses from transformers
import Control.Monad.Trans.Class
import Control.Monad.IO.Class
-- Monad typeclasses from mtl
import Control.Monad.Error.Class
import Control.Monad.Cont.Class

newtype GameT m a = GameT {getGameT :: RWST GameConfig GameOutput GameState m a}
    deriving (Alternative, Monad, Functor, MonadFix, MonadPlus, Applicative,
              MonadTrans, MonadIO,
              MonadError e, MonadCont,
              MonadGameDraw)

We'll also provide the underivable instance for MonadGameResource and a convenience function equivalent to runRWST
instance (MonadGameResource m) => MonadGameResource (GameT m)

runGameT :: GameT m a -> GameConfig -> GameState -> m (a, GameState, GameOutput)
runGameT = runRWST . getGameT

This lets us get to the meat of providing MonadGameState which just passes everything off onto RWST.
instance (Monad m) => MonadGameState (GameT m) where
    getConfig   = GameT ask
    output      = GameT . tell
    getState    = GameT get
    updateState = GameT . state

If we just added MonadGameState to something that already provided support for resources and drawing we just made a MonadGame.
instance (MonadGameDraw m, MonadGameResource m) => MonadGame (GameT m)

Resource handling
We can handle resources with IO and MVars as in jcast's answer. We'll make a transformer just so we have a type to attach an instance for MonadGameResource to. This is total overkill. To add overkill to overkill, I'm going to newType IdentityT just to get its MonadTrans instance. We'll derive everything we can.
newtype GameResourceT m a = GameResourceT {getGameResourceT :: IdentityT m a}
    deriving (Alternative, Monad, Functor, MonadFix, Applicative,
              MonadTrans, MonadIO,
              MonadError e, MonadReader r, MonadState s, MonadWriter w, MonadCont,
              MonadGameState, MonadGameDraw)

runGameResourceT :: GameResourceT m a -> m a
runGameResourceT = runIdentityT . getGameResourceT

We'll add an instance for MonadGameResource. This is exactly the same as the other answers.
gameResourceIO :: (MonadIO m) => IO a -> GameResourceT m a
gameResourceIO = GameResourceT . IdentityT . liftIO

instance (MonadIO m) => MonadGameResource (GameResourceT m) where
    requestResource a = gameResourceIO $ do
        var <- newEmptyMVar
        forkIO (a >>= putMVar var)
        return (gameResourceIO . tryTakeMVar $ var)

If we just added resource handling to something that already supported drawing and state, we have a MonadGame
instance (MonadGameState m, MonadGameDraw m, MonadIO m) => MonadGame (GameResourceT m)

Drawing
Like Gabriel Gonzales pointed out, "You can purify any IO interface mechanically". We'll use this trick to implement MonadGameDraw. The only drawing operation is to Draw with a function from the TimeStep to what to do next.
newtype DrawF next = Draw (TimeStep -> next)
    deriving (Functor)

Combined with the free monad transformer, this is the trick I'm using to eliminate the need for a (TimeStep -> a -> Game a). Our DrawT transformer that adds drawing responsibility to a monad with FreeT DrawF.
newtype DrawT m a = DrawT {getDrawT :: FreeT DrawF m a}
    deriving (Alternative, Monad, Functor, MonadPlus, Applicative,
              MonadTrans, MonadIO,
              MonadError e, MonadReader r, MonadState s, MonadWriter w, MonadCont,
              MonadFree DrawF,
              MonadGameState)

Once again we'll define the default instance for MonadGameResource and another convenience function.
instance (MonadGameResource m) => MonadGameResource (DrawT m)

runDrawT :: DrawT m a -> m (FreeF DrawF a (FreeT DrawF m a))
runDrawT = runFreeT . getDrawT

The MonadGameDraw instance says we need to Free (Draw next) where the next thing to do is return the TimeStamp.
instance (Monad m) => MonadGameDraw (DrawT m) where
    draw = DrawT . FreeT . return . Free . Draw $ return

If we just added drawing to something that already handles state and resources, we have a MonadGame
instance (MonadGameState m, MonadGameResource m) => MonadGame (DrawT m)

The game engine
Drawing and the game state interact with each other - when we draw we need to get the output from the RWST to know what to draw. This is easy to do if GameT is directly under DrawT. Our toy loop is very simple; it draws the output and reads lines from the input.
runDrawIO :: (MonadIO m) => GameConfig -> GameState -> DrawT (GameT m) a -> m a
runDrawIO cfg s x = do
    (f, s, GameOutput w) <- runGameT (runDrawT x) cfg s
    case f of
        Pure a -> return a
        Free (Draw f) -> do
            liftIO . putStr . w $ []
            keys <- liftIO getLine
            runDrawIO cfg (GameState (Just keys)) (DrawT . f $ TimeStep)

From this we can define running a game in IO by adding GameResourceT.
runGameIO :: DrawT (GameT (GameResourceT IO)) a -> IO a
runGameIO = runGameResourceT . runDrawIO GameConfig (GameState Nothing)

Finally, we can write runGame with the signature we've wanted from the beginning.
runGame :: (forall m. MonadGame m => m a) -> IO a
runGame x = runGameIO x

Example
This example requests the reverse of the last input after 5 seconds and displays everything that has data available each frame.
example :: MonadGame m => m ()
example = go []
    where
        go handles = do
            handles <- dump handles
            state <- getState
            handles <- case keys state of
                Nothing -> return handles
                Just x  -> do
                    handle <- requestResource ((threadDelay 5000000 >>) . return . reverse $ x)
                    return ((x,handle):handles)
            draw
            go handles
        dump [] = return []
        dump ((name, handle):xs) = do
            resource <- handle
            case resource of
                Nothing -> liftM ((name,handle):) $ dump xs
                Just contents -> do
                    output . GameOutput $ (name ++) . ("\n" ++) . (contents ++) . ("\n" ++)
                    dump xs

main = runGameIO example

A: You probably want to look up MVars: http://hackage.haskell.org/package/base-4.7.0.1/docs/Control-Concurrent-MVar.html.
tryReadMVar :: MVar a -> IO (Maybe a)

gives you your ResourceRequest, and
putMVar :: MVar a -> a -> IO ()

can be used to press the result at the end of the thread.  Something like (ignoring newtypes etc.):
requestResourceImpl :: IO a -> IO (IO (Maybe a))
requestResourceImpl a = do
    mv <- newEmptyMVar
    forkIO $ do
        x <- a
        putMVar mv x
    return $ tryReadMVar mv

This doesn't handle cases where a throws exceptions etc; if a does throw an exception, your resulting ResourceRequest will simply never report the resource as being available.
I strongly recommend making GameMonad an abstract type.  You can make it a newtype (you can add deriving MonadReader etc. if necessary).  Then you don't export its constructor; instead, define abstract operations like requestResource and export them instead.


text:
Q: Responsive Photoswipe Photoswipe is responsive. But i can't get mine to look good in mobile.
First image is my version second from the demo.
I Copied the gallery code from demo.
This is link to my project: http://madeleinepersson.net/Photoswipe

    <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

    <button class="pswp__button pswp__button--share" title="Share"></button>

    <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

    <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button>

A: This is not specific to PhotoSwipe. Your sample page is not a valid HTML document, there is no doctype, no html, head or body element. You need to fix that first.
You should add the viewport meta element to your page. Using the one line of code below, the viewport's width is set to the device width, not to some larger value used by mobile browsers to make websites look "ok" that are not prepared for mobile, like yours right now. Add this to your head element and your page should look like the demo:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

A: I also see that your photos are in landscape mode, so the image will appear as such when viewed in portrait mode on mobile device. You can combine portrait orientation images to fill whole frame on site.


text:
Q: bad math or bad programming, maybe both? I'm writing a Python program to generate the Luna Free State flag from the famous Heinlein novel The Moon is a Harsh Mistress, as a personal project. I've been cribbing heraldry rules and matching mathematical formulas off the web, but something is clearly wrong in my bendsinister routine, since the assertion fails when uncommented. The area of the bend sinister should be 1/3 the total area of the flag, and it isn't. The only really dodgy thing I've done is to guess at the formula for the height of the trapezoid, but I guess the errors could be anywhere. I've trimmed out most of the code, leaving only what's necessary to show the problem. Hopefully someone less mathematically-challenged can spot the error!
#!/usr/bin/python
'generate bend sinister according to rules of heraldry'
import sys, os, random, math, Image, ImageDraw
FLAG = Image.new('RGB', (900, 600), 'black')
CANVAS = ImageDraw.Draw(FLAG)
DEBUGGING = True

def bendsinister(image = FLAG, draw = CANVAS):
 '''a bend sinister covers 1/3 of the field, sinister chief to dexter base

    (some sources on the web say 1/5 of the field, but we'll use 1/3)
    the "field" in this case being the area of the flag, so we need to
    find a trapezoid which is 1/6 the total area (width * height).

    we need to return only the width of the diagonal, which is double
    the height of the calculated trapezoid
 '''
 x, y = image.size
 b = math.sqrt((x ** 2) + (y ** 2))
 A = float(x * y)
 debug('%d * %d = %d' % (x, y, A))
 H = triangle_height(A / 2, b)  # height of triangular half of flag
 width = trapezoid_height(b, H, A / 6) * 2
 if command == 'bendsinister':
  show_bendsinister(x, y, width, image, draw)
 return width

def show_bendsinister(x, y, width, image = FLAG, draw = CANVAS):
 'for debugging formula'
 dexter_base, sinister_chief = (0, y), (x, 0)
 draw.line((dexter_base, sinister_chief), 'blue', int(width))
 image.show()
 debug(image.getcolors(2))  # should be twice as many black pixels as blue

def triangle_height(a, b):
 'a=bh/2'
 h = float(a) / (float(b) / 2)
 debug('triangle height: %.2f' % h)
 return h

def trapezoid_height(b, H, a):
 '''calculate trapezoid height (h) given the area (a) of the trapezoid and
    base b, the longer base, when it is known that the trapezoid is a section
    of a triangle of height H, such that the top, t, equals b when h=0 and
    t=0 when h=H. h is therefore inversely proportional to t with the formula
    t=(1-(h/H))*b, found simply by looking for what fit the two extremes.
    the area of a trapezoid is simply the height times the average length of
    the two bases, b and t, i.e.: a=h*((b+t)/2). the formula reduces
    then to (2*a)/b=(2*h)+(h**2)/H, which is the quadratic equation
    (1/H)*(h**2)+(2*h)-((2*a)/b)=0; solve for h using the quadratic formula
 '''
 try:
  h = (-2 + math.sqrt(4 - 4 * (1.0 / H) * -((2 * a) / b))) / (2 * (1.0 / H))
  debug('trapezoid height with plus: %.2f' % h)
 except:  # must be imaginary, so try minus instead
  h = (-2 - math.sqrt(4 - 4 * (1.0 / H) * -((2 * a) / b))) / (2 * (1.0 / H))
  debug('trapezoid height with minus: %.2f' % h)
 t = (1 - (float(h) / H)) * b
 debug('t=%d, a=%d, check=%d' % (t, round(a), round(h * ((b + t) / 2))))
 #assert round(a) == round(h * ((b + t) / 2))
 return h

def debug(message):
 if DEBUGGING:
  print >>sys.stderr, message

if __name__ == '__main__':
 command = os.path.splitext(os.path.basename(sys.argv[0]))[0]
 print eval(command)(*sys.argv[1:]) or ''

Here is the debugging output, showing I'm far off from the 1/3 area:

jcomeau@intrepid:~/rentacoder/jcomeau/tanstaafl$ ./bendsinister.py
900 * 600 = 540000
triangle height: 499.23
trapezoid height with plus: 77.23
t=914, a=90000, check=77077
[(154427, (0, 0, 255)), (385573, (0, 0, 0))]
154.462354191

Here is an image of the output, with some added lines:

The red line divides the two triangles, either can be used for the calculation of the trapezoid. I'm using the one starting at the top left. The green line is the height of that triangle, the variable H in the program.

For the finished script and flag (using the correction supplied by Michael Anderson), see http://unternet.net/tanstaafl/. Thanks all for the help!

A: Break the rectangle into two triangles. They will be identical.
The Black triangle + Blue Trapezoid is Triangle A.
The Black Triangle on its own is Triangle B
Triangle A and Triangle B are similar triangles so their area is related by the square of the scale factor relating them.
We want the Blue Trapezoid to be one third of the area of Triangle A. (This way the bend will take one third of the overall rectangle). This means that Triangle B must be 2/3 area of Triangle A. Thus the scalefactor must be sqrt(2/3).
You should then be able to convert this to give you the coordinates of the bend geometry pretty easily.

A: I executed the following code in an IDLE session
from PIL import Image, ImageDraw
from math import sqrt

'generate bend sinister according to rules of heraldry'
import sys, os, random, math
FLAG = Image.new('RGB', (900, 600), 'black')
CANVAS = ImageDraw.Draw(FLAG)
DEBUGGING = True

def debug(message):
    if DEBUGGING:
        print >>sys.stderr, message

def show_bendsinister(x, y, width, image = FLAG, draw = CANVAS):
 'for debugging formula'
 dexter_base, sinister_chief = (0, y), (x, 0)
 print 'dexter_base==',dexter_base,'sinister_chief==',sinister_chief
 draw.line((dexter_base, sinister_chief), 'blue', int(width))
 image.show()
 debug(image.getcolors(2))  # should be twice as many black pixels as blue

def trapezoid_height(x, y, P):
 '''Given a rectangle whose width and length are (x) and (y)

The half of this rectangle is a large triangle A
whose base (b) is the diagonal of the rectangle
and its height (H) goes from its base (b) to
the right angle of the large triangle.
(x) and (y) are the side-lengths of the triangle.
The area of this large triangle is (x*y)/2 = (H*b)/2

Given a trapezoid whose base is the diagonal (b) of the rectangle
and base (b) of the large triangle, its height is (h)
and its top is (t).
Given (S) as the area of the trapezoid.
In general, the trapezoid is disymtric because the triangle have x != y.
So the area is S = h*(b + t)/2

This function trapezoid_height() calculates the height (h) of the trapezoid
in order that the trapezoid have an area (S) which must be
the percentage (P) of the area of the large triangle A. So:
h*(b + t)/2 = S = P*[H*b /2]  ==> h*(b + t) = P*H*b
==> h*t = P*H*b - h*b ==> h*t*(H-h) = [P*H - h]*b*(H-h)

The large triangle is the sum of the trapezoid and of a little triangle B
having an height equal to (H-h) and a base which is the top (t)
of the trapezoid.
The area of this little triangle B is t*(H-h)/2 and must be equal to (1-P)*[H*b / 2]
==> t*(H-h) = (1-P)*H*b ==> h*t*(H-h) = h*(1-P)*H*b

From h*t*(H-h) = [P*H - h]*b*(H-h)  and  h*t*(H-h) = h*(1-P)*H*b
we obtain [P*H - h]*b*(H-h) = h*(1-P)*H*b
==> b*h**2 - (b*H + xy)*h + P*x*y*H = 0
==> h**2 - 2*H*h + P*(H**2) = 0
That leads to the solution H*(1 - sqrt(1-P)), the other H*(1 + sqrt(1-P))
being bigger than H
'''

 H = math.sqrt( (x*x*y*y) / (x*x + y*y) )
 return H*(1 - sqrt(1-P))

def bendsinister(image = FLAG, draw = CANVAS):
 '''a bend sinister covers 1/3 of the field, sinister chief to dexter base

    (some sources on the web say 1/5 of the field, but we'll use 1/3)
    the "field" in this case being the area of the flag, so we need to
    find a trapezoid which is 1/6 the total area (width * height).

    we need to return only the width of the diagonal, which is double
    the height of the calculated trapezoid
 '''
 x, y = image.size
 print 'x ==',x,'y ==',y
 percentage = float(1)/3
 width = 2 * trapezoid_height(x, y , percentage)
 print 'height ==',width/2
 print 'width==',width

 if command == 'bendsinister':
  show_bendsinister(x, y, width, image, draw)
 return width

command = 'bendsinister'
print bendsinister()

result
x == 900 y == 600
height == 91.6103029364
width== 183.220605873
dexter_base== (0, 600) sinister_chief== (900, 0)
[(180340, (0, 0, 255)), (359660, (0, 0, 0))]
183.220605873

The blue stripe displayed doesn't give the impression to be 1/3 of the field's area, but the numbers speak:
359660 / 180340 = 1.994344


text:
Q: Sticky shift key Is there a way to get "sticky" shift, so that I can (sequentially) type

*

*shift, 5 to get %

*shift, 3 to get #

*shift, r to get R
There's shift lock in X11, but that doesn't cancel after producing a shifted character.

A: Your requirement forms part of the AccessX accessibility features that has been packaged for X11 into the xkbset command which you should be able to find in the package of the same name.
The usage is
xkbset sticky twokey

After this, every time you press and release the Shift key, the following single typed character will be shifted. It applies similarly to the Control key.  To cancel the action use
xkbset -sticky twokey


text:
Q: Undetermined error on Java WS with play framework 2.6.x when trying to connect to a web service, according to SOAP UI on the image below, I receive an indeterminate error (handshake_failure)

Could you tell me the source of the error please? thank you
This is my code on play framework 2.6.x
public CompletionStage<Result> index() {

    final JsonNode task = Json.newObject()
                              .put("idPartenaire"   , "CETEMCO")
                              .put("password"       , "CETEMCO@2020")
                              .put("hmac"           , "5f35c3a156fd71c96961467a945016e22e3c9f34ff17ce4a07728fc9d4e4f645")
                              .put("message"        , "TEST-MESSAGE")
                              .put("messageType"    , "TEST-MESSAGE-TYPE");

    final CompletionStage<WSResponse> eventualResponse = ws.url("https://test.portnet.ma/portnet/PortnetMessageReceiverService?wsdl")
                                                           .post(task);

    return eventualResponse.thenApplyAsync(response ->
                ok(response.asJson())
                ,httpExecutionContext.current());
}


text:
Q: Change style of output with LINQ, GroupBy I have this DotNetFiddle.
Code:
using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        // create Questions

        var questionOne = new Question(){QuestionId = 1, ActualQuestion = "Who"};
        var questionTwo = new Question(){QuestionId = 2, ActualQuestion = "What"};
        var questionThree = new Question(){QuestionId = 3, ActualQuestion = "Where"};

        // Assign questions to the specified list of questions

        var applicationOneQuestions = new List<Question>(){questionOne, questionTwo, questionThree};
        var applicationTwoQuestions = new List<Question>() {questionOne, questionTwo};
        var applicationThreeQuestions = new List<Question>() {questionOne, questionThree};
        var applicationFourQuestions = new List<Question>() {questionOne};

        // Create Applications

        var applicationOne = new Application(){AppId = 1, Questions = applicationOneQuestions};
        var applicationTwo = new Application(){AppId = 2, Questions = applicationTwoQuestions};
        var applicationThree = new Application() {AppId = 3, Questions = applicationThreeQuestions};
        var applicationFour = new Application() {AppId = 4, Questions = applicationFourQuestions};

        // Create List of Applications

        var lstApplications = new List<Application>(){applicationOne, applicationTwo, applicationThree, applicationFour};

        // Group Applications based on Questions

        var groupApplications = lstApplications.GroupBy(x => x.Questions).Select(t => new Section { AppIds = t.Select(z => z.AppId).ToList() , Questions = t.Key}).ToList();

        foreach(var item in groupApplications)
        {
            foreach(var appId in item.AppIds)
            {
                Console.WriteLine(appId);

            }

            foreach(var question in item.Questions)
            {
                Console.WriteLine(question.ActualQuestion);
            }

            Console.WriteLine("\n");
        }
    }
}

public class Application
    {
        public int AppId { get; set; }
        public List<Question> Questions { get; set; }
    }

public class Section
       {
            public List<int> AppIds { get; set; }
            public List<Question> Questions { get; set; }
        }

public class Question
{
    public int QuestionId {get;set;}
    public string ActualQuestion {get;set;}
}

Once you run the program, you get an output like so:
1
Who
What
Where

2
Who
What

3
Who
Where

4
Who

Now, I would like to change the output to look like this:
A1, A2, A3, A4 - Who
A1, A2 - What
A1, A3 - Where

Basically,

*

*application 1,2,3,4 all contain question 1 - who

*application 1, 2 contain question 2 - what

*application 1, 3 contain question 3 - where

How do I achieve this output?

A: I'm not quite sure what the method syntax would be, but here's a query syntax that will get you the desired output. I think the trouble you're having in trying to get the method syntax down is likely due to using a Select where you'd want to use a SelectMany.
var questionGroups = from application in lstApplications
                     from question in application.Questions
                     group application.AppId by question.ActualQuestion;

foreach (var question in questionGroups)
    Console.WriteLine($"{string.Join(" ", question.Select(x => $"A{x}"))} - {question.Key}");

A: With query syntax:
var appGroups =
  from app in lstApplications
  from question in app.Questions
  group app by question;

With lambda syntax:
var appGroups = lstApplications
    .SelectMany(app => app.Questions, (app, question) => new { app, question })
    .GroupBy(item => item.question, item => item.app);

Printing the output:
foreach (var appGroup in appGroups)
    Console.WriteLine($"{string.Join(", ", appGroup.Select(app => "A" + app.AppId))} - {appGroup.Key.ActualQuestion}");


text:
Q: autocomplete multiple textboxes based on selected option on dropdown using jquery in php mysql I have a select box that fetches the value from my database, whenever I chose a value from the select box it should show the corresponding data from my database.
For example, If i chose a research, it should show the researcher together with the date started and put it in the two existing textbox.
It is working on my first text box but the second text box is not displaying a value.
Here is my select box that fetches its values from my database;
<select id="sel_research">
<option value="0">- Select-</option>
<?php
$sql_research = "SELECT * FROM tblproposals WHERE ProposalStatus = 'Implemented' ";
$research_data = mysqli_query($con,$sql_research);
while($row = mysqli_fetch_assoc($research_data) ){
$researchid = $row['id'];
$research_name = $row['TitleOfResearch'];
echo "<option value='".$researchid."' >".$research_name."</option>";
}
        ?>
    </select>

Here is my first textbox;
<input type="text" id="author"> //it is working here

Here is my second textbox;
<input type="text" id="datestarted" required>//it is not working here

Here is my jquery;
$(document).ready(function(){
$("#sel_research").change(function(){
var resid = $(this).val();
$.ajax({
url: 'get-researcher.php',
type: 'post',
data: {res:resid},
dataType: 'json',
success:function(response){
var len = response.length;
$("#author").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['Researcher'];
var date_imp = response[i]['DateOfImplementation'];

$("#author").val(name);
$("#datestarted").val(date_imp);
                  }
                }
            });
        });

    });

Here is my "get-researcher.php"
<?php
include "includes/configs.php";
$resid = 0;
if(isset($_POST['res'])){
$resid = mysqli_real_escape_string($con,$_POST['res']);
}

$research_arr = array();
if($resid > 0){
$sql = "SELECT * FROM tblproposals WHERE id='".$resid."' ";
$result = mysqli_query($con,$sql);

while( $row = mysqli_fetch_array($result) ){
$res_id = $row['id'];
$name = $row['Researcher'];
$research_arr[] = array("id" => $res_id, "Researcher" => $name);
  }
}

echo json_encode($research_arr);

I think i need to use the parseJSON but i got lost on where and how to write it.


text:
Q: get the value of a cell in a different worksheet by referring the name of the worksheet contains in some other cell I want to get the value of a cell in a different worksheet by referring the name of the worksheet contains in some other cell.
For an instance, I have this formula to get the value from a cell from another sheet ='Sheet2'!H25. But I want to replace the 'Sheet2' of the formula of a cell contains the text "sheet2".
Cell A25 contains the name of a sheet titled "Sheet2" which I got from the formula =MID(CELL("filename", A1),FIND("]",CELL("filename", A1))+1,31)
So, instead of ='Sheet2'!H25 I tried the formula =INDIRECT("'" A25 & "'!" & H25) But it doesn't work. How to make it work.
P.S: A25 is in the Sheet1 and H25 is in the sheet2

A: You just forgot to double-quote H25 .
Either:
=INDIRECT("'" & A25 & "'" & "!" & "H25")

or
=INDIRECT("'" & A25& "'!H25")

(the second equation combines the various parts after the sheet-name)


text:
Q: Reg: Default Privileges on PostgreSQL Schemas I have a situation where many users can create database objects across all the available schema.
There is a generic user pg_dump_user used for by all the developers to dump the whole database to their local db whenever required. So this user should have read access to all the database objects.
To achieve this, I have tried setting the default privilege at schema level as well as at the user level.
--Default privileges set for each schema
ALTER DEFAULT PRIVILEGES IN SCHEMA xyz GRANT SELECT ON TABLES to ro_user';

--Default privileges set for each user
ALTER DEFAULT PRIVILEGES FOR ROLE abc_user GRANT SELECT ON TABLES to ro_user' ;

Even though above setup is there, after certain times these are getting vanished as the new objects created are not accessible by ro_user.
Any pointer on this would help, my aim is just to achieve select access for all the objects current and future for a user so as to do pg_dump.

A: The documentation about ALTER DEFAULT PRIVILEGES tells you a possible reason - it is not that clearly described, though.
Let's see, what is said:

You can change default privileges only for objects that will be
  created by yourself or by roles that you are a member of.

This means that the default privileges defined by this statement applies only to objects that are created by you (or the role you are a member of).  Let's see this in action!
alice's schema
First, we are logged in as alice.  Then, in a newly created schema, we create a table and grant some rights to bob:
SELECT current_user;
 current_user
──────────────
 alice

SHOW search_path ;
 search_path
──────────────
 test, public

CREATE SCHEMA alicetest;

ALTER DEFAULT PRIVILEGES
    FOR ROLE alice
    IN SCHEMA alicetest
    GRANT ALL ON TABLES TO alice;

GRANT SELECT ON alicetest.a TO bob;
-- this I do only for showing the privileges -
-- the owner has by default ALL and is not shown by \dp

\dp alicetest.a
                             Access privileges
  Schema   │ Name │ Type  │  Access privileges  │ Column access privileges
───────────┼──────┼───────┼─────────────────────┼──────────────────────────
 alicetest │ a    │ table │ alice=arwdDxt/alice↵│
           │      │       │ bob=r/alice         │

alice now has all rights on her table, as expected.
bob' table in the same schema
Now, after obtaining access to this schema, bob tries to create a table:
SELECT current_user;
 current_user
──────────────
 bob

CREATE TABLE alicetest.b (id integer);

GRANT SELECT ON alicetest.b TO alice;

\dp alicetest.b
                            Access privileges
  Schema   │ Name │ Type  │ Access privileges │ Column access privileges
───────────┼──────┼───────┼───────────────────┼──────────────────────────
 alicetest │ b    │ table │ bob=arwdDxt/bob  ↵│
           │      │       │ alice=r/bob       │

As you can see, despite creating the table in alice's schema where she set the default privileges, bob's table doesn't have all those permissions.  This happens because alice is not a member of bob.
Let's check this membership thing, too, and try to define default privileges by alice again, this time for another role:
ALTER DEFAULT PRIVILEGES
    FOR ROLE charlie
    IN SCHEMA alicetest
    GRANT ALL ON TABLES TO alice;
ERROR:  must be member of role "charlie"

So, some mighty enough user grants her a membership in charlie, then she tries again, with success:
ALTER DEFAULT PRIVILEGES
    FOR ROLE charlie
    IN SCHEMA alicetest
    GRANT ALL ON TABLES TO alice;
ALTER DEFAULT PRIVILEGES

charlie's round
Then charlie creates a new table:
CREATE TABLE alicetest.c (id integer);

And the privileges:
\dp alicetest.c
                               Access privileges
  Schema   │ Name │ Type  │    Access privileges    │ Column access privileges
───────────┼──────┼───────┼─────────────────────────┼──────────────────────────
 alicetest │ c    │ table │ charlie=arwdDxt/charlie↵│
           │      │       │ alice=arwdDxt/charlie   │

As you see, alice, as a member of charlie, gets her access to this table.
To answer your question,
I guess you defined the default privileges for yourself (alice in the example), but you developers act as a bunch of bobs here, not getting the necessary privileges.  One way to get around this (as we do it at work) is to do a
SET ROLE TO schema_owner;

every time before creating a new object in the schema.  This should be a role that all developers are a member of (otherwise you'd get an error).
NOTE that \dp is a psql command.

A:
I don't think it is possible to do what you want in a single command.

Your First Command
--Default privileges set for each schema
ALTER DEFAULT PRIVILEGES IN SCHEMA xyz GRANT SELECT ON TABLES to ro_user';

This doesn't work because it only sets this default for the user who issues the command. And as you said, "many users can create database objects across all the available schema." Hence, each one would have to set this default (on each schema). Or a superuser could set it for each of them as you tried next.

Your Second Command
--Default privileges set for each user
ALTER DEFAULT PRIVILEGES FOR ROLE abc_user GRANT SELECT ON TABLES to ro_user'

;
This should work, but it might appear as if it is decaying over time if you are adding new users (and not setting this). Are you sure that default permissions stopped working for new tables created (and owned) by a user where you set this?
Did you run \ddp in psql to see default privileges? Did they have them set originally and then not set later or was it that later (even with it set) it didn't go grant the privileges to ro_user?

What I wish worked (and think you want)
-- set default privileges for a whole team to deliver a specific schema to another whole team
ALTER DEFAULT PRIVILEGES FOR ROLE engineering IN SCHEMA GRANT SELECT ON TABLES to analytics;

The key concept here is that I want every user in the engineering team to inherit these default privileges so that every table one of them creates is readable by every member of reporting. But defaults are not inherited like this. This surprised me because the permissions are inherited by every member of reporting. So, the only way is as you did above, setting the defaults for every user that creates tables.
I only mention this in case that is why the default privileges appeared to decay - i.e. if you assumed (like me) that the defaults would be inherited by members of the table-creating role.


text:
Q: Group by with results If I have this table:
UserID | Score1 | Score2
1      | 10     | 5
2      | 50     | 15
3      | 30     | 25
1      | 50     | 10
2      | 0      | 100
3      | 1      | 5

I want to sort this table to score1+score2, but I also want to get the seperate scores back.
But it has to be grouped by userId, and only returning the highest score of the user (so MAX score1+score2).
But I cannot do a group by because then I will rule out users with same scores. This is a headbreaker for me...
From above table the result should be:
UserID | Score1 | Score2 | TotalScore
2      | 0      | 100    | 100
1      | 50     | 10     | 60
3      | 30     | 25     | 55

A: SELECT UserID, Score1, Score2, Score1 + Score2 AS "Total"
FROM myTable
ORDER BY Score1 + Score2 DESC

you don't need a GROUP BY because it's not an aggregate function, it's just a calculated column.
Edit
You need to do a join on your max total score and your user id after you've grouped.  Here's an example with a common table expression:
WITH maxScores AS (
    SELECT UserID AS "id", MAX(Score1 + Score2) AS "total"
    FROM scores
    GROUP BY UserID
)
SELECT s.UserID, s.Score1, s.Score2, s.Score1 + s.Score2 AS "Total"
FROM scores s
JOIN maxScores m ON s.UserID = m.id
    AND s.Score1 + s.Score2 = m.Total

A: select UserID, Score1, Score2
    from YourTable
    order by Score1 + Score2

A: Are you looking something like this?
declare @t table( id int, s1 int, s2 int)

insert into @t (id, s1, s2) values (0, 10, 5)
insert into @t (id, s1, s2) values (1, 50, 15)
insert into @t (id, s1, s2) values (2, 20, 25)
insert into @t (id, s1, s2) values (1, 30, 0)

select id, s1, s2, (s1+s2) as 'total' from @t order by (s1+s2) desc, id asc

1   50  15  65
2   20  25  45
1   30  0   30
0   10  5   15

A: So then, is this what you want?
declare @t table( id int, s1 int, s2 int)

insert into @t (id, s1, s2) values (0, 10, 5)
insert into @t (id, s1, s2) values (1, 50, 15)
insert into @t (id, s1, s2) values (2, 30, 25)
insert into @t (id, s1, s2) values (1, 40, 0)

select id, MAX(s1) max_s1, MAX(s2) max_s2, SUM(total) total from
(select id, s1, s2, (s1+s2) as 'total' from @t) a
group by id
order by total

I'm afraid you really did not specify what you want to do with s1 and s2 after grouping the rows with same id ...

A: How about this?
SELECT Q1.UserID, Q1.Score1, Q1.Score2, Q1.Total
FROM (SELECT UserID, Score1, Score2, (Score1+Score2) AS Total
    FROM myTable) AS Q1,
(SELECT UserId, Max(Score1 + Score2) As Total FROM myTable GROUP BY UserId) As Q2
WHERE Q1.UserId=Q2.UserId AND Q1.Total=Q2.Total
ORDER BY 4 DESC, 1

A: Does this answer it? Presuming that you would want to include duplicates of the same score1 + score2 for the same id (if not change the DENSE_RANK to ROW_NUMBER)
create table #data (id int,score1 int, score2 int)
insert into #data Values (0,10,5)
insert into #data Values (1,50,15)
insert into #data Values (2,30,25)
insert into #data Values (1,40,0)

** edit for sorting as per question revision**
;with scores AS
(
SELECT
id
,score1
,score2
,DENSE_RANK() OVER (PARTITION BY id ORDER BY score1 + score2 DESC) AS score_rank
FROM #data
)
SELECT
id
,score1
,score2
,score1 + score2 AS sum_
FROM scores where score_rank = 1
ORDER BY score1 + score2 DESC


text:
Q: knockout js subscribing to select list selected option is showing undefined repeatedly I have I drop down list prepopulated with a list of strings. My select list binding is like so:
<select id="industryDropDown"
    data-bind="options: $root.orgIndustrySuggestions, value: $root.selectedIndustryTag, optionsCaption: ''"></select>

In my viewmodel I have this:
self.selectedIndustryTag.subscribe(function (newValue) {
    if (newValue !== '') {
        if (newValue !== 'undefined')
            {
        alert(self.selectedIndustryTag());
        self.selectedIndustryTag('');
        }
    }
}, self);

I am trying to get the selected value from the drop down list, do something where the alert() is now, and then reset the selected value to the default empty string option.
Currently when I run this, page load is fine. But when I select something it will show me the selected value the first time, but them throw up a kajillion (i counted) alerts saying 'undefined' after that.

A: You are over complicating your logic for one.  Create a fiddle demonstrating your error and we could probably show you why, but in a nutshell you have a recursive loop (you are subscribing to a value and setting it inside of that function) and you are also testing multiple times when you don't need to -
self.selectedIndustryTag.subscribe(function (newValue) {
    if (newValue) {
        alert(self.selectedIndustryTag());
         // The next line will refire the subscription
         //self.selectedIndustryTag('');
    }
}, self);

The conditional statement - if (newValue) will test whether newValue equals null, undefined, false, or string empty ('')

A: Was that exactly a kajillion? or was it more like ten bajillion?
The reason you have this problem is that you're entering an endless loop. A change to selectedIndustryTag in the UI raises the subscribe. Inside the subscribe you change selectedIndustryTag which raises the subscribe which changes the selectedIndustryTag which.... well you probably get the point.
The way to resolve this is to have 2 properties. The live one edited by the UI, which you can subscribe to, and a second one which you use internally (which the subscribe can update).
Another issue you have, you're using strict non-equality operator !== but comparing to the string 'undefined'. That will never evaluate as you should be comparing against undefined (without quotes).
so change
if (newValue !== 'undefined')

to
if (newValue !== undefined)

Live example: http://jsfiddle.net/2NqFY/


text:
Q: libclang get primitive value How can I get the value of a primitive literal using libclang?
For example, if I have a CXCursor of cursor kind CXCursor_IntegerLiteral, how can I extract the literal value.

UPDATE:
I've run into so many problems using libclang. I highly recommend avoiding it entirely and instead use the C++ interface clang provides. The C++ interface is highly useable and very well documented: http://clang.llvm.org/doxygen/annotated.html
The only purpose I see of libclang now is to generate the ASTUnit object for you as with the following code (it's not exactly easy otherwise):
ASTUnit * astUnit;
{
    index = clang_createIndex(0, 0);
    tu = clang_parseTranslationUnit(
        index, 0,
        clangArgs, nClangArgs,
        0, 0, CXTranslationUnit_None
        );
    astUnit = static_cast<ASTUnit *>(tu->TUData);
}

Now you might say that libclang is stable and the C++ interface isn't. That hardly matters, as the time you spend figuring out the AST with libclang and creating kludges with it wastes so much of your time anyway. I'd just as soon spend a few hours fixing up code that does not compile after a version upgrade (if even needed).

A: Instead of reparsing the original, you already have all the information you need inside the translation unit :
if (kind == CXCursor_IntegerLiteral)
{
    CXSourceRange range = clang_getCursorExtent(cursor);
    CXToken *tokens = 0;
    unsigned int nTokens = 0;
    clang_tokenize(tu, range, &tokens, &nTokens);
    for (unsigned int i = 0; i < nTokens; i++)
    {
        CXString spelling = clang_getTokenSpelling(tu, tokens[i]);
        printf("token = %s\n", clang_getCString(spelling));
        clang_disposeString(spelling);
    }
    clang_disposeTokens(tu, tokens, nTokens);
}

You will see that the first token is the integer itself, the next one is not relevant (eg. it's ; for int i = 42;.

A: If you have access to a CXCursor, you can make use of the clang_Cursor_Evaluate function, for example:
CXChildVisitResult var_decl_visitor(
    CXCursor cursor, CXCursor parent, CXClientData data) {
  auto kind = clang_getCursorKind(cursor);

  switch (kind) {
  case CXCursor_IntegerLiteral: {
    auto res = clang_Cursor_Evaluate(cursor);
    auto value = clang_EvalResult_getAsInt(res);
    clang_EvalResult_dispose(res);

    std::cout << "IntegerLiteral " << value << std::endl;

    break;
  }
  default:
    break;
  }

  return CXChildVisit_Recurse;
}

Outputs:
IntegerLiteral 42

A: I found a way to do this by referring to the original files:
std::string getCursorText (CXCursor cur) {
    CXSourceRange range = clang_getCursorExtent(cur);
    CXSourceLocation begin = clang_getRangeStart(range);
    CXSourceLocation end = clang_getRangeEnd(range);
    CXFile cxFile;
    unsigned int beginOff;
    unsigned int endOff;
    clang_getExpansionLocation(begin, &cxFile, 0, 0, &beginOff);
    clang_getExpansionLocation(end, 0, 0, 0, &endOff);
    ClangString filename = clang_getFileName(cxFile);
    unsigned int textSize = endOff - beginOff;

    FILE * file = fopen(filename.c_str(), "r");
    if (file == 0) {
        exit(ExitCode::CANT_OPEN_FILE);
    }
    fseek(file, beginOff, SEEK_SET);
    char buff[4096];
    char * pBuff = buff;
    if (textSize + 1 > sizeof(buff)) {
        pBuff = new char[textSize + 1];
    }
    pBuff[textSize] = '\0';
    fread(pBuff, 1, textSize, file);
    std::string res(pBuff);
    if (pBuff != buff) {
        delete [] pBuff;
    }
    fclose(file);
    return res;
}

A: You can actually use a combination of libclang and the C++ interface.
The libclang CXCursor type contains a data field which contains references to the underlying AST nodes.
I was able to successfully access the IntegerLiteral value by casting data[1] to the IntegerLiteral type.
I'm implementing this in Nim so I will provide Nim code, but you can likely do the same in C++.
let literal = cast[clang.IntegerLiteral](cursor.data[1])
echo literal.getValue().getLimitedValue()

The IntegerLiteral type is wrapped like so:
type
  APIntObj* {.importcpp: "llvm::APInt", header: "llvm/ADT/APInt.h".} = object
    # https://github.com/llvm-mirror/llvm/blob/master/include/llvm/ADT/APInt.h
  APInt* = ptr APIntObj

  IntegerLiteralObj* {.importcpp: "clang::IntegerLiteral", header: "clang/AST/Expr.h".} = object
  IntegerLiteral* = ptr IntegerLiteralObj

proc getValue*(i: IntegerLiteral): APIntObj {.importcpp: "#.getValue()".}
  # This is implemented by the superclass: https://clang.llvm.org/doxygen/classclang_1_1APIntStorage.html
proc getLimitedValue*(a: APInt | APIntObj): culonglong {.importcpp: "#.getLimitedValue()".}

Hope this helps someone :)


text:
Q: Edges don't show in a graph using Networkx - Python I am plotting a directed graph in python using networkx and matplotlib. However, not all edges are visible. The nodes are so close to each other that it doesn't show a path between two nodes.
Code:
import networkx as nx

resultNodes = ['P0', 'P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'P9']

resultEdges = [('P0', 'P4'), ('P0', 'P2'), ('P0', 'P1'), ('P1', 'P7'), ('P1', 'P8'),
               ('P1', 'P2'), ('P2', 'P3'), ('P4', 'P5'), ('P4', 'P6'), ('P5', 'P6'),
               ('P9', 'P2'), ('P9', 'P7'), ('P9', 'P1')]

G=nx.DiGraph()

G.add_nodes_from(resultNodes)
G.add_edges_from(resultEdges)

print("Nodes of graph: ")
print(G.nodes())
print("Edges of graph: ")
print(G.edges())

nx.draw(G,with_labels=True,font_size=15,node_color='yellowgreen',node_size=1000)

A: You can calculate the positions of the nodes, and pass to the draw function. See the doc.
Example:
pos = nx.drawing.layout.circular_layout(G)

nx.draw(G, pos=pos, with_labels=True, font_size=15,
        node_color='yellowgreen', node_size=1000)


text:
Q: Is there a way to keep my map visible while I walk around? One of the features I really liked in Diablo 2 was the ability to change your map position. You could either keep it in the upper right hand corner or switch it so that it was over-layed on the screen and your character could essentially walk around on top of it. Like this:

Is there a way that I can set my map up like this in Diablo 3? If not exactly like this, is there any option other than keeping it in the upper right hand corner?

A: No, that feature was intentionally taken out by the designers because they wanted to avoid that situation we all know in D2 where we spend about 10% of our time looking at the action and 90% looking at the minimap.
Source:

You are very much correct in your statement that this was a deliberate design choice, Caelestis. We did not want to have the Diablo II scenario where people just stared at a dot on a map to guide themselves through an area. We made the map full screen, completely opaque and prevented commands from being sent while it is open to stop this from occurring. We also like the concept that your character has to take a few moments and stop so that they can get their bearings :)

As a bonus, you can always kind of see what areas you haven't explored yet in the minimap to the upper right of the screen.


text:
Q: Do Lifehacker and Stack Exchange have some sort of partnership? Why is Lifehacker replicating SE questions in full? I love Lifehacker as much as any other fan but I am a bit confused as to how they are creating posts (which do give credit) that mimic SE questions in full.
How Do I Stop My Fire Alarm from Going Off When I Cook? Lifehacker
How do I stop my fire alarm from going off when I cook? Seasoned Advice (cooking.stackexchange.com)
The titles for both posts are the same, so nothing prevents Lifehacker's post from being higher in the rankings (and there should be nothing wrong with that seeing that Lifehacker is a recommended knowledge resource).

The section is labelled "crowdhacker", so I assume the comments stay on Lifehacker, as well as any new answers or critique.
Is this sort of writing style (inasmuch as the cc-wiki allows it) encouraged, or is this some sort of partnership between Stack Exchange and Lifehacker to scratch each other's back?

A: Yes. Stack Exchange does have a new partnership in place with Lifehacker. Keep an eye out for a "Crowdhacker" post published at their site once or twice a week.
And we appreciate the SEO concerns. Don't hesitate to shout out if you think the content deal is doing more harm than good. (We're pretty sure it's not). Or if you see something you wrote published somewhere you don't want it.
Thanks for keeping an eye out!


text:
Q: Get None from a Fields data in instead of an empty string I have this field in the WTForms form
name = StringField('Name', validators = [Optional(), Length(max = 100)])

When the field is submitted empty then form.name.data will, as expected, contain an empty string.
Is there some way to make it return None in instead of an empty string? It is just because it is very convenient to deal with null in the database like in this update:
update t
set
    name = coalesce(%(name)s, name),
    other = coalesce(%(other)s, other)

With the above code I don't need to check if the field is empty or not and take actions accordingly be it in the Python code on in the SQL code. The null with the coalesce solves that easily.

A: There is the filters parameter to the Field constructor
name = StringField(
    'Name',
    validators = [Optional(), Length(max = 100)],
    filters = [lambda x: x or None]
)

http://wtforms.readthedocs.org/en/latest/fields.html#the-field-base-class

A: In my case I added a base class for my forms (all forms are inherited from this class):
class BaseFrom(FlaskForm):

    @property
    def fields(self) -> dict:
        """Returns a dict of fields with values, a value='' substitutes with None"""

        def process_item(item):
            if isinstance(item, dict):
                return process_dict(item)
            elif isinstance(item, list):
                return process_list(item)
            elif item == '':
                return None
            return item

        def process_dict(d: dict) -> dict:
            return {k: process_item(v) for k, v in d.items()}

        def process_list(l_: list) -> list:
            return [process_item(v) for v in l_]

        return process_dict({f: value.data for f, value in self._fields.items()})

So, when an object is being mapped from form input to dataclass, the mapper uses fields property to retrieve data from the form
@dataclass
class BaseModel:

    @classmethod
    def from_form(cls, obj: dict):
        self = object.__new__(cls)
        for f in dataclasses.fields(cls):
            setattr(self, f.name, obj.get(f.name))
        return self

d = BaseModel.from_form(form_instance.fields)

where form_instance is an instance of a class inherited from 'BaseForm'
I have nested forms, so this method will convert all empty inputs to None recursively


text:
Q: how to download a CVS reposititory from sourceforge How do I download this code with cvs?  I press "enter" when prompted for a password, but no download initiates.
thufir@mordor:~$
thufir@mordor:~$ cvs -d:pserver:anonymous@jamochamud.cvs.sourceforge.net:/cvsroot/jamochamud login
Logging in to :pserver:anonymous@jamochamud.cvs.sourceforge.net:2401/cvsroot/jamochamud
CVS password:
thufir@mordor:~$
thufir@mordor:~$ cvs --version

Concurrent Versions System (CVS) 1.12.13-MirDebian-11 (client/server)

Copyright (C) 2005 Free Software Foundation, Inc.

Portions contributed by Thorsten Glaser for the MirOS Project.
Senior active maintainers include Larry Jones, Derek R. Price,
and Mark D. Baushke.  Please see the AUTHORS and README files from the CVS
distribution kit for a complete list of contributors and copyrights.

CVS may be copied only under the terms of the GNU General Public License,
a copy of which can be found with the CVS distribution kit.

Specify the --help option for further information about CVS
thufir@mordor:~$

I should be able to download as so:

Anonymous CVS Access
This project's SourceForge.net CVS repository can be checked out
  through anonymous (pserver) CVS with the following instruction set.
  The module you wish to check out must be specified as the modulename.
  When prompted for a password for anonymous, simply press the Enter
  key. To determine the names of the modules created by this project,
  you may examine their CVS repository via the provided web-based CVS
  repository viewer.
cvs
  -d:pserver:anonymous@jamochamud.cvs.sourceforge.net:/cvsroot/jamochamud
  login

https://sourceforge.net/p/jamochamud/code/?source=navbar

A: After you have logged in:
cvs checkout [repository]

A: I had thought that cvs repositories had all gone but this one works well enough with the following commands:

*

*If you do not have a $HOME/.cvspass file in place already use the following command:
touch $HOME/.cvspass

*Login as you have previously done and use the Enter key as the password:
cvs -d:pserver:anonymous@jamochamud.cvs.sourceforge.net:/cvsroot/jamochamud login

*Download the required module, I have selected what I believe is the most appropriate one but there are a few choices. Try this:
cvs -z3 -d:pserver:anonymous@jamochamud.cvs.sourceforge.net:/cvsroot/jamochamud co -P JamochaMUD/

You can manually use extranet/, gui/ and utils/ as module names.

*You can download all of the modules and in fact the entire repository  (and I suspect that this not what you really want) with this:
cvs -z3 -d:pserver:anonymous@jamochamud.cvs.sourceforge.net:/cvsroot/jamochamud co -P .

Don't miss the dot on the end as this is crucial for this command.
All worked fine on my system and hopefully on yours as well :)


text:
Q: How to generate customObject cls files in VS Code using SalesforceDX In my VS Code project there is a folder:
tools > sobjects > customObjects

Which contains .cls file representations of the custom objects.
I've recently run command:
SFDX: Retrieve Source from Org

And I've got the latest meta data, but I am missing some .cls files the folder:
tools > sobjects > customObjects

Is there a command I need to run to generate these files?

A: Those files will be refreshed from the org your project is connected to if you open the command palette in vscode and run SFDX: Refresh SObject Definitions.


text:
Q: Laravel 4 Illuminate \ Database \ Eloquent \ MassAssignmentException error Hei, I already searched many answers out there but could not solve this problem.
Here is the code for my migration
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateActiveTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('activations', function($table)
        {
            $table->bigInteger('id')->primary();
            $table->tinyInteger('token');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('activations');
    }
}

For model (models/Activation.php)
<?php

class Activation extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'activations';
    protected $guarded = array();
}

And i am calling Activation table like this.
Activation::create(['id' => 2, 'token' => 1231]);

Seriously i have no idea what's wrong here. And i am newbie at laravel 4. Hope somebody with teach me whats happening and how to solve it.

A: You need to use the $fillable property in your Activation class when you use Mass Assignment.
class Activation extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'activations';

    protected $fillable = ['id', 'token'];
}


text:
Q: rich:hotKey for Form Submission? I've got a login form that looks something like this, using RichFaces and Seam:
<h:form id="loginForm">
   <h:outputLabel value="Username" />
   <h:inputText value="#{identity.credentials.username}" />
   <h:outputLabel value="Password" />
   <h:inputText value="#{identity.credentials.password}" />

   <h:commandLink action="#{identity.login()}" value="Login" />
</h:form>

I'd like to be able to allow the user to hit 'enter' and automatically submit the form to login.  I've tried using Richfaces' <rich:hotKey /> feature, but I think I'm doing something wrong.  The code I've put in looks like this:
<rich:hotKey key="return"
   handler="#{rich:element('loginForm')}.submit()" />

However, when I hit enter inside the form, nothing happens.  Any idea what I'm doing wrong here?

A: I think you need to use selector property. Something like,
<rich:hotKey key="return"
             handler="#{rich:element('loginForm')}.submit()"
             selector="#loginForm"/>

Also, instead of submitting the form, you should click submit button. Something like,
<rich:hotKey key="return"
             handler="#{rich:element('loginButton')}.click()"
             selector="#loginForm"/>

A: Try the following code. I hope you can get some idea..
 <body>
        <h:form id="loginForm">

            <h:outputLabel value="Username : " />
            <h:inputText id="userNameId" value="#{Login.username}" />
            <h:outputLabel value="Password : " />
            <h:inputText id="passwordId" value="#{Login.password}" />

            <a4j:commandButton id="loginButton" action="#{Login.loginButton}" value="Login" focus="button"/>

            <rich:hotKey key="return"
                         selector="#userNameId"
                         handler="#{rich:element('loginForm:loginButton')}.click();
                         event.stopPropagation();event.preventDefault();
                         return false;"/>

            <rich:hotKey key="return"
                         selector="#passwordId"
                         handler="#{rich:element('loginForm:loginButton')}.click();
                         event.stopPropagation();event.preventDefault();
                         return false;"/>
        </h:form>
    </body>

A: For all those still struggling with this issue, I've finally gotten something that works.  My code now looks like this:
<h:form id="loginForm">
   <h:outputLabel value="Username" />
   <h:inputText value="#{identity.credentials.username}" />
   <h:outputLabel value="Password" />
   <h:inputText value="#{identity.credentials.password}" />

   <h:commandLink action="#{identity.login()}" value="Login" />
   <rich:hotKey key="return"
             handler="#{rich:element('loginForm')}.submit()"
             selector="#loginForm"/>

</h:form>

You can also use a more specific selector so that an enter press only submits the form when the focus is on one of the form fields.  Either way, this FINALLY solved my problem.