text:
Q: Retrieve users from specific group and OU in Active Dirctory I want to retrieve all users in a given group from specific OU in Active Directory. My code throws an exception

The operation was aborted because the client side timeout limit was exceeded

I get this exception at
foreach (SearchResultEntry entry in searchResponse.Entries)

My group name is Arya and OU name is TestOU
However when I write my filter as
string searchFilter = "(&(objectCategory=user)"

it works and returns users from all OU's, I think which I do not want.
bool bMoreData = false;

DirectoryEntry rootDSE = new DirectoryEntry("LDAP://" + domain);
string[] attributes = { "samaccountname", "displayname", "name", "initials" };

System.Net.NetworkCredential credential = new System.Net.NetworkCredential(admin, password, "IP address");

LdapDirectoryIdentifier directoryIdentifier = new LdapDirectoryIdentifier("ip address"); //389 (unsecured LDAP)
LdapConnection connection = new LdapConnection(directoryIdentifier, credential);
connection.Bind();

string searchFilter = "(&(objectCategory=user)(memberOf=cn=Arya,ou=TestOU,dc=Maintenance,dc=org))";
SearchRequest request = new SearchRequest("DC=Maintenance,DC=org", searchFilter, System.DirectoryServices.Protocols.SearchScope.Base, attributes);
// getCookie();

DirSyncRequestControl dirSyncRC = new DirSyncRequestControl(cookie, System.DirectoryServices.Protocols.DirectorySynchronizationOptions.IncrementalValues, Int32.MaxValue);
request.Controls.Add(dirSyncRC);

SearchResponse searchResponse = (SearchResponse)connection.SendRequest(request);

foreach (SearchResultEntry entry in searchResponse.Entries)// Exception thrown here
{
    Console.WriteLine("{0}:{1}",
    searchResponse.Entries.IndexOf(entry),
    entry.DistinguishedName);
}

foreach (DirectoryControl control in searchResponse.Controls)
{
    if (control is DirSyncResponseControl)
    {
        DirSyncResponseControl dsrc = control as DirSyncResponseControl;
        cookie = dsrc.Cookie;
        bMoreData = dsrc.MoreData;
        break;
    }
}

A: I found problem with the below line
DirSyncRequestControl dirSyncRC = new DirSyncRequestControl(cookie, System.DirectoryServices.Protocols.DirectorySynchronizationOptions.IncrementalValues, Int32.MaxValue);

when replaced it with it worked for me.
DirSyncRequestControl dirSyncRC = new DirSyncRequestControl(cookie, System.DirectoryServices.Protocols.DirectorySynchronizationOptions.ObjectSecurity, Int32.MaxValue);

A: You can bind to a PrincipalContext for your OU, and then find that group you're looking for:
// create your domain context - bind to the OU you're interested in
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null, "OU=TestOU"))
{
   // define a "query-by-example" principal - here, we search for any GroupPrincipal
   GroupPrincipal group = ctx.FindByIdentity("Arya");

   // if group is found - enumerate its members
   if(group != null)
   {
       foreach(var found in group.GetMembers())
       {
            //
       }
   }
}

If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 (downloadable .CHM file from Microsoft - January 2008 issue of MSDN Magazine) which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement. Or see the MSDN documentation on the System.DirectoryServices.AccountManagement namespace.


text:
Q: Use Android debug keystore after installing distribution version? I'm developing an Android-app. Debugging works fine, but after installing the distributed version of the app from the Play Store, I can't run it anymore while developing, because it says the signing certificates are different.
I'm guessing this has something to do with the keystores.
Is there any way to use both the distribution and debug keystores at the same time, or should I deinstall the app each time before debugging ?

A:
Is there any way to use both the distribution and debug keystores at
  the same time, or should I deinstall the app each time before
  debugging ?

No. It's not possible. Because when you debugging from IDE it's used default debug.keystore but your device contains built with your own private keystore.
Solution:
You can set your OWN keystore as a Default in Android Studio.
OR
You should uninstall your previous version and install the new one.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to access Clipping Rectangle postion of UIScrollView in NGUI I am using NGUI v3.5.4r2 version. I am try to access Clipping Rectangle position in UIScrollView. I can get height and width of Clipping Rectangle but unable to access position of Clipping Rectangle of UIScrollView.
Your help will be appreciated.
Thanks You.

A: You can use the localCorners variable of UIRect (of which UIPanel inherits) to get the Vector3 point of any of the corners.
UIPanel mPanel;
Vector3 bottom_Left = mPanel.localCorners[0];
Vector3 top_Left = mPanel.localCorners[1];
Vector3 top_Right = mPanel.localCorners[2];
Vector3 bottom_Right = mPanel.localCorners[3];


text:
Q: Need to Remove Web Analytics Completely We have an issue on our SharePoint 2010 Enterprise site where the WebAnalyticsStaging database has become corrupt and I need to completely remove Web Analytics from the site and then reconfigure it so that it creates new databases and starts fresh. I can find all kinds of articles on how to configure it for use but I have not been able to find anything that tells me how to remove/delete it. Are there any good blogs/articles out there? Does anyone have any advice on this?
Thanks,
Doug

A: From central admin > manage Service Application > Select the Web Analytic and then ribbon select delete it.
after that make sure no related database exist on SQL Server.
http://sp-vinod.blogspot.com/2012/11/cannot-delete-orphaned-web-analytics.html


text:
Q: jQuery - get td cell index of a control ** EDIT** I'm very sorry. I need the td index, not the row index.
Using jQuery, how do I get the index of the td lblName is in?

A: Update for updated question:
$('#lblName').parent().index();

or
document.getElementById('lblName').parentNode.cellIndex

Original answer:
Use .index().
$('#lblName').closest('tr').index();

The .index() method has a few different use patterns.
This one means "take the first element matched by the selector, and return its zero based index of its position among its siblings".

Or natively, do this...
document.getElementById('lblName').parentNode.parentNode.rowIndex

Or combine the two...
$('#lblName').closest('tr')[0].rowIndex;

A: var index = $('#lblName').closest('tr').index();

A: $("table tr").index($("#lblName").parents("tr:first"))

A: Hope, this piece of code would be of any help.
You can use the index() with parentsUntill() to the parent TR element of that TD.
example http://jsfiddle.net/ylokesh/bGvHZ/
$('#lblName').parentsUntil('tr').index()


text:
Q: CMake, add_subdirectory и наследование окружения Делаю проект с компиляцией под несколько платформ на c++. Некоторые файлы нужно прогнать утилитой (для простоты понимания скажем, что это транспилятор). Этот транспилятор нужно собрать из исходников, для него уже настроен CMakeLists.txt.
Подключаю его так:
add_subdirectory(my/transpilator)

Ну и добавляю таргет:
add_custom_target(transpile ALL COMMAND ${CMAKE_COMMAND} -D...
            -DTRANSPILER_EXECUTABLE=$<TARGET_FILE:my_transpiler> -P transpile_all.cmake)

Подключаю его как зависимость к главному таргету и при сборке transpile_all.cmake транспилирует нужные файлы.
Проблема же возникает на платформах вроде Android или IOS. Так как для них нужно настраивать специфическое окружение, флаги компилятора, архитектуру и прочее, очевидно, что при подключении проекта транспилятора через add_subdirectory он унаследует все эти настройки. Окружение же настраивается тулчейном и добавить add_subdirectory перед настройкой окружения я не могу.
На данный момент думаю использовать "костыльное" решение - запускать cmake для транспилятора во время конфигурации и компилировать его. Что-то вроде:
execute_process(COMMAND ${CMAKE_COMMAND} -Htranspiler/folder -Btranspiler/output)
execute_process(COMMAND ${CMAKE_COMMAND} --build transpiler/folder ...)

Потом там экспортировать какую-нибудь переменную окружения и читать из нее путь до бинарника, чтобы передать в transpile_all.cmake.
В правильном ли я направлении думаю, или же есть какой-то способ, скажем, сделать add_subdirectory, но без наследования настроек окружения, или что-то подобное?


text:
Q: Application opens twice when file specified Typing open -a emacs opens one window.  Fine.
Typing open -a emacs foo.txt opens two windows, one as above, and one with foo.txt in it.
Why is that and what should I do to fix it?

A: You have to enclose the document you're trying to open in quotes
open -a emacs "/foo/bar/foobar.txt"


text:
Q: Issue faced when trying to add zooming(react-three-fiber) I have this sample https://codesandbox.io/s/r3f-sky-dome-forked-614gw?file=/src/index.js. But zooming not working even if I use enableZoom thus I really need your kind help on how I can fix it.
Please HELP

A: Zoom actually does work. The problem is that the control's target is (0, 0, 0) and the position of your camera is already (0, 0, 0.1). So there is not much room for zoom in anymore.


text:
Q: uninitialized constant Mongoid::Paperclip paperclip gem
my gem file looks like
gem "mongoid-paperclip", :require => "mongoid_paperclip"

and model
class User
    include Mongoid::Document
    include Mongoid::Paperclip
    has_mongoid_attached_file :image
end

i am getting error like
 uninitialized constant Mongoid::Paperclip

i am using rails 3.2.11
Anybody knows what causing this problem

A: Putting this in the Gemfile solved it for me:
gem "mongoid-paperclip", :require => "mongoid_paperclip"

A: I have added below line in my Gemfile and run bundle install
gem "mongoid-paperclip", :require => "mongoid_paperclip"
And add this in your model has_mongoid_attached_file :image
In addition to this, if you want to save different versions for the uploaded image then probably you will need to do the below steps

*

*Add rmagick to your Gemfile gem 'rmagick'

*In your model
has_mongoid_attached_file :image, :styles => { :thumb => '100x100', :big_thumb => '120x120', :medium => '247x173'}

This works for me.


text:
Q: Pivot_longer (dplyr) in R without row names I have a problem in my analysis and i am stuck.I have a resulted tibble that is :
> corr
# A tibble: 1 x 138
  A       B     C     D     E     F     G     H      I      J
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>  <dbl>
1 0.625 0.393 0.771 0.405 0.636 0.249 0.372 0.154 -0.112  0.293
# ... with 128 more variables:

I want to pivot longer it but i don't have any row specific name if order to start it.
I am using :
corr%>%pivot_longer( names_to = "income", values_to = "count")

but R reports me an error :
Error in `build_longer_spec()`:
! `cols` must select at least one column.

I tried to transpose it and works fine but i cannot extract the names any further.
I think that pivot_longer will transpose it and keep the names of the tibble structure but i don;t know how to do it . Any help ?

A: In cols , you can select everything() -
df <- data.frame(A = 5, B = 4, C = 8, D = 10)

tidyr::pivot_longer(df, cols = tidyselect::everything(),
                    names_to = "income", values_to = "count")

#  income count
#  <chr>  <dbl>
#1 A          5
#2 B          4
#3 C          8
#4 D         10


