text:
Q: How to update one of the table columns which is basically having Year i just need an incremental update My table name is kanaja_postmeta and i have around 1000 rows where i want to change the meta_value column values from 2017-01-23 00:00:00 to 2018-01-23 00:00:00,
I tried using the query
Update `kanaja_wp`.`kanaja_postmeta` set `meta_value` = Date_Add(YYYY,+1,`meta_value`);

but getting an error code 1064.

    meta_id
    post_id
    meta_key
    meta_value

    403723
    131871
    _EventStartDate
    2017-01-23,00:00:00

    404269
    131881
    _EventStartDate
    2017-01-03 00:00:00

    404485
    131883
    _EventStartDate
    2017-01-03 00:00:00

    405271
    131885
    _EventStartDate
    2017-12-20 00:00:00

meta_id post_id meta_key meta_value

403723  131871  _EventStartDate 2017-01-23 00:00:00
404269  131881  _EventStartDate 2017-01-03 00:00:00
404485  131883  _EventStartDate 2017-01-03 00:00:00
405271  131885  _EventStartDate 2017-12-20 00:00:00
404695  131887  _EventStartDate 2017-01-04 00:00:00

I just want to change only the year 2017 to 2018 how can i do that.

A: I used two mysql function in combination with each other. One to turn your specific date format into a unix timestamp and one function to return a proper datetime after adding a year to it.
Here is an example of how to add one year to a datetime
SELECT
  FROM_UNIXTIME(
    UNIX_TIMESTAMP('2017-01-23 00:00:00') + (60 * 60 * 24 * 365)
  )

A: Just try with below mysql query:
 UPDATE kanaja_wp.kanaja_postmeta SET meta_value = DATE_ADD('2017-01-23 00:00:00', INTERVAL 1 YEAR) **WHERE ID =1**

But make sure that you add proper where condition.

A: This query works fine and it fulfilled my requirement
UPDATE kanaja_wp.kanaja_postmeta
SET meta_value = DATE_ADD(meta_value, INTERVAL 1 YEAR)
WHERE meta_key="_EventEndDateUTC";

It works for all row names both start and End date as well.
Thanks for the answers :)


