text:
Q: Combobox selection sequence for images I'm a little noobish so sorry if this is really simple...
I have ~120 pictures and I would like to be able to select and display one of those pictures when the name in the combobox corresponds to that picture. I would like to know how to populate the combobox with the name of each picture and select a picture from the box without making 120 "if" statements? Each image has it's own filename in the project.Properties.Resources folder
Also, if there's a way to rename 120 pictures really quickly, that would save me a lot of time but it's fine if i just have to do it by hand.
The form is WPF and I'm using Visual studio 2012 Express

A: You can create a Model to hold your image data and populate a ObservableCollection<T> of that model, Then we can bind that collection to the ComboBox and set the ComboBox selectedItem to a Image control
Here is an example:
Code:
namespace WpfApplication14
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private ObservableCollection<MyImage> _images = new ObservableCollection<MyImage>();
        private MyImage _selectedImage;

        public MainWindow()
        {
            InitializeComponent();

             // Add image files to collection
            foreach (var image in Directory.GetFiles(@"C:\your image directory"))
            {
                // set name and path in model
                Images.Add(new MyImage { Path = image, Name = System.IO.Path.GetFileNameWithoutExtension(image) });
            }
        }

        public ObservableCollection<MyImage> Images
        {
            get { return _images; }
            set { _images = value; }
        }

        public MyImage SelectedImage
        {
            get { return _selectedImage; }
            set { _selectedImage = value; NotifyPropertyChanged("SelectedImage"); }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
    }

    public class MyImage
    {
        public string Name { get; set; }
        public string Path { get; set; }
    }
}

Xaml:
<Window x:Class="WpfApplication14.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Name="UI">
    <StackPanel DataContext="{Binding ElementName=UI}">
        <TextBlock Text="Images" />
        <ComboBox ItemsSource="{Binding Images}" SelectedItem="{Binding SelectedImage}" DisplayMemberPath="Name"/>
        <TextBlock Text="Selected Image" />
        <Image Source="{Binding SelectedImage.Path}" />
    </StackPanel>
</Window>

Result:

A: Well WPF memories are really rusty but as a generalization, you need to know where the selected image in in List. What you can do is keep track of index/positoin of each image in list in a dictionary:
private imageIndices=new Dictionary<string, int>();

store indices:
imageIndices[<IMAGE_NAME>] = <INDEX_OF_IMAGE>;

get name of image from dropdown and get where that image is from dictionary:
var n=<IMAGE_NAME>;

list.Select(imageIndices[<IMAGE_NAME>]);//use actual method name to select


text:
Q: How to view the data against it's associated id in cakephp? Table
    Tables

 Product        Plan            ProductPlan
 id |name       id |name        id  | product_id | plan_id
 1    aplha      1   a          1        1          2
 2    bravo      2   b          2        4          c
 3    charlie    4   c
 4    delta

I want to view the data against it's related id, for example if product has two plan it will be in list of that product. like that
      alpha  |  delta   |
       a          c
       b

view code is

        <?php foreach ($p as $ps){?>

            <?php echo __l($ps['Product']['name']);?>

        <?php }?>

        <?php foreach ($p as $p1){
                foreach($p1['Plan'] as $plan){
                        debug($plan);
        ?>

                <?php echo __l($plan['name']);?>

        <?php }
                    }?>

when i debug the $p1 array is,
 array(
'Product' => array(
    'product_id' => '1',
    'name' => 'Event Manager',
    'slug' => 'event-manager',
    'is_visible' => true
),
'Plan' => array(
    (int) 0 => array(
        'plan_id' => '1',
        'name' => 'FREE',
        'description' => '30 Days Trial',
        'amount' => '0.00',
        'expiry_days' => '30',
        'created' => '2012-01-12 16:51:21',
        'modified' => '2012-01-12 16:51:22',
        'PlansProduct' => array(
            'plan_product_id' => '1',
            'product_id' => '1',
            'plan_id' => '1'
        )
    ),
    (int) 1 => array(
        'plan_id' => '2',
        'name' => 'BRONZE',
        'description' => '60 Days Trial',
        'amount' => '10.00',
        'expiry_days' => '60',
        'created' => '2012-01-12 16:52:24',
        'modified' => '2012-01-12 16:52:25',
        'PlansProduct' => array(
            'plan_product_id' => '2',
            'product_id' => '1',
            'plan_id' => '2'
        )
    )
)

)
how can i do that? Thanks in advance.

A: Am I understanding that "Product has many Plans and Plan has many products" (many to many)(http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm). In this case, you must declare this relationship in the model.
//models/product.php
class Product extends AppModel{
    public $hasAndBelongsToMany = array(
        'Plan' =>
            array(
                'className'              => 'Plan',
                'joinTable'              => 'ProductPlan',
                'foreignKey'             => 'id',
                'associationForeignKey'  => 'id',
                'unique'                 => true,
                'conditions'             => '',
                'fields'                 => '',
                'order'                  => '',
                'limit'                  => '',
                'offset'                 => '',
                'finderQuery'            => '',
                'deleteQuery'            => '',
                'insertQuery'            => ''
            )
    );
}

If the relationship is "one to many", the declaration is like:
class Product extends AppModel {
    public $hasMany = array(
        'Plan' => array(
            'className'     => 'Plan',
            'foreignKey'    => 'product_id'
        )
    );
}

And you need to add a foreign key named "product_id" into "Plan" table.

A: You have to pass three variable from controller.
That variables contains three different Table data.
Than use when required.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the meaning of $@? I came across the makefile when I read something about flex
  fb3-1: fb3-1.l fb3-1.y fb3-1.h
     bison -d fb3-1.y
     flex -ofb3-1.lex.c fb3-1.l
     cc -o $@ fb3-1.tab.c fb3-1.lex.c fb3-1funcs.c

but what's the meaning of $@? Is it in the shell or some argument of gcc?

A: $@ is just short-hand for the file name of the current target (fb3-1 in this case).
See the Automatic Variables section of the gnu make manual for full details on this and other useful automatic variables such as $<.


text:
Q: Why I'm getting TypeError: Cannot read property '1' of undefined while running an apps script on Google Sheets? I've been trying to find where the cause of it here, but I just can't.
Basically, it should look for the row(s) win Form Responses 1 containing testNo equal to the one and set "Yes" to them...
It does that, but it keeps giving me this error in the Logs.
I think that because the formRepValues may come with an array containing an empty element, it may be causing this error...?
function sendEmail() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getActiveSheet();
  const testSheet = ss.getSheetByName("Todays Tests v2");
  const row = sheet.getActiveCell().getRow();
  const col = sheet.getActiveCell().getColumn();
  const emailSent = testSheet.getRange(row, 13, 1, 1).getValue();

  const formRespSheet = ss.getSheetByName('Form Responses 1');
  const formRespRng = formRespSheet.getRange(2, 13, formRespSheet.getLastRow() - 1, 2);
  const formRespValues = formRespRng.getValues();

  if (ss.getActiveSheet().getSheetName() == testSheet.getSheetName() &&
    row > 5 &&
    col == 14 &&
    emailSent != 'Yes') {
    const email = testSheet.getRange(row, 4).getValue();
    const name = testSheet.getRange(row, 2).getValue();
    const testNo = testSheet.getRange(row, 1).getValue();

    for (var n = 0; formRespValues.length; n++) {
      if (formRespValues[n][1] == testNo) {
        formRespSheet.getRange('M' + (2 + n)).setValue('Yes');
      }
    }
  }
}

Thank you!

A: I believe you forgot to set a condition to stop your for loop: the expression formRespValues.length will cause the for loop to run indefinitely.
Try the following:
for (var n = 0; n < formRespValues.length; n++) {
     if (formRespValues[n][1] == testNo) {
       formRespSheet.getRange('M' + (2 + n)).setValue('Yes');
     }
}


text:
Q: Trying to convert js string to NSDateFormatter JS Date type is
11-22-2013 00:00:00

And I want to convert it to
 NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];

 [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

but getting nil in myConvertedDate if I do
  NSDate *myConvertedDate = [df dateFromString:myDate];

A: Format string does not match date.  Did you mean
MM-dd-yyyy HH:mm:ss

A: Use this
    NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];

    [df setDateFormat:@"MM-dd-yyyy HH:mm:ss"];
    NSDate *myConvertedDate = [df dateFromString:myDate];

As your date format is 11-22-2013 00:00:00 (MM-dd-yyyy HH:mm:ss)


text:
Q: Homotopy between idempotents of small difference Let $A$ be a unital $C^*$-algebra. It is known that if $p$ and $q$ are projections in $A$ with
$$\|p-q\|<1,$$
then $p$ and $q$ are homotopic through a path of projections.
Question: Does a similar statement hold for idempotents? More precisely, if $e$ and $f$ are idempotents in $A$, does there exist $\delta>0$ such that $e$ and $f$ are homotopic through idempotents whenever
$$\|e-f\|<\delta?$$

A: Supposing that
$$
\Vert f-e\Vert < {1\over \Vert e \Vert +\Vert f \Vert},  \tag{*}
$$
let $u=ef+(1-e)(1-f)$.  Then
$$
  \Vert u-1\Vert =
  \Vert ef-e-f+ef\Vert=
  \Vert e(f-e) - (f-e)f \Vert \leq $$ $$ \leq
  \Vert e \Vert\Vert f-e\Vert + \Vert f-e \Vert\Vert f \Vert =
  (\Vert e \Vert +\Vert f \Vert)(\Vert f-e\Vert) <1.
  $$
This implies that $u$ is invertible.  Moreover we have that
$eu=uf$, whence $e=ufu^{-1}$.
Notice that the fact that $\Vert u-1\Vert <1$ implies not only that $u$ is invertible, but also that the power series defining the logarithm converges at $u$, so that $u=e^h$, for some $h$ in $A$. We then obtain a path of idempotents joining $f$ and $e$ by
$$u_t=e^{th}fe^{-th}.$$

Remarks:

*

*This does not provide a universal $\delta$, as required in the OP, but at least shows that being homotopically equivalent is invariant under small perturbations.

*My impression is that there is no universal $\delta$ and I'll report back should I be able to prove it.

*An elementary estimate shows that if $\Vert f-e\Vert <(4\Vert e\Vert )^{-1}$, then condition (*) above holds, so we deduce that $e$ is
homotopically equivalent to every idempotent element in a neighborhood of $e$.

A: By Lemma (11.2.7) in (Rørdam, M.; Larsen, F.; Laustsen, N., An introduction to (K)-theory for (C^*)-algebras, London Mathematical Society Student Texts. 49. Cambridge: Cambridge University Press. xii, 242 p. (2000). ZBL0967.19001.), for every idempotent $e$ in $A$, one has that
$$
  \rho (e):= ee^*(1 + (e - e^*)(e^*-e))^{-1}
  $$
is a projection (self-adjoint idempotent) and $e\sim_h\rho (e)$ (meaning that $e$ and $\rho (e)$ are  homotopic through a path
of idempotents).
Thus, given $e$ and $f$ satisfying $\Vert e-f\Vert <\delta $ (the precise value of $\delta $ to be filled in later), we have that
$e\sim_h\rho (e)$ and   $f\sim_h\rho (f)$, so if we can manage to prove that   $\rho (e)\sim_h\rho (f)$, we will get, by transitivity,
that $e\sim_h f$.
As noted in the OP, since $\rho (e)$ and $\rho (f)$ are projections, it would be enough to  prove that $\Vert \rho (e)-\rho (f)\Vert <1$.
It is not difficult to see that the range of an idempotent element $e$ coincides with the range of $\rho (e)$, so $\rho (e)$ is in fact the
orthogonal projection onto the range of $e$.
Given idempotents $e$ and $f$, let us henceforth write $E$ and $F$ for the ranges of $e$ and $f$, respectively, and by
$p$ and $q$ the orthogonal projections onto $E$ and $F$, which amounts to saying that $p=\rho (e)$ and $q=\rho (f)$.
Define
$$
  \alpha (E, F) = \sup\{\text{dist}(x,F): x\in E,\  \Vert x\Vert \leq 1\},
  $$
