text:
Q: memory leak from numberWithInt? I think my program is leaking memory in the last line of this loop but i dont see why it should. Im not calling alloc. Can anyone explain this? I know it might be a really obvious answer but Im just getting started with objective C. Is it just that the numberWithInt call adds a +1 retain or something? Thanks
for (int k=0; k<=27; k++) {
    NSNumber *zero= [NSNumber numberWithInt:0];
    [randomUsed insertObject:zero atIndex:k];
    [alphaKeys insertObject:zero atIndex:k];
}

A: The code that you have here doesn't have any leak.
You must think in term of ownership. You don't own zero here since it was not returned from a alloc or new. Since you don't own it, you don't need to releaseit.
What you're thinking is that insertObject: is increasing the retainCount, which is true. When you insert zerointo your arrays, randomUsed and alphaKeys retains your zero object. In this case, it's the arrays that own it, not you. They need to release it, not you.
If there's a leak, it's the array themselves that are leaking, not your zero object.
Please review the cocoa memory management guide.


text:
Q: Azure Indoor map on React-Native I showed azure map on a web portal but could not found any solution how to see it on a mobile device using React-Native. We do not want to use  web view for these problems. How do I show the azure map of mobile devices using react native. I have not found any library for showing Azure indoor maps on  mobile devices.
Please not use we view we required react native for azure map.

A: The indoor maps feature is currently only available in the Azure Maps Web SDK. Azure Maps does have native mobile SDK's, but these don't yet have the new indoor functionality, and they aren't React-Native libraries.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to try all possible paths? I need to try all possible paths, branching every time I hit a certain point. There are <128 possible paths for this problem, so no need to worry about exponential scaling.

*

*I have a player that can take steps through a field. The player
takes a step, and on a step there could be an encounter.

*There are two options when an encounter is found: i) Input 'B' or ii) Input 'G'.

*I would like to try both and continue repeating this until the end of the field is reached. The end goal is to have tried all possibilities.

Here is the template, in Python, for what I am talking about (Step object returns the next step using next()):
from row_maker_inlined import Step

def main():
    initial_stats = {'n':1,'step':250,'o':13,'i':113,'dng':0,'inp':'Empty'}
    player = Step(initial_stats)
    end_of_field = 128

    # Walk until reaching an encounter:
    while player.step['n'] < end_of_field:
        player.next()
        if player.step['enc']:
            print 'An encounter has been reached.'
#           Perform an input on an encounter step:
            player.input = 'B'

#           Make a branch of player?
#           perform this on the branch:
#           player.input = 'G'
#   Keep doing this, and branching on each encounter, until the end is reached.

As you can see, the problem is rather simple. Just I have no idea, as a beginner programmer, how to solve such a problem.
I believe I may need to use recursion in order to keep branching. But I really just do  not understand how one 'makes a branch' using recursion, or anything else.
What kind of solution should I be looking at?

A: You should be looking at search algorithms like breath first search (BFS) and depth first search (DFS).
Wikipedia has this as the pseudo-code implementation of BFS:
  procedure BFS(G, v) is
    let Q be a queue
    Q.enqueue(v)
    label v as discovered
    while Q is not empty
        v← Q.dequeue()
        for all edges from v to w in G.adjacentEdges(v) do
            if w is not labeled as discovered
                Q.enqueue(w)
                label w as discovered

Essentially, when you reach an "encounter" you want to add this point to your queue at the end. Then you pick your FIRST element off of the queue and explore it, putting all its children into the queue, and so on. It's a non-recursive solution that is simple enough to do what you want.
DFS is similar but instead of picking the FIRST element form the queue, you pick the last. This makes it so that you explore a single path all the way to a dead end before coming back to explore another.
Good luck!


text:
Q: Basic batch file error I'm writing my first batch file and have two basic questions. I'm using Windows7 and wondering if there is an easy way to run something as an administrator? At the moment I just type cmd into the search bar and hit ctrl + shift + enter. I can right-click on the file and choose to run it as admin, but I was wondering if I could make this part of my batchfile. The second piece of my question is how to pass arguments to a program that I am opening. At the moment I am using the following code:
ECHO OFF

ECHO This will export a shapefile from my postgresql database

PAUSE

::START "pgsql2shp export" "C:\Program Files (x86)\PostgreSQL\9.1\bin\pgsql2shp.exe" [-f 'D:\test.shp' -h localhost -u postgres -p 5434 spatial_data 'SELECT * FROM public.energy']
::START "pgsql2shp export" "C:\Program Files (x86)\PostgreSQL\9.1\bin\" "-f 'D:\test.shp' -h localhost -u postgres -p 5434 spatial_data 'SELECT * FROM public.energy'" "pgsql2shp.exe"

START "pgsql2shp export" "C:\Program Files (x86)\PostgreSQL\9.1\bin\pgsql2shp.exe" "-f 'D:\test.shp' -h localhost -u postgres -p 5434 spatial_data 'SELECT * FROM public.energy'"

PAUSE

ECHO shpfile complete

PAUSE                       :: requires user input to end

I have run this file by pasting the following into the command line, after cd-ing to the following dir: C:\Program Files (x86)\PostgreSQL\9.1\bin
>pgsql2shp.exe -f D:\test.shp -h localhost -u postgres -p 5434 spatial_data "SELECT
* FROM public.energy"

My batch file code gives an error on a new terminal, but it disappears before I can read it, and I don't know what is going wrong.

A: The runas command is what provides this ability for you.  It will allow you to run any program AS someone else:

runas /noprofile /user:mymachine\administrator cmd