text:
Q: How to dynamically create onTap gestures as a user inputs text? I want to create a custom input field which matches some known strings and then changes the style and adds an onTap gesture when those text values are pressed (ideally using a modifier key to trigger the onTap - I'm using windows for this project - though I think I can figure this out on my own if I can get the rest of the system nailed down) dynamically as the user inputs text.
I've tried to research this, but most of the options I've seen seem to only want to change the style of the text, or don't seem to function as a dynamic text replacement.
One option was to extend TextEditingController and override the buildTextSpan function, but it's not clear to me that this provides a way to create onTap gestures for each individual block (or even blocks) of text.
Unfortunately, I can't provide any examples of what I've done to try this, because I'm not sure there's a predefined system that can accomplish this.
-- EDIT --
A bit more clarity on what I'm looking for.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed doe eiusmod
tempor incididunt ut labore et dolore magna aliqua. Amet commodo nulla
facilisi nullam vehicula. [onclick](https://stackoverflow.com/posts/71918728)
faucibus
interdum posuere lorem.
[onclick2](https://stackoverflow.com/posts/71918728)
Potenti
nullam ac tortor vitae purus
faucibus. Tellus cras adipiscing enim eu
turpis egestas pretium aenean pharetra. Mauris pellentesque pulvinar
pellentesque habitant [onclickN](https://stackoverflow.com/posts/71918728)
morbi tristique.
 Odio pellentesque diam volutpat
commodo sed egestas egestas fringilla. Nec sagittis aliquam malesuada
bibendum arcu vitae elementum curabitur. Scelerisque purus semper eget duis
at tellus. Convallis tellus id interdum velit laoreet id donec ultrices.

The idea is that the user can input text, and some known strings would automatically be tagged and built as an onClick detector with some optional styling. The text and links above show more or less how I think it would look for an end user (roughly, of course) however it should be dynamically created as the user inputs text.

A: you can try extended_text_field, with this, you can create your on reg text, such as @ or # with tap gesture:
class AtText extends SpecialText {
  static const String flag = "@";
  final int start;

  /// whether show background for @somebody
  final bool showAtBackground;

  AtText(TextStyle textStyle, SpecialTextGestureTapCallback onTap,
      {this.showAtBackground: false, this.start})
      : super(
          flag,
          " ",
          textStyle,
        );

  @override
  InlineSpan finishText() {
    TextStyle textStyle =
        this.textStyle?.copyWith(color: Colors.blue, fontSize: 16.0);

    final String atText = toString();

    return showAtBackground
        ? BackgroundTextSpan(
            background: Paint()..color = Colors.blue.withOpacity(0.15),
            text: atText,
            actualText: atText,
            start: start,

            ///caret can move into special text
            deleteAll: true,
            style: textStyle,
            recognizer: (TapGestureRecognizer()
              ..onTap = () {
                if (onTap != null) onTap(atText);
              }))
        : SpecialTextSpan(
            text: atText,
            actualText: atText,
            start: start,
            style: textStyle,
            recognizer: (TapGestureRecognizer()
              ..onTap = () {
                if (onTap != null) onTap(atText);
              }));
  }
}

A: here is the custom Form field extends of StatelessWidget...
it's one of the reusable components ways to create a dynamic Widget to use
anywhere in your App...
if you looking to add more arguments (click on any properties then click Ctrl+Q)
to know the DataType of the property so you can define it then pass to the contractor
for Example, onSaved is a void Function() DataType and so on...
`class CustomFormField extends StatelessWidget {
  const CustomFormField(
      {
      this.onSaved,
      required this.textInputType,
      required this.suffixIcon,
      this.obscureText,
      required this.validator,
        this.controller,Key? key}) : super (key: key);

  final void Function(String?)? onSaved;
  final TextInputType? textInputType;
  final Widget? suffixIcon;
  final bool? obscureText;
  final FormFieldValidator? validator;
  final TextEditingController? controller;

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      validator: validator,
      keyboardType: textInputType,
      controller: controller,
      decoration: InputDecoration(
          suffixIcon: suffixIcon,
          floatingLabelBehavior: FloatingLabelBehavior.always,
          enabledBorder: _outlineInputBorder(),
      onSaved: onSaved,
      obscureText: obscureText ?? false,
    );
  }

  OutlineInputBorder _outlineInputBorder() {
    return OutlineInputBorder(
      borderRadius: BorderRadius.circular(20),
      borderSide: const BorderSide(color: Colors.black),
      gapPadding:  10,
    );
  }
}`

A: The most customizable example of how to solve this problem is by extending TextEditingController. Once TextEditingController is extended, overriding buildTextSpan() allows you to selectively style TextSpans. This also allows you to add a recognizer to the TextSpan, which is what we're really after. This article provides a write up on the idea. https://www.flutterclutter.dev/flutter/tutorials/styling-parts-of-a-textfield/2021/101326/.
class CustomTextController extends TextEditingController {
  CustomTextController();

  @override
  TextSpan buildTextSpan(
      {required BuildContext context,
      TextStyle? style,
      required bool withComposing}) {
    final List<InlineSpan> textSpanChildren = [];
    text.splitMapJoin('test', onMatch: (match) {
      final String? matchVal = match.group(0);
      _addTextSpan(
          textSpanChildren,
          matchVal,
          style,
          TapGestureRecognizer()
            ..onTap = () {
              print('tapped');
            });
      return '';
    }, onNonMatch: (String text) {
      _addTextSpan(textSpanChildren, text, style, null);
      return '';
    });

    return TextSpan(
      children: textSpanChildren,
    );
  }

  void _addTextSpan(
    List<InlineSpan> textSpanChildren,
    String? textToBeStyled,
    TextStyle? style,
    GestureRecognizer? gestureRecognizer,
  ) {
    textSpanChildren.add(
      TextSpan(
        text: textToBeStyled,
        style: style,
        recognizer: gestureRecognizer,
      ),
    );
  }
}

When overriding buildTextSpan(), first we set up a list to hold the TextSpans we want the user to actually see.
Next, split the text using splitMapJoin to a pattern - either a regex or a simple string - and on each match to our pattern, we add a TextSpan to the list of children we want to use for our final TextSpan which returns from buildTextSpan().
This is where we can add the inline onTap functionality. When we add a TextSpan to the textSpanChildren list, using _addTextSpan, we can add a recognizer to the TextSpan. For example, we can add a TapGestureRecognizer and can set the onTap callback using TapGestureRecognizer()..onTap = () {}.
The matches don't need to return anything special because we aren't using the results of splitMapJoin, just the iteration over the parts of the string, so returning '' is fine. onNonMatch works similarly, but since we don't have any interest in this value, we can simply say there's no need for a recognizer.
In the code example above, you can create a TextField using the extended controller, and whatever matches the pattern in splitMapJoin will have a tap gesture on it.
Obviously, the example above has only a single, hard-coded pattern to match, but you can refer to the link above if you'd like a more extensible approach that builds a regex pattern depending on an arbitrary amount of input patterns.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inverse of polynomial in $(\mathbb{Z}/m\mathbb{Z})[X]/(x^N-1)$ where $m$ is a prime power. I want to check if my answer to the following question is sound.
Note: The operation ($\star$) denotes polynomial multiplication in a quotient polynomial ring, and $p$ is a prime.
Suppose $f(x) \in \mathbb{Z}[x]/(x^N-1)$ such that there exist $F(x)$ and $f(x)\star F(x)\equiv 1 (\bmod p^i)$ for some $i\geq 1$.  Prove that the polynomial $G(x) = F(x)\star (2-f(x)\star F(x))$ satisfies $f(x)\star G(x)\equiv 1 (\bmod p^{2i})$
Source: Hoffstein-Pipher-Silverman, an introduction to mathematical cryptography. Problem 7.27, page 460
Following is my attempt:
$f(x)\star G(x) = 2\star f(x)\star F(x) - f(x)^2\star F(x)^2$. Hence, $f(x)\star G(x) (\bmod p^i) \equiv 2-1 (\bmod p^i) \equiv 1 (\bmod p^i)$.
Since $\mathbb{Z}/p^i\mathbb{Z} \subset \mathbb{Z}/p^{2i}\mathbb{Z}$, it follows that $f(x)\star G(x) \equiv 1 (\bmod p^{2i})$
In the above proof, I am using the assumption that $\mathbb{Z}/p^i\mathbb{Z} \subset \mathbb{Z}/p^{2i}\mathbb{Z}$. However, I am not sure of that fact. At least, by looking at the element of $\mathbb{Z}/5\mathbb{Z}$ and $\mathbb{Z}/25\mathbb{Z}$ as integer, it follows that $\mathbb{Z}/5\mathbb{Z} \subset \mathbb{Z}/25\mathbb{Z}$.
Any help/hint will be welcomed. Also, if this is a duplicated question or the wrong StackExchange, I apologize in advance. A quick search on this stack exchange did not produce a similar question.

A: Obviously $\equiv 1\bmod p^i$ doesn't imply $\equiv 1 \bmod p^{2i}$.
Write $fF = 1+p^i H$ so that
$$fG = 2fF - (fF)^2= 2+2p^i H- 1-p^{2i} H^2-2p^i H$$


text:
Q: Reclassify is not including one value in its range of one class? Trying to reclassify data into a binary map of 0's for no data (in this case, no flooding) and 1's for any level of data (flooding). Range for 1's is about 0-85 feet. and 0's are NO DATA.

But, when I do the reclassification, the output is 3 classes - 0, 1, and 85. The 85's are 4 pixels with a value of 85. I don't understand why this is a separate class, when it is within the range for 1 (0.335534 - 85.22314).

This only happens sometimes, despite my using the same process again and again. I don't have any exclusions listed in the classify box.
Does anyone know why this is happening?

A: One possibility is that your range in Old Values does not include all pixel values. For example, if you have a pixel value of 85.49, it will be rounded off to integer 85 as the output raster will always be of integer type according to documentation.
Also according to the documentation above

The input raster must have valid statistics. If the statistics do not
  exist, they can be created ...

The documentation then described a set of rules by which ArcGIS comes up with a remap table, which could be missing some pixel values in figuring out the range. According to this thread in GeoNet, for example:

Apparently, the default behavior of ArcGIS is to calculate raster
  histograms quickly using some unspecified subset of the data (even
  though it says that the sampling pattern for GRID files is to use all
  the data/no skipping!). You can force the program to consider all of
  the unique data values using the instructions contained here:
  http://resources.arcgis.com/content/kbase?fa=articleShow&d=35443


text:
Q: Toast with custom message I start to learn Android programming, and now I try to display a toast with a custom string.
Random r = new Random();
int i = r.nextInt(100 - 90 + 1) + 90;
String message = String.format(r);

Toast.makeText(getApplicationContext(), "@".replace(message), Toast.LENGTH_LONG).show();

Any ideas what I'm doing wrong? I'm getting the following error message:

Error:(40, 40) error: no suitable method found for format(Random) method String.format(String,Object...) is not applicable (argument mismatch; Random cannot be converted to String) method String.format(Locale,String,Object...) is not applicable (argument mismatch; Random cannot be converted to Locale)

A: Ok. Looks like int cannot be converted to String.
So this fixed my problem:
Random r = new Random();
int i = r.nextInt(100 - 90 + 1) + 90;
String message = String.format(Integer.toString(i));

Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();

A: Even though you've found the answer yourself, I still want to provide some examples to make sure that you understand how String#format(String, Object...) works:
Random r = new Random();
String message = null;

int i = r.nextInt(100 - 90 + 1) + 90;
message = String.format("%d", i);

float f = 0.1;
message = String.format("%f", f);

String s = "Hello world";
message = String.format("%s", s);

// "Hello world, f=0.1"
message = String.format("%s, f=%f", s, f);

More explanation about java formatting can be reached at:

*

*Formatter (Java Platform SE 7 ) - Oracle Help Center

*The Java™ Tutorials - Formatting Numeric Print Output


text:
Q: Network connection between two operation systems in a virtual machine I have a Windows 7 machine with VMware installed on it. I created two separate Windows 2003 Server virtual machines.
I want to establish a network connection between the two virtual machines (Both Windows 2003 Server) through their IP addresses. The IP addresses are 100.100.100.1 and 192.168.10.11.
How do I go about this?

A: Set the network options to bridged network in both VMs, and specify an IP in the same range i.e. 192.168.10.11 and 192.168.10.12. If the IPs are in a different range you'd need a router. besides 192.168.x.xis for private networks, so that it wouldn't be routed.

A: You will need a router on the network.  with a route that looks something like this:
192.168.10.0  to 100.100.100.0
100.100.100.0 to 192.168.10.0
This will bridge the gap between the two networks.  You cannot do this without a router.  Keep in mind if you have other equipment on the network of 192.168.10.0 the above route will give all equipment access to the server on the 100.100.100.0

A: In short
On each guest
Create a second network adapter

*

*custom host-to-host network

*DHCP dynamic

Create a router
Install a third virtual machine and install DHCP router software

*

*create second custom host-to-host network adapter
(first network adapter is router-host network)

*create unique network ROUTER on second adapter

Go back to each guest
Assign second adapter on both guests to ROUTER network
Be carefull
Read the instructions in the step-by-step manual carefully.
Avoid conflict of two DHCP server running on the same network.
Step by Step
An explicit instruction can be found
here
Found in the VMware documentation


text:
Q: Массив и его перебор Есть задача - написать макрос для MS Excel. Макросу нужно указать папку, а он в этой папке должен найти все файлы Эксель и проделать с ними опреации:

*

*Открыть книгу

*Скопировать определенные ячейки

*Вставить их содержимое в другую книгу

*Закрыть книгу

В общем, собрать из всех файлов одну таблицу.
В отличие от привычного Питона, в ВБА не понятно абсолютно всё.
Читал справки на офсайте Майкрософт, но там почему-то дают ложные описания.

*

*Как создать пустой массив, чтобы в него влазило любое количество элементов?
Пробовал Dim ExcelFiles() As Variant, но в этот массив ничего нельзя добавить. Если указать длину, то работает, но хотелось бы узнать как создать именно пустой массив.

*Как узнать кол-во элементов (длину) массива? Ответы нашел только расплывчатые. Аналог Array.length в ЯваСкрипте, например.

*Как работают циклы?
Есть такой фрагмент:

For j = 0 To UBound(ExcelFiles)
    Workbooks.Open (ExcelFiles(j))
    Workbooks(ExcelFiles(j)).Close SaveChanges:=False
Next j
Длина массива ExcelFiles = 3, но фактически цикл выполняет только Workbooks.Open (ExcelFiles(j)) для первого элемента массива. Никаких ошибок не выдаёт. Просто делает вид, как будто всё сделано правильно.
Ну и самое главное: с помощью чего его можно отладить?

A: *

*Массив можно указать минимальный:
ReDim ArrData (1 To 2, 1 To 1)
и добавлять в него элементы, но с сохранением данных можно изменять только последнюю размерность:
 ReDim Preserve ArrData (1 To 2, 1 To 5)

*Длина массива (первая размерность - по умолчанию, можно не указывать):
UBound(ArrData)
UBound(ArrData,2)

*Не цикл виноват. Книга - это объект и в переменную нужно заносить как объект:
Set wBook = Workbooks.Open(Filename:=j)

With wBook
    ' действия в книге
    .Close
End With

С помощью чего производить отладку?
а) доп. программы;
б) очень полезно первой строкой в модуле иметь
Option Explicit

Установить через Tools-Options
Отлавливает ошибки синтаксиса, необъявленные переменные, дублирование переменных или имен процедур. Оч-ч-чень полезная штучка.
Пример: "wBook" "wBoоk" - одна буква "о" кириллическая. Такую ошибку долго можно искать, Option Explicit на нее укажет сразу.
в) Debug.Print
В нужных местах кода с помощью оператора можно взять данные, параметры, значения переменных, промежуточные вычисления и проч. и вывести полученное в окно Immediate (показать окно - Gtrl+G или через меню View)


text:
Q: Why does $n$ have to be a perfect square for me to construct an equilateral triangle out of equal smaller ones? If I have $n$ unit squares and want to build a bigger square out of the ones I already have, it is obvious that $n$ itself has to be a perfect square.
But after doing some elementary math it turned out for me that in order to construct a bigger equilateral triangle out of $n$ unit equilateral triangles, $n$ has to be a perfect square as well! I was completely shocked.
I also know that the square, triangle and hexagon are the only regular polygons you can tile a plane with (and the whole thing I've described doesn't work if you consider hexagons, as was pointed out to me by @Travis), so that was pretty much the end of the journey there.
Is there some kind of explanation to this? It seems very odd to me that you always need a perfect square.

A: If you build a larger triangle out of copies of a triangle (it need not be equilateral), say, $n$ to a side, then any linear dimension of the large triangle is $n$ times as long as that as the small triangle, and so the area of the large triangle is $n^2$ times that of the small, and therefore it takes $n^2$ small triangles to make a large one. The same argument shows that the same applies to any shape for which this works, not just triangles and squares.


text:
Q: Encapsulating common vba code in a separated workbook I have many Excel workbooks in the same shared folder on a file server. In each workbook there's some data and an "Update charts" button that generates / updates charts inside the workbook based on the data.
This is all implemented and works, but I have a maintenance problem... If I have to change or fix something in my macros, I have to update the macros in all workbooks.
I would prefer to have one additional workbook that contains nothing else, but my macros to generate / update the charts. All the other workbooks should call these macros when the button is pressed. That way, when I have to change the chart generation, I could do it in one place. The best would be if the users don't even have to open the macro workbook.
Is there a best practice / advice for that? Can this be safely implemented at all provided that multiple users are simultaneously updating the workbooks and generating the charts using the "Update charts" button?
Thank you.

A: You need to create an add-in with the code. The user loads the add-in once and it stays loaded in Excel until it is removed. The code is always there ready to be executed.
The add-in needs to be able to recognize when a workbook is the right workbook for the code. I use a defined name in all the workbooks that are "appicable" to the add-in. If the activeworkbook has that name, then the code will run. Otherwise it won't.
In the add-in, you need a custom class module that dimensions an Application variable WithEvents. Then you will use the Workbook_Open or Workbook_Activate event to determine if a particular workbook has the defined names.
I don't like to use on-worksheet buttons to do this kind of thing. ActiveX controls are flaky when the control is on a different sheet than the code (you get a lot of Automation errors). And Forms buttons don't have events so they're harder to hook up.
I generally use a Ribbon button with a callback. The callback enables/disables the ribbon based on whether the activeworkbook is applicable.
You don't give a lot of specifics, so neither can I. But hopefully this will start you down the right path.
Ribbon Callbacks
One of the ways that you can make sure your code only runs under the right conditions is to check those conditions at the top of your procedure. The way I prefer to do it, however, is to make the user interface elements unavailable except when the conditions are appropriate.
In the old days, that meant setting the Enabled property of a CommandBarButton. I would use application level events so that every time a workbook window was activated, code like this would run
Application.Commandbars("mybar").Controls("PrintInvoice").Enabled = IsInvoice(ActiveWorkbook)

With the Ribbon, it's different. Ribbon controls (which are defined in XML) have an enabled attribute.  You can set that to True or False. But you can also choose not use the enabled attribute and instead use the getEnabled attribute.
getEnabled="InvoiceAppBtnPrintGetEnabled"

Then in your VBA, you can still use the application level events. But instead of manipulating a CommandBarButton, you simply invalidate the Ribbon. When you invalidate the Ribbon, it forces it to run your InvoiceAppBtnPrintGetEnabled procedure which then enables or disables the ribbon button.
See Ron de Bruin's site for more info: http://www.rondebruin.nl/win/s2/win013.htm


text:
Q: How to save multiple functions as each files(*.sql) in Postgresql? I'm using PostgreSQL version 8.2 and trying to save all functions/views source code as each files on a local.
But it seems to be impossible to extract each function's code to each files.

example:
I'd like to save source files like below:
function a1, a2, a3 -----> a1.sql, a2.sql, a3.sql

How can I do it?

A: This is not a complete solution, but should get you started in the right direction.

Assuming you are using psql for this, you can save the source code of a single function by spooling the output of select procsrc from pg_proc where proname = '...' to a file, e.g.:
\t
\a
\o a1.sql
select prosrc from pg_proc where proname = 'a1';
\o

The \t \a configures psql to only output the content of the column prosrc. The \o a1.sql redirects the query result to a file.
As you want one file per function, you need to run this for each function. You can either do this manually or generate a script which does this by running a SQL statement:
\t \a \o extract_source.sql
select concat('\t '\a \o ', proname, '.sql', chr(10),
              'select prosrc from pg_proc where proname = ''', proname, ''';',
              chr(10),
              '\o', chr(10))
from pg_proc;
\o
\i extract_source.sql

The query generates the first script for each procedure, then runs the generated script.
Not tested, you probably need to tweak that to meet your needs.

Note that the content of prosrc is NOT the complete function.
It lacks the return type, the arguments and the language definition. In more modern Postgres versions you could use pg_get_functiondef() for that, but with 8.2 you  will need to put all those things together using the columns from pg_proc. The most complicated part is getting the function arguments right (because Postgres 8.2 also lacks, pg_get_function_arguments())
Without the arguments, it will be something like:
select concat('create or replace function ',
              proname, '(......) ',
              'returns ', rt.typname,
              ' as $$ ',
              prosrc,
              '$$ language ', l.lanname, ';')
from pg_proc p
  join pg_language l on l.oid = p.prolang
  join pg_type rt on rt.oid = p.prorettype
where proname = 'a1';

instead of "just" select prosrc .... from pg_proc.


text:
Q: Meissner effect, screening current and Lenz's Law The Meissner effect is described as the expulsion of magnetic field from bulk metal by circulating supercurrents near surface as metal becomes superconducting. My understanding of the onset of persistent currents was based on Lenz's law (finite rate of flux change would generate E-field inside the bulk which would then trigger the current) However, wikipedia[1] says that it is a misconception without further explanation.
Then, what mechanism is responsible for the formation of persistent currents?

A: The subtlety here is the difference between a perfect conductor and a superconductor. These are not the same thing!
For a perfect conductor, you expect the material to perfectly resist changes of the internal magnetic field. Thus, you expect that if you start to apply a field , the field will be perfectly screened.
But consider a superconductor in which you apply a magnetic field above the critical temperature T_c, and then cool below T_c. If it were just becoming a perfect conductor at T_c, then it should only care about the rate of change of the magnetic field, and thus it would be perfectly content with the internal applied field.
However, in reality the superconductor expels the magnetic field in this situation (the Meissner effect). This is related to the fact that the superconducting state is a thermodynamic, collective phase.
So the difference between a perfect conductor and a superconductor (for the purposes of this conversation) is that the former perfectly resists changes of the internal magnetic field, while the latter perfectly resists any internal magnetic field at all, whether it is changing or static.


text:
Q: Profit and loss with cost to carry report: Preference to show / not show symbol level information We need the below enhancement in the "Profit and Loss Cost to Carry" Report

*

*Right now when we group this report by selecting any parameter say Account, Asset, Custom UDA 1, etc then automatically Symbol level information also comes.

*But here we need to give the preference. This will be on the front end.
Preference Name: "Show Symbol Info in Grouping": with 2 options True and False.
If True (Default Value): Report will work in the existing way. Means if we select any grouping then automatically Symbol Level information will also come.
If False: In this case just the Summary row will come (not any Symbol Level information)

A: Although it's not the most efficient way to solve this. You could just add a report parameter and set the hidden property of the rowgroup that show the Symbol level data.
So add a new parameter called say pShowSymbols with two options e.g.
Value Label
0     Show Symbols
1     Hide Symbols

Set the default value to 0
Then set the hidden property of the rowgroup that show the Symbol level data to something like
=Parameters!pShowSymbols.Value = 1

This will return true when "Hide Symbols" is selected by the user and the rowgroup will not be shown.


text:
Q: Spliting word between two strings in ruby on rails I have the following string
"summary"=>"Amazing (games) - Master"

I want to fetch values - v1=Amazing and v2= games.
How do I do this using ruby on rails?

A: Use a regular expression with named captures.
EXP = /^(?<v1>\w*)\s*\(\w*\)\s*-\s*(?<v2>\w*)$/.freeze
matches = value.match(EXP)
puts matches[:v1]
puts matches[:v2]

A: You have to find something that is common on all of the strings that you can use as a delimeter to split the string on:
summary = "Amazing (games) - test"

v1, v2 = summary.split("(")

v2 = v2.split(")")[0]

puts v1
puts v2

A: Without a regex you can do
v1, v2 = summary.split(')').first.split('(').map(&:strip)


text:
Q: Why did this automatic expansion array fail? #include<stdio.h>
#include<stdlib.h>

int main() {
  char c;
  int n = 10;
  int *p = (int*) malloc(n * sizeof(int));
  int i = 0, j = 0;

  do {
    scanf("%d", (p + i++));
    c = getchar();
    if (i == n / 2) {
      (int*) realloc(p, n * 2 * sizeof(int));
      n = n * 2;
    }
  } while (c != '\n');

  for (; j < i; j++) {
    printf("%d ", *(p + j));
  }
  free(p);
}

I need an automatic expansion array, when the user input half of the array, it will expand two times bigger than before, and maybe it worked.   But when I input more number into the array, some of the former number are lost.  I don't know why this can happened.  Why realloc function fail to copy the former numbers?
like this
1 2 3 2 2 1 2 3 2 1 2 4 5 3 3 2 1 2 3 2 1 2 3 2 1 2 3 2 1

1990352 0 1973264 0 2 1 2 3 2 1 2 4 5 3 3 2 1 2 3 2 1 2 3 2 1 2 3 2 1

A: The return value of realloc(), the newly allocated pointer, is unused in OP's code.
Save the returned value, test for success, then assign.
// (int*)realloc(p,n*2*sizeof (int));

// Instead
void *new_p = realloc(p, sizeof *p * n * 2);
if (new_p == NULL) {
  Handle_allocation_failure();  // User code here
  return EXIT_FAILURE;
}
p = new_p;
n = n*2;

Avoid sizing to the type as it is error prone.  Sizing to the type of the de-referenced pointer is easy to code right, review and maintain.  Casts not needed.
// Idiom
ptr = malloc(sizeof *ptr * n);


text:
Q: Azure FrontDoor graduation application/origin rollout Is there any details on how to achieve gradual rollout for application (running behind Azure Front door) based on origin health? Something similar to compute where we scale out/in based on some metric.
I am looking for dynamically increase the traffic to an origin based on
scenario 1 - Time
scenario 2: increase step/weighted value based on custom value computed by region. every X hr if region is still healthy increase traffic by Y %. and if health of region goes down, decrease traffic by Y %.


text:
Q: Compress directory to tar.gz with Commons Compress I'm running into a problem using the commons compress library to create a tar.gz of a directory. I have a directory structure that is as follows.
parent/
    child/
        file1.raw
        fileN.raw

I'm using the following code to do the compression. It runs fine without exceptions. However, when I try to decompress that tar.gz, I get a single file with the name "childDirToCompress". Its the correct size so the files have clearly been appended to each other in the tarring process. The desired output would be a directory. I can't figure out what I'm doing wrong. Can any wise commons compresser set me upon the correct path?
CreateTarGZ() throws CompressorException, FileNotFoundException, ArchiveException, IOException {
            File f = new File("parent");
            File f2 = new File("parent/childDirToCompress");

            File outFile = new File(f2.getAbsolutePath() + ".tar.gz");
            if(!outFile.exists()){
                outFile.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(outFile);

            TarArchiveOutputStream taos = new TarArchiveOutputStream(new GZIPOutputStream(new BufferedOutputStream(fos)));
            taos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
            taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
            addFilesToCompression(taos, f2, ".");
            taos.close();

        }

        private static void addFilesToCompression(TarArchiveOutputStream taos, File file, String dir) throws IOException{
            taos.putArchiveEntry(new TarArchiveEntry(file, dir));

            if (file.isFile()) {
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                IOUtils.copy(bis, taos);
                taos.closeArchiveEntry();
                bis.close();
            }

            else if(file.isDirectory()) {
                taos.closeArchiveEntry();
                for (File childFile : file.listFiles()) {
                    addFilesToCompression(taos, childFile, file.getName());

                }
            }
        }

A: I ended up doing the following:
public URL createTarGzip() throws IOException {
    Path inputDirectoryPath = ...
    File outputFile = new File("/path/to/filename.tar.gz");

    try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            GzipCompressorOutputStream gzipOutputStream = new GzipCompressorOutputStream(bufferedOutputStream);
            TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(gzipOutputStream)) {

        tarArchiveOutputStream.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
        tarArchiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

        List<File> files = new ArrayList<>(FileUtils.listFiles(
                inputDirectoryPath,
                new RegexFileFilter("^(.*?)"),
                DirectoryFileFilter.DIRECTORY
        ));

        for (int i = 0; i < files.size(); i++) {
            File currentFile = files.get(i);

            String relativeFilePath = new File(inputDirectoryPath.toUri()).toURI().relativize(
                    new File(currentFile.getAbsolutePath()).toURI()).getPath();

            TarArchiveEntry tarEntry = new TarArchiveEntry(currentFile, relativeFilePath);
            tarEntry.setSize(currentFile.length());

            tarArchiveOutputStream.putArchiveEntry(tarEntry);
            tarArchiveOutputStream.write(IOUtils.toByteArray(new FileInputStream(currentFile)));
            tarArchiveOutputStream.closeArchiveEntry();
        }
        tarArchiveOutputStream.close();
        return outputFile.toURI().toURL();
    }
}

This takes care of the some of the edge cases that come up in the other solutions.

A: I had to make some adjustments to @merrick solution to get it to work related to the path. Perhaps with the latest maven dependencies. The currently accepted solution didn't work for me.
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.RegexFileFilter;

public class TAR {

    public static void CreateTarGZ(String inputDirectoryPath, String outputPath) throws IOException {

        File inputFile = new File(inputDirectoryPath);
        File outputFile = new File(outputPath);

        try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                GzipCompressorOutputStream gzipOutputStream = new GzipCompressorOutputStream(bufferedOutputStream);
                TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(gzipOutputStream)) {

            tarArchiveOutputStream.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
            tarArchiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

            List<File> files = new ArrayList<>(FileUtils.listFiles(
                    inputFile,
                    new RegexFileFilter("^(.*?)"),
                    DirectoryFileFilter.DIRECTORY
            ));

            for (int i = 0; i < files.size(); i++) {
                File currentFile = files.get(i);

                String relativeFilePath = inputFile.toURI().relativize(
                        new File(currentFile.getAbsolutePath()).toURI()).getPath();

                TarArchiveEntry tarEntry = new TarArchiveEntry(currentFile, relativeFilePath);
                tarEntry.setSize(currentFile.length());

                tarArchiveOutputStream.putArchiveEntry(tarEntry);
                tarArchiveOutputStream.write(IOUtils.toByteArray(new FileInputStream(currentFile)));
                tarArchiveOutputStream.closeArchiveEntry();
            }
            tarArchiveOutputStream.close();
        }
    }
}

Maven
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.18</version>
        </dependency>

A: Something I use (via Files.walk API), you can chain gzip(tar(youFile));
public static File gzip(File fileToCompress) throws IOException {

    final File gzipFile = new File(fileToCompress.toPath().getParent().toFile(),
            fileToCompress.getName() + ".gz");

    final byte[] buffer = new byte[1024];

    try (FileInputStream in = new FileInputStream(fileToCompress);
            GZIPOutputStream out = new GZIPOutputStream(
                    new FileOutputStream(gzipFile))) {

        int len;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
    }

    return gzipFile;
}

public static File tar(File folderToCompress) throws IOException, ArchiveException {

    final File tarFile = Files.createTempFile(null, ".tar").toFile();

    try (TarArchiveOutputStream out = (TarArchiveOutputStream) new ArchiveStreamFactory()
            .createArchiveOutputStream(ArchiveStreamFactory.TAR,
                    new FileOutputStream(tarFile))) {

        out.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

        Files.walk(folderToCompress.toPath()) //
                .forEach(source -> {

                    if (source.toFile().isFile()) {
                        final String relatifSourcePath = StringUtils.substringAfter(
                                source.toString(), folderToCompress.getPath());

                        final TarArchiveEntry entry = new TarArchiveEntry(
                                source.toFile(), relatifSourcePath);

                        try (InputStream in = new FileInputStream(source.toFile())){
                            out.putArchiveEntry(entry);

                            IOUtils.copy(in, out);

                            out.closeArchiveEntry();
                        }
                        catch (IOException e) {
                            // Handle this better than bellow...
                            throw new RuntimeException(e);
                        }
                    }
                });

    }

    return tarFile;
}

A: Check below for Apache commons-compress and File walker examples.
This example tar.gz a directory.
public static void createTarGzipFolder(Path source) throws IOException {

        if (!Files.isDirectory(source)) {
            throw new IOException("Please provide a directory.");
        }

        // get folder name as zip file name
        String tarFileName = source.getFileName().toString() + ".tar.gz";

        try (OutputStream fOut = Files.newOutputStream(Paths.get(tarFileName));
             BufferedOutputStream buffOut = new BufferedOutputStream(fOut);
             GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(buffOut);
             TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut)) {

            Files.walkFileTree(source, new SimpleFileVisitor<>() {

                @Override
                public FileVisitResult visitFile(Path file,
                                            BasicFileAttributes attributes) {

                    // only copy files, no symbolic links
                    if (attributes.isSymbolicLink()) {
                        return FileVisitResult.CONTINUE;
                    }

                    // get filename
                    Path targetFile = source.relativize(file);

                    try {
                        TarArchiveEntry tarEntry = new TarArchiveEntry(
                                file.toFile(), targetFile.toString());

                        tOut.putArchiveEntry(tarEntry);

                        Files.copy(file, tOut);

                        tOut.closeArchiveEntry();

                        System.out.printf("file : %s%n", file);

                    } catch (IOException e) {
                        System.err.printf("Unable to tar.gz : %s%n%s%n", file, e);
                    }

                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) {
                    System.err.printf("Unable to tar.gz : %s%n%s%n", file, exc);
                    return FileVisitResult.CONTINUE;
                }

            });

            tOut.finish();
        }

    }

This example extracts a tar.gz, and checks zip slip attack.
public static void decompressTarGzipFile(Path source, Path target)
        throws IOException {

        if (Files.notExists(source)) {
            throw new IOException("File doesn't exists!");
        }

        try (InputStream fi = Files.newInputStream(source);
             BufferedInputStream bi = new BufferedInputStream(fi);
             GzipCompressorInputStream gzi = new GzipCompressorInputStream(bi);
             TarArchiveInputStream ti = new TarArchiveInputStream(gzi)) {

            ArchiveEntry entry;
            while ((entry = ti.getNextEntry()) != null) {

                Path newPath = zipSlipProtect(entry, target);

                if (entry.isDirectory()) {
                    Files.createDirectories(newPath);
                } else {

                    // check parent folder again
                    Path parent = newPath.getParent();
                    if (parent != null) {
                        if (Files.notExists(parent)) {
                            Files.createDirectories(parent);
                        }
                    }

                    // copy TarArchiveInputStream to Path newPath
                    Files.copy(ti, newPath, StandardCopyOption.REPLACE_EXISTING);

                }
            }
        }
    }

    private static Path zipSlipProtect(ArchiveEntry entry, Path targetDir)
        throws IOException {

        Path targetDirResolved = targetDir.resolve(entry.getName());

        Path normalizePath = targetDirResolved.normalize();

        if (!normalizePath.startsWith(targetDir)) {
            throw new IOException("Bad entry: " + entry.getName());
        }

        return normalizePath;
    }

References

*

*https://mkyong.com/java/how-to-create-tar-gz-in-java/

*https://commons.apache.org/proper/commons-compress/examples.html

A: I followed this solution and it worked until I was processing a larger set of files and it randomly crashes after processing 15000 - 16000 files. the following line is leaking file handlers:
IOUtils.copy(new FileInputStream(f), tOut);

and the code crashed with a "Too many open files" error at the OS level
The following minor change fix the problem:
FileInputStream in = new FileInputStream(f);
IOUtils.copy(in, tOut);
in.close();

A: I haven't figured out what exactly was going wrong but a scouring of google caches I found a working example. Sorry for the tumbleweed!
public void CreateTarGZ()
    throws FileNotFoundException, IOException
{
    try {
        System.out.println(new File(".").getAbsolutePath());
        dirPath = "parent/childDirToCompress/";
        tarGzPath = "archive.tar.gz";
        fOut = new FileOutputStream(new File(tarGzPath));
        bOut = new BufferedOutputStream(fOut);
        gzOut = new GzipCompressorOutputStream(bOut);
        tOut = new TarArchiveOutputStream(gzOut);
        addFileToTarGz(tOut, dirPath, "");
    } finally {
        tOut.finish();
        tOut.close();
        gzOut.close();
        bOut.close();
        fOut.close();
    }
}

private void addFileToTarGz(TarArchiveOutputStream tOut, String path, String base)
    throws IOException
{
    File f = new File(path);
    System.out.println(f.exists());
    String entryName = base + f.getName();
    TarArchiveEntry tarEntry = new TarArchiveEntry(f, entryName);
    tOut.putArchiveEntry(tarEntry);

    if (f.isFile()) {
        IOUtils.copy(new FileInputStream(f), tOut);
        tOut.closeArchiveEntry();
    } else {
        tOut.closeArchiveEntry();
        File[] children = f.listFiles();
        if (children != null) {
            for (File child : children) {
                System.out.println(child.getName());
                addFileToTarGz(tOut, child.getAbsolutePath(), entryName + "/");
            }
        }
    }
}


text:
Q: Elasticsearch with Java, how to access elements of a multi value field with Java API I have done lots of Googling with this but no luck. Basically I have a field on my document that contains lots of different IDs, I want to go through each one and store it into an ArrayList.
Can this be done / is there an easier way if doing this?

A: I believe you have to cast it. You extract the SearchHitField instance for that field, and then cast to a collection. It should look something like this, for a multi-field of integer IDs:
SearchHitField field = searchHit.getFields().get(fieldName);
List<Integer> value = (List<Integer>) field.getValue();


text:
Q: Fluent Nnihbernate References as one-to-one I have two tables that I want to use with one to one relation.
class ParentMap{
    public ParentMap(){
        References(x => x.ChildMap, "parent_id").Cascade.All();
    }
}

the child has no related mapping.
The problem is that the parent_id column is created at the parent and not at the child.
I can work, but it is not right logically.
What is the best way to map one to one  with references, I really searched (-;
Thanks

A: You can use HasOne on the parent to map it as a one-to-one relationship. This would mean the join happens on the primary key of the tables and the primary keys would be synchronized when saving.
If this does not work for you, then an alternative method is to map:
Parent
public ParentMap()
{
    HasOne(x => x.Child)
        .PropertyRef(x => x.Parent)
        .Cascade.All();
}

Child
public ChildMap()
{
    References(x => x.Parent, "parent_id");
}

This would require you to have a property Parent on the child. One-to-one relationships are bidirectional.


text:
Q: facebook profile img redirect not loading image This must be an easy one, but can't get to solve it:
I'm getting an url from facebook login api, like this:
http://graph.facebook.com/10152374498960753/picture?width=150&height=150

if I store that and put it in a  it doesn't load
<img alt="64x64" class="avatar media-object pull-left" src="http://graph.facebook.com/10152374498960753/picture?width=150&height=150">

because the above url is actually redirecting to another url. Shouldn't the browser deal with the redirect by it self? anyways, How can I get the image to lad??
Thanks!

A: It is working!
This one is working fine
http://graph.facebook.com/zuck/picture?width=170&height=170

Perhaps, the problem is regarding your ID because this user data request
http://graph.facebook.com/10152374498960753

alone gives a Bad Request status.
Make sure you have the right ID and double-check the privacy status of the user.


text:
Q: New version of Ubuntu does not recognize monitor I have installed the new version of Ubuntu, 22.04. All is well except that it does not recognize my monitor, a bit outdated, and it is not possible to change the basic setting.
My monitor is Samsung Syncmaster 940N.
xrandr command output:
carlo@carlo-K31CD-K xrandr xrandr: Failed to get size of gamma for output default Screen 0: minimum 1024 x 768, current 1024 x 768, maximum 1024 x 768 default connected primary 1024x768+0+0 0mm x 0mm 1024x768 76.00*


text:
Q: Java Swing Timers Avoid Repetition After much help from the generous users of this website, I've managed to make my timers function properly in a program I'm designing. Here is a small snippet of the code:
//Class represents what do when a button is pressed
private static class ButtonHandler implements ActionListener {
    public void actionPerformed (ActionEvent e) {
        them.setText("");
        final JButton button = (JButton)e.getSource();
        Timer timer = new Timer(1000, new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        final String tc = random();
                        them.setText("They chose: " + tc + "!");
                        Timer timer = new Timer(1000, new ActionListener() {
                                    @Override
                                    public void actionPerformed(ActionEvent e) {
                                        if (button == rock) {
                                            whoWins("rock", tc);
                                        } else if (button == paper) {
                                            whoWins("paper", tc);
                                        } else if (button == scissors) {
                                            whoWins("scissors", tc);
                                        }
                                        yourWins.setText("Your wins: " + yw);
                                        theirWins.setText("Their wins: " + tw);
                                    }
                                });
                        timer.setRepeats(false);
                        timer.start();

                    }
                });
        timer.setRepeats(false);
        timer.start();
    }

}

What I would like to do is avoid having to define multiple timers just to get them to fire in succession. If it's possible to create a timer class that I call upon when I need to have a delay, that would be best. If I need to replace "new ActionListener()" with "this" or something, please notify me. I am new to java and I'd like to figure this out so I can continue working on various home projects.

A: You Could...
Create a class for each action you need to perform, implementing ActionListener. You will need to supply appropriate methods to set what ever states you need to carry between classes.
Then create a instance of each Timer you need and assign it the appropriate action class (which you created previously) and use isRunning and restart when you want to use them, depending on your needs
You Could...
Create a single instance of an ActionListener and a Timer and some kind of state flag.
The ActionListener would check the state of the flag and take appropriate action based upon its value
When you need to, you would set the flags state and start the Timer.
IMHO, this makes the code rather inflexible as all the states are grouped together, rather then been isolated in there own separate blocks.
You could also use this idea, but instead of setting the flag externally, you would simply prepare the state when you start the Timer and allow the ActionListener to change the state go the flag on each tick of the Timer.
This means you could set the Timer to repeat and each tick would perform a different action, stopping the Timer within the ActionListener when your done...


text:
Q: Multiple negative z-index in dropdown menu I have a dropdown menu with 4 menu categories. One, Two, Three & Four.
Each category have a negative z-index command.
One (z-index-1)
Two (z-index-2)
Three (z-index-2)
Four (z-index-2)
That way, zindex-1 is always in front (ΟΝΕ).
If I press menu Two, I want it to become z-index -1 and the rest to change automatically to -2 etc.
i.e
One (z-index-2)
Two (z-index-1)
Three (z-index-2)
Four (z-index-2)
I wonder , is there a better way to write this code? Thanks

$('.one').css({
'position': 'absolute',
'z-index': '-1'
});

$('.two').css({
'position': 'absolute',
'z-index': '-2'
});

$('.three').css({
'position': 'absolute',
'z-index': '-2'
});

$('.four').css({
'position': 'absolute',
'z-index': '-2'
});

A: for starters -
$('.one,.two,.three,.four').click(function() {
   $('.one,.two,.three,.four').css({position: 'absolute', 'z-index': '-2'});
   $(this).css('z-index', '-1');
})

But if you added your html, and actual purpose in doing that, I believe the answer will be much different.


text:
Q: How to subtracte a value from the CURDATE()? I am trying to get the value of the current day minus five days but i want the result in special format (not the MySQL format) :
SELECT DATE_FORMAT(DATE_SUB( DATE_FORMAT( CURDATE( ) ,  '%d.%m.%Y' ) , INTERVAL -5
DAY ),  '%d.%m.%Y')

I change the format of the curdate() and the format of the result but the current day is:
03.09.2013

i get the result like the following:
25.09.2003

can anybody explain that to me what is wrong why i could not get the right result?

A: First of all, you should subtract the values in DATE (or compatible) format, and then convert it to the format you want to receive:
SELECT DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL -5 DAY), '%d.%m.%Y')

The second issue in your query is that you're subtracting a negative value, witch ends up with adding a value (for example: 10 - (-5) = 15). You should you use one of the following:
SELECT DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 5 DAY), '%d.%m.%Y')

or
SELECT DATE_FORMAT(DATE_ADD(CURDATE(), INTERVAL -5 DAY), '%d.%m.%Y')

There is also a little bit shorter way how to write this query:
SELECT DATE_FORMAT(CURDATE() - INTERVAL 5 DAY,  '%d.%m.%Y')

SQLFiddle here
See also:

*

*ADDDATE() function in the official MySQL documentation


text:
Q: Can i track the email is sent or not in c#? I'm using SMTP to send the email, if the receiver email address is wrong then the email is not sent and no exception found.
So anyone helps me to find out the email was sent or not.?


text:
Q: using rewire to test node ES6 module - function not defined EDIT : This was answered pretty quickly by someone pointing to something obvious in the rewire documentation. Note that I wrapped my modules in IIFEs because I was trying to get node to stop complaining about block scoped declarations outside of strict mode. Instead of using IIFEs (with strict mode), the easier way is just to use the --use-strict flag on your node command:
node --use-strict app.js

that way you can use ES6 in your code as normal and they will still be accessible by rewire. Hooray!

I am trying to test my node ES6 application. More specifically, I am trying to test a function in a module that isn't exported from a module. Currently, I cannot even get that function to be defined in my test. I am trying to use rewire to test this.
I'm not sure if this might a problem with strict mode or using ES6, but I cannot seem to find any hints to solutions online :(
Any help would be appreciated!
Here is my module:
//myModule.js
(function(){
  'use strict';

  let myFunction = () => {
    return 'hello';
  };

})();

And here is my test:
//myModule.spec.js
(function(){
  'use strict';

  let rewire = require('rewire');
  let myModule = rewire('./myModule.js');

  describe('app', () => {

    it('should do something', () => {

      let func = myModule.__get__('myFunction');
      expect(func).toBeDefined();

    });

  });

})();

And this is the output I get from running jasmine-node on the directory:
Failures:

  1) app should do something
   Message:
     ReferenceError: myFunction is not defined
   Stacktrace:
     ReferenceError: myFunction is not defined

A: Those IIFE's you're wrapping your code with are causing the problem. It's even mentioned in the fine manual:

Variables inside functions can not be changed by rewire


text:
Q: How to upload a excel file and parse it in server without saving the file locally in hapi.js I am trying to parse excel file data in the server and it is working fine but the problem is that it is saving file which we upload in the local disk in upload folder and then it is reading data.Here is the code which is working fine but when uploading large xlsx file is the issue because it will require extra memory and create same as another file in local disk.
server.route({
    method: 'post',
    path: `${(options.apiBase || '/xlsx/')}get`,
    config: {
        payload: {
            output: 'stream',
            parse: true,
            allow: 'multipart/form-data'
        }
    },
    handler: function (req, reply) {
        try {
            const data = req.payload;
            if (data.file) {
                let name = data.file.hapi.filename;
                console.log("FIlename: " + name);

                let path = __dirname + "/uploads/" + name;
                let file = fs.createWriteStream(path);

                data.file.pipe(file);
                data.file.on('end', function (err) {

                    if (typeof require !== 'undefined')
                        XLSX = require('xlsx');

                    const workbook = XLSX.readFile(path);
                    console.log("row======>>>>");
                    const sheet_name_list = workbook.SheetNames;
                    const content =
                        XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
                    console.log(content);

                    var ret = {
                        filename: data.file.hapi.filename,
                        headers: data.file.hapi.headers
                    }
                    reply(JSON.stringify(content));
                })
            } catch (err) {
                console.log('Err----------------------' + err);
                // error handling
                reply(Boom.badRequest(err.message, err));
            }
        }
});

next();

A: You need to set config.payload.parse to false. This will return the raw stream. But realize that if you're uploading multipart/form-data, you will need to parse it yourself.
config: {
    payload: {
        output: 'stream',
        parse: false,
        allow: 'multipart/form-data'
    }
}

This is handled by the subtext module. See https://github.com/hapijs/subtext/blob/0bf83af78e364518577913db1bbc9c27bc739d7a/lib/index.js#L67


text:
Q: Sizeof(Array) Prints wrong value I have initialized an array of size 10 but on printing the sizof array shows  40 . The code is as follows  ,
#include <iostream>

using namespace std;

int main() {
    int  arr[10] =  {2,4,5,6,7,8,9,6,90};

        printf("%d \n" , sizeof(arr));

}

Output :
/Users/venkat/Library/Caches/CLion2016.1/cmake/generated/InsertionSort-e101b03d/e101b03d/Debug/InsertionSort
40

Process finished with exit code 0

What does C prints 40 here ?

A: sizeofreturns the size of the array in memory, not the length of the array. Then since sizeof(int) is 4 bytes and your array has 10 int values, its size is 40.

A: Your array contain 10 ints.
10 * sizeof(int)
int here is 32 bits = 4 bytes.
4*10 = 40. Simple math

A: Because sizeof is a built in operator that works on the type of the expression. For arrays (and not pointers) it will print sizeof(array_element_type) * array_length.
On your system, it must be that sizeof(int) is 4.
And once you get excited over learning that
sizeof(array)/sizeof(array[0]) == array_length

bear in mind that once you pass the array into a function, it will decay to a pointer and that will no longer hold.

A: You need to divide sizeof (arr) by the size of one element:
sizeof (arr)/ sizeof (arr[0])
This because sizeof(arr) shows the number of bytes the argument is made of, i.e. sizeof(int) * array dimention


text:
Q: When does $c\mid a(n+x)+b+1$, if we know that $c\mid an+b$? If $an+b$ is divisible by $c$. Then for which values of $x$ will $a(n+x)+b+1$ be divisible by $c$?
$a$, $b$, $c$, $n$, $x$ are all non-negative integers.

A: As suggested in the comments, if $c\mid an+b$, then $$c\mid a(n+x)+b+1 $$$$\iff c\mid a(n+x)+b+1-an-b=ax+1$$
$$\iff ax\equiv -1\pmod{\! c}$$
If $(a,c)=d>1$, then $d\mid -1$, impossible.
So necessarily $(a,c)=1$. It turns out it is sufficient for $x$ to exist.
$a^{-1}$ exists mod $c$, so $ax\equiv -1\iff x\equiv -a^{-1}\pmod{\! c}$.
Expressed without modular arithmetic, we have $$c\mid ax+1\iff a(-x)+ck=1$$
for some integer $k\in\Bbb Z$.
Such integer pair $(-x,k)$ exists iff $(a,c)=1$ by Bezout's lemma.


text:
Q: symfony 2 set locale based on user preferences stored in DB I am trying to set the locale based on the current user's preferences which are stored in the DB.
Our User class therefore has a getPreferredLanguage which returns a locale identify ('en', 'fr_FR', etc.).
I've considered the following approach:

*

*register a "locale" listener service that subscribes to the KernelEvents::REQUEST event.

*this service has access to the security context (via its constructor)

*this service's onKernelRequest method attempts to get the user from the security context, get the user's preferred locale, and set it as the request's locale.

Unfortunately, this doesn't work. When the "locale" listener service's onRequestEvent method is invoked, the security context does not have a token. It seems that the context listener is invoked at a very late stage (with a priority of 0), and it is impossible to tell my "locale" listener to run before the security context.
Does anyone know how to fix this approach, or suggest another one?

A: You may be interested in the locale listener, which I posted in this answer: Symfony2 locale detection: not considering _locale in session
Edit: If a user changes his language in the profile, it's no problem. You can hook into profile edit success event if you're are using FOSUserBundle (master). Otherwise in your profile controller, if you're using a self made system. Here is a example for FOSUserBundle:
<?php
namespace Acme\UserBundle\EventListener;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ChangeLanguageListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
                FOSUserEvents::PROFILE_EDIT_SUCCESS => 'onProfileEditSuccess',
        );
    }

    public function onProfileEditSuccess(FormEvent $event)
    {
        $request = $event->getRequest();
        $session = $request->getSession();
        $form = $event->getForm();
        $user = $form->getData();
        $lang = $user->getLanguage();

        $session->set('_locale', $lang);
        $request->setLocale($lang);
    }
}

and in the services.yml
services:
    acme.change_language:
        class: Acme\UserBundle\EventListener\ChangeLanguageListener
        tags:
            - { name: kernel.event_subscriber }

for multiple sessions in multiple browser is no problem, as every new session requires a new login. Hmm, ok, not after changing the language, as only the current session would be updated. But you can modify the LanguageListener to support this.
And the case if an admin changes the language should be insignificant.

A: If you reach this answer through Google, I am currently using this solution.
    <?php

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatorInterface;

class SetLocaleEventSubscriber implements EventSubscriberInterface
{

    private Security $security;
    private TranslatorInterface $translator;

    public function __construct(Security $security, TranslatorInterface $translator)
    {
        $this->security = $security;
        $this->translator = $translator;
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::CONTROLLER => [
                ['setLocale', 1]
            ]
        ];
    }

    public function setLocale(ControllerEvent $event)
    {
        if (!$event->isMasterRequest()) {
            return;
        }
        $request = $event->getRequest();
        /**
         * @var \App\Entit\User
         */
        $user = $this->security->getUser();

        if ($user) {;
            $request->setLocale($user->getLocale());
            $this->translator->setLocale($user->getLocale());
        }
    }
}

A: In order to achieve this, you need to setup an event subscriber on the Kernel::REQUEST event with a higher priority than the default Locale listener as indicated in the documentation
At this time, you will unfortunately not be able to access to the current logged in user because this is something set in another Symfony event triggered after the Locale listener.
However, you can access to the session.
The solution is to save the user's locale in the session just after a successful login, and then set the locale in the request from the session.
// src/EventSubscriber/UserLocaleSubscriber.php
namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;

/**
 * Stores the locale of the user in the session after the
 * login. This can be used by the LocaleSubscriber afterwards.
 */
class UserLocaleSubscriber implements EventSubscriberInterface
{
    private $requestStack;

    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    public function onInteractiveLogin(InteractiveLoginEvent $event)
    {
        $user = $event->getAuthenticationToken()->getUser();

        if (null !== $user->getLocale()) {
            $this->requestStack->getSession()->set('_locale', $user->getLocale());
        }
    }

    public static function getSubscribedEvents()
    {
        return [
            SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin',
        ];
    }
}

// src/EventSubscriber/LocaleSubscriber.php
namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class LocaleSubscriber implements EventSubscriberInterface
{
    public function onKernelRequest(RequestEvent $event)
    {
        $request = $event->getRequest();

        if ($request->getSession()) {
            // Set user's locale from session
            if ($locale = $request->getSession()->get('_locale')) {
                $request->setLocale($locale);
            }
        }
    }

    public static function getSubscribedEvents()
    {
        return [
            // must be registered before (i.e. with a higher priority than) the default Locale listener
            KernelEvents::REQUEST => [['onKernelRequest', 20]],
        ];
    }
}


text:
Q: Setting desktop picture in OS X 10.6
Possible Duplicate:
How can I programatically change the background in Mac OS X?

Hi,
I've whipped together a small (in this case python, but the language is not important) script which gets a jpg from a webpage and sets it as the current background image in OSX (testing and coding on 10.6.3).
My question is how to effectuate the setting of the background image.
My current approach involves regex replacing the paths in ~/Library/Preferences/com.apple.desktop.plist and then restarting (killing) Finder.app.
The last part does not work, as restarting finder, by killing it, doesn't reset/re-initializes the plist.
Do anyone have a better idea, or if there's any kind of signal (i.e. from terminal) I can use? Any idea is greatly appreciated.

*

*Chuck


text:
Q: Show Prestashop Layered Navigation Block and All Products on Home Page I am creating an e-commerce website on the platform of prestashop. I tried various ways to to show the product filters i.e. Layered Navigation Block to appear on the home page. How can I do this ? I'm using the default theme of Prestashop.
Also, on the home page, only a few products are being displayed. For Example, only the popular and the best seller products are being displayed. Instead, I wish to display all the products on the home page. How can I do this ?

A: You can try to use "Home featured products" and set a necessary number of products to display in it in order to show more products on your homepage. It is the simplest way to solve your requirements with products, in another case you need to use some third-party modules to do it. What about the second point, you can't use default Layered Navigation Module outside the Category pages so you also need a third-party module to do this or need to make some development to the module.


text:
Q: CSS and JS files sometimes can't load on our Wordpress website I have trouble to get and know about this issue.
We have our website which is built on Wordpress CMS. One month ago, I did some website optimization related to website speed, because our website loads too slow.
But after doing some stuffs by using wp-optimize and wp-fastest-cache plugin. Our website sometimes may not loads CSS and JS files properly at the time of loading.
While visiting our some website pages, it will loads only content and images.
Why it was happening? There is any solution to overcomes from this problem.
Thanks,
Gopal Kshirsagar


text:
Q: Angular 6 - How to disable all buttons excluding clicked button I have been using Angular for a couple of weeks now and it's starting to make sense and I can mostly fix any problems I find but this one I don't know where to start. If it was JQuery, it wouldn't be a problem.
I have a form which has an edit button next to each text box.

When you click the edit button, it makes the field editable and change the buttons to save and close. It also disables all the other edit buttons until either the save or close button is clicked.

What I wanted to do is have a text box with a Bootstrap 4 class which makes the field readonly and when you click the edit button, it removes the Bootstrap class and makes it editable. I couldn't get to work so I implemented another solution which I am not happy with even though it works.
This is my HTML page which is cut down to the 2 elements show but there are more
<form [formGroup]="editForm">

        Developer Name

            {{ developer.developerName }}<button (click)="editDeveloperName()" [disabled]="disabled" class="btn btn-sm btn-link" type="button"></button>

        Developer Name

                <input type="text" formControlName="developerName" name="developerName" class="form-control" id="developerName">

                    <button (click)="saveDeveloperName()" class="btn btn-success" type="button"></button>
                    <button (click)="closeDeveloperName()" class="btn btn-default" type="button"></button>

        Reception Phone

            {{ developer.receptionPhone }}<button (click)="editReceptionPhone()" [disabled]="disabled" class="btn btn-sm btn-link" type="button"></button>

        Reception Phone

                <input type="text" formControlName="receptionPhone" name="receptionPhone" class="form-control" id="receptionPhone">

                    <button (click)="saveReceptionPhone()" class="btn btn-success" type="button"></button>
                    <button (click)="closeReceptionPhone()" class="btn btn-default" type="button"></button>

  </form>

This is my component (stripped down to show important info)
export class DeveloperDetailComponent implements OnInit {

    developer: Developer;
  editForm: FormGroup;
  disabled: boolean = false;

  developerNameEditBtn: boolean = false;
  receptionPhoneEditBtn: boolean = false;
  // more of these for other formelements

  developerNameEdit: boolean = false;
  receptionPhoneEdit: boolean = false;
  // more of these for other formelements

  constructor() {} //other stuff in here

  ngOnInit() {}//other stuff in here

  editDeveloperName() {
    this.developerNameEdit = true;
    this.disabled = true;
  }

  saveDeveloperName() {
    this.disabled = false;
  }

  closeDeveloperName() {
    this.developerNameEdit = false;
    this.disabled = false;
  }

  editReceptionPhone() {
    this.receptionPhoneEdit = true;
    this.disabled = true;
  }

  saveReceptionPhone() {
    this.disabled = false;
  }

  closeReceptionPhone() {
    this.receptionPhoneEdit = false;
    this.disabled = false;
  }
}

I worked out that I need 3 functions.

*

*edit

*save

*close

I thought about somehow passing the input element to the functions and in those function handle the disabling of the other elements etc.
Has anyone got suggestions on how to do this? Maybe links to examples that do something similar. After some research I thought about using directives but don't know where to start.


text:
Q: IBM DataPower write error(8) Our DP can act as both client and server in our architecture . First, our members call our service, then our asynchronous service call theirs. First transaction completed successfully but in second transaction, I am getting error below:
wsgw (OI_MemberServices): DP Error: 0x0113001c|0x00000000|Connection error
wsgw (OI_MemberServices): Connection error
wsgw (OI_MemberServices): Error in stream. Descriptor number unavailable. Additional information: Write error (8)
wsgw (OI_MemberServices): Network Error on back side server https://BE_MEMBER_YKR:8443/tr.com.gnx.matchIdentitiesResult.web/matchIdentitiesResultWs

But, I have noticed something today. At top of these logs:
valcred (OIClientValCred): SSLProxyProfile 'OI2WSSLPP': connection error: certificate not trusted

Actually, I did not pay attention to it first because it had different tid. Could it possible that they are related somehow? There is also something else, we use same SSL cert in our test env for same member and nothing went wrong so far.
What I did to solve this:

*

*I had tcpdump for both side. Nothing suspicious.

*Their service is up and reachable.

*SSL Proxy Profile > OI2WSSLPP > Permit Connections to Insecure SSL Servers : off > on

*SSL Proxy Profile > OIClientSSLPP > Permit Connections to Insecure SSL Servers : off > on

*Crypto Profile > OIClientCP > Permit insecure SSL renegotiation to a legacy SSL client : disabled > enabled

All advises are much appriciated!!
tnx
DP Firmware: XI52.6.0.0.3


text:
Q: Maintain initial list items order while adding or removing items in it I need to be able to remove items from the list and insert them back while maintaining the same order. My list begins with initial set of items. New items can't be inserted. So, added-items and max-item-count stays same.
Example:
My initial list is as following
0=201, 1=402, 2=952, 3=101, 4=-54, 5=0

If I remove items at 2, 4 positions, I have
0=201, 1=402, 3=101, 5=0

But, when I add items of removed positions back to list; {2, 4}, I have
0=201, 1=402, 3=101, 5=0, 2=952, 4=-54

I want the items to be added in initial order. i.e.
0=201, 1=402, 2=952, 3=101, 4=-54, 5=0

They must be in the original order that they were removed in. This is just an example, these values cannot be sorted. They are in the order they were added in.
If you suggest to use a backup list of originals, how do I determine correct adjacent positions to current list? So, if original list has 6 items, and value -54 is at 4 index. I remove {2, 3, 4} items from list. New list's size changes to 3. I can't add item at 4 index in original list to new list at 4 index. New list will have only {0, 1, 2} as valid positions. Besides, this mightn't even keep order.
So the question is, how can I remove and add elements into a list and make sure that the order is kept?
Also, should this be done with a LinkedList? If yes, how?
Edit: Original list is an ArrayList. I can't modify this type. Certainly, I would need to feed it items from another collection after determining correct index.

A: Take a backup list of originals at first, but in Map <Index, Map<oldValue, NewValue>> (As per your requirement). If you remove any item from ArrayList mark the New Value as null in Map.

A: import org.junit.Test

class Fixing60945040 {

    private val originalItems = mutableListOf(
        201, 402, 952, 101, -54, 19
    )

    /**
     * a backup map of original items
     *
     * Why LinkedHashMap? HashMap works with access-order implementation.
     * Items do not keep insertion order in HashMap. So, inserting original
     * items will look like: 402, 19, 101, -54, 952, 201
     *
     * LinkedHashMap keeps insertion-order by default.
     *
     * Map<Int, Boolean> = (value, hidden)
     *
     * So, items like 201, 402 etc are keys for the map
     * and boolean tells us if this item is visible
     */
    private lateinit var backupMap: LinkedHashMap<Int, Boolean>

    /**
     * create a backup of original items
     */
    private fun createBackupMap(): LinkedHashMap<Int, Boolean> {

        val backupMap = LinkedHashMap<Int, Boolean>()
        for (item in originalItems) {
            backupMap[item] = true
        }
        return backupMap
    }

    private fun removeItem(item: Int) {
        println("Removing: $item")

        assert(originalItems.contains(item)) { "Can't remove an item that doesn't exist in the list." }

        // remove this value from original list
        val modified = originalItems.remove(item)
        if (modified) {
            // item was removed. Now, mark this item as hidden in the backup map
            backupMap[item] = false
        }
    }

    private fun insertItem(item: Int) {
        println("Inserting: $item")

        assert(!originalItems.contains(item)) { "Can't insert duplicate item." }
        assert(backupMap.containsKey(item)) { "Can't insert unknown new item." }

        // mark this item as visible in the backup map
        backupMap[item] = true

        // to know the insertion index, we need to iterate through
        // backup map
        var insertionIndex = 0
        for (entry in backupMap) {

            if (!entry.value /* !isVisible */ ) {
                /* not visible, this item is marked as hidden; ignoring */
                continue
            }

            // Is this key same as the item to be inserted?
            if (entry.key == item) {
                // It is. Insert the item.
                originalItems.add(insertionIndex, item)
                break
            } else {
                // It isn't, increase the index; check the next key.
                insertionIndex++
            }
        }
    }

    @Test
    fun test() {
        backupMap = createBackupMap()

        println("list: $originalItems \n")

        removeItem(952)
        removeItem(-54)
        println("list: $originalItems \n")

        removeItem(101)
        println("list: $originalItems \n")

        insertItem(-54)
        println("list: $originalItems \n")

        insertItem(101)
        println("list: $originalItems \n")

        insertItem(952)
        println("list: $originalItems \n")
    }
}

If anyone finds any performance improvement, please comment. If you think there's a better approach, please add an answer.


text:
Q: I am trying to make a bouncy ball collision effect in python pygame, but my ball keeps going under the line, or limit that I gave So here is the full code, but the problem is in the class Ball where my function move is. What happens when it executes is that the ball bounces and starts going lower and lower, just like real life. But when it hits the limit of how low it can go, the ball starts going under the limit.
I am very sorry for having taken your time.
from selectors import SelectorKey
from tkinter import Y
import pygame

pygame.init()
width, height = 1000, 600
Win = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
Acs = 0.5

class Ball():
    def __init__(self):
        self.y = 200
        self.velocity = 10
        self.bouncy = 1

    def draw(self):
        pygame.draw.circle(Win, (255, 0, 0), (500, self.y), 15)

    def move(self):
        self.velocity += Acs
        self.y += self.velocity
        print(self.velocity)
        if self.y > 400:
            self.velocity = -self.velocity + self.bouncy
        if self.y <= 400:
            self.velocity == 0
            self.bouncy == 0
            self.y == 400

def game():
    ball = Ball()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
        ball.move()

        Win.fill((255, 255, 255))
        pygame.draw.line(Win, (0, 0, 0), (0, 400), (1000, 400), 10)
        ball.draw()
        clock.tick(60)
        pygame.display.update()

game()
pygame.quit()

where I have a problem is here:
    def move(self):
        self.velocity += Acs
        self.y += self.velocity
        print(self.velocity)
        if self.y > 400:
            self.velocity = -self.velocity + self.bouncy
        if self.y <= 400:
            self.velocity == 0
            self.bouncy == 0
            self.y == 400

A: The problem with bouncing balls (and every non-linear physics simulation where you have very drastic changes) is that your simulation might put you below the limit in a single time step, so you have to make sure that you enforce the limit. A simple way to fix that for a game is to force the y position when you hit the floor. Change your move method to this and it works (note that the if self.y <= 400: branch didn't do anything, so I removed it).
    def move(self):
        self.velocity += Acs
        self.y += self.velocity
        if self.y > 400:
            self.velocity = -self.velocity + self.bouncy
            self.y = 400  # Ensure the limits

For a slightly more realistic bouncing effect, you can use your self.bouncy attribute as an actual coefficient of restitution and change slightly the formula for the bounce. 5% of loss every bounce gave a reasonably good result.
class Ball():
    def __init__(self):
        self.y = 200
        self.velocity = 10
        self.bouncy = 0.05  # Now a coefficient of restitution

    def draw(self):
        pygame.draw.circle(Win, (255, 0, 0), (500, self.y), 15)

    def move(self):
        self.velocity += Acs
        self.y += self.velocity
        if self.y > 400:  # Note that the loss of velocity is a function of the previous velocity
            self.velocity = -self.velocity + self.bouncy*self.velocity
            self.y = 400  # Ensure the limits


text:
Q: Invalid characters in generated latex sources I'm running doxygen (1.5.8) on a C# project off of Visual Studio 2008 on a Windows machine running XP. While generating the latex code, some illegal sequences are included. It always involves the following sequence: "" (a latin-I with a dieresis, something like the binary shift operator, and a Spanish open-question-mark). I've seen it happen in the context "using {\bf System}", but maybe there are others.
The generated latex file reads
    \begin{CompactItemize}
    \item
    using {\bf System}
    \end{CompactItemize}

While the source is simply:
using System;
using System.Collections.Generic;
using System.Linq;

Some strange Windows BOF character? It seems it's only before the using System; directive (the first of each file).

A:

That's an ISO-8859-1 representation of the UTF-8 encoded character U+FEFF, the BYTE ORDER MARK. The BOM is intended for use as the first code point in UTF-16 files and should not be used in UTF-8 files, but there are some very stupid tools that produce it by default, unfortunately. And if you are creating files by concatenating bits of text from other files you can even end up with BOMs in the middle of your document.
Find the editor that is saving files as "UTF-8 with BOM" and burn it.
ETA re updated question:

using {\bf System}
While the source is simply:
using System;

Check that source in a hex editor for a hidden faux-BOM before the 'using'.

A: It looks like a character encoding problem to me.
That three-character sequence is the Unicode byte-order mark 0xfeff encoded in UTF-8, although I'm not sure why the byte-order mark would be showing up in the middle of your documentation... that could be significant or it could just be a coincidence.


text:
Q: GWT - how to map hierarchy structure of web site into activities / places / widges? i am new here and in GWT, and my english is not so good, so please excuse me.
i need to create a web site, using GWT. the website has hierarchical structure: main global caption, and couple of buttons. each button opens new part of the application, which has its own sub tabs. each one of the sub-tab suppose to be navigatable. for example:
Main form
-> application issues
---> preferences
---> create something
--->edit something
-> administration
---> user management
--> policies
now, i want to understand what is the best option to use GWT.
i thought of two options:
1. there will be in the entry point main activity. in its start function we will create ActivityManager for each sub-menu (= sub tab = child). each sub menu will create activity managers for each its sub menu, and so on.
we will set a display for each activity manager, and fire change place event.
the problem is that i need to manage the places (all the places should go to the main activity, that should takes its params and delegate to the sub places, etc.)
otherwise, when the user copy and paste the url, it will cause only the child activity to start, and the parent activity to be not initialized.

*

*i can create OOP hierarchy of widges, so - there will be an activity for each leaf in the hierarchy structure tree. there will be also matching widges hierarchy. each leaf widge contains its own components, and all its parent components (such as - the main caption of the form)
in this option, there is only one active activity.

what is the best option? how would you implement hierarchy structure?
thanks....

A: The best option for the hierarchy of menus is to use nested TabPanel widgets. These can go as deep as you need and is a great alternative to building menus.
I see you also want to manage two things:

*

*When the user inputs a URL, you want him to land on the correct tab.

*When the user navigates between tabs, you want the URL to change according to where he is going.

Landing the user on the correct tab
For #1, you need to manage the user arriving to your app in method onModuleLoad. See this piece of code for selecting the correct tab.
public void onModuleLoad() {
    tabPanel = new TabPanel();

    tabPanel.add(new HTML("
Page 0 Content: Llamas
"), " Page 0 ");
    tabPanel.add(new HTML("
Page 1 Content: Alpacas
"), " Page 1 ");
    tabPanel.add(new HTML("
Page 2 Content: Camels
"), " Page 2 ");

    String hash = Window.Location.getHash();
    if (hash != null && hash.startsWith("#page")) {
        int tabIndex = Integer.parseInt(hash.substring(5));
        tabPanel.selectTab(tabIndex);
    } else {
        tabPanel.selectTab(0);
    }
    RootPanel.get().add(tabPanel);
}

This code
Managing navigation history
See this page in GWT documentation. My code above was taken from this page, but in my example I removed History management.
In both cases, the key concept is to find the correct widget based on the url hash and selecting it.


text:
Q: Sitecore page editor dropdown I would kindly ask for your help :) From couple of days I am trying to achieve "linked" custom field in content editor and dropdown in page editor.
Basically I want to have dropdown in page editor and content editor which are responsible for a same thing.
In my c# code i have enums which represent directions. I created custom field which accepts assembly and class with overridden onload method and successfully populate dropdown values in the content editor. So far so good but i have no idea how to create dropdown which will represent the same functionality inside page editor.
So please give me any ideas...

A: Judging from your reply to my comment you need to think of the following: How is my field value being rendered onto a page?
If you are always using 1 control to do this then you just need to ensure that this control has 2 different rendering modes depending on the Context.PageMode
But as I understand it you want this dropdown to also appear when someone renders your custom field using a <sc:FieldRenderer>. In this case you'll need to look into the RenderField pipeline of Sitecore. There you find a processor called RenderWebEditing. Possibly through some manipulation here you can get your dropdown appear as you wish.


text:
Q: TypeError: __init__() missing 1 required positional argument: 'message' when calling from command line I am struggling to pass some arguments from the command line, so far the code looks like this:
class DeviceManager:
    def __init__(self):
        self.network_ip = self.__get_network_ip__()
        self.devices = self.__get_devices__()
        self.sort_by("id")
    ...other methods such as pick_by_rangeID(f,t)...

This is the file Tool.py:
    import argparse
    from Device_Manager import*
    if __name__ == "__main__":
        dm = DeviceManager()
        parser = argparse.ArgumentParser()

        parser.add_argument("method", help ="method to call")
        parser.add_argument("-f", type = int, help ="from")
        parser.add_argument("-t", type = int, help ="to")
        args = parser.parse_args()

        if args.method == "sbID":
            dm.pick_by_range_ID(args.f,args.t)

And I am expecting to call it from the command line as: python Tool.py sbID -f 5 -t 6, which leads me to the error: TypeError: __init__() missing 1 required positional argument: 'message', as far as I have read, this happens when an object is initialized with missing arguments of its class.
For my surprise, if I run the method directly as bellow, the exception doesn't occurs.
dm = DeviceManager()
devs = dm.pick_by_range_ID(5,6)

How can I fix this?
Edit: addition of the pick_by_rangeID method:
 def pick_by_range_ID(self,from_ID = 0, to_ID = 999999) -> list:
        selected = []
        for dev in self.devices:
            id = dev.deviceID
            if id >= from_ID and id <= to_ID:
                selected.append(dev)
        if len(selected) == 0:
            raise ArgumentError("There are no IDs in that range.")
        return selected

A: Solution:
The problem is at the line:
raise ArgumentError("There are no IDs in that range.")

ArgumentError takes two arguments (class) ArgumentError(argument: Action | None, message: str)
I solved by doing this:
raise ArgumentError(None, "There are no IDs in that range.")


text:
Q: (Lotto 6/49 simulation) Calculate how many draws will take place until a user-entered combination hits the jackpot I have my code and data for my Lotto 6/49 simulation. I just don't know how to create a simple mathematical expression to calculate how many draws will take place until the user hits the jackpot
Code:
#include <stdio.h>
#include <stdlib.h>     //need this library to use srand and rand without warnings
#include <time.h>       //need this library to use time function
int main(void) {
    int i, j, k , temp, count1=0;
    unsigned int count2=1;
    int select[6];
    int jackpot[6];
    printf("Welcome to Lotto 6/49! The 6 numbers you choose must match the 6 randomly chosen numbers in the lottery in order to win the jackpot. Select your 6 numbers!\n\n");
    for(i=0; i<6; i++)
    {
        printf("Enter a number between 1-49: ");
        scanf("%d", &select[i]);
    }
    srand(time(NULL));
    for(;;){
        for(i=0; i!= 6 ; )  //This loop produces the winning number combination
        {
            temp= (rand() %49)+1;  //produce a random number between 1 and 49
            for( k =0 ; k<i && (temp!=jackpot[k]) ; k++);  //make sure we do not have duplicate

            if (k==i){      //only write to the array if we do not have a duplicate
                jackpot[i] = temp;
                i++;                //only increment the loop if we write a value to the array
            }
        }
        printf("\nThe winning numbers are: ");  //displays the winning numbers
        for(i=0;i<6;i++)
            printf("\t%d\t",jackpot[i]);
        printf("\n");
        // This loop will check the user array with the jackpot array to determine if it is a winning combination
        for(i=0; i<6 && i ==count1; i++){ //if we do not match the first element, we skip the rest
            for(j=0; j<6 ; j++)
            {
                if(select[i]==jackpot[j]){
                    count1+=1;      // only increment if we match
                }
            }
        }
        if(count1==6){ //all 6 numbers matched
            printf("\n\nYou win the JACKPOT! Congratulations! \nIt took you %d draws to win", count2);
            break;
        }
        else{
        count2+=1;
        count1=0;   //reset match count
        }
    }
    return 0;
}

Data (number range limited to 8 numbers for easier recording, eg temp= (rand() %8)+1 instead of temp= (rand() %49)+1 @ line 19.)
Count1 = user input matched
Count2 = # of draws

                                                 ↑
                                 I have no clue how to calculate this