$$
  \beta (E, F) = \sup\{\text{dist}(x,E): x\in F,\  \Vert x\Vert \leq 1\}.
  $$
and finally put
$$
  d(E, F) = \max\{\alpha (E, F),\beta (E, F)\}.
  $$
Lemma 1. We have
$$
  d(E,F)\leq \Vert e-f\Vert .
  $$
If moreover  $e$ and $f$ are self-adjoint, then
$$
  \Vert e-f\Vert \leq 2d(E,F).
  $$
Proof.  For $x$ in $E$ with $\Vert x\Vert \leq 1$, we have
$$
  \text{dist}(x,F) \leq  \Vert x-f(x)\Vert  = \Vert e(x)-f(x)\Vert  \leq  \Vert e-f\Vert ,
  $$
so $\alpha (E, F)\leq \Vert e-f\Vert $, and it can be likewise proved that    $\beta (E, F)\leq \Vert e-f\Vert $, whence  $d(E, F)\leq \Vert e-f\Vert $.
Now assume that $e$ and $f$ are self-adjoint, so in particular  $\Vert e\Vert  \leq 1$ and  $\Vert f\Vert  \leq 1$.
For every $x$ in $H$ with $\Vert x\Vert \leq 1$, we have that   $e(x)\in E$ and $\Vert e(x)\Vert \leq 1$.  Moreover, the element in $F$ closest to $e(x)$
is $f(e(x))$, so
$$
  \Vert e(x)-f(e(x))\Vert  =  \text{dist}(e(x), F) \leq  \alpha (E,F)\leq d(E,F).
  $$
Taking the supremum for all $x$ in $H$ with $\Vert x\Vert \leq 1$, we  deduce that
$$
  \Vert e-fe\Vert \leq d(E,F),
  $$
and a symmetric  reasoning gives
$\Vert f-ef\Vert \leq d(E,F)$, so also
$$
  \Vert f-fe\Vert  =   \Vert (f-ef)^*\Vert  =   \Vert f-ef\Vert \leq d(E,F).
  $$
This said we obtain
$$
  \Vert e-f\Vert  =
  \Vert e-fe+fe-f\Vert  \leq
  \Vert e-fe\Vert +\Vert fe-f\Vert  \leq
  2d(E,F).
  \tag*{$\blacksquare$}
  $$
Lemma 2.  We have
$$
  \Vert p-q\Vert \leq 2\Vert e-f\Vert .
  $$
Proof.  This follows from
$$
  \Vert p-q\Vert \leq 2d(E,F)\leq 2\Vert e-f\Vert .
  \tag*{$\blacksquare$}
  $$
Theorem.  If $\Vert e-f\Vert <1/2$, then $e\sim_hf$.
Proof.  By Lemma (2) we have
$$
  \Vert \rho(e)-\rho(f)\Vert =\Vert p-q\Vert \leq 2\Vert e-f\Vert <1,
  $$
so the conclusion follows as indicated above. $\qquad \blacksquare$


text:
Q: How to add multiple AND conditions on same columns on a LEFT JOIN query I'm trying to apply multiple groups of conditions on a left join, for ex :
SELECT p.id
FROM project p
LEFT JOIN project_data d ON p.id = d.project_id
WHERE (d.field_id = 1 AND d.value != "") AND (d.field_id = 3 AND d.value > 100)

Here is my db structure :
project_data
+----+-----------+----------+----------+
| id | project_1 | field_id |  value   |
+----+-----------+----------+----------+
|  1 |         1 |        1 |          |
|  3 |         1 |        3 | 80       |
|  4 |         2 |        1 | SomeData |
|  6 |         2 |        3 | 105      |
|  7 |         3 |        1 | SomeData |
|  9 |         3 |        3 | 50       |
+----+-----------+----------+----------+

So what i'm trying to achieve is to return ONLY the project 2, who have a project data with field_id = 1 and a non empty value, and another project data with field_id = 3 and a value > 100.
But this returns an empty list.
I guess it's because I have multiples conditions on the same columns.
This seems pretty easy, but I haven't find a way to do that.
Thank you for your help!
[EDIT]
I found a solution, but really not sure it's the best one (please let me know if you have something better)
SELECT p.id
FROM project p
JOIN project_data d ON p.id = d.project_id AND ((d.field_id = 1 AND d.value != "") OR (d.field_id = 3 AND d.value > 100))
GROUP BY p.id
HAVING COUNT(DISTINCT d.field_id) = 2

A: Try this:
SELECT p.id
FROM project p
LEFT JOIN project_data d
  ON p.id = d.project_id
  AND d.field_id IN (1,3)
  AND d.value != ""
  AND d.value > 100;

In a LEFT JOIN environment, the most left table is the reference table. In your case it's the project table. The purpose of a LEFT JOIN is to return whatever data from the most left table regardless of it has a match with other table(s) after it or not. If you do a WHERE condition on table after the reference, you're just breaking the LEFT JOIN and turn it into a normal join instead. Unless, you're specifically trying to find non-matching data in the table reference.
See some examples here
New detail suggests that OP is actually looking any matches from the second table; which, with the same query I suggested above, can be done by simply changing the left join to a normal join. Therefore:
SELECT *
FROM project p
JOIN project_data d
  ON p.id = d.project_id
  AND d.field_id IN (1,3)
  AND d.value != ""
  AND d.value > 100;

Updated fiddle

A: A working solution
SELECT p.id
FROM project p
JOIN project_data d ON p.id = d.project_id AND ((d.field_id = 1 AND d.value != "") OR (d.field_id = 3 AND d.value > 100))
GROUP BY p.id
HAVING COUNT(DISTINCT d.field_id) = 2

OR another way with multiple LEFT JOIN
SELECT p.id
FROM project p
LEFT JOIN project_data d1 ON p.id = d1.project_id AND d1.field_id = 3
LEFT JOIN project_data d2 ON p.id = d2.project_id AND d2.field_id = 1
LEFT JOIN project_data d3 ON p.id = d3.project_id AND d3.field_id = 11
WHERE (d1.value < 110 AND d1.value > 100) AND (d2.value <> '') AND (d3.value = '' OR d3.value IS NULL);


text:
Q: Is there a way to use Big5 Encoding in Windows Phone 7? I know that WP7 does not have Big5 encoding, but I want to encode a web page in Big5. How do I encode a string from Unicode to Big5 in WP7?

A: The best way to get you started is to get a conversion table setup. I put up such a table on pastebin. It's ; separated, and the first codepoint is Unicode, whereas the second one is Big5.
Of course if it's for a web page, I think the whole exercise is futile and pointless, since you could just declare the charset as utf-8 and be done with it...


text:
Q: Generate Truth Table How to generate truth table by coding in Javascript for three literals (a, b, c) and also find a given  boolean expression (![(a && b) || c])?
I am trying following code:

let input = ['a', 'b', 'c'];
let expression = ['(a&&b)', '((a&&b)||c)', '(!((a&&b)||c))'];
let tableValue = [];

function exp(input, expression) {
  for (let i = 0; i <= Math.pow(2, input.length) - 1; i++) {
    for (let j = 0; j <= input.length - 1; j++) {
      if (('a&&b')) {
        tableValue[j] = (i & Math.pow(2, j)) == false;
      }
    }
    console.log(tableValue);
  }
}
console.log(exp(input));

A: That if (('a&&b')) doesn't evaluate anything. It's a string, not a function that you can call with the values. That's something you should use instead, e.g.
const expression = (a, b, c) => (!((a&&b)||c));

Then you can fill your table by calling the function, like

const expression = (a, b, c) => !((a&&b)||c);
const tf = x => x?'T':'F'
for (let i = 0; i < 2; i++) {
  for (let j = 0; j < 2; j++) {
    for (let k = 0; k < 2; k++) {
      const a = Boolean(i), b = Boolean(j), c = Boolean(k);
      console.log(`a: ${tf(a)}, b: ${tf(b)}, c: ${tf(c)}, result: ${tf(expression(a, b, c))}`);
 //                                                                    ^^^^^^^^^^^^^^^^^^^
    }
  }
}

Instead of logging, you can also build a table row values object (and format it later), and using your approach with bitwise operators you can do it for an arbitrarily large number of boolean variables:

function exp(input, expression) {
  const rows = [];
  for (let i = 0; i < (1 << input.length); i++) {
    const entries = input.map((name, j) =>
      [name, (i >>> j) & 1 == 1]
    );
    const values = entries.map(e => e[1]);
    const obj = Object.fromEntries(entries);
    obj.result = expression(...values);
    rows.push(obj);
  }
  return rows;
}
const table = exp(
  ['a', 'b', 'c'],
  (a, b, c) => ((a&&b)||c)
);
for (const row of table) {
  console.log(Object.entries(row).map(([k, v]) => `${k}: ${v?'T':'F'}`).join(', '));
}

You can also do this with dynamic expressions that are given as strings, if you insist, using a form of eval:

const expressions = ['(a&&b)', '((a&&b)||c)', '(!((a&&b)||c))'];
const input = ['a', 'b', 'c'];
const functionsByExpr = Object.fromEntries(expressions.map(expr =>
  [expr, new Function(...input, `return ${expr};`)]
//       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
));

const rows = [];
for (let i = 0; i < (1 << input.length); i++) {
  const entries = input.map((name, j) =>
    [name, (i >>> j) & 1 == 1]
  );
  const values = entries.map(e => e[1]);
  const obj = Object.fromEntries(entries);
  for (const expr of expressions) {
    obj[expr] = functionsByExpr[expr](...values);
  }
  rows.push(obj);
}

console.log(input.join(' ')+' → '+expressions.join(' '));
console.log('-'.repeat(input.reduce((s,i) => s+i.length+1, expressions.reduce((s,e) => s+e.length+1, 1))));
for (const row of rows) {
  const cell = c => ' '.repeat(c.length/2-1) + (row[c]?'T':'F') + ' '.repeat(c.length/2)
  console.log(input.map(cell).join(' ')+' | '+expressions.map(cell).join(' '));
}


text:
Q: How can I put a video in ionic with mediaCapture? In the app I get this error Object: object,
After recording the video when giving it ready to be displayed on the screen I get that error.
VideoPage.HTML
<ion-header>
  <ion-toolbar color="primary">
    <ion-title>Subir Video</ion-title>
    <ion-buttons slot="start">
      <ion-back-button defaultHref="/autoventa"></ion-back-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-progress-bar [value]="uploadProgress" color="tertiary"></ion-progress-bar>

  <ion-list>
    <ion-item-sliding *ngFor="let f of files">
      <ion-item (click)="openFile(f)">
        <ion-icon name="videocam" slot="start" *ngIf=" f.name.endsWith('mp4')"></ion-icon>

        <ion-label class = "ion-text-wrap">
        {{ f.name }}
        <p> {{ f.fullPath }}</p>
        </ion-label>
    </ion-item>

    <ion-item-options side="start">
      <ion-item-option (click)="deleteFile(f)" color="danger">
        <ion-icon name="trash" slot="icon-only"></ion-icon>
      </ion-item-option>
    </ion-item-options>

    <ion-item-options side ="end">
      <ion-item-option (click)="uploadFile(f)" color = "primary">
        <ion-icon name="cloud-upload" slot = "icon-only"></ion-icon>
      </ion-item-option>
    </ion-item-options>
    </ion-item-sliding>
  </ion-list>