As you can see from the above quote, you simply specify the appropriate user from the list there, and boom, u run as that user.
The native issue w/ this method is the fact that the password will either a) need to be entered manually (if user isn't an admin user), or b) the password will be exposed on the runas command.
There are other utilities out there:

*

*elevate is one such.  You can download it here:  WinAbility Elevate.  This program basically lets you run any command as an elevated user even from a non admin command prompt.

To answer your second question; when passing information to the script, you have to use the proper command argument syntax:
Z:\Users\Phillip>copy con go.cmd
@echo off
echo/Passed First Parameter:  %1
echo/Passed Second Parameter:  %2
echo/
echo/Pased Third Formatted Parameter:  /d:%3
echo/
^Z
        1 file(s) copied.

Z:\Users\Phillip>go yes no ok
Passed First Parameter:  yes
Passed Second Parameter:  no

Pased Third Formatted Parameter:  /d:ok

The %1, %2, %3 syntax refers to the actual parameters passed to the program, this can include file names, programs, etc, as long as the information drops into the window as a valid file name or text entry.
The same command syntax above still applies to passing command line parameters with spaces in them as well:
Z:\Users\Phillip>go yes no "asdfasdfasdf asdf as dfa sdf "
Passed First Parameter:  yes
Passed Second Parameter:  no

Pased Third Formatted Parameter:  /d:"asdfasdfasdf asdf as dfa sdf "

However, if you are dragging/dropping, you should get into the habit of actually quoting the %3 or whatever parameter yourself (always try first, some systems do pass with the quotes already embedded, some do not, so best to test first.


text:
Q: Custom Post type archives / categories give 404 I have a client that wants a blog, a press section, and a "More Posts" section for feel good, community service type of posts. I used the standard post type for the blog, and everything works fine. I registered the two other post types with this code which is within a custom_posts(); function that I add with add_action( 'init', 'custom_posts');
register_post_type( 'press',
    // let's now add all the options for this post type
    array( 'labels' => array(
        'name' => __( 'Press', 'bonestheme' ),
        'singular_name' => __( 'Press', 'bonestheme' ),
        'all_items' => __( 'All Press', 'bonestheme' ),
        'add_new' => __( 'Add New', 'bonestheme' ),
        'add_new_item' => __( 'Add New Post', 'bonestheme' ),
        'edit' => __( 'Edit', 'bonestheme' ),
        'edit_item' => __( 'Edit Post', 'bonestheme' ),
        'new_item' => __( 'New Post', 'bonestheme' ),
        'view_item' => __( 'View Post', 'bonestheme' ),
        'search_items' => __( 'Search Posts', 'bonestheme' ),
        'not_found' =>  __( 'Nothing found in the Database.', 'bonestheme' ),
        'not_found_in_trash' => __( 'Nothing found in Trash', 'bonestheme' ),
        'parent_item_colon' => ''
        ),
        'description' => __( 'Press', 'bonestheme' ),
        'public' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'show_ui' => true,
        'query_var' => true,
        'menu_position' => 8,
        'rewrite'   => array( 'slug' => 'press-posts' ),
        'has_archive' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'supports' => array( 'title', 'thumbnail', 'excerpt', 'revisions', 'sticky', 'custom-fields', 'editor', 'author' )
    )
);

register_post_type( 'more_posts',
    array( 'labels' => array(
        'name' => __( 'More Posts', 'bonestheme' ),
        'singular_name' => __( 'Post', 'bonestheme' ),
        'all_items' => __( 'All Posts', 'bonestheme' ),
        'add_new' => __( 'Add New', 'bonestheme' ),
        'add_new_item' => __( 'Add New Post', 'bonestheme' ),
        'edit' => __( 'Edit', 'bonestheme' ),
        'edit_item' => __( 'Edit Post', 'bonestheme' ),
        'new_item' => __( 'New Post', 'bonestheme' ),
        'view_item' => __( 'View Post', 'bonestheme' ),
        'search_items' => __( 'Search Posts', 'bonestheme' ),
        'not_found' =>  __( 'Nothing found in the Database.', 'bonestheme' ),
        'not_found_in_trash' => __( 'Nothing found in Trash', 'bonestheme' ),
        'parent_item_colon' => ''
        ),
        'description' => __( 'More Posts', 'bonestheme' ),
        'public' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => true,
        'show_ui' => true,
        'query_var' => true,
        'menu_position' => 9,
        'rewrite'   => array( 'slug' => 'more-posts' ),
        'has_archive' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'supports' => array( 'title', 'thumbnail', 'excerpt', 'revisions', 'sticky', 'custom-fields', 'editor', 'author' ),
    )
);

I am adding the taxonomies with this code, also in the custom_posts(); function:
    register_taxonomy( 'press_cat',
    array('press'), /* if you change the name of register_post_type( 'press', then you have to change this */
    array('hierarchical' => true,     /* if this is true, it acts like categories */
        'labels' => array(
            'name' => __( 'Categories', 'bonestheme' ), /* name of the custom taxonomy */
            'singular_name' => __( 'Press Category', 'bonestheme' ), /* single taxonomy name */
            'search_items' =>  __( 'Search Press Categories', 'bonestheme' ), /* search title for taxomony */
            'all_items' => __( 'All Press Categories', 'bonestheme' ), /* all title for taxonomies */
            'parent_item' => __( 'Parent Press Category', 'bonestheme' ), /* parent title for taxonomy */
            'parent_item_colon' => __( 'Parent Press Category:', 'bonestheme' ), /* parent taxonomy title */
            'edit_item' => __( 'Edit Press Category', 'bonestheme' ), /* edit custom taxonomy title */
            'update_item' => __( 'Update Press Category', 'bonestheme' ), /* update title for taxonomy */
            'add_new_item' => __( 'Add New Press Category', 'bonestheme' ), /* add new title for taxonomy */
            'new_item_name' => __( 'New Press Category Name', 'bonestheme' ) /* name title for taxonomy */
        ),
        'show_admin_column' => true,
        'show_ui' => true,
        'query_var' => true,
        'rewrite' => array( 'slug' => 'press-posts-category' )
    )
);
register_taxonomy( 'more_cat',
    array('more_posts'), /* if you change the name of register_post_type( 'more-posts', then you have to change this */
    array('hierarchical' => true,     /* if this is true, it acts like categories */
        'labels' => array(
            'name' => __( 'Categories', 'bonestheme' ), /* name of the custom taxonomy */
            'singular_name' => __( 'Post Category', 'bonestheme' ), /* single taxonomy name */
            'search_items' =>  __( 'Search Posts Categories', 'bonestheme' ), /* search title for taxomony */
            'all_items' => __( 'All Posts Categories', 'bonestheme' ), /* all title for taxonomies */
            'parent_item' => __( 'Parent Posts Category', 'bonestheme' ), /* parent title for taxonomy */
            'parent_item_colon' => __( 'Parent Posts Category:', 'bonestheme' ), /* parent taxonomy title */
            'edit_item' => __( 'Edit Posts Category', 'bonestheme' ), /* edit custom taxonomy title */
            'update_item' => __( 'Update Posts Category', 'bonestheme' ), /* update title for taxonomy */
            'add_new_item' => __( 'Add New Posts Category', 'bonestheme' ), /* add new title for taxonomy */
            'new_item_name' => __( 'New Posts Category Name', 'bonestheme' ) /* name title for taxonomy */
        ),
        'show_admin_column' => true,
        'show_ui' => true,
        'query_var' => true,
        'rewrite' => array( 'slug' => 'more-posts-category' )
    )
);

Press - archive is broken(404) when using custom permalinks (works fine with std perma)
More - archive is broken(404) when using custom permalinks (works fine with std perma)
More - category gives me a page, but returns no posts (there are 2 posts in there)
I am using this plugin to create the archive and category lists on the sidebar, it seems to be functioning correctly. The URLs it gives me are:
/press/2015/02/  -  press archives
/more_posts/2015/02/  -  more archive
/more-posts-category/giving-back/  -  more categories

A: Custom post type archives don't have year/month rewrite rules, they only have a single archive which will be at /press/ and /more_posts/. If you want those, you'll have to add them yourself. For the taxonomy, add the taxonomies argument to your post type registration to insure the two objects are connected, see the note about this on register_post_type.


text:
Q: for loop in pgfplots I have a file with 3 columns, space separated. The first two columns represent the center of a circle (x,y) and the last column is the circle radius.
I want to select every 4 rows (or more generally specifying row numbers in a list) and plot selected circles by a for loop.
I do not seem to work it out in pgfplotstable. Any hints?!
Thanks

A: Here's a slightly adapted version of my answer to Drawing different tikz shapes parameterized by data from a file. It draws the circles using a scatterplots. You can choose to draw only every n-th mark using the mark repeat key, choosing which entry to start with using the mark phase key.

\documentclass{article}

\usepackage{pgfplots, filecontents}

\begin{filecontents}{data.dat}
# x y r
1 1 1
3 2 0.5
6 3 0.4
4 1 0.8
5 4 0.3
6 2 1
\end{filecontents}

\makeatletter
\begin{document}
\begin{tikzpicture}
\begin{axis}[scatter,
    scatter src=explicit,
    axis equal,
    only marks,
    grid=both,
    width=10cm,
    xmin=0, xmax=8,
    disabledatascaling,
    scatter/@pre marker code/.code={% Transform the data units to paper units
    \pgfkeys{/pgf/fpu=true}
      \pgfmathparse{(\pgfplotspointmeta*
        10^\pgfplots@data@scale@trafo@EXPONENT@x)*\pgfplots@x@veclength)}
      \pgfmathfloattofixed{\pgfmathresult}%
      \pgfkeys{/pgf/fpu=false}
      \scope[mark size=\pgfmathresult]
    }
]
\addplot [fill=yellow, mark repeat=2] file {data.dat};
\end{axis}
\end{tikzpicture}

\end{document}


text:
Q: Почему когда мы реализуем UserDetailsService, в методе loadUserByUsername мы в аргументах получаем username? Я начал изучать Spring Security, и столкнулся с непониманием, почему когда мы реализуем UserDetailsService, в методе loadUserByUsername, в аргументах получаем только username. А что делать, если у меня два юзера с одинаковыми юзернеймами? Или юзернейм должен быть уникален? Если так зачем, тогда использовать id?

A: из документации UserDetailsService
* @param username the username identifying the user whose data is required.

Это то значение которое пользователь вводит в поле логин при входе на сайт и дальше с помощью этого идентификатора пользователя проверяется пароль (достается с БД запись пользователя для сравнения пароля БД с входным)


text:
Q: Ansible service module returns service status as stopped when the service is actually running Trying to stop a service (dse datastax enterprise) using ansible 2.7
   - name: Stop service dse, if started
 service:
  name: dse
  state: stopped

What I think ansible is saying is, I'm not doing anything because this service is already stopped. Part of the verbose output:
ok: [myhostname.domain.com] => {
"changed": false,
"invocation": {
    "module_args": {
        "daemon_reload": false,
        "enabled": null,
        "force": null,
        "masked": null,
        "name": "dse",
        "no_block": false,
        "scope": null,
        "state": "stopped",
        "user": null
    }
},
"name": "dse",
"state": "stopped",

When I check the service on the remote host this is what I see
[user@remotehost ~]$ service dse status
dse is running

So what am I missing here?
FYI it's recommended doing a sudo service dse stop for this service, I don't know if lack of the sudo will make such a difference.

A: My understanding of this is since I do not have an unrestricted sudo and I do not have the ability to execute in /bin/sh thus it is failing.
The same command works when directly run on the server, and that is because
Ansible sends Python code to be executed on the targeted servers. Since Ansible is running Python code and generally not executing system commands directly, you can't limit system commands with sudo and expect them to work with Ansible.
More: https://gist.github.com/nanobeep/3b3d614a709086ff832a
Not sure everyone has this luxury but in my case modifying the sudoers file
from
TheGroupNameImPartOf ALL= ALL, !SU, !SHELLS
to
TheGroupNameImPartOf ALL= ALL
Did the magic!


text:
Q: Creating keyboard hotkeys/shortcuts in Word with VBA For some reason my shortcuts in my normal.dotm files gets deleted once in a while,
so I know i can create shortcuts in word by clicking around in word (https://wordribbon.tips.net/T008058_Assigning_a_Macro_to_a_Shortcut_Key.html)
but I would like to hardcode them instead like I do in excel:
Sub keyBoardShortCuts()

    Application.OnKey "%^d", "updateDB"
    Application.OnKey "%^p", "openProjectList"
    Application.OnKey "%^m", "addNewLS"
    Application.OnKey "%^l", "createLS"
    Application.OnKey "%^g", "loadGui"
    Application.OnKey "%^b", "Custom_Button_Click"

End Sub
Private Sub Workbook_Open()
    Call keyBoardShortCuts
End Sub

However this does not work in word, so what is the syntax to do so in word?

A: You'll need to use KeyBindings and the constants from Enum WdKey  (press F2 to see the list) :
With Application.KeyBindings
    .Add KeyCode:=BuildKeyCode(wdKeyAlt, wdKeyControl, wdKeyD), _
         KeyCategory:=wdKeyCategoryCommand, _
         Command:="updateDB"
    .Add KeyCode:=BuildKeyCode(wdKeyAlt, wdKeyControl, wdKeyP), _
         KeyCategory:=wdKeyCategoryCommand, _
         Command:="openProjectList"
    .Add KeyCode:=BuildKeyCode(wdKeyAlt, wdKeyControl, wdKeyM), _
         KeyCategory:=wdKeyCategoryCommand, _
         Command:="addNewLS"
    '...
End With 'Application.KeyBindings


text:
Q: Controller action not working with external callback I have a custom payment module where I need a controller for callback to get notified about the payment, but the payment service only gives me the error that the response contains html. Also, in the controller action I log every request and there aren't any requests from the callback service coming in. When I cann the exact same URL manually in the browser, everything works as expected and the callback also works fine with a simple test php file, only with Magento controllers it doesn't. I just don't understand why I don't get the request. Any ideas?

A: Is it hosted on a local server or hosted on a server where the site is reachable?
http://localhost or any local network address is just unreachable from  outside.


text:
Q: When does the conformal dimension in 2d CFT have to be integer? I am quite confused. In all books on CFT it is stated that the conformal dimension $h$ of the chiral quasi-primary field has to be integer or half-integer. This seems to be crucial in certain proofs. See, for example, (6.142) in di Francesco, authors use $l+n+h_A=0$, where $l$ and $n$ are integers.
Also, if $h$ is not an integer, it's quite hard to imagine what $\phi(0)|0\rangle$ is; assuming that $$\phi(z)=\sum_{m\in \mathbb{Z}}z^{-m-h}\phi_m$$
However, as the discussion of Verma modules and minimal models starts, we begin considering the HWSs of $L_0$, the vectors $|h\rangle$ with arbitrary real values of $h$. I minimal models, $h$ takes certain rational values.
What am I missing? Are the fields corresponding to these states non-primary? When $h$ is integer and when is not?

A: Conformal dimensions do not have to be integer. Only the difference between the left and right dimensions, i.e. the conformal spin, should be integer for correlation functions to be single-valued.
In the Section 6.5 of di Francesco et al, all you need for defining normal ordering is that the OPE (6.124) of the two fields $A$ and $B$ involves integer powers of their separation. This assumption is independent from $A$ and $B$ having integer conformal dimensions. Rather, it means
$$
h_{(AB)}\in h_A + h_B + \mathbb{Z}
$$
Then there is an attempt to rewrite the normal ordering in terms of modes. In the mode decompositions (6.140), a priori $n+h_A$ and $p+h_B$ should be integer, but $n,p,h_A,h_B$ could be non-integer. Similarly, the mode numbers $m$ of $(AB)$ (as in $(AB)_m$) need not be integer, but $m+h_{(AB)}$ should be integer.
None of this relies on fields being primary or quasi-primary. (In general, conformal dimensions are defined as eigenvalues of $L_0$.)


text:
Q: Can't vertical center align text inside a JLabel numBox is a square JLabel like the ones in the game 2048. The text where the number goes will not vertically center.
neither
numBox.setVerticalAlignment(JLabel.CENTER);

nor
numBox.setVerticalTextPosition(JLabel.CENTER);

are working.
Text shows up horizontally centered but at the top of the box that the label shows up in.
How do I get the text to show up in the middle of the JLabel?

A: You can give an alignment suggestion to the layout manager by using:
label.setAlignmentY(JLabel.CENTER_ALIGNMENT);

If this doesn't help then post a proper SSCCE that demonstrates the problem.


text:
Q: Firefox and IE9 different handling of scrollbars when overflow:auto Hope you can help me. I am wanting my div with max-height and overflow:auto to render the scrollbars inside the element
div
{
    overflow:auto;
    max-height:700px;
}

Firefox and Chrome are, as desired, putting the vertical scrollbar inside the overflowing div, however IE9 is putting the scrollbar outside of the div.
Can anyone help me get that scrollbar inside the element on IE?
You can see the actual page here:
http://new.lambwatch.co.uk/chat.htm
And the scrolling div is that div on the right.

A: First, add
<meta http-equiv="X-UA-Compatible" content="IE=edge">

in head. If doesn't help, try to not float the div with scrollbar.


text:
Q: How do I properly initialize 'struct stat' using C++11? For years I have been initializing my struct stat like this:
#include <sys/stat.h>
struct stat foo = {0};

Specifically, that {0} set all the fields to zero, equivalent to memset (&foo, NULL, sizeof foo);.  Now with C++11, this has started yielding warnings:
foo.cpp:2:19: warning: missing field 'st_mode' initializer [-Wmissing-field-initializers]
  struct stat s = {0};
                    ^

This is because of the new initializer syntax of C++11, and the warning implies I am not initializing all members.  What is the preferred way to instantiate and initialize a struct stat in C++11?

A: Use
stat s{};

instead and it will do the job without any warnings. It is called value-initialization of the object. Although in your case struct stat foo = {0}; should perform aggregate initialization (assuming your struct stat is an aggregate), and the remaining members should be value-initialized also, so technically the code is correct.

A: If your compiler is older and doesn't support struct s{} syntax, you might still be able to use C99 syntax: struct stat s = { .st_dev = 0 };  Failing even that, or if you have to wipe one, memset( &s, 0, sizeof(struct stat) ); will always work.

A: Could this stem from a case of misunderstanding {0}? You know that the 0 doesn't actually mean "set all fields to zero", right? It means "set the first field to zero" ... and all the other ones are left to the whim of the language (which, as it happens, will zero-initialise them anyway).
struct stat foo = {} would more accurately describe your intention, and I suspect it would also take care of the warning.
Of course, nowadays, you can be absolutely clear by writing struct stat foo{};.


text:
Q: How to get the item count in the first row of a WrapPanel? A list of UIElements with the same height are added to a WrapPanel, and the XAML is
<Grid>
    <ListView ScrollViewer.HorizontalScrollBarVisibility="Disabled">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
    </ListView >
</Grid>

When run it looks like this

In order to get the item count of the first row, I tried to calculate the coordinates (relative to the listview) of each item's upper-left corner, by comparing each item's vertical offset with the first item, I can get the item count of the first row.
But the code can easily break if items have different height.
ListView listView = (sender as ListView);
if (listView.Items.Count > 0)
{
    UIElement firstItem = ((listView.Items)[0] as UIElement);
    double y = firstItem.TranslatePoint(new Point(0, 0), listView).Y;

    int counter = 0;
    foreach (UIElement item in listView.Items)
    {
        if ((item.TranslatePoint(new Point(0, 0), listView).Y != y))
        {
            break;
        }
        counter++;
    }
}

What is the correct way to do this?

A: This method should get the job done:
private static int GetItemsInFirstRow(ItemsControl itemsControl)
{
    double previousX = -1;
    int itemIndex;

    for (itemIndex = 0; itemIndex < itemsControl.Items.Count; itemIndex++)
    {
        var container = (UIElement)itemsControl.ItemContainerGenerator
                                                .ContainerFromIndex(itemIndex);

        var x = container.TranslatePoint(new Point(), itemsControl).X;

        if (x <= previousX)
        {
            break;
        }

        previousX = x;
    }

    return itemIndex;
}


text:
Q: How to read start_urls from csv file in scrapy? I have two spiders. Let's say A and B. A scrapes bunch of urls and writes it into a csv file and B scrapes inside those urls reading from the csv file generated by A. But it throws FileNotFound error from B before A can actually create the file. How can I make my spiders behave such that B waits until A comes back with url? Any other solution would be helpful.
WriteToCsv.py file
def write_to_csv(item):
    with open('urls.csv', 'a', newline='') as csvfile:
        fieldnames = ['url']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writerow({'url': item})

class WriteToCsv(object):
    def process_item(self, item, spider):
        if item['url']:
            write_to_csv("http://pypi.org" +item["url"])
        return item

Pipelines.py file
ITEM_PIPELINES = {
    'PyPi.WriteToCsv.WriteToCsv': 100,
    'PyPi.pipelines.PypiPipeline': 300,
}

read_csv method
def read_csv():
x = []
with open('urls.csv', 'r') as csvFile:
    reader = csv.reader(csvFile)
    for row in reader:
        x = [''.join(url) for url in reader]
return x

start_urls in B spider file
start_urls = read_csv() #Error here

A: I would consider using a single spider with two methods parse and final_parse. As far as I can tell from the context you have provided there is no need to write the URLs to disk.
parse should contain the logic for scraping the URLs that spider A is currently writing to the csv and should return a new request with a callback to the final_parse method.
def parse(self, response):
    url = do_something(response.body_as_unicode())
    return scrapy.Request(url, callback=self.final_parse)

final_parse should then contain the parsing logic that was previously in spider B.
def final_parse(self, response):
    item = do_something_else(response.body_as_unicode())
    return item

Note: If you need to pass any additional information from parse to final_parse you can use the meta argument of scrapy.Request.
If you do need the URLs, you could add this as a field to your item.
It can be accessed with response.url.


text:
Q: Firebase / Recaptcha / Ionic / Angular - Cannot assign to read only property 'taskData' of object '[object Object]' I have an Ionic app (@ionic/angular: 4.0.0-beta.17) and I'm using Firebase as my Authenticator (via @angular/fire).
Whenever I try to sign in with a phone number, I pass the number (as E.164) and the appVerifier, and I made an invisible recaptcha. I can assure you that these values are valid.
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)

Unexpectedly, I get a TypeError from Recaptcha:

ERROR TypeError: Cannot assign to read only property 'taskData' of object '[object Object]'
at HTMLDivElement.addEventListener (zone.js:1829)
at gg (recaptcha__iw.js:91)
at Vp (recaptcha__iw.js:89)
at He.Ot.A (recaptcha__iw.js:163)
at am (recaptcha__iw.js:566)
at He.am.render (recaptcha__iw.js:565)
at iW (recaptcha__iw.js:569)
at Oi (recaptcha__iw.js:578)
at jJ.w.CQ.jJ.a0.jJ.Eu (recaptcha__iw.js:573)
at Object.Ei [as reset] (recaptcha__iw.js:574)

This is the whole process of authentication:
return firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
  .then(result => (windowRef as any).confirmationResult = result)
  .catch(err => { // <-- returns error
    appVerifier.render().then(widgetId => grecaptcha.reset(widgetId));
    return Promise.reject(err);
  });

After that error occurs, I get another error regarding this line:
appVerifier.render().then(widgetId => grecaptcha.reset(widgetId));

Uncaught TypeError: Cannot read property 'then' of null
at jJ.w.CQ.jJ.a0.jJ.Eu (recaptcha__iw.js:573)
at Object.Ei [as reset] (recaptcha__iw.js:574)
at auth.state.ts:107 <----- (the line I mentioned above)
at e.g (auth.esm.js:17)
at Fb (auth.esm.js:20)
at Bb (auth.esm.js:20)
at A.push../node_modules/@firebase/auth/dist/auth.esm.js.g.Xb (auth.esm.js:19)
at kb (auth.esm.js:13)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)

For some reason, when I downgrade the package @ionic/angular back to version 4.0.0-beta.15, it seems to work. I have no idea what's happening behind the scene.
I'm not sure if this bug is related to Ionic or Recaptcha or Firebase.
package.json (deps only)
"dependencies": {
  "@angular/common": "~7.0.0",
  "@angular/core": "~7.0.0",
  "@angular/fire": "~5.1.0",
  "@angular/forms": "~7.0.0",
  "@angular/http": "~7.0.0",
  "@angular/platform-browser": "~7.0.0",
  "@angular/platform-browser-dynamic": "~7.0.0",
  "@angular/router": "~7.0.0",
  "@fortawesome/angular-fontawesome": "^0.3.0",
  "@fortawesome/fontawesome-svg-core": "^1.2.8",
  "@fortawesome/pro-light-svg-icons": "^5.5.0",
  "@fortawesome/pro-regular-svg-icons": "^5.5.0",
  "@fortawesome/pro-solid-svg-icons": "^5.5.0",
  "@ionic-native/core": "^5.0.0-beta.21",
  "@ionic-native/google-maps": "^5.0.0-beta.25",
  "@ionic-native/social-sharing": "^5.0.0-beta.21",
  "@ionic-native/splash-screen": "5.0.0-beta.21",
  "@ionic-native/status-bar": "5.0.0-beta.21",
  "@ionic/angular": "4.0.0-beta.17",
  "@ionic/pro": "^2.0.3",
  "@ngx-translate/core": "^11.0.0",
  "@ngx-translate/http-loader": "^4.0.0",
  "@ngxs/devtools-plugin": "^3.2.0",
  "@ngxs/form-plugin": "^3.2.0",
  "@ngxs/router-plugin": "^3.2.0",
  "@ngxs/store": "^3.2.0",
  "cordova-browser": "5.0.4",
  "cordova-plugin-device": "^2.0.2",
  "cordova-plugin-googlemaps": "2.4.6",
  "cordova-plugin-ionic-keyboard": "^2.1.3",
  "cordova-plugin-ionic-webview": "^2.2.1",
  "cordova-plugin-splashscreen": "^5.0.2",
  "cordova-plugin-statusbar": "^2.4.2",
  "cordova-plugin-whitelist": "^1.3.3",
  "core-js": "^2.5.3",
  "firebase": "^5.5.8",
  "libphonenumber-js": "^1.6.5",
  "lodash": "^4.17.11",
  "rxjs": "6.2.2",
  "zone.js": "^0.8.26"
},
"devDependencies": {
  "@angular-devkit/architect": "~0.8.5",
  "@angular-devkit/build-angular": "~0.8.5",
  "@angular-devkit/core": "~0.8.5",
  "@angular-devkit/schematics": "~0.8.5",
  "@angular/cli": "~7.0.0",
  "@angular/compiler": "~7.0.0",
  "@angular/compiler-cli": "~7.0.0",
  "@angular/language-service": "~7.0.0",
  "@ionic/angular-toolkit": "^1.0.0",
  "@types/jasmine": "~2.8.6",
  "@types/jasminewd2": "~2.0.3",
  "@types/lodash": "^4.14.119",
  "@types/node": "~10.12.0",
  "codelyzer": "~4.5.0",
  "jasmine-core": "~2.99.1",
  "jasmine-spec-reporter": "~4.2.1",
  "karma": "~3.0.0",
  "karma-chrome-launcher": "~2.2.0",
  "karma-coverage-istanbul-reporter": "~2.0.0",
  "karma-jasmine": "~1.1.1",
  "karma-jasmine-html-reporter": "^0.2.2",
  "protractor": "~5.4.0",
  "ts-node": "~7.0.0",
  "tslint": "~5.11.0",
  "typescript": "~3.1.6"
},

$ ionic info
Ionic:

   ionic (Ionic CLI)             : 4.5.0 (C:\Users\Eliya\AppData\Roaming\npm\node_modules\ionic)
   Ionic Framework               : @ionic/angular 4.0.0-beta.17
   @angular-devkit/build-angular : 0.8.8
   @angular-devkit/schematics    : 0.8.8
   @angular/cli                  : 7.0.7
   @ionic/angular-toolkit        : 1.2.0

Cordova:

   cordova (Cordova CLI) : not installed
   Cordova Platforms     : browser 5.0.4
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 2.2.1, (and 5 other plugins)

System:

   Android SDK Tools : 26.1.1 (E:\android-sdk)
   NodeJS            : v10.11.0 (C:\Program Files\nodejs\node.exe)
   npm               : 6.4.1
   OS                : Windows 10


text:
Q: Libgdx: Lags in soundtrack looping I'm having trouble with music looping in libgdx. I know a simmilair topic was here before, but it didn't help me at all. The thing is that when you go to main menu in my game (link) the sound of rain is looped. Unfortunately, there is a short moment of silence between each play and I don't know why - you can download the game and see what I mean. I'm already using .ogg format, so the solution from the other topic I found here didn't really help.
If I play this sound in a loop in Audacity, it works perfectly.
Here is my code (I don't think it'll help, though):
rainSoundtrack = Gdx.audio.newMusic(Gdx.files.internal("soundtrack.ogg"));
rainSoundtrack.setLooping(true);

A: The problem is the way libGDX handles Music. I will quote a badlogic post on GitHub issue 1654.

the Android situation is a bit more complicated and sad. On Android we use the system facilities to playback audio, namely MediaPlayer. This pieces of Android software uses device dependend drivers under the hood (audio drivers, custom codec implementations, etc.). This means that we are at the mercy of hardware vendors like Samsung and their driver implementations.

The problem is not bound only to libGDX, it is Android issue 18756.
Solution
Your soundtrack is short and small in term of memory size so using libGDX sound is actually better in this case and it is free of this gap bug.
Music -> long and big files, not loaded into memory
Sound -> short and small files, loaded into memory
Use Sound class and loop it. Example:
long id;
...
public void create() {
    music = Gdx.audio.newSound(Gdx.files.internal("soundtrack.ogg"));
    id = music.loop(); //Sound may not be ready here!
}

public void render() {
    if(id == -1)
        id = music.loop();
}


text:
Q: Custom resampling method in caret I need to create a custom resampling method in R package caret where: For each leave-pair-out-cross-validation, from the training set I derive new data using a function I implemented. Then it is used as training set, and tested against the 2 instances left out. In the next iteration new data will be derived from the new training set resampled.
In the caret custom models manual page it is showed how to make a custom model but I would like to make a custom resampling method in the trainControl function that can be used with any train model. Is that possible in caret ?
So to recap, I need some sort of LGOCV that for each iteration takes the input training set and transforms it in a new dataframe with a function I created that will be used as actual training.

A: So, if you had 8 training set samples would this scheme result in choose(8,2) = 28 resamples? Also, I'm assuming that this isn't two nested leave-one-out loops.
If so, here is a solution that might breakdown with large sample sizes.
num_samps <- 8
holdout <- combn(num_samps, 2)
in_training <- apply(holdout, 2,
                     function(x, all) all[!(all %in% x)],
                     all = 1:num_samps)

## need a more effcient way of doing this:
index <- vector(mode = "list", length = ncol(in_training))
for(i in 1:ncol(in_training)) index[[i]] <- in_training[,i]
## cosmetic:
names(index) <- caret:::prettySeq(seq(along = index))

ctrl <- trainControl(method = "cv", ## this will be ignored since
                     ## we supply index below
                     index = index)

Max


text:
Q: Saving function pointer in a class
Possible Duplicate:
How can I pass a class member function as a callback?

I have two classes A and B
class A
{
public:
   void SetHandler(void (*p)(OMX_BUFFERHEADERTYPE*)){ Handler = p; };
private:
  void (*Handler)(OMX_BUFFERHEADERTYPE*);
}

and
in B I have a function
void B::handler(OMX_BUFFERHEADERTYPE* p){};

now when (from B) I call
inst_a.SetHandler(&B::handler);

i get the following error:
B.cpp:740:69: error: no matching function for call to 'A::SetHandler(void (COMXVideo::*)(OMX_BUFFERHEADERTYPE*))'
B.cpp:740:69: note: candidate is:
A.h:161:8: note: void A::SetHandler(void (*)(OMX_BUFFERHEADERTYPE*))
A.h:161:8: note:   no known conversion for argument 1 from 'void (B::*)(OMX_BUFFERHEADERTYPE*)' to 'void (*)(OMX_BUFFERHEADERTYPE*)'

what am I doing wrong?
Best Regards

A: &B::handler is not a function pointer, but a pointer to member function. If B::handler doesn't need members of B, you can define it static. Then SetHandler(&B::handler) will work.
If you must have a pointer to member function, you can define it as
void (B::*Handler)(OMX_BUFFERHEADERTYPE*);

when you call such a member function, you need a pointer to an object as well
(inst_b->*Handler)(omxbuffer);

or with a reference
(inst_b.*Handler)(omxbuffer);

A: try somthing like this:
template<typename C>
class EventObject
{

    public:
        typedef void (C::*FunctionType)();

        template <typename ... T>
        EventObject(C& obj,FunctionType methode): obj (obj), callback (methode) {};

       void execute(){obj.*callback();};

    private:
        C& obj;
        FunctionType callback;
};


text:
Q: Distribute VM and force new mac address I wish to distribute a VMWare VM for users (who are technically challenged and unable to install a complex product).  Users may run several instances of the VM in their environment, so it's essential that each VM have NIC's with unique MAC addresses.
Is there a way to distribute the VM in such a way that on first boot if forces new MAC addresses onto the NIC's?
If users just add the VM to their inventory and select 'moved' instead of 'copied' then they get the same MAC's (I believe).
I'm using VMWare WOrkstation 12 in case that matters.

A: The canonical "correct" way to distribute VM images for VMware vSphere is to distribute .ova files created using ovftool, and then use the vSphere GUI to install the .ova file. This automatically distributes a "copied" version of the virtual machine that has a different MAC address when deployed. However, there is a way to do the job if you're going to instead distribute a zipped up VMware Workstation directory. What you need to do is, immediately before you zip up the directory, is first copy the .vmx file someplace else. Then edit the vmx file and look for a line that looks like
ethernet0.generatedAddress = "00:0c:29:28:70:9d"

Remove that line from the vmx file.
Then zip it up and distribute it. That should give you copy of the virtual machine that does not have a built in MAC address and that should generate a new MAC address upon deployment. (This is assuming a VM with a single Ethernet interface). Then copy the original .vmx file back into place.
Note that for certain operating systems, such as Red Hat Enterprise Linux 6, there are udev rules that tie a specific Ethernet interface to a specific MAC address. These must be removed to allow eth0 to come up after the deployment. If your operating system is one of those, that is a separate question.


text:
Q: Proving continuity of a certain map This problem is quite simple however I am having some troubles to follow what exactly I am supposed to prove here.
Here is the part (a) of this problem which I have solved
For each $\lambda \ge e$ there is a unique $x \in [0,1]$ satisfying $e^x = \lambda x$
The problem is:
Consider the equation $e^x = \lambda x$
Show that the map that takes $\lambda$ to $x$ above is a continuous map on $[e, \infty)$
My question is: Am I supposed to show that the function defined by $\lambda(x) = e^x/x$ is continuous on given domain ? Or is it some other interpretation that I am missing here.
I am having unable to interpret the question correctly, any help would be appreciated.
Edit:
I got that problem actually asks for proving that map $g(\lambda) = x_1$ is continuous where $x_1$ is the unique $x$ satisfying the map $e^x =\lambda x$ . However I am still confused as to how to prove this rigorously?
Any help?

A: We want to prove that the real function $g:[e,+\infty)\to\mathbb{R}$ such that $g(\lambda)\in[0,1]$ and $e^{g(\lambda)}=g(\lambda)\lambda$ for all $\lambda\geq e$ (which you have already shown to be well defined) is continuous. First of all, let $f:(0,1]\to\mathbb{R}$ be the continuous function $f(x)=e^x/x$. Then, you have probably already shown that $f$ is strictly decreasing on $(0,1]$ because $f'(x)=e^x\left(\frac{1}{x}-\frac{1}{x^2}\right)<0$ for all $x\in(0,1)$. Now, since $f$ is continuous, strictly decreasing, $f(1)=e$ and $\lim_{x\to 0^+}f(x)=+\infty$ you know that $\text{Im}(f)=[e,+\infty)$. Now the proposition that you need to use.

Proposition (Continuity of an inverse function.) If $f:I\to\mathbb{R}$ is a strictly monotonic function (not necessarily continuous) where $I$ is an interval then the function $g:f[I]\to I$ such that $g=f^{-1}$ (which exists since $f$ is injective) is continuous.

Notice that, in our case, the function $g$ of the said proposition is in fact $g:[e,+\infty)\to(0,1]$ such that $\forall\lambda\geq e:e^{g(\lambda)}=g(\lambda)\lambda$ ($g(\lambda)$ can't be $0$ since $e^x$ is never zero). Hence, we conclude that, by this proposition, $g$ is indeed continuous.
The proof of the said proposition is given by @mauro-allegranza on the linked question. However, I will also adapt it for this particular case. Let $\lambda\geq e$ and $\epsilon>0$. If $x:=g(\lambda)\in(0,1)$ (i.e. $\lambda\in(e,+\infty)$) then we know, by the fact that $f$ is strictly decreasing, that $f(x_1)>f(x)=\lambda>f(x_2)$ where $x_1\in(x-\epsilon,x)\cap(0,1]$ and $x_2\in(x,x+\epsilon)\cap(0,1]$ since $x$ is an interior point of $(0,1)$. Now choose $\delta:=\min\{f(x_1)-\lambda,\lambda-f(x_2)\}$. Then, if $\mu\in[e,+\infty)$ is such that $|\lambda-\mu|<\delta$,
$$f(x_1)>\mu>f(x_2)\Rightarrow x_1< g(\mu) < x_2 \Rightarrow |g(\mu)-x|<\epsilon$$
which means that $g$ is continuous on $\lambda\in(e,+\infty)$. For the continuity of $g$ on $\lambda=e$ you can do basically the same by only making use of $x_1\in(x-\epsilon,x)\cap(0,1]$.


text:
Q: Muntz-Coffman Algorithm (Scheduling)
I'm wondering how exactly do you calculate the time slices (2, 4, 5.5, 7, 8.5).

A: Muntz–Coffman is basically the critical path method. The priority of each job is the maximum duration of a chain of dependencies starting from that job. At each point in time, the running jobs are those with the highest priority.
Initial priorities are computed in linear time in reverse topological order.
K: 1 + max(0) = 1
H: 1 + max(0, K) = 2
I: 2 + max(0, K) = 3
J: 4 + max(0) = 4
E: 3 + max(0, H) = 5
F: 2 + max(0, H, I) = 5
G: 3 + max(0, I, J) = 7
A: 2 + max(0, E, F) = 7
B: 1 + max(0, E, F, G) = 8
C: 1 + max(0, G) = 8
D: 2 + max(0, F, G) = 9

D (2 units) is the unique maximum, so it gets a machine all to itself. B (1 unit) and C (1 unit) are tied, so they split the other machine 50/50. At time t, the priority of D is 9 - 2t, and the priority of B and C is 8 - t. Until these three jobs finish, they remain above priority 7, the next highest, D is above B and C, and B and C remain tied.
At time 2, the next highest are A (2 units) and G (3 units), which each receive their own machine. After 2 units of time, A is done, and G's priority has been reduced to 5, tying with E and F. Now E, F, and G are all scheduled with an even three-way split, which lasts until time 5.5 at which point G is finished and the the others are now at priority 4, tying them with J.
Three-way work continues until at time 7, F is done and E's and J's priorities have slipped to 3. Now E, I, and J are scheduled until E is done and I's and J's priorities are down to 2, at which point (time 8.5) H, I, and J are scheduled. H and I finish and J is at 1, at which point (time 10) J and K are scheduled 50/50 until the end at time 11.


text:
Q: why is my pc showing hidden files even after renaming files starting with a dot My pc shows hidden files even after renaming the file with a name which starts with a dot is there any solution for this.

A: Ctrl+H Should toggle whether hidden files are visible.
To permanently change the setting in nautlius go
Edit > Preferences > Views

And turn off: Show hidden and backup files

A: Create an empty documents rename it .hidden. Open it (Mousepad for xubuntu). Type the folder name you want to hide. I have attached a picture. Here $RECYCLE.BIN
and System Volume Information are hidden. So I type the name in .hidden file and put it in the folder where this two folders are currently in that I want to hide. After that hide the folders by CTRL+H. Good luck.


text:
Q: Python: Surface Integral over Mesh Question
How can I compute the surface integral of a specified function of the outer surface of a mesh in python?
Code
I tried to create a minimal workable example. In this example, I try to compute the surface area of a box, which I define using trimesh.

I only compute the surface area because it can be easily checked using the trimesh package (mesh.area), but in the future I will have much more complex functions, therefore, I cannot use the build-in trimesh.integrate.
This is why I have turned to quadpy for the surface integration.
Here is the code:
import numpy as np
import quadpy
import trimesh

# CREATE THE BOX
# object (box)
box = trimesh.creation.box(extents=[0.3, 0.3, 0.3])

# show
box.show(viewer='gl')

# SURFACE INTEGRATION

# 1 GET TRIANGLES of trimesh mesh object
triangles = box.triangles
# 2 SHAPE the triangles array into the shape accepted by quadpy
# trimesh -> (num_traingles, corners, xyz coordinates)
# quadpy ->  (corners, num_triangles, xyz_coords)
triangles_re = np.reshape(triangles,(
                       np.shape(triangles)[1],
                       np.shape(triangles)[0],
                       np.shape(triangles)[2])
                 )
# 3 DEFINE INTEGRATION FUNCTION
def f(x):
    # -> get area of surface Integral[1, Area] = Area
    return np.ones(np.shape(x))

sol, error_estimate = quadpy.t2.integrate_adaptive(f, triangles_re,  1.0e-10)

Issue
I am getting the following error:

assert all(areas > minimum_triangle_area)

AssertionError


text:
Q: Overleaf not showing .eps image in IEEE transactions class I am trying to insert a .eps image in IEEEtran class using the following source code:
begin{figure}[!b]
    \centering
    \includegraphics[scale=0.5]{fig.eps}
    \caption{Figure}
\end{figure}

The compilation does not show the image, and show a thumbnail like this

The file does exist at the path and if I use a file with .jpg format, it compiles successfully. There is something wrong in the way I am inserting the .eps file only.
Please suggest possible solutions.
Thank you.
UPDATE: The draft option is not enabled for class or for graphics. I even tried with \includegraphics[draft=false], but the output is the same.

A: Just change compiler to XeLatex: Menu-->Compilator-->XeLatex
code example:
\documentclass{article}
\usepackage{graphicx}

\begin{document}
\begin{figure}[h]
\includegraphics[width=1\linewidth]{PHOTO.eps}
\caption{}
\label{ris:image}
\end{figure}
\end{document}


text:
Q: Windows Desktop Cordova App Crashing Instalty with no error messages I'm using Visual Studio 2015 RC to create a Cordova App, it works great on Windows Phone Device, Android Emulator and Device, iOS Ripple, but with Windows Desktop it just bombs out instantly with no indication of what went wrong.
Any idea how to debug this?

A: I guess it is the known issue with the certificate required on Windows platform.
https://msopentech.com/blog/2014/11/11/cordova-certificate-issue-were-working-on-it/
You can download the right certificate from there and add it to your project.


text:
Q: I'm getting this error after 'upgrading' (happened as a result of trying to play music) within unity within chromebook This is what it gives me after both resaving a new crouton file over the old one and trying to update it with: sudo sh -e ~/Downloads/crouton -n precise -u
It gives me this error:
Processing was halted because there were too many errors.
Failed to complete chroot setup.
Unmounting /mnt/stateful_partition/crouton/chroots/precise...

But, before this error occurred - it gave this one after solving it with the sudo sh -e ~/Downloads/crouton -n precise -u :
(EE) Server terminated with error (1). Closing log file.
/usr/bin/xinit: giving up
/usr/bin/xinit: unable to connect to X server: No such file or directory
/usr/bin/xinit: server error
Unmounting /mnt/stateful_partition/crouton/chroots/precise...

I know the order is lacking but bear with it and if you need further explanation - well, I'm all ears.


text:
Q: Use Angular interpolated string in CSS content property I am using the CSS content property content: attr(myValue); in an Angular 7 component's .css file
&::before {
    content: attr(myValue);
    position: absolute;
    left: 2em;
    font-weight: bold;
    top: 1em;
    display: block;
    font-family: 'Roboto', sans-serif;
    font-weight: 700;
    font-size: .785rem;
}

which is connected to a string value in the component's .html file like this:

        ...

I want to insert an interpolated string value in the myValue in the .html.  I have tried the various bind techniques outlined in the official Angular template syntax guide without any success.
Is there a way to insert the interpolated value in myValue?  In other words, can I do the equivalent of this:

        ...

A: You cannot bind an unknown property like myValue on a div to a value, the runtime is giving you an error
Error: Template parse errors:
Can't bind to 'myValue' since it isn't a known property of 'div'. ("

]myValue="{{'something'}}">
"): ng:///AppModule/AppComponent.html@4:31

You have to use attr.myValue instead. It is possible to use single quotes ' aswell as double-quotes ".
attr.myValue="{{myBoundValue}}"
attr.myValue='{{myBoundValue}}'

You could ommit the curly braces by using this syntax
[attr.myValue]="myBoundValue"


text:
Q: showPermissionDialog with ExternalInterface (facebook/ flash) I trying to pomp showPermissionDialog for allow the user to post something in a friend Wall.
I have the flowing javascript code:
  <script type="text/javascript">
    function showStreamPermissions() {
    FB.Connect.showPermissionDialog("publish_stream", doResult);
     }
 </script>

On may as3 class file i have this code to call  showStreamPermissions:
protected function showPermissionDialog(e:MouseEvent):void {

  ExternalInterface.call("showStreamPermissions");

  }

But when i click the button to show Premonition Dialog , nothing happens?
Does anyone know why ?
Thanks.
MB

A: I  figure what was the problem. It´s necessary to  allow script access
params.allowScriptAccess="always";


text:
Q: Debian 8 - Random freezing issues I've installed a dual boot Windows 10 / Debian 8 Jessie and frequently my laptop is totally freezing and I can't do anything about it : Everything is fixed including the mouse. I have to restart it manually.
The freezes happen randomly.
My environment is Gnome, my laptop is an Asus Zenbook UX32LN : Intel Core i5 4200U, 8go RAM, 256 GO SSD, and two graphical cards (Intel graphics and NVIDIA 840m)
I had Ubuntu and Elementary OS before Debian and it worked perfectly.
I don't know what other informations you need, just ask me !

A: Do a:
sudo apt-get install firmware-linux firmware-linux-free firmware-linux-nonfree intel-microcode

And reboot. That might fix the issue.

A: I had the same problem with mageia, zorin os (ubuntu) and manjaro (arch linux). Stopping time synchronisation solved it on manjaro:
sudo systemctl ntpd stop


text:
Q: Using substitution $p = x + \frac{1}{x}$ to reduce $2x^4+x^3-6x^2+x+2=0$ How do I use the substitution $p = x + \frac{1}{x}$ to show that the equation
$$2x^4+x^3-6x^2+x+2=0$$
reduces to $2p^2+p-10=0$.
Now, I can do the problem in reverse, but when I try solving $p = x + \frac{1}{x}$ for $x$ and substituting, the resulting equation is too complicated and nothing like the form required.

A: HINT :
Dividing the both sides by $x^2$ gives
$$2x^2+x-6+\frac 1x+\frac{2}{x^2}=0,$$
i.e.
$$2\left(x^2+\frac{1}{x^2}\right)+\left(x+\frac 1x\right)-6=0.$$

A: Hint: divide the equation by $x^2$, then group terms and use the identity $(x+\frac{1}{x})^2 = x^2 + \frac{1}{x^2} + 2$.


text:
Q: how to get set-cookie from HTTP header request and send it in another API angular In my angular project, I have a basic signin page where user enters their email and password and on submit, I send the email and password to server and receive a response that contains setcookie which I have to use in the next page which is two-factor authentication.
I want to use that cookie in another API call (for two-factor authentication) but I don't know how.
This is my userLogin API call:
userLogin(formdata: Login ): Observable<any> {
    return this.http.post
    (this.ServerUrl + 'Account/login', formdata, { headers: new HttpHeaders({'accept': 'text/plain',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + this.token,
      }), observe: 'response' , withCredentials: true });
  }

And this is the response cookies that i get from server:
Cookies
And this is my user2fa API call:
 user2Fa(formdata: Factor ): Observable<any> {
    return this.http.post
    (this.ServerUrl + 'Account/twoFactorLogin', formdata, { headers: new HttpHeaders({'accept': 'text/plain',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + this.token,
      }), observe: 'response' , withCredentials: true });
  }

A: You are unable to access the cookie from your Angular code are you? I had faced similar issues in the past but I did not require to make any changes in my code. I had to make some environment-specific changes.
I do not know the exact environment you are working with, but the following points might help you out with finding a solution:

*

*The login REST API call and the subsequent REST API call, if they being made to the same server/URL domain, the cookies should be automatically sent along with your request in the subsequent requests by your browser.

*Check the Headers tab of your response from the login REST API's response. Does the set-cookie entry have an attribute named "HttpOnly"? If this is the case, I doubt whether the cookie will be accessible from javascript code.

*If point no. 2 is applicable, is your Angular application running on HTTP and your REST API running on HTTPS? If so, unless your Angular application is running on HTTPS, your browser will not be sending back the received cookie in the subsequent requests. In this case, you may need to use a self-signed certificate to run your Angular application on HTTPS on localhost to test.

Also, I would suggest you test your current set-up running the Angular application and check if the same behavior is seen.


text:
Q: Creating a "favorite" feature on a list of questions that get randomized I'm having a hard time correctly implementing a 'favorites' feature for my app.  Moving through a list of objects, the user should be able to check/uncheck something as a favorite.  Once the activity moves into the onPause(); state, it should save the list of favorites (rather, the complete list of boolean markers that signal whether something is a favorite or not... true for favorite, false for not a favorite.)  Obviously, upon moving into the onResume(); state, the list should be loaded so they can view the favorites that they've previously marked.
My issue, I think, truly comes from the fact that the list is randomized upon initialization.  I'm sure my algorithm is off, but I've tried various ways to the point where I can hardly bare to look at it anymore.
Main Activity Java
public class MainActivity extends ActionBarActivity {

Global global_main;

@Override
protected void onCreate(Bundle savedInstanceState) {

    global_main = Global.getInstance("all");

}

@Override
protected void onResume(){
    super.onResume();

    SharedPreferences settings = getSharedPreferences(FILE_FAVORITES, 0);

    for(int index = 0; index < TOTAL_QUESTIONS; index++){

        boolean favFromFile = settings.getBoolean(("savedFavorite_" + String.valueOf(index)), false);
        global_main.setFav(index, favFromFile);

    }

}

@Override
protected void onPause(){
    super.onPause();

    SharedPreferences settings = getSharedPreferences(FILE_FAVORITES, 0);
    SharedPreferences.Editor editor = settings.edit();

    for(int index = 0; index < TOTAL_QUESTIONS; index++){
        editor.putBoolean(("savedFavorite_" + String.valueOf(index)), global_main.getFav(index));

        // Commit the edits!
        editor.commit();
    }

}

Practice Java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = getIntent();
    selectedSection = intent.getStringExtra(chooseSection.chosenSection);

    global = Global.getInstance(selectedSection);

}

Global Class
public class Global {

private static Global global = null;

//Current total of questions which the user has chosen
//EX: if Multiplication was chosen and has 10 questions in the array
//Then this equals 10
int CURRENT_TOTAL;

//This is the position that the first question of the user's choice starts with
//EX: If user chooses Multiplication, and the multiplication questions start at questions[19];
//Then this equals 19
int CURRENT_START;

//This is the position that the last question of the user's choice ends with
//EX: If user chooses Multiplication, and the multiplication questions end at questions[24];
//Then this equals 24
int CURRENT_END;

//Basic question structure
class questionStruct
{

    String q;
    String a;
    int position; //original position in the array;
    boolean favorite;

}

//Array of question structures
questionStruct[] questions = new questionStruct[TOTAL_QUESTIONS];

//userChoice is the choice of question type that the user has selected.
//EX: Multiplication, Division, Addition, Subtraction, or All/Default
public static Global getInstance(String userChoice) {
    if(global == null)
    {
        global = new Global();
        global.initialize();
    }

    global.getChoice(userChoice);
    global.setQuestionsDefault();
    global.randomize();
    return global;

}

public void initialize() {
    for (int i = 0; i < TOTAL_QUESTIONS; i++) {
        questions[i] = new questionStruct();
    }

    questions[0].q = "Question 1 Text";
    questions[0].a = "Answer";
    questions[0].position = 0;
    questions[1].q = "Question 2 Text";
    questions[1].a = "Answer";
    questions[1].position = 1;
    questions[2].q = "Question 3 Text";
    questions[2].a = "Answer";
    questions[2].position = 2;
    ....ETC.
    ....ETC.
    ....ETC.
}

public void setQuestionsDefault(){

    questionStruct temp = new questionStruct();

    for(int index = 0; index < TOTAL_QUESTIONS; index++){

        int count = questions[index].position;

        temp = questions[count];
        questions[count] = questions[index];
        questions[index] = temp;

        temp = null;
    }
}

//Randomize the questions only within the range of the category
//which the user has chosen
public void randomize(){

    for(int index = CURRENT_END; index >= CURRENT_START; index --)
    {
        //Generate random number to switch with random block
        Random rand = new Random();
        int currentQ = rand.nextInt((CURRENT_END - CURRENT_START) + 1) + CURRENT_START;

        //Switch two Question blocks
        questionStruct temp = questions[currentQ];
        questions[currentQ] = questions[index];
        questions[index] = temp;

    }
}

public void setFav(int q, boolean b){
    questions[q].favorite = b;
}

public boolean getFav(int q){
    return questions[q].favorite;
}

That MIGHT be everything pertinent to my issues.  I apologize if I left anything out or if something doesn't make sense.  Feel free to ask questions.  I'm still currently in the middle of altering everything to get it to work, so I might have copied over something that doesn't quite add up.
EDIT: I'll also add the code for the "favorite" button click to turn a favorite into a non-favorite and vise versa.  Even though it's critical to having this work, it's not something I was worried about functioning properly because it's so simple.  But, if someone feels they'd like to see it, and in turn help me out, then here it is.
This is also in the Practice Questions Java file:
public void setFavoriteButton(){
    if(global.getFav(tempQQ)){
        FAVORITE.setBackgroundColor(Color.YELLOW);
    }
    else{
        FAVORITE.setBackgroundColor(getResources().getColor(R.color.primary));
    }
}

@Override
public void onClick(View v){

    switch(v.getId()){

        case R.id.favorite:
            updateFavorite();
            break;
    }
}

public void updateFavorite(){

    if(global.getFav(tempQQ)){
        global.setFav(tempQQ, false);
    }
    else{
        global.setFav(tempQQ, true);
    }

    setFavoriteButton();
}

EDIT: I might should add that I believe the issue is algorithmic.  If I didn't have the "randomize" feature in conjunction with the favorites, I'd be fine I think.  But I think both are important for my app to be very useful.  So that's where my focus is at, trying to implement a favorites feature at the same time while keeping the randomization each time the Global is called.

A: As I believe you are storing your favorites state in your questionStruct class, you don't need to restore your favorites state in your onResume(), you can keep it in onCreate().
As @bonnyz has answered, you can use Collections.shuffle(myQuiz); to shuffle your items in onResume() and refresh your Adapter with notifyDataSetChanged().

A: I really suggest you to use a more Object-oriented approach to handle your model.
You can create the model class Quiz, that will probably looks like this:
class Quiz{

    private boolean favorite;
    private String question;
    private String answer;

    public Quiz(String question, String answer){
        this.question = question;
        this.answer = answer;
    }

    public boolean isFavorite() {
        return favorite;
    }

    public void setFavorite(boolean favorite) {
        this.favorite = favorite;
    }

    //...
}

In this way, you can create a list of Quiz and do shuffle, ordering, check for favorite and so on:
    //Create the list of questions
    ArrayList<Quiz> myQuiz = new ArrayList<Quiz>();
    myQuiz.add(new Quiz("Question?", "Ansewer!"));
    //...

    //Shuffle all!
    Collections.shuffle(myQuiz);

    //Iterate and check for favorites
    for(Quiz q : myQuiz){
       if(q.isFavorite()){
          //this is favorite!
       }
    }

Regarding the persistence of the data, you can consider an SQLite approach, or simply serialize your list and save it in your SharedPreference.


text:
Q: jQuery, Dialog, Tabs and DataTables: how to wait for one to finish before going ahead? I have a tricky problem, that can be solved with chained callbacks, but that results in quite complex code.
I have some nested components: a jQueryUI Dialog. Inside it, I have jQueryUI Tabs. And in each tab, I have a DataTables component, calling AJAX data.
My problem is that when I load all the HTML inside the Dialog, everything fires up in parallel: tabs tries to create itself, while each DataTable gathers it's data, all at the same time!
The result is a complete mess: the Tabs don't hold the correct elements, since each DataTable creates new nodes on the DOM, after Tabs initialization. The Dialog assumes the wrong dimensions, because the DOM was small when it initialized, but grew up when each DataTable displayed the data.
To make things work, I would need to:
1) Wait for each DataTable to initialize.
2) When they're all done, initialize the Tabs.
3) When Tabs are ready, finally open the Dialog.

