text:
Q: customized pagination in codeigniter I have codeigniter applicatin which have pagination code that work like a charm. Pagination allow the visitor to select how much records he would like to see per page. Now, I would like to add the following:
displaying X to Y from total of Z records.
Now, Z is easy...i have that solved. Can anyone tell me how could I achive this?
Here is the function that i have:
  public function displayAllUsers()
   {

        if ($this->uri->segment(3) !="") {
        $limit = $this->uri->segment(3);
        } else {
        $limit = 10;
        }

        $offset = 4;
        $offset = $this->uri->segment(4);
        $this->db->limit($limit, $offset);
        $data['users'] = $this->backOfficeUsersModel->get();
        $totalresults = $this->db->get('back_office_users')->num_rows();

        $this->session->set_userdata('totalresults', $totalresults);

        //initializing & configuring paging
        $this->load->library('pagination');
        $config['base_url'] = site_url('/backOfficeUsers/displayAllUsers/'.$limit.'/');
        $config['total_rows'] = $totalresults;
        $config['per_page'] = $limit;
        $config['uri_segment'] = 4;
        $config['full_tag_open'] = '

';
        $config['full_tag_close'] = '

';
        $config['cur_tag_open'] = '
';
        $config['cur_tag_close'] = '
';
        $config['num_tag_open'] = '
';
        $config['num_tag_close'] = '
';

        $this->pagination->initialize($config);

       //....irelevant content.....

    } // end of function displayAllUsers

Any help will be deeply appreciated.

A: It shouldn't be that hard. In fact, it's kinda obvious how you can get the value for X and Y if you understand pagination.
First of all, the difference between X and Y will of course be equal to $limit - 1. The value of X should be equal to the variable, $offset, plus 1 (Offset generally starts from 0 not 1). And from there, I'm sure that you understand that Y is equal to $offset + $limit.
$X = $offset + 1;
$Y = $offset + $limit;

In case, you're at the last page, you'll want to make sure you have the right value for Y. You'll need to check the total rows you grab from the database, if it's less than the limit per page, then change it to something like this
if (fetched_rows < $limit)
{
    $Y -= ($limit - fetched_rows);
}


text:
Q: Copy multiple cells from grid to clipboard in excel format? I'm working on a tool which connects to a SQL Database, gets back a dataset, and displays that data in a grid. The user must be able to select a block of cells (just rectangular) and press CTRL+C to copy it to the clipboard.
How do I do this:

*

*In a format that can be pasted into Excel? I'm hoping there's already something ready-made for this. It doesn't need all the clipboard features like Excel, just highlighting a rectangular group of cells and copying it to the clipboard.

*If it can be done in a TStringGrid I would prefer to keep my functionality in that, but could also work with a component which supports this.

A: You can try to copy you cell values as TAB delimited text, something like this code does:
procedure TForm1.Button1Click(Sender: TObject);
var
  S: string;
  X, Y: Integer;
begin
  S := '';
  for Y := StringGrid1.Selection.Top to StringGrid1.Selection.Bottom do
  begin
    for X := StringGrid1.Selection.Left to StringGrid1.Selection.Right - 1 do
      S := S + StringGrid1.Cells[X, Y] + #9;
    S := S + StringGrid1.Cells[StringGrid1.Selection.Right, Y] + sLineBreak;
  end;
  Delete(S, Length(S) - Length(sLineBreak) + 1, Length(sLineBreak));
  Clipboard.AsText := S;
end;

redpajama_set_name: RedPajamaStackExchange


text:
Q: alinear imagenes verticalmente html Cual sería la forma correcta de alinear estas dos imagenes?

He intentado marcarles el mismo margen arriba, entre otras cosas, pero solo me marca de más no de menos, no tengo muchos conocimientos de css. Gracias.

A: Para alinear dos o más objetos del DOM puedes utilizar vertical-align, en tu caso podrías alinear ambos al centro de la siguiente forma:
#button-menu, #logo-menu {
    vertical-align: middle;
}

Las opciones de alineación que tienes son las siguientes:

baseline | sub | super | text-top | text-bottom | middle | top | bottom

Espero sea de ayuda saludos ;)


text:
Q: Does shrinking making space available to partitions everywhere? In Disk Management for Windows 2008, I have an extended partition that looks like this:
|----X:\ Drive----||----Y:\ Drive----||-------Z:\ Drive-------|
I am running out of space for the Y: drive. I have a lot of space I can spare in the Z: drive. If I shrink the Z: drive, will the space be available to extend the Y: drive? Or will the empty space only be for any drives that come after the Z: drive?
I wish there was some kind of preview to this, so I am asking for help.

A: Partition managers like gparted let you expand the disk space in either direction.  Because this is the standard behavior for partitioning, its a safe assumption that Windows 2008 Disk Manager does the same.  If you scale the the first block of your Z:\ drive to the right, those blocks to the right of Y:\ now become available.  Visually...
|----X:\ Drive----||----Y:\ Drive----||>>-----Z:\ Drive-------|

|----X:\ Drive----||----Y:\ Drive----||--free--||--Z:\ Drive--|

|----X:\ Drive----||---------Y:\ Drive---------||--Z:\ Drive--|

Hope this helps!  I believe the W2k8 Disk Manager will give you a "preview" of what's going to happen before it actually writes the changes to the partition table.  Microsoft TechNet seems to agree with me.
Good luck, and remember that backing up should be the first thing you do! ;)


text:
Q: Trimming PS Objects As Though They Are Strings I have an array, $final, where each element in the array is a custom object. Each object is a computername in the form 'computername@ipaddress' (ex: AJFFF01@10.10.10.10). What I need is a list of the computer names without the '@IPADRESS'. I've tried using .toString() on each item, however it returns nothing. Please help!
Below is the output of Get-member of $final (which provides the same methods for $final[0] | gm):
PS C:\windows\system32> $final | gm

   TypeName: Selected.System.Xml.XmlElement

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
#text       NoteProperty System.String #text=AJFFF09@10.10.10.10

Thank you all in advance.

A: so it looks like you have an array of XmlElements rather than an array of custom objects.  Further it appears that there is a #text property available that contains the string you are looking for.  You'd be able to access that by calling $final[0].'#text' (make sure to remember the quotes around the property name).  Then you'd have to parse the string to remove the extra data but you can do that either using regex matches or .substring() methods.

A: An simple way to get the required data is to use split
Refer to the below for better understanding:
$Array='AJFFF01@10.10.10.10'
$CompName=$array.split('@')[0]
$CompName

Hope it HElps.


text:
Q: image alignment vs image stabilization? From my understanding, image alignment and image stabilization are two different things. I consider that image alignment is just about shifting (rotating or translating) the image so that it follows a specific axis, but without modifying the original image. On the other hand, image stabilization tries to modify the original image so that most of it looks similar to the previous ones. Am I correct in this reasoning?
Considering this, for a radar-based image, in which it is going to be applied some mechanical stabilization, is it worth using an image stabilization technique? Or just using the output of the mechanical stabilization with some kind of image alignment??
Radar image example:

Cheers


text:
Q: powershell query to extract specific string from text file and export that in excel need to extract the string "  VQ_UHC_GovtPrograms_Sales_LeadCapture_Mandarin_Callback@VQ-switch" from below log file" when the condition is "is not found on Switch" error is found in the log.
=================================================
So the output should be:
QueueName    Date
==================================================
2022-08-07 20:36:41.534 ERROR 11100 --- [com.test.PCT.invoker.default] split.logs.queue-stat                    : Stat request failed for Stat Server: statserver-test-rrr_1a StatName: 'AverAbandCallTime' QueueName: 'VQ_UHC_GovtPrograms_Sales_LeadCapture_Mandarin_Callback@VQ-switch' Reason: 'Queue 'VQ_UHC_GovtPrograms_Sales_LeadCapture_Mandarin_Callback' is not found on Switch 'VQ-switch'  (Tenant 'Environment')'
=======


text:
Q: Python matplotlib savefig: Change font size I have some figures that I have plotted using matplotlib, however the font size is too small when I use it in a latex document. I've tried to alter the font size using the following code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.transforms
from matplotlib.colors import LogNorm

plt.rcParams['figure.figsize'] = (10.0, 7.0) # set default size of plots
font = {'family' : 'sans',
        'weight' : 'normal',
        'size'   : 40}
matplotlib.rc('font', **font)

#================= Draw histogram =====================
fig, ax = plt.subplots()
ax.hist2d(flow[:, 0], flow[:, 1], bins=400, norm = LogNorm(), cmap='viridis')
for xc in gt_points[:, 0]:
    ax.axvline(x=xc, linestyle=':', c='r')
    print(xc)
ax.axhline(0, linestyle=':', c='r')
ax.set_xlabel('vx [pixels per second]')
ax.set_ylabel('vy [pixels per second]')
ax.set_xlim([k_means_x_min, k_means_x_max])
ax.set_ylim([k_means_y_min, k_means_y_max])
fig.tight_layout()
plt.show()
fig.savefig('histogram.pdf', bbox_inches='tight', transparent=True)

Except changing the 'size' : 40 parameter doesn't change anything and the resulting pdf has loads of whitespace around it and isn't 'tight' at all (see image). Can anyone tell me what I'm doing wrong?
Many thanks!

Edit: Adding the lines
    matplotlib.rc('xtick', labelsize=20)
    matplotlib.rc('ytick', labelsize=20)
works for at least making the numbers on x and y axis larger. However, as mentioned matplotlib.rc('font', **font) does nothing...

A: As per the documentation, this works:
font = {'family' : 'normal',
        'weight' : 'normal',
        'size'   : 22}
matplotlib.rc('font', **font)

I'm guessing the problem was that 'family' : 'sans' isn't recognised by my python.

A: You can change axes labels directly using this:
ax.set_ylabel('vx [pixels per second]', fontsize=40)


text:
Q: Github authentication auto-failing As it says, moment I try to connect to a github repo it just straight up fails, doesn't ask for authentication, just dies right away and gives "fatal authentication" error. Is previous authentication saved somewhere?

A: Figured it out, when using Git Bash integrated in VScode, it tracks credentials in Windows Credential Manager, deleting the saved credentials will bring up the prompt again


text:
Q: Print messages at end of make compilation always with Cmake? I have seen How to print messages after make done with cmake? which in principle should answer my question, but it does not - so here is an example I prepared.
Say I have these two files in /tmp/cmake_test3:
main.c:
#include <stdio.h>

const char greeting[] = "hello world";

int main() {
    printf("%s!\n", greeting);
    return 0;
}

CMakeLists.txt:
cmake_minimum_required(VERSION 3.7)
SET(CMAKE_INCLUDE_CURRENT_DIR ON)

project(my_project)
message("PROJECT_NAME is '${PROJECT_NAME}'")

# change the behavior by setting variable here to TRUE or FALSE
set(USE_CUSTOM_COMMAND TRUE)