</ion-content>
<ion-footer>
<ion-toolbar color = "primary">
  <ion-button fill="clear" expand="full" color="light" (click)="selectMedia()">
    <ion-icon slot = "start" name="document"></ion-icon>
    Seleccionar Media
  </ion-button>
</ion-toolbar>
</ion-footer>

Declaration of Variables
media folder... I put it before the @component
and files[] before the constructor
const MEDIA_FOLDER_NAME = 'my_media';
files = [];

my recordVideo in videoPage.ts
I use this method to open the camera and record, this part works but at the moment of giving it ready I get an Object object error
  recordVideo(){

    this.mediaCapture.captureVideo().then(
      (data: MediaFile[]) => {
        if(data.length > 0 ){
          this.copyFileToLocalDir(data[0].fullPath)
        }
      },
      (err: CaptureError) => {
        console.log(err)
        alert(err);
      }

    );
  }

CopyFile
after recording command to call this method
but I think the error is in this method
 copyFileToLocalDir(fullPath){
    let myPath = fullPath;
    // Make sure we copy from the right location
    if (fullPath.indexOf('file://') < 0) {
      myPath = 'file://' + fullPath;
    }

    const ext = myPath.split('.').pop();
    const d = Date.now();
    const newName = `${d}.${ext}`;

    const name = myPath.substr(myPath.lastIndexOf('/') + 1);
    const copyFrom = myPath.substr(0, myPath.lastIndexOf('/') + 1);
    const copyTo = this.file.dataDirectory + MEDIA_FOLDER_NAME;

    this.file.copyFile(copyFrom, name, copyTo, newName).then(
      success => {
        this.loadFiles();
      },
      error => {
        console.log('error: ', error);
        alert(error);
      }
    );
  }

LoadFiles with this method I show the files
loadFiles(){
    this.file.listDir(this.file.dataDirectory, MEDIA_FOLDER_NAME).then(
      res => {
        this.files = res;
      },(err)=> {
        console.log('Error al cargar archivos: ', err);
        alert(err);
      }

    );
  }

ngOnInit
 ngOnInit() {
    this.plt.ready().then(() =>{
      let path  = this.file.dataDirectory +MEDIA_FOLDER_NAME;
      this.file.checkDir(path, MEDIA_FOLDER_NAME).then(
        () => {
          this.loadFiles();
        },
        err => {
          this.file.createDir(path, MEDIA_FOLDER_NAME, false);
        }
      );
    });
  }


text:
Q: java.sql.SQLSyntaxErrorException: ORA-00903: invalid table name in Java on select count on function return I am getting Table not found exception for the following query
select count(1) from (pkg_queries.query1function(id));

Type table_type is  Table of record_type

query1function is a function from the package which returns table_type.
In java code on prepared statement execution, the select query gives an Invalid Table name Exception. The Same query is successfully executed in Oracle SQL developer.
Is it possible that it is a Java Oracle Driver issue? How to resolve it?


text:
Q: Error: Missing either an "out" or "dir" config value with r.js / grunt-requirejs Below is my build configuration file: build.js
{
    appDir: '../src',
    baseUrl: 'libs',
    paths: {
        app: 'js'
    },
    dir: '../prod',
    out:"../js/main-built.js",
    fileExclusionRegExp: /.less$/,
    optimize: "uglify2",
    optimizeCss: "standard",
    modules: [{
        name: '../js/main'
    }]
}

I am using "grunt-requirejs": "~0.4.2" as my build npm and Gruntfile requirejs configuration + r.js 2.1.16:
requirejs: {
    std: {
        options: grunt.file.read('config/build.js')
    }
}

Whenever i am try to execute grunt requirejs it is throwing below error on my console:
Error: Error: Missing either an "out" or "dir" config value. If using "appDir" for a full project optimization, use "dir". If you want to optimize to one file, use "out".
    at Function.build.createConfig (d:\app\node_modules\grunt-requirejs\node_modules\requirejs\bin\r.js:27717:19)
I want to consolidate some of the JS files like jquery and its plugins etc. into 1 file and i am using AMD pattern similar to project https://github.com/hegdeashwin/Protocore

Can you please help me out here and tell what i have missed in my configuration ?
Thanks & Regards

A: You're using grunt.file.read which reads a file and returns the file's content as a string.
Use grunt.file.readJSON instead.


text:
Q: Relation between Legendre and Chebyshev polynomials Where I could find relationships between Legendre and Chebyshev polynomials?
For example I found with maple
$$ P_n(\cos\theta)=\sum_{k=0}^n(-1)^{n+k}\frac{2-\delta_{k0}}{4^n}
\binom{n-k}{\frac{n-k}{2}}\binom{n+k}{\frac{n+k}{2}}\cos(k\theta)$$
The sum runs over $n+k$ even, and $\delta_{k0}=1$ if and only if $k=0$. (And $\cos(k\theta)$ are the Chebyshev polynomials)
But would like to know how its proved, and what the inverse relationship is.
Are there any papers or books with these types of relationships?

A: On pp.13~15 of Fox, L. Parker. Chebyshev polynomials in numerical analysis. No. 519.4 F6. 1968., especially (64)(65), we can see the arguement. As an approach to the minimax solution to the function $\Pi(x)=(x-x_{0})\cdots(x-x_{n})$ with equal weights $w(x)=1$, we can write $$\Pi(x)=\frac{2^{n+1}(n+1)!^{2}}{(2n+2)!}P_{n+1}(x)$$ where $P_{k}(x)$ is a Legendre polynomial of degree $k$.
and by the orthogonal transformation provided there we could also write it in terms of weight $w(x)=\frac{1}{\sqrt{(1-x^{2})}}$ and $$\Pi(x)=2^{-n}T_{n+1}(x)$$ where $T_{k}(x)$ is a Chebyshev polynomial of degree $k$.
And these two equalities gave identity involving both Legendre and Chebyshev polynomials.

A: Both the Legendre and Chebyshev polynomials are particular cases of Jacobi polynomials $P_n^{(\alpha,\beta)}(x)$. A general connection formula of the type $$P_n^{(\gamma,\delta)}(x)=\sum_{k=0}^nc_{n,k}^{\gamma,\delta;\alpha,\beta}P_k^{(\alpha,\beta)}(x)$$ can be found on page 256 of the book [Mourad E.H. Ismail, Classical and quantum orthogonal polynomials in one variable,
Encyclopedia of Mathematics and its Applications 98, Cambridge University Press, Cambridge, 2005].


text:
Q: Why a command launched with nohup isn't able to write file after user logout? I'm using nohup to launch matlab and run a script which requires to read and write some given files.
nohup matlab -nojvm -nodisplay -r 'MyScript'&

This runs smoothly while I'm logged in but as soon as I log out and log in again I see that my matlab process is no longer running. After checking the nohup.out file I find the following error message:
Unable to write file $HOME/matlab/my_mat_file.mat: permission denied

It seems that as soon as I log out the owner of the matlab process changes and he no longer has access to my files. How can I prevent this error from occurring without changing the file permissions, e.g., by granting write permissions to everyone?
This error message pops up also while using GNU-screen. If I run ls -al $HOME inside my GNU-screen session before log out I'll have

I detach form the GNU-screen session, log out, log in, and reattach to the screen session just to find that I lost access to files which I used to have access to inside screen. The output of ls -al $HOME is now

Intriguing, isn't it?

A: It as to do with authentication.
I'll start with some concepts on tickets and tokens and how Kerberos authentication system and AFS uses them. By the end the answer to my question will be clear, I'm not allowed to write into the file simply because my AFS token was removed at logout. That said, the solution for my problem was to include in the matlab script a few lines which determine if whether the token exists or not creating it in case it doesn't. How has this been done exactly concludes the answer.
Authentication
Providing a distributed file system, accessible form anywhere, implies a robust security system. This is why AFS has a strong authentication system, integrated with the Kerberos authentication system.
Authentication in AFS is solved by means of a token. Tokens grant users access to the data during their life span. In many cases, token handling is seamless, requiring no user intervention. However, the user can, at any given time, list the tokens issued in its name using tokens
username@machine00 ~ $ tokens

Tokens held by the Cache Manager:

User's (AFS ID xxxxx) tokens for afs@your.system.domain [Expires Mar 20 05:10]
   --End of list--

AFS tokens are obtained from a Kerberos identifier ticket. Similarly to tokens Kerberos tickets also identify the user. While using the Kerberos authetication system, the user is issued by the KDC (Key Distribution Center) an initial ticket called ticket-granting ticket. This first ticket uniquely identifies the user and allows him to obtain specific tickets required for further services like the AFS tokens. In fact, you can use directly the Kerberos  ticket for the AFS service has the AFS identification token.
In most cases, the Kerberos' ticket-granting ticket is automatically obtained during user login. With the same thing happening for the AFS initial token. Like tokens, Kerberos tickets handling is in most cases invisible for the user but you can list the issued tickets using klist
username@machine00 ~ $ klist
Credentials cache: FILE:/tmp/krb5cc_V16088
        Principal: username@KERBEROS.REALM.DOMAIN

  Issued           Expires          Principal
Mar 19 19:10:11  Mar 20 05:10:11  krbtgt/KERBEROS.REALM.DOMAIN@KERBEROS.REALM.DOMAIN
Mar 19 19:10:11  Mar 20 05:10:11  afs/your.system.domain@KERBEROS.REALM.DOMAIN
username@machine00 ~ $

the credentials cache is the location of the file where tickets are found. The Principal is the user id and basically results from the combination of username and Kerberos' realm domain. Notice that the Kerberos realm is generally given in uppercase and it is case sensitive. Following we have the list of issued tickets, with the corresponding issued and expiration dates.  In this case, the first ticket (krtbg) corresponds to the ticket-granting ticket on the realm KERBEROS.REALM.DOMAIN while the second corresponds to the AFS token on the afs cell your.system.domain (which usually has same name as the domain in which it can be found). Other Kerberos tickets may show up in the list in case they have been requested.
Token renewal
When an AFS token expires, the access to the AFS account is no longer possible. The symptoms that such an event as occurred vary from OS to OS, however in Unix/Linux you usually get a permission denied message while trying to access your files:
username@machine00 ~ $ ls
ls: .: Permission denied

When a token expires you need to renew it. An easy way to do it is to logout and login again, since, in most cases, token renewal happens automatically at login. But it turns out that sometimes log out is not an option, especially if you are running something you don't want to exit which is the case.
An alternative solution for ticket renewal is using kinit and aklog, in sequence. The first of these commands (kinit), which requires your password, allows user re-authentication and ticket-granting ticket renewal. Next, aklog command allows you to obtain an AFS token from the Kerberos ticket. Notice that kinit tries to get a ticket for the default principal and realm. In case these are not defined, or if the user is using a different username at time of the ticket request, kinit should be used as kinit <principal>@<realm>, for instance:
username@machine00 ~ $ kinit username@KERBEROS.REALM.DOMAIN
username@KERBEROS.REALM.DOMAIN's Password:
username@machine00 ~ $