Is there an easy way to do that?? I'm currently using lots of callbacks, and all the content is dynamic, database driven, so I have to do lots of generalization, almost nothing can be hardcoded. The thing works already, but it's ugly!
This is one of the situations where I would turn off JavaScript async behavior and make it all sync and sequential, if I could.
Maybe jQuery queue, promise or something like that can help me? Any help will be greatly appreciated!

A: I have found a suitable solution, so I will publish it here to help anyone else facing a similar problem.
First, I have found that DataTables has an event fired on creation. It's the "init" event:
$("#TableID").on("init", function() { whatever(); } );

Second, my other problem is the indeterminate number of DataTables I had to wait, before initializing the Tabs. So I created a small function, called RenderManager, to keep track of all my DataTables. When the last one finishes, a callback is called. I made this function very general, so it can be used on any situation where you have to wait for several parallel processing to finish before moving on:
function RenderManager(action, id, callback)
{
  if(typeof RenderManager.groups == 'undefined' ) RenderManager.groups = {};

  switch(action)
  {
    case "init":
      RenderManager.groups[id] = { _callback:callback, _counter:0 };
    break;
    case "add":
      if(typeof RenderManager.groups[id] == 'undefined' )
        console.log('Group "'+id+'" referenced before init.');
      else
        RenderManager.groups[id]._counter++;
    break;
    case "remove":
      if(typeof RenderManager.groups[id] == 'undefined' )
        console.log('Group "'+id+'" referenced before init.');
      else
      {
        RenderManager.groups[id]._counter--;
        if(RenderManager.groups[id]._counter == 0)
          RenderManager.groups[id]._callback();
      }
    break;
  }
}

