text:
Q: Using HttpClient to send JSON query string in a URL to a web service (Java) I have a web service that I built... what I am trying to do now is send a simple request that contains a json query string from a Tapestry web app to that web service. I searched around and most people say to use Apache HttpClient to achieve this. Along with HttpClient I am using URIBuilder.
The Json object that I am trying to send looks like this

{"user":{"userEmail":"jdoe@gmail.com","firstName":"John","lastName":"Doe","phone":"203-   555-5555"},"password":"dead"}

*I realize the issues with the password being sent in plain text etc...
The url that works (tested by manually entering in a web browser and this web service already services an Android client and an iOS client) looks like this

http:// ##.##.###.##/createuser?json={"user":{"userEmail":"jdoe@gmail.com","firstName":"John","lastName":"Doe","phone":"203-555-5555"},"password":"dead"}

Here is the HttpClient code that I have mashed together from google'ing around trying to figure out why this wont work. Essentially what I am trying to do is create a URI with URIBuilder and then construct an HttpPost or HttpGet object with the newly built URI. But something is going wrong in the URIBuilding process. When I debug, an exception gets thrown when I try to set all the aspects of the URI.
Object onSuccess() throws ClientProtocolException, IOException, URISyntaxException{
    // json = {"user":{"userEmail":"jdoe@gmail.com","firstName":"John","lastName":"Doe","phone":"203- 555-5555"},"password":"dead"}
    String json = user.toJson();
    URIBuilder builder = new URIBuilder();
    // Error gets thrown when I step over the next line
    builder.setScheme("http").setHost("##.###.##.###").setPort(8080).setPath("createuser").setQuery("json=" +json);
    URI uri = builder.build();

    HttpPost request = new HttpPost(uri);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    String tmp = request.getURI().toString();

    HttpResponse response = httpClient.execute(request);
    index.setResponse(EntityUtils.toString(response.getEntity()));
    return index;

The error that comes back when I step over the line that I commented in the code is

[ERROR] TapestryModule.RequestExceptionHandler Processing of request failed with uncaught exception:org.apache.http.client.utils.URLEncodedUtils.parse(Ljava/lang/String;Ljava/nio/charset/Charset;)Ljava/util/List;
  java.lang.NoSuchMethodError:org.apache.http.client.utils.URLEncodedUtils.parse(Ljava/lang/String;Ljava/nio/charset/Charset;)Ljava/util/List;

I have tried a lot of other combinations of methods and objects to get this request to send off to the server correctly and nothing seems to work. Hopefully I am overlooking something relatively simple.
Thanks in advance for any guidance you can provide.

A: You most likely have the wrong version or two versions of the apache httpcomponents on your classpath. If you are running Tapestry it will print out all packages on the classpath on the error page. Investigate there, find which httpcomponents is loaded, figure out where it comes from and fix it.
If this does not work, you should share some of your runtime environment with us. Which servlet engine, running from which IDE or are you running from the command line. Are you using Maven? If so share your pom. Etc.


text:
Q: How to install IIS Express 8 and SQL Server 2012 using WiX? I want to create an installer using WiX, which will install following pieces of software, if they aren't installed already:

*

*installs IIS Server Express 8.0

*SQL Server 2012 Express.

To do this, I created following Setup.wxs file:
<?xml version="1.0"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Product Id="*"
        Name="Your Application"
        Language="1033"
        Version="1.0.0.0"
        UpgradeCode="6431D91E-AD61-4FBB-A081-B63A0E416888"
        Manufacturer="Your Company">
        <Package Description="#Description"
            Comments="Comments"
            InstallerVersion="200"
            Compressed="yes"/>
        <!-- Installation directory and files are defined in Files.wxs -->
        <Directory Id="TARGETDIR" Name="SourceDir"/>

        <!--
            Using the Wix UI library.

            WixUI_Minimal is the most basic of the WixUI stock dialog sets.
            Its sole dialog combines the welcome and license-agreement
            dialogs and omits the feature customization dialog.
            WixUI_Minimal is appropriate when your product has no optional
            features.
        -->
        <UIRef Id="WixUI_Minimal"/>

        <Binary Id="Iis"
                SourceFile="D:\dev\wix-installer\ref\iis-8-express\iisexpress_8_0_RTM_x64_de-DE.msi" />

        <Binary Id="SqlServer"
                SourceFile="D:\dev\wix-installer\ref\sql-server-2012-express\SQLEXPR_x64_DEU.exe" />

    <CustomAction
        Id="InstallIis"
        Impersonate="no"
        Execute="deferred"
        BinaryKey="Iis"
        ExeCommand="D:\dev\wix-installer\ref\iis-8-express\iisexpress_8_0_RTM_x64_de-DE.msi"
        Return="asyncWait" />
    <CustomAction
        Id="InstallSqlServer"
        Impersonate="no"
        Execute="deferred"
        BinaryKey="SqlServer"
        ExeCommand="D:\dev\wix-installer\ref\sql-server-2012-express\SQLEXPR_x64_DEU.exe"
        Return="asyncWait" />

        <InstallExecuteSequence>
            <Custom Action="InstallIis" After="InstallInitialize"/>
            <Custom Action="InstallSqlServer" After="InstallIis"/>
        </InstallExecuteSequence>
    </Product>
</Wix>

The Files.wxs file contains following text:
<?xml version="1.0"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
</Wix>

When I run msiexec /l*v "log.txt" /i Installer.msi, I get a message that there was a failure during the installation. Here is the contents of the log.txt file.
How should I modify the WiX files in order for them to install IIS and SQL Server by executing the files iisexpress_8_0_RTM_x64_de-DE.msi and SQLEXPR_x64_DEU.exe?

redpajama_set_name: RedPajamaStackExchange


text: Q: Using iTunes gift code while temporarily staying in another country I am from Russia but currently stay in another country. I got an iTunes gift code as a present from a friend in Russia. Can I use this code while I'm in another country? I believe my Apple ID country is set to Russia.


text:
Q: Probability $\sum_{j=n+1}^{2n+1} {M \choose m+1}{M-m-1 \choose j-m-1}/{N \choose j} $ I have a prob. problem:
A school has $N$ students in which $M$ students are leader (of each class in school), and $N>M$.
There are $2n+1$ balls in the black box including $n+1$ blue balls and $n$ red balls (where $2n+1<M$).
The balls are randomly distributed to students in the school such that one student get only one (blue or red) ball.
1/ Given value $m$ ($m\le n$), what is the probability  $P_1$  that $M$ leaders take $m+1$ blue balls and at most $m$ red ones?
2/ What is the probability $P_2$ that $M$ leaders take the number of blue balls greater than red ones?
I already computed $P_1=\sum_{j=n+1}^{2n+1} {M \choose m+1}{M-m-1 \choose j-m-1}/{N \choose j} $ but not sure it's correct.
but not $P2$.
Can anyone help me to find out $P_1$? and also $P_2$? And could you give the simplification  and upper bound of them?
Thank you.

A: I think P1should be $P1 = \binom{M}{m+1}\sum ^m_{j=0} \binom{M-m-1}{j}$
$P2 = \sum ^n _{i=1} \binom{M}{i} \sum _{j=0} ^{j \lt i} \binom {M-i}{j}$


text:
Q: Convex sublevels of non-convex function
For a function to be quasi convex, the requirements are:

*

*The domain is convex.

*The sublevel sets are convex.

In my understanding, this function is not convex as it has a negative second derivative.
In the figure, the first condition is satisfied. Regarding the second condition, if we see the sublevel for $\beta$ i.e. $ S_\beta $ where $f(x)<\beta$, the section where the function has negative second derivative gets included. So why is the sublevel $ S_\beta $ considered as convex ?

A: It's not convex it's quasiconvex. A quasiconvex function means that the inverse image of any set of the form $(-\infty,a)$ is convex. Graphically this means the inverse image of all the points below $\beta$ must be convex and since it is the interval $(-\infty,c)$ the function is quasiconvex.


text:
Q: VBA Pivot Table not adding column to xlRowField and xlCount at the same time So when I manually create a pivot table where I just want to use one column and obtain the count of each unique value I'd add that column to the xlRowField and xlCount using the Excel UI.
With the manual approach I'd get something like this:
Values  | Count
-------------------
Value 1 | 20
Value 2 | 19
Value 3 | 5
-------------------
Grand Total | 44

This is a very simple process and works flawlessly. However, when I try to play back the exact recording with VBA the behaviour changes. Even after a few VBA modifications to simplify it the behaviour still differs from the manual process.
Instead of adding the column data to both xlRowField and xlCount as I had recorded manually it adds it to xlRowField, removes it, and adds it to xlCount leaving me with a table only displaying the grand total.
Count
-------------------
Grand Total | 44

I'm sure I'm not the only one running into this issue, but I don't really know how to phrase this question so I can find the solutions here on StackOverflow.
EDIT: While messing around with the code one last time before pasting it here I think I sorted it.
Code after a few edits but still essentially the same as the recorded VBA code was as follows.
Dim PT As PivotTable
Set PT = ActiveWorkbook.PivotCaches _
    .Create(SourceType:=xlDatabase, SourceData:="Sheet1"R1C1:R1048576C1", Version:=6) _
    .CreatePivotTable(TableDestination:="Sheet2!R1C1", TableName:="PivotTable1", DefaultVersion:=6)

Dim PF As PivotField

With PT
    Set PF .PivotFields("Values")
    PF.Orientation = xlRowField
    PF.Position = 1

    Set PF = .AddDataField(.Pivotfields("Values"), "Count of Values", xlCount)
    .InGridDropZones = True
    .RowAxislayout xlTabularRow
End With

The solution I found was just to reverse the order the fields were added to the pivot table. Add the xLcount field first and then the xlRowField.

A: Figured it out actually after randomly messing around with the VBA code a bit more. Kind of feels like it's more of a workaround, but at least it works.
Dim PT As PivotTable
Set PT = ActiveWorkbook.PivotCaches _
    .Create(SourceType:=xlDatabase, SourceData:="Sheet1"R1C1:R1048576C1", Version:=6) _
    .CreatePivotTable(TableDestination:="Sheet2!R1C1", TableName:="PivotTable1", DefaultVersion:=6)

Dim PF As PivotField

With PT
    Set PF = .AddDataField(.Pivotfields("Values"), "Count of Values", xlCount)
    .InGridDropZones = True
    .RowAxislayout xlTabularRow

    Set PF .PivotFields("Values")
    PF.Orientation = xlRowField
    PF.Position = 1
End With

Flipping the two fields within the 'With' block solved the issue. Don't entirely understand why though.


text:
Q: How do we draw abstract method in uml class diagram public abstract class Shape {
    abstract int area();
}

How do we draw the UML class diagram for the abstract method? Use +, - or #?
public class Room {
    int nWindows;
}

And what if the class instance variable doesn't have public, private or protected?

A: Abstract
According to UML specification:

The name of an abstract Classifier is shown in italics, where permitted by the font in use. Alternatively or in addition, an abstract Classifier may be shown using the textual annotation {abstract} after or below its name.

Note however that Operation is not a Classifier. It still has an isAbstract attribute as a BehavioralFeature but 2.5 specification does not define how to model the fact of being abstract. Older specifications (1.4.x) were using the same method as for Classifiers and it is a widely recognized method to show operation abstraction. Note only that the elements in curly brackets for features are presented at the end of line rather than just after the name (Classifier simply has no other specification directly after name).
Possibly authors made an omission in 2.5 specification for Feature abstraction notation by a mistake.
An abstract operation can of course have any visibility kind.
Of course the operation might be abstract only if its containing Classifier (Class in your case) is also abstract.
No visibility kind
In general visibility kind in UML is optional i.e. you can simply omit it. Just take into consideration that UML is a model so it actually can ignore some irrelevant elements or can specify them at a later stage of modelling. Not using any visibility kind in UML does not allow you to make any assumption about it's final visibility kind.
On the other hand if in actual code you use no visibility kind specification (if allowed at all) there is some default behaviour. For example

*

*in Java it's package (#) - in UML understanding, Java calls it "package-private",

*in C++ you'll end up with private feature (-),

*in PHP such features are treated as public (+)

and so on.


text:
Q: How do I prevent the tab from changing I am able to get into the function it calls the prevent and I return false but the tab still switches?  Any ideas of what I am doing wrong?

Template

Action

Scheduler

$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (event) {

  var isValidationValid = templateInstance.validateScreen();

  if(isValidationValid)
  {
    localStorage.setItem('activeTab', $(event.target).attr('href'));
    $(event.target).attr("href");
    return true;
  }
  else
  {

    event.preventDefault();
    return false;

  }

});

A: Ok it was really stupid I used shown instead of show now it is working...
 $(document).on('show.bs.tab', 'a[data-toggle="tab"]', function (event) {

        debugger;
        var isValidationValid = templateInstance.validateScreen();

        if(isValidationValid)
        {
            localStorage.setItem('activeTab', $(event.target).attr('href'));
            $(event.target).attr("href");
            return true;
        }
        else {

            event.preventDefault();
              return false;

        }

    });


text:
Q: Why Xtext doesn't recognize JavaFX properties? I started using JavaFX recently. Unfortunately I've been unable to use auto-complete in my css editor with XText.
My project was created using maven so I added JavaFX SDK to the class path.
I'm working on eclipse Luna 4.4 editing the css files with e(fx)clipse Css Editor.
How can I have Xtext working correctly while editing Css files in eclipse?

A: I had the same issue of being unable to get auto-complete with my JavaFX CSS. My fix was add the JavaFX SDK to the library list. To do that:

*

*Go to Project | Properties

*Select Java Build Path in the tree

*Click on the Libraries tab

*Click the Add Library... button

*Choose JavaFX SDK

*Click Next then Finish

*Click Apply

*Click OK

CSS editing worked after those steps.


text:
Q: componentDidCatch second parameter not type compatible with function being called from within I have a standard componentDidCatch in my component, which is typed like below and calls an external Logging library from within:
  componentDidCatch(error: Error, info: React.ErrorInfo) {
    Logger.logErrorMessage(error.message, info);
  }

However the 3rd party logging library logErrorMessage function is typed something like:
type ArbitraryValue = undefined | string | number | boolean | ArbitraryObject;

interface ArbitraryObject {
  [p: string]: ArbitraryValue;
}

...

logErrorMessage(message: string, info: ArbitraryObject): void;

The TS error message displays the following
.../ErrorBoundary.tsx:38:82 - error TS2345: Argument of type 'ErrorInfo' is not assignable to parameter of type 'ArbitraryObject'.
  Index signature is missing in type 'ErrorInfo'.

38     Logger.logErrorMessage(error, info);
                                     ~~~~

What is the best way to get my info parameter of componentDidCatch to adhere to the ArbitraryObject interface of logErrorMessage? Optimally without having to change the Logger library source.


text:
Q: Identify a device from UWP App & .NET Framework Windows Service Is there any value that identifies a system (windows 10 desktop device) which can be read both from a UWP app and from a Windows Service written in .NET Framework ?
I already considered:

*

*Computername > To unsecure and can be faked to easily

*ASHWID > Not available in .NET Framework

*Network Snapshot (Read all Network Adapter addresses and build a magic string) > Works but changes every time a network was switched

Any other identifier that is accessible from both worlds on a single system?
Background: The app consists of three components. A Windows Service, a UWP App and a cloud broker. On first connection, the service and the UWP App do a handshake over the cloud broker. For this initial handshake an identifier must be submitted so both can then exchange a secure token.
Any ideas?
Thanks


text:
Q: Django Heroku Server Error (500) when I set Debug - False. When Debug - True it is working good I get error 500 when debug = False. But when my debug = True it is workd fine.
My settings.py:
import os
from pathlib import Path
from decouple import config
import django_heroku

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ["*"]

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'main',
    'blog',
    'rest_framework',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware'
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],  # Before: 'DIRS': ['templates']
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': config('DB_NAME'),
        'USER': config('DB_USER'),
        'PASSWORD': config('DB_PASSWORD'),
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

django_heroku.settings(locals())

But when i try to put
django_heroku.settings(locals(), staticfiles=False)

it works fine on localhost but when i loaded it on heroku server it did not load css file, so i got just html code without css. So as far as i know it's a conflict between django staticfiles and heroku staticfiles but i dodn't know how to solve it.

A: To get started, pip install whitenoise. Then you need to add the configuration to the settings file:
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    .......
]

STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"


text:
Q: Vectors in three dimensions and two unknown components Given vector $\vec{v} = (\frac{1}{4}, \frac{1}{3}, a)$ and vector $\vec{w} = (1, b, -1)$, I am supposed to find a real number for a and b such that the two vectors $\vec{v}$ and $\vec{w}$ are orthogonal/perpendicular. I know that the dot product should equal 0, but how do I determine a and b from that?
It looks like to me that this question could have multiple solutions for a and b, but I cant find a simple method of determining this without guessing the numbers...

A: The usual inner product on $\mathbb{R}^{3}$ is given by:
$$\langle v, w \rangle := v_{1}w_{1}+v_{2}w_{2}+v_{3}w_{3}$$
where $v = (v_{1},v_{2},v_{3})$ and $w= (w_{1},w_{2},w_{3})$. In your case:
$$\langle v, w \rangle = \frac{1}{4}+\frac{b}{3}-a.$$
As you mentioned, in order to $v$ and $w$ to be orthogonal we must have:
$$\langle v, w \rangle = 0$$
so that any $a$ and $b$ satisfying:
$$\frac{1}{4}+\frac{b}{3}-a = 0$$
fulfills the condition. We have infinitely many answers and you can pick any of such solutions as the solution of your problem.


text:
Q: How to show opus number in main header and not in score headers? I'm trying to engrave a sonata in three movements. I want to indicate the opus number only in the main \header block, but not in each separate score \header block.
So far, I've only been able to achieve showing the opus number in the score \header block, but not in the main \header block.
Code:
\version "2.22.2"

\paper {
    #(define fonts
        (set-global-fonts
            #:roman "Bodoni* 06"
            #:music "beethoven"
            #:brace "beethoven"
        )
    )
    print-all-headers = ##t
}

\header {
    title = "S O N A T A."
    opus = "Op. 79"
    composer = "L. van Beethoven"
    tagline = ##f
}