The opposite of aklog is unlog, which deletes the AFS token. Correspondingly, kdestroy removes the tickets' file, deleting all Kerberos tickets.
How this saved the day and helped me love my friends & family
As said in the beginning, knowing about this concepts helped me to better understand what was happening with my matlab session. After logout my AFS token was no longer there and my running processes had no longer permission to write into my afs volume. Since, at the moment, I am only interested in guaranteeing that my matlab script keeps running reading and writing files even after I logout I was careful to include a test on the AFS token previous to any access to the AFS volume
ticket_status = unix('klist -s');
if ticket_status ~= 0,
   unix 'kinit username@KERBEROS.REALM.DOMAIN <<< "password"';
   unix  aklog
end

As I said, this goes into the matlab script and I have placed it just before any save or load matlab commands. The code uses matlab command unix to run its arguments on a Unix shell and return the results. The Unix command klist -s runs klist silently but returns its exit status. We test the exit status for credentials and request new ones in case they don't exist or have expired.


text:
Q: Renaming Checkbox Fields with iTextSharp im am trying to rename fields in itext. I can successfully rename textfields, but i am getting errors renaming checkboxfields. Here is the code so far:
try {
    pdfReader = new PdfReader(s_pdfread);
} catch (Exception ex) {
    Console.WriteLine("Can't create Filestream from " + s_pdfread);
    Console.WriteLine(ex.Message);
    ShowHelp();
    Environment.Exit(-1);
}

List <renameJob> jobsToDo = new List<renameJob> ();

try {
    using (FileStream fs = new FileStream(s_pdfwrite, FileMode.Create)) {
        PdfStamper stamper = new PdfStamper(pdfReader, fs);
        AcroFields fields = stamper.AcroFields;

        foreach (var field in stamper.AcroFields.Fields) {
            Console.WriteLine("fieldKeySRC: " + field.Key);
            string newFieldname = field.Key.Replace(s_searchFor, s_replaceWith);
            newFieldname = newFieldname.Replace(".", "");

            // special name for checkbox
            /*switch (stamper.AcroFields.GetFieldType(field.Key)) {
                case AcroFields.FIELD_TYPE_CHECKBOX:
                    newFieldname = newFieldname + ".0";
                    break;
            } planned for future. In finaly version i need to add this .0 */

            if (field.Key != newFieldname) {
                renameJob job = new renameJob();
                job.oldName = field.Key;
                job.newName = newFieldname;
                jobsToDo.Add(job);
            }
        }

        foreach (renameJob job in jobsToDo) {
            if (fields.RenameField(job.oldName, job.newName) == true) {
                Console.WriteLine("renameField: " + job.oldName + " to " + job.newName);
            }
            else {
                Console.WriteLine("!!! failed: renameField: " + job.oldName + " to " + job.newName);
            }

        }

        stamper.Close();

why does this fail for checkboxes and work fine for textboxes.... ?

A: As mkl explains, the "." in a field name is NOT part of the name, it's there to indicate a hierarchy.
Suppose you have a parent field named "parent" with two kids "kid1" and "kid2". In this case, the fully qualified names of the kid fields are "parent.kid1" and "parent.kid2".
With iText, you can rename fields, but you can't change the hierarchy. For instance: you can change the fully qualified name "mybox" into "hisbox", you can change the fully qualified name "parent.kid1" into "parent.child1" and "parent.kid2" into "parent.child2".
IT DOESN'T MATTER if these fields are text fields, checkbox fields, or any other type of field!
In other words: your question is wrong! The problem you have, is that you're not trying to rename a field. Instead you're trying to change "parent.kid1" into "parentkid1" and "parent.kid2" into "parentkid2". That's not the same as renaming! That's removing the hierarchy, changing a parent and two kids into two parentless kids! You can't use the rename function to do this.
If you really want to throw away the hierarchy, you need to add two new fields "parentkid1" and "parentkid2" that copy the properties of "parent.kid1" and "parent.kid2". Once you have these copies, you need to remove "parent", "kid1" and "kid2".
That's much more work. I'd advise against it, as it's an error-prone operation.


text:
Q: How to read directory that contains different parquets in parts? Given a parquet dataset with a job_id abc, saved in parts as such:
my_dataset/
  part0.abc.parquet
  part1.abc.parquet
  part2.abc.parquet

It is possible to read the dataset with vaex or pandas:
import vaex
df = vaex.open('my_dataset')

import pandas as pd
df = pd.read_parquet('my_dataset')

But sometimes our ETL pipeline appends to the the my_dataset directory with parts of parquet from another job id xyz, that caused the directory to becomes something like:
my_dataset/
  part0.abc.parquet
  part0.xyz.parquet
  part1.abc.parquet
  part1.xyz.parquet
  part2.abc.parquet
  part2.xyz.parquet

The main problem is we don't know the job ID created by the ETL pipeline, but we know that they are unique.
Is there some method in pandas.read_parquet to automatically group the parts together? E.g.
import pandas as pd
dfs = pd.read_parquet('my_dataset')

[out]:
{
 'abc': pd.DataFrame, # That reads from `part*.abc.parquet`
 'xyz': pd.DataFrame  # That reads from `part*.xyz.parquet`
}

I've tried doing some glob reading


text:
Q: Cannot get @EnvironmentObject in Controller I'm trying to use @EnvironmentObject to control some aspects of my app. The issue I'm having is that one of my controllers can't access the environment object. I get the fatal error "No @ObservableObject of type Environment found".
I've searched other questions, and every solution I could find consisted of sending .environmentObject(myEnvironment) to the view in question. The problem is this is not a view, and I don't seem to have that option.
Also, in my SceneDelegate I send the environmentObject to the first view, so that is not the problem.
Here is my code.
First, I created a model to declare all my environment variables
Environment
struct Environment {
        var showMenu: Bool
        var searchText: String
        var location : Location

        init() {
            self.showMenu = false
            self.searchText = ""
            self.location = Location()
        }
    }

Next I have a controller which purpose is to handle any actions related to the environment, right now it has none
EnvironmentController
import Foundation

class EnvironmentController : ObservableObject {
    @Published var environment = Environment()
}

Now, in the SceneDelegate I call the NextDeparturesView, which in turn calls, the MapView.
MapView
import SwiftUI
import MapKit

//MARK: Map View
struct MapView : UIViewRepresentable {

    @EnvironmentObject var environmentController: EnvironmentController
    var locationController = LocationController()

    func makeUIView(context: Context) -> MKMapView {
        MKMapView(frame: .zero)
    }

    func updateUIView(_ uiView: MKMapView, context: Context) {
        let coordinate = CLLocationCoordinate2D(
            latitude: environmentController.environment.location.latitude,
            longitude: environmentController.environment.location.longitude)
        let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        uiView.showsUserLocation = true
        uiView.setRegion(region, animated: true)
    }
}

You'll notice that in the MapView I call the LocationController, which is where the fatal error occurs
LocationController
import SwiftUI
import MapKit
import CoreLocation

final class LocationController: NSObject, CLLocationManagerDelegate, ObservableObject {
    //MARK: Vars
    @EnvironmentObject var environmentController: EnvironmentController
    @ObservedObject var userSettingsController = UserSettingsController()

    //var declaration - Irrelevant code to the question

    //MARK: Location Manager
    var locationManager = CLLocationManager()

    //MARK: Init
    override init() {
        //more irrelevant code

        super.init()

        //Ask for location access
        self.updateLocation()
    }

    //MARK: Functions
    func updateLocation() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        if locationManager.responds(to: #selector(CLLocationManager.requestAlwaysAuthorization)){
            locationManager.requestAlwaysAuthorization()
        }
        else {
            locationManager.startUpdatingLocation()
        }
    }

    //MARK: CLLocationManagerDelegate methods
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error updating location :%@", error)
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .notDetermined:
            self.setDefaultLocation()
            break
        case .restricted:
            self.setDefaultLocation()
            break
        case .denied:
            self.setDefaultLocation()
            break
        default:
            locationManager.startUpdatingLocation()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        let currentLocation = manager.location?.coordinate
        self.environmentController.environment.location.latitude = Double(currentLocation!.latitude)
        self.environmentController.environment.location.longitude = Double(currentLocation!.longitude)

        manager.stopUpdatingLocation()
    }

    //MARK: Other Functions

    func recenter() {
        locationManager.startUpdatingLocation()
    }

    func setDefaultLocation() {
        if self.$userSettingsController.userCity.wrappedValue == "" {
            self.environmentController.environment.location.latitude = 0.0
            self.environmentController.environment.location.longitude = 0.0
        } else {
            self.environmentController.environment.location.latitude = self.citiesDictionary[self.userSettingsController.userCity]!.latitude
            self.environmentController.environment.location.longitude = self.citiesDictionary[self.userSettingsController.userCity]!.longitude
        }
    }
}

So, this is where the fatal error occurs. For instance, my app usually calls setDefaultLocation() first, and the app is crashing there. Any idea what I am doing wrong, or how to solve it?
Thank you in advance.
EDIT
After much help from @pawello2222 I've solved my problem, however with some changes to the overall structure of my application.
I will accept his answer as the correct one, but I'll provide a list of things that I did, so anyone seeing this in the future might get nudged in the right direction.

*

*I was wrongly assuming that View and UIViewRepresentable could both access the @EnvironmentObject. Only View can.

*In my Environment struct, instead of a Location var, I now have a LocationController, so the same instance is used throughout the application. In my LocationController I now have a @Published var location: Location, so every View has access to the same location.

*In structs of the type View I create the @EnvironmentObject var environmentController: EnvironmentController and use the LocationController associated with it. In other class types, I simply have an init method which receives a LocationController, which is sent through the environmentController, for instance, when I call MapView I do: MapView(locController: environmentController.environment.locationController) thus insuring that it is the same controller used throughout the application and the same Location that is being changed. It is important that to use @ObservedObject var locationController: LocationController in classes such as MapView, otherwise changes won't be detected.

Hope this helps.

A: Don't use @EnvironmentObject in your Controller/ViewModel (in fact anywhere outside a View). If you want to observe changes to Environment in your Controller you can do this:
class Environment: ObservableObject {
    @Published var showMenu: Bool = false
    @Published var searchText: String = ""
    @Published var location : Location = Location()
}

class Controller: ObservableObject {
    @Published var showMenu: Bool

    private var environment: Environment
    private var cancellables = Set<AnyCancellable>()

    init(environment: Environment) {
        _showMenu = .init(initialValue: environment.showMenu)
        environment.$showMenu
            .receive(on: DispatchQueue.main)
            .sink(receiveValue: { [weak self] value in
                self?.showMenu = value
            })
            .store(in: &cancellables)
    }
}

You can also use other forms of Dependency Injection to inject the Environment (or even use a singleton).

Generally there are different ways to show your Environment variables (eg. showMenu) in the View (and refresh it):
1) The Environment is injected into your View (NOT to ViewModel) as an @EnvironmentObject - for cases when you need to access the Environment from the View only.
2) The ViewModel subscribes to the Environment (as presented above) and publishes its own variables to the View. No need to use an @EnvironmentObject in your View then.
3) The Environment is injected into your View as an @EnvironmentObject and then is passed to the ViewModel.


text:
Q: Evaluate $\int \frac{x}{x^4+5}dx$
$$\int \frac{x}{x^4+5}dx$$

$u=x^2$
$du=2xdx\Rightarrow \frac{du}{2}=xdx$
$$\int \frac{x}{x^4+5}=\frac{1}{2}\int \frac{du}{u^2+5}$$
I want to get to the expression in the form of $\frac{da}{a^2+1}$ so I factor out $5$ to get to:
$$\frac{1}{2}\int \frac{du}{5[(\frac{u}{\sqrt{5}})^2+1]}$$
$\frac{du}{5[(\frac{u}{\sqrt{5}})^2+1]}$ is in the form of $\frac{\frac{a}{b}}{\frac{5c}{d}}$ so if I factor out the $5$ should it be $$\int \frac{1}{2}*\frac{1}{5}\frac{du}{[(\frac{u}{\sqrt{5}})^2+1]}$$
or
$$\int \frac{1}{2}*5\frac{du}{[(\frac{u}{\sqrt{5}})^2+1]}$$