Usage is simple: first, call it using init, to inform the group name and desired callback:
RenderManager('init', 'MyGroup', function() { CreateTabs(); });

For each DataTable created (or parallel proccess started), add it to the group:
RenderManager('add', 'MyGroup');

And then bind a remove to each DataTable's init event (or to the finish of any parallel proccess), using:
$("#TableID").on("init", function() { RenderManager('remove', 'MyGroup'); } );

That's it! When the last DataTable finishes it's job, CreateTabs(); will be called, no matter the order of execution, no matter which DataTable finished first.
As you can see, this function is just a counter: when the "stack" goes back to zero, the callback fires. It can be improved, with registration of the IDs of each element, but this is overkill for the problem I'm currently solving.


text:
Q: Javascript - how to set child drop down menu based on parent dropdown menu selection For example take a look at http://katz.cd/submit.php. Notice when you select a type, that type is carried through to all the other type dropdown menus.
How do I do this?

A: Here's how they did it, taken straight from their HTML source:
function doal(){
    var se = document.getElementsByName("type[]");

    for (var i = 0; i < se.length; i++){
        se[i].value = document.getElementById("seX").value;
    }
}

Each drop down has the same name in their case, which is "type[]". "seX" is their main drop down. getElementsByName() puts the found elements into the array which they've named "se". This is all an onChange event. So say you had a main dropdown called "main" and others that "main" changed, let's call them "others". Your function could look like this:
function changeAll(){
    var toChange = document.getElementsByName("others");

    for (var i = 0; i < toChange.length; i++){
        toChange[i].value = document.getElementById("main").value;
    }
}