text:
Q: Yii2: Registering javascript when loading (nested) Gridview through renderAjax I am using Yii2 and struggling to load a GridView (kartik\grid\GridView)  from within a an ExpandRowColumn (kartik\grid\ExpandRowColumn) in a master Gridview using the detailUrl option.
Everything works fine when using the detail option, which loads all subgrids on page-load which destroys page load times. Using the detailUrl option, the subgrid loads properly, however pagination and sorting on the subgrids malfunction, as seemingly the javascript which is registered on with a Gridview on a normal page-load, does not seem initialised.
My code:
ExpandableRowColumn
$this->columns[] = [

                'class' => 'kartik\grid\ExpandRowColumn',
                'expandOneOnly' => true,
                'width' => '50px',
                'visible' => true,
                'order' => DynaGrid::ORDER_FIX_LEFT,
                'value' => function ($model, $key, $index, $column) {
                    return GridView::ROW_COLLAPSED;
                },
                'detailUrl' => Yii::$app->urlManager->createUrl(['/' . Yii::$app->controller->id . '/sector-details', 'filter' => $this->getSubgridFilter()]),

                /*
                  //Proper functioning code using detail option
                  'detail' => function ($model, $key, $index, $column) {
                  $searchModel = new \app\models\search\Subject;
                  $searchModel->bySector = $key;
                  $dataProvider = $searchModel->search($this->getSubGridFilter());
                  return Yii::$app->controller->renderPartial('/linkage/_subgrid', [
                  'searchModel' => $searchModel,
                  'dataProvider' => $dataProvider,
                  'gridId' => $key,
                  ]);
                  },
                 *
                 */
            ];

Controller Action
public function actionSectorDetails(array $filter = [])
{
    if (isset($_POST['expandRowKey'])) {
        $sectorId = $_POST['expandRowKey'];
        $searchModel = $this->_initSearch();
        $searchModel->bySector = $sectorId;
        $dataProvider = $searchModel->search($filter);
        return $this->renderAjax('/linkage/_subgrid', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
                    'gridId' => $sectorId,
        ]);
    } else {
        return '
No data found
';
    }
}

Gridview
//ID examples: actor-subgrid-x
$gridId = Yii::$app->controller->id . '-subgrid-' . $gridId;
$glyph = app\helpers\IconHelper::getIcon($caller);

$gridConfig = [
    'simple' => true,
    'id' => $gridId . '-inner',
    'title' => $title,
    'model' => $searchModel,
    'provider' => $dataProvider,
    'pagerOptions' => ['linkOptions' => ['class' => 'item-link']]
];
?>

        <?php
        Pjax::begin(['id' => $gridId, 'enablePushState' => false]);
        DynaGrid::widget([
                    'columns' => $this->columns,
                    'storage' => DynaGrid::TYPE_COOKIE,
                    'theme' => $this->theme,
                    'userSpecific' => false,
                    'showPersonalize' => false,
                    'showFilter' => false,
                    'showSort' => false,
                    'allowThemeSetting' => false,
                    'gridOptions' => $this->gridOptions,
                    'options' => ['id' => $gridId], // a unique identifier is important
        ]);
        Pjax::end()
        ?>

The problem is,whenever I click a pagination or a sorting link, it redirects to the link called by the detailUrl, i.e. sector-details, rather than the main controller action.
The javascript handling the PJAX to catch subgrid pagination and sorting does not seem loaded...
How can I fully load a Gridview using renderAjax?
Please Help!!
How can I get this sorted out


text:
Q: KendoUI: Get the name of the last view I would like to get the id of the last view in KendoUI. I already inspected the event object but found nothing that reveals this.
This could be the view that I came from with a tap or the view that I came from with the back button.

A: What about this:
var id = $('[data-role=view]:last').attr('id');

A: This answer is for Kendo UI Mobile applications, but the basic principal could be used as a basis for a solution for Kendo UI Desktop as well.
I was using e.view.nextViewID in the show event handler of my views to get the previous view but this stopped working with kendo ui version 2014.1.528. So, I've figured out the following work-around that uses the pane.navigate event to store the previous view in a global variable:
var previousView = '';
var app = new kendo.mobile.Application();
app.pane.bind("navigate",
    function(e) {
        previousView = e.sender.view().id;
    }
);

I also found that app.pane can be undefined at first so I have wrapped the above call to app.pane.bind in setTimeout with a delay of 50ms - if there's an official way to know when app.pane is set please share.

A: To improve the answer above slightly, one can attach events to the app's pane object directly at initalization of the application object, so one does not need the timeout because the app's init fires a tad too early.
var previous_view = '';
function store_previous_view(e)
{
    try
    {
        previous_view = e.sender.view().id;
    }
    catch(e){}
}
app = new kendo.mobile.Application({navigate: store_previous_view});

The try-catch is there because the event will fire immediately and view() will return null at the very first time. So one should check the value of previous_view for sanity before using it.
This works in Kendo UI core 2014.3.1119. I don't know if it is a loophole or intended behaviour, it's definitely not documented.


text:
Q: Why do webpages break in MVC if they're missing '/' from the URL? So I have a website that uses cshtml pages
  ie:  index.cshtml
as a View  for my site
However if I browse in my URL to
http://mywebsite.com/index
 it breaks the rendering of the _Layout
but if I go to:
http://mywebsite.com/index/
It's magically working and using the correct _Layout


text:
Q: GitHub: Как сделать Rebase and merge вместо Squash and merge Сделал pull request из своей ветки в main,
чтобы смержить предлагает разрешить конфлиты и сделать Squash and merge,
но в таком случае не будет виден ежедневный прогресс и тонны коммитов - все просто соберется в один.
Думаю, дело в том, что моя ветка кроме
80 commits ahead

еще и
1 commit behind main

Как мне подтянуть то одно изменение и потом запушить с возможностью сделать rebase или обычный merge.
Если я в своей ветке делаю
git pull

то говорит:
main -> origin/main
Already up to date.


text:
Q: OpenCL SDK overview and hardware interoperability I am a little bit confused of the overall situation when it comes to OpenCL development so I'll just state my current understanding and questions as a list. Please correct me if I'm wrong.

*

*I know there are SDKs ("Platforms") by Intel, AMD (and I guess there is also OpenCL support in the Nvidia SDK?)

*Are there SDKs by other vendors?

*Will the SDK of one vendor support the devices of another? e.g. Nvidia devices with AMD sdk? I am able to run programs on my Intel CPU using AMD SDK.

*Is it the way to go to install multiple platforms at once and handle them at runtime?
Thank you!

A: 1) Intel SDK offers OpenCL 1.2 support for CPU and GPU devices (for instance i7, HD4000, Xeon Phi, etc.), AMD SDK offers OpenCL 1.2 support for CPU and GPU devices (for instance Opteron, HD5xxx, HD6xxx, HD7xxx, etc.), NVIDIA SDK offers OpenCL 1.1 support only for GPUs (for instance GTX 2xx, GTX 4xx, GTX 5xx, Tesla, etc.).
2) Yes, from Apple, ARM and more.
3) Yes, thanks to OpenCL ICD, you can compile an executable on NVIDIA SDK and run on a AMD hardware. However you have to be careful with OpenCL versions, some problem can arise from compiling with an OpenCL 1.2 SDK and running on a 1.1. platform.
4) Yes, you can query OpenCL at runtime for the list of available platforms and use one or all of them. I uses everyday Intel OpenCL CPU device side by side with multiple AMD OpenCL GPU devices.

A: This is a duplicate of How to use 2 OpenCL runtimes, which was answered. Short answer: The SDK just gets you the headers. The installed drivers provide the platforms and devices. You can use any that are installed.

A: The Intel OpenCL SDK supports OpenCL 1.2 for the CPU but only OpenCL 1.1 for Intel HD.  Quoting their webpage "OpenCL 1.2 on CPU mixed with OpenCL 1.1 on Intel® HD Graphics".  However, the drivers for Intel HD don't seem to be very good.  It crashes on most of code that runs on everything else.
The Nvidia SDK does not include the C++ bindings file cl.hpp.  You can copy it form another SDK or get it from the Khronos Group OpenCL site.
I had problems running OpenCL on non AMD devices with the AMD SDK so I use the Intel SDK instead and it works on AMD, Intel, and Nvidia.  However, the 1.1 C++ bindings and the 1.2 C++ bindings are not 100% compatible.  If you want your code to work on both Nvidia and AMD GPUS only use OpenCL 1.1 and this define:
    #define CL_USE_DEPRECATED_OPENCL_1_1_APIS


text:
Q: ANOVA - Adding interaction term changes a main effect to being insignificant. How can that be? UPDATE: I don't think the single posted answer is correct. When I run summary(lm(DependentVar ~ IndVar1 * IndVar2, data = Data1)) the first listing is IndVar11 @ p = 0.113, and the four IndVar1:IndVar2 entries are all non significant (p = 0.16 to p = 0.41).
Regarding the suggested duplicate - the accepted answer there is about small p-value differences and small samples sizes, neither of which is the case here.  In that answer, the author says he doesn't see other way this can happen.  So what is happening here?

I'm looking for an explanation as to how an independent variable can go from being highly significant to being highly insignificant when an interaction term is added.  IndVar1, below.
IndVar1 has 2 levels.  IndVar2 has 5 levels.
Thanks
> Model_1 <- aov(DependentVar ~ IndVar1 + IndVar2, data = Data1)
> Anova(Model_1, type="III")
Anova Table (Type III tests)

Response: DependentVar
             Sum Sq   Df    F value    Pr(>F)
(Intercept) 18486.4    1 11622.9984 < 2.2e-16 ***
IndVar1         23.7    1    14.8532 0.0001353 ***
IndVar2    39.7    4     6.3382 5.711e-05 ***
Residuals    2175.1 1341
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

> Model_1 <- aov(DependentVar ~ IndVar1 * IndVar2, data = Data1)
> Anova(Model_1, type="III")
Anova Table (Type III tests)

Response: DependentVar
                    Sum Sq   Df   F value    Pr(>F)
(Intercept)        15473.4    1 9781.1865 < 2.2e-16 ***
IndVar1                 4.3    1    2.7758 0.1131780
IndVar2           36.8    4    5.8247 0.0001231 ***
IndVar1:IndVar2    14.1    4    2.2124 0.0666647 .
Residuals           2149.1 1337
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
>

A: In a model with interactions, the interpretation of the IndVar1 term is not 'the effect' of IndVar1, or even 'the association', since the whole point of the interaction is that the association of IndVar1 with the outcome is different for different value of IndVar2.
So, what is it? Well, for Type III sums of squares, it's the estimated association at the value of IndVar2 coded as zero.  In this case, if you haven't changed any of the defaults, that will be the estimated association between IndVar1 and the outcome at the reference category (first category) of IndVar2. There's very waek evidence for the association being non-zero
This could happen for multiple reasons,  which we can't distinguish because you haven't told us enough

*

*maybe the association is actually weak at that level of IndVar2