A: Your last line isn't correct, you can procced as follows:
$$\int \frac{1}{2}*\frac{1}{5}\frac{du}{[(\frac{u}{\sqrt{5}})^2+1]}=\frac 1 {10}\int\frac{du}{u^2/5+1}$$
Set $t=\frac{u}{\sqrt5}$ and $dt=\frac{1}{\sqrt 5}du$
$$=\frac{1}{2\sqrt 5}\int\frac{dt}{t^2+1}$$
$$=\frac{\arctan t}{2\sqrt 5}=\frac{\arctan \left(u/\sqrt 5\right)}{2\sqrt 5}=\frac{\arctan \left(x^2/\sqrt 5\right)}{2\sqrt 5}+C$$

A: The First is correct. Let $t=u/\sqrt5$ then $dt=du/\sqrt5$:
$$\frac 12 \frac 1{\sqrt5}\int\frac {dt}{1+t^2}=\frac 12 \frac 1{\sqrt5}\tan^{-1}(t)+c=\frac 12 \frac 1{\sqrt5}\tan^{-1}(\frac {x^2}{\sqrt5})+c$$


text:
Q: Recaptcha solver automation I'm building a bot that purchases restocked items on ecommerce sites and I'm getting stuck at the recaptcha solver part. I have my bot connected to "Anti-Captcha" where they send you the solution code for the recaptcha, but I'm having troubles as to where I send the code I receive. Do I send it to google through a specified url or to the ecommerce site? Here is the code for the captcha solver:
def solve_captcha(current_url):
    solver = recaptchaV2Proxyless()
    solver.set_verbose(1)
    solver.set_key(api_key)
    solver.set_website_url(current_url)
    solver.set_website_key(site_key)
    print(solver.get_balance())
    g_response = solver.solve_and_return_solution()
    if g_response != 0:
        print("g-response: " + g_response)
    else:
        print("task finished with error " + solver.error_code)

A: Once you get the captcha key you have to then send it to the ecommerce website. When you complete a captcha the website sends a POST request which contains the captcha key to itself. To be able to figure out where and how to send it you can solve the captcha manually and use your browser's developer tools to intercept which request sends the captcha key. From there on just replicate the request but insert the captcha key you get from the solver.


text:
Q: Merge datasets where dates are not within a range of each other I have two sets of data. The datasets have the following columns: Patient_name, Drug_administered, Date_of_administration. There are two drugs: X and Y.
I want to delete the rows from Set1 in which a patient got drug Y (in Set2) within 14 days of getting drug X (in Set1).
Here is what the datasets look like:
Set1
Patient_name Drug_administered Date_of_administration
 A               x                3/6/2010
 A               x                4/7/2011
 A               x                4/8/2011
 B               x                6/18/2014
 B               x                6/19/2014
 B               x                7/19/2014

Set2
  Patient_name   Drug_administered  Date_of_administration
   A               y                 3/6/2009
   A               y                 4/18/2011
   A               y                 4/8/2014
   B               y                 6/18/2013
   B               y                 6/19/2013
   B               y                 7/19/2013

For instance, I would like to delete the second entry of patient A in set1, because he received drug Y within 14 days of receiving drug X.
How can I do this, in Excel or R?

A: You can try this:
colnames(set1) <- c("ID", "x.given", "x.date")
colnames(set2) <- c("ID", "y.given", "y.date")

both <- merge(set1, set2, by="ID")

subset(both, subset=abs(as.Date(x.date) - as.Date(y.date)) > 14))

It joins the datasets on the ID column then subsets to where the absolute difference in administration dates is greater than 14 days, thereby removing cases where x and y were administered within 14 days of each other.


text:
Q: repay calculation with grace days and month in R First of all, apologies for posting the same question again.
I want to add the grace period to a repay table for the flat interest calculation method such that the interest amount can be received for the grace period.
dataframe1: This is the normal scenario.
uid     emi_date    amt interest    tenure  emi      Rep_seq    status  balance
KII-453 01/01/2020  100 2%          12      10.33333    1          1    113.67
KII-453 01/02/2020  100 2%          12      10.33333    2          1    103.3367
KII-453 01/03/2020  100 2%          12      10.33333    3          1    93.00333
KII-453 01/04/2020  100 2%          12      10.33333    4          0    82.67
KII-453 01/05/2020  100 2%          12      10.33333    5          0    72.33667
KII-453 01/06/2020  100 2%          12      10.33333    6          0    62.00333
KII-453 01/07/2020  100 2%          12      10.33333    7          0    51.67
KII-453 01/08/2020  100 2%          12      10.33333    8          0    41.33667
KII-453 01/09/2020  100 2%          12      10.33333    9          0    31.00333
KII-453 01/10/2020  100 2%          12      10.33333    10         0    20.67
KII-453 01/11/2020  100 2%          12      10.33333    11         0    10.33667
KII-453 01/12/2020  100 2%          12      10.33333    12         0    0.003333

From the dataframe1, I'm trying to provide the grace period for the next x months  from the last date with status = 1 (In dataframe 1 this is emi_date = '01/03/2020')
balance calculation:

*

*row 1 = 124 - 10.333 = 113.67,

*row 2 and onwards = balance row1 - emi = 113.67 - 10.333

The desired result should look like this:
uid     emi_date    amt interest    tenure  emi       rep_seq   status  balance
KII-453 01/01/2020  100   2%          12    10.33333    1         1     113.67
KII-453 01/02/2020  100   2%          12    10.33333    2         2     103.3367
KII-453 01/03/2020  100   2%          12    10.33333    3         3     93.00333
KII-453 01/04/2020  100   2%          12    0           4         0     95.00333
KII-453 01/05/2020  100   2%          12    0           5         0     97.04333
KII-453 01/06/2020  100   2%          12    10.33333    6         0     86.71
KII-453 01/07/2020  100   2%          12    10.33333    7         0     76.37667
KII-453 01/08/2020  100   2%          12    10.33333    8         0     66.04333
KII-453 01/09/2020  100   2%          12    10.33333    9         0     55.71
KII-453 01/10/2020  100   2%          12    10.33333    10        0     45.37667
KII-453 01/11/2020  100   2%          12    10.33333    11        0     35.04333
KII-453 01/12/2020  100   2%          12    10.33333    12        0     24.71
KII-453 01/01/2021  100   2%          12    10.33333    13        0     14.37667
KII-453 01/02/2021  100   2%          12    10.33333    14        0     4.043333
KII-453 01/03/2021  100   2%          12    4.043333    15        0     0

balance calculation (row1) = 124 - 10.333 =113.67, row2 and onward till status (1) = balance row1(113.67)-emi(10.333)
To add grace period, we are next two months emi as 0. and balance calculation for those two months will be for 01/04/2020 = amt(100)*interest(2%) + previous balance (93.00333) and for 01/05/2020 = (amt(100)*interest(2%))+(amt(100)*interest(2%))*2%+ previous balance (95.00333)
The rest balance calculation will be as it is (For Eg. Previous balance - emi) till the balance is < emi, if the balance < emi we will carry forward that balance in emi to next month and keep balance 0 for that month.
P.S - Interest method used is flat, for reducing i'm trying to build the logic it would be helpful if SO can help me for that as well.
For the example purpose i have created the dataframe for one uid in real i have ~10000 unique uid in dataframe.
Input Dput:
   dataframe1<- structure(list(uid = c("KII-62", "KII-62", "KII-62",
"KII-62", "KII-62", "KII-62", "KII-62",
"KII-62", "KII-62", "KII-62", "KII-62",
"KII-62", "KII-62", "KII-62", "KII-62",
"KII-62", "KII-62", "KII-62", "KII-62",
"KII-62", "KII-62", "KII-62", "KII-62",
"KII-62", "KII-63", "KII-63", "KII-63",
"KII-63", "KII-63", "KII-63", "KII-63",
"KII-63", "KII-63", "KII-63", "KII-63",
"KII-63"), emi_date = c("05/12/2019", "05/01/2020", "05/02/2020",
"05/03/2020", "05/04/2020", "05/05/2020", "05/06/2020", "05/07/2020",
"05/08/2020", "05/09/2020", "05/10/2020", "05/11/2020", "05/12/2020",
"05/01/2021", "05/02/2021", "05/03/2021", "05/04/2021", "05/05/2021",
"05/06/2021", "05/07/2021", "05/08/2021", "05/09/2021", "05/10/2021",
"05/11/2021", "05/12/2019", "05/01/2020", "05/02/2020", "05/03/2020",
"05/04/2020", "05/05/2020", "05/06/2020", "05/07/2020", "05/08/2020",
"05/09/2020", "05/10/2020", "05/11/2020"), amt = c(470000, 470000,
470000, 470000, 470000, 470000, 470000, 470000, 470000, 470000,
470000, 470000, 470000, 470000, 470000, 470000, 470000, 470000,
470000, 470000, 470000, 470000, 470000, 470000, 220000, 220000,
220000, 220000, 220000, 220000, 220000, 220000, 220000, 220000,
220000, 220000), interest = c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2), tenure = c(24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12), emi = c(28983.33, 28983.33,
28983.33, 28983.33, 28983.33, 28983.33, 28983.33, 28983.33, 28983.33,
28983.33, 28983.33, 28983.33, 28983.33, 28983.33, 28983.33, 28983.33,
28983.33, 28983.33, 28983.33, 28983.33, 28983.33, 28983.33, 28983.33,
28983.33, 22733.33, 22733.33, 22733.33, 22733.33, 22733.33, 22733.33,
22733.33, 22733.33, 22733.33, 22733.33, 22733.33, 22733.33),
    Rep_seq = c("1", "2", "3", "4", "5", "6", "7", "8", "9",
    "10", "11", "12", "13", "14", "15", "16", "17", "18", "19",
    "20", "21", "22", "23", "24", "1", "2", "3", "4", "5", "6",
    "7", "8", "9", "10", "11", "12"), status = c(1L, 1L, 1L,
    1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L), balance = c(450416.666666667, 430833.333333333,
    411250, 391666.666666667, 372083.333333333, 352500, 332916.666666667,
    313333.333333333, 293750, 274166.666666667, 254583.333333333,
    235000, 215416.666666667, 195833.333333333, 176250, 156666.666666667,
    137083.333333333, 117500, 97916.6666666667, 78333.3333333333,
    58750, 39166.6666666667, 19583.3333333333, 8e-28, 201666.666666667,
    183333.333333333, 165000, 146666.666666667, 128333.333333333,
    110000, 91666.6666666667, 73333.3333333333, 55000, 36666.6666666667,
    18333.3333333333, 4e-28)), .Names = c("uid", "emi_date",
"amt", "interest", "tenure", "emi", "Rep_seq", "status", "balance"
), class = "data.frame", row.names = c(NA, 36L))