EDIT: Also, in case you don't know onChange events, it would look something like this:
<select id="main" onChange="changeAll()">
  <option>Example</option>
</select>

<select id="others">
  <option>Example</option>
</select>


text:
Q: Two different opinions on whether a topological vector space is a uniform space Van de Vel's Theory on Convexity Structures says a TVS is uniform iff it is locally convex:

3.10.1. Proposition. Let $X$ be a topological vector space, equipped with the
  standard convexity and with the canonical translation-invariant uniformity. Then $X$ is uniform iff it is locally convex. If, in addition, $X$ is (topologically) metrizable, then it is metrizable as a convex structure.

Wikipedia says a TVS is uniform:

a topological vector space (also called a linear topological space) is one of the basic structures investigated in functional analysis. As the name suggests the space blends a topological structure (a uniform structure to be precise) with the algebraic concept of a vector space.

So I guess I mess things up again. What am I missing?
Thanks and regards!


text:
Q: Azure B2C - OIDC redirects to Reset Password Flow instead of signing a user in We have an application that utilizes AzureB2C.  The application also has links to partner websites that signs in a user via OIDC.  We have the following scenario:

*

*User goes to the website and the website redirects to AzureB2C Sign in page.

*The user chooses to Reset his password and goes through the reset password flow.  After the user resets his password, he is automatically signed in to our application