add_executable(my_executable
               main.c
              )

target_compile_options(my_executable PRIVATE
                       -Wall
                       -std=c99
                      )

if(USE_CUSTOM_COMMAND)
  message("Using custom command")
  add_custom_command(TARGET my_executable POST_BUILD
                     COMMAND ${CMAKE_COMMAND} -E cmake_echo_color --cyan
                     "Executable: $<TARGET_FILE_DIR:my_executable>"
                     COMMENT "print out executable path"
                    )
else()
  message("Using custom target")
  add_custom_target(printout ALL
      ${CMAKE_COMMAND} -E cmake_echo_color --cyan "PC Executable: $<TARGET_FILE:my_executable>"
      COMMENT "print out executable path"
      VERBATIM
  )
  add_dependencies(printout my_executable)
endif()

So, in /tmp/cmake_test3 I do:
mkdir build && cd build
cmake ../ -DCMAKE_BUILD_TYPE=Debug

For the CMakeLists.txt posted as is, I get the following:
$ cmake ../ -DCMAKE_BUILD_TYPE=Debug
-- The C compiler identification is GNU 6.3.0
-- The CXX compiler identification is GNU 6.3.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
PROJECT_NAME is 'my_project'
Using custom command
-- Configuring done
-- Generating done
-- Build files have been written to: /tmp/cmake_test3/build

# `make` first time - outputs message printout
$ make
Scanning dependencies of target my_executable
[ 50%] Building C object CMakeFiles/my_executable.dir/main.c.o
[100%] Linking C executable my_executable
print out executable path
Executable: /tmp/cmake_test3/build
[100%] Built target my_executable

# `make` second time - no message printout
$ make
[100%] Built target my_executable

# make clean; then `make my_executable` first time - outputs message printout
$ make clean
$ make my_executable
[ 50%] Building C object CMakeFiles/my_executable.dir/main.c.o
[100%] Linking C executable my_executable
print out executable path
Executable: /tmp/cmake_test3/build
[100%] Built target my_executable

# `make my_executable` second time - no message printout
$ make my_executable
[100%] Built target my_executable

Ok, so now, change the set(USE_CUSTOM_COMMAND TRUE) to set(USE_CUSTOM_COMMAND FALSE) in the CmakeLists.txt, and let's repeat the process - still in the build/ subdirectory:
$  rm -rf *
$ cmake ../ -DCMAKE_BUILD_TYPE=Debug
-- The C compiler identification is GNU 6.3.0
-- The CXX compiler identification is GNU 6.3.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
PROJECT_NAME is 'my_project'
Using custom target
-- Configuring done
-- Generating done
-- Build files have been written to: /tmp/cmake_test3/build

# `make` first time - outputs message printout
$ make
Scanning dependencies of target my_executable
[ 33%] Building C object CMakeFiles/my_executable.dir/main.c.o
[ 66%] Linking C executable my_executable
[ 66%] Built target my_executable
Scanning dependencies of target printout
[100%] print out executable path
PC Executable: /tmp/cmake_test3/build/my_executable
[100%] Built target printout

# `make` second time - outputs message printout
$ make
[ 66%] Built target my_executable
[100%] print out executable path
PC Executable: /tmp/cmake_test3/build/my_executable
[100%] Built target printout

# make clean; then `make my_executable` first time - no message printout
$ make clean
$ make my_executable
[ 50%] Building C object CMakeFiles/my_executable.dir/main.c.o
[100%] Linking C executable my_executable
[100%] Built target my_executable

# `make my_executable` second time - no message printout
$ make my_executable
[100%] Built target my_executable

So, how do I get a message - specified at CMake level - to print something at end of make always - that is, regardless of:

*

*if a binary is built or not,

*whether I call make or make all or make my_executable ?


text:
Q: Why does shortcut don't have the same behavior when applied on multiple keys Here's my problem.
I wrote a little Volume Control Script to control my volume like windows do with it's Microsoft Keyboard's shortcut.
I have 3 functions. Two to controls volumes and the other one to control the Hold state of the key to continue rise or down my volume
Here's the code.
    ;//**************************************************
    ;// Volume Mouse Control
    ;//**************************************************
    VolumeUp(p_numberToDecrease, p_holdToDecrease = true)
    {
        Send {Volume_Up %p_numberToDecrease%}

        if(p_holdtoDecrease)
        {
            VolumeHoldTreatment("Up")
        }
    }

    VolumeDown(p_numberToDecrease, p_holdToDecrease = true)
    {
        Send {Volume_Down %p_numberToDecrease%}

        if(p_holdtoDecrease)
        {
            VolumeHoldTreatment("Down")
        }
    }

    VolumeHoldTreatment(p_treatment)
    {
        Count := 0

        Sleep 300
        While GetKeyState(A_ThisHotkey,"P")
        {
            ++Count
            if(p_treatment == "Up")
            {
                Send {Volume_Up %Count%}
            }
            else
            {
                Send {Volume_Down %Count%}
            }
            Sleep 25
        }
    }

When I call the methods in the shortcuts like this ↓, they work correctly.
I can rise up and down my volume.
If I hold the key more then 300ms, the volume will continue rising/downing.
    XButton1:: VolumeDown(1)
    XButton2:: VolumeUp(1)

But When I add my mute shortcut ↓
    XButton1 & XButton2:: Send {Volume_Mute}
    XButton2 & XButton1:: Send {Volume_Mute}

The hold behavior don't act normaly. I need to press my Button1/2 two times to call the hold behavior. Why ?
Thanks for your help

A: The combinations
XButton1 & XButton2:: Send {Volume_Mute}
XButton2 & XButton1:: Send {Volume_Mute}

make XButton1 and XButton2 prefix keys. Prefix keys have a slightly different behaviour. They only fire upon release, which can't be avoided: For example, if you press XButton1, it is possible that you will press XButton2, causing the combination to be triggered. Only if you haven't pressed any additional button, XButton1:: will be triggered, and that on the other hand can't be determined before it was released.
To your VolumeHoldTreatment() function: In this case, a loop with GetKeyState() isn't necessary. A normal key will continue firing anyway when you hold it down. That's why some people are able to produce the word LOL with way too many O letters, with only three keystrokes.
Disregarding the mute function, something like this would do exactly the same:
XButton1::Send, {Volume_Down}
XButton2::Send, {Volume_Up}

Avoiding the use of a combination like XButton1 & XButton2 and therewith preventing the occurrence of prefix keys will save you a lot of trouble and can e.g. be accomplished like this:
XButton1::
    if( GetKeyState("XButton2") ) {
        Send, {Volume_Mute}
    } else {
        Send, {Volume_Down}
    }
return

XButton2::
    if( GetKeyState("XButton1") ) {
        Send, {Volume_Mute}
    } else {
        Send, {Volume_Up}
    }
return

This will work almost flawlessly: If you hold just one button, it will be triggered again and again, continuously sending Volume_Up or Volume_Down. As soon as you press both keys, two things will happen:

*

*The key you pressed first will stop firing

*The other key will send the {Volume_Mute}
Unfortunately, this comes with two downsides when muting: a) There will always be at least one Volume_Up or Volume_Down (even more when you take a really long time pressing the second button) sent before the {Volume_Mute} is sent. b) If you hold both keys for a long time, {Volume_Mute} will be sent over and over again; but this at least won't change the outcome.
Update:
The XButtons indeed show a strange behaviour, namely they don't keep firing when they are held down. Check out this code:
XButton1::
    if( GetKeyState("XButton2", "P") ) {
        SetTimer, FireVolumeUp, Off
        Send, {Volume_Mute}
    } else {
        SetTimer, FireVolumeDown, 100
    }
return

XButton1 Up::
     SetTimer, FireVolumeDown, Off
return

XButton2::
    if( GetKeyState("XButton1", "P") ) {
        SetTimer, FireVolumeDown, Off
        Send, {Volume_Mute}
    } else {
       SetTimer, FireVolumeUp, 100
    }
return

XButton2 Up::
     SetTimer, FireVolumeUp, Off
return

FireVolumeUp:
    Send, {Volume_Up}
return

FireVolumeDown:
    Send, {Volume_Down}
return

This has become more similar to your code, but it uses timers instead of loops, making the script able to execute other code in between timer runs. Also, I'm using XButtonN Up:: hotkeys, leading to more precision in terms of detecting the key release. The rest should be pretty self-explanatory. If you don't want the timers to wait 100 ms before their first run, add a GoSub, FireVolume... before each SetTimer.


text:
Q: PostgreSQL scaling up to 64 cores? In this Computer World article, it specifies that PostgreSQL can scale up to a core limit of 64. Does this mean for one multi-core processor of 64 cores? Or multiple processors with fewer cores?
The reason why I ask is because I am trying to find how much processors PostgreSQL may scale up to but of course that may be limited to the type of processor. However, I've been finding other statistics in other databases (i.e. Microsoft SQL Server here stating it can scale up to 320 logical processors) and they don't specify their number of cores. Is this a very vague statistic?
Any thoughts would be much appreciated. Thanks!

A: No it's a very precise statistic. A "logical processor" is a core. And a core is just that, it doesn't matter how they're spread over physical processors.
And if you're dealing with a machine with more cores than the supported number, this shouldn't be an issue with PostgreSQL. Each connection is inherently single-threaded* so whatever number of cores you have is what's going to limit the efficiency and efficacy of concurrent connections.
Needless to say this also means you should put your money in faster cores than quantity of cores unless you want to cluster things in a more complicated method.
* 2017 Update: Some queries (or subqueries) may be executed in parallel.

A: Others have clarified that a logical processor generally refers to a CPU core, but I do want to comment on the statement that it doesn't matter how cores are spread over CPUs.
You can have caches on the CPU die that are shared among cores or that are dedicated to single or subgroups of cores. For example, one common config is dedicated L1 cache and shared L2 cache. In this instance, the scalability of a single dual core CPU can differ from two single core CPUs.
These scalability affects continue into main memory, with NUMA machines exhibiting different behavior than non-NUMA.
I point these out only because the OP is discussing questions of scalability, whose answers are generally more nuanced than "program X can use Y CPU cores".