Row 1 balance for uid = KII-62 would be (amt * interest * tenure)+amt, the same will repeat for Row 1 balance for uid = KII-63
Row 1 Balance (KII-62):
(4,70,000*0.02*24)+4,70,000 = 6,96,500
Thanks to SO, below is the code that I'm using for the calculation but getting a negative value at the end of the 2-3 months, please help in resolve the issue.
library(tidyverse)
library (lubridate) # for dmy()
startingbalance <- 124
period <- "1 month"
dataframe1 %>%
  mutate(index = seq(1,nrow(.))) %>%
  mutate(emi_date = dmy(emi_date)) %>%
  mutate(emi = case_when(status - lag(status) < 0 ~ 0, status - lag(status,2L) < 0 ~ 0, TRUE ~ emi)) %>%
  mutate(balance = case_when(index == 1 ~ startingbalance - emi,
                                index > 1 & emi > 0 & status == 1 ~ lag(balance) - emi,
                                index > 1 & emi == 0 & lag(status) == 1 & lag(status,2L) == 1 ~ lag(balance) + (amt * (as.integer(gsub("%","",interest))) / 100),
                                index > 1 & emi == 0 & lag(status) == 0 & lag(status,2L) == 1 ~ lag(balance,2L) + 2 * (amt * (as.integer(gsub("%","",interest))) / 100),
                                TRUE ~ NaN)) %>%
  select(-index) %>%
  do(add_row(., uid = .$uid[nrow(.)],emi_date = .$emi_date[nrow(.)] + period(period), amt = .$amt[nrow(.)],interest = .$interest[nrow(.)],tenure = .$tenure[nrow(.)],emi = .$emi[nrow(.)],status = .$status[nrow(.)],Rep_seq = .$Rep_seq[nrow(.)] + 1,balance = NaN)) %>%
  do(add_row(., uid = .$uid[nrow(.)],emi_date = .$emi_date[nrow(.)] + period(period), amt = .$amt[nrow(.)],interest = .$interest[nrow(.)],tenure = .$tenure[nrow(.)],emi = .$emi[nrow(.)],status = .$status[nrow(.)],Rep_seq = .$Rep_seq[nrow(.)] + 1,balance = NaN)) %>%
  do(add_row(., uid = .$uid[nrow(.)],emi_date = .$emi_date[nrow(.)] + period(period), amt = .$amt[nrow(.)],interest = .$interest[nrow(.)],tenure = .$tenure[nrow(.)],emi = .$emi[nrow(.)],status = .$status[nrow(.)],Rep_seq = .$Rep_seq[nrow(.)] + 1,balance = NaN)) %>%
  mutate(balance =  {ind <- which(is.nan(balance)); for(i in ind){balance[i] <- balance[i-1] - emi[i]}; balance}) %>%
  mutate(emi = case_when(balance < 0 ~ lag(balance), TRUE ~ emi),
         balance = case_when(balance < 0 ~ 0, TRUE ~ balance))


text:
Q: How do I access SSRS reports with a new user account when the old windows account has been corrupted I run SQL Server 2014 locally. My old windows account has been corrupted. I created a new windows account, gave myself sysadmin permissions on SSMS and I can log onto the database fine. I also logged on Reporting Services Configuration Manager and changed the Service Account to the new user account. However I can not access localhost/reportserver on internet explorer.  It's saying I don't have sufficient permissions.

A: Ah I just found the answer. It's a Trusted Site issue:
To Configure Local Report Server and Report Manager Administration
Complete the configuration steps in this section if you are browsing to a local report server and you see errors similar to the following:
User 'Domain[user name]' does not have required permissions. Verify that sufficient permissions have been granted and Windows User Account Control (UAC) restrictions have been addressed.
Trusted Site Settings in the Browser:
Open a browser window with Run as administrator permissions. From the Start menu, click All Programs, right-click Internet Explorer, and select Run as administrator.
Click Allow to continue.
In the URL address, enter the Report Manager URL. For instructions, see Report Manager (SSRS Native Mode) in SQL Server Books Online.
Click Tools.
Click Internet Options.
Click Security.
Click Trusted Sites.
Click Sites.
Add https://[your-server-name]
Clear the check box Require server certification (https:) for all sites in this zone if you are not using HTTPS for the default site.
Click Add.
Click OK.
https://learn.microsoft.com/en-us/sql/reporting-services/report-server/configure-a-native-mode-report-server-for-local-administration-ssrs?view=sql-server-2017


text:
Q: JTable with striped background Using a different background color for odd and even rows is a commonly used trick to improve readability of large tables.
I want to use this effect in Swing's JTable. I started out by creating a custom table renderer, but this can only be used to paint actual cells, and I also want to add stripes to the "white" part of the table where there might be no cells. I can subclass JTable and override paintComponent(), but I would prefer an option where I can just change the table's rendering.
Is there a better way of doing this?
Edit: According to the answers so far this seems to be impossible without extending JTable. However, when I override JTable.paintComponent() it also only paints the area where there are rows. How can I paint the rest?

A: Use getCellRect( getRowCount() - 1, 0, true ).y to get the top y-coordinate of the empty space, and then paint some Rectangles and (Grid-)Lines with paintComponent( Graphics g ).

 To make it much easier for you, here's a long (but complete) solution ;-)
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

public class StripedEvenInWhitePartsTable extends JTable
{

  public StripedEvenInWhitePartsTable( String[][] data, String[] fields )
  {
    super( data, fields );
    setFillsViewportHeight( true ); //to show the empty space of the table
  }

  @Override
  public void paintComponent( Graphics g )
  {
    super.paintComponent( g );

    paintEmptyRows( g );
  }

  public void paintEmptyRows( Graphics g )
  {
    Graphics newGraphics = g.create();
    newGraphics.setColor( UIManager.getColor( "Table.gridColor" ) );

    Rectangle rectOfLastRow = getCellRect( getRowCount() - 1, 0, true );
    int firstNonExistentRowY = rectOfLastRow.y; //the top Y-coordinate of the first empty tablerow

    if ( getVisibleRect().height > firstNonExistentRowY ) //only paint the grid if empty space is visible
    {
      //fill the rows alternating and paint the row-lines:
      int rowYToDraw = (firstNonExistentRowY - 1) + getRowHeight(); //minus 1 otherwise the first empty row is one pixel to high
      int actualRow = getRowCount() - 1; //to continue the stripes from the area with table-data

      while ( rowYToDraw < getHeight() )
      {
        if ( actualRow % 2 == 0 )
        {
          newGraphics.setColor( Color.ORANGE ); //change this to another color (Color.YELLOW, anyone?) to show that only the free space is painted
          newGraphics.fillRect( 0, rowYToDraw, getWidth(), getRowHeight() );
          newGraphics.setColor( UIManager.getColor( "Table.gridColor" ) );
        }

        newGraphics.drawLine( 0, rowYToDraw, getWidth(), rowYToDraw );

        rowYToDraw += getRowHeight();
        actualRow++;
      }

      //paint the column-lines:
      int x = 0;
      for ( int i = 0; i < getColumnCount(); i++ )
      {
        TableColumn column = getColumnModel().getColumn( i );
        x += column.getWidth(); //add the column width to the x-coordinate

        newGraphics.drawLine( x - 1, firstNonExistentRowY, x - 1, getHeight() );
      }

      newGraphics.dispose();

    } //if empty space is visible

  } //paintEmptyRows

  public Component prepareRenderer( TableCellRenderer renderer, int row, int column )
  {
    Component c = super.prepareRenderer( renderer, row, column );

    if ( !isRowSelected( row ) )
    {
      c.setBackground( row % 2 == 0 ? getBackground() : Color.ORANGE );
    }

    return c;
  }

  public static void main( String[] argv )
  {
    String data[][] = { { "A0", "B0", "C0" }, { "A1", "B1", "C1" }, { "A2", "B2", "C2" }, { "A3", "B3", "C3" }, { "A4", "B4", "C4" } };
    String fields[] = { "A", "B", "C" };

    JFrame frame = new JFrame( "a JTable with striped empty space" );
    StripedEvenInWhitePartsTable table = new StripedEvenInWhitePartsTable( data, fields );
    JScrollPane pane = new JScrollPane( table );

    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.add( pane );
    frame.setSize( 400, 300 );
    frame.setLocationRelativeTo( null );
    frame.setVisible( true );
  }

}

This example could be extended to:

*

*fix the painted pseudogrid for variable RowHeights (I'm using the lowest height used in any row)

*explain to the user why nothing happens if he clicks in the empty space to edit the cells (via tooltip)

*add an extra row to the table model if the user clicks in the empty space (nooo! no Excel please!)

*use the empty space to draw a reflection of the table (including all rendered data ( what for? ;-) )

A: The JXtable provided by swingx allow you to implements such rendering
Take a look at http://swinglabs.org/docs/components/JXTable/tutorial.jsp?step=3#RowHighlighting

A: Use Table Row Rendering concepts which is easier than dealing with individual renderers.
This approach only works for rendered cells. If you want to paint outside the bounds of the table, then you will need to override the paintComponent() method to add custom painting.

A: You can also use a custom TableCellRenderer which will pick the color for you, with a part of code like this inside:
if (isSelected) //color remains the same while selected
{
    lFgColor = table.getSelectionForeground();
    lBgColor = table.getSelectionBackground();
}
else
{
    lFgColor = table.getForeground();
    if (row%2 != 0) //once out of two rows, change color
        lBgColor = table.getBackground();
    else
    {
        //New look and feels like nimbus declare this property, try to use it
        lBgColor = UIManager.getColor("Table.alternateRowColor");
        if (lBgColor == null) //If not, choose your own color
            lBgColor = UIManager.getColor("Table.light");
        }
    }
}

Edit: I missed the fact that you tried that already, and that you need to extend this color to the space without cells. To my knowledge, this is not possible with the current implementation of JTable or JXTable. The highlighters from JXTable are mostly sophisticated renderers, they still cater only to cells.
To extend the space, the only possibilities I see are:

*

*draw it yourself, in your own component.

*"hack" a way by adding a fake last column, with a custom JTableHeader which wouldn't display the last column header (and a renderer avoiding the grid for this last column). Also, the table resizing mode should be AUTO_RESIZE_LAST_COLUMN, in this case. This is a lot of conditions to make it work, and I'm not really sure it would work anyway.

A: Either use JXTable or if you are super-lazy ( or super time-short :-)) ) you can just use "Nimbus" look-and-feel, JTable looks there stripped by default :)


text:
Q: How to declare a C struct with a pointer to array in ctypes? I read the official ctypes tutorial and also searched SO, but I could not find a way to declare this kind of structure with ctypes. This structure is returned by one of the functions I write an Python interface for.
typedef struct{
    int i;
    float *b1;
    float (*w1)[];
}foo;

This is what I have so far:
class foo(Structure):
 _fields_=[("i",c_int),
  ("b1",POINTER(c_int)),
  ("w1",?????????)]

Thanks for your help!

A: In C, a pointer to an array stores the same memory address as a pointer to the first element in the array.  Therefore:
class foo(Structure):
    _fields_=[("i",c_int),
              ("b1",POINTER(c_int)),
              ("w1",POINTER(c_float))]

You can access the elements of the array using integer indexes.  For example: myfoo.w1[5].
It would be better C coding style to declare w1 as float *w1, so that you can access elements of the array using myfoo->w1[5] instead of having to dereference twice.


text:
Q: UI freeze onChange event when trying to display an alert I'm using react-native-datepicker Modal and onDateChange event im trying to display an altert. But when I do it the alert pops up first and immediately disappears and then freeze the whole UI. My code as bellow.
<View style={{ flexDirection: 'row' }}>
            <DatePicker
                style={{ width:Dimensions.get('window').width/2 - 10}}
                date={this.state.date}
                mode="date"
                placeholder="select date"
                format="YYYY-MM-DD"
                minDate={minimumDate}
                maxDate={currentDate}
                confirmBtnText="Confirm"
                cancelBtnText="Cancel"
                customStyles={{
                    dateIcon: {
                        position: 'absolute',
                        left: 0,
                        top: 4,
                        marginLeft: 0
                    },
                    dateInput: {
                        marginLeft: 36
                    }
                    // ... You can check the source to find the other keys.
                }}
                onDateChange={(date) => { this.dateChange(date)}}
            />