*The user then clicks a link that should allow him to SSO in via OIDC

*Instead of being automatically signed in, the Azure B2C "Reset Password" page is displayed to the user.

As a workaround, the user has to logout and log back in again to be automatically SSO'd in to the partner site.
How do we fix this so that OIDC does not send the user to the Reset Password page?

A: There was a bug in the setup for the "recommended" password reset flow.
https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-password-reset-policy?pivots=b2c-custom-policy#self-service-password-reset-recommended
In the ForgotPassword technical profile, set UseTechnicalProfileForSessionManagement to SM-Noop.


text:
Q: Is there a way to change column Default value to blank for SharePoint Online I have a situation where the value of the field is removed the column default value doesn't get changed to blank. I have tried directly removing the default value from the column but I get the error "Please enter a valid default value. It must not be blank". Any idea on how to remove the value once it is set.

A: Maybe it's how you're trying to do it?  When you're in the list, try going to the gear, list settings, click on the column name to edit, delete the default value, and hit OK.  That worked without issue for me, anyhow.  #fingerscrossed!

A: Please perform the following troubleshooting:
1.Please delete the Default value. Click on the column name >> Column settings >> Edit.

2.Please make sure disable "Require that this column contains information" option.

3.Please refresh page and clear browser cache.

A: I had the same issue. It's the "Do not specify a default value for this location" button that is missing.
If you open the URL in Edge or Internet Explorer it will appear. Seems to be a bug affecting Chrome users.