*maybe there are very few observations at that level of IndVar2, so you can't tell if the association is  actually weak or strong

*maybe the observations at that level of IndVar2 mostly have the same value of IndVar1, so again you can't tell if the association is  actually weak or strong

As an example of the first type, might think of income by age-group and gender, where you could see a strong effect of age, a strong effect of gender, and an interaction -- but if your lowest age group was 0-10, there wouldn't be much gender difference in that age group because none of them are earning much.


text:
Q: complex column selection in dplyr group_by I would like to use, within a group_by call, dplyr's column selectors like starts_with(), ends_with(), matches(), ..., or even the syntax -colName.
(Silly) example of the syntax I am after:
library("dplyr")

# I would like to do something like this
mtcars %>%
   group_by(matches("a")) %>%
   summarise(mpg=mean(mpg))
# but I get a "wrong result size" error

I was hoping it would work, by analogy with:
mtcars %>% select(matches("a"))

which here would select columns drat, am, gear, carb
To be crystal clear: I want to use matches("a") (or equivalent) to achieve the same output as:
mtcars %>%
group_by(drat, am, gear, carb) %>%
summarise(mpg=mean(mpg))

I am only interested in answers using dplyr. Thanks!

The current answer, while good, only allows selecting columns with a regex.
I am still looking for a more global answer that would allow the use of the full range of dplyr's selection syntax.  Of course I can massage any regex to select what I want, but I wish I had something which integrates nicer with dplyr (especially to use the -colName syntax). I am going to leave this opened for a while.

A: Here is an option to construct your own group_at() which I don't think exists with the matches and SE  group_by_() function:
mtcars %>%
      group_by_(.dots = names(mtcars)[matches("a", vars = names(mtcars))]) %>%
      summarise(mpg = mean(mpg))

#Source: local data frame [26 x 5]
#Groups: drat, am, gear [?]

#    drat    am  gear  carb   mpg
#   <dbl> <dbl> <dbl> <dbl> <dbl>
#1   2.76     0     3     1 18.10
#2   2.76     0     3     2 15.50
#3   2.93     0     3     4 10.40
#4   3.00     0     3     4 10.40
#5   3.07     0     3     3 16.30
#6   3.08     0     3     1 21.40
#7   3.08     0     3     2 19.20
#8   3.15     0     3     2 16.95
#9   3.21     0     3     4 14.30
#10  3.23     0     3     4 14.70
# ... with 16 more rows

Or equivalently, just use grep:
mtcars %>%
      group_by_(.dots = grep('a', names(mtcars), value = TRUE)) %>%
      summarise(mpg=mean(mpg))

A: group_by_at was added to dplyr some time in 2017 and does just that.
mtcars %>%
   group_by_at(matches("a")) %>%
   summarise(mpg=mean(mpg))


text:
Q: Working with raster files of very large size I am generalist web developer with zero GIS experience, and I have a GIS-related question.
I have some raster data that I am trying to expose to users in form of a tile API. The user provides the x/y coordinates and the zoom level, and I return the PNG tile from the raster dataset.
The raster data is very simple: it's (x, y, d) tuples, where x and y are grid coordinates, and d is an integer. I store these data as memory-mapped numpy files, where each file corresponds to a single complete dataset. The datasets are independent from each other, and range in size from 5,000^2 to 150,000^2 "pixels".
My prototype web API server (written in Python) is also pretty straightforward:
The caller of the API can specify the dataset, the x/y/zoom parameters, and an optional filter range for d. When a request for a tile comes in, the Python server loads the dataset (the numpy file) into RAM, crops out the piece it needs for the tile, filters the data, downsamples it, converts it into a PNG, and then sends the PNG to the user.
The dataset, once it is loaded, is retained in RAM until the server shuts down. If the server happens to run out of RAM (because too many datasets are concurrently loaded), it frees up memory by unloading the least-frequently used dataset.
This setup has worked great for smaller datasets (<1Gb) that don't push the limits of my test box which has 128Gb RAM.
However, I am now trying to scale this architecture to handle arbitrarily large raster datasets. The datasets I am working with now are 90Gb each. I am finding that if I try to request tiles from 2 different 90Gb datasets at once, the server spends most of its time loading/unloading the data. Server response times go from tens of milliseconds to seconds. Imagine using google maps and having to wait 10+ seconds for tiles to load.
Which finally brings me to my question: I assume this is a well-understood problem in the GIS space. How do you serve tiles from terabyte-sized raster datasets to multiple users concurrently?
I am trying to get myself familiar with the problem space, so I am looking for suggestions on what to read. What are some good books or courses?


text:
Q: Convert error to map or struct Just started with Go and currently trying to create a REST API. Using gorm & gin to do the same. Where am stuck is, am trying to fetch a value from the error object, but am not able to do that in a straight forward way.
The error type, if I know correctly, just hasa an Error method available, which gives whatever is in the Message part of the object. This is the error object I have.
{
    "Severity": "ERROR",
    "Code": "23505",
    "Message": "duplicate key value violates unique constraint \"uix_users_email\"",
    "Detail": "Key (email)=(johndoe@gmail.com) already exists.",
    "Hint": "",
    "Position": "",
    "InternalPosition": "",
    "InternalQuery": "",
    "Where": "",
    "Schema": "public",
    "Table": "users",
    "Column": "",
    "DataTypeName": "",
    "Constraint": "uix_users_email",
    "File": "nbtinsert.c",
    "Line": "433",
    "Routine": "_bt_check_unique"
}

Now, what I want to do is, access the Detail key, and am a bit confused. This is what I have currently done to be able to achieve this:
if err := a.DB.Create(&user).Error; err != nil {
    val, _ := json.Marshal(err)
    m := make(map[string]string)
    json.Unmarshal(val, &m)
    context.JSON(422, gin.H{"error": m["Detail"]})
    return
}

But this seems like an overkill. I have to Marshal the error, then Unmarshal it into a map & then finally use it.
Is there a simpler way to do this?

A: Assert it to pq.Error and access the fields as explained in the pq docs:
if err, ok := err.(*pq.Error); ok {
    fmt.Println("pq error:", err.Code.Name())
    // Or whatever other field(s) you need
}

The full type is also documented.


text:
Q: R: assign values to a column when two other columns match Here is my sample data:
samp_df <- tibble(id= c("A", "A", "B", "B"),
              event= c(111, 112, 113, 114),
              values = c(23, 12, 45, 60),
              min_value = c(12, 12, 113, 113))