</View>

My date change method as bellow
 dateChange = (date)=>{
    alert("date is:",date)
 }

What am I missing here??


text:
Q: Why client.post in Django keeps returns GET response I'm developing web apps under django 2.0.4 and python 3. And I need to write a test for the Signup view, to make sure that the redirection happens after a successful signup is made. Here is the code:
forms.py
from django.contrib.auth.forms import UserCreationForm
from django.cotnrib.auth.models import User
class SignupForm(UserCreationForm):
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField(max_length=200)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',)

views.py
from django.shortcuts import render, redirect
from .form import SignupForm

class SignupView(View):
    template_name='signup/signup.html'
    form_class = SignupForm

    def get(self, request, *args, **kwargs):
        form = self.form_class()
        return render(request, self.template_name, {'form' : form })

    post(self, request, *args, **kwargs):
        form = self.self.form_class(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user=authenticate(username=username, password=raw_password)
            if user is Not None:
                login(request, user)
                return redirect('index')
        else:
            form = self.form_class()
            context = {'form' : form}
            return render(request, self.template_name, {'form' : form})

urls.py (app)
from django.url import path

urlpatterns = [
    path('signup/', views.SignupView.as_view(), name='signup'),
    ...
]

signup.html
<form method="post" action="{% url 'signup' %}>
    {% csrf_token %}
    <table>
        {{ form.as_table }}
    </table>
    <button type="submit">sign up</button>
</form>

All above works well, until I try to make a test on the post. That is a test against the code.
return redirect('index')

Here is the test code in "test_views.py"
class SignUpViewTest(TestCase):
    def test_view_redirect_after_post(self):
      post_data = {'username': 'mary',
                 'first_name':'Mary',
                 'last_name': 'Farh',
                 'password1': '1234_abcd',
                 'password2':'1234_abcd',
                 'email': 'goinhome@outlook.com'}
      resp = self.client.post(reverse('signup'), post_data)
      #self.assertRedircts(resp, reverse('index'))
      self.assertEqual(resp.status_code, 302)

I ALWASYS get resp.status_code as 200. And I am quite sure that the HttpResponse comes from "else" clause (in views.py).
class SignupView(View)
    def post(self,request, *args, **kwargs)
        ...
        if form.is_valid():
            ...
        else:
            form = self.form_class()
            context = {'form' : form}
            return render(request, self.template_name, {'form' : form})

Please tell me why the branch
if  form.is_valid():
    ...

is bypassed. And tell me how to fix my test.
Thank you!


text:
Q: Word for a moniker that you use to address friends What is the word for the words we use to address a person or people to whom we stand in a particular relationship.
For example I usually address my friends as "boss". I greet them with "Hey boss, how are you doing?"
Neighbouring words or terms include term of endearment which doesn't fit as endearment seems too affectionate a word for the context to which I'm referring.
Similarly pet name is too affectionate and it's also used to tag a specific person rather than a collection of people.
NB: Apologies if my wording is unclear.
Edit: Emphasised collection of people to clarify why pet name or nickname aren't appropriate in my context.

A: OED:
nickname, n.

*

*A (usually familiar or humorous) name which is given to a person, place, etc., as a supposedly appropriate replacement for or addition to the proper name.
1984   M. Scammell Solzhenitsyn (1985) iii. 77   In early adolescence, when he suddenly grew much taller than the others, he earned the nickname of 'Ostrich'.
2001   Vanity Fair (N.Y.) May 219/2   In negotiations, Grossman exuded a menacing charm; around Greenwich Village, his nickname was 'the floating Buddha'.

$10 word - high register: sobriquet n. (also found spelled as soubriquet) An epithet, a nickname.

1867   A. Trollope Last Chron. Barset II. xlix. 57   Her name was Susan, but he had always called her Posy, having himself invented for her that soubriquet.

A: You might talk of casual terms of address in general for such terms as "pal", "buddy", "mate",  etc. However, the terms you are referring to are of another sort, they are apparently a very  personal choice of yours among terms not  used for that purpose; for this reason you might talk of (highly) idiosyncratic terms of address.


text:
Q: How to solve $\frac{dy}{dx}=\frac{1-x^2+y^2}{2xy}$ I'm having trouble in trying to make  $\frac{dy}{dx}=\frac{1-x^2+y^2}{2xy}$ a variable separable equation so I can integrate it. Any ideas?

A: Hint:
$$
\,d\left(\frac{y^2}{x}\right) = \frac{2xy dy - y^2 dx}{x^2} = \left(\frac{1}{x^2} - 1\right)\,dx
$$

A: $$2xyy'=1-x^2+y^2$$
$u=y^2$ and $u'=2yy'$
$$xu'-u=1-x^2$$
is a linear ODE easy to solve :
First, solve the associated homogeneous ODE : $xU'-U=0$ which gives $U=Cx$
Second, replace the constant $C$ by a function $f(x)$, hense $u=(f(x))x$ and $u'=f+xf'$
$$xu'-u=x(f+xf')-xf=x^2f'=1-x^2$$
$$f'=\frac{1}{x^2}-1$$
$$f=-\frac{1}{x}-x+c$$
$$u=xf=-1-x^2+cx$$
$$y=\pm\sqrt{u}=\pm \sqrt{-1-x^2+cx}$$


text:
Q: DJANGO_SETTINGS_MODULE not defined when building Sphinx documentation I'm following this tutorial in order to generate documentation for my Django project.
I've added sys.path.append(os.path.join(os.path.dirname(__name__), '..')) to the conf.py file within my documentation directory.
But running make html keeps giving me errors like this:

ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

My project is running fine, so I'm not sure where I'm supposed to call settings.configure()?

A: Directory Structure
Basing on a vanilla install with the following directory structure here are the steps that should work. The directory structure may be different as long as the path in conf.py is set correctly.
├── docs
│   ├── Makefile
│   ├── build
│   └── source
│       ├── _static
│       ├── _templates
│       ├── conf.py
│       └── index.rst
└── myproj
    ├── anapp
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── migrations
    │   │   └── __init__.py
    │   ├── models.py
    │   ├── tests.py
    │   └── views.py
    ├── manage.py
    └── myproj
        ├── __init__.py
        ├── settings.py
        ├── urls.py
        └── wsgi.py

Sphinx Configuration
conf.py needs a few settings so that autodoc is able to bootstrap the Django app:
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.join(os.path.abspath('.'), '../../myproj'))    # <•• 1

os.environ['DJANGO_SETTINGS_MODULE'] = 'myproj.settings'                  # <•• 2

import django
django.setup()                                                            # <•• 3

1 ⇒ appending the Django project directory (the one with manage.py) to the Python path, which is necessary for 2 and for resolving autodoc directives in the .rst files.
2 ⇒ setting an env variable with the location of the settings module. This example is based on a vanilla django-admin setup. If you are using a more sophisticated settings structure (e.g. dev, staging, production settings extending from some base settings) just update the path, e.g. myproj.settings.dev.
3 ⇒ finally calling django.setup() is necessary to populate Django's application registry, which Sphinx needs in order to generate the docs from an intact Django setup.
Everything should be in place now for $ make html to work with autodoc.


text:
Q: initial sort order for a sortable custom column in admin I have created a number of 'views' column in the admin area of my posts. There are several tutorials for this and I did in fact use a number of these to arrive at my end result.
It works as expected but I would like the initial sort order to be numeric descending, but unfortunately when you first select it, it is always ascending. Clicking it again gives you a descending list. I would like for it to be initially descending when first selected, and then if you want ascending (which is unlikely) I will click it again.
I have tried a number of solutions (all of my own device) but none that work 100% as required.
Here is my initial code which sorts ascending then descending:
add_action( 'pre_get_posts', 'my_views_orderby' );
function my_views_orderby( $query ) {
    if( ! is_admin() )
        return;

    $orderby = $query->get( 'orderby');

    if( 'view' == $orderby ) {
        $query->set('meta_key','views');
        $query->set('orderby','meta_value_num');
    }
}

My initial solution was to add a sort order:
add_action( 'pre_get_posts', 'my_views_orderby' );
function my_views_orderby( $query ) {
    if( ! is_admin() )
        return;

    $orderby = $query->get( 'orderby');

    if( 'view' == $orderby ) {
        $query->set('meta_key','views');
        $query->set('orderby','meta_value_num');
        $query->set('order','desc');
    }
}

This kinda works, but it is ALWAYS descending, since I am setting it that way.
So then I made it conditional:
add_action( 'pre_get_posts', 'my_views_orderby' );
function my_views_orderby( $query ) {
    if( ! is_admin() )
        return;

    $orderby = $query->get( 'orderby');

    if( 'view' == $orderby ) {
        $query->set('meta_key','views');
        $query->set('orderby','meta_value_num');
        $orderdir = $query->get( 'order');
        if('desc' == $orderdir) {
            $query->set('order','asc');
        } else {
            $query->set('order','desc');
        }
    }
}

Now this works, but the sort indicator is the wrong way around. ie when it is sorted ascending, the icon is indicating descending and vice versa. When I hover over the sort column, the icon indicates the PRESENT state and not the state it will become. Also, the link url (which appears at the bottom of chrome) is telling me it is going to sort by the incorrect direction. What this means, if I am already sorted by views descending, the link indicates it will sort by descending, and v.v.
In the off chance it's relevant, this is how I have declared the column as sortable:
add_filter( 'manage_edit-post_sortable_columns', 'my_sortable_view_column' );
function my_sortable_view_column( $columns ) {
    $columns['post_views'] = 'view';
    return $columns;
}

A: Instead of adding your column label "view" as a string, pass it in as an array with 1 as the second value. Like this: array('view',1)
Full Code:
add_filter( 'manage_edit-post_sortable_columns', 'my_sortable_view_column' );
function my_sortable_view_column( $columns ) {
    $columns['post_views'] = array('view',1);
    return $columns;
}

I don't have a WP Codex for this, but I found someone else posted a solution here:
http://www.weblogmechanic.com/2014/02/13/making-custom-column-wordpress-admin-sort-reverse-order/