text:
Q: Get attributes from touching lines in network - results seems random This question is similar to this one: Get attribute from touching line layer (QGIS) but there is a new and more komplex problem in that context I need to solve:
I have to plan drains, usually along a road network or any existing network digitized with snapping and tracing.  In in that drains will be cables. The cables will also be digitized with tracing and end in every drain junction. No cables cross a junction. There could be up to 10 cables inside one drain. The drains are identified by ID's.
Every cable need a (virtual)field with the ID of the drain in which it lies. With the refFunctions solution:
(geomintersects('drain','drainid')

from the question linked above, I will get the drain ID for every cable, BUT the cables are also touching other drains at their end/start nodes if there is a junction. The results will become something like random! If the drains are not touching at their junctions (digitizing a small gab), the expression will work fine. But that is not a well suiting solution for me.
You can reproduce the situation with the following package:

A: In theory, if the refFunctions plugin defines the spatial relation predicates as per the OGC standard, contains or overlaps should work, if your geometries are as precise as you describe. In your example data-set however, the cables extent out of the drains so that where contains fails, within succeeds. And in the reality of floating point numbers, both contains and within are tricky with entities like lines, but overlaps, or crosses even, might catch them.
So just check them all:
COALESCE( geomwithin( 'drains', 'ID' ),  geomcontains( 'drains', 'ID' ),  geomoverlaps( 'drains', 'ID' ),  geomcrosses( 'drains', 'ID' ))

A: If you convert your pipes from lines to polygons as Cyril suggested, the solution becomes simple. Now it doesn't matter that a cable intersects multiple pipe polygons, because it's only within the one corresponding pipe polygon. Use geomwithin() instead of geomintersects() in the expression you already wrote.


text:
Q: ¿Por qué tengo este error en la base de datos en xampp? Tengo un error en la base de datos, esto es lo que me dice:

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'gradbook.gbook_semaphore' doesn't exist: SELECT expire, value
  FROM {semaphore} WHERE name = :name; Array ( [:name] => variable_init
  ) in lock_may_be_available() (line 167 of
  C:\xampp\htdocs\librodelgraduado\includes\lock.inc).

pero cuando le paso la basa de datos, empieza a leerla, se para, sigue leyendo y después da error. Estoy usando Drupal 7 y MySQL.


text:
Q: Kafka KO (Broker may not be available) : number of connection attempts In my application I have to handle the case where Kafka is not available. In this case (which I voluntarily provide by stopping the Kafka server), my client makes repeated attempts to connect for 6 minutes. How can I change these 6 minutes of attempts? Is there a property to change the 6 minute wait?
Thank you

A: thanks for the replies.
So, with Kafka down, the call that is on hold for 6 minutes is this (I use it to then ask for Kafka's status):
KafkaStreams kafkaStreams = streamsBuilder.getKafkaStreams (); // 6 minute wait (WARN Broker may not be available)
state = kafkaStreams.state ();

or, I tried alternatively, but nothing changes, this call:
streamsBuilder.isRunning (); // 6 minute wait (WARN Broker may not be available)

Variables I have set:
spring.kafka.streams.auto-startup = false
spring.kafka.producer.acks = all
spring.kafka.producer.retries = 600
spring.kafka.producer.properties.retry.backoff.ms = 100
spring.kafka.producer.properties.linger.ms = 0

I also tried using KafkaAdmin (FastFail) to no avail:
kafkaAdmin.setFatalIfBrokerNotAvailable(true);
/ * speed up fail fast * /
kafkaAdmin.setOperationTimeout(5);
kafkaAdmin.setCloseTimeout(5);

Thank you


text:
Q: How to find total number of question, total correct answer and total incorrect?  Table-Red
"user_question_id": 1
"option_one_correct": true,
"user_option_one_correct": true,
"option_two_correct": true,
"user_option_two_correct": true,
"option_three_correct": true,
"user_option_three_correct": true,
"option_four_correct": true,
"user_option_four_correct": true,
"option_five_correct": true,
"user_option_five_correct": true,
"one_incorrect": 0,
"two_correct": 1,
"two_incorrect": 0,
"three_correct": 1,
"three_incorrect": 0,
"four_correct": 1,
"four_incorrect": 0,
"five_correct": 1,
"five_incorrect": 0,

"user_question_id": 2
"option_one_correct": true,
"user_option_one_correct": true,
"option_two_correct": true,
"user_option_two_correct": true,
"option_three_correct": false,
"user_option_three_correct": true,
"option_four_correct": false,
"user_option_four_correct": true,
"option_five_correct": true,
"user_option_five_correct": true,
"one_correct": 1,
"one_incorrect": 0,
"two_correct": 1,
"two_incorrect": 0,
"three_correct": 0,
"three_incorrect": 1,
"four_correct": 0,
"four_incorrect": 1,
"five_correct": 1,
"five_incorrect": 0,

Expected Result is total result total question,total correct answer,total incorrect answer
How to find total question and total correct and incorrect answer by query. i tried many ways but didn't find any solution

A: Assuming that table has name table1 and field names are case sensitive (because of apostrophes)
select
  count(*)*5 questions, sum("one_correct"+"two_correct"+"three_correct"+"four_correct"+"five_correct") correct_answers,
sum("one_incorrect"+"two_incorrect"+"three_incorrect"+"four_incorrect"+"five_incorrect") incorrect_answers from table1


text:
Q: Resource allocator in Java I have this resource allocator class
public class ResourceAllocator {

ArrayList<Request> queue = new ArrayList<>();
Lock lock = new ReentrantLock();
int maxResources;
int available;

public ResourceAllocator(int max) {
    maxResources = max;
    available = max;
}

public int getMax() {
    return maxResources;
}

public void getResources(Request req) {
    lock.lock();
    try {
        if (req.getRequest() <= available) {
            available = available - req.getRequest();
            req.allocate();
        } else {
            queue.add(req);
        }
    } finally {
        lock.unlock();
    }
}

public void returnResources(int n) {
    lock.lock();
    try {
        available = available + n;
        if (queue.size() > 0) {
            Request req = queue.get(0);
            while (queue.size() > 0 &&
                    req.getRequest() <= available) {
                available = available - req.getRequest();
                req.allocate();
                queue.remove(0);
                if (queue.size() > 0) {
                    req = queue.get(0);
                }
            }
        }
    } finally {
        lock.unlock();
    }
}

public int size(){
    return queue.size();
}
}

which is called from a thread
public class QThread extends Thread {

Semaphore sem = new Semaphore(0);
ResourceAllocator resources;
int number;

public QThread(ResourceAllocator rs, int n) {
    resources = rs;
    number = n;
}

public void run() {
    int items = (int) (Math.random() * resources.getMax()) + 1;
    Request req = new Request(sem, items);
    resources.getResources(req);
    try {
        sem.acquire();
    } catch (InterruptedException ex) {
    }
    System.out.printf("Thread %3d got %3d resources\n", number, items);
    try{
        Thread.sleep(2000);
    }catch(InterruptedException ex){

    }
    resources.returnResources(items);
    System.out.printf("Thread %3d returned %3d resources\n", number,items);
}
}

And all is fine apart from the fact that resources are allocated FIFO.
Any ideas how could I change this to allow clients with small requests to proceed before clients with large requests, bounded overtaking?

A: how about using a PriorityQueue where the priority is the inverse of the size of the request?

A: You can use PriorityQueue which suits best to your needs, then you can implement custom Comparator (if you think in future you may need a different implementation for sorting) or else Comparablewhich will sort your Request so that jobs in terms of size are submitted, executed first.

A: If you know the size of the job ahead of time, use a PriorityQueue instead of an ArrayList to hold the jobs and implement Comparable
son your Request object such that small jobs are sorted before large ones.


text:
Q: A book about brothers with magical powers, set in southern United States This is about a book series I read in the 80's or 90's. The books were about brothers in either Georgia or North Carolina. There was some sort of metal-sculpting theme thrown in. One brother was somehow twice as powerful because his uncle was his dad. He had a crutch that he affixed miniature figures to. The family was well off but the brother with the crutch was not raised as part of the family until his mid to late teens.
I've put this on a fantasy site because there was magic involved. It was modern, set in the south either Georgia or North Carolina. For their magic/powers to work they had to be completely "whole" when they were supposed to come into their magic. I believe the brother that didn't know he was related was a swimmer and injured himself. As it turned out he hurt himself just after the change.

A: Pretty sure this from Tom Deitz's Soulsmith Trilogy, consisting of Soulsmith, Dreambuilder and Wordwright. Ron Dillon, in a fall from high diving platform, is rendered lame and he loses his adoptive parents the same day. Sent to live in the Georgia backwoods with his aunt and a cousin. His real family, the Welches, are well off. He casts the miniature figures in shop class and adorns his crutch with them. And if I remember right his cousin is really his brother. The magic in his family does require you to be "whole" for you to be awakened in it. For this reason, the females in the family are disqualified by having their hymen broken before maturity. Ron, as it turns out, manages to have his power awaken prior to his leg injury, although it initially stunts his development. Also, those who have been awakened can only be killed by a particular method discovered at birth.

 The crutch and its figurines play a part in the climax, as it turns out that his uncle's weakness consists of a 3 inch silver sword, driven into his skull with a blow from the crutch.

In the later books, there's a tinker who gives him advice about smithing. There's also a divination system that involves what songs come on the radio and he builds a Brazen Head from which to get advice.

A: There are some similarities with books from The Tales of Alvin Maker series, written by Orson Scott Card:

*

*the protagonist is a young blacksmith's apprentice,

*it is set in alternative version of Colonial United States,

*in this series many people have a limited magical ability called "knack".


text:
Q: Remove NA and only fill cells containing numbers in tableGrob I have a table (top.table) I would like to display in a ggplot, but am having issues reformatting the table. I need to format it such that all NA elements are blank, and only fill with specified colors if there is a number contained within the element. Basically, fill the colors like in the code below except the NA elements should be filled default (white), and the NA text should be removed. If the removing of the NA is not possible in the way I described, changing the text color/fill would also work for me (i.e. change text color/fill of numbers, but not NA).
top.table <- structure(c(7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 57.5, 45.5,
NA, NA, NA, 128.5, 78.5, 71.5, 49, NA, NA, NA, 1043, NA, NA,
710, 838, 1481, 737, NA, NA, 1096, 5923, 3697, NA, 1726, NA,
NA, 3545, NA, NA, 1733, 2333, NA, 3807, 1795, NA, 2761, NA, 2887,
NA, NA, 2211, 2544), .Dim = c(11L, 5L), .Dimnames = list(NULL,
    c("Sample Number", "Static", "D10 FB", "D12 FB", "D14 FB"
    )))

colors <- structure(list(newcolor = c("dodgerblue2", "#E31A1C", "#FDBF6F",
"palegreen2", "skyblue2", "green4", "#6A3D9A", "#FF7F00", "gold1",
"#CAB2D6", "#FB9A99")), row.names = c(NA, -11L), class = c("tbl_df",
"tbl", "data.frame"))

tt1 <- ttheme_minimal(
  core = list(bg_params = list(fill = colors, col = NA))
)

g <- tableGrob(top.table, theme = tt1)
grid.draw(g)

A: This may seem like a very obvious solution, but why not just replace the NA with empty strings when you plot the table?
g <- tableGrob(replace(top.table, is.na(top.table), ""), theme = tt1)

grid.newpage()
grid.draw(g)

A: With help from @AllanCameron, the solution I came up with was to use repeat the colors to the number of columns in top.table and use replace() to convert all NA elements to "white" before calling tableGrob()
#make repeated columns of colors
table.colors <- matrix(rep(colors, each = ncol(top.table)),
                       ncol = ncol(top.table), byrow = TRUE)

#index matrix to fine NAs
table.ind <- is.na(top.table)

#make replacements
table.colors <- replace(table.colors, table.ind, "white")

tt1 <- ttheme_minimal(
  core = list(bg_params = list(fill = table.colors))
)

g <- tableGrob(replace(top.table, is.na(top.table), ""), theme = tt1)

grid.draw(g)


text:
Q: Sending data from one activity to another causes app to crash in Android Studio I am very new to Android Studio and am having some issues sending data received from the device via Bluetooth to a new activity.
I do have a foreground service class but am not sure if from there is where I send that data or not. In the function below I am receiving the data and creating an intent to send it to the other activity.
Basically, I am receiving the data sent continuously for now and it needs to be redirected to another activity.
@Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        super.onCharacteristicChanged(gatt, characteristic);
        //deviceList.setText("Data");
        byte[] value = characteristic.getValue();
        StringBuilder output = new StringBuilder();
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Log.i("BLE", "receive value ----------------------------");
                output.append("BLE receive value ----------------------------\n");
                ((TextView)findViewById(R.id.data)).append(output);
                }
        });
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < value.length; i++) {
                    Log.w("BLE", "character_value = " + value[i]);
                    Intent intent2 = new Intent(MainActivity4.this, MainActivity5.class);
                    intent2.putExtra("inputExtra", value[i]);
                    startActivity(intent2);
                }
            }
        });
    }