A: Postgres can scale up to as many processors as you want to install, and your OS can handle/manage effectively.  You can install Postgres on a 128 core machine (or even a machine with 128 physical processors) and it will work fine. It may even work better than on a 64 core machine if the OS scheduler can handle that many cores.
Postgres has been shown to scale linearly up to 64 cores (with caveats: We're talking about read performance, in a specific configuration (disk, RAM, OS, etc.) -- Robert Haas has a blog article with a nice graph which I've reproduced below:

What's important about this graph?
The relationship is linear (or nearly so) as long as the Number of Clients is less than or equal to the Number of Cores, and then begins what looks to be roughly a log-linear decrease in performance as you have more client connections than you do cores to run Postgres backends on because the backends start fighting for the CPU (load average goes above 1.0, etc...).
While it has only been demonstrated for up to 64 cores, you can generalize that you can keep adding cores (and clients) and keep improving performance, up to the limit of some other subsystem (disk, memory, network) where processes are no longer having CPU contention problems but are instead waiting on something else.
(Haas also has another article where they proved linear scalability to 32 cores which has some great reference material on scalability in general -- highly recommended background reading!)

A: In this case, they mean multiple processors with fewer cores... Some of the talk is future-proofing. Some is marketing-speak.


text:
Q: Why does GCC claim clock_gettime() implicitly declared, but the preprocessor is perfectly happy with a related macro? I'm trying to measure the amount of time an operation is taking, as accurately as possible. My research led me to believe that clock_gettime() and friends is what I want.
However, I can't for the life of me get it to work. Consider this seemingly trivial example:
#include <time.h>
#include <unistd.h>

int main(void)
{
    struct timespec t;
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t);
    return 0;
}

If I run that through the preprocessor, everything looks like it's just fine:
$ cpp time.c | tail -n10
# 1163 "/usr/include/unistd.h" 3 4

# 3 "time.c" 2

int main(void)
{
 struct timespec t;
 clock_gettime(2, &t);
 return 0;
}

However, if I try to compile the preprocessed code, it won't:
$ cpp time.c > time-prep.c
$ cc -o time -Wall -std=c11 -lrt time-prep.c
/tmp/user/1000/cc00SdhB.o: In function `main':
time-prep.c:(.text+0x15): undefined reference to `clock_gettime'
collect2: error: ld returned 1 exit status
$

If I try to compile the original, it doesn't go any better:
$ cc -o time -Wall -std=c11 -lrt time.c
time.c: In function 'main':
time.c:6:18: error: storage size of 't' isn't known
time.c:7:2: warning: implicit declaration of function 'clock_gettime' [-Wimplicit-function-declaration]
time.c:7:16: error: 'CLOCK_PROCESS_CPUTIME_ID' undeclared (first use in this function)
time.c:7:16: note: each undeclared identifier is reported only once for each function it appears in
time.c:6:18: warning: unused variable 't' [-Wunused-variable]
$

The man page for clock_gettime says that I need to

Link with -lrt (only for glibc versions before 2.17).

but as you can see, I'm already doing that. Adding or removing -lrt to cc doesn't seem to make any difference whatsoever in my case.
I have looked at /usr/include/time.h but don't see anything obvious that I am missing.
What (presumably trivial) incantation is missing for me to be able to use clock_gettime() in my code?

A: The Linux documentation for clock_gettime() specifies a feature-test requirement:
_POSIX_C_SOURCE >= 199309L

You could consider fulfilling that directly, perhaps via a #define directive at the very beginning of your code, since the code in fact does depend on it.
If you do not provide such a #define, then gcc may nevertheless do it for you, depending on the options you specify to it.  By default, it will do.  Likewise with -std=gnu99 or -std=gnu11.  But you attempted to compile with -std=c11, which asks for strict(ish) compliance with C11.  C11 does not define the needed POSIX feature-test macro.

A: You can define _GNU_SOURCE above any #include. There is an example:
$cat ./main.c
// Need for clock_gettime()
// Have to be at the begining of the file
#define _GNU_SOURCE

#include <time.h>
#include <unistd.h>

int main(void)
{
    ...
}


text:
Q: Is it possible to execute PHP code when I specify and not when the page is loaded This is my code(form).

  Content Type
<input id="type" type="radio" name="content_type" value='article' onclick="check_type()">Article </input>
<input id="type" type="radio" name="content_type" value='image' onclick="check_type()">Image </input>
<input id="type" type="radio" name="content_type" value='url' onclick="check_type()">Url </input>

  Select Asset
<select disabled="disabled" id="asset" name="content_asset">
<option value='create_new_content'>select asset</option>
    <?php
    $dir='../Assets/10/';
    if($handle = opendir($dir)){
      while(($file = readdir($handle)) !== false){
    if($file != "." && $file != ".." && $file != "Thumbs.db"){
     $extension = explode('.',$file);
     if($extension[1] == 'png' || $extension[1] == 'gif' || $extension[1] == 'jpg'){
       echo "<option value=".$file.">".$file."</option>";
    }
      }
    }
    closedir($handle);
  }
 ?>
</select>

Is it possible to execute the PHP code when the radio button is clicked. I enable the drop down box using javascript when the radio button is clicked.

A: You would have to put the php code to execute on another page and call it with AJAX.
EDIT: jQuery has a neat way of doing this.

A: PHP is executed on the server side, I'm not sure but I suspect that precludes it re-rendering anything without a page reload. I think JavaScript might help!
Edit: in fact, it looks like the related threads off to the right there are exactly the sort of information you'd want.

A: use ajax for load your php on an event

A: NO, because the PHP code is already executed when you load this form on browser.
It would be better if you create three different dropdown for Article, Image and URL each and keep them hidden, and based on selection of radio button show relative dropdown.
Looks like you are re-factoring/patching the code so I would not suggest you jQuery or some other option.
ATB


text:
Q: Given $v, w, z \in \mathbb{R}$, show this equation as true I am now trying to understand, given $v, w, z \in \mathbb{R^{3}}$, its true that $(v\times w)\times z$=$c_{1}v+c_{2}+c_{3}(v \times w)$. $c_{1}, c_{2}, c_{3} \in \mathbb{R}$. This is cros product by the way.
So this is a true equation. But I want to know how to show $c_{1}=-w\cdot z, c_{2}=v\cdot z, c_{3}=0$.
I first want to prove $c_{3}=0$, I want to let $v$x$w=n$, make the dot product of n and $c_{1}v+c_{2}+c_{3}(v \times w)$ to prove that $c_{3}=0$.

A: The definition of cross product is $c=a\times b$, is
$c_x=a_yb_z-a_zb_y$
$c_y=a_zb_x-a_xb_z$
$c_z=a_xb_y-a_yb_x$
Now, for your expression, $d=(v\times w)\times z=-z\times (v\times w)$ because the cross product is "anticommutative." By the component wise definition of cross product, $$\begin{split}d_x&=-z_y(v\times w)_z-z_z(v\times w)_y\\&=-z_y(v_xw_y-v_yw_x)+z_z(v_zw_x-v_xw_z)\\&=v_x(-z_yw_y-z_zw_z)+w_x(z_yv_y+z_zv_z)+[v_xz_xw_x-v_xz_xw_x]\\&=-v_x(z_xw_x+z_yw_y+z_zw_z)+w_x(v_xz_x+z_yv_y+z_zv_z)\\&=(z\cdot w)w_x-(z\cdot w)v_x\end{split}$$
Likewise, for the y and z components you get $d_y=(z\cdot v)w_y-(z\cdot w)v_y$ and $d_z=(z\cdot v)w_z-(z\cdot w)v_z$. Putting the components together, you find $d=(z\cdot v)w-(z\cdot w)v$.
Thus $c_1=-z\cdot w, c_2=(z\cdot v)w, c_3=0$.

You could also use directly the vector triple product, which says that $a\times (b \times c)=b(a\cdot c)-c(a\cdot b)$, or $(a\times b)\times c=-c\times(a\times b)=-(c\cdot b)a+(c\cdot a)b$


text:
Q: How to use an if condition to filter JSON in PHP I am working on a REST API, and I have a JSON file which has lots of values. I want to check for a specific category, and when I find that category the loop will break and content will show for that particular category. Here is my code:

    <meta charset="UTF-8">
    <title>SuperDeal.com Baap of all deals</title>

    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" media="all" />

    <link rel="stylesheet" href="bootstrap/css/custom.css" media="all" />

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                    Toggle navigation

                </button>
                SuperDeal.com

Home

Register and win

Conatct Us

    <?php
$ch = curl_init("http://tools.vcommission.com/api/coupons.php…"); // add your url which contains json file
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
$json = json_decode($content, true);
//print_R($json);
$count=count($json);
echo'
BlueStone Offers	Link	';
for($i=0;$i<$count;$i++)
{
    if ($json[$i]['offer_name']=='Bluestone.com CPS - India'){
        echo'
'.$json[$i]['offer_name'].'
        '.$json[$i]['coupon_title'].'
        '.$json[$i]['coupon_code'].'
         Grap The Deal

';
        echo'
';
    }
    break;
}

?>
<?php
echo substr("Koovs.com CPS - India",6);
?>

… I am trying to populate the "Bluestone Offers" HTML table with only the relevant entries contained in the JSON response. I am inspecting the offer_name field for a specific string value ("Bluestone.com CPS - India", as above).