I would like to create a column in the dataframe that has the event of the min value. So in the example the column would look like: c(112, 112, 113, 113). So the idea is that  I want to take the value from event whenever values and min_value match. It is important that this is also grouped by the id variable.
Here is what I tried, but it's not exactly right as it add NA's instead of the event:
samp_df <- samp_df %>% group_by(id) %>%
  mutate(event_with_min = if_else(min_value == value,
                                  event, NA_integer_)

A dplyr solution would also be optimal!

A: library(tibble)
library(dplyr)
library(tidyr)

samp_df <- tibble(id= c("A", "A", "B", "B"),
                  event= c(111, 112, 113, 114),
                  values = c(23, 12, 45, 60))

samp_df %>%
  group_by(id) %>%
  mutate(min_value = min(values),
         event_with_min = if_else(min_value == values, event, NA_real_)) %>%
  fill(event_with_min, .direction = "downup")
#> # A tibble: 4 x 5
#> # Groups:   id [2]
#>   id    event values min_value event_with_min
#>   <chr> <dbl>  <dbl>     <dbl>          <dbl>
#> 1 A       111     23        12            112
#> 2 A       112     12        12            112
#> 3 B       113     45        45            113
#> 4 B       114     60        45            113

Created on 2022-10-14 by the reprex package (v2.0.1)
I've had to sign up as a guest as I am working on a train. Will revert to own user once back at home! Peter


text:
Q: How to add recently open documents to the OpenRecent menu items in WPF I had develop an Wpf application which open an .doc file and doing some operations. Now I want to add open recent feature in menu items which shows the list of recently opened document. Now there is a wpf class called jump list but I do not understand how to use the jump list in my application.

A: You can use the ShowRecentCategory property of the JumpList.
When you start the app create the jump list:
JumpList jumpList = new JumpList();
jumpList.ShowRecentCategory = true;
JumpList.SetJumpList(Application.Current, jumpList);

Then when you want to add a document to the recent list use the AddToRecentCategory method:
JumpList.AddToRecentCategory(/*item path*/);

Important to rememer: "If your application is not registered to handle the file type of the item, it will not appear in the Recent list and calls to AddToRecentCategory(String) will fail silently."


text:
Q: Javascript for loop variable is strange when writing on a file I have this code in './utils/url.js'. it basically makes the application/x-www-form-urlencoded content form:
const ContentForm = ()=>{
    let params = new URLSearchParams()
    const randomString = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
    params.append('email', `${randomString}@gmail.com`)
    return params;
}
module.exports = ContentForm;

The email parameter is a random string.
and index.js:
const axios = require('axios').default;
const fs = require('fs');
const params = require('./utils/url')

for (let i = 0; i < 1000; i++) {
const config = {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }
// sending post with data of web/application the url http://somewhere.com/my-account/
axios.post('http://somewhere.com/my-account/',params(),config, {
})
    .then(function (response) {
         console.log("request successfully made")
    })
    .catch(function (error) {
        // seeing the error response code
        console.log(error.response.status);
    })
    .finally(function () {
        // always executed
        fs.writeFileSync('./r.txt',String(i));
    })

}

So I want that the 'i' variable be written in the ./r.txt. It actually means that which request we are sending write now. but the problem is that it is really strange in it:
look the video of r.txt changes here

A: You are running 1000 asynchronous operations in a loop.  You start them sequentially, but they all run in parallel.  Then as each one finishes each one calls fs.writeFileSync() and it's a race to see which one calls it when.  It will be random in what order each one finishes, which is what I think your video shows.
You can sequence them to be in order using await like this:
const axios = require("axios").default;
const fs = require("fs");
const params = require("./utils/url");

async function run() {

    for (let i = 0; i < 1000; i++) {
        const config = {
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
        };
        // sending post with data of web/appliaction the url http://somewhere.com/my-account/
        await axios
            .post("http://somewhere.com/my-account/", params(), config, {})
            .then(function(response) {
                console.log("request succesfully made");
            })
            .catch(function(error) {
                // seeing the error response code
                console.log(error.response.status);
            })
            .finally(function() {
                // always executed
                fs.writeFileSync("./r.txt", String(i));
            });
    }
}

run().then(() => {
    console.log("done");
}).catch(err => {
    console.log(err);
});

Or, reorganized a bit to not mix await and .then() in the same function like this:
const axios = require("axios").default;
const fs = require("fs");
const params = require("./utils/url");

async function run() {
    for (let i = 0; i < 1000; i++) {
        const config = {
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
        };
        // sending post with data of web/appliaction the url http://somewhere.com/my-account/
        try {
            let response = await axios.post("http://somewhere.com/my-account/", params(), config, {});
            console.log("request succesfully made");
        } catch(error) {
            console.log(error.response.status, error);
        } finally {
            fs.writeFileSync("./r.txt", String(i));
        }
    }
}

run().then(() => {
    console.log("done");
}).catch(err => {
    console.log(err);
});

A: async function writeToFile(){
    for (let i = 0; i < 1000; i++) {
      const config = {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      };
      // sending post with data of web/appliaction the url http://somewhere.com/my-account/
     await axios
        .post("http://somewhere.com/my-account/", params(), config, {})
        .then(function (response) {
          console.log("request succesfully made");
        })
        .catch(function (error) {
          // seeing the error response code
          console.log(error.response.status);
        })
        .finally(function () {
          // always executed
          fs.writeFileSync("./r.txt", String(i));
        });
    }
}


text:
Q: Reason of ValueError: negative dimensions are not allowed? I have been trying to plot the output of the function defined below,but not able to get the output. I tried several things but getting different errors every time. If somebody can help me with what it is that I am doing wrong, I shall be grateful.
import matplotlib.pyplot as plt
%matplotlib inline
import math
import sympy as sym
x = sym.symbols('x',positive = True)
lambd = 4
a= 3
def f(x):
    return lambd**a * x**(a-1) * sym.exp(-lambd*x) / math.factorial(a-1)
x1 = np.linspace(0,1,10)
plt.plot(x1,f(x1))

In case I change the x1 as np.linspace(0,1,100) then the error is
"ValueError: sequence too large; cannot be greater than 32"
What can be the reason for that? Some guidance in this will be highly appreciated.

A: You're passing a numpy array x1 to a function f. The problem that inside this function you have sympy.exp() which does not understand what to do with an array, since it only works on symbols and numbers.
The easiest would be to use numpy.exp instead.
import matplotlib.pyplot as plt
import numpy as np
import math

lambd = 4
a= 3

def f(x):
    return lambd**a * x**(a-1) * np.exp(-lambd*x) / math.factorial(a-1)

x1 = np.linspace(0,1,10)
plt.plot(x1,f(x1))

plt.show()

If, for whatever reason, you need to use some function that only works on single numbers and not arrays, you can use numpy.vectorize to convert the function to one that evaluates the input array elementwise.
import matplotlib.pyplot as plt
import sympy as sym
import numpy as np
import math

lambd = 4
a= 3

def f(x):
    return lambd**a * x**(a-1) * sym.exp(-lambd*x) / math.factorial(a-1)

fv = np.vectorize(f)

x1 = np.linspace(0,1,10)
plt.plot(x1,fv(x1))

plt.show()


text:
Q: Help with proof regarding the interior of a Set Let A, B $\subset$ R and let $x_{0}$ $\in$ R such that $x_{0}$ $\in$ int(A) and $x_{0}$ $\in$ int(B).
Show that $x_{0}$ $\in$ int(A$\cap$B)
Any insight would be helpful.
P.D i know conceptually is easy to grasp but i dont know how to formalize it

A: $
\newcommand{\Int}{\operatorname{int}}
$
Hints:

*

*Recall that $x \in \Int(S)$ if and only if there exists some $T \subseteq S$ which is an open neighborhood of $x$.

*Since $x_0$ is in both $\Int(A)$ and $\Int(B)$, we can find such sets $A_0,B_0$ for each of $A,B$, respectively.

*Observe that the intersection $A_0 \cap B_0$ contains $x_0$, and is an open neighborhood of $x_0$ contained within $A \cap B$. Reapply the definition of interior in this light.

I'll leave the justifications up to you.


text:
Q: AT&T syntax error: junk '(rbp)' after expression when assembling incq -8(rbp) i got these errors when i tried to compile my code and i dont know why. Could anyone help me. I am writing in the AT&T syntax
Errors: error junk '(rbp) after expression on the lines noted with *** in the inout subroutine
Code:
.text                   #section directive intended to hold all instructions

formatint:  .asciz  "%ld"

formatstr:  .asciz  "%s"        #format string for string printing, the s stands for string

DNNIDA:     .asciz          "names: x and y \nnetID's: xID and yID\nThis is assignment 1b inout\n"
enter:      .asciz          "\n"

.global main                #this is the main label

main:

    movq    $0, %rax        #no vector registers in use for printf (labmanual)
    movq    $formatstr, %rdi
    movq    $DNNIDA, %rdi       #load adress of string to rdi register
    call    printf          #printing the string that is displayed on top

    call    inout           #calling the inout subroutine

    movq    $0, %rax        #no vector registers in use for printf (labmanual)
    movq    $formatstr, %rdi
    movq    $enter, %rdi        #load the adress off the next string into rdi register
    call    printf          #printing the enter string (a return)
    call    end

end:

    mov     $0, %rdi        #load program exit code
    call        exit            #exiting the program

inout:

    pushq   %rbp            #Prologue: push the base pointer
    movq    %rsp, %rbp      #copy stack pointer to RBP

    subq    $8, %rsp        #reserve stack space for variable
    leaq    -8(%rbp), %rsi      #load adress of stack var in rsi
    movq    $formatint, %rdi    #load first argument of scanf
    movq    $0, %rax        #no vector registers in use for printf (labmanual)
    call    scanf           #call scanf

    movq    $formatint, %rdi
    movq    $0, %rax        #no vector registers in use for printf (labmanual)
    ***incq    -8(rbp)         #increments the number by one

    ***movq    -8(rbp), %rsi       #move a return value into RAX
    call    printf          #call printf
    movq    %rbp, %rsp      #Epilogue: clear local variables from stack
    popq    %rbp            #Restore caller's base pointer
    ret             #returns from subroutine


text:
Q: Quotient group-cosets Compute the factor group $(\mathbb{Z_6}\times \mathbb{Z_4})/\langle(3,2)\rangle$ and   $\langle(3,2)\rangle=\{(0,0), (3,2)\}$.
Here is what I have so far. I know I have 12 left cosets which are.
$$(1,0)+ \langle(3,2)\rangle =\{(1,0),(4,2)\}$$
$$(2,0)+ \langle(3,2)\rangle=\{(2,0),(5,2)\}$$
$$(3,0)+ \langle(3,2)\rangle=\{(3,0),(0,2)\}$$
$$(4,0)+ \langle(3,2)\rangle =\{(4,0),(1,2)\}$$
$$(5,0)+ \langle(3,2)\rangle =\{(5,0),(2,2)\}$$
$$(0,1)+ \langle(3,2)\rangle =\{(0,1),(3,3)\}$$
$$(0,3)+ \langle(3,2)\rangle =\{(0,3),(3,1)\}$$
$$(1,1)+ \langle(3,2)\rangle =\{(1,1),(4,3)\}$$
$$(1,3)+ \langle(3,2)\rangle =\{(1,3),(4,1)\}$$
$$(2,1)+ \langle(3,2)\rangle =\{(2,1),(5,3)\}$$
$$(2,3)+ \langle(3,2)\rangle =\{(2,3),(5,1)\}$$
Now I have to find a group that this is isomorphic to which I am having trouble with. I think its isomorphic to $\mathbb{Z_{12}}$ but I can't seem to find a generator for the cossets. Thanks

A: The element $(2,1)+\langle(3,2)\rangle$ is indeed of order 12, precisely because $(2,1)$ is of order 12 in $\mathbb{Z}_6 \times \mathbb{Z}_4$, and the subgroup in $\mathbb{Z}_6 \times \mathbb{Z}_4$ generated by $(2,1)$ does not contain $(3,2)$. This can be seen by observing that the 3 in the left entry of $(3,2)$ cannot be generated by the 2 in the left entry of $(2,1)$.


text:
Q: How can I convert an Array to Json (Java) I want to convert an Array into a Json Object like
String[] array = {"value1", "value2"};

into
{
  "array": ["value1", "value2"]
}

I am using Spring (Jackson XML).
I tried:
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode jsonNode = objectMapper.createObjectNode();

String[] array = {"value1", "value2"};
jsonNode.put("array", Arrays.toString(array));

System.out.print(jsonNode.toString());

But the result is
{
  "array":"[value1, value2]"
}

And not
{
  "array":["value1", "value2"]
}

what I want to get.

A: You are converting Array of strings into string and adding it to json object
String[] array = {"value1", "value2"};
String arr = Arrays.toString(array)   //converting array into string

Just add the array directly to ObjectNode using putArray
ArrayNode arrayNode = jsonNode.putArray("array");
Arrays.stream(array).forEach(str->arrayNode.add(str));

or you can also use addAll directly by converting array into ArrayNode
jsonNode.putArray("array").addAll(objectMapper.valueToTree(array));


text:
Q: How do I load OS Variables into PL/SQL? This should be pretty straightforward but the search words are so common that I am not finding an answer:
Q.  How do I load the values from an operating system variable (RHEL) into PL/SQL on an Oracle 11g database?
Code:
begin
dba_utilities.utilities_with_ext_proc.send_email(
        p_recipient   => '$MAIL_LIST',
        p_subject     => 'Subject'
        p_body        => 'Body
);
End ;

The procedure works fine if I put in an email address but there is a system variable called $MAIL_LIST that contains a group of people.  I can also confirm that this is working on other servers but I am setting up a replacement.
Thanks in advance and sorry if the question is overly simple!

A: You can access the environment variables via the getenv method in Java's System class. To invoke this from PL/SQL, you can create a Java stored procedure as follows:
CREATE FUNCTION getenv(name VARCHAR2) RETURN VARCHAR2
  AS LANGUAGE JAVA
  NAME 'java.lang.System.getenv(java.lang.String) return java.lang.String';

Now, you can write your PL/SQL code as follows:
begin
dba_utilities.utilities_with_ext_proc.send_email(
        p_recipient   => getenv('MAIL_LIST'),
        p_subject     => 'Subject'
        p_body        => 'Body
);
End ;

The stored procedure can also exist inside a PL/SQL package (if you don't want to create a schema-level function just to acquire environment variables).


text:
Q: error on one of my methods of my tictactoe game I keep getting the following error.
The user can only enter a number from 1 to 9. And this is what my error shows:

hint: does getemptyspot return valid entered spot even with initial zero entry:
  hint: does getemptyspot return valid entered spot even with initial 10 entry.

Also, if the board is full, my code should return -1. And if the spot is already taken, my code should return "That number is not available. Choose another from the numbered spots"
My code is as follows:
public int getEmptySpot()
{
    System.out.print("Choose a number where you want your marker to go");
    int spot = in.nextInt();
    if(b.isAvailable(spot))
    {
        return spot;
    }
    if(spot == 0 || spot > 10)
    {
        System.out.println("That number is not available. Choose another from   the numbered spots");
    }
    return -1;
}

A: may you post the detail of isAvailable()?
it looks like the code cannot reach the 2nd if() sub.
why use the different styles of the if()?
try like this:
if(spot >0 && spot <10){
    return spot;
}else{
}


text:
Q: Как разбить массив php на несколько массивов? Здравствуйте.
после запроса select у меня в переменной $nav содержится массив такого вида
Array (
[offline] => Array
    (
        [title] => Offline
        [nav] =>
    )

[404] => Array
    (
        [title] => 404
        [nav] =>
    )

[home] => Array
    (
        [title] => Главная
        [nav] =>
    )

[login] => Array
    (
        [title] => Войти
        [nav] => user
    )

[register] => Array
    (
        [title] => Регистрация
        [nav] => user
    )

[help] => Array
    (
        [title] => Помощь
        [nav] => footer
    )

[advertising] => Array
    (
        [title] => Реклама
        [nav] => footer
    )

[jobs] => Array
    (
        [title] => Вакансии
        [nav] => footer
    )

[team] => Array
    (
        [title] => Команда
        [nav] => footer
    )

[lessons] => Array
    (
        [title] => Уроки
        [nav] => training
    )

[books] => Array
    (
        [title] => Книги
        [nav] => training
    )

[video] => Array
    (
        [title] => Видео
        [nav] => training
    )

[projects] => Array
    (
        [title] => Проекты
        [nav] => work
    )

[news] => Array
    (
        [title] => Новости
        [nav] => main
    )

[forum] => Array
    (
        [title] => Форум
        [nav] => main
    )

[store] => Array
    (
        [title] => Магазин
        [nav] => main
    )

[doc] => Array
    (
        [title] => Справочник
        [nav] => main
    )

[blog] => Array
    (
        [title] => Блог
        [nav] =>
    )

[tools] => Array
    (
        [title] => Инструменты
        [nav] =>
    )

[add] => Array
    (
        [title] => Публикации
        [nav] =>
    )

[order] => Array
    (
        [title] => Заказы
        [nav] =>
    )

[templates] => Array
    (
        [title] => HTML шаблоны
        [nav] => download
    )

[psd] => Array
    (
        [title] => PSD исходники
        [nav] => download
    )

[fonts] => Array
    (
        [title] => Веб шрифты
        [nav] => download
    )

[plugins] => Array
    (
        [title] => Javascript плагины
        [nav] => download
    )

[textures] => Array
    (
        [title] => Текстуры
        [nav] => download
    )

[images] => Array
    (
        [title] => Изображения
        [nav] => download
    )

[software] => Array
    (
        [title] => Программы
        [nav] => download
    )

[services] => Array
    (
        [title] => Сервисы
        [nav] => info
    )

[hosting] => Array
    (
        [title] => Хостинг
        [nav] => info
    )

[cms] => Array
    (
        [title] => CMS системы
        [nav] => info
    )

[users] => Array
    (
        [title] => Пользователи
        [nav] =>
    )

[feedback] => Array
    (
        [title] => Служба поддержки
        [nav] =>
    )

[studio] => Array
    (
        [title] => Студия
        [nav] =>
    )
)

как Вы можете заметить значение поля [nav] повторяется, это сделано для разных меню
Вопрос:
как разбить этот массив на отдельные массивы?
например у меня есть 4 совпадения со значением footer, та вот 4 эти поля нужно вынести в отдельную переменную, например $nav_footer
Прошу помощи в реализации.

A: Обойдите свое меню, сгруппируйте элементы по ключам и воспользуйтесь функцией extract, чтобы  создать соответствующие переменные.
$menuData = [.
    'offline' => ['title' => "Offline",  'nav' => null],
    '404'     => ['title' => "404",      'nav' => null],
    'home'    => ['title' => "Главная",  'nav' => null],
    'login'   => ['title' => "Войти",    'nav' => "user"],
    'register'=> ['title' => "Регистрация",'nav' => "user"],
    'help'    => ['title' => "Помощь",   'nav' => "footer"],
    'advertising' => ['title' => "Реклама",'nav' => "footer"],
    'jobs'    => ['title' => "Вакансии", 'nav' => "footer"],
    'team'    => ['title' => "Команда",  'nav' => "footer"],
];

$data = [];
foreach($menuData as $k => $md){
    $mkey = "nav".(empty($md['nav']) ? "" : "_".$md['nav']);
    $data[$mkey][$k] = ['title' => $md['title']];
}

extract($data);

print_r($nav_footer);

в выводе этой переменной получите 4 элемента.
если не пользоваться extract(), то просто изначально записать в переменные, не используя доп. массив:
foreach($menuData as $k => $md){
    ${$mkey}[$k] = ['title' => $md['title']];
}

Я правда не вижу особого смысла в разделении этого массива на отдельные переменные, и, как кажется, достаточно бы было простой группировки (print_r($data) и дальнейшего использования $data['nav_footer'] и т.п.).


text:
Q: Where to find extension-printer.dll I have tried using the printer methods but I get errors when whenever I use them. Have searched the web and the solution was to install the printer.dll file but I have failed to get this file.
forexample I get this for printer_list function
Call to undefined function printer_list()
How can I solve this.

A: Please refer to http://php.net/manual/fa/printer.installation.php

This » PECL extension is not bundled with PHP.
Windows users must enable php_printer.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

You can find the currently available DLLs at

*

*http://windows.php.net/downloads/pecl/releases/
Printer does not have an official release, but there is snapshot release available at

*

*http://windows.php.net/downloads/pecl/snaps/printer/0.1.0-dev/
You need to find the right one for the PHP version you are using. As you can tell by the file names, these DLLs are for 5.3 to 5.5 - if you need it for a different PHP version, you need to build it yourself.


text:
Q: Remove Item on RecyclerView Android Studio How to delete an item on Recycler View in Android Studio after clicked an item? Here is my code now :
public CustomViewHolder(View itemView) {
        super(itemView);
        namaItemView = (TextView) itemView.findViewById(R.id.namaos);
        img_icon = (ImageView) itemView.findViewById(R.id.img_icon);
        img_icon.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.img_icon){
            Toast.makeText(v.getContext(), "You choose "+sisop.get(getAdapterPosition()).nama,
                    Toast.LENGTH_SHORT).show();
        }
    }

A: first.. remove from your list using .remove(position), then notifyItemRemoved(position), then notify range change notifyItemRangeChanged(position, mDataSet.size())
    @Override
    public void onClick(View v) {
         list.remove(position);
         notifyItemRemoved(position);
         notifyItemRangeChanged(position, mDataSet.size());
    }

A: When onClick is called use below code
yourDataList.remove(position);
notifyItemRemoved(position);

For further details you may refer below link thatwill give further deatils
https://stackoverflow.com/questions/26076965/android-recyclerview-addition-removal-of-items


text:
Q: Test identicality of discrete distributions Is there a standard way to test whether two vectors were drawn with the same discrete distribution in R? Something like a Kolmogorov-Smirnov test, but for discrete distributions.
I think two-sample chi-squared test would be appropriate. Does any package provide it? I can't get chisq.test to work for me.

A: The issue with the Kolmogorov-Smirnov test and distributions that aren't continuous is that the possible permutations of the observations are not all equally likely, so the null distribution of the test statistic doesn't apply.
Indeed it's no longer distribution-free, and using the test "as is" is generally quite conservative (has a substantially lower type I error rate than the nominal rate - and correspondingly lower power).
One possibility is to use the statistic but actually compute the permutation distribution (in small samples) or sample from it (a randomization test).
The chi-square test tends to have low power against interesting alternatives because it ignores ordering. Smooth tests of goodness of fit (which in the simplest case can be treated as a partitioning of the chi-square into low-order components and an untested residual) don't ignore the ordering and tend to have better power. See, for example, the books by Rayner and Best (and others, in some cases).

To get the chi-square to work (though with ordered data I wouldn't do it this way, as I mentioned) you'll need to present it as a two-row (or -column) table of counts:
value:   0  1  2  3  4  5
    X:   4  7  9  3  1  1
    Y:   0  2  5  6 12  5

What you are doing is a test of homogeneity of proportions. For the chi-square, which conditions on both margins, this is identical to a test of independence.
So for this data frame, which I have called xycnt:
  x  y
0 4  0
1 7  2
2 9  5
3 3  6
4 1 12
5 1  5

we just do this:
> chisq.test(xycnt)

    Pearson's Chi-squared test

data:  xycnt
X-squared = 20.6108, df = 5, p-value = 0.0009593

Warning message:
In chisq.test(xycnt) : Chi-squared approximation may be incorrect

In this case it complains because the expected counts in some cells are small. One solution is not to rely on the chi-square approximation to the test statistic but to simulate its distribution, obtaining a simulated p-value:
chisq.test(xycnt,simulate.p.value=TRUE,B=100000)

    Pearson's Chi-squared test with simulated p-value (based on 1e+05 replicates)

data:  xycnt
X-squared = 20.6108, df = NA, p-value = 0.00032

With such a small p-value, simulated estimates of it are a bit variable, but always small. You can always up the number of simulations further, it's pretty fast. (Ten million simulations generally give p-values between 0.00032 and 0.00033 and only take a few seconds)

A: Doing a google search for 'Kolmogorov-Smirnov test using R' shows a 'ks.test( ...
in the stat package (a default package).  Don't know about the discrete part, but you can read through and see if it applies to your project.


text:
Q: Crash loading data from coreData in airplane mode When I load my app with internet then go into airplane mode I can load posts saved to the coreData fine. But If I load my airplane already in airplane mode I get a crash on this line:
let results = try moc.fetch(fetchRequest)

from this function:
   func loadImages(_ fetched:@escaping (_ images:[FullRes]?) -> Void) {

    saveQueue.async() {
        let context = self.getContext()

        guard let moc = context else {
            return
        }

        let fetchRequest: NSFetchRequest<NSFetchRequestResult> = FullRes.fetchRequest()
        //let request: NSFetchRequest<NSFetchRequestResult> = FullRes.fetchRequest()
        //let fetchRequest = NSFetchRequest(entityName: "FullRes")//NSFetchRequest(entityName: "FullRes")

        do {

            let results = try moc.fetch(fetchRequest)

            let imageData = results as? [FullRes]
            DispatchQueue.main.async() {
                fetched(imageData)

            }
        } catch let error as NSError {
            print("Could not fetch \(error), \(error.userInfo)")
            return
        }
    }
}

And it gives me this message:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error:  is not a valid NSFetchRequest.'
Not sure why this is occuring...Any ideas?

A: I fixed it by putting this
if Reachability.isConnectedToNetwork() == true {
    }

around my loadPosts() function in ViewDidload as it was calling methods from AppDelegate!
Took me hours ;)


text:
Q: iOS MFMailComposeViewController and getting users Name from contact card I want to get the "Me" card's Name so when i create the mail window with MFMailComposeViewController
I can
MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
[mailer setSubject:@"Suggestion: from (Name of Person)"];

Basically substitute the (Name of Person) with the name on their contact card.

A: You can't get the "Me" card from the iOS SDK. There's a me method for the mac, but not for iOS. If the name of the person will be in the From: field, what value is there in adding it to the subject line?


text:
Q: Why doesn't this code read the number correctly? # Inport functions.
from random import randint
from random import seed
# Generate numbers. The first seed is based off of how many milliseconds have passed since Epoch (1970). Aka theres no way to perfectly predict this.
seed(randint(0,100))
x = randint(0,100)
seed(randint(0,100))
y = randint(0,100)
seed(randint(0,100))
z = randint(0,100)
seed(randint(0,100))
a = randint(0,100)
seed(randint(0,100))
b = randint(0,100)
list = [a,b,x,y,z]
# Input number.
input = int(input('Input a whole number from 0 - 100.'))
# Simple check loop. 5 times since theres 5 numbers.
for x in list:
            '# If input matches first item in list
        if input == list[0]:
            '# Set Y to 1 than stop looping.
            Y = 1
            break
        else:
            '# Otherwise delete the first item in the list and try again.
            Y = 0
            del list[0]
# Than if Y is one print bingo, otherwise print try again.
if Y == 1:
        print('Bingo!')
else:
        print('Try again.')

This py3 code always prints 'Try again.' I've tried forcefully setting x to 9 but it doesn't work, can anyone diagnose this? I've made sure it was properly indented in codesculpter3, anyone know why it doesn't work?

A: There were quite a few errors (see the comments). But in particular, you have used list and input as variables. The code is also appending a list that it is iterating over, which can lead to errors (hint: if you ever do this, then create a new list).
This is a "pythonic" version of the code that would work:
import random

# random list of 5 numbers (0 to 100)
my_list = [random.randint(0,100) for x in range(5)]

got_it = 0  # variable for correct guess
for x in my_list:
    y = int(input('Input a whole number from 0 - 100.'))
    if y == x:
        got_it = 1
        print('bingo !')
        break
if got_it == 0:
    print('try again')


text:
Q: External hard drive with iPhoto library doesn't open My son pulled out the USB cable while iPhoto was running from the external hard drive and a message came up when I plugged it back in that said there were inconsistencies that needed to be repaired. So I followed the instructions to complete it but it didn't work.
Next I used a new external hard drive to make a back up of the MacBook and a copy of the iPhoto Library.
Then the iPhoto Library msg said that it was either being used by another user or unreadable. I saw that there were 4 other options if you opened iPhoto while pressing command-option.
Once copied I tried to open the copy but kept saying it was unreadable still. Restarted etc., didn't work again. Tried the first option, repairing permissions... didn't work, next tried option 3, but then the message came up saying that it would only be available once Time Machine had finished. But Time Machine isn't on!
I'm not sure what to try next.

A: It sounds like you made a copy of the library after it was corrupted. Your only option I suppose is to grab the images and start a new library.
Find the original, if possible, right click on it and choose "Show Package Contents".

In there navigate to "Masters". In there, run a search for Kind=Image.

Copy all of the results out of there, to a safe location.
Then do another search for Kind="Movie", and copy those as well.


text:
Q: Pushing air downwards using a fan, to hover in air I believe that I am simply missing something over here, but cannot find it.
I want to just think theoretically, that if I use a fan (drone manner) to push air downwards, like a rocket, I would be pushed upwards.
So I need to apply a constant force of  upwards. In my case, it's 700N approx.
Now, much electrical power would be needed for the job?

A: If you use a single fan, it will not only accelerate air downwards but also add a bit of swirl. Just as the downward acceleration results in an upward force (the desired lift), the rotational acceleration will result in a torque on the fan and motor assembly, so it will start to rotate in the opposite direction of the fan's rotation.
Either you use an even number of fans and create counter-rotating pairs of them, or you add some device to produce counter-torque. In most helicopters of the Sikorsky type this is a small vertical rotor at the end of a tailboom, or it is a jet of air (Google for NOTAR to learn more).
Once this is solved, start with the static thrust equation of a propeller:
$$T_0 = \frac{P\cdot\eta_{Prop}\cdot\eta_{el}}{\sqrt{\frac{2\cdot T_0}{\pi\cdot d_P^2\cdot\rho}}} = \sqrt[\LARGE{3\:}]{P^2\cdot\eta_{Prop}^2\cdot\eta_{el}^2\cdot\pi\cdot \frac{d_P^2}{2}\cdot\rho}$$
Nomenclature:
$\kern4mm T_0\kern7mm$Thrust at zero forward speed
$\kern4mm P\kern8mm$Motor power
$\kern4mm \eta_{Prop}\kern2mm$propeller efficiency. Could be anything between 0.5 and 0.85
$\kern4mm \eta_{el}\kern6mm$electric efficiency of motor and its controller
$\kern4mm d_P\kern6mm$propeller diameter
$\kern4mm \rho\kern9mm$air density
$\kern4mm \pi\kern9mm$3.14159265…

A: The required power is
$$W=\sqrt{\frac{\left ( mg \right )^{3}}{2pS}}$$
-S being the surface of the disc enclosing the fan
-g being gravity acceletation
-p is density of air (kg/m3)
-m is the mass being lifted
The demonstration is Rankine-Froude theorem, which relies on Bernouilli's principle in the air column of the fan to show that
$$T=2psv^{2}$$
-T being the lifting force
-v being the induced speed of air at the fan
From there you get in stationnary flight that gravity=lift:
$$mg=2psv^{2}$$
or
$$v=\sqrt{\frac{mg}{2pS}}$$
Then by multiplying the speed with the force(=mg) you get the power W in the first equation.
In your specific case you can replace "mg" by 700 N


text:
Q: Image Download in PHP     $image_name = rawurldecode($name);
    $image_path = 'http://' . rawurldecode($path) . '/resources/images/banner/' . $image_name;
    $mime = explode('.', $image_name);

    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header('Content-Type: image/' . $mime[1]);
    header("Content-Disposition: attachment; filename=$image_name");
    header('Content-Transfer-Encoding: binary');
    ob_clean();
    flush();
    readfile($image_path);

I have this code above it's running fine in my local but when I upload it in my server I can still download it but the image is broken. you can see the upper part of the image but the lower part is all gray.

A: Can you try this.
$image_name = rawurldecode($name);
$image_path = 'http://' . rawurldecode($path) . '/resources/images/banner/' . $image_name;
$mime = explode('.', $image_name);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($image_path));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($image_path));
readfile($image_name);
exit;