When the process reaches the part where the data is to be sent to new activity the app crashes. Any advice and help would be greatly appreciated. Thanks!
Here is the Logcat I get when the app crashes
2021-03-29 21:20:50.554 16879-16879/com.example.Pillwoah W/BLE: character_value = 0
2021-03-29 21:20:50.594 16879-16879/com.example.Pillwoah W/BLE: character_value = 0
2021-03-29 21:20:50.630 16879-16879/com.example.Pillwoah W/BLE: character_value = -128
2021-03-29 21:20:50.669 16879-16879/com.example.Pillwoah W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@d16ea24
2021-03-29 21:20:50.698 16879-16879/com.example.Pillwoah D/AndroidRuntime: Shutting down VM
2021-03-29 21:20:50.703 16879-16879/com.example.Pillwoah E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.Pillwoah, PID: 16879
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.Pillwoah/com.example.Pillwoah.MainActivity5}: java.lang.NullPointerException: Attempt to invoke virtual method 'byte[] android.content.Intent.getByteArrayExtra(java.lang.String)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3195)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3410)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2017)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7397)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'byte[] android.content.Intent.getByteArrayExtra(java.lang.String)' on a null object reference
    at com.example.Pillwoah.MainActivity5.<init>(MainActivity5.java:119)
    at java.lang.Class.newInstance(Native Method)
    at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
    at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1250)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3183)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3410)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2017)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7397)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)


text:
Q: R summarize_if more complex functions to multiple columns Hi I am looking for an elegant solution ideally combination dplyr&purr.
I will group data by id and then I have 4 numeric columns and I want to apply to all of these
columns sum function. Additionally I want to apply to this 4 numeric columns conditional sum based on diff column.
So let' say to be specific I want from summarize sum of all 4 columns, sum of all 4 columns where diff<11, sum of all columns where diff<21
I started with this but got stucked
df%>%group_by(id)%>%summarise_if(is.numeric,.funs = (sum,~sum(.[diff<11]))

    df<-structure(list(id = c(10274565, 10274449, 10274449, 10274449,
10274565, 10274557, 10274557, 10274449, 10274565, 10274565, 10274565,
10274557, 10274565, 10274557, 10274557, 10274557, 10274557, 10274557,
10274557, 10274449, 10274449), d_amt = c(70L, 52L, 47L, 31L,
100L, 17L, 74L, 54L, 83L, 90L, 76L, 98L, 73L, 49L, 81L, 82L,
80L, 24L, 30L, 21L, 43L), d_cnt = c(3L, 4L, 3L, 3L, 5L, 3L, 1L,
3L, 1L, 3L, 3L, 3L, 5L, 1L, 4L, 1L, 1L, 5L, 4L, 4L, 5L), w_amt = c(74L,
16L, 20L, 73L, 22L, 11L, 61L, 90L, 78L, 94L, 64L, 58L, 84L, 15L,
42L, 31L, 53L, 92L, 76L, 14L, 65L), w_cnt = c(4L, 5L, 1L, 1L,
5L, 2L, 4L, 3L, 3L, 2L, 5L, 1L, 4L, 1L, 4L, 4L, 1L, 1L, 4L, 3L,
1L), diff = structure(c(43, 30, 20, 16, 22, 57, 50, 40, 64, 51,
50, 8, 88, 85, 79, 43, 28, 22, 17, 13, 3), class = "difftime", units = "days")), row.names = c(NA,
-21L), class = c("tbl_df", "tbl", "data.frame"))

A: You could try:
library(dplyr)

df %>%
  group_by(id) %>%
  summarise(
    across(
      where(is.integer),
      list(below11 = ~ sum(.[diff < 11]),
           below21 = ~ sum(.[diff < 21]))
    )
  )

Output:
# A tibble: 3 x 9
        id d_amt_below11 d_amt_below21 d_cnt_below11 d_cnt_below21 w_amt_below11 w_amt_below21 w_cnt_below11 w_cnt_below21
     <dbl>         <int>         <int>         <int>         <int>         <int>         <int>         <int>         <int>
1 10274449            43           142             5            15            65           172             1             6
2 10274557            98           128             3             7            58           134             1             5
3 10274565             0             0             0             0             0             0             0             0

Note that the columns in your example appear to be integer, therefore the is.integer part.

A: You can use :
library(dplyr)
df %>%
  group_by(id) %>%
  summarise(across(where(is.numeric), ~sum(.[diff < 11])))

#        id d_amt d_cnt w_amt w_cnt
#     <dbl> <int> <int> <int> <int>
#1 10274449    43     5    65     1
#2 10274557    98     3    58     1
#3 10274565     0     0     0     0

Or if you are using older version of dplyr :
df %>%
  group_by(id) %>%
  summarise_if(is.numeric, ~sum(.[diff < 11]))

A: You could group by the diff column and then summarise over groups:
library(dplyr)
df %>%
  mutate(dif_cat = case_when(diff < 11 ~ "<11",
                             diff < 22 ~ "<22",
                             TRUE ~ ">=22")) %>%
  group_by(id, dif_cat) %>%
  summarise(across(where(is.numeric), ~sum(.)))

# A tibble: 7 x 6
# Groups:   id [3]
        id dif_cat d_amt d_cnt w_amt w_cnt
     <dbl> <chr>   <int> <int> <int> <int>
1 10274449 <11        43     5    65     1
2 10274449 <22        99    10   107     5
3 10274449 >=22      106     7   106     8
4 10274557 <11        98     3    58     1
5 10274557 <22        30     4    76     4
6 10274557 >=22      407    16   305    17
7 10274565 >=22      492    20   416    23


text:
Q: Client side validation with Jquery - MVC C# app I am working on a very LEGACY ASP.NET MVC app using C# which is built from 2009. They don't have any client side validation at all. In other words, they don't use validation mechanism provided by the ASP.NET MVC framework as the following link
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-5.0#client-side-validation
They use service, interface etc... to do validation. Not using data annotations, either. As a result, they don't have unit tests for model validator. All validation rules will be tested manually through server side only or the unit tests have strong dependency to Resource.resx or other services which I don't think they are unit tests.
Therefore, I have added a client side validation and server-side validation by using data anotations.
Unfortunately, my PR is declined because they said that they don't want to use or add jQuery to the current application.
The reason is that: "they want to build portable micro-frontends pointing at APIs rather than all encompassing large applications the current app. because of that jQuery Validate is at the complete opposite end of the scale from zero compromise. It can be done by HTML5 and plenty of other client side only JS libraries there are plenty of better compromises. The other end of the scale (our ideal) is the validation happens in an encapsulated web component that uses Angular Forms." (An answer from a Front end developer)
The problem is that we have not the plan to replace that legacy app yet and I don't see the reason why I cannot use Validation mechanism from Microsoft to do both client side and server side validation. My thought is that it is better to do validation in correct way, rather than let it be bad and will be replaced by web-component soon.
Based on the source code, I am not sure they are able to apply proper validation way in new technology because with the ASP.NET MVC app, I think they did not apply correctly or I don't think they understand the framework.
Any ideas why I should not use jQuery for MS's validation on a legacy app?
Thanks