text:
Q: Tried importing a library and ended up with Plugin with id 'com.android.application' not found I just tried importing a library into my android project and ended up with this Plugin with id 'com.android.application' not found. error. I was supposed to import "Filters.jar" file from jhlabs but accidentally imported "gradle-wrapper.jar" of another project . I am stuck here and nothing seems to work. I also accidentally deleted my project level build.gradle file, Which contained the following code :
// Top-level build file where you can add configuration options common to all sub-projects/modules.

    buildscript {

        repositories {
            google()
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.1.2'

            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }

    allprojects {
        repositories {
            google()
            jcenter()
        }
    }

    task clean(type: Delete) {
        delete rootProject.buildDir
    }

I was trying to import the library following this answer,
https://stackoverflow.com/a/35369267/9504498
I messed up apparently I have tried many solutions but nothing is working. Please, help me fix this error I am stuck here.
How can I get the project level build.gradle file back? and how can I fix this Plugin with id 'com.android.application' not found.?
Any help will be appreciated, Thanks.

A: You need to re-add your build.gradle to your project by following the structure of sample project which you can create from Android Studio.
Usually, the project structure is like the following:
app              -> (your app module)
gradle
build.gradle     ->  (project build.gradle)
gradlew
gradlew.bat
local.properties
settings.gradle

The following error:

Plugin with id 'com.android.application' not found.

is because gradle can't found the plugin from your project build.gradle, so add the following code to your project build.gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

For adding a jar library, as @daniel-nugent says, try:
How to manually include external aar package using new Gradle Android Build System

A: Tried many options but nothing really worked and finally, created a new project with exact name as the previous one and the exact package name, then copied the "main" from the previous project to the new project and edited the app level build.gradle by copying from the previous project and things are back to normal now. Will try importing the .jar library by following @daniel-nugent method.


text:
Q: should Class.getResourceAsStream be closed? I was wondering if this is required since when I use this method, the file is being read from the classpath. Does "not closing" it lead to a memory leak.
How can I test for such memory leaks?

A: As a rule of thumb you should close all streams (and ay other types that provide close functionality).  It can lead ro resource leaks (memory is one type of resource).
Although there is automatic garbage collection that reclaims memory eventually when an object is no longer referred to, it might still hold native resources that might not be released.  Also, if some other long-lived object (e.g. the classloader) keeps a hold on the resource, it will not be claimed by the garbage collector.
If your program is short lived, or f you only open a small number of resources, you might not run into problems, but resource leaks are hard to detect in long-running applications.

A: The type returned is an inputstream so, regardless the concrete implementation (which could change from version to version), you have a close() method that imho should be called.
No matter if that method is actually doing something useful with the current version.

A: You are assuming that Class.getResourceAsStream() will always return a stream that points to a file inside your class' JAR file. This is incorrect. Your classpath may also contains folders, in which case Class.getResourceAsStream() will return a FileInputStream. Some other class loaders might also return other type of resources, such as remote files (in the case of a URLClassLoader).
Even in the case of a JAR file, it is possible that the implementation maintain, by whatever mean, a persistant view inside the JAR file to the compressed bytes of the file you are accessing. Maybe it is holding upon a memory mapped ByteBuffer...
Why take the chance? You should always close streams (and any other Closeable, actually), no matter how they were given to you.
Note that since Java 7, the preferred method to handle closing any resource is definitely the try-with-resources construct. It correctly handles several corner cases that are very hard to manage in hand written code, and yet it is almost as easy to write for you as if you had simply forgot about closing the resource. For example, you may use code like this:
    try (InputStream in = Class.getResourceAsStream("someresource.txt")) {
        // Use the stream as you need to...
    }

    // Then forget about it... and yet, it has been closed properly.

As for detecting leaks, the best strategy is to obtain a memory dump at the time the VM is shut down, then analyze it with some tool. Two popular tools are VisualVM and Eclipse mat.


text:
Q: how can i append textbox based on dynamic created dropdown children on changes i want to add child text boxes on the selection of child dropdown counting. I have try the separate code on jsfiddle which is working http://jsfiddle.net/hs7t8/ . There are two dropdown list are created on the selection of guest selection dropdown . it dynamically generates two drop down on add room button click. first one is adult and second is children. On the selection of children dropdown i want to text boxes accroding to the selection of the children dropdown. but it is not adding to page. please Help me out .complete running code on http://jsfiddle.net/pYRj3/1/
$('#guestsRoomsSelect').change(function () {

        if ($(this).val() === '0') {
               var $var2 = '

 Adults'
                $var2 = $var2 + '
      <select id="adults" class="t_adults" style="margin-left:7px;margin-right:7px; border-right: 0.5px solid #FFFFFF;">      <option value="1">1</option>        <option value="2" selected="selected">2</option>'
                $var2 = $var2 + '<option value="3">3</option>       <option value="4">4</option>        <option value="5">5</option>        <option value="6">6</option>        <option value="7">7</option>'
                $var2 = $var2 + '<option value="8">8</option>       <option value="9">9</option>        <option value="10">10</option>      </select>
'
                $var2 = $var2 + '
 Children
   <select id="hc_f_children" class="hc_evt_children " style="border-right: 0.5px solid #FFFFFF;">'
                $var2 = $var2 + '<option value="0" selected="selected">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option>'
                $var2 = $var2 + '<option value="4">4</option> </select>

';
                $("#Addition").prepend('<fieldset id="' + counter + '" data-index="' + index + '">' + $var2 + '</fieldset>');
                counter = counter + 1;
                index++;

                $('#roomconfig').show(300);

        }
        else if ($(this).val() === '1-1' || $(this).val() === '3-1' || $(this).val() === '4-1' || $(this).val() === '2-2' || $(this).val() === '2-1') {

          $('#roomconfig').hide(300);

            $('#Addition fieldset :first').remove();
        } });

    var forage = 0;
    $(".addRoom").click(function () {
        // on add room event

        var $var1 = '

 '
        $var1 = $var1 + '       <select id="adults" class="t_adults" style="margin-left:7px;margin-right:7px; border-right: 0.5px solid #FFFFFF;">      <option value="1">1</option>        <option value="2" selected="selected">2</option>'
        $var1 = $var1 + '<option value="3">3</option>       <option value="4">4</option>        <option value="5">5</option>        <option value="6">6</option>        <option value="7">7</option>'
        $var1 = $var1 + '<option value="8">8</option>       <option value="9">9</option>        <option value="10">10</option>      </select>
'
        $var1 = $var1 + '
   <select id="hc_f_children_' + forage + '" class="hc_evt_children " style="border-right: 0.5px solid #FFFFFF;" onselect="getIdvalue()">'
        $var1 = $var1 + '<option value="0" selected="selected">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option>'
        $var1 = $var1 + '<option value="4">4</option> </select>

'
        $var1 = $var1 + '
 remove
';

        $("#Addition").append('<fieldset id="' + counter + '" data-index="' + index + '"' + $var1 + '</fieldset>');

        counter++;
        index++;
        forage++;
        // for remove element
        $(".btnrmv").click(function () {
            $("#roomconfig fieldset#" + this.id).remove();
            counter--;

        });

        var Idvalue = null;
        // Add childage textbox
        function getIdvalue() {
            Idvalue = $('.hc_evt_children').attr("id");

        }

        $(Idvalue).change(function () {

            var index1 = $(".ch input").size();
            var requested = parseInt($(".hc_evt_children").val(), 5);

            if (requested > index1) {
                for (i = index1; i < requested; i++) {
                    var $ctrl = $('<input/>').attr({ type: 'text', name: 'text', value: '' });
                    $("#chileage_" + forage).append($ctrl);
                }
            }
            else if (requested < index1) {
                var x = requested - 1;
                $("#chileage_ input:gt(" + x + ")").remove();
            }
        });

    });

Add room

A: Don't use the attribute onselect when creaating your markup. It won't fire.
Instead, after appending the child dropdown list, bind the change event to the dropdown.
On Need More Room selected:
 $('#hc_f_children').bind('change', function() { // your code here, which adds those textboxes });
On Add room pressed:
 $('#hc_f_children_'+ forage).bind('change', function() { // your code here, which adds those textboxes });


text:
Q: SQL query cannot create user's table I don't understand why this query wouldn't work. This query was working until I wanted to add the last column "groups".
CREATE TABLE users(
 id MEDIUMINT NOT NULL AUTO_INCREMENT,
 username CHAR(30) NOT NULL,
 name VARCHAR(100),
 password VARCHAR(30),
 email VARCHAR(100),
 groups VARCHAR(100),
 PRIMARY KEY (id)
);

A: "groups" is a reserved name in MySQL, if you really want to use It then you can avoid it by using backticks like:
`groups`

A: GROUPS is a new reserved keyword added in Mysql v8.0

Either you can use a different name in place of groups like bunch or cluster

OR

Use backticks for groups, but make sure you use backticks everywhere you use groups

You can check the list of reserved keywords in Mysql v8.0


text:
Q: MAX function returning multiple values for each group I'm trying to create a query to show the current account from each branch
that is also a joint account, that has the highest free overdraft limit.
I've almost got it working, but it is seems to be returning all joint current accounts for branches (branches 1 and 3 only have one current account that is a joint account so that is why they are only ones returning one value)
I believe it may have something to do with the GROUP BY function but if I remove any of the attributes from the GROUP BY clause it says it is not a valid GROUP BY.
Can anyone explain what I am doing wrong?

    SELECT MAX(a.freeOverdraftLimit), b.branchAddress.streetAddress, b.branchAddress.city, b.branchAddress.postcode, b.branchID, c.pname.forename, c.pname.surname
    FROM kt_accountTable a
    JOIN kt_branchTable b ON a.branchID = b.branchID
    JOIN kt_customerAccount c ON a.accountNum = c.accountNum
    WHERE jointAccount = 'Y' AND accountType = 'Current'
    GROUP BY b.branchID, b.branchAddress.streetAddress, b.branchAddress.city, b.branchAddress.postcode, c.pname.forename, c.pname.surname
    ORDER BY COUNT(a.freeOverdraftLimit);

Account Table Structure
Branch Table Structure
Customer Account Table Structure
Query Result

A:
Can anyone explain what I am doing wrong?

There is nothing in your query that specifies the condition to limiting to the account with the highest free overdraft limit.
Since you tagged your question "Oracle", I'll assume you are using a relatively recent version and walk through how to do this using the CROSS APPLY join feature.
Since you want your result set to show one row per branch, start with just that table...
SELECT b.branchAddress.streetAddress,
       b.branchAddress.city,
       b.branchAddress.postcode,
       b.branchID
FROM   kt_branchTable b

Next, use CROSS APPLY to find the ONE account having the highest overdraft limit, using the accountNumber to break ties.
(NOTE: Assumes every branch has at least one account.  If not a good assumption, use OUTER APPLY/)
SELECT a.freeOverdraftLimit,
       b.branchAddress.streetAddress,
       b.branchAddress.city,
       b.branchAddress.postcode,
       b.branchID
FROM   kt_branchTable b
CROSS APPLY ( SELECT a.freeOverdraftLimit, a.accountNum
              FROM   kt_accountTable a
              WHERE  a.branchId = b.branchID
              ORDER BY a.freeOverdraftLimit DESC, a.accountNumber ASC
              FETCH FIRST 1 ROW ONLY ) a

From here, it's easy to add in the customer info for that account, giving you your final answer as follows:
SELECT a.freeOverdraftLimit,
       b.branchAddress.streetAddress,
       b.branchAddress.city,
       b.branchAddress.postcode,
       b.branchID,
       c.pname.forename,
       c.pname.surname
FROM   kt_branchTable b
CROSS APPLY ( SELECT a.freeOverdraftLimit, a.accountNum
              FROM   kt_accountTable a
              WHERE  a.branchId = b.branchID
              ORDER BY a.freeOverdraftLimit DESC
              FETCH FIRST 1 ROW ONLY ) a
INNER JOIN kt_customerAccount c ON c.accountNum = a.accountNum

NOTE: it's not clear from your data model whether multiple customers can own the same account (i.e., two rows in kt_customerAccount having the same accountNumber.  If so, this solution will give duplicates.  But you did not specify the requirements for handling that situation (show all, show first, etc.), so I'm not handling it as part of my answer here.


text:
Q: Почему не код не работает с входными данными на 7? Друзья, всем привет! Решил порешать олимпиадки за 9-11 класс по информатике. В качестве языка был выбран питон. Не на долго хватило моих скиллов.
Проблема вот в чём:
Сидел решал эту задачу
"Задача 2. Чётные – нечётные Маша любит чётные числа, а Миша – нечётные. Поэтому они всегда радуются, если встречают числа, которые им нравятся.
Сегодня им встретились все целые числа от A до B включительно. Маша решила посчитать сумму всех чётных чисел от A до B, а Миша – сумму всех нечётных, после чего они начали спорить, у кого получилась сумма больше. Помогите им – найдите разность между суммой Маши и суммой Миши.
Программа получает на вход два целых положительных числа A и B, не превосходящие 2×109. Программа должна вывести одно число – разность между суммой чётных чисел и суммой нечётных чисел от A до B.
Примеры входных и выходных данных
Ввод 3 6 Вывод 2 Примечание  Сумма чётных чисел равна 4 + 6 = 10, сумма нечётных чисел равна 3 + 5 = 8, разность равна 2.
Ввод 3 7 Вывод -5 Примечание  Сумма чётных чисел равна 4 + 6 = 10, сумма нечётных чисел равна 3 + 5 = 8, разность равна 2"
Сама задача по себе не сложная, но при вводе чисел 3 и 6 всё ок, получается и всё работает, а когда 3 и 7, то консоль просто молчит и всё. Может быть кто-нибудь знает в чём проблема?
Вот код:
num_1 = int(input())
num_2 = int(input())
i = num_1

chet_sum = 0
nechet_sum = 0

# пока i больше или равно num_1 и пока i меньше или равно num_2
while i>=num_1 and i<=num_2:

    # если при делении по модулю на i на 2 остаток равен нулю
    if i % 2 == 0:
        chet_sum = chet_sum + i
        i = i+1
        continue

    # если при делении по модулю на i на 2 остаток равен не нулю
    if i % 2 != 0 and i != num_2:
        nechet_sum = nechet_sum + i
        i = i+1
        continue

print(chet_sum - nechet_sum)

input()

введите сюда код

A: У вас ошибка в этой строке:
if i % 2 != 0 and i != num_2:

Не нужно ставить условие i != num_2, ведь в условии задачи сказано, что числа от А до Б включительно.
Бонусом вам более короткий функциональный вариант:
a = int(input())
b = int(input())

even = [i for i in range(a, b+1) if i%2==0]
odd = [i for i in range(a, b+1) if i%2==1]

print(sum(even)-sum(odd)

A: while i>=num_1 and i<=num_2:
при достижении i==7 у вас выполнялось условие i<=num_2 и цикл уходил на следующи круг и так в бесконечность.

if i % 2 != 0 and i != num_2:
сюда i==num_2 уже не попадал.


text:
Q: Why does my string violate constraints? This is my @Pattern.List:
@NotNull
@Pattern.List({
        @Pattern(regexp="[A-Z][a-z]+\\s[A-Z][a-z]+", message="Name contains invalid characters."),
        @Pattern(regexp="[A-Z][a-z]+", message="Name contains invalid characters.")
        })
public String getName() {
    return name;
}

The string is North Dakota.
I admit I'm not the best at regex and I'm new to this, but shouldn't that work?
It works if I remove the @Pattern annotation.
This is the error:
Caused by: javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.

A: You seem to expect that when you provide a @Pattern.List, that the value should then match at least one pattern of the list. But this is not true. The value must match any one pattern of the list. In case of "North Dakota", only the first pattern matches, but the second not. Hence you keep seeing this constraint violation error.
The @Pattern.List should only be used for patterns which cannot be represented by a single pattern, or each needs a dfferent message (such as complex password matching on various types of characters).
In this particular case, you just need to simplify the regular expression into one pattern wherein you specify the second word as optional by placing it in (...)?.
@NotNull
@Pattern(regexp="[A-Z][a-z]+(\\s[A-Z][a-z]+)?", message="Name contains invalid characters.")
public String getName() {
    return name;
}


text:
Q: I have two query And i want to get result form both I have two query And i want to get result form tbl_users_new_rides where findride category
ride_From data and ride_to from equal to pool_ride_type='offerride' ride_from and ride_to
value. below is two query can i mrge these query according requirment .
Thanks for help
select ride_from,ride_to from tbl_users_new_rides where pool_ride_type='findride'
select ride_from,ride_to from tbl_users_new_rides where pool_ride_type='offerride'

A: I think this is correct
select ride_from,ride_to from tbl_users_new_rides where pool_ride_type='offerride' or pool_ride_type='findride'

A: Inshort u can use like this to get exact matching results -
select ride_from,ride_to from tbl_users_new_rides where pool_ride_type IN ('findride', 'offerride');


text:
Q: How can a top level directory structure reveal the purpose of the application? Robert C. Martin in one of his talks about clean architecture openly criticizes fairly standard way of doing things nowadays.
Robert C. Martin - Clean Architecture and Design
What I understand as standard way is something like this:
solution
    - UI project
        - Models
        - Views
        - Controllers
        - Assets
    - Logic project
    - Data project

Martin here says, that the application should reveal its purpose immediately when you look at its top level directory structure... I wonder, can anyone provide an example of such directory structure, for instance while using MVVM pattern as a delivery mechanism? How can one structure his application the way Martin is describing?

A: From what I see in your example I can only guess that it is a ASP.NET MVC application, we need to take a look at the Logic or Data projects to understand what this application is about.
Most of the time people organize all their directory structure based on the technology or framework used.  This comes from the way default project template are created (knowing nothing about what your application is supposed to do they really can't do much more than that for us).
Now, what Robert C. Martin tells us is that our top level directory structure should reflect on what the application does and not how it is built.  I'm not sure it is a good idea to do that at the solution level.  However, I always recommend to have a Domain project were we could apply Domain Driver Design principles.
If in such Domain project you see at the root level the following folders:
Clients
Orders
Billing
Shipping
Promotions
...

You could guess it is some kind of E-commerce application.  You would have to go even deeper in the directory structure if the folders you would have found are like Models, DTOs or Exceptions.
I don't like to have too many projects in my solution (under 10 if possible) so I don't go and create one project per domain object of my system.  This is why I think the root level of projects not solutions are were we should focus our attention on defining what the application is doing.

A: He isn't talking about a structure that gives away the application purpose as such. He said, at the top level there should be use cases so you can quickly see what it does and where code changes are required. I dont think he was talking about folder names at all. More information availbility.


text:
Q: How to fix "Error: Access token has expired or is not yet valid" when calling M365 API to fetch TodoTaskLists? I'm trying to make GET request to ("me/todo/lists") endpoint for M365. It works initially after a fresh authentication and acquiring the access-token.
It even works when the access token is saved and the request is made after a couple of minutes, meaning that the code for using the saved access token works.
But when I try to call the API after sometime by storing the access token, I get the error: "Error: Access token has expired or is not yet valid"
Here's the code for making the request with the saved access token
public async getTaskLists(accessToken: string) {
        class MyAuthenticationProvider implements AuthenticationProvider {
            /**
             * This method will get called before every request to the msgraph server
             * This should return a Promise that resolves to an accessToken (in case of success) or rejects with error (in case of failure)
             * Basically this method will contain the implementation for getting and refreshing accessTokens
             */
            public async getAccessToken(): Promise<string> {
                return accessToken;
            }
        }
        const options = {
            authProvider: new MyAuthenticationProvider(), // An instance created from previous step
        };
        const client = Client.initWithMiddleware(options);

        //this part fetches task-lists from M365 and populates them into placed in a tree-view using registerTreeDataProvider

        let dataObject = [];
        let children: string[] = [];
        try {
            let taskList = await client.api("/me/todo/lists").get();
            console.log(taskList);
            } catch (error) {
            console.log(error);
            }
    }
}

A: It is a short-lived access token that is only valid for an hour I think. You need to refresh the token before it expires to be able to make API calls successfully. That means you MUST save the refresh_token in order to do so. refresh_token can be used multiple times from my experiences which is good since it might break the connection if the refresh_token can only be used once and the refresh token response is lost due to network issues. However, it is good practice to save the last refresh_token returned from MS.


text:
Q: How to make a PS file form a TeX document with graphics ? Could someone explain me how to generate a PS file from a TeX file. I have included some graphics in my TeX file.
I used graphicx package.
I am using TeXLive
Thank you.

A: Unless I misunderstood the question, I think something along the following lines should give you a PS file:
latex sample2e.tex
dvips sample2e.dvi

(The sample2e.tex was slightly modified by adding \usepackage{graphicx} in the preamble, and inserting a sample image with \includegraphics at the end.)
This uses dvips about which there is extensive documentation. Should you want a PDF, you can just complete the above steps with ps2pdf.


text:
Q: asp string compare (encoding i think) i'm sending a post request to my asp page,
i use the parameter that i get to read file this way:
station = request.form("station")
StationFolderPath = currentDir & "iPhoneListener\Locations\" & station
fs.FolderExists(StationFolderPath)

with english letters there is not problem.
but when i send hebrew letters its not find the folder.
i checked it with this
response.write(right(station,6))

and got: #1497 maybe someone know how to encode this &#1497 to normal letter.
thanks

A: You could use the HTML Decode function from here and change the first line in your code to station = HTMLDecode(request.form("station")).
Function HTMLDecode(sText)
    Dim regEx
    Dim matches
    Dim match
    sText = Replace(sText, """, Chr(34))
    sText = Replace(sText, "<"  , Chr(60))
    sText = Replace(sText, ">"  , Chr(62))
    sText = Replace(sText, "&" , Chr(38))
    sText = Replace(sText, " ", Chr(32))

    Set regEx= New RegExp

    With regEx
     .Pattern = "&#(\d+);" 'Match html unicode escapes
     .Global = True
    End With

    Set matches = regEx.Execute(sText)

    'Iterate over matches
    For Each match in matches
        'For each unicode match, replace the whole match, with the ChrW of the digits.

        sText = Replace(sText, match.Value, ChrW(match.SubMatches(0)))
    Next

    HTMLDecode = sText
End Function


text:
Q: Android how to get Suggested strings array of the TextEdit Is there a way to get an array of the suggestions strings which are shown when you typing in EditText? The problem is I have an EditText and in case of user use "Show Suggestions" option the result of the string from this EditText is different in case of user pressed, lets say UI button (this is a Button from the layout), and a return button at the soft keyboard. In first case user gets an exact string but in second - it gets corrected (suggested) string even user do NOT select this suggestion. How to solve this problem? How to get from EditText "suggested" string? Do I need to implement my own IME?

A: Maybe this can help you ?  Hello Auto Complete
Or if you want to write one on your own.. Writing your own autocompleteview

A: Are you trying to disable suggestions or to modify them?
If you want to disable them completely, check this out:
How to disable displaying "suggestions" on the Soft Keyboard


text:
Q: How to add multiple tags to URL in Django and Taggit I have this model here, where I pass the tags using TaggableManager.
class Post(models.Model):
    title = models.CharField(max_length=120)
    content = models.TextField()
    date_published = models.DateField(auto_now_add=True)
    tags = TaggableManager()
    slug = models.SlugField(max_length=40, blank=True)

And this is how I view the data:
class TagView(ListView):
    model = Post
    template_name = 'tagview.html'
    paginate_by = 10

    def get_queryset(self):
        return get_list_or_404(Post, tags__slug = self.kwargs.get('tag'))

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        context['tag'] = self.kwargs.get('tag')
        return context

This works as per 1 tag, but I want to include multiple tags, I've searched a lot but couldn't think of how to implement it. This is my urls.py - path('tag/<slug:tag>/', views.TagView.as_view(), name='tagview'),
I want something like /tags/[django][python]/ etc..

A: a alternative approach witch will accomplish the same end result will be to
use query_params this means you will leave the url open to receive any arguments witch will follow the base url to this path, and you will check to see if the query_params has the 'tag' key's we are looking for.
the URL request would look something like this:
http://127.0.0.1:8000/blog?tag=python&tag=django
#urls.py
path('', views.TagView.as_view(), name='tagview'),
#views.py
class TagView()
    def get(self, request):
        posts = Post.objects.all()
        is_there_a_tag = request.query_params.get('tag')
        if is_there_a_tag is not None:

           tag_list = request.query_params.getlist('tag')
        matches = self.posts.filter(tags__name__in=tag_list).distinct()


text:
Q: Angular 2 - Http Get request - pass json Object How can I do a http get request and pass an json Object
This is my json-Object
{{firstname:"Peter", lastname:"Test"}

and this Object I want to pass in the http request to get a list Of matched persons.
how is it possible? This example just shows a simple get request with  a json result. How do I have to modify it?

//Component:

person:Person;
persons:Person [];
....
//Whre can I pass the person, here in the service??
getMatchedPersons(){
  this.httpService.getMatchedPersons().subscribe(
     data =>  this.persons = data,
    error => aller(error)
    );
 );

  //SERVICE
  //pass parameters?? how to send the person object here?
  getMatchedPersons(){
    return this.http.get('url').map(res => res.json());
  }

A: The Http.get method takes an object that implements RequestOptionsArgs as a second parameter.
The search field of that object can be used to set a string or a URLSearchParams object.
An example:
 // Parameters obj-
 let params: URLSearchParams = new URLSearchParams();
 params.set('firstname', yourFirstNameData);
 params.set('lastname', yourLastNameData);

 //Http request-
 return this.http.get('url', {
   search: params
 }).subscribe(
   (response) => //some manipulation with response
 );

A: For pure javascript:
You must serialize your json to a list of parameters:
?firstname=peter&lastname=test

and append it to the URL because GET requests have no body.
There are a few ways of converting JSON to QueryParameters.
They are addressed in this question: Is there any native function to convert json to url parameters?
There you can choose the poison of your liking, mine was:
function obj_to_query(obj) {
    var parts = [];
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
        }
    }
    return "?" + parts.join('&');
}

But mind you that GET requests must obbey the URL limit that based on this answer is recomended to stay under 2000 characters to be safe:

RFC says 8000
  IE8 and IE9 go as far as 2083
  Search engines only read to 2048

Using Angular2 URLSearchParams
With the same method of converting a plain JSON to arguments one could use URLSearchParams as suggested by Рома Скидан:
 let params: URLSearchParams = objToSearchParams(obj);

 return this.http.get('url', {
   search: params
 }).subscribe(
   (response) => //some manipulation with response
 );

 function objToSearchParams(obj): URLSearchParams{
    let params: URLSearchParams = new URLSearchParams();
    for (var key in obj) {
        if (obj.hasOwnProperty(key))
            params.set(key, obj[key]);
    }
    return params;
 }

A: Maybe you want to stringify the json object
var json = JSON.stringify(myObj);

this.http.get('url'+'?myobj='+encodeURIComponent(json))

A: Use a POST request to pass objects to the server:
//SERVICE
getMatchedPersons(searchObj: any){
    return this.http.post('url', JSON.stringify(searchObj))
                    .map(res => res.json());
}

Then you can pass whatever JS object you want and send it to the server in your http request.
getMatchedPersons(searchObj: any){
    this.httpService.getMatchedPersons(searchObj: any).subscribe(
        data =>  this.persons = data,
        error => alert(error);
    );
);

A: Similar to AngJobs' but maybe more up-to-date??  Calling encodeURIComponent is not necessary.  Here's the Angular:
const stringifiedParams = JSON.stringify(this.filterParams);
return this.http.get<any[]>(`persons`, {params: {filter: stringifiedParams}});

On the server Node deserializes the params with JSON.parse:
filter = JSON.parse(req.query.filter.toString());

A: Actually there's an easier way for flushing parameters
getMatchedPersons(myObject: any): Observable<Person[]> {
    return this.http.get<Person[]>('url', { params: { ...myObject } });
}

*

*The above code represents a function that accepts a JSON object myObject as a parameter.

*HttpClient.get method accepts an options paramter as its second paramter.

*The options parameter contains many useful keys, but we're only interested with the params key in our case.

*the value of params is { ...myObject }, that is- we're using the spread operator to pass all key:value pairs from an object.
Refer that this will do the job, and will not make the URL look ugly with all those ? and key=value and & characters, of course in either case those parameters won't be shown for the user since it's just an HTTP call, but still, if anyone is using a logger interceptor, they will have a clean log.


text:
Q: RequestContext throws NPE from a different context than FacesContext Why calling RequestContext rq = RequestContext.getCurrentInstance() from a different context than FacesContext throws a NullPointerException ?
I am not able to do something like :
RequestContext rq = RequestContext.getCurrentInstance() //NPE is thrown
if (rq != null) {
..
}

What I am trying to do is to retrieve a bean inside a WebFilter and call a method. This method uses above snippet; so it throws NullPointerException.
Thank you for your help.

A: Instance of RequestContext is saved as an attribute in FacesContext, so when there is not FacesContext you will have NPE. Here is the code which will tell you how RequestContext is obtained, and that will be cleared:
return (RequestContext) FacesContext.getCurrentInstance().getAttributes().get(Constants.REQUEST_CONTEXT_ATTR);

Creating RequestContext and saving it as FacesContext attribute is done in PhaseListener of Primefaces, after Restore view phase, so it doesn't exist in your filter.


text:
Q: Smtp Received from IP addresses not matching I am sending emails via SMTP, in C#, to Google Mail and although it is working, there is an issue:

Received: from 11.111.11.103 (mx101.company.com. [11.111.11.101])
          by mx.google.com with ESMTP id fw15si12217298wbb.73.2011.12.06.06.44.24;
          Tue, 06 Dec 2011 06:44:25 -0800 (PST)

I have multiple IP addresses that I send from, and I have configured my HelloDomain to be the first IP address (x.x.x.103) which can be seen working above (also it's name is mx103.company.com).  I was expecting to see the output below:

Received: from 11.111.11.103 (mx103.company.com. [11.111.11.103])
          by mx.google.com with ESMTP id fw15si12217298wbb.73.2011.12.06.06.44.24;
          Tue, 06 Dec 2011 06:44:25 -0800 (PST)

Any ideas on why this is happening?

A: Ok, so the answer is configuring your LocalEndPoint.  I have been banging my head against the keyboard all day and finally realised that I wasn't assigning the LocalEndPoint, which in turn defaulted to the first IP address.


text:
Q: Graphics capabilities of MacBook Pro? I'm considering purchasing a MacBook Pro, but a major issue for me is whether or not it has the computing power to support graphics-intensive applications. Specifically, the two most graphically intense applications I'd be doing are Final Cut Pro video editing (approx. 60 min vids) and playing Diablo 3. Since D3 is the more graphically challenging player here, I'll use it as the baseline. My current MacBook Pro (either 2009 or 2010) struggles with this game to be playable, so I'm a bit skeptical to trust the minimum system requirements for D3 since my current machine meets them:

*

*Mac OS X 10.6.8, 10.7.x, or newer

*Intel Core 2 Duo (or better)

*NVIDIA GeForce 8600M GT or ATI Radeon HD 2600 (or better)

*2 GB RAM

*12 GB Available Disk Space

*DVD-ROM drive

*Video Settings reaching minimum resolution of 1024x768

Getting the obvious out of the way, I can see by looking at MacBook Pro specs comparison that I need to have at the very minimum a 15" or 17" model, since the 13" does not have a separate high-performance graphics card. Additionally, I know that the 15" and 17" both have plenty of RAM and CPU power. The problem is, I have no idea where the MacBook's AMD Radeon HD 6750M/6770M stand against the technical specs.
Would the MacBook Pro be able to reasonably support these use cases (Final Cut Pro and Diablo 3)? I define "reasonably" as: no choppy frame rate, responsive interaction, and not having to be set the game at the absolute minimum specs just to play (also, the computer not becoming as hot as the sun would be a bonus, but not a deal-breaker).

A: I don't have a recent MBP, but in my experience the applications should run well.
For games, I suggest to look at youtube videos. For example, Diablo 3 Beta Gameplay MacBook Pro.
You can find a good comparison of the graphics chips here:
Apple 15-inch MacBook Pro (Late 2011) Review
If you have time, I would wait about one month (until June/July 2012); the chances for new MacBook Pros being released are high.

A: The current MBP's have similar benchmark scores and performance to my 27" iMac from late 2010.  Diablo 3 runs great, with only the shadows turned down a bit.
Bottom line is that if you can wait, it's always worth it to get the next model, assuming it is soon.  If you need a computer today, the current MBP's are great.  I've got a late 2011 15" MBP at work and it's a workhorse.  And since graphics are your big concern, go for the best discrete GPU.

A: There are many, many graphics card benchmark lists.  Here's one that shows the Radeon 6750M to be about 2.5 times faster than the GeForce 8600M:
http://novabench.com/gpuchart.php?a=1
Of course every benchmark is different, but you can be assured that the video card in the 15 and 17 inch MBPs will run this game well.
Use google to find other benchmarks if you'd like more points of data:
https://www.google.com/search?q=compare+6750M+8600M


text:
Q: Git repository similar to local, how to merge I don't know exactly how to put it but here is my problem:
I have a git repository related to laravel project. I also have the same folder on local but i deleted the .git folder, .gitignore and .gitattrib files, i.e. my local folder is no longer connected to github. Now i have made changes to local files and want to push those to the original repository. How can i do that?

A: One way to do this would be to simply commit your changes as a new commit in your repository:

*

*Ensure you have a clone of your repository locally
If needs be, reclone it, or if you already have one you can most
likely reuse that clone.

*Make sure you're on the right branch in that clone
If needs be, create and checkout a new branch for the modifications
that you did locally while "unconnected to GitHub".

*Then bring those changes into your working folder of the clone
Basically, copy from the local, "unconnected" folder
... and copy to the working folder of your repository
Note! If any of your "local changes" involved deleting or
moving file you need to ensure you do the same thing in your
working folder.
If you got any kind of directory comparison tool, such as
Beyond Compare, then
you should use this to ensure you synchronize not just file
contents but also directory structure.

*Then all you have to do is commit your modified files into your repository

*

*Do a git status to ensure everything looks good

*Do a git status --ignored to ensure git won't ignore any files you care about

*Do a git add . to stage your modifications

*Do a git commit to commit your changes

*Verify everything looks good
Do a build, whatever

*Merge your changes into your main branch (develop or master or whatever)


text:
Q: objective c convert int to unsigned char hex I've to convert
int x = 4 in to unsigned char y = 0x04
int x = 0 in to unsigned char y = 0x00
int x = -4 in to unsigned char y = 0xFC
int x = -8 in to unsigned char y = 0xF8
and so on, till -20 to 0xEC.
Does anyone know a smart way to do ?

A: There is no conversion as such; simply cast from int to unsigned char:
int x = -4;
unsigned char y = (unsigned char)x;

There is also no hex as such; that's just a formatting option to printf() or whatever:
printf("y=0x%02x", (unsigned)y);


text:
Q: Create XML with xmlns:xlink attribute in a node i'm trying to add generate an output like this:
<mets ....
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.loc.gov/METS/
http://www.loc.gov/standards/mets/mets.xsd">

I can generate everything fine, but cannot add the xmlns:xlink attribute. The closest I get is:
$this->xml = new SimpleXMLElement('<mets></mets>');
$mets->addAttribute("xlink:someName", "blabla", "http://www.w3.org/1999/xlink");
$mets->addAttribute("xsi:schemaLocation", "http://www.loc.gov/METS/
http://www.loc.gov/standards/mets/mets.xsd",
"http://www.w3.org/2001/XMLSchema-instance");

Generates:
<mets ....
xmlns:xlink="http://www.w3.org/1999/xlink"
----begin of part I don't desire-----
xlink:someName="blablabla"
----end of  part I don't desire-----
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.loc.gov/METS/
http://www.loc.gov/standards/mets/mets.xsd">

How can I add xmlns:xlink without adding  xlink:somethingElse?

A: The solution I've come up with is rather straight forward:
Because
$mets->addAttribute("xlink:someName", "", "http://www.w3.org/1999/xlink");

will always add two attributes - one for the namespace declaration (xmlns:xlink) and then the attribute you actually add (xlink:someName) - all you need to do is then to remove the unwanted added attribute and the prefix namespace attribute will remain:
unset($mets->attributes('xlink', true)['someName']);

Full example:
$mets = new SimpleXMLElement('<mets></mets>');
$mets->addAttribute("xlink:someName", "", "http://www.w3.org/1999/xlink");
unset($mets->attributes('xlink', true)['someName']);
echo $mets->asXML();

Output:
<?xml version="1.0"?>
<mets xmlns:xlink="http://www.w3.org/1999/xlink"/>

However this normally should not be necessary. You either need to use the namespace for something - then simplexml will add it when needed - or you don't need it, then there is no need to add it.
XML itself has no requirement at all to declare a namespace which is not used. Therefore you likely can leave it out as well or you only need to add it where you need to add it, e.g. the specific xlink element / attribute later on.
Any XML parser that supports namespaces will support any well-formed XML+Namspaces document, so there should really be no reason to worry whether or not the root element has that declaration and with which prefix. Simplexml just takes care of that, just add the xlink attribute where you need it. Example:
$mets = new SimpleXMLElement('<mets></mets>');
$child = $mets->addChild('child');
$child->addAttribute('xlink:href', 'child.xml', 'http://www.w3.org/1999/xlink');
$child = $child->addChild('child');
$child->addAttribute('xlink:href', 'child.xml', 'http://www.w3.org/1999/xlink');
echo $mets->asXML();

Output:
<?xml version="1.0"?>
<mets>
  <child xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="child.xml">
    <child xlink:href="child.xml"/>
  </child>
</mets>


text:
Q: Describing the surface of a sphere in Huygens' Principle $U(P) = \frac {iU(r_0)}{\lambda} \int_{S} \frac {e^{iks}}{s} K(\chi)\,dS$
Where $S$ describes the surface of the sphere, how is the surface of the sphere described?
Sorry if you feel this is quite a simple question, I couldn't find the information anywhere on the internet.
(I'm not entirely sure about the tag either) so any edits would be much appreciated

A: "Describes" is used here like "inscribed"
Note that there is an $S$ underneath the integral sign as well. This means that its a surface integral. The integral is carried out over a surface, analogous to how a line integral is carried out over a path.
$\rm dS$ will be a small area element. In most surface integrals, you can write it as a product of two differentials. For example, on a plane (parallel to $xy$ plane), $\rm dS=\rm dx \rm dy$. For a sphere, $\rm dS=r\rm d\theta \times r\sin\theta\rm d\varphi $.
Question: Are you trying to learn optics via Wikipedia(looking at your previous questions). Wikiepdia is a bad place to learn stuff--its a reference--which means that it assumes you know everything and want to know more :/. I suggest getting a textbook if you are Wikipedia-studying. There also are free online lecture videos and material, like those from MIT or Khan Academy.


text:
Q: how to find where the interval of continuous numbers starts and ends? I have a vector
vec <- c(2, 3, 5, 6, 7, 8, 16, 19, 22, 23, 24)

The continuous numbers are:
c(2, 3)
c(5, 6, 7, 8)
c(22, 23, 24)

So the first vector starts at 2 and ends at 3;
for the second vector starts at 5 and ends at 8;
for the third vector starts at 22 and ends at 24;
There is a function to identify where the continuous numbers starts and ends?

A: By using diff to check the differences between each consecutive value, you can find where the difference is not +1.
diff(vec)
## [1] 1 2 1 1 1 8 3 3 1 1
c(1, diff(vec)) != 1
## [1] FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE  TRUE  TRUE FALSE FALSE

Then use cumsum to make a group identifier:
cumsum(c(1, diff(vec))!=1)
## [1] 0 0 1 1 1 1 2 3 4 4 4

And use this to split your data up:
split(vec, cumsum(c(1, diff(vec))!=1))
##$`0`
##[1] 2 3
##
##$`1`
##[1] 5 6 7 8
##
##$`2`
##[1] 16
##
##$`3`
##[1] 19
##
##$`4`
##[1] 22 23 24

Which can be Filtered to consecutive values:
Filter(\(x) length(x) > 1, split(vec, cumsum(c(1, diff(vec))!=1)))
##$`0`
##[1] 2 3
##
##$`1`
##[1] 5 6 7 8
##
##$`4`
##[1] 22 23 24

A: Another one
vec=c( 2  ,  3  ,  5  ,  6  ,  7 ,   8   ,  16 , 19 , 22 , 23 , 24 )

x <- replace(NA, vec, vec)
# [1] NA  2  3 NA  5  6  7  8 NA NA NA NA NA NA NA 16 NA NA 19 NA NA 22 23 24

l <- split(x, with(rle(is.na(x)), rep(seq.int(length(lengths)), lengths)))
# l <- split(x, data.table::rleid(is.na(x))) ## same as above
l <- Filter(Negate(anyNA), l)
l
# $`2`
# [1] 2 3
#
# $`4`
# [1] 5 6 7 8
#
# $`6`
# [1] 16
#
# $`8`
# [1] 19
#
# $`10`
# [1] 22 23 24

If you have a length requirement:
l[lengths(l) > 1]
# $`2`
# [1] 2 3
#
# $`4`
# [1] 5 6 7 8
#
# $`10`
# [1] 22 23 24


text:
Q: Reading an xml subtrees and the descendants C# I have an XML file that contains several subTrees and those subtrees can also contain subtrees in them. something like this:
<File>
...
...
<C>
..
<D>..</D>
</C>
</File>

(The ".." are elements in the subtree). How can i read each subtree and then to reaad all its element (if this subtree containg a subtree i want to read it seperately and all his elements)?

A: XmlReader supports reading a subtree for that purpose; you can use the subtree-reader to as an input to other models (XmlDocument, XElement, etc) if you so wish:
using(var reader = XmlReader.Create(source))
{
    reader.MoveToContent();
    reader.ReadStartElement(); // <File>
    while(reader.NodeType != XmlNodeType.EndElement)
    {
        Console.WriteLine("subtree:");
        using(var subtree = reader.ReadSubtree())
        {
            while(subtree.Read())
                Console.WriteLine(subtree.NodeType + ": " + subtree.Name);
        }
        reader.Read();
    }
    reader.ReadEndElement(); // </File>
}

A: You could use a XDocument to read XML documents in .NET. For example to read the value of the D node:
var doc = XDocument.Load("test.xml");
var value = doc.Root.Element("C").Element("D").Value;

A: I got the solution with the following code
var doc = XDocument.Load("C:\\Test.xml");
var DBID = doc.Root.Element("database").FirstAttribute.Name;
var DBIDValue = doc.Root.Element("database").FirstAttribute.Value;


text:
Q: Is there a System event when processes are created? Is there any event when a new process is created.  I'm writing a c# application that checks for certain processes, but I don't want to write an infinite loop to iterate through all known processes continuously.  Instead, I rather check each process that is created or iterate through all current processes triggered by an event.  Any suggestions?
        Process[] pArray;
        while (true)
        {
            pArray = Process.GetProcesses();

            foreach (Process p in pArray)
            {
                foreach (String pName in listOfProcesses)  //just a list of process names to search for
                {

                    if (pName.Equals(p.ProcessName, StringComparison.CurrentCultureIgnoreCase))
                    {
                       //do some stuff

                    }
                }
            }

            Thread.Sleep(refreshRate * 1000);
        }

A: WMI gives you a means to listen for process creation (and about a million other things).  See my answer here.
 void WaitForProcess()
{
    ManagementEventWatcher startWatch = new ManagementEventWatcher(
      new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
    startWatch.EventArrived
                        += new EventArrivedEventHandler(startWatch_EventArrived);
    startWatch.Start();
}

static void startWatch_EventArrived(object sender, EventArrivedEventArgs e)
{
    Console.WriteLine("Process started: {0}"
                      , e.NewEvent.Properties["ProcessName"].Value);
    if (this is the process I'm interested in)
    {
             startWatch.Stop();
    }
}


text:
Q: How to convert csv to json with arrays I have a csv file with an initial data for my app.

    {
   "id": 1,
   "topic": "Архитектура",
   "question": "Как называется буддийское архитектурное культовое сооружение?",
   "rightanswer": "Ступа",
   "wronganswer1": "Баба",
   "wronganswer2": "Яга",
   "wronganswer3": "Метла",
   "passed": false,
   "right": false
 },

I need to parse it to json with the array of "answers", what options i have ?
Result should be like that :
 {
   "id": 1,
   "topic": "Архитектура",
   "question": "Как называется буддийское архитектурное культовое сооружение?",
   "answers":[
        "Ступа",
        "Баба",
        "Яга",
        "Метла" ],
   "passed": false,
   "right": false
 }

A: You are almost in the right direction but you have to use JSONArray for answers rather then adding them directly into the object with the name.
you can have an if where you will check if key contains the answer string then you can add into the JSONArray else add that key and value into JSONObject and add this JSONArray with the key answers into the main object once you done by adding all field.
This logic will keep your logic flexible.
it will help you to achieve your desire JSON.
EDIT: I would suggest you change your excel structure if you can. you should have all possible options in a single column (such as opt1,opt2,opt3,opt4) and correct answers in another column to gain simplicity and flexibility in your excel designa nd code.

A: I'm using gson
    String str = "{\r\n" +
            "   \"id\": 1,\r\n" +
            "   \"topic\": \"Архитектура\",\r\n" +
            "   \"question\": \"Как называется буддийское архитектурное культовое сооружение?\",\r\n" +
            "   \"rightanswer\": \"Ступа\",\r\n" +
            "   \"wronganswer1\": \"Баба\",\r\n" +
            "   \"wronganswer2\": \"Яга\",\r\n" +
            "   \"wronganswer3\": \"Метла\",\r\n" +
            "   \"passed\": false,\r\n" +
            "   \"right\": false\r\n" +
            " }"; //<== your json input

    JsonParser parser = new JsonParser();
    JsonObject input = parser.parse(str).getAsJsonObject(); //parser you Json to object
    JsonObject output =  new JsonObject();//my new jsonOutput
    output.add("id", input.get("id"));
    //other field .....

    //the trick start here
    JsonArray answer = new JsonArray();
    answer.add(input.get("rightanswer"));
    answer.add(input.get("wronganswer1"));
    answer.add(input.get("wronganswer2"));
    answer.add(input.get("wronganswer3"));
    output.add("answers", answer);

    System.out.println(output.toString());

result
{"id":1,"answers":["Ступа","Баба","Яга","Метла"]} // to lazy to parse other field sorry

Hope it helps


text:
Q: How do I set UISlider to have only one track image rather than using a minimum track image and a maximum track image in Swift? Hello I was wondering how to just have one track image for my customized slider. I am having an issue where if I set the minimum track image and the maximum track image using the same image, my slider has a gap in the thumb image such as in this picture. .
This is my custom class UISlider code.
  import UIKit

class NightVisionSlider: UISlider {

   required init?(coder: NSCoder) {
        super.init(coder:coder)

      self.setThumbImage(UIImage(named:"Night Vision Slider Knob3.png")!, for:.normal)

        let trackingImage = UIImage(named:"Night Vision Bar 2.png")!

      self.setMinimumTrackImage(trackingImage, for:.normal)

       self.setMaximumTrackImage(trackingImage, for:.normal)

    }

}

How can I just have one complete tracking image, so my slider doesn't have this flaw?

A: class CustomSlider: UISlider
{

    override func awakeFromNib()
    {
       super.awakeFromNib()
       self.setThumbImage(UIImage(named:"Night Vision Slider Knob3.png")!, for:.normal)

       let trackingImage = UIImage(named:"Night Vision Bar 2.png")!

       self.setMinimumTrackImage(trackingImage, for:.normal)

       self.setMaximumTrackImage(trackingImage, for:.normal)

    }
    override func layoutSubviews()
    {
        super.layoutSubviews()
        super.layer.cornerRadius = self.frame.height/2  //Do something additional if you want to do!.
    }

    override func trackRect(forBounds bounds: CGRect) -> CGRect
    {
        var newBounds = super.trackRect(forBounds: bounds)
        newBounds.size.height = 10 //Size of your track
        return newBounds
    }
}


text:
Q: how to add radius around location? How can i add radius here..or dynamically ...??
 {
                GPSLongitude = location.getLongitude();
                GPSLatitude = location.getLatitude();
                Log.i("GPS","Lat: "+GPSLatitude+" Long "+ GPSLongitude);
                Toast.makeText(getApplicationContext(), "Location is "+GPSLatitude+" Long "+ GPSLongitude, Toast.LENGTH_LONG).show();
                googleMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(GPSLatitude,GPSLongitude) , 16.0f) );
                }


text:
Q: Secure access of webassets with Flask and AWS S3 I am trying to serve files securely (images in this case) to my users. I would like to do this using flask and preferably amazon s3 however I would be open to another cloud storage solution if required.
I have managed to get my flask static files like css and such on s3 however this is all non-secure. So everyone who has the link can open the static files. This is obviously not what I want for secure content. I can't seems to figure out how I can make a file available to just authenticated user that 'owns' the file.
For example: When I log into my dropbox account and copy a random file's download link. Then go over to anther computer and use this link it will denie me access. Even though I am still logged in and the download link is available to user on the latter pc.

A: Make the request to your Flask application, which will authenticate the user and then issue a redirect to the S3 object. The trick is that the redirect should be to a signed temporary URL that expires in a minute or so, so it can't be saved and used later or by others.
You can use boto.s3.key.generate_url function in your Flask app to create the temporary URL.


text:
Q: Getting raw json string or customer jackson mapper from httpbuilder-ng get request I'm updating groovy scripts from httpbuilder to httpbuilder-ng. These scripts interact with various webservices to get messages. I'm looking to parse the responses preferably using Jackson into objects. However, I can't seem to get the raw json response like I could in httpbuilder as httpbuilder-ng auto parses into a lazymap in all cases.
The old implementation using httpbuilder allowed you to use the body.text method to get the raw json string without it being parsed into a lazymap. This could then be used with ObjectMapper in Jackson to create my POJO's. However, httpbuilder-ng doesn't seem to support this.
I have already tried the method here for getting the raw json, but the body.text method does not seem to work in version 1.03 that I'm using http://coffeaelectronica.com/blog/2016/httpbuilder-ng-demo.html.
I have also tried to add my own custom encoders to override Groovy's default creation of JSON objects without any success. It is supposedly possible as detailed in the wiki https://http-builder-ng.github.io/http-builder-ng/asciidoc/html5/. If anyone has a code snippet of how to do this it would be appreciated!
Old httpbuilder code:
def http = new HTTPBuilder("http://${proxy}.domain.ie")

    http.request(GET, TEXT) {
        uri.path = "/blah/plugins/blah/queues"
        headers.Accept = 'application/json'
        headers.'Cookie' = "token=${token}"

        response.success = { resp, json ->
            assert resp.status < 300
            LOGGER.info("GET queues request succeeded, HTTP " + resp.status)

            ObjectMapper objectMapper = new ObjectMapper()

            queues = objectMapper.readValue(json, Queue[].class)
        }

        response.failure = { resp ->
            assert resp.status >= 300
            LOGGER.info("GET queues request failed, HTTP " + resp.status)
            return null
        }
    }

new http-builder-ng code:
def http = configure {
        request.uri = "http://${proxy}.domain.ie"
        request.headers["Accept"] = "application/json"
        request.headers["Cookie"] = "token=${token}"
        request.contentType = TEXT
    }

    return http.get {
        request.uri.path = "/blah/plugins/blah/queues"

        response.success { FromServer fs, Object body ->
            return body.text // doesn't work
        }

        response.failure {
            return null
        }
    }

Update
Found the solution. It was to add a custom parser and a closure using the FromServer.inputstream.text method.
def text = httpBuilder.get {
        request.uri.path = '/blah/plugins/blah/queues'
        response.parser('application/json') { ChainedHttpConfig cfg, FromServer fs ->
            String text = fs.inputStream.text
        }
    }


text:
Q: C# namespace manager doesn't work parsing a XML with namespace I am trying to parse the XML from this url, sampled below, in C#:
<?xml version="1.0" encoding="UTF-8"?>
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01"
                 xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
    <gesmes:subject>Reference rates</gesmes:subject>
    <gesmes:Sender>
        <gesmes:name>European Central Bank</gesmes:name>
    </gesmes:Sender>
    <Cube>
        <Cube time='2020-01-16'>
            <Cube currency='USD' rate='1.1169'/>
            <Cube currency='JPY' rate='122.80'/>
            <Cube currency='BGN' rate='1.9558'/>
        </Cube>
    </Cube>
</gesmes:Envelope>

This is the code I am using to get currencies:
xml.Load(@"https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(xml.NameTable);
ns.AddNamespace("gesmes", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");

XmlNodeList nodes = xml.DocumentElement.SelectNodes("/gesmes:Envelope/Cube/Cube/Cube", ns);
foreach (XmlNode node in nodes)
{
  // some code here
}

However, nodes is always null. I have tried a lot of options, and the unique option it worked for me was removing namespace from the original XML. But I would like to parse the source directly without modifications.

A: There are three issues to correct:

*

*You misdefine the namespace associated with gesmes.
Change
ns.AddNamespace("gesmes", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");

to
ns.AddNamespace("gesmes", "http://www.gesmes.org/xml/2002-08-01");

*Your XPath doesn't take into account that Cube and its descendants are in the default namespace.
Create a prefix for the default namespace:
ns.AddNamespace("eu", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");

*Update your XPath with the namespace prefix from #2:
/gesmes:Envelope/eu:Cube/eu:Cube/eu:Cube
                 ^^^     ^^^     ^^^

(Cube cubed?    )
After fixing the above issues, your code should work as expected.

A: Linq XML has always given me less headaches:
var doc = XDocument.Load("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
string ns = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref";

var outerCube = doc.Root.Element(XName.Get("Cube", ns));
var timeCube = outerCube.Element(XName.Get("Cube", ns));

Console.WriteLine("Time: " + timeCube.Attribute("time").Value);

foreach (var cube in timeCube.Elements())
{
    Console.WriteLine(cube.Attribute("currency").Value + " => " + cube.Attribute("rate"));
}

A: I just wrote the same code for somebody last month.  Use a dictionary
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string URL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(URL);
            XNamespace ns = doc.Root.GetDefaultNamespace();

            Dictionary<string, decimal> dict = doc.Descendants(ns + "Cube").Where(x => x.Attribute("currency") != null)
                .GroupBy(x => (string)x.Attribute("currency"), y => (decimal)y.Attribute("rate"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }

}


text:
Q: Supervisorctl Fails to load my new project I have one existing flask project under supervisorctl that works flawlessly!
I added a new flask app called Blog but this fails to load under supervisorctl.
If I start it manually, it works, by doing:
mongod --dbpath /home/www/blog/mongodb

gunicorn myblog:app -b mysite.com:8080

However, if run the project on supervisorctl via:
supervisorctl start blog

it does this:
blog: ERROR (abnormal termination)

If I check the stderr logs, I get:
  File "/home/www/blog/myblog.py", line 5, in <module>
    from flaskext.markdown import Markdown
ImportError: No module named flaskext.markdown

Supervisor config (.conf):
[program:blog]
command = gunicorn myblog:app -b mysite.com:8080 --loglevel=critical
directory = /home/www/blog
user = myuser

This seems like a simple error - oops I must not have installed flaskext.markdown right?? Wrong! if I go to my directory with this flask app, and enable virtualenv its already installed...
Thus, I am not sure what to do from here? Does anyone have any thoughts? Thank you.

A: You have to add virtualenv path to the command line:
[program:blog]
command = /path/to/virtualenv/bin/gunicorn myblog:app -b mysite.com:8080 --loglevel=critical
directory = /home/www/blog
user = myuser

Save changes, then reload supervisor config and try to start blog again.