\book {
    % MOVEMENT 1
    \score {
        \header {
            title = "I."
            subtitle = ##f
            composer = ##f
        }
        \new PianoStaff \with { instrumentName = \markup { \huge \bold "25." }} <<
            \new Staff = "up" \with {
                \consists "Merge_rests_engraver"
            } \relative c'' {
                \override Score.BarNumber.stencil = #(make-stencil-circler 0.1 0.25 ly:text-interface::print)
                \override Score.BarNumber.font-series = #'bold

                \clef treble
                \key g \major
                \time 3/4
                \tempo "Presto alla tedesca."

                <g g'>4\f-. <b b'>-. <g g'>-. \bar ".|:"

                <d' d'>2(c'8 b a g fis g b g)
                fis4(e) d8(c b a gis a c a)
                fis2 a4-. c-. a-. fis-.

                g8\f d cis d fis g a d, cis d g a
                b g fis g c d e d c b a g fis4\p r8_\markup{\italic{leggerimente}}
                d fis a d fis, a d fis a, d fis a d, fis a d fis, a d fis e d4 r8
            }

            \new Staff = "down" \with { \consists "Merge_rests_engraver" } \relative c {
                \clef bass
                \key g \major
                \time 3/4

                \repeat unfold 9 {
                    <g' b>8 d'
                }

                \repeat unfold 5 {
                    <g, c> e'
                }

                \repeat unfold 7 {
                    <g, a c> d'
                }

                <g, b>2.
                <fis, d' fis>
                <g d' g>2 <a a'>8 <b b'>
                <c c'>4 <c c'> <cis cis'>
            }
        >>

        \layout {}
    }
}

Result:
The "Op. 79" appears below the I. header, and not below the SONATA. header

How do I make sure that the opus number appears below the title of the whole piece, and not the title of the movement?

A: I'm not sure exactly what you want to do, but I would do something like this:
\version "2.22.2"

\paper {
    print-all-headers = ##t
}

\header {
    tagline = ##f
}

\book {
    % MOVEMENT 1
    \score {
        \header {
            title = "S O N A T A."
            opus = "Op. 79"
            composer = "L. van Beethoven"
            subtitle = "I."
        }
        { c'4 4 4 4 }
    }
    % MOVEMENT 2
    \score {
        \header {
            opus = ##f
            composer = ##f
            subtitle = "II."
        }
        { c'4 4 4 4 }
    }
}

Put everything in the first movement's header (I use subtitle here) and then only the subtitle in the subsequent movements.
(By the way, it's nice to have a minimal working example of the code you're working on when you post.)


text:
Q: ArrayAdapter getView() not being called I'm trying to populate a GridView from my android activity's layout using a custom ArrayAdapter in which I overrided getView(). When I run the app, the GridView shows up on the screen but completely empty. I've deduced that the issue is that getView() never gets called. I did check to see that the ArrayList was not empty. I used some log statements (similar to System.out.print() for those that aren't familiar with Android programming), and found that my ArrayList being passed to the adapter was not empty, however the getCount() method of my adapter always returned 0.  I've tried to look through some android source code to find when getView() is supposed to get called, which led to obtainView() and mObjects. It all seems pretty straight forward and I haven't found anything wrong.  Barring some sort of anti-miracle explanation, so far I've come up empty (likely due to me being an amateur programmer). Any help would be greatly appreciated.
Activity file:
import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.*;
import android.widget.*;

public class LevelMapActivity extends FragmentActivity implements View.OnClickListener{

    public final int TOTAL_LEVELS = 12;//TODO Set TOTAL_LEVELS to figure out how many levels exist.
    public final int COLUMNS = 5;

    GridView grid;
LevelSelectorAdapter adapter;
ArrayList<LevelSelector> levels;

@Override
public void onCreate(Bundle savedInstanceState){

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_level_map);

    grid = (GridView)findViewById(R.id.GridView_LevelMap);
    grid.setNumColumns(COLUMNS);

    levels = new ArrayList<LevelSelector>();

    for(int i=0; i<TOTAL_LEVELS/5; i++){
        for(int j=0; j<5; j++){
            LevelSelector levelSelector = new LevelSelector(this, i*COLUMNS+j+1);
            levels.add((i*COLUMNS)+j, levelSelector);
        }
    }
    for(int j=0; j<TOTAL_LEVELS%5; j++){
        LevelSelector levelSelector = new LevelSelector(this, TOTAL_LEVELS-(COLUMNS-1)+j);
        levels.add(j+TOTAL_LEVELS-COLUMNS, levelSelector);
    }

    adapter = new LevelSelectorAdapter(this, R.layout.level_selector, levels);
    grid.setAdapter(adapter);

}//ends onCreate()

@Override
public void onPause(){

    // TODO Auto-generated method stub
    super.onPause();

}//ends onPause()

@Override
public void onClick(View view){

    // TODO Auto-generated method stub

}//ends onClick()

}//ends Class

Adapter file:
import java.util.ArrayList;

import android.content.Context;
import android.util.Log;
import android.view.*;
import android.widget.*;

public class LevelSelectorAdapter extends ArrayAdapter<LevelSelector>{

Context context;
int resource;
ArrayList<LevelSelector> levelSelectors;

public LevelSelectorAdapter(Context context, int resource, ArrayList<LevelSelector> levelSelectors){

    super(context, resource);
    this.context = context;
    this.resource = resource;
    this.levelSelectors = levelSelectors;

}//ends LevelSelectorAdapter()

public static class ViewHolder{
    public TextView level;
    public TextView time;
}

@Override
public View getView(int position, View convertView, ViewGroup parent){

    View view = convertView;
    ViewHolder holder;

    if(view == null){
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(resource, null);
        holder = new ViewHolder();
        holder.level = (TextView)view.findViewById(R.id.TextView_LevelSelector_Level);
        holder.time = (TextView)view.findViewById(R.id.TextView_LevelSelector_Time);
        view.setTag(holder);
    }
    else{
        holder = (ViewHolder)view.getTag();
    }

    final LevelSelector levelSelector = levelSelectors.get(position);
    if(levelSelector != null){
        holder.level.setText(Integer.toString(levelSelector.getLevel()));
        holder.time.setText(Integer.toString(levelSelector.getTime()));
    }

    return view;

}//ends getView()

}//ends Class

A: Because of one of the way I had experimented with the adapter to try to override the getView() method, I had previously no need for the array passed to the adapter in its constructor.
Passing the array to the super constructor causes it to be initiated and therefore usable within the getCount() method. That's why getCount() came out to 0 each time, even though the array was not empty.


text:
Q: Replace Text in XML files with placeholder text I performed text mining on files that I am preparing for publication right now. There are several XML files that contain text within segments (see basic example below). Due to copyright restrictions, I have to make sure that the files that I am going to publish do not contain the whole text while someone who has the texts should be able to 'reconstruct' the files. To make sure that one can still perform basic text mining (= count lengths), the segment length should not change. Therefore I am looking for a way to replace every word except for the first and last one in all segments with dummy / placeholder text.
Basic example:
Input:
<text>

<seg xml:id="A">Lorem ipsum dolor sit amet</seg>
<seg xml:id="B">sed diam nonumy eirmod tempor invidunt</seg>

</text>

Output:
<text>

<seg xml:id="A">Lorem blank blank blank amet</seg>
<seg xml:id="B">sed blank blank blank blank invidunt</seg>

</text>

A: There is rapply to recursively replace values in a nested list:
Let be data.xml containing your input.
library(tidyverse)
library(xml2)

read_xml("data.xml") %>%
  as_list() %>%
  rapply(how = "replace", function(x) {
    tokens <-
      x %>%
      str_split(" ") %>%
      simplify()

    n_tokens <- length(tokens)

    c(
      tokens[[1]],
      rep("blank", n_tokens - 2),
      tokens[[n_tokens]]
    ) %>%
      paste0(collapse = " ")
  }) %>%
  as_xml_document() %>%
  write_xml("data2.xml")

Output file data2.xml:
<?xml version="1.0" encoding="UTF-8"?>
<text>

    <seg id="A">Lorem blank blank blank amet</seg>
    <seg id="B">sed blank blank blank blank invidunt</seg>

</text>


text:
Q: ng-show doesn't change on routeChange in AngularJS I am developing an website with AngularJS and
mobile angular UI.
I have a menu bar which will show on clicking a button and should be closed when I click the options in it. But it isn't working as expected.
My files:
index.html

         page1

js for hiding menu
app.controller('mainController', function ($rootScope, $scope) {

  $rootScope.showMenu = false;

  $rootScope.$on("$routeChangeStart", function () {
      $rootScope.showMenu = false;
  });

});

So while switching to some other file the menu should hide ideally. But it didn't happen so.

A: The problem is how you show your menu. With this code:

you change showMenu property of the child scope. This showMenu is not the same as $rootScope.showMenu. For this reason when you change $rootScope.showMenu in $routeChangeStart it doesn't effect child scope property. Instead you should do something like this:

and in controller:
$scope.toggleMenuBar = function() {
    $rootScope.showMenu = !$rootScope.showMenu;
};


text:
Q: I would like to import a csv with employees and create a hierarchy of the data I am attempting to create a powershell script that will import a csv that has employees in the following format.
ID,FirstName, LastName, Managers ID
1, John, Doe, 0 (is the top of hierarchy)
2, Jane, Doe, 1
45, Josh, Davis, 1
33, Steve, Clark, 2

my problem is, as the employees are in the csv they are not in order of the hierarchy. Is there a way to organize these people and export it to another csv file?

A: As already mentioned by @Kory Gill, you missing some constrains for a proper definition of your request (and they do not show from your example either), like:

*

*The Id and ManagerId column do not have to be in order
(or is a manager higher in the hierarchy always listed first?)

*There is no relation between ManagerId and the hierarchy level
(or has a manager higher in the hierarchy always a lower ManagerId?)

*The depth of the hierarchy is undefined (unlimited)
(I presume that the number of manager levels could always grow after a reorganization)

Presuming that the above constrains apply, the question gets more complex but also more challenging. To show this, I have set the Id of the the top manager John Doe to 11 and sorted the list accordingly, leaving the original hierarchy intact:
$Employees = ConvertFrom-Csv 'ID, FirstName, LastName, ManagerId
2, Jane, Doe, 11
11, John, Doe, 0
45, Josh, Davis, 11
33, Steve, Clark, 2'

Which this requirements, you might want to create a recursive function to figure out the manager of the manager (of the manager ... etc). Below is an example how you might tackel this:
Function Add-ManagerLevel([Object[]]$Employees) {

    Function Get-Level($ManagerId, [Int]$Level = 0) {               # 0 is the top of hierarchy
        $Manager = $Employees | Where-Object {$_.Id -eq $ManagerId}
        If (!$Manager) {$Level} Else {Get-Level $Manager.ManagerId ($Level + 1)}
    }

    $Employees | ForEach-Object {
        $_ | Add-Member "Level" (Get-Level $_.ManagerId) -PassThru
    }
}

note that the Get-Level help function calls itself to find out if a manager has a higher manager.
This will give the following output:
Add-ManagerLevel $Employees | Format-Table

ID FirstName LastName ManagerId Level
-- --------- -------- --------- -----
2  Jane      Doe      11            1
11 John      Doe      0             0
45 Josh      Davis    11            1
33 Steve     Clark    2             2

Which this result you can sort your list on hierarchy level, e.g.:
Add-ManagerLevel $Employees | Sort-Object Level | Format-Table

A: I agree with Kory Gill's comment.
However, making some assumptions. Do you mean something like this?
Clear-Host
(Import-Csv -Path 'E:\Temp\Employees.csv' |
Select-Object -Property 'Managers ID', ID, FirstName, LastName |
Group-Object -Property 'Managers ID' |
Sort-Object -Property  'Managers ID',ID) |
ForEach{
    "Processing GroupManagersID $($PSItem.Name)`t" + ('*')*20
    ForEach ($Staff in $PSItem)
    {
        $Staff.Group |
        Select-Object -Property ID, FirstName, LastName
    }
    "`n"
}

# Results

Processing GroupManagersID 0    ********************

ID FirstName LastName
-- --------- --------
1  John      Doe

Processing GroupManagersID 1    ********************
2  Jane      Doe
45 Josh      Davis

Processing GroupManagersID 2    ********************
33 Steve     Clark


text:
Q: C++ Inner Class Destructor Resource Management This appears similar to where I'm headed as well as this question.
Consider the following
template<typename T>
class A
{

private:

    class B
    {

    private:

        B* link;

    public:

        B();
       ~B();

    };

    B* head;

public:

    A();
   ~A();
};

The above creates the structure below assuming the function to create and link each B is declared and defined

If I perform the operation as shown above, then
B* position = head;
position = head->link;
head->link = nullptr;
delete[] head;
head = position;

I understand that calling the inner class destructor will result in the outer class destructor being called.  Have I correctly handled garbage collecting the resource x or have I done something undefined?

A: In the code provided the inner class will not call the outer class' destructor, nor should it, as the outer class only has a pointer to the inner class as a member.
There is no need for garbage collection if A is created with automatic storage duration (i.e. as a variable without new). It will be destroyed when it goes out of scope. The rule of thumb is that each new should have a matching delete.
To illustrate I've simplified the code, placed the node removal code in a member function and provided a simple example of its use:
struct A
{
    struct B
    {
        B* link;
    };
    B* head;
    void delete_head()
    {
        B* position = head;
        position = head->link;
        //head->link = nullptr; // not needed, it is being deleted anyway
        delete head; // not delete[]! This isn't an array pointer
        head = position;
    }
};

int main()
{
    A a;
    a.head = new A::B; // create head node
    a.head->link = new A::B; // create node
    a.delete_head(); // call A::~B()
    a.delete_head(); // call A::~B()
    // no more nodes in a, but A's destructor is not yet called
} // A::~A() is called here


text:
Q: Convergent or Divergent Series? $\sum\limits_{n=1}^{\infty} \frac{(-1)^{n+1}}{\sqrt[n+1]{10}}$ I need to find whether this series is convergent or divergent:
$$
\sum_{n = 1}^{\infty}\frac{\left(-1\right)^{ n + 1}}
{\,\sqrt[n + 1]{\, 10\, }\, }
$$
(1) Alternating series test does not provide any additional information since $\lim_{n \to \infty} \frac{1}{\sqrt[n+1]{10}} = 1$ and not $0$. A ratio test with its larger series $\sum\limits_{n=1}^{\infty} \frac{1}{\sqrt[n+1]{10}}$ results in $1$ meaning its inconclusive. Can someone guide me in the right direction?

A: The general term of the series is not converging to $0$: as you mentioned it, its absolute value converges to one.
Therefore the series diverges.

A: An explicit, crude bound on the terms.
If
$(1+a)^{1/n} = 1+b$,
then,
by Bernoulli's inequality,
$1+a
=(1+b)^n
\ge 1+nb
$
so
$b
\le a/n
$
so
$(1+a)^{1/n}
\le 1+a/n
$.
Therefore
$\dfrac1{(1+a)^{1/n}}
\ge \dfrac1{1+a/n}
=\dfrac{n}{n+a}
=1-\dfrac{a}{n+a}
\to 1
$
as
$n \to \infty$.
In this case,
$\dfrac1{10^{1/n}}
\ge 1-\dfrac{9}{n+9}
$.


text:
Q: Indistinguishable Continuous Version of Martingale Assume a filtered probability space, where the filtration is the augmented filtration generated by a Brownian motion.
More precisely, define the set
$$
\mathcal{N} = \{ A \subset \Omega \mid \exists B \in \mathcal{F} : P(B) = 0, A \subset B \}
$$
Then define
$$
\mathcal{F}_t = \sigma( \mathcal{N}, W_s , 0 \leq s \leq t ), \quad t \in [0,T]. $$
Let $M = (M_t)_{t \in [0,T]}$ be a square integrable martingale. Then, we can choose a cadlag modification $\tilde{M}$ of $M.$ By the martingale representation theorem $\tilde{M}$ is continuous up to indistinguishability.
Does it follow that $M$ is continuous up to indistinguishability?


text:
Q: Share Internet throught network interfaces ok so i'm working in VMWare and have 2 virtual machines (Ubuntu and Windows 7). The Ubuntu machine has 2 network interfaces (eth0 & eht1), the eth0 interface is using NAT to connect to the internet through my real computer and the eth1 interface is using host-only to connect to the Windows machine. The windows machine only has one interface using host-only.
What i'm trying to do is share internet to the windows machine through the interfaces. I've tried the following commands but can't get it to work.
sudo iptables --flush
sudo iptables -A INPUT -i eth1 -j ACCEPT
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Any help is greatly appreciated. Thanks

A: You must enable IP forwarding in your Linux guest.
In /etc/sysctl.conf put this:
net.ipv4.ip_forward = 1
Then issue this command:
sysctl -w
It should echo back the same line you put in the file.
Check if it was properly enabled:
sysctl net.ipv4.ip_forward
Should output 1 if enabled and 0 if disabled.
If required restart the networking service for changes to take effect.


text:
Q: Interpreting cost change plot in a neural network for learning XOR I tried to build a neural net for learning XOR. The design is as follows:
1st layer: compute linear function of input 4:2 with 2:2 weights and adding 1:2 bias.
2nd layer: apply sigmoid to all elements in 4:2 matrix from layer 1.
3rd layer: compute linear function of the 2nd layer's output with 2:1 weights
final layer: apply sigmoid to 4:1 vector from the previous layer
The model converges well after as much as 1,000,000 of iterations (I don't know if it's too big of a number for such a simple problem.
I get the following plot (X - iterations, Y - cost). It seems a little bit strange. Why it stays on the same cost value for so long? Could anyone explain is it a normal graph for such a problem and is anything wrong with my setup that causes such cost behavior? Thanks

A: Gradient descent isn't a great optimizer. It's not unusual for GD to reach a plateau of very slow progress before finding a good descent direction again.
See this post for a comparison of GD and Levenberg-Marquardt for a simple linear regression network with poor conditioning.

*

*Can we apply analyticity of a neural network to improve upon gradient descent?
See this post for an explanation of why poor conditioning makes gradient descent challenging.

*

*For convex problems, does gradient in Stochastic Gradient Descent (SGD) always point at the global extreme value?
In the case of this particular task, it's true that a small, single-layer network with sigmoid neurons can solve the XOR task. However, there's a difference between the theoretical possibility of solving a task and whether or not it's practical to train a network to do so. One reason that networks are wider and deeper and use tricks like residual layers, batch norm, sophisticated optimizers and ReLUs is to make these networks easier to train using gradient descent.


text:
Q: how to get to .error in $httppost in angular I have this MVC controller post action
 [HttpPost]
 public JsonResult RunEventService(EventService data){
     System.Threading.Thread.Sleep(5000);
     var resp = new StatusMessages();
     try {
         if (!string.IsNullOrEmpty(data.ServiceName)) {
             resp.success = true;
             resp.Message = string.Format("The service source - {0} has been created successfully", data.ServiceName);
         }
         else {
             resp.success = false;
             resp.Message = "Please enter the name of the service that you want to create.";
         }
     }
     catch (Exception ex) {
         resp.success = false;
         resp.Message = ex.Message;
         resp.DetailedError = ex.StackTrace;
     }
     return Json(resp);
 }

and this status message class
public class StatusMessages {
    public bool success { get; set; }
    public string ErrorMessage { get; set; }
    public string DetailedError { get; set; }
    public string Message { get; set; }
}

I am calling the http post through this code
var url = applicationRoot + "Ad/Service";
$http.post(url, JSON.stringify($scope.dataErrorService)).success(function (data) {
    $scope.ServiceMessage = data.Message;
    $(".ServiceMessage").attr("class", "ServiceMessage");
}).error(function (data, status, headers, config) {
    $(".ServiceMessageError").attr("class", "ServiceMessageError");
});

How would my code execute the .error section when the resp.success = false; is valid? It is always going to the use .success method.
I can read the status message in the success and do stuff accordingly, but I want to know what can call the .error function.  Am I doing things the correct way?

A: You need to change a status code in answer from server.
If code eq 200 (OK), then calls a success method.
You need to send an error code (500 for example)

A: You can use the $q for this.
Example:
var url = applicationRoot + "Ad/Service";

var deferred = $q.defer();

$http.post(url).success(function(response) {
    if (!response.success)
        deferred.reject(response.data);
    else
        deferred.resolve(response.data);
}).error(function(error) {
    console.error(error);
    deferred.reject(error);
});

return deferred.promise;


text:
Q: Intuition behind the Monte carlo method Addendum
Thanks to Schrodinger's cat answer, I'm now able to produce the graph below. It shows that if you don't want to underestimate low probability events for further simulations, you really need to simulate loads of uniform numbers...

Original question
I'd like to show graphically the intuition of the Monte Carlo method. The idea is the more random numbers you use, the more the simulated distributions below are populated. Once you reach a number large enough (500? 1000? more ?), these simulated distributions don't present any "hole" and can be used to simulate other processes.

The marks are each initial random number projected first horizontally on the cumulative and then projected vertically on the density. I used 40 random numbers in this example and highlighted 4 colored points just to show the projection sequence.
So far

*

*I have the random numbers between [0,1]

*I('d like to) project them on the y axis of the Cumulative normal distribution

*which corresponds to a point on the normal density.

MWE does not connect the dots and does not make correspond the random numbers and their projections on the graphs.
Probably because I need the inverse normal cumulative but based on Equation 8 at https://core.ac.uk/download/pdf/41787448.pdf gives a simple expression for the best logistic fit for the cumulative normal distribution:
$\phi(z) \approx \frac{1}{(1 + e^{-1.702z})}$  %% (i use a more accurate one in MWE but it'd be sufficient for the example. The  inverse :  $z(\phi) \approx - \frac{ln (\frac{1}{\phi}-1)}{1.702}$
Here is MWE so far, Based on pedagogic-graph-of-lognormal-distribution
\documentclass{standalone}
\usepackage{tikz}

\usepackage{pgfplots}
\usepgfplotslibrary{groupplots,fillbetween}

\def\m{0}
\def\SIG{1}
\def\NumRand{50}

\begin{document}
\begin{tikzpicture}[declare function={
g(\x)= 1/(sqrt(2*pi))*exp(-0.5*(pow((\x-\m),2))/(2*\SIG^2));
h(\x)=1/(1 + exp(-0.07056*((\x-\m)/\SIG)^3 - 1.5976*(\x-\m)/\SIG));
}]

\begin{groupplot}[group style={
            group size=2 by 2, horizontal sep=0pt, vertical sep=0pt,
            xticklabels at=edge bottom},  legend pos=south east,
%       grid=both
        ]
        \nextgroupplot[group/empty plot]

        %---- top right    -------------------
        \nextgroupplot[]
        \addplot[name path=BL1,only marks,very thick,color=red,domain=-4:4,samples=\NumRand] ({x},{g(x)});
        \addlegendentry{$\mathcal{N}(0,1)$}

        %----  bottom left  -------------------
        \nextgroupplot
        \addplot+[only marks,fill=blue!60, opacity= 0.5, samples=\NumRand,domain=-0.1:0.1] (0,rnd);
        \addlegendentry{Uniform random numbers}
        %----  bottom right    -------------------
        \nextgroupplot[]
        \addplot[name path=BR1,only marks, color=red!50, domain=-4:4, samples=\NumRand] ({x},{h(x)});
        \addlegendentry{Normal cumulative}
        \end{groupplot}

\end{tikzpicture}
\end{document}

The accuracy of the  cumulative normal expression is discussed at length in the referenced article.  There are more accurate expressions there, but they're not quite so easy to invert and require more computational overhead.  This one can be used for coding purposes where you want to generate "random" samples from a normal distribution

A: EDIT: You may be asking for this:
\documentclass[tikz,border=3mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}
\usepgfplotslibrary{groupplots}
\begin{document}
\begin{tikzpicture}[declare function={
g(\x,\m,\SIG)= 1/(sqrt(2*pi))*exp(-0.5*(pow((\x-\m),2))/(2*\SIG^2));
h(\x,\m,\SIG)=1/(1 + exp(-0.07056*((\x-\m)/\SIG)^3 - 1.5976*(\x-\m)/\SIG));
phi(\z)=1/(1+exp(-1.702*\z));
z(\phi)=-ln((1-\phi)/\phi)/1.702;
}]
\edef\m{0}
\edef\SIG{1}
\edef\NumRand{50}
\newcommand\RandDist[1]{\edef\irun{0}%
\pgfmathsetmacro{\mysum}{0}%
\edef\lstcoords{}%
\edef\lstcm{}%
\edef\lstgf{}%
\loop
\pgfmathsetmacro{\myrnd}{rnd}%
\pgfmathsetmacro{\mysum}{\mysum+\myrnd}%
\edef\lstcoords{\lstcoords (#1,\myrnd)}%
\pgfmathsetmacro{\myz}{z(\myrnd)}%
\edef\lstcm{\lstcm (\myz,\myrnd)}%
\pgfmathsetmacro{\myg}{g(\myz,\m,\SIG)}%
\edef\lstgf{\lstgf (\myz,\myg)}%
\edef\irun{\the\numexpr\irun+1}%
\ifnum\irun<\NumRand\relax
\repeat
}
\RandDist{0}
\begin{groupplot}[group style={
            group size=2 by 2, horizontal sep=0pt, vertical sep=0pt,
            xticklabels at=edge bottom},  legend pos=south east,
%       grid=both
        ]
        \nextgroupplot[group/empty plot]

        %---- top right    -------------------
        \nextgroupplot[]
        \addplot[forget plot,very thick,color=red,domain=-4:4,samples=\NumRand+1] ({x},{g(x,\m,\SIG)});
        \addplot[only marks,very thick,color=red]
         coordinates {\lstgf};
        \addlegendentry{$\mathcal{N}(0,1)$}

        %----  bottom left  -------------------
        \nextgroupplot
        \addplot+[only marks,fill=blue!60, opacity= 0.5]
            coordinates {\lstcoords};
        \addlegendentry{Uniform random numbers}
        %----  bottom right    -------------------
        \nextgroupplot[]
        \addplot[forget plot,very thick,color=red, domain=-4:4, samples=\NumRand+1] ({x},{h(x,\m,\SIG)});
        %\addplot[orange, domain=-4:4,]({x},{phi(x)});
        \addplot[only marks,fill=red!50]  coordinates {\lstcm};
        \addlegendentry{Normal cumulative}
        \end{groupplot}

\end{tikzpicture}
\end{document}

You can animate it.
\documentclass[tikz,border=3mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}
\usepgfplotslibrary{groupplots}
\tikzset{declare function={
g(\x,\m,\SIG)= 1/(sqrt(2*pi))*exp(-0.5*(pow((\x-\m),2))/(2*\SIG^2));
h(\x,\m,\SIG)=1/(1 + exp(-0.07056*((\x-\m)/\SIG)^3 - 1.5976*(\x-\m)/\SIG));
phi(\z)=1/(1+exp(-1.702*\z));
z(\phi)=-ln((1-\phi)/\phi)/1.702;
}}
\begin{document}
\begingroup
\edef\m{0}
\edef\SIG{1}
\edef\NumRand{50}
\newcommand\RandDist[1]{\edef\irun{0}%
\pgfmathsetmacro{\mysum}{0}%
\edef\lstcoords{}%
\edef\lstcm{}%
\edef\lstgf{}%
\loop
\pgfmathsetmacro{\myrnd}{rnd}%
\pgfmathsetmacro{\mysum}{\mysum+\myrnd}%
\edef\lstcoords{\lstcoords (#1,\myrnd)}%
\pgfmathsetmacro{\myz}{z(\myrnd)}%
\edef\lstcm{\lstcm (\myz,\myrnd)}%
\pgfmathsetmacro{\myg}{g(\myz,\m,\SIG)}%
\edef\lstgf{\lstgf (\myz,\myg)}%
\edef\irun{\the\numexpr\irun+1}%
\ifnum\irun<\NumRand\relax
\repeat
}
\RandDist{0}
\pgfplotsinvokeforeach{1,...,\NumRand}{\begin{tikzpicture}
\begin{groupplot}[group style={
            group size=2 by 2, horizontal sep=0pt, vertical sep=0pt,
            xticklabels at=edge bottom},  legend pos=south east,
%       grid=both
        ]
        \nextgroupplot[group/empty plot]

        %---- top right    -------------------
        \nextgroupplot[]
        \addplot[forget plot,very thick,color=red,domain=-4:4,samples=\NumRand+1] ({x},{g(x,\m,\SIG)});
        \addplot[only marks,very thick,color=red,
            x filter/.expression={(\coordindex >#1 ? nan : x)}]
         coordinates {\lstgf};
        \addlegendentry{$\mathcal{N}(0,1)$}

        %----  bottom left  -------------------
        \nextgroupplot
        \addplot+[only marks,fill=blue!60, opacity= 0.5,
            x filter/.expression={(\coordindex >#1 ? nan : x)}]
            coordinates {\lstcoords};
        \addlegendentry{Uniform random numbers}
        %----  bottom right    -------------------
        \nextgroupplot[]
        \addplot[forget plot,very thick,color=red, domain=-4:4, samples=\NumRand+1] ({x},{h(x,\m,\SIG)});
        %\addplot[orange, domain=-4:4,]({x},{phi(x)});
        \addplot[only marks,fill=red!50,
            x filter/.expression={(\coordindex >#1 ? nan : x)}]  coordinates {\lstcm};
        \addlegendentry{Normal cumulative}
        \end{groupplot}
\end{tikzpicture}}
\endgroup
\end{document}

However, I am not sure about the interpretation.
ORIGINAL ANSWER: This may be missing the whole point of this exercise. All this does is to generate a set of random distributions of points, computes their averages and plots the distribution of averages. And it varies the number of sets in an animation.
\documentclass[tikz,border=3mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}
\usepgfplotslibrary{groupplots,fillbetween}
\begin{document}
\foreach \X in {4,8,...,80}
{\begin{tikzpicture}
\edef\NumRand{50}
\edef\NumSamples{\X}
\edef\NumBins{25}
\edef\irun{0}%
\loop
\expandafter\edef\csname NumBin\irun\endcsname{0}%
\edef\irun{\the\numexpr\irun+1}%
\ifnum\irun<\NumBins\relax
\repeat
\newcommand\RandDist[1]{\edef\irun{0}%
\pgfmathsetmacro{\mysum}{0}%
\edef\lstcoords{}%
\loop
\pgfmathsetmacro{\myrnd}{rnd}%
\pgfmathsetmacro{\mysum}{\mysum+\myrnd}%
\edef\lstcoords{\lstcoords (##1,\myrnd)}%
\edef\irun{\the\numexpr\irun+1}%
\ifnum\irun<\NumRand\relax
\repeat
}
\pgfplotsforeachungrouped\isample in{0,...,\the\numexpr\NumSamples-1}
{\pgfmathsetmacro{\xsample}{2*\isample/\NumSamples-1}%
\RandDist{\xsample}%
\expandafter\edef\csname lstpst\isample\endcsname{\lstcoords}%
\pgfmathsetmacro{\avg}{\mysum/\NumRand}%
\expandafter\edef\csname avg\isample\endcsname{(\xsample,\avg)}%
\pgfmathtruncatemacro{\nBin}{25*\avg}%
\edef\currbin{\csname NumBin\nBin\endcsname}%
\expandafter\edef\csname NumBin\nBin\endcsname{\the\numexpr\currbin+1}%
}
\edef\lstbars{}%
\edef\irun{0}%
\loop
\edef\lstbars{\lstbars (\irun,\csname NumBin\irun\endcsname)}%
\edef\irun{\the\numexpr\irun+1}%
\ifnum\irun<\NumBins\relax
\repeat
%\typeout{\lstcoords,\mysum,\lstbars}
\begin{groupplot}[group style={
            group size=2 by 2, horizontal sep=2em, vertical sep=0pt,
            xticklabels at=edge bottom},  legend pos=south east,
%       grid=both
        ]
        \nextgroupplot[title=samples]
        \edef\temp{\noexpand\addplot[only marks,mark=*,fill=blue!60, opacity= 0.5]
        coordinates {\csname lstpst0\endcsname};
        \noexpand\addlegendentry{samples}
        \noexpand\addplot[only marks,mark=square*,fill=red!60]
        coordinates {\csname avg0\endcsname};
        \noexpand\addlegendentry{average}}
        \temp
        \pgfplotsinvokeforeach{1,...,\the\numexpr\NumSamples-1}
        {\edef\temp{\noexpand\addplot[forget plot,only marks,mark=*,fill=blue!60, opacity= 0.5]
        coordinates {\csname lstpst##1\endcsname};
        \noexpand\addplot[forget plot,only marks,mark=square*,fill=red!60]
        coordinates {\csname avg##1\endcsname};}
        \temp}
%        \addlegendentry{Uniform random numbers}
        %---- top right    -------------------
        \nextgroupplot[title=distribution of averages,
            xtick={0,...,\NumBins},xticklabel=\empty]
        \addplot[ybar,bar width=pi*1pt,fill=blue] coordinates{\lstbars};
        %----  bottom left  -------------------
        \end{groupplot}

\end{tikzpicture}}
\end{document}


text:
Q: stopping a long poll with rxjava in android I am doing a long poll to an API from an android client using retrofit and rxjava. In this case, we wait for a 200 or 408 timeout response from an API and handle the response or reconnect to wait again for more data. This works just fine. I need to stop rx from retrying on certain error codes (like a 500) or if I want to interrupt the process, for example my app was background so let's stop the long poll.
 retrofitInterface.startPolling()  //returns an Observable
                    .repeat()
                    .retry()
                    .subscribe(new Subscriber<List<Stuff>>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(List<Stuff> updates) {
                             //process stuff
                            }

                        }
                    });

I'm not sure if repeatWhen and retryWhen is the right solution here, where I want to keep repeating and retrying http calls to the API but stop repeating in some condition (say I flip a bool in the class to false) or stop retrying if the status code is a 500 instead of say a 408.

A: It's easier if you wrap your request answer in object of type <Response<?>>, this gives you control over the error code.
What I did for that use case is throwing a specific exception when I have some specific error code:
public <T> T throwExceptionIfFailure(T res) {
    Response result = (Response<?>) res;
    if (!result.isSuccessful()) {
        try {
            String msg = result.errorBody().string();
            if (result.code() == 401 || result.code() == 403) {
                invalidateToken();
                msg = context.getString(R.string.invalid_credential);
            } else if (result.code() == 502) {
                msg = context.getString(R.string.server_down);
            }

            throw Exceptions.propagate(new IOException(msg));
        } catch (Throwable e) {
            throw Exceptions.propagate(e);
        }
    } else {
        return res;
    }
}

and I added this method in a map function of RX:
    serviceRetrofit.getContacts()
            .map(result -> serviceRetrofit.throwExceptionIfFailure(result))
            .map(result -> createOrUpdateContact(result))
            .retry(4)
            .onErrorReturn(error -> handleErrorEvent(error))
            .doOnCompleted(() -> emitStoreChange(new Store.StoreChangeEvent()))
            .subscribe();


text:
Q: How return a multidimensional arrayList in java? I want to create a multidimensional array and pass it as a parameter in a method and then fill the arrayList with elements and return the new version of the arrayList to be able to use that array in different classes but I get java.lang.NoSuchMethodError: I think the problem is about the way i return the array. I searched but I could not find . How can I do it correctly?
here is my code;
public test{

 public static List<List<String>> 2Darray=new ArrayList<List<String>>(); // TE ERROR IN THIS LINE

 public List<List<String>> fillArray(List<List<String>> array){

BufferedReader in = null;
            ArrayList<String> row = new ArrayList<String>();
            try {
                in = new BufferedReader(new FileReader("sampleFile.txt"));
                String read = null;
                    while ((read = in.readLine()) != null) {
                        String[] splited = read.split("\\s+");
                        for(int i=0; i<splited.length ; i++){
                            row.add(splited[i]);
                        }
                        array.add(row);
                    }

                } catch (IOException e) {
                System.out.println("There was a problem: " + e);
                e.printStackTrace();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                }
      return array;
}

A: A little tinkering (just getting it to compile) results in this which seems not to have a problem. Perhaps your issue is elsewhere.
public List<List<String>> fillArray(List<List<String>> array) {

    BufferedReader in = null;
    ArrayList<String> row = new ArrayList<String>();
    try {
        in = new BufferedReader(new FileReader("sampleFile.txt"));
        String read = null;
        while ((read = in.readLine()) != null) {
            String[] splited = read.split("\\s+");
            for (int i = 0; i < splited.length; i++) {
                row.add(splited[i]);
            }
            array.add(row);
        }

    } catch (IOException e) {
        System.out.println("There was a problem: " + e);
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return array;
}

BTW: You should really use try with resources - it is much clearer.

A: Modified your code a bit so that it compiled, and replaced the reading from a text file to reading a string. There were several issues, but it seems to work. Give it a try.
The main problems I noticed were mismatching curly braces, and starting a variable name with a number.
import java.util.*;
import java.io.*;

public class Main {
  public static List<List<String>> array2D = new ArrayList<List<String>>();

  public List<List<String>> fillArray(List<List<String>> array) {

    BufferedReader in = null;
    ArrayList<String> row = new ArrayList<String>();
    try {
      String str = "Some test text";
      InputStream is = new ByteArrayInputStream(str.getBytes());
      //in = new BufferedReader(new FileReader("sampleFile.txt"));
      in = new BufferedReader(new InputStreamReader(is));
      String read = null;
      while ((read = in.readLine()) != null) {
        String[] splited = read.split("\\s+");
        for(int i=0; i<splited.length ; i++) {
            row.add(splited[i]);
        }
        array.add(row);
      }

    }
    catch (IOException e) {
      System.out.println("There was a problem: " + e);
      e.printStackTrace();
    }
    finally {
      try {
        in.close();
      }
      catch (IOException e) {
      }
    }
    return array;
  }

  public static void main(String[] args) {
    Main main = new Main();
    List<List<String>> test = main.fillArray(array2D);

    for(int i  = 0; i < test.size(); i++) {
      for(int j = 0; j < test.get(i).size(); j++) {
        System.out.println(test.get(i).get(j));
      }
    }
  }
}


text:
Q: Unable to perform operation "make branch" in replica  of vob We recently changed mastership of a stream from one site (inh) to another(ies).  Things were fine till following error.
Now a delivery from child branch to the "moved branch" results in error. Not all merges are problematic. Select directories (or I think so) are not merging.
  Unable to perform operation "make branch" in replica "interfaces_src_ies" of VOB "\interfaces_src".
    Master replica of branch type "project_subset_QPE-5060" is "interfaces_src.inh".
    There is no candidate version which can be checked out.
    Unable to check out "M:\dyn_project_subset\interfaces_src\src\java\src\chs\cof\project".

How can I fix this?  How can  I change mastership of  "branch type "project_subset_QPE-5060  to interfaces_src.ies

A: That should mean, as detailed in the IBM technote swg21142784, that the mastership transfer was incomplete.
That can happen when there was a checked out file at the time of the transfer.
Make sure there is no checked out files (on both sites), and try and transfer the mastership again (even if it says it is already transferred)
Or, as described in the technote, try and create the branch on the other site, and create a synchronization packet from the mastering site using multitool syncreplica -export so the site where the element creation is going to happen receives the mkbranch operation.
You see that kind of operation in IBM technote swg21118471.
On Windows, this setting can also help preventing this situation:
cleardlg.exe/options/Operations tab/Advanced Options:
When creating an element in a replicated VOB,
make current replica the master of all newly created branches.

A: I also had this exact issue when trying to checkout a file to modify.
I was able to create a view, but when I tried to checkout a file it kept complaining about:
Error checking out '<file>'.
Unable to perform operation "make branch" in replica "<branch>" of VOB "<vob>".
Master replica of branch type "<type>" is "<X>"
Unable to check out "<file>"

This was fixed by changing the ClearCase Registry Server to the correct host, and then re-creating the View.


text:
Q: Angular material: SassError: Invalid CSS after "@include mat": expected 1 selector or at-rule, was ".core();" Angular version : 12
npm : 6.13.1
node :12.14.1
Getting below error when building the application.

  /src/abc.scss - Error: Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
[1] ModuleBuildError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
[1] SassError: Invalid CSS after "@include mat": expected 1 selector or at-rule, was ".core();"
[1]         on line 8 of src/mv-app-theme.scss
[1] >> @include mat.core();
[1]    ---------^
[1]
[1]     at processResult (D:\project\node_modules\webpack\lib\NormalModule.js:676:19)
[1]     at D:\project\node_modules\webpack\lib\NormalModule.js:778:5
[1]     at D:\project\node_modules\loader-runner\lib\LoaderRunner.js:399:11
[1]     at D:\project\node_modules\loader-runner\lib\LoaderRunner.js:251:18
[1]     at context.callback (D:\project\node_modules\loader-runner\lib\LoaderRunner.js:124:13)
[1]     at Object.callback (D:\project\node_modules\sass-loader\dist\index.js:54:7)
[1]     at Object.done [as callback] (D:\project\node_modules\neo-async\async.js:8069:18)
[1]     at options.error (D:\project\node_modules\node-sass\lib\index.js:294:32)

Then I removed node-sass, now getting different error, Any idea?

 (node:19948) UnhandledPromiseRejectionWarning: TypeError: MessagePort was found in message but not listed in transferList
[1]     at new Worker (internal/worker.js:144:17)
[1]     at SassWorkerImplementation.createWorker (D:\project\node_modules\@angular-devkit\build-angular\src\sass\sass-service.js:96:24)
[1]     at SassWorkerImplementation.render (D:\project\node_modules\@angular-devkit\build-angular\src\sass\sass-service.js:62:40)
    at Object.loader (D:\project\node_modules\sass-loader\dist\index.js:46:3)

A: Found the answer
If we are upgrading Angular to 12 , node version should not be below 12.20
Got answer from this post
Getting error while running "ng serve" for my first angular application


text:
Q: get list of ruby gems in bash I am really new to ruby and just trying to get a list of gems with their details as a csv file. My preference is writing a bash script for that and not using any ruby script file. I know that I can use gem list -d but I don't know any easy way to parse the output. The other way that I could think, is using something like
ruby -e 'Gem.loaded_specs.each { |name, spec| printf "%s,%s,%s,%s,\"%s\"\n", name, spec.version, spec.summary, spec.homepage, spec.licenses[0] }'

but it is just returning one line. I would appreciate any help.


text:
Q: iPhone SDK, selection Rectangle around a view I have a Drawing app of sorts and am looking for some feedback on ways to draw a selection rectangle, and or the resize grips for a selected view.
So I have a custom class that is inherited from UIView, in it it contains a UIImageView, UILabel, and UIButton. I can have several on the screen at one time.  I want to tap on one and draw a selection rectangle around it. From there if i drag I want the view and the selection rectangle to move with it. I would like the Selection Rectangle maybe 4px larger than the exiting bounds rect.
So my question is what is the best way to get the Selection Rectangle around the selected UIView object?
Do I offset the object so what when I add in the UIImageView, UILabel, and UIButton that are part of it I have a 4px buffer around the edges?
Do I adjust the View when selected to reposition the subview, increase the bounds and offset the frame?
Do I just create a new UIView that is 4px larger than the selected object and just move it with the selected view?
Do I just create a new UIView that is 4px larger than the selected object and and make the selected view a subview of it?
or?  (your Idea Here...)
Thank you for your comments and Suggestions...
Scooter133

A: Consider setting the borderWidth property on your view's layer.  Note that this is drawn within the view's bounds, so it may be more useful as a highlight state than a selection rectangle.


text:
Q: Issues converting Keras code into PyTorch code (shaping) I have some keras code that I need to convert to Pytorch. I am new to pytorch and I am having trouble wrapping my head around how to take in input the same way that I did in keras. I have spent many hours on this any tips or help is very appreciated.
Here is the keras code I am dealing with. The input shape is (5000,1)
    def build(input_shape, classes):
        model = Sequential()

        filter_num = ['None',32,64,128,256]
        kernel_size = ['None',8,8,8,8]
        conv_stride_size = ['None',1,1,1,1]
        pool_stride_size = ['None',4,4,4,4]
        pool_size = ['None',8,8,8,8]

        # Block1
        model.add(Conv1D(filters=filter_num[1], kernel_size=kernel_size[1], input_shape=input_shape,
                         strides=conv_stride_size[1], padding='same',
                         name='block1_conv1'))
        model.add(BatchNormalization(axis=-1))
        model.add(ELU(alpha=1.0, name='block1_adv_act1'))
        model.add(Conv1D(filters=filter_num[1], kernel_size=kernel_size[1],
                         strides=conv_stride_size[1], padding='same',
                         name='block1_conv2'))
        model.add(BatchNormalization(axis=-1))
        model.add(ELU(alpha=1.0, name='block1_adv_act2'))
        model.add(MaxPooling1D(pool_size=pool_size[1], strides=pool_stride_size[1],
                               padding='same', name='block1_pool'))
        model.add(Dropout(0.1, name='block1_dropout'))

        # Block 2
        model.add(Conv1D(filters=filter_num[2], kernel_size=kernel_size[2],
                         strides=conv_stride_size[2], padding='same',
                         name='block2_conv1'))
        model.add(BatchNormalization())
        model.add(Activation('relu', name='block2_act1'))

        model.add(Conv1D(filters=filter_num[2], kernel_size=kernel_size[2],
                         strides=conv_stride_size[2], padding='same',
                         name='block2_conv2'))
        model.add(BatchNormalization())
        model.add(Activation('relu', name='block2_act2'))
        model.add(MaxPooling1D(pool_size=pool_size[2], strides=pool_stride_size[3],
                               padding='same', name='block2_pool'))
        model.add(Dropout(0.1, name='block2_dropout'))

        # Block 3
        model.add(Conv1D(filters=filter_num[3], kernel_size=kernel_size[3],
                         strides=conv_stride_size[3], padding='same',
                         name='block3_conv1'))
        model.add(BatchNormalization())
        model.add(Activation('relu', name='block3_act1'))
        model.add(Conv1D(filters=filter_num[3], kernel_size=kernel_size[3],
                         strides=conv_stride_size[3], padding='same',
                         name='block3_conv2'))
        model.add(BatchNormalization())
        model.add(Activation('relu', name='block3_act2'))
        model.add(MaxPooling1D(pool_size=pool_size[3], strides=pool_stride_size[3],
                               padding='same', name='block3_pool'))
        model.add(Dropout(0.1, name='block3_dropout'))

        # Block 4
        model.add(Conv1D(filters=filter_num[4], kernel_size=kernel_size[4],
                         strides=conv_stride_size[4], padding='same',
                         name='block4_conv1'))
        model.add(BatchNormalization())
        model.add(Activation('relu', name='block4_act1'))
        model.add(Conv1D(filters=filter_num[4], kernel_size=kernel_size[4],
                         strides=conv_stride_size[4], padding='same',
                         name='block4_conv2'))
        model.add(BatchNormalization())
        model.add(Activation('relu', name='block4_act2'))
        model.add(MaxPooling1D(pool_size=pool_size[4], strides=pool_stride_size[4],
                               padding='same', name='block4_pool'))
        model.add(Dropout(0.1, name='block4_dropout'))

        # FC #1
        model.add(Flatten(name='flatten'))
        model.add(Dense(512, kernel_initializer=glorot_uniform(seed=0), name='fc1'))
        model.add(BatchNormalization())
        model.add(Activation('relu', name='fc1_act'))

        model.add(Dropout(0.7, name='fc1_dropout'))

        #FC #2
        model.add(Dense(512, kernel_initializer=glorot_uniform(seed=0), name='fc2'))
        model.add(BatchNormalization())
        model.add(Activation('relu', name='fc2_act'))

        model.add(Dropout(0.5, name='fc2_dropout'))

        # Classification
        model.add(Dense(classes, kernel_initializer=glorot_uniform(seed=0), name='fc3'))
        model.add(Activation('softmax', name="softmax"))
        return model

Here are the results of model.summary() from the keras code
Layer (type)                 Output Shape              Param #
=================================================================
block1_conv1 (Conv1D)        (None, 5000, 32)          288
_________________________________________________________________
batch_normalization_1 (Batch (None, 5000, 32)          128
_________________________________________________________________
block1_adv_act1 (ELU)        (None, 5000, 32)          0
_________________________________________________________________
block1_conv2 (Conv1D)        (None, 5000, 32)          8224
_________________________________________________________________
batch_normalization_2 (Batch (None, 5000, 32)          128
_________________________________________________________________
block1_adv_act2 (ELU)        (None, 5000, 32)          0
_________________________________________________________________
block1_pool (MaxPooling1D)   (None, 1250, 32)          0
_________________________________________________________________
block1_dropout (Dropout)     (None, 1250, 32)          0
_________________________________________________________________
block2_conv1 (Conv1D)        (None, 1250, 64)          16448
_________________________________________________________________
batch_normalization_3 (Batch (None, 1250, 64)          256
_________________________________________________________________
block2_act1 (Activation)     (None, 1250, 64)          0
_________________________________________________________________
block2_conv2 (Conv1D)        (None, 1250, 64)          32832
_________________________________________________________________
batch_normalization_4 (Batch (None, 1250, 64)          256
_________________________________________________________________
block2_act2 (Activation)     (None, 1250, 64)          0
_________________________________________________________________
block2_pool (MaxPooling1D)   (None, 313, 64)           0
_________________________________________________________________
block2_dropout (Dropout)     (None, 313, 64)           0
_________________________________________________________________
block3_conv1 (Conv1D)        (None, 313, 128)          65664
_________________________________________________________________
batch_normalization_5 (Batch (None, 313, 128)          512
_________________________________________________________________
block3_act1 (Activation)     (None, 313, 128)          0
_________________________________________________________________
block3_conv2 (Conv1D)        (None, 313, 128)          131200
_________________________________________________________________
batch_normalization_6 (Batch (None, 313, 128)          512
_________________________________________________________________
block3_act2 (Activation)     (None, 313, 128)          0
_________________________________________________________________
block3_pool (MaxPooling1D)   (None, 79, 128)           0
_________________________________________________________________
block3_dropout (Dropout)     (None, 79, 128)           0
_________________________________________________________________
block4_conv1 (Conv1D)        (None, 79, 256)           262400
_________________________________________________________________
batch_normalization_7 (Batch (None, 79, 256)           1024
_________________________________________________________________
block4_act1 (Activation)     (None, 79, 256)           0
_________________________________________________________________
block4_conv2 (Conv1D)        (None, 79, 256)           524544
_________________________________________________________________
batch_normalization_8 (Batch (None, 79, 256)           1024
_________________________________________________________________
block4_act2 (Activation)     (None, 79, 256)           0
_________________________________________________________________
block4_pool (MaxPooling1D)   (None, 20, 256)           0
_________________________________________________________________
block4_dropout (Dropout)     (None, 20, 256)           0
_________________________________________________________________
flatten (Flatten)            (None, 5120)              0
_________________________________________________________________
fc1 (Dense)                  (None, 512)               2621952
_________________________________________________________________
batch_normalization_9 (Batch (None, 512)               2048
_________________________________________________________________
fc1_act (Activation)         (None, 512)               0
_________________________________________________________________
fc1_dropout (Dropout)        (None, 512)               0
_________________________________________________________________
fc2 (Dense)                  (None, 512)               262656
_________________________________________________________________
batch_normalization_10 (Batc (None, 512)               2048
_________________________________________________________________
fc2_act (Activation)         (None, 512)               0
_________________________________________________________________
fc2_dropout (Dropout)        (None, 512)               0
_________________________________________________________________
fc3 (Dense)                  (None, 101)               51813
_________________________________________________________________
softmax (Activation)         (None, 101)               0
=================================================================
Total params: 3,985,957
Trainable params: 3,981,989
Non-trainable params: 3,968

Here is what I have made in pytorch
class model(torch.nn.Module):
    def __init__(self, input_channels, kernel_size, stride, pool_kernel, pool_stride, dropout_p, dropout_inplace=False):
        super(model, self).__init__()
        self.encoder = nn.Sequential(
            BasicBlock1(input_channels, kernel_size, stride, pool_kernel, pool_stride, dropout_p),
            BasicBlock(input_channels//4, kernel_size, stride, pool_kernel, pool_stride, dropout_p),
            BasicBlock(input_channels//16, kernel_size, stride, pool_kernel, pool_stride, dropout_p),
            BasicBlock(input_channels//16//4, kernel_size, stride, pool_kernel, pool_stride, dropout_p)
        )

        self.decoder = nn.Sequential(
            nn.Linear(5120, 512),
            nn.BatchNorm1d(512),
            nn.ReLU(),
            nn.Dropout(p=dropout_p, inplace=dropout_inplace),
            nn.Linear(512, 512),
            nn.BatchNorm1d(512),
            nn.ReLU(),
            nn.Dropout(p=dropout_p, inplace=dropout_inplace),
            nn.Linear(512, 101),
            nn.Softmax(dim=101)
        )
    def forward(self, x):
        x = self.encoder(x)

        x = x.view(x.size(0), -1)  # flatten

        x = self.decoder(x)
        return x

def BasicBlock(input_channels, kernel_size, stride, pool_kernel, pool_stride, dropout_p, dropout_inplace=False):
    return nn.Sequential(
        nn.Conv1d(in_channels=input_channels, out_channels=input_channels, kernel_size=kernel_size, stride=stride,
                  padding=get_pad_size(input_channels, input_channels, kernel_size)),
        nn.BatchNorm1d(32),
        nn.ReLU(),
        nn.Conv1d(in_channels=input_channels, out_channels=input_channels, kernel_size=kernel_size, stride=stride,
                  padding=get_pad_size(input_channels, input_channels, kernel_size)),
        nn.BatchNorm1d(32),
        nn.ReLU(),
        nn.MaxPool1d(kernel_size=pool_kernel, stride=pool_stride,
                     padding=get_pad_size(input_channels, input_channels/4, kernel_size)),
        nn.Dropout(p=dropout_p, inplace=dropout_inplace)
    )

def BasicBlock1(input_channels, kernel_size, stride, pool_kernel, pool_stride, dropout_p, dropout_inplace=False):
    return nn.Sequential(
        nn.Conv1d(in_channels=1, out_channels=input_channels, kernel_size=kernel_size, stride=stride,
                  padding=get_pad_size(input_channels, input_channels, kernel_size)),
        nn.BatchNorm1d(32),
        nn.ReLU(),
        nn.Conv1d(in_channels=input_channels, out_channels=input_channels, kernel_size=kernel_size, stride=stride,
                  padding=get_pad_size(input_channels, input_channels, kernel_size)),
        nn.BatchNorm1d(32),
        nn.ReLU(),
        nn.MaxPool1d(kernel_size=pool_kernel, stride=pool_stride,
                     padding=get_pad_size(input_channels, input_channels/4, kernel_size)),
        nn.Dropout(p=dropout_p, inplace=dropout_inplace)
    )

def get_pad_size(input_shape, output_shape, kernel_size, stride=1, dilation=1):
    """
    Gets the right padded needed to maintain same shape in the conv layers
    BEWARE: works only on odd size kernel size
    :param input_shape: the input shape to the conv layer
    :param output_shape: the desired output shape of the conv layer
    :param kernel_size: the size of the kernel window, has to be odd
    :param stride: Stride of the convolution
    :param dilation: Spacing between kernel elements
    :return: the appropriate pad size for the needed configuration
    :Author: Aneesh
    """

    if kernel_size % 2 == 0:
        raise ValueError(
            "Kernel size has to be odd for this function to work properly. Current Value is %d." % kernel_size)

    return (int((output_shape * stride - stride + kernel_size - input_shape + (kernel_size - 1) * (dilation - 1)) / 2))

Lastly here is the model summary for what my pytorch model creates
model(
  (encoder): Sequential(
    (0): Sequential(
      (0): Conv1d(1, 5000, kernel_size=(7,), stride=(1,), padding=(3,))
      (1): BatchNorm1d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (2): ReLU()
      (3): Conv1d(5000, 5000, kernel_size=(7,), stride=(1,), padding=(3,))
      (4): BatchNorm1d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (5): ReLU()
      (6): MaxPool1d(kernel_size=8, stride=4, padding=-1872, dilation=1, ceil_mode=False)
      (7): Dropout(p=0.1)
    )
    (1): Sequential(
      (0): Conv1d(1250, 1250, kernel_size=(7,), stride=(1,), padding=(3,))
      (1): BatchNorm1d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (2): ReLU()
      (3): Conv1d(1250, 1250, kernel_size=(7,), stride=(1,), padding=(3,))
      (4): BatchNorm1d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (5): ReLU()
      (6): MaxPool1d(kernel_size=8, stride=4, padding=-465, dilation=1, ceil_mode=False)
      (7): Dropout(p=0.1)
    )
    (2): Sequential(
      (0): Conv1d(312, 312, kernel_size=(7,), stride=(1,), padding=(3,))
      (1): BatchNorm1d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (2): ReLU()
      (3): Conv1d(312, 312, kernel_size=(7,), stride=(1,), padding=(3,))
      (4): BatchNorm1d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (5): ReLU()
      (6): MaxPool1d(kernel_size=8, stride=4, padding=-114, dilation=1, ceil_mode=False)
      (7): Dropout(p=0.1)
    )
    (3): Sequential(
      (0): Conv1d(78, 78, kernel_size=(7,), stride=(1,), padding=(3,))
      (1): BatchNorm1d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (2): ReLU()
      (3): Conv1d(78, 78, kernel_size=(7,), stride=(1,), padding=(3,))
      (4): BatchNorm1d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
      (5): ReLU()
      (6): MaxPool1d(kernel_size=8, stride=4, padding=-26, dilation=1, ceil_mode=False)
      (7): Dropout(p=0.1)
    )
  )
  (decoder): Sequential(
    (0): Linear(in_features=5120, out_features=512, bias=True)
    (1): BatchNorm1d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (2): ReLU()
    (3): Dropout(p=0.1)
    (4): Linear(in_features=512, out_features=512, bias=True)
    (5): BatchNorm1d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
    (6): ReLU()
    (7): Dropout(p=0.1)
    (8): Linear(in_features=512, out_features=101, bias=True)
    (9): Softmax()
  )
)

A: I think your fundamental problem is that you confuse in_channels and out_channels with Keras shapes. Let's just take the first convolutional layer as an example. In Keras you have:
Conv1D(filters=32, kernel_size=8, input_shape=(5000,1), strides=1, padding='same')

The PyTorch equivalent should be (changing the kernel size to 7 like you did, we'll come back to it later):
nn.Conv1d(in_channels=1, out_channels=32, kernel_size=7, stride=1, padding=3) # different kernel size

Note that you don't need to give the shape of your input sequence for pytorch. Now let's see how it compares to what you did:
nn.Conv1d(in_channels=1, out_channels=5000, kernel_size=7, stride=1, padding=0) # note padding

You just created a huge network. While the correct implementation produces an output of [b, 32, 5000] where b is the batch size, your output is [b, 5000, 5000].
Hope this example helps you to correct the rest of your implementation.
Finally, some notes on replicating same padding in pytorch. With even kernel sizes, to preserve the size of your input you need asymmetric padding. This I think might not be available when you create the layer. I see you instead changed the kernel size to 7, but it can actually be done with the original kernel size of 8. You can use padding in your forward() function to create the required asymmetric padding.
layer = nn.Conv1d(in_channels=1, out_channels=32, kernel_size=8, stride=1, padding=0) # layer without padding
x = torch.empty(1, 1, 5000).normal_()  # random input

# forward run
x_padded = torch.nn.functional.pad(x, (3,4))
y = layer(x_padded).shape
print(y.shape)  # torch.Size([1, 32, 5000])


text:
Q: Init object error TypeError: 'int' objecthas no attribute, python with generator I have a fucntion like:
def image_process(ind):
    return rotate(img[ind])
I am calling this function with Pool.imap to construct a generator
something like:
gen= pool.imap(image_process,[1,2,3,4,5,6],chunksize=100)
However, this generator seems to be empty. I can't run a forloop over it.
As soon as the interpreter reaches the following line:
for k,im in enumerate(gen) it throws an error: TypeError 'int' object has no attribute 'getitem'


text:
Q: Forwarding Application and Services Logs using nxlog Using nxlog 'im_mseventlog' module I'm able to forward all Windows Logs (Application, Security, System... ) logs to the remote syslog server. But I'm not able to forward eventlogs present under 'Application and Service Logs -> Microsoft -> Windows -> Windows Firewall with Advanced Security Logs' to the syslog server using nxlog. Is there any module to forward those event logs

A: Got solution for forwarding 'Application and Service Logs -> Microsoft -> Windows -> Windows Firewall with Advanced Security Logs' using nxlog.
Need to add the following Query inside the 'im_msvistalog' module
Query   <QueryList>  \
                <Query Id="0">  \
                <Select Path="System">*</Select> \
            <Select Path="Application">*</Select>  \
            <Select Path="Security">*</Select> \
            <Select Path="Microsoft-Windows-Windows Firewall With Advanced Security/Firewall">*</Select> \
            </Query> \
        </QueryList>\

This would forward the windows firewall with advanced security log along with other eventlogs. Thanks for the answers and suggestion.

A: AFAIK there is no other EventLog modules for nxlog.
It could be possible that Enterprise version is more capable in this field than Community version I assume your are using.
Maybe not directly answering your question but you can try other log shipper ... I recommend https://github.com/Cimpress-MCP/TimberWinR, it uses MS's LogParser to access EventLog.


text:
Q: Sudoers and setfacl command with arguments (:, " chars) in a case of a deployment script (https://github.com/EasyCorp/easy-deploy-bundle/blob/master/doc/default-deployer.md#security-options) I need to run setfacl from a distant machine that push code.
To do that in the sudoer file I've add for a specific user the right to run the command without password, but I would like do it for a full command:
username  ALL=(ALL:ALL) NOPASSWD: /usr/bin/setfacl setfacl -RL -m u:"www-data":rwX var/cache/ var/log/

At the moment I'm forced to remove arguments of the command, because the full command is rejected. I've tried to add a \ to escape :, the same for ". But it don't work.
username  ALL=(ALL:ALL) NOPASSWD: /usr/bin/setfacl setfacl

Thanks a lot

A: setfacl is the same as /usr/bin/setfacl. Prefer the later. Don't write both though.
You're right, to escape : the prefix is \.
To specify multiple paths, you must repeat the command by using a comma as a separator. You could also duplicate the whole line. It's up to you.
The end result should looks like:
username ALL=(ALL:ALL) NOPASSWD: /usr/bin/setfacl -RL -m u\:www-data\:rwX var/cache, /usr/bin/setfacl -R -m u\:www-data\:rwX var/log


text:
Q: Why would Android 2.2 reboot after install of an .apk file? I am getting reports from beta testers that after installing my .apk file their device is rebooting. After reboot the application operates as normal. Reboot after installation is not part of the desired/expected behavior, and itself sounds like a security breach.
Can anyone speculate as to why Android might reboot after an .apk install?
UPDATE:
One of the devices was an LG Ally, the other was a Samsung Galaxy Note

A: Are your Beta users using a rooted device? Do they have some kind of security app like "Lookout" installed on their device?
I'd suggest that you make your app create a trace log on the sdcard, that you'd get your beta tester to email to you.
Of course, this debugging process would be easier if someone loaned you the same model of the device your beta user is using.

A: No matter what your app should never be able to crash the operating system.  A lot of this can depend on the device and manufacturer.  For example, I noticed that when using a certain app to stream music on 2.3.x on the Droid X, the device would sometimes restart.  I could not fix this issue myself but instead had to wait until a fix was provided by Motorola (which it eventually was).  I would see if you can find a common occurrence on certain devices or manufacturers then do some researching on their reported bugs page.  Also, what type of application is this (game/media/utility?)


text:
Q: Is `ServletContext` interface implemented by any classes inside Tomcat server? I'm currently learning Java EE using Tomcat 9 server, with focus on the ServletContext interface.
I want to know what classes implement ServletContext interface, so I checked the official Oracle documentation. But the official documentation does not list any classes that implement ServletContext interface. And I noticed that ServletContext interface is public, therefore I was thinking the ServletContext interface must have been implemented by some classes inside tomcat server.
Because I'm relatively new to Java EE and Tomcat, therefore I'm not sure if my assumption is correct. Also, if my assumption is indeed correct, could someone please tell me where I can find the source code that implement ServletContext interface? I would love to have a look at the source code and try to understand how it really works.

A: Yes, this is how it works. JavaEE is a specification so all you have is interfaces. The implementation is provided by the containers.
In tomcat it's implemented by ApplicationContext.java


text:
Q: Does pressure of a closed box with air in it change as a function of the gravitational acceleration? If I took a hypothetical box of fixed volume and filled it with 1 mol of N2 at home, measured the pressure, then teleported this box to increasingly distant points from the Earth, would I see the pressure drop?
Since Pressure = Force / Area
and Force = mass x acceleration
Decreasing the gravitational acceleration should decrease the pressure?
This in turn should decrease the temperature based on PV=nRT.
Though maybe  ideal gas law does not apply in this context?
Where am I going wrong with this?

A: In the presence if gravity there will be a pressure gradient in the box, with the pressure at the bottom of the box greater than that at the top. As you move the box away, or reduce gravity, then the pressure gradient will decrease, with the pressure in the box becoming uniform as gravity disappears.
EDIT: Let's be a bit more quantitative. The pressure gradient in the box will be,
$$\frac{dP}{dz}=-\rho g$$
where $z$ is measured upward from the bottom of the box. The ideal gas law can be recast as:
$$P=\frac{n}{V} RT=\frac{\rho}{M}RT$$
where $M$ is the molar mass.
Then we have, $$\frac{d}{dz}\left(\frac{\rho}{M}RT\right)=-\rho g$$ or
$$\frac{d\rho}{dz}+\left(\frac{Mg}{RT}\right)\rho=0$$
So, the solution for $\rho$ is $\rho (z)=\rho_0 \exp\left(\frac{-zMg}{RT}\right)$, where $\rho_0$ is the density at the bottom of the box. If the height of the box is small such that $H<<RT/Mg$, then this can be linearized as, $\rho (z)=\rho_0\left(1- \frac{zMg}{RT}\right)$.
Now, if the volume of your box is $V$ and the total mass of the gas that you place in the box is $m$, then the denisty of the gas in the box in the absence of gravity is $\rho=\frac{m}{V}$. If this same mass of gas, in the same volume, is now exposed to gravity then we must have
$$\frac{1}{H}\int_{0}^{H}\rho_0\left(1- \frac{zMg}{RT}\right)dz=\frac{m}{V}=\frac{m}{HA}$$
Where $H$ is the height of the box, and $A$ is the area of its base. This gives:
$$\rho_0=\frac{m}{V}\frac{1}{\left(1-\frac{MgH}{2RT}\right)}$$
Then the pressure in the box is:
$$P(z)=\frac{\rho_0 RT}{M}-\rho_0 gz$$
Note that this analysis assumes that the temperature of the box remains constant.


text:
Q: Install Apache Hue on windows Is Apache Hue supported in windows.
I downloaded the hue 2.1.0 and modified the hue.ini to point to hadoop(psudo-distributed mode).
Modified: In Hadoop and Yarn
hadoop_hdfs_home -> hadoop-2.7.3/lib
hadoop_bin -> hadoop-2.7.3/bin
hadoop_conf_dir -> hadoop-2.7.3/etc/hadoop
webhdfs_url=http://localhost:50070/webhdfs/v1

The Hue doesn't seem to start in localhost:8888.
Does windows supports Hue and if there is anything I need to change?
Thank you for your comments.


text:
Q: What is this control which is in Windows 10 Store App?
How to create this control in Windows 10 Universal App? Please help. Thanks in Advance !

A: This looks like the Pivot control, which was previously available only for Windows Phone, and is now also available for the universal device family. The Pivot control provides adaptive behavior based on the screen size and input type.
This sample shows how to implement this control. You can style it in different ways - the option you are looking for would be scenario 1 from the code sample. Hope this helps.


text:
Q: Was ExtensionSidebarPane broken in Chrome 92 upgrade? I released a Chrome DevTools extension a couple years ago that uses
chrome.devtools.panels.elements.createSidebarPane(title, callback)
to add an ExtensionSidebarPane. This worked fine until Chrome 92. Now the Pane is created with the title, but it is blank.
The calls I am using are still documented: https://developer.chrome.com/docs/extensions/reference/devtools_panels/, but the example code that I used has been moved to into the mv2-archive section of the google-extension-samples repo. And the chrome-query example code no longer works either. So maybe that means it is unsupported now. On the other hand, everything I have found so far seems to say v2 should be supported to the end of 2021. And I haven't found any alternative v3 examples of adding info to the devtools UI.
Obviously createSidebarPane is getting called, because the blank pane is created with the expected title. And intentionally throwing an error in the callback shows that it is getting called with the expected ExtensionSidebarPane object as a parameter, it's just that calling setExpression or setObject on it doesn't do anything. I am not seeing any other errors or warnings.
I would hate to retire my extension, since I know people use it, but I am not sure what else to try.


text:
Q: Solutions of the Falkner Skan Equation for Negative Beta I was wondering what the solution to the Falkner Skan equation, $$f^{\prime\prime\prime}+ff^{\prime\prime}+\beta(1-f^{\prime 2})=0$$ looks like for negative values of $\beta$ and whether solutions for a particular values of $\beta$ are unique or if you could get multiple solutions for a given value of $\beta$?
The conditions for this equation are $f(0)=f^\prime(0)=0$ and $f^\prime(x)\rightarrow1$ as $x\rightarrow \infty$

A: This is not an answer, but a remark due to the discussion in the comments.
Our equation is autonomous, because it doesn't contain the independent variable $x$.
$$f^{\prime\prime\prime}+ff^{\prime\prime}+\beta(1-f^{\prime 2})=0$$
So we can consider another function:
$$f'=u(f)$$
$$f''=\frac{du}{dx}=\frac{du}{df}\frac{df}{dx}=u \cdot u'$$
$$f'''=\frac{d}{dx}(u \cdot u')=u \cdot \frac{d}{df}(u \cdot u')=u (u'^2+uu'')$$
So we obtain a second order equation:
$$u (u'^2+uu'')+f uu'+\beta(1-u^2)=0$$

$$u^2 u''+u ~u'(u'+f)+\beta(1-u^2)=0$$

The boundary conditions are another story. From the first two conditions we know that $u(0)=0$, as for another condition, we'll need to work on that.
Note that for $u \to 1$ we can consider the approximate equation:
$$u u''+u'(u'+f)=0 \\ (u u')'+f u'=0 $$
And for $u \to 0$ another approximate equation:
$$u^2 u''+u ~u'(u'+f)+\beta=0$$


text:
Q: Highlight any cell in a column that is the same as a single cell in another column I have a list of dates in column C.
I have a single date in cell J1.
I want to conditional highlight all the cells in column C that have the same value as cell J1. I also want the opposite: to highlight cell J1 if its value is found anywhere in column C; that way all of the duplicates will be highlighted at the same time.
I have tried with =MATCH(C:C,$J1,0)>0, =COUNTIF(C:C,$J1)>1, =C:C=$J1, and tons of others, but none seems to work. Any ideas?

A: Custom Formula:
=C1=$J$1

Apply to:
C:C

Custom Formula:
=MATCH(J1,C:C,0)

Apply to:
J1