text:
Q: Socket.io client sending but not receiving. How to debug? I have a Node.js server that serves a game that uses socket.io for communciation.
The server has socket.io as a Websocket Server.
The client is a Vue project that is built with Vite.
All this is deployed on Heroku.
The problem is that the client has a succesful WS connection and sends data to the server which the server sees. However, the server appears to be unable to send data back the client.
Developer Tools > Network tab (WS)
active ws connection
Locally, of course, this works fine.
I've enabled http-session-affinity and DEBUG=socket* dist/index.js
socket.io:server incoming connection with id pp-tr6sHkUhv0XQmAAAA
socket.io-parser decoded 0 as {"type":0,"nsp":"/"}
socket.io:client connecting to namespace /
socket.io:namespace adding socket to nsp /
socket.io:socket socket connected - writing packet
socket.io:socket join room cKL5uTe1EsFYQVpfAAAB
socket.io-parser encoding packet {"type":0,"data":{"sid":"cKL5uTe1EsFYQVpfAAAB"},"nsp":"/"}
socket.io-parser encoded {"type":0,"data":{"sid":"cKL5uTe1EsFYQVpfAAAB"},"nsp":"/"} as 0{"sid":"cKL5uTe1EsFYQVpfAAAB"}
socket.io-parser decoded 2["join-room","prelobby"] as {"type":2,"nsp":"/","data":["join-room","prelobby"]}
socket.io:socket got packet {"type":2,"nsp":"/","data":["join-room","prelobby"]}
socket.io:socket emitting event ["join-room","prelobby"]
socket.io:socket dispatching an event ["join-room","prelobby"]
heroku/router at=info method=GET path="/socket.io/?EIO=4&transport=polling&t=OMRi4mx&sid=pp-tr6sHkUhv0XQmAAAA" host=xxx.herokuapp.com request_id=a93e01fd-f3ce-4d66-9f8f-4421a2e04d5d fwd="88.159.232.55" dyno=web.1 connect=0ms service=146ms status=200 bytes=168 protocol=https
socket.io-parser decoded 2["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}] as {"type":2,"nsp":"/","data":["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]}
socket got packet {"type":2,"nsp":"/","data":["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]}
socket.io:socket emitting event ["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]
socket.io:socket dispatching an event ["create-lobby",{"id":"bf791395-2316-4a8c-bffc-ca8b8b600385","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]
socket.io-parser decoded 2["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}] as {"type":2,"nsp":"/","data":["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]}
socket.io:socket got packet {"type":2,"nsp":"/","data":["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]}
socket.io:socket emitting event ["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]
socket.io:socket dispatching an event ["create-lobby",{"id":"d881d972-a341-487d-9831-90d0769e21ee","teamName":"TEAM NAME HERE","players":[],"maxPlayers":4,"started":false,"takenSlots":[]}]

Server:
const server = new Server(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"],
    },
    transports: ["polling", "websocket"],
    allowEIO3: true,
    allowUpgrades: true,
});
const server: http.Server = httpServer.initialise();
server.listen(env.PORT, () => {
   console.log(`Server listening on port ${env.PORT}`);
});
const io = sockets.start(server);

Client:
this.socket = io();
this.socket.emit(SocketEvents.JOIN_ROOM, "prelobby");
this.socket.on(SocketEvents.LOBBY_CREATED, (lobbyData) => {
      console.log("received lobby data", lobbyData);
      LobbyData.data = lobbyData;
      this.cameras.main.fadeOut(1000);
      this.socket.emit(SocketEvents.LEAVE_ROOM, "prelobby");
});

vite.config.js
export default defineConfig({
  plugins: [vue({
    template: {
      transformAssetUrls: {
        includeAbsolute: false,
      }
    }
  })],
  server: {
    proxy: {
      '/api': {
        target: `http://localhost:4000`,
        changeOrigin: true,
      },
      '/socket.io': {
        target: `ws://localhost:4000`,
        ws: true,
        changeOrigin: true,
      }
    },
  },
  build: {
    rollupOptions: {
      external: [],
    }
  }
})


text:
Q: Missing a fundamental understanding wrt methods I am an OLD procedural language programmer, trying to learn Obj C. And after pulling out all my hair realize I am missing a fundamental understanding
When I alloc an instance of an object ( myObj), give it some data via methods, and the call a method/send a message to that instance, can the implementation routine assume that all the data in that instance is available?
i.e  [myObj doSomeStuff]
can the implementation of doSomeStuff assume that all the instance data of myObj is available or do I need to send in as arguments of all the parts and pieces of myObj that I need?

A: Ditto on what Luis and rmaddy said.  Some of this is best illustrated with an example.  Lets consider a Circle class object:
Here is the .h file:
//  Circle.h

#import <Foundation/Foundation.h>

@interface Circle : NSObject
{
    double radius;
    double pi;
}

@property double radius, pi;

-(double) area;
-(double) diameter;
-(double) circumference;

@end

And then the implementation file (note that I have defined instance methods as Luis points out):
//  Circle.m

#import "Circle.h"

@implementation Circle

@synthesize radius, pi;

// Initialize with default radius:
- (instancetype)init {
    self = [super init];
    if (self) {
        pi = 3.14159;
        NSLog(@"Circle created.");
    }
    return self;
}

-(double) area {
    return pi*radius*radius;
}

-(double) diameter {
    return 2*radius;
}

-(double) circumference {
    return 2*pi*radius;
}

@end

Now create a circle object in main and send messages to return several relevant quantities:
//  main.m

#import <Foundation/Foundation.h>
#import "Circle.h"

int main(int argc, const char * argv[])
{
    @autoreleasepool {

        Circle *aCircle = [[Circle alloc] init];

        [aCircle setRadius:2];

        NSLog(@"Area = %f",[aCircle area]);
        NSLog(@"Circumference = %f",[aCircle circumference]);
        NSLog(@"Diameter = %f",[aCircle diameter]);
        NSLog(@"Check pi = %f",[aCircle pi]);

    }
    return 0;
}

You can see from this example the value of pi is set when the object is created and then is stored as part of the object, available for other calculations.
Note:  you wouldn't want to define pi this way in practice, this is just a simple example to illustrate the point.
Note also that I could have set other internal values of the object after it was created, then this data is also available from that point forward, subject to the qualifications pointed out in the post.
Does this make better sense?  You should run this code and experiment with the idea until you feel more comfortable with it.
EDIT:  At Andrew Madsen's suggestion, updated the accessor methods for area, diameter, and circumference; these should not be prefixed with 'get'

A: YES, if the method is an instance method (those who starts with a "-" not "+").


text:
Q: Admin/backend and frontends as one project or separate projects I'm developing a front end with reactjs for a fairly large project which has two main interfaces.front-end of the main site and front-end of the admin.
Should i develop these as two different projects or one project in reactjs. if i structure these as two separate projects i'm well aware that it means i will have to do lot of repeating code on both projects. So i presume i should consider it as one project as below.
client (Project Folder)

*

*app/main

*app/admin

If i'm developing this as one project how do different front-ends route to different sub-domains if it lies in one project folder.

*

*example.com - main front-end

*admin.example.com - admin front-end

A: It is okay to have a shared codebase for admin and public sites. But you will need to generate different js/css bundles for them. So your public index.html includes something like public.js and public.css. And the admin uses admin.js and admin.css. The public files contain all the shared functionality and the stuff which is used on the public site only. Same thing for admin.
Making that separation can significantly reduce the file sizes, as typically admin apps include some charts, rich text editors, css frameworks and tons of other stuff which may affect your public site loading speed.
To implement separate bundles with webpack, which you probably use, you need to create a few independent entry points.
The docs — https://webpack.github.io/docs/multiple-entry-points.html
Also, you will need to use different react-router setups and redux stores (if you use those). But the presentational components and utilities can be shared.


text:
Q: MPDF generates blank pages before content instead of breaking table to 2 pages I've got strange problem on pdf generation via MPDF (5.7 version).
HTML for pdf contains pretty much 1 div and table inside it:
<div style="width: 992px; height: 1403px; margin: 0 auto; padding-left: 30px; -webkit-box-sizing: border-box;-moz-box-sizing: border-box;box-sizing: border-box;">

    <TABLE BORDER BORDERCOLOR=#fff CELLSPACING=0 WIDTH=100%>

Table content doesn't fit 1 page, so it should have break for 2 pages somewhere inside, but instead it adds 4 blank pages before content, then outputs 1 tr on page which is 1 line and on last page rest of the table.
Here's MPDF config:
    $mpdf = new mPDF('utf-8', 'A4', '6', '', 10, 10, 7, 7, 10, 10);
    $mpdf->charset_in = 'utf-8';
    $mpdf->shrink_tables_to_fit = 0;
    $mpdf->list_indent_first_level = 0;
    $mpdf->WriteHTML($html, 2);

shrink_tables_to_fit cannot be removed, since it's document for print.
Other templates work fine with tables breaking into pages.
Is there any way to fix this?
UPDATE:
Issue gone after upgrading to 6.0 version.

A: Check mPDF plugin and used only supported CSS and try with this mPDF code.
    $mpdf=new mPDF();
    $mpdf->SetDisplayMode('fullpage');
    $mpdf->list_indent_first_level = 0;
    $mpdf->WriteHTML($html);

A: I got the same problem with Version:5.7.2, I have resolved this by removing colspan and rowspan from the table without upgrading.

A: You need to use page-break options in additional div to get control of breaks.


text:
Q: Python PIP claims that a package is installed but whet I use package it is not found I have been trying to setup a proper virtual environment. I came upon this. But I am still unable to use the package:
yathi@DarkWater-U:~$ pip install virtualenvwrapper
Requirement already satisfied (use --upgrade to upgrade): virtualenvwrapper in /usr/local/lib/python2.7/dist-packages
Cleaning up...
yathi@DarkWater-U:~$ workon
workon: command not found
yathi@DarkWater-U:~$ mkvirtualenv
mkvirtualenv: command not found

With some googling I found that the problem is probably because I used sudo pip install instead of pip install. But now I don't know how to correct the problem and install the package correctly.

A: Please read the documentation:
$ pip install virtualenvwrapper
...
$ export WORKON_HOME=~/Envs
$ mkdir -p $WORKON_HOME
$ source /usr/local/bin/virtualenvwrapper.sh
$ mkvirtualenv env1


text:
Q: Python - Select function or alter module based on user input during class instantiation I think posting even a minimal working example of this problem might be messy, so I'm going to outline the problem using pseudocode. I have a module where I have defined a class - let's call it my_class.py. The class methods use a lot of similar code so it made sense to break out these code blocks into functions and put them into a separate module - let's call it functions.py. To clarify, functions.py looks like this:
def dependent(inverted):
    if inverted:
        return this
    else:
        return that

def func_a():
    do stuff...
    dependent()

def func_b():
    dependent()
    do stuff...

... more functions ...

def func_z()
    do stuff...
    dependent()

and my_class.py looks like this:
from functions import func_a, func_b, func_c

class A():
    def __init__(self, inverted=False):
        self.inverted = inverted

    def method_1(self,):
         do stuff....
         func_a()
         do sfuff ...
         func_b()

    def method_2(self,):
        func_c()

    ... more methods using functions from functions.py

Now, you might be looking at that weird "dependent" function in functions.py and the "inverted" keyword in the class init method. You see, the functions func_a, func_b, ... , func_z in functions.py also reuse a lot of the same code so I put that code in a function named dependent - because functions func_a, func_b, etc. are dependent on it.
Things were looking pretty slick, but then I noticed a corner case I needed to consider. This case is easily accounted for using a Boolean variable named "inverted". The user should specify if the problem is inverted while instantiating the class. The issue is that the only function that directly changes is the dependent function. The other functions, func_a, func_b, etc. will change indirectly since they are dependent on "dependent". Note, the class never actually calls "dependent", only func_a, func_b, etc.
I think I may have painted myself into a corner. I can't think of a clean way to alter or pass the inverted option to the "dependent" function from the class to the module said class is importing. In fact, that process seems circular and dumb.
I have thought of two solutions.
1) Pass self.inverted to func_a, func_b, ..., func_z. So the methods would look like this:
def method_1(self):
    do stuff...
    func_a(self.inverted)
    ...

and func_a, func_b, etc. would look like this:
def func_a(inverted):
    do stuff...
    dependent(inverted)

or 2) create two functions modules with the only difference being one has dependent set to return that and the other has dependent set to return this (the inverted case). Then the class init method would import the corresponding function module based on the inverted argument. Visually:
class A():
    def __init__(self, inverted=False):
        if inverted:
            from functions_inverted.py import func_a, func_b, ...
        else:
            from functions_normal.py import func_a, func_b, ...

I don't like either option since I am repeating a lot of code and it kind of nullifies the original intent of making the code modular and clean. If I had noticed the corner case earlier I likely would have taken a different approach, however, at this point, a significant amount of time has been used getting the code to its current state.
Is there a better solution - one that keeps the code modular and clean - so that I can alter all the functions in functions.py by only passing an option to the function "dependent" when this option is provided during class instantiation? Note that multiple instances of the class may be called/running simultaneously.
Thanks!

A: Given the last requirement,

Note that multiple instances of the class may be called/running simultaneously.

you can wrap all your functions in a class (they become methods) and make inverted a parameter you pass to every instance of that class. Then you set self.inverted on every instance __init__, and you check that when running the dependent function (from that instance).
It looks like you have done that at an upper level where it is not needed. You may just instantiate the utility class with the functions there, and change your function calls to use the methods of the instance instead.


text:
Q: ListBox SelectionChanged event with MVVM and CommandParameter I'm developing a MVVM app with WPF, C# and .NET Framework 4.6.1.
I'm trying to implement ListBox SelectionChanged event using MVVM. To do it I have done this:
Install nuget package: PM> Install-Package System.Windows.Interactivity.WPF.
Add xmlns:interactivity="http://schemas.microsoft.com/expression/2010/interactivity" on xaml.
Add this code to my ListBox in xaml:
<ListBox x:Name="listBoxTrzType" Grid.Column="1" Margin="10,0,25,0" VerticalAlignment="Center" Height="25" ItemsSource="{Binding TrzTypes}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Name}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <interactivity:Interaction.Triggers>
        <interactivity:EventTrigger EventName="SelectionChanged">
            <interactivity:InvokeCommandAction Command="{Binding ListBoxTrzTypeSelectionChanged}"
                                                CommandParameter="{Binding ElementName=listBoxTrzType, Path=SelectedItem}">
            </interactivity:InvokeCommandAction>
        </interactivity:EventTrigger>
    </interactivity:Interaction.Triggers>
</ListBox>

On ViewModel I have:
public ICommand ListBoxTrzTypeSelectionChanged
{
    get { return new DelegateCommand(TrzTypeSelectionChanged); }
}

private void TrzTypeSelectionChanged()
{
    throw new NotImplementedException();
}

And DelegateCommand class:
public class DelegateCommand : ICommand
{
    private readonly Action _action;

    public DelegateCommand(Action action)
    {
        _action = action;
    }

    public void Execute(object parameter)
    {
        _action();
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

#pragma warning disable 67
    public event EventHandler CanExecuteChanged { add { } remove { } }
#pragma warning restore 67
}

But my problem is that I don't know how to pass CommandParameter="{Binding ElementName=listBoxTrzType, Path=SelectedItem}" to private void TrzTypeSelectionChanged().
I've been searching a lot on Internet and I haven't found any example (only examples with CanExecute).
How do I have to modify my ViewModel class to access SelectedItem parameter?

A: Actually, to use interaction behaviors for such task is overkill.
You even don't need a command here. It's enough to add SelectedItem property into view model and listen for property changes:
public class SomeVm : INotifyPropertyChanged
{
    // INPC implementation is omitted

    public IEnumerable<SomeType> Items { get; }
    public SomeType SelectedItem
    {
        get { return selectedItem; }
        set
        {
            if (selectedItem != value)
            {
                selectedItem = value;
                OnPropertyChanged();
                // do what you want, when property changes
            }
        }
    }
}

XAML:
<ListBox ItemsSource="{Binding Items}"
         SelectedItem="{Binding SelectedItem}"
         DisplayMemberPath="Name"/>

A: In your DelegateCommand
change private readonly Action _action; to private readonly Action<object> _action; then in your execute method
public void Execute(object parameter)
{
    _action.Invoke(parameter);
}

Now your ViewModel function needs to look like this:
private void TrzTypeSelectionChanged(object parameter)
{
    throw new NotImplementedException();
}

And you are good to go.


text:
Q: iOS - Programatically load view on app didFinishingLaunching This question is mostly about how I should structure my app. When the app loads the user can select from a list of videos to play, however the actual video player is on a different view controller. At the moment I am just keeping that view controller in memory so that the video can play continuously while the user is navigating throughout the app.
So the problems is that if the user selects a video before loading that movie view controller, nothing will happen of course.
How should I structure my app so that the video can play continuously whether or not the movie player view controller is held in memory? Is this possible?

A: I'm not 100% sure what you're trying to do; but a default project created in XCode will "Programatically load view on app didFinishingLaunching" without any further coding needed.
Generally you should structure your app with an initial view or view controller (like a navigation controller); and start any visible actions in the "viewDidLoad" method of the target view.
In your case, I would recommend loading straight to the video controller first; and then programmatically segueing to the video selector view if no video is selected.

A: Usually, I create a structure like this in my projects, I think you need to take a special look in OverlayViewController, check out a example:
MainViewController - As rootViewController
|- content (Any view controller to be presented, yes inside MainViewController)
|- OverlayViewController (a view controller over content )

This structure allows you to change contents without change entire hierarchy.
At MainViewController you will need a method to change current content to another, there is a simple example of how can you do that:
// PS I'm not sure if this will work in the first try, I wrote from my mind right now :)
func changeViewController (controller: UIViewController) {
  let from: UIViewController

  if childViewControllers.count > 0 {
    from = childViewControllers.first as! UIViewController
  }
  else {
    presentViewController(controller)
    return
  }

  let transitionContext = SomeViewControllerContextTransitioning (
    fromViewController: from,
    toViewController: controller
  )

  transitionContext.onAnimationComplete = { success in

    if !success {
      // TODO: Error fallback
    }
    else {
      from.view.removeFromSuperview()
      from.removeFromParentViewController()
      controller.didMoveToParentViewController(self)
    }

  }

  from.willMoveToParentViewController(nil)
  addChildViewController(controller)

  SomeAnimator().animateTransition(transitionContext)
}

And finally, in your MainViewController you can observe or control your video playback.
I hope this can help you.


text:
Q: PictureBox.Invalidate not re-rendering correctly I'm trying to build a little test application (and my WinForm skills have rusted somewhat) with an Image and some overlays on top of it.

My image is set to stretch in the PictureBox but my fields on the right hand side I want to be from the origin of the image. Therefore I decided to render directly on the image that the PictureBox is using to ensure that the co-ordinates are always correct. Here's the white box rendering:
  private void pbImage_Paint(object sender, PaintEventArgs e)
    {
        try
        {
            if (this.rdFront.Checked)
                RenderFront(pbImage.Image, true);
            else
                RenderBack(pbImage.Image, true);

        }
        catch (ArgumentNullException ex)
        { }
    }

public void RenderFront(Image image, bool includeBoxes)
    {
        // If we have no image then we can't render
        if (image == null)
            throw new ArgumentNullException("image");

        Graphics gfx = Graphics.FromImage(image);

        // Get the top label
        foreach (MessageConfiguration config in this.config.Values.Where(c => c.Front))
        {
            if (includeBoxes)
            {
                // Fill a White rectangle and then surround with a black border
                gfx.FillRectangle(Brushes.White, config.X, config.Y, config.Width, config.Height);
                gfx.DrawRectangle(Pens.Black, config.X - 1, config.Y - 1, config.Width + 2, config.Height + 2);
            }

            gfx.DrawString(config.Text, new Font(FontFamily.GenericMonospace, config.FontSize), Brushes.Black, new PointF(config.X, config.Y));
        }
    }

The problem that I've got is if I do this and always draw on the underlying image then when I move the white overlay, I end up with un-drawn parts of the image. So I decided to clone the image before each re-render (on the basis that I don't care about performance).
I therefore decided to clone the image whenever I need to manually invalidate it, and call this when a setting changes:
    public void Refresh()
    {
        if (this.rdFront.Checked)
            pbImage.Image = new Bitmap(front);
        else
            pbImage.Image = new Bitmap(back);

        this.pbImage.Invalidate();
    }

Now I'm sure I must be missing something obvious - if I modify one of the values my penguins render with no overlay. However if I force a resize of the application then both the penguins and the overlay suddenly appear.
Can anyone suggest what I might be doing wrong?
Edit
Here's a download link to the project as it's quite small. Paste a path to an image in the 'Front Image' box and try using the controls on the right (set 100x100 height and width). Try re-sizing to see the desired affect.  https://dl.dropboxusercontent.com/u/41796243/TemplateTester.zip

A: Controls and Forms have a Refresh method already. Are you really calling your Refresh method? Aren't you getting a warning that you should use the new keyword? Better give your Refresh method another name (e.g RefreshImage)!

I'm really not sure why you are using a picture box but then decide to do your on painting. I suggest to draw to an image off-screen and then simply assign it to the picture box:
public void RefreshImage()
{
    Bitmap bmp;
    if (this.rdFront.Checked)
        bmp = new Bitmap(front);
    else
        bmp = new Bitmap(back);

    using (Graphics gfx = Graphics.FromImage(bmp)) {
        foreach (MessageConfiguration config in this.config.Values.Where(c => c.Front))
        {
            if (includeBoxes) {
                // Fill a White rectangle and then surround with a black border
                gfx.FillRectangle(Brushes.White, config.X, config.Y, config.Width, config.Height);
                gfx.DrawRectangle(Pens.Black, config.X - 1, config.Y - 1, config.Width + 2, config.Height + 2);
            }
            gfx.DrawString(config.Text, new Font(FontFamily.GenericMonospace, config.FontSize), Brushes.Black, new PointF(config.X, config.Y));
        }
    }

    pbImage.Image = bmp;
}

and remove the pbImage_Paint method.

Another possibility is to use the pbImage_Paint event handler in another way. Call the base.Paint() handler of the picture box that draws the image but leave the image itself unchanged. Instead draw on top of it by using the Graphics object given by the PaintEventArgs e argument. This Graphics object represents the client area of the picture box. This does not alter the Bitmap assigned to the picture box, but only draws on the screen.
private void pbImage_Paint(object sender, PaintEventArgs e)
{
    base.Paint(); // Paints the image
    if (this.rdFront.Checked)
        RenderFront(e.Graphics, true);
    else
        RenderBack(e.Graphics, true);
}

public void RenderFront(Graphics g, bool includeBoxes)
{
    foreach (MessageConfiguration config in this.config.Values.Where(c => c.Front)) {
        if (includeBoxes) {
            g.FillRectangle(Brushes.White, config.X, config.Y, config.Width, config.Height);
            g.DrawRectangle(Pens.Black, config.X - 1, config.Y - 1, config.Width + 2, config.Height + 2);
        }
        g.DrawString(config.Text, new Font(FontFamily.GenericMonospace, config.FontSize), Brushes.Black, new PointF(config.X, config.Y));
    }
}


text:
Q: How do I make types that can only contain certain properties in flow? I have some code like this:
/* @flow */

type Options = {
  userdir?: string,
}

function foo(options: Options) {
  return 'foo';
}

foo({userDir: 'bar'});

I expected that flow would warn me here, that there is no property userDir in my Options type. But according to the flow type checker, this code is totally fine. How do I make types that can only have certain properties in flow?

A: In your snippet, you're declaring an optional property, so Flow doesn't complain.
If you need Flow to tell you about the missing property, you need to remove the question mark :
type Options = {
    userdir: string;
};

If you need that property to be defined, but also allow it to be null or undefined, you can use a 'maybe type' :
type Options = {
    userdir: ?string;
};

edit : We discussed this on Reactiflux, turns out Flow (as of 0.32) just added Exact types :
type Options = {|
    userdir: ?string;
|};

Using this syntax, when calling foo({userDir: 'bar'}); Flow will complain about the userDir property, which does not exist in the above definition.


text:
Q: Framework7 + AngularJS (DOM changes so angular can't find controllers) I'm using framework7 and AngularJS for making a mobile app. I just need AngularJS for databinding.
When clicking on a link with framework7, the content of a div changes. In the new content I set a new controller, but angular can't find it. Is there a way to notify angular that the DOM has changed?
You can download the project here: http://www35.zippyshare.com/v/yDszXHuB/file.html
This DemoController in index.html works. It changes the {{title}}

This DemoControllerAbout in about.html does not work. It won't change {{title}}

A: At the moment, the integration of Framework7 and AngularJS is a work-in-progress.  Specifically, page routing functionality conflicts with each other leading to undesired effects.
See https://github.com/nolimits4web/Framework7/issues/35

A: You should try to compile the views on pageinit event. Try this
Framework7.prototype.plugins.angular = function(app, params) {
    function compile(newPage) {
        try {
            var $page = $(newPage);
            var injector = angular.element("[ng-app]").injector();
            var $compile = injector.get("$compile");
            var $timeout = injector.get("$timeout");
            var $scope = injector.get("$rootScope");
            $scope = $scope.$$childHead;
            $timeout(function() {
                $compile($page)($scope);
            })
        } catch (e) {
            //console.error("Some Error Occured While Compiling The Template", e);
        }
    }

    return {
        hooks: {
            pageInit: function(pageData) {
                compile(pageData.container);
            }
        }
    }

};

and set this plugin while initialization of framework7 app
new Framework7({
  ....
  angular : true
  ....
})

For more details you can refer below github repo with fully working demos
https://github.com/ashvin777/framework7.angular

A: You need to recompile the DOM snippet that's being injected:
$compile(domSnippet)($scope);
$scope.$apply();

See more info on this blog article I created: http://www.timo-ernst.net/blog/2016/02/24/how-to-use-ajax-pages-with-angular-1-x-in-framework7/
There is also a demo project available on Github: https://github.com/valnub/Framework7-Ajax-Pages-With-Angular-Demo