text:
Q: Count How many times an item appears in relation to a value from another cell I have 2 worksheets, what I want to achieve is to count how many times an item in column B appears if column A has a value of "1" on it.
Worksheet 1
Column A (A2=1, A4=1, A7=1, A10=1, A13=1, A14=1, A15=1, A17=1, A18=1
Column B (B1= John Doe, B2= Philip Seymour, B3= Anthony Jones, B4= Thomas Moore, B5= Lindsey Lohan, B6= Rudy Duterte, B7= Philip Seymour, B8= Anthony Jones, B9= John Doe, B10= Philip Seymour, B11= Anthony Jones, B12= Thomas Moore, B13=Lindsey Lohan, B14= Rudy Duterte, B15= Anthony Jones, B16= John Doe, B17= Rudy Duterte
the result will be reflected in worksheet two like this
John Doe = 3
Philip Seymour = 1
Anthony Jones = 1
Thomas Moore = 1
Lindsey Lohan = 1
Rudy Duterte = 3

A: Found this and got the result I wanted:
=SUMPRODUCT(('2015'!$B$2:$B$19=Count!A2)*('2015'!$A$2:$A$19=1))


text:
Q: TYPO3 extbase access sorting when using the fluid debug array I see a nested array lige this:
building
 [+]floor
    [+]room

When clicking the + the sub array is expanded sorted by UID and not by the "sorting" as I have specified in my repository.
protected $defaultOrderings = array(
    'sorting' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING
);

Can I either access the sorting value somehow?
Or can I somehow force TYPO3 to sort its own array after sorting?

A: The sorting field should not be manually set.
If you want to sort the entries please use the DataHandler like the Typo3 Backend.
Here is a solution:
TYPO3 CommandController: How to set table field "sorting" of Extbase Object?

A: By "clicking the +", you mean that the subobjects aren't sorted the way you specified in the TCA?
The sorting is lost on the subobjects because Extbases PersistenceRepository by default only sorts by the order specified in the object itself. But thats no biggie, you just have to specify to order by the subproperty, either with the defaultOrderings property or when building the query:
class FloorRepository extends \TYPO3\CMS\Extbase\Persistence\Repository {

    // Order by BE sorting
    protected $defaultOrderings = array(
        'sorting' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING
        'room.sorting' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING
    );

    ...

 }

This should give you the Rooms of a Floor, Ordered by the sorting of the Floors, and in each Floor, the Rooms sorted by their sorting.

A: You can access the sorting property by defining it as integer in your model and creating the related getter (setter if needed)
protected $sorting


text:
Q: Create dictionary from 3 lists - python Looking for some help in creating a dictionary using 3 python lists
a = ['alpha','bravo','charlie']
b = ['a','b','c']
c = [1,2,3]

output:
{'alpha': {'letter': 'a', 'number': 1},
 'bravo': {'letter': 'b', 'number': 2},
 'charlie': {'letter': 'c', 'number': 3}}

I tried something like this. This may be close, but needs some tweaking:
{k: dict(v) for k,v in zip(a, zip(('letter', b),('number', c)))}

A: The dict comprehension can zip all three iterables at once, and just include a dict literal for the sub-dict:
{k: {'letter': let, 'number': num} for k, let, num in zip(a, b, c)}

A: You should zip all 3 lists together:
result = {greek: {'letter': letter, 'number': number} for greek, letter, number in zip(a, b, c)}

A: A zip-heavy version (as you seem to have tried that):
output = {k: dict(zip(('letter', 'number'), vs))
          for k, vs in zip(a, zip(b, c))}

Or:
output = {k: dict(zip(('letter', 'number'), vs))
          for k, *vs in zip(a, b, c)}

Or to use your {k: dict(v) for k,v in zip(a, ...)} and only fix the ... part:
output = {k: dict(v) for k,v in zip(a, map(zip, repeat(('letter', 'number')), zip(b, c)))}

Or with some itertools, making C code do all the work (other than configuring the work):
from itertools import repeat

output = dict(zip(a, map(dict, map(zip, repeat(('letter', 'number')), zip(b, c)))))


text:
Q: PayPal Sandbox not able to find password field I'm currently using HtmlUnitDriver, and while I am able to set the username, I keep getting an error that Selenium could not find the password field. I am using JavascriptExecutor to set these values inside the PayPal sandbox form, but I'm still unable to get past the password step.
HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.CHROME)
JavascriptExecutor executor = (JavascriptExecutor)driver

        driver.setJavascriptEnabled(true)
        driver.get(url)
        log.debug "setting username"
        Thread.sleep(5000)
        if(driver.findElement(By.xpath("//*[@id='email']")).displayed){
            executor.executeScript("document.getElementById('email').value = 'email';")
            log.debug "Username was set"

        } else {
            log.debug "We never set the username!"
        }

        if(driver.findElement(By.xpath("//*[@id='password']")).displayed){
            executor.executeScript("document.getElementById('password').value='password';")

        } else {
            log.debug "We never set the password."
        }

I understand that I am setting sleeps in there, and that's bad practice for Selenium testing, but I'm pretty much at my wits end here. The url in that case is the link to express checkout, which is something like this: https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=#################
Any help would be greatly appreciated!

A: As I mentioned earlier, there are multiple issues here:

*

*When I load the initial page, I see this UI:

As you see, Password button is really invisible. So unless we click the Next button, there's no chance that this script will work.
So the following has to be added in order to achieve any kind of progress:
driver.findElement(By.id("btnNext")).submit()

*However unfortunately I cannot get this button to be clicked correctly with HtmlUnitDriver. It seems button is clicked, but nothing happens, so Password field remains hidden. However as soon as I switch to ChromeDriver, this is not an issue anymore, and the same code works. So I guess you've hit one of the HtmlUnitDriver limitations, and need to use Chrome or Gecko driver.

*Finally a few adjustments to the code will make it more reliable and faster. Here's the final version that works for "real" browsers (Chrome or Gecko):
    WebDriver driver = new ChromeDriver()
    WebDriverWait wait = new WebDriverWait(driver, 10)

    driver.get(url)

    // The following line waits for email field to appear. It's more economical and reliable than Thread.sleep
    WebElement email = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("email")))
    log.debug "setting username"
    email.sendKeys("email@gmail.com")
    log.debug "Username was set " + email.getAttribute("value")

    driver.findElement(By.id("btnNext")).submit()

    // Here again using the same method to verify when password becomes visible
    WebElement password = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("password")))
    log.debug "setting password"
    password.sendKeys("password")
    log.debug "Password was set " + password.getAttribute("value")

(note: I wrote this code in Java, so I hope I translated all correctly, but if I didn't feel free to fix it)
The result of this script looks like this in Chrome:

With HtmlUnitDriver, script will show an error:

org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.id: email (tried for 10 second(s) with 500 MILLISECONDS interval)


text:
Q: Regex to validate several ranges of values (.NET) I have the option to use a regex to validate some values and I would like to know the best way to do it.
I have several ranges (not in the same regex/validation) such as 1-9 (this is easy :P), and:
1-99
1-999
1-9999
Also, I need to check for leading zeros, so, 0432 is a possible match.
I know that Regex might not be the best approach for this, but it's what I have, and it's part of a framework I have to use.

A: There is a fundamental flaw with all other answers!!
bool isMatch = Regex.IsMatch("9999", @"\d{1,3}");

Returns true although the number is not a 1-3 digit number. That is because part of the word matches the expression.
You needs to use:
bool isMatch = Regex.IsMatch("9999", @"^\d{1,n}$");

Where n is the maximum number of digits.
UPDATE
In order to make sure it is not zero, change it to below:
bool isMatch = Regex.IsMatch("9999", @"(^\d{2,n}$)|[1-9]");

UPDATE 2
It still would not work if we have 00 or 000 or 0000. My brain hurts, I will have a look again later. We can do it as two expressions ("(^\d{2,n}$)|[1-9]" and NOT (0)|(00)|(000)|(0000)) but that probably is not accepted as a SINGLE regex answer.

A: The easy way (n is the amount of numbers):
[0-9]{n}

A: I'm not 100% clear on what you want but perhaps something like this?
\d{1,2}

This is the equivalent to \d\d? and will match any one- or two-digit number, that is any number from 0 to 99, including leading zeros.
If you really want to exclude 0, then things get a lot more complicated.
Basically, you need to check for 1–9 and 01–09 explicitly. The third group of allowed numbers will have two digits that do not start with a zero:
0?[123456789]|[123456789]\d

Now the part before the | will check whether it's a number below 10, with optional leading zero. The second alternative will check whether it's a two-digit number not starting with a zero.
The rest of the ranges can be checked by extending this.


text:
Q: \leftskip, \linewidth and minipage I have an environment with a minipageof the length \linewidth-\parindent (using the calc package). When I stick this in a place where \leftskip=\parindent it protrudes in the margin. Shouldn't \linewidth adapt to these new dimensions and keep the minipage inside the margin?
\documentclass{article}
\usepackage{blindtext}
\usepackage{calc}

\newenvironment{env}
    {\hfill\begin{minipage}{\linewidth-\parindent}\bf}
    {\end{minipage}}

\begin{document}

\tiny

\blindtext

\begin{env}
\blindtext
\end{env}

\blindtext

\setlength{\leftskip}{\parindent}

\blindtext

\begin{env}
\blindtext
\end{env}

\end{document}

EDIT: With the hints from David I found what I needed from this question (is this a duplicate?):
\newenvironment{env}
    {\list{}{}\item\relax
    \nointerlineskip\leavevmode}
    {\endlist}

This indents the margin via list (like LaTeXs quote) and \nointerlineskip\leavevmode fixes problems with missing items.

A: If you set a TeX primitive register such as \leftskip then nothing is recalculated not \linewidth or \leftmargin or \@totaleftmargin that is why LaTeX has a list structure and a list environment to set all these parameters to consistent value.
If you want an indented region, do not set \leftskip use quote or a similarly defined environment.
Never set \leftskip directly in latex you will break almost all its display constructs (not just your own definitions).

A: Though probably different from what the OP is asking, the following is just a suggestion using the changepage package to achieve the indented paragraphs. Hope it helps. A little bit more insight as to the usage of the environment would help to provide a more suitable solution. Referencing is possible.

\documentclass[letterpaper]{article}
\usepackage{lipsum}
\usepackage{changepage}
\begin{document}
\lipsum[1-1]
\begin{adjustwidth*}{0.25\linewidth}{}
\lipsum[1-1]
\begin{equation}
    E=mc^2 \label{eq1}
\end{equation}
    \begin{enumerate}
        \item one \label{item1}
    \end{enumerate}
\end{adjustwidth*}
Reference Equation~\ref{eq1}. Reference Item~\ref{item1}.

\lipsum[1-1]
\end{document}


text:
Q: VB. Prime number checker. Invalid input Can't seem to make my code work when I try to add in integer.tryparse to handle invalid input and for the message to read "invalid input". For example, if the number is a letter instead of a number. Here is what I have so far:
Public Class Form1

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        Answer.Text = ""
    End Sub

    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
        Dim iNum, iSum As Double
        Dim isPrime As Boolean = False
        iNum = Integer.Parse(TextBox1.Text)
        For i = 2 To Math.Sqrt(iNum) Step 1
            iSum = iNum Mod i
            If (iSum = 0) Then
                isPrime = True
                Exit For
            End If
        Next
        If isPrime Then
            Answer.Text = "Is Not Prime"
        Else
            Answer.Text = "Is Prime"
        End If
    End Sub

End Class

A: This should do it:
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
    Dim iNum, iSum As Double
    Dim isPrime As Boolean = False
    If Not Integer.TryParse(TextBox1.Text, iNum)
        Answer.Text = "invalid input"
    Else
        For i = 2 To Math.Sqrt(iNum) Step 1
            iSum = iNum Mod i
            If (iSum = 0) Then
                isPrime = True
                Exit For
            End If
        Next
        If isPrime Then
            Answer.Text = "Is Not Prime"
        Else
            Answer.Text = "Is Prime"
        End If
    End If
End Sub


text:
Q: Newly configured fields of WIT's not showing up in existing TFS Project I am trying to do some configurations of TFS work items. I added couple of new fields in the WIT type Bug. Then I uploaded the Process template using Visual Studio. But I dont see the changes in my existing Projects. If I create a new Project based on template that I changed, the new fields do appear in the new Project's Bug work item type.
I tried restarting Visual Studio, Browser, cleared cache but no use.

A: That is because you just uploaded a Process Template. The template is only used on creating new Projects as you mentioned correctly.
If you want to use the new fields in existing Teamprojects, you need to import the WIT Bug to those.
You can do this with the witadmin.exe in the Developer Command Prompt for  Visual Studio.
eg.
witadmin.exe importwitd /collection:http://[tfsserver]:[port]/tfs/[collectionname]/ /p:[projectname] /f:[c:\temp\bug.xml]

Replace the parameters in the braces []
Documentation to witadmin.exe can be found here