text:
Q: Enable Remote Desktop in Windows Firewall from command line note: #command-line tag do not imply batch-file-only, I will accept a PowerShell script or any freely available utility, which can be started from command line and finish its work unattended.

tl;dr
how to unattendedly transform firewall rules exactly to state GUI puts it, on Windows Vista to Windows 10 of any interface (display) language?
Elaborating
This question is similar to #786383, but it's not the same.
Basically, because answer isn't good for me:

*

*set rule group="remote desktop" new enable=Yes opens port 3389 for public networks, and I want to avoid that. Also, different Windows languages have different group names, but I need an universal solution.

*netsh firewall set service type = remotedesktop mode = enable isn't working for me either: it is deprecated since win7, and allows rdp for current network only (if you're in public one, 3389 will be opened for public networks and won't work in private networks afterwards).

Note that before RDP is enabled via GUI, there is only one rule per protocol for RDP. But when RDP is enabled via GUI, port only gets opened for private and domain networks, and rules split for this. After enabling, there are 4 rules in Windows 8+ and 2 rules (no UDP) in Windows XP, Vista and 7.
Work-around I'm currently using is adding my own rules:
netsh.exe advfirewall firewall add rule name="Remote Desktop - User Mode (TCP-In)" dir=in action=allow program="%%SystemRoot%%\system32\svchost.exe" service="TermService" description="Inbound rule for the Remote Desktop service to allow RDP traffic. [TCP 3389] added by LogicDaemon's script" enable=yes profile=private,domain localport=3389 protocol=tcp
netsh.exe advfirewall firewall add rule name="Remote Desktop - User Mode (UDP-In)" dir=in action=allow program="%%SystemRoot%%\system32\svchost.exe" service="TermService" description="Inbound rule for the Remote Desktop service to allow RDP traffic. [UDP 3389] added by LogicDaemon's script" enable=yes profile=private,domain localport=3389 protocol=udp

but that's bad, because (unlike standard ones) they can be modified by user, have no group (to work with other scripts), and don't get automatically disabled when RDP is turned off via GUI.
Screenshots
Firewall rules before enabling RDP via GUI for the first time * **

Same rules when RDP is enabled via GUI (state I want to get):

And after disabling RDP in GUI:

I won't retell the whole story of this fight with windows command line utilities, until somebody asks. Here is that story in Russian.

A: If I understand the question correctly this will get you what you want. This is PowerShell:
$FireWall = New-Object -comObject HNetCfg.FwPolicy2
$EnableRules = $FireWall.rules | Where-Object {$_.LocalPorts -like "*3389*" -and $_.Profiles -eq "3"}
ForEach ($Rule In $EnableRules){($Rule.Enabled = "True")}

This will filter out the rules and grab the correct rule names agnostic of language. It does this by filtering on port 3389 and finding the rule associated with "Domain and Private networks". Profiles -eq 3 is the bitmap mask for Private and Domain networks, you can see the reference here:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa366303(v=vs.85).aspx
Where 1 (Domain networks) + 2 (Private networks) = 3
Here is the MSDN link where I figured out the rest:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa365309(v=vs.85).aspx
And here is how I figured out what the properties and methods were for the other objects:
PS C:\> $FireWall | Get-Member

   TypeName: System.__ComObject#{98325047-c671-4174-8d81-defcd3f03186}

Name                                         MemberType            Definition
----                                         ----------            ----------
EnableRuleGroup                              Method                void EnableRuleGroup (int, string, bool)
IsRuleGroupEnabled                           Method                bool IsRuleGroupEnabled (int, string)
RestoreLocalFirewallDefaults                 Method                void RestoreLocalFirewallDefaults ()
BlockAllInboundTraffic                       ParameterizedProperty bool BlockAllInboundTraffic (NET_FW_PROFILE_TYPE2...
DefaultInboundAction                         ParameterizedProperty NET_FW_ACTION_ DefaultInboundAction (NET_FW_PROFI...
DefaultOutboundAction                        ParameterizedProperty NET_FW_ACTION_ DefaultOutboundAction (NET_FW_PROF...
ExcludedInterfaces                           ParameterizedProperty Variant ExcludedInterfaces (NET_FW_PROFILE_TYPE2_...
FirewallEnabled                              ParameterizedProperty bool FirewallEnabled (NET_FW_PROFILE_TYPE2_) {get...
IsRuleGroupCurrentlyEnabled                  ParameterizedProperty bool IsRuleGroupCurrentlyEnabled (string) {get}
NotificationsDisabled                        ParameterizedProperty bool NotificationsDisabled (NET_FW_PROFILE_TYPE2_...
UnicastResponsesToMulticastBroadcastDisabled ParameterizedProperty bool UnicastResponsesToMulticastBroadcastDisabled...
CurrentProfileTypes                          Property              int CurrentProfileTypes () {get}
LocalPolicyModifyState                       Property              NET_FW_MODIFY_STATE_ LocalPolicyModifyState () {g...
Rules                                        Property              INetFwRules Rules () {get}
ServiceRestriction                           Property              INetFwServiceRestriction ServiceRestriction () {g...

PS C:\> $Rules | Get-Member

   TypeName: System.__ComObject#{9c27c8da-189b-4dde-89f7-8b39a316782c}

Name                 MemberType Definition
----                 ---------- ----------
Action               Property   NET_FW_ACTION_ Action () {get} {set}
ApplicationName      Property   string ApplicationName () {get} {set}
Description          Property   string Description () {get} {set}
Direction            Property   NET_FW_RULE_DIRECTION_ Direction () {get} {set}
EdgeTraversal        Property   bool EdgeTraversal () {get} {set}
EdgeTraversalOptions Property   int EdgeTraversalOptions () {get} {set}
Enabled              Property   bool Enabled () {get} {set}
Grouping             Property   string Grouping () {get} {set}
IcmpTypesAndCodes    Property   string IcmpTypesAndCodes () {get} {set}
Interfaces           Property   Variant Interfaces () {get} {set}
InterfaceTypes       Property   string InterfaceTypes () {get} {set}
LocalAddresses       Property   string LocalAddresses () {get} {set}
LocalPorts           Property   string LocalPorts () {get} {set}
Name                 Property   string Name () {get} {set}
Profiles             Property   int Profiles () {get} {set}
Protocol             Property   int Protocol () {get} {set}
RemoteAddresses      Property   string RemoteAddresses () {get} {set}
RemotePorts          Property   string RemotePorts () {get} {set}
serviceName          Property   string serviceName () {get} {set}

A: The following cmd commands..
netsh firewall set service type = remotedesktop mode = enable

and
REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /

are not sufficient to enable remote desktop.
I had to add this one to make it work (Client: Windows 10).
netsh advfirewall firewall add rule name="Open Remote Desktop" protocol=TCP dir=in localport=3389 action=allow

A: netsh firewall set service type = remotedesktop mode = enable

or
REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f

A: If you are looking for PowerShell solution, the following can be used:
Enable-NetFirewallRule -Name "RemoteDesktop-UserMode-In-TCP"
Enable-NetFirewallRule -Name "RemoteDesktop-UserMode-In-UDP"


text:
Q: ParallelTable local variables don't update precision I'm finding that precision of variables updated outside ParallelTable don't update inside of it the way I'd hope. Here's the minimal code that demonstrates my point:
a1 = SetPrecision[1.0, 20];
Precision[a1]
ParallelTable[
  Print[Precision[a1]];
  , {j, 1}];
a1 = SetPrecision[1.0, 30];
a2 = a1;
Precision /@ {a1, a2}
ParallelTable[
  Print[Precision /@ {a1, a2}];
  , {j, 1}];

which outputs
20.
20.
{30., 30.}
{20.,30.}

The key problem is that output lines 3 and 4 aren't the same. a1 is defined differently inside and outside ParallelTable. Why is this and how can I make sure a1 is properly updated?
For contrast, note the problem does not occur if a1 has its value updated instead of its precision:
a1 = 1.0;
a1
ParallelTable[
  Print[a1];
  , {j, 1}];
a1 = 2.0;
a2 = a1;
{a1, a2}
ParallelTable[
  Print[{a1, a2}];
  , {j, 1}];

output:
1.
1.
{2., 2.}
{2.,2.}

Some possibly related questions:
ParallelTable and Precision
-- This seems to answer a related but different question?
ParallelTable and Table do not give same result
-- I couldn't quite grasp this one to figure out if it was answering my question. A more straightforward answer would be very helpful.

A: What you are seeing can be traced back to the behavior of DistributeDefinitions which is used internally by ParallelTable. DistributeDefinitions seems to have some way to determine which of its argument should in fact be distributed [1]. If the value of a variable is unchanged, it will do nothing. Consider the following snippet, for example:
a1 = SetPrecision[1.0, 20];
DistributeDefinitions[a1]
(*{a1}*)
DistributeDefinitions[a1]
(*{}*)

The empty braces indicate that nothing was distributed. Now, a change of precision will not trigger such an update, as can be seen when evaluating
a1 = SetPrecision[2.0, 20];
DistributeDefinitions[a1]
(*{a1}*)
a1 = SetPrecision[2.0, 30];
DistributeDefinitions[a1]
(*{}*)

I can't tell you why this is the case, maybe someone else can shed light on this. As to how to work around this, we already mentioned several possible ways in the comments:

*

*Using shared variables (note that this of course has additional side-effects you may or may not want)
SetSharedVariable[a1]
a1 = SetPrecision[2.0, 20]

*Manually setting the precision on all kernels
ParallelEvaluate[a1 = SetPrecision[2.0, 20]]

[1] As an aside I want to mention that the documentation seems incorrect, or confusing at the least. It states: "DistributeDefinitions in effect applies ParallelEvaluate to all assignments for values and attributes with the symbols [...], including not only ownvalues but also downvalues, upvalues, and other types of values."

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scrambling sentences on Python I'm trying to make a program that scrambles the order of sentences. The program must take an input file and scramble it into an output file. However, when the sentences are scrambled, they should be numbered according to their original order. For example,
Input
I love apples
I love candy
I love God

Output
2:I love candy

3:I love God

1:I love apples

I'm really not sure how to begin, so if you can provide me with ideas or a way to approach this problem or what functions and methods i should be using then that would be very great.

A: Assuming you have an array sentences:
#zip in the original order
sentences = zip(range(len(sentences)), sentences)
random.shuffle(sentences)
for i, sentence in sentences:
   print "{0}: {1}".format(i, sentence)

A: import random
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
  suffixes = []
  for i,line in enumerate(infile):
    line = line.strip()
    prefix, suffix = line.rsplit(' ', 1)
    suffixes.append((i,suffix))

  random.shuffle(suffixes)
  for i,suffix in suffixes:
    print("%d:%s %s" %(i, prefix, suffix))

A: from random import shuffle

def scramble(infile, outfile):
    with open(infile) as f1, open(outfile, 'w') as f2:
        myrows = list(enumerate(f1, 1))
        shuffle(myrows)
        f2.writelines(('%-4d: %s' % r for r in myrows))

scramble(__file__, '/tmp/scrambled.txt')
with open('/tmp/scrambled.txt') as sf:
    print ''.join(sf)

A: You seem to be having trouble with the other answers so here is a complete solution which I've tested so it should work:
from random import shuffle

finput = 'path/input.txt'
foutput = 'path/output.txt'

with open(finput, 'r') as fin, open(foutput, 'w') as fout:
    sentences = fin.readlines()

    #add the order using enumeration
    sentences = list(enumerate(sentences))
    shuffle(sentences)
    for i, sentence in sentences:
        fout.write("{0}: {1}".format(i + 1, sentence))


text:
Q: onStop(), onPause(), onCreate(), onResume(), and GPS I have an app working that is GPS based.  It has many activities and all use the GPS.  For example, one activity shows the distance to a location, another shows the speed and direction.  I set up and call requestLocationUpdates() in onCreate() and call removeUpdates() in onPause().
This all works but the GPS blinks and has to re-acquire when switching activities.  I did a test and if I put the removeUpdates() in onStop() instead of in onPause() there is no blinking.  Apparently onStop() is called after the new activity starts which explains the lack of blinking.
I have read the posts on this subject and there seems to be a difference of opinion.  However, it looks like I should use onStop() and am wondering if there is any reason I should not.
The second issue is that there is no onResume() code so there is no GPS after a back-arrow or after turning the screen off and on.  I should fix this.  Right now my onCreate() code creates the location manager and basically has all my code in it.  It looks like following the life cycle flow chart that I should move the removeUpdates() to onStop and move the creation of the lm and ll to onStart().  Is this correct?
Here is my onCreate() code:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.set);
    textView1 = (TextView)findViewById(R.id.textView1);
    lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    ll = new mylocationlistener();
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}

Here is my onPause code:
    @Override
    protected void onPause() {
        super.onPause();
        if(lm != null) {
            lm.removeUpdates(ll);
        }
        ll = null;
        lm = null;
    }

So I think I should just change the onPause() to onStop() and make onStart() this:
@Override
public void onStart() {
    super.onStart();
    lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    ll = new mylocationlistener();
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}

And my onCreate code as this;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.set);
    textView1 = (TextView)findViewById(R.id.textView1);
  }

This said, I am kind of new to all this and this is my first application so I would like to know what I am missing here.

A: I've done something similar to your app, except that I've delegated the GPS functionality to a service which stops the GPS when no activities are bound to it and starts it when an activity binds to it. I bind to the service in the onStarts and unbind in the onStops. Logging the on.. methods when I switch activities gives a sequence like this:
FIRST Activity onCreate
FIRST Activity onStart
FIRST Activity onResume
FIRST Activity onPause
SECOND Activity onCreate
SECOND Activity onStart
SECOND Activity onResume
FIRST Activity onStop

If done it via a service so that I've only got one LocationManager to control, you could either take the same approach, or requestUpdates in the onStarts() and remove them in the onStops()

A: First of all I'd suggest following good read about location strategies.
If you just want a one-time location fix you need to make it a bit more independent from the activity life cycle because acquiring the GPS location can take longer than the user switches your activities.
So don't stop the request in onPause or onStop. You could use a special location query handler that lives as a singleton instance in your Application object (create a derivative of Application for that).
Tell that location handler to get a fresh fix if necessary in your activities' onStart or onResume method for example. Let the handler keep the latest and best location data which can be immediately used as needed.
You could query for the first time a NETWORK_PROVIDER location because this should be faster than GPS and you immediately have something to work with even though it's not accurate. On top of that you'd also get a location in case the user turned off the GPS module.
However, that depends on how accurate the result has to be. You could also create a local service that queries the GPS location and waits for its result to come. When the result is there you can notify your currently running activity via a local broadcast intent.
In any case, you can get the last known location with locationManager.getLastKnownLocation

A: First, I'm not 100% what question you're asking here, but I will try to help you out.  OnPause is called whenever the Activity loses focus.  This is primarily for popups and such that cause the Activity to be in the background, but blurred.  OnStop is called whenever a new activity is started.  You should put your location retrieval code in OnResume.  OnResume is called any time that the application begins again.  This includes any calls to OnCreate or OnStart.  You should put your lm.removeUpdates(ll); logic in OnStop as well.  This is the generally accept method for location retrieval in a life cycle;  I just ended a sentence with a semicolon... I've been coding too much.


text:
Q: An involution defined on the intersection of opposite Schubert cells in real full flag manifolds Let $F_n$ denote the full flag manifold consisting of all complete flags in $\mathbb{R}^n$. For the standard basis $\{ e_1,\dots,e_n\}$ of $\mathbb{R}^n$, denote the standard opposite flags:
$\sigma_- = \{e_1\} \subset \{e_1,e_2\} \subset\dots\subset \{ e_1,\dots,e_n\}$,
$\sigma_+ = \{e_n\} \subset \{e_n,e_{n-1}\} \subset\dots\subset \{ e_n,\dots,e_1\}$.
Notation: For a point $\sigma\in F_n$, denote by $C(\sigma)$ the set of all flags transverse to $\sigma$. This is known as a maximal Schubert cell.
Let $U_n$ denote the set of unipotent upper-triangular matrices in $SL_n(\mathbb{R})$. The maximal Schubert cell $C(\sigma_-)$ can be regarded as $U_n$ where the (fixed) identification $U_n \to C(\sigma_-)$ is given by $u\mapsto u\cdot \sigma_+$. The intersection $C(\sigma_+) \cap C(\sigma_-)$ is then seen as an open set in $U_n$ which is the complement of the union of the zero sets of $n-1$ polynomials $p_1,\dots,p_{n-1}$, where
$p_k (u) = \det u^{(k)}$ where $u^{(k)}$ denotes the upper-right $k\times k$ block matrix of $u$.
We define an involution $\iota: U_n\mapsto U_n$, $u\mapsto u^{-1}$. One can show that the involution preserves the intersection $C(\sigma_+) \cap C(\sigma_-)$.
An answer to the following question would be much appreciated.
Question. Does $\iota$ preserve any connected components of $C(\sigma_+) \cap C(\sigma_-)$?
When $n=3$ or $n \equiv 2\mod 4$, then it is not hard to show that $\iota$ does not preserve any connected components. I would like to know if this is true in general.


text:
Q: Changing HTML elements with JavaScript I'm learning JavaScript and I'm trying to create a 'circle calculator' which will take user input through a form and return them the area and circumference of the circle.
It all works except for displaying the result in the paragraph with the ID "circleData". It displays for a fraction of a second after submitting the form then disappears.
I would like the result of the Circle methods (the variable "text") to remain in the paragraph until the user submits the form again (when it should fill with the new data).
<!doctype html>

    <meta charset="utf-8">
    <title>JavaScript Test</title>

A Circle Calculator

    <form name="Circle" onsubmit="printCircle()" method="post">
      Enter the radius:

      <input type="text" name="Radius">

      Enter the units:

      <input type="text" name="Units">

      <input type="submit" value="Submit">

    </form>

A: Add a return false; in your function.
var printCircle = function(){
      aCircle._radius = document.forms["Circle"]["Radius"].value;
      var units = document.forms["Circle"]["Units"].value;
      var text = "A circle with the radius of " + aCircle._radius + units + " has a circumference of " + aCircle._perim.toFixed(2) + units + " and an area of " + aCircle._area.toFixed(2) + units;
      document.getElementById("circleData").innerHTML= text;

      // prevent the form from its natural bahavior
      return false;
    }

The form's onSubmit event prevents the form from submitting the data if it gets a false.
<form name="Circle" onsubmit="return printCircle();" method="post">

Alternatively, you can do it the better and most effective way.
var printCircle = function(){
   event.preventDefault();
   ...
}

And then:
<form name="Circle" onsubmit="printCircle();" method="post">

Read more

A: onsubmit="printCircle();return false;"


text:
Q: Unknown column error when using two COUNT statements in one query I am trying to run 2 different occurrences of COUNT in one SQL query but am getting this error:

Column not found: 1054 Unknown column 'po.product_id' in 'on clause'

Here is the sql:
SELECT COUNT(*) vouchersleft, `prod_name`,
        `start_date`,
        `end_date`,
        `reg_price`,
        `sale_price`,
        bbp.`prod_id`,
        `vouch_limits`,
        `sp_name`,
        `order_id`,
        `img_name`,
        `outlets`
        FROM `vouchers` as `v`
        INNER JOIN `bb_products` as `bbp` ON bbp.`prod_id` = v.`product_id`
        INNER JOIN `service_providers` as `sp` ON sp.`service_provider_id` = bbp.`provider_id`
        INNER JOIN `prod_pics` as `pp` ON pp.`prod_id` = bbp.`prod_id`
        INNER JOIN (SELECT COUNT(DISTINCT `outlet_id`) AS `outlets` FROM `prod_outlets` GROUP BY `product_id`) as `po` ON po.`product_id` = bbp.`prod_id`
        WHERE `frontend` = :frontend
        AND bbp.`featured` = :featured
        AND `order_id` = :order_id
        AND pp.`featured` = :featured_img
        GROUP BY bbp.`prod_id`

A: Including the column in the GROUP BY is not enough.  You need to also include it in the SELECT:
SELECT product_id, COUNT(DISTINCT `outlet_id`) AS `outlets`
FROM `prod_outlets`
GROUP BY `product_id`

A: If you want to join by the column it has to be returned by your SELECT statement. Include product_id in column list that you're selecting.
Change:
INNER JOIN (SELECT COUNT(DISTINCT `outlet_id`) AS `outlets` FROM `prod_outlets` GROUP BY `product_id`) as `po` ON po.`product_id` = bbp.`prod_id`

To:
INNER JOIN (SELECT `product_id`, COUNT(DISTINCT `outlet_id`) AS `outlets` FROM `prod_outlets` GROUP BY `product_id`) as `po` ON po.`product_id` = bbp.`prod_id`

Without the column selected, product_id is not visible outside of this intermediate table (here named po). This is why you get an error unknown column, because only known column is outlets.

A: Why not just join directly
SELECT COUNT(*) vouchersleft, `prod_name`,
        `start_date`,
        `end_date`,
        `reg_price`,
        `sale_price`,
        bbp.`prod_id`,
        `vouch_limits`,
        `sp_name`,
        `order_id`,
        `img_name`,
         COUNT(DISTINCT po.`outlet_id`) AS `outlets`
        FROM `vouchers` as `v`
        INNER JOIN `bb_products` as `bbp` ON bbp.`prod_id` = v.`product_id`
        INNER JOIN `service_providers` as `sp` ON sp.`service_provider_id` = bbp.`provider_id`
        INNER JOIN `prod_pics` as `pp` ON pp.`prod_id` = bbp.`prod_id`
        RIGHT JOIN `prod_outlets`  as `po` ON po.`product_id` = bbp.`prod_id`
        WHERE `frontend` = :frontend
        AND bbp.`featured` = :featured
        AND `order_id` = :order_id
        AND pp.`featured` = :featured_img
        GROUP BY bbp.`prod_id`


text:
Q: nodejs express app.get restrict for specific url I'm thinking of relatibly easy actions to make my node.js server more secure and i thought of restricting the app.get calls to only one url (the website hosted in another hosting). Is this possible?
I did not find such a thing on the net.
Regards,


text:
Q: Deleting Temporary Internet Files through Group Policy I have a domain controller running on Windows 2008 Server R2 and users login to application servers on which Windows 2003 Server SP2 is installed. I have applied a Group Policy to clean temporary internet files on exit i.e to delete all temporary internet files when users close the browser. But the group policy doesn't seem to work as user profile size keeps on increasing and the major space is occupied by temporary internet files therefore increasing the disk usage. How can i enforce automatic deletion of temporary internet files?

A: Use a script.  There are a bunch here.
EDIT:  Now that I think about, though, a better approach would probably be to just limit the maximum cache size through GPO.  Profile sizes won't grow out of control because of temporary internet files, and your users won't have to cache new files every time they access a webpage, only to have those cache files blown away on a regular basis.


text:
Q: Laravel's Storage::Files not finding my files i wanted to count how many images are in a storage directory but it seems that Storage::Files not finding any of them, i've stored 4 images in storage\app\public\property\*id_of_the_property* and i've already excuted php artisan storage:link and the link are working perfectly, at least at first glance.
Here is my config\FilesSystems.php
'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],

    ],

And my controler :
public function show($id)
    {

        $show = [];
        $directory = 'property/'.$id;
        $files = Storage::Files($directory);
        $count = count($files);

        $show['count'] = $count;
        $show['directory'] = $directory;

        return $show;
    }

But the the variable $show['count'] is displaying 0 when it should be 4 and the Storage::Files are not doing any thing since $show['directory'] are showing "property/1" and 1 is the id that i'm testing with. What am i missing?
i've tryed using :
$directory = Storage::url('property/'.$id);
/* Result "/storage/property/1" */
$directory = Storage::url('app/public/property/'.$id);
/* Result "/storage/app/public/property/1" */

or
$directory = Storage_path('property\\'.$id);
/* Result "D:\\xampp\\htdocs\\www\\APP\\storage\\property\\1" */
$directory = Storage_path('app/public/property/'.$id);
/* Result "D:\\xampp\\htdocs\\www\\APP\\storage\\app\\public\\property\\1" */

but no success too, the count are still 0.
Thank you for the help.

A: you can use File facade
use Illuminate\Support\Facades\File;
...
$images = File::allFiles(storage_path('app/public/property')); // this is recursive

or
$images = File::files(storage_path('app/public/property/'.$id)); // this is NOT recursive

A: Use public_path($directory); for this


text:
Q: Stream/Bloc/Repository/Firebase data flow Flutter I'm starting with flutter as I want to port my swift app to Flutter, but I'm getting stuck understanding the pattern Bloc/Repository/Firebase as I'm following the tutorial https://bloclibrary.dev/#/flutterfirestoretodostutorial dough I use the real time database, not Firestore.
My swift app is basically a map where you can add Alerts at your actual coordinates. The Alert get sent to Firebase and the firebase observer on the map updates the map showing the just added alert.
The above tutorial should help me porting my app. I'm just not sure I do understand the logic behind the code.
My concerns are 2:
First. There is an Entity layer between the model object and the firebase object.  It is explained that this will facilitate having different Data providers, but I don't really see it facilitating anything. In the Model class there is a toEntity() and a fromEntity() conversion method, and in the Entity class there is a fromSnapshot() and a toDocument() conversion method. I don't see what's the point here. Is it really necessary? What's wrong with   doing the conversion directly in the Model class , having different methods for each Data provider?
Second. Inside the TodoBloc I can't follow the logic.
The first event that is sent to the bloc at AppStart is LoadTodos.
BlocProvider<TodosBloc>(
          create: (context) {
            return TodosBloc(
              todosRepository: FirebaseTodosRepository(),
            )..add(LoadTodos());

In the mapEventToState() method of TodoBloc that event gets mapped to this Stream:
Stream<TodosState> _mapLoadTodosToState() async* {
    _todosSubscription?.cancel();
    _todosSubscription = _todosRepository.todos().listen(
          (todos) => add(TodosUpdated(todos)),
        );
  }

So far so good. As I understand this subscribes to the todos() Stream ()
@override
  Stream<List<Todo>> todos() {
    return todoCollection.snapshots().map((snapshot) {
      return snapshot.documents
          .map((doc) => Todo.fromEntity(TodoEntity.fromSnapshot(doc)))
          .toList();
    });
  }

and this should be the equivalent of the firebase observer in my swift app. It this part inside the listen closure I'm not sure to understand: (todos) => add(TodosUpdated(todos)) .
This sends to itself (TodoBloc) a TodosUpdated event on which the bloc will map this Stream:
Stream<TodosState> _mapTodosUpdatedToState(TodosUpdated event) async* {
    yield TodosLoaded(event.todos);
  }

which is this:
class TodosLoaded extends TodosState {
  final List<Todo> todos;

  const TodosLoaded([this.todos = const []]);

  @override
  List<Object> get props => [todos];

  @override
  String toString() => 'TodosLoaded { todos: $todos }';
}

Is this the actual list of Firebase objects? Does the todos() Stream return the entire node every time a new object is added in Firebase?
In my swift app the observer returns only the .childAdded after the first download of the node.
Should I use the firebase_database package that has a FirebaseList class(https://pub.dev/documentation/firebase_database/latest/ui_firebase_list/FirebaseList-class.html) that will just return a List on any change on the node as my observers do in my swift app?
Sorry for this very long and messy question, but I'm quite lost here starting with bloc pattern.
Thank you very much for your time and help.

A: Ok, I I think I understood the logic behind it, but if you see that I didn't get it right please correct me as at this stage of getting into a new paradigm is very important not to carry any misconceptions.

*

*todos() is the Stream coming from Firebase and returns a List<Todo>.

*_mapLoadTodosToState() is the bloc method that  attach a  bloc listener to todos() and in the .listen(onData) callback, it sends to the bloc an TodosUpdated(todos) event containing the latest list.

*TodosUpdated(todos) gets mapped to _mapTodosUpdatedToState, which yields
TodosLoaded(event.todos) , the new state that BlocProvider uses to build the UI.

Thank you and I hope this will help others struggling to master BloC pattern at a more complex level.
Cheers


text:
Q: pandas converting a float remove exponents I have data that looks like this:
Date            MBs     GBs
0   2018-08-14 20:10    32.00 MB    0.00 GB
1   2018-08-14 20:05    4.00 MB     0.00 GB
2   2018-08-14 20:00    1000.99 MB  1.23 GB

I stripped away the MB and GB by doing this:
df['MBs']=df['MB'].str.strip('MB')
df['GBs']=df['GB'].str.strip('GB')

Then converted the number to a float and got the totals:
df['MBs'] = df['MBs'].astype('float')
df['GBs'] = df['MBs'].astype('float')

df.loc['Total', ['MBs', 'GBs']] = df.sum()

But when I run it my data has exponents
Date    Data Transferred (MB)   Data Transferred (GB)
146 2018-08-14 08:00:00 1.871237e+05    1.874017e+05
147 2018-08-14 07:55:00 1.123211e+05    1.961854e+05
148 2018-08-14 07:50:00 2.187703e+05    2.187123e+05
...
Total       1.408910e+08    1.408910e+08

How do I convert change that float from exponent to "normal", im only converting it because I need to get the totals

A: You are trying to avoid using scientific notation:So here is what you can do:
import pandas as pd
pd.set_option('display.float_format', lambda x: '%.3f' % x)

this line of code set the pandas display format so it will not use scientific notaion
reference:http://pandas.pydata.org/pandas-docs/stable/options.html?highlight=display%20float_format

A: That's just how floats are represented by pandas, and that isn't something you change. You can, however, change the representation if you format the data as a string.
# Don't run this line.
# df = pd.concat([df] * 10000, ignore_index=True)
# This should be run on the *unstripped* version of your DataFrame.
df.loc['Total', ['MBs', 'GBs']] = (
    df[['MBs', 'GBs']]
       .stack()
       .str.split()
       .str[0]
       .astype(float)
       .unstack()
       .sum()
       .agg('{:.2f}'.format))

df.tail()

                   Date          MBs       GBs
29996  2018-08-14 20:00   1000.99 MB   1.23 GB
29997  2018-08-14 20:10     32.00 MB   0.00 GB
29998  2018-08-14 20:05      4.00 MB   0.00 GB
29999  2018-08-14 20:00   1000.99 MB   1.23 GB
Total               NaN  10369900.00  12300.00


text:
Q: Align mfc controls I want to create a dialog where every box is the same size and has the same margin between each other. Is it possible to do this in the editor or do I have to go to the code behind?
As you can see on the image there is different spacing between the controls.(I am using VS 2010 if that matters)

A: You should use the Dialog Editor tools to do that. That's what they're there for.
Select the first column of controls and choose "Space Evenly Down" either from from (a) the Format menu or (b) the Dialog Editor toolbar.
For the second column you can either do the same, or as I prefer, for each row select the two controls and use the "Align Bottoms" tool to make sure both columns are vertically aligned.
See the MSDN page on this sort of thing.


text:
Q: docker login using -p gives error, and when I switch to --password-stdin like it recommends still gives error - gitlab-ci I have a docker registry setup on my gitlab server. Here is my .gitlab-ci.yml file:
image: docker:18.05.0-ce

services:
  - docker:dind

stages:
  - build
  - test
  - release

variables:
  TEST_IMAGE: http://my.gitlab.ip:4444/path/to/project:$CI_COMMIT_REF_NAME
  RELEASE_IMAGE: http://my.gitlab.ip:4444/path/to/project:latest

before_script:
  - docker login -u $USERNAME -p $PASSWORD http://my.gitlab.ip:4444

build:
  stage: build
  script:
    - docker build --pull -t $TEST_IMAGE .
    - docker push $TEST_IMAGE

# ...

# more commands

I am using a secret variable for my username and password. When I push code and the runner runs through this file, I get the following error:
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Error response from daemon: Get https://my.gitlab.ip:4444/v2/: http: server gave HTTP response to HTTPS client

So I tried using --password-stdin instead like this:

*

*docker login -u $USERNAME --password-stdin $PASSWORD http://my.gitlab.ip:4444
And I get this error:
"docker login" requires at most 1 argument.
See 'docker login --help'.

Usage:  docker login [OPTIONS] [SERVER] [flags]

Edit:
I have also tried this for my docker login command:
docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY

and received this error:
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Error response from daemon: Get https://my.gitlab.ip:4444/v2/: http: server gave HTTP response to HTTPS client

I have made the following changes on my gitlab server:
In /etc/default/docker:
DOCKER_OPTS="--insecure-registry http://my.gitlab.ip:4444"

In /etc/docker/daemon.json:
{
    "insecure-registries" : ["http://my.gitlab.ip:4444"]
}

I have also done the same on my gitlab runner (different server).
Why is it showing that I'm using https in the error and how do I change it to http?

A: I'm not sure when you set this up, but there is an updated permission model after GitLab 8.12 when using GitLab runners and logging into the GitLab Container registry.
As per the docs, you can do:
before_script:
  - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY

A: Not sure if you already resolved your issue, but while searching for the difference of the login options (and best practises) I noticed your error is actually not even about that, is it?
The error we see is the following:
Error response from daemon: Get https://my.gitlab.ip:4444/v2/: http: server gave HTTP response to HTTPS client

but in your .gitlab-ci.yml file you list https://my.gitlab.ip:4444/v2/ as your URL. While this doesn't have to be related, it seems to me that ssl is missing somewhere, e.g. http vs https.

A: According to gitlab docs --password-stdin is a flag not a command line variable. In the example provided the password was being read from a file not directly through command line.


text:
Q: Grouping in SQL Server when you have a datetime2 column I have a table with the following format:
Date                        Login
2020-03-12 01:42:00.0000000 agent2
2020-03-12 01:42:00.0000000 agent2
2020-03-12 01:43:00.0000000 pma
2020-03-12 01:43:00.0000000 agent2
2020-03-12 01:43:00.0000000 agent2
2020-03-12 01:43:00.0000000 agent3
2020-03-12 01:43:00.0000000 agent1
2020-03-12 01:43:00.0000000 agent1

I need to group it per user per minute, however, when using the group by on the login field (as per below) I am getting an error "Column 'Date' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause".
SELECT  Date , Login
  FROM connections
  GROUP BY login

Expected result would be something like:
Date                        Login    Connections
2020-03-12 01:42:00.0000000 agent2   2
2020-03-12 01:43:00.0000000 pma      1
2020-03-12 01:43:00.0000000 agent2   2
2020-03-12 01:43:00.0000000 agent3   1
2020-03-12 01:43:00.0000000 agent1   2

Is this because one cannot group by when you have a datetime2 type column? Do I need to create another table for the connections count?

A: You aren't grouping by the datetime2 column in your query, so of course it isn't working.
You need to add it to the GROUP BY and then add a COUNT:
SELECT [Date], --I suggest a better name, date is a different data type
       [Login], --I suggest a different name. LOGIN is a reserved keyword
       COUNT(IDColumn) --I assume you have an ID you can count on?
FROM dbo.connections
GROUP BY [Date],
         [Login];


text:
Q: Android API and Gradle version I am new at developing Android apps. Currently, I am planning to do the API version upgrader  from API 25 to API 28. Is that necessary to upgrade the Gladle version as well? In my opinion it is needn't.
Please advice.
Thank you.

A: Yes it is required. Some cases it is not. WHEN IT IS COMPATIBLE.
When moving 3 versions and ESPECIALLY when moving to the new AndroidX support and API 28 it is definitely required. Anyone who says it is not, has not done this upgrade yet.
Gradle plugins are written specifically to match the build tools, and while not every update is a breaking change between the two. It is recommended that you stay with compatible versions. They must be compatible. For example if you are moving to 28, you will be likely using the migration tool to migrate to androidx namespaces. This breaks a lot of code and requires a little TLC to get it back up and running.
Then your Gradle will need an extra properties file to know that children namespaces will not match and will cause conflicts. To fix this we add a gradle.properties file in project root.
gradle.properties
 android.enableJetifier=true
 android.useAndroidX=true
 org.gradle.jvmargs=-Xmx1536m <--OPTIONAL Up to you, memory management

The AndroidX is for the latest 28 API
The Jetifier is for enabling transitive and direct dependencies to have an attempt at translating those into latest androidx compatibility compiling mode.
If you don't do these items, you will not get properly compiling on 28.
Kotlin Version 1.2.70 is where you want to be. As .71 has freezing issues.
Gradle. 3.3.0-alpha11 or you can do 3.4.0-alpha01. No one enjoys using alpha builds, but if you are moving into androidx and build tools 28, I recommend it otherwise you will fight compiling issues. Just keep an eye out for the stable release in the coming months.
Make sure you have the latest allprojects repos as well as they use jetpack now.
So in your parent project build.gradle include.
PROJECT LEVEL build.gradle
  buildscript {
    ext.kotlin_version = '1.2.70'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0-alpha11'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

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

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

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

Application Module level build.gradle
    apply plugin: 'com.android.application'
    apply plugin: 'kotlin-android'
    apply plugin: 'kotlin-android-extensions'
    apply plugin: 'kotlin-kapt'

        android {
           compileSdkVersion 28
           buildToolsVersion '28.0.3'
etc.....//////

     dependencies {
        //Kotlin Compiler Libraries
        implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
        implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.25.3'
        implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:0.25.3'

        //Android Google Libraries
        implementation 'androidx.appcompat:appcompat:1.0.0'
        implementation 'com.google.android.material:material:1.0.0'
        implementation 'androidx.appcompat:appcompat:1.0.0'
        implementation 'androidx.legacy:legacy-support-v4:1.0.0'
        implementation 'androidx.cardview:cardview:1.0.0'
        implementation 'androidx.recyclerview:recyclerview:1.0.0'
        implementation "androidx.constraintlayout:constraintlayout:2.0.0-alpha2"
        implementation "com.google.android.gms:play-services-location:16.0.0"

etc.....//////

Trust me when I tell you. I spent days battling the androidx updates to get into 28 early on. So if someone gives you compatible versions that match and play well together. Take it and run with it. I have done that for you above.
More info on migrating to 28 and and supporting new namespaces by Android.
https://developer.android.com/jetpack/androidx/migrate
One of their most painful updates I've ever dealt with since version 1. So prepare for some annoyances ;).
Happy Coding.

A: It's not mandatory. Update or not it's fully your choice. Gradle update or Sdk update they are not connected to each other directly. Sdk update gives you new different features, Gradle update gives you other different features. Those are different. But updating is always good. I suggest you to update Gradle.


text:
Q: Correct duplicate records in SQL Server database I have a table that contains many records, in which there is a nic column  which should have unique value. But it contains some dirt, means there are some duplicate values there.
Like user with
id = 567 has nic = '786-786'

and also
id = 897 has nic = '786-786'.

I want to write a stored procedure what should remove those duplicate and append 1 at the end like
id = 567 , nic= '786-786'
id = 788 , nic = '786-786-1'
id = 2344, nic = '786-786-2'

Is it possible?

A: use a window function / analytic function such as
Row_number() over (partition by Nic, order by ID)
SQL Fiddle
Something like...
UPDATE B
SET B.Nic = C.NewNic
FROM Foo B
INNER JOIN (SELECT ID, NIC + '-'  + cast(Row_number()
over (partition by NIC order by ID ) as varchar(20)) as newNic
FROM FOo) C
 on C.ID = B.ID

This will give you
id = 567 , nic= '786-786-1'
id = 788 , nic = '786-786-2'
id = 2344, nic = '786-786-3'

You could always do a case statement and when row is 1 then not display and subtract 1 if you have to leave the first one without a -1
SQL Fiddle getting rid of the -1 for first record...
UPDATE B
SET B.Nic = Case WHEN C.RN = 1 then B.Nic Else B.Nic+ '-'+cast((RN-1) as varchar(20)) end
FROM Foo B
INNER JOIN (SELECT ID, NIC, cast(Row_number()
over (partition by NIC order by ID ) as varchar(20)) as RN
FROM FOo) C
 on C.ID = B.ID

Resulting in:
ID  NIC
567 786-786
897 786-786-1

and a SQL Fiddle showing multiple nic's
ID  NIC
567 786-786
600 786-786-1
897 786-786-2
10  786-787
12  786-787-1
900 786-787-2

A: for tsql
you can do this by simple update, try this query:
select id, nic, rank() over (partition by nic order by id)
from your_table as t1
where exists(select 1 from your_table where nic = t1.nic and id <> t1.id)

You can build update query, or return update string as field of this select. Read about rank()


text:
Q: Meaning and solution for Spring 3 error message? "Using getResponseBodyAsStream instead is recommended" I'm using Spring 3 and every time I submit a HTML form to a Spring controller I get this message, which I don't understand:
org.apache.commons.httpclient.HttpMethodBase getResponseBody
WARNING: Going to buffer response body of large or unknown size.
Using getResponseBodyAsStream instead is recommended.

Is there a configuration change I can make in Spring to avoid this?

A: You can add configuration http.method.response.buffer.warnlimit=1024*1024*10 in the application.properties. it works for me.

A: This occurs with the commons-httpclient API when the getResponseBody() method is used.  The warning means that a response body could potentially be very large (such as a large file download, etc.) and loading the whole thing into memory at once as a String could be very inefficient.  The way to avoid this potential inefficiency is to use getResponseBodyAsStream(), which will allow proper buffering and streaming of the response body.
I am not sure why Spring is using getResponseBody().  Could it be your HTTP client?  Are you using a custom-written HTTP client to perform the request?


text:
Q: How to install Erlang 24.1 on Amazon Linux 2 I need to install Erlang 24.1 on Aamazon Linux 2. I am using package cloud script and repos for this but it fails with following message.
(venv) [CORP\shiv.d@a-1njrk968l4brs yum.repos.d]$ sudo yum install erlang
Loaded plugins: amzn_workspaces_filter_updates, halt_os_update_check, priorities, update-motd
rabbitmq_erlang/x86_64/signature                                                                                |  833 B  00:00:00
rabbitmq_erlang/x86_64/signature                                                                                | 1.8 kB  00:00:00 !!!
Not using downloaded rabbitmq_erlang/repomd.xml because it is older than what we have:
  Current   : Fri Oct  1 10:15:14 2021
  Downloaded: Tue Sep 14 08:38:56 2021
rabbitmq_erlang-source/signature                                                                                |  819 B  00:00:00
rabbitmq_erlang-source/signature                                                                                |  951 B  00:00:00 !!!
rabbitmq_rabbitmq-server-source/signature                                                                                |  836 B  00:00:00
rabbitmq_rabbitmq-server-source/signature                                                                                | 1.0 kB  00:00:00 !!!
356 packages excluded due to repository priority protections
Resolving Dependencies
--> Running transaction check
---> Package erlang.x86_64 0:24.1-1.el8 will be installed
--> Processing Dependency: libz.so.1(ZLIB_1.2.7.1)(64bit) for package: erlang-24.1-1.el8.x86_64
--> Finished Dependency Resolution
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest
(venv) [CORP\shiv.d@a-1njrk968l4brs yum.repos.d]$

It complains about zlib 1.2.7.1 which is already installed.

A: Not 100% sure, but it might be due to the Linux version n Amazon Linux.
As you can see in the Erlang package name, erlang.x86_64 0:24.1-1.el8.
It indicate that it is for Enterprise Linux 8.
If you try to run rpm -E %{rhel}, it will return you 7, hence you'll need the erlang that support el7


text:
Q: Is there a problem for TexStudio 3.01 on Mac? I do not succeed with downloading TexStudio 3.01 from https://www.texstudio.org and use it with MacAir, and the product is identified as malware. I have installed and used earlier versions of Texstudio including 2.12.22.
I have tried the advice of control clicking the icon, and then open, in order to sidestep the mis-identification of malware, but that did not help.
Is there a way to resolve the problem?

A: This is a common problem. The solution is to right click on the app's icon and select Open from the popup menu. You will then be presented with a window asking you to click the Open button if you're sure you want to open the application. This is mentioned on the TeXstudio download page next to the macOS download section.


text:
Q: Probability that iid uniform random variables equal the natural numbers I have random variables $X_1 , X_2 \ldots $ that $X_n\sim \text{Unif}\{ 1, \ldots , n\}$, and I want to calculate
$$\Bbb P ( \{ X_1 , X_2 , \ldots \} = \Bbb N )$$
My intuition is that this means each $X_n = n$, which occurs with probability $\frac 1 n$.
Does this seem correct?

A: Not quite. Just because we have $\{X_1,X_2,\dots\}=\mathbb{N}$, this does not necessarily imply that $X_1=1$, $X_2=2$, and so on. Rather, all we know is that the set of all $X_n$'s includes every natural number. For instance, we could have
$$(X_1,X_2,X_3,X_4,X_5,X_6,...)=(1,1,2,2,3,3,...).$$
There are infinitely many possible sequences. Moreover, the probability of any particular sequence of $(X_1,X_2,X_3,...)$ is $\frac{1}{2}\cdot\frac{1}{2}\cdot\frac{1}{3}\cdots =0$. So we'll have to reason differently.
Notice that $\{X_1,X_2,\dots\}=\mathbb{N}$ if and only if for every $n \in \mathbb{N}$, we have $n \in \{X_1,X_2,\dots\}$. Therefore we have $\{X_1,X_2,\dots\}\neq \mathbb{N}$ if and only if there exists $n \in \mathbb{N}$ such that $n \notin\{X_1,X_2,\dots\}$. So we can write
$$\{\{X_1,X_2,\dots\}\neq\mathbb{N}\} = \bigcup_{n \in \mathbb{N}} \{n \notin \{X_1,X_2,\dots\}\}.$$
We can use a union bound to write
$$P(\{X_1,X_2,\dots\}\neq \mathbb{N}) \leq \sum_{n=1}^\infty P(n \notin \{X_1,X_2,\dots\}).$$
The advantage of this is that the event $\{n \notin\{X_1,X_2,\dots\}\}$ implies $X_1 \neq n$, $X_2 \neq n$, $X_3 \neq n$, and so on. This is something we can actually calculate the probability of, assuming the $X_i$ are independent.
You should find that all of these probabilities are zero, so $P(\{X_1,X_2,\dots\}=\mathbb{N})=1$.

A: Since I am not confident with the reasoning inthe comment of the other answer I will give another last argumentation step.
Indeed, we can give the bound bound
$$\Bbb P(\{X_1,X_2,\dots\}\neq \mathbb{N}) \leq \sum_{n=1}^\infty \Bbb P(n \notin \{X_1,X_2,\dots\})$$
Now indeed
$$\Bbb P(n \notin \{X_1,X_2,\dots\}) = \Bbb P(X_1 \neq n , X_2 \neq n , \ldots) = \Bbb P(X_{n} \neq n , X_{n+1} \neq n , \ldots)$$
which is indeed an infinite product. But the fact that all factors are less thatn $1$ is not sufficient to conclude that that this product is zero. For example
$\prod_{k=1}^\infty e^{-\frac 1 {k^2}} = e^{-\sum_{k=1}^\infty \frac 1 {k^2}} = e^{- \frac{\pi^2}{6}}  > 0$. Therefore we need an additional argument. Now note that
$$\sum_{k=n}^\infty \Bbb P (X_k = n) = \sum_{k=n}^\infty \frac 1 k = \infty$$
The Borel-Cantelli lemma implies that
$$\Bbb P ( X_k = n \text{ for infinitely many } k \geq n) = 1$$
In particular we get $$\Bbb P ( X_k = n \text{ for at least one } k \geq n) = 1$$
which shows that $$\Bbb P(X_{n} \neq n , X_{n+1} \neq n , \ldots) =  0$$
All in all $\Bbb P(\{X_1,X_2,\dots\}\neq \mathbb{N}) = 0$.


text:
Q: Are there any good, general optimization algorithms for nonlinear regression in R? I have generated data similar to a model I want to build:
n = 1000

sample_data = data.frame(
  t = pmax(3, 4+rnorm(n)*3),
  x1 = rnorm(n),
  x2=rbinom(n, 50, 0.5)
)

B1 = 100
B2 = 0.5
B3 = 5
B4 = 0.1
B5 = 0.1
B6 = 0.01

sample_data$y = with(sample_data, x1 +
 (B1-x1+B2*x2) * (exp(max(t-(B3+B4*x2), 0) * (B5 + B6*x2)))) + rnorm(n)*50

This is similar to a thermodynamic system where a second unknown "temperature" exists (B1+B2*x2), along with a lag in a changing effect (B3+B4*x2), as well as a coefficient for that rate (B5+B6*x2).
My main goal in this scenario is to extract the parameters so that I can describe the underlying phenomena of the model.
I have attempted to use nls(), but it seems to be having difficulties with the specific model I am using, as I do not want to assume any coefficients for certain variables, including x1 and t, as the former is theoretically restricted, and the latter would be redundant.
I have attempted to build a log-likelihood function that takes in these parameters, as well as a $\hat{\sigma}^2$ estimate for the error, and then use optim() to maximize the log likelihood:
make_ll_function <- function(
  data
){

  # function to return
  model_func <- function(X){
    B1 = X[1]
    B2 = X[2]
    B3 = X[3]
    B4 = X[4]
    B5 = X[5]
    B6 = X[6]
    sigma2 = X[7]

    estimates = with(
      data,
      x1 + (B1-x1+B2*x2) * (exp(pmax(t-(B3+B4*x2), 0) * (B5 + B6*x2)))
    )

    ll = -nrow(data)/2 * log(sigma2)  -
      1/sigma2*sum(
        (data$y - estimates)^2
      )
    # invert for maximization
    return(-ll)
  }
  return(model_func)
}

initial_values = c(
  50,#B1
  1, #B2
  1, #B3
  1, #B4
  1, #B5
  0.1, #B6
  1000 # ballpark estimate of sigma^2
)

model_func = make_ll_function(sample_data)

(model_params = optim(initial_values, model_func,
                      method='SANN',
                      control=list(
                        maxit=100000,
                        ndeps=1e-4,
                        tmax=100,
                        temp=5
                      )))

When I run this, though, the parameter estimates are nothing like the original values. This is true even if I reduce the amount of error on the y term to have a standard deviation of 1.
The results are similar or worse for different optimization algorithms, and it is representative of the issue I am having with the regular data.
As for additional solutions I've tried:

*

*Increasing sample size barely helps

*Adding a huge penalty for any parameter going out of bounds (< 0 in this case) seems to work surprisingly well (I got an R^2 of about 0.8). I am guessing the behavior of the functions changes dramatically enough when certain signs are flipped that should not be flipped.

In many cases, though, I cannot rely heavily on (2), as I do not have a good idea of the bounds of a variable. I can possibly constrain the calculated quantities (e.g., B3+B4*x2) themselves to something reasonable using the same penalty method, but that's about it.
Edit: fixed max()->pmax()


text:
Q: Isomorphism question What would be an isomorphism between
$\mathcal{F}(S;V / U)$ and $\mathcal{F}(S;V)/ \mathcal{F}(S;U)$, where
$S$ is a set, $V$ a vector space and $U$ a subspace of $V$. $\mathcal{F}(A,B)$ denotes the set of functions from $A$ to $B$ and $V/U$ is the quotient space.

A: A $\varphi\in \mathcal F(S;V)$ can be viewed as a sequence indiced by the elements of $S$, and accordingly write $\varphi(s)$ as the $s^{\text{th}}$ coordinate $\varphi_s$. Apply the canonical $V\to V/U$ 'coordinatewise', giving an $\mathcal F(S;V)\to\mathcal F(S;V/U)$, see that its surjective and find its kernel.

A: To produce such an isomorphism we have to get a hold on the elements of $V/U$ without explicitly talking about a complement of $U$ in $V$.
A general element of $V/U$ is represented by elements $v\in V$, where $v$ and $v'\in V$ represent the same element $p\in V/U$ iff there is an $u\in U$ such that $v'=v+u$.
Therefore a general element  $\Phi\in {\cal F}(S,V/U)$ is represented by functions $\phi:\ s\mapsto v(s)\in V$, and any  $\phi\in{\cal F}(S,V)$ can be used to represent such a $\Phi$. Two  functions $\phi$,  $\phi'\in{\cal F}(S,V)$ represent the same $\Phi:\ S\to {\cal F}(S,V/U)$ iff for each $s\in S$  the values $\phi(s)$ and $\phi'(s)$ are equivalent mod $U$, i.e., iff for each $s\in S$ there is an $u=:u(s)\in U$ such that $\phi'(s)=\phi(s)+u(s)$. This is saying that the two functions $\phi$,  $\phi'\in{\cal F}(S,V)$ differ by a $\theta\in {\cal F}(S,U)$.


text:
Q: How to decrypt AWS S3 file during download? Here is my download code :
 IAmazonS3 client;

            string key = tenant_id + @"/files/" + filename;
            try
            {
                using (client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1))
                {
                    GetObjectRequest request = new GetObjectRequest
                    {
                        BucketName = existingBucketName,
                        Key = key
                    };

                    using (GetObjectResponse response = client.GetObject(request))
                    {
                        string dest = path;
                        if (!File.Exists(dest))
                        {
                            response.WriteResponseStreamToFile(dest);
                        }
                    }
                }
                return true;
            }

I would like to decrypt files during the download process. I've gone through the support docs but unable to proceed. What changes do I need to make in my current code to achieve this ?

A: It depends on how the file was encrypted. S3 supports client-side encryption and server-side encryption.
If the file is encrypted using server-side encryption, either S3 is managing the keys or you need to provide the key in your request. If the file was encrypted client-side prior to being uploaded to S3 then you must decrypt the downloaded file yourself. In this case check out the AmazonS3EncryptionClient to help make things easier.


text:
Q: Use Loader to load listview data in backgroud for smooth scrolling I have a custom listview which has more child views . When I scroll the listview it scrolls very slow leading to avoid the use of the application. I am very much new to android ,please help me how to load the data in background thread , so that the listview scrolls smooth
SearchListActivity.java
public class SearchListActivity extends ListActivity{

    String from[];
    static String longClickValue;
    int to[];
    static String name="",birthdate="",westerZodiac="",turnsAge="",nextBD="",eventType="";
    static Bitmap bitMap=null;
    //CustomCursorAdapter adapter;
    CustomSimpleCursor adapter;

    TextView emptyView;
    Cursor cursor=null;
    CursorLoader cursorLoader=null;
    ImageView imageV;
    @SuppressLint("NewApi") @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.search_list_activity);

        cursorLoader=new CursorLoader(this,BirthdayProvider.CONTENT_URI,null, null,null,null);

        cursor=cursorLoader.loadInBackground();

        from=new String[]{BirthdayProvider.NAME,BirthdayProvider.NUMBER,BirthdayProvider.CATEGORY,BirthdayProvider.EVENT_TYPE,BirthdayProvider.EVENT_DAY,BirthdayProvider.WESTERN_ZODIAC};

        to=new int[]{R.id.title_name,R.id.sub_title_contact_number,R.id.sub_title_category,R.id.txtview_type_of_reminder,R.id.sub_title_birthdate,R.id.txtview_zodiac};

        if (cursor.moveToFirst()) {
            adapter=new CustomSimpleCursor(this, R.layout.list_row, cursor, from, to);
            getListView().setAdapter(adapter);
        }

        else
        {
            emptyView=(TextView)getListView().findViewById(android.R.id.empty);
        }

        getListView().setLongClickable(true);

        getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> arg0, View v,int index, long arg3) {
                TextView txtName=(TextView)v.findViewById(R.id.title_name);
                name=txtName.getText().toString();

                imageV=(ImageView)v.findViewById(R.id.ImageView02);
                //imageV.setImageDrawable(getResources().getDrawable(R.drawable.rings_icon));

                ImageView imgView=(ImageView)v.findViewById(R.id.list_image);
                bitMap=((BitmapDrawable)imgView.getDrawable()).getBitmap();

                TextView label=(TextView)v.findViewById(R.id.sub_title_contact_number);

                longClickValue=label.getText().toString();

                Intent intent=new Intent(getBaseContext(),ContactInfoMoreOption.class);
                intent.putExtra("intentType","SearchListActivity");
                intent.putExtra("longClickValue",longClickValue);
                intent.putExtra("imgObj",imageV.toString());
                startActivity(intent);
                return true;
            }
        });

    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        TextView txtName=(TextView)v.findViewById(R.id.title_name);
        name=txtName.getText().toString();

        ImageView imgView=(ImageView)v.findViewById(R.id.list_image);
        bitMap=((BitmapDrawable)imgView.getDrawable()).getBitmap();

        TextView txtBirthdate=(TextView)v.findViewById(R.id.sub_title_birthdate);
        birthdate=txtBirthdate.getText().toString();

        TextView txtTurnsAge=(TextView)v.findViewById(R.id.txtview_turns);
        turnsAge=txtTurnsAge.getText().toString();

        TextView txtWesterZodiac=(TextView)v.findViewById(R.id.txtview_zodiac);
        westerZodiac=txtWesterZodiac.getText().toString();

        TextView txtNextBD=(TextView)v.findViewById(R.id.txtview_next_bd);
        nextBD=txtNextBD.getText().toString();

        TextView txtEventType=(TextView)v.findViewById(R.id.txtview_type_of_reminder);
        eventType=txtEventType.getText().toString();

        Intent intent=new Intent(getBaseContext(),ContactInfoActivity.class);
        startActivity(intent);
    }
}

CustomSimpleCursor.java
public class CustomSimpleCursor extends SimpleCursorAdapter{

    Typeface font;
    TextView txtDaysRemainigValue,txtTurnsAge;

    @SuppressWarnings("deprecation")
    public CustomSimpleCursor(Context context, int layout, Cursor c,
            String[] from, int[] to) {
        super(context, layout, c, from, to);
    }
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
            super.bindView(view, context, cursor);

            String todayBD = null;

            //Zodiac icon
            try {
                    ImageView thumbZodiacIcon = (ImageView) view.findViewById(R.id.ImageView01);
                    InputStream is = context.getResources().getAssets().open(cursor.getString(cursor.getColumnIndexOrThrow(BirthdayProvider.ZODIAC_ICON)));
                    Bitmap bit = /*BirthdayCalculation.ShrinkBitmap(is,200, 200);*/BitmapFactory.decodeStream(is);
                    thumbZodiacIcon.setImageBitmap(bit);

            } catch (Exception e1) {
                    e1.printStackTrace();
            }

         // Event icon
            try {
                    ImageView thumbEventIcon = (ImageView) view.findViewById(R.id.ImageView02);
                    InputStream is = context.getResources().getAssets().open(cursor.getString(cursor.getColumnIndexOrThrow(BirthdayProvider.EVENT_ICON)));
                    Bitmap bit =BitmapFactory.decodeStream(is);
                    thumbEventIcon.setImageBitmap(bit);

            } catch (Exception e1) {
                    e1.printStackTrace();
            }

            //Contact photo
            try {
                ImageView thumbContact = (ImageView) view.findViewById(R.id.list_image);
                byte bitmapData[]=cursor.getBlob(cursor.getColumnIndex(BirthdayProvider.PHOTO));
                Bitmap bit = BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length);
                thumbContact.setImageBitmap(bit);

                /*Animation localAnimation = AnimationUtils.loadAnimation(context,R.anim.fadein_image);
                thumbContact.startAnimation(localAnimation);*/

        } catch (Exception e1) {
                e1.printStackTrace();
        }

        //Days remaining for BirthDay

         txtDaysRemainigValue=(TextView)view.findViewById(R.id.txtview_days_left);

         String year=cursor.getString(cursor.getColumnIndex(BirthdayProvider.EVENT_YEAR));
         String month=cursor.getString(cursor.getColumnIndex(BirthdayProvider.EVENT_MONTH));
         String date=cursor.getString(cursor.getColumnIndex(BirthdayProvider.EVENT_DATE));
         String remainingDays=BirthdayCalculation.getDaysRemainingForNextBirthDay(year, month, date);

          Calendar today=Calendar.getInstance();
          int CMonth=(today.get(Calendar.MONDAY)+1);
          int CDate=(today.get(Calendar.DAY_OF_MONTH));

          txtDaysRemainigValue.setTextColor(Color.parseColor("#990000"));
          txtDaysRemainigValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, 27);

          //checking whether the BD is on TODAY

          if (remainingDays.equals("1") && (CDate==Integer.parseInt(date) && (CMonth)==Integer.parseInt(month))) {

              Log.v("else if executed","else if executed");
              Log.v("Remainin Days",remainingDays+" = Custom month"+cursor.getString(cursor.getColumnIndex(BirthdayProvider.NAME))+"="+(CMonth)+"="+month);
             Log.v("Remainin Days",remainingDays+" = Custom date"+ cursor.getString(cursor.getColumnIndex(BirthdayProvider.NAME))+"="+CDate+"="+date);
              txtDaysRemainigValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
              txtDaysRemainigValue.setTextColor(Color.parseColor("#00CC33"));
            remainingDays="today".toLowerCase();
        }

          //checking whether the BD is on TOMORROW
          else if (remainingDays.equals("1")) {

             Log.v("Remainin Days",remainingDays+" = Custom month"+cursor.getString(cursor.getColumnIndex(BirthdayProvider.NAME))+"="+(CMonth)+"="+month);
             Log.v("Remainin Days",remainingDays+" = Custom date"+ cursor.getString(cursor.getColumnIndex(BirthdayProvider.NAME))+"="+CDate+"="+date);
              txtDaysRemainigValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
              txtDaysRemainigValue.setTextColor(Color.parseColor("#FFFF00"));
            remainingDays="tomorrow".toLowerCase();
        }

        //checking how many days remaining BD
          else{
              remainingDays=BirthdayCalculation.getDaysRemainingForNextBirthDay(year, month, date);
              txtDaysRemainigValue.setTextSize(TypedValue.COMPLEX_UNIT_SP, 27);
              txtDaysRemainigValue.setTextColor(Color.parseColor("#990000"));

          }
          txtDaysRemainigValue=(TextView)view.findViewById(R.id.txtview_days_left);
          font=Typeface.createFromAsset(context.getAssets(), "DS_DIGIB.ttf");
          txtDaysRemainigValue.setTypeface(font);

          //Log.v("Custom month",cursor.getString(cursor.getColumnIndex(BirthdayProvider.NAME))+"="+(CMonth)+"="+month);
          //Log.v("Custom date", cursor.getString(cursor.getColumnIndex(BirthdayProvider.NAME))+"="+CDate+"="+date);
          txtDaysRemainigValue.setText(remainingDays);

      //Turns age
        font=Typeface.createFromAsset(context.getAssets(), "athletic.ttf");
        txtTurnsAge=(TextView)view.findViewById(R.id.txtview_turns);
        //txtTurnsAge.setTypeface(font);
        String turnsAge=BirthdayCalculation.getAge(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(date));
        txtTurnsAge.setText(turnsAge);

      //Event week
        try {

            TextView txtEventWeek=(TextView)view.findViewById(R.id.txtview_next_bd);
            String eventWeek=BirthdayCalculation.getDayOfWeek(year, month, date);
            font=Typeface.createFromAsset(context.getAssets(), "Comic Sans.ttf");
            txtEventWeek.setTypeface(font);
            txtEventWeek.setText(eventWeek);

        } catch (Exception e) {
            e.printStackTrace();
        }

        // Contact Name

        TextView txtNumber=(TextView)view.findViewById(R.id.sub_title_contact_number);
        font=Typeface.createFromAsset(context.getAssets(), "Roboto_Light.ttf");
        txtNumber.setTypeface(font);

        TextView txtBirtgDay=(TextView)view.findViewById(R.id.sub_title_birthdate);
        font=Typeface.createFromAsset(context.getAssets(), "Roboto_Light.ttf");
        txtBirtgDay.setTypeface(font);

        TextView txtZodiac=(TextView)view.findViewById(R.id.TextView02);
        font=Typeface.createFromAsset(context.getAssets(), "Roboto_Light.ttf");
        txtZodiac.setTypeface(font);

        TextView txtZodiacValue=(TextView)view.findViewById(R.id.txtview_zodiac);
        font=Typeface.createFromAsset(context.getAssets(), "Comic Sans.ttf");
        txtZodiacValue.setTypeface(font);

        TextView txtNextBD=(TextView)view.findViewById(R.id.TextView01);
        font=Typeface.createFromAsset(context.getAssets(), "Roboto_Light.ttf");
        txtNextBD.setTypeface(font);

        TextView txtTurnsAge=(TextView)view.findViewById(R.id.list_image_arrow);
        font=Typeface.createFromAsset(context.getAssets(), "athletic.ttf");
        txtTurnsAge.setTypeface(font);

        TextView txtDayRemainig=(TextView)view.findViewById(R.id.TextView04);
        font=Typeface.createFromAsset(context.getAssets(), "athletic.ttf");
        txtDayRemainig.setTypeface(font);

        TextView txtTurnsAgeValue=(TextView)view.findViewById(R.id.txtview_turns);
        font=Typeface.createFromAsset(context.getAssets(), "DS_DIGIB.ttf");
        txtTurnsAgeValue.setTypeface(font);

    }
}

A: To improve speed of your listview your must complete next steps:

*

*Use ViewHolder patter because view.findViewById is slow operation.

*You can load all needed typeface before. Your every time load same typefaces. For example Typeface.createFromAsset(context.getAssets(), "Roboto_Light.ttf")

*You can load all zodiac icon before because i think that zodiac icon has limit count

*if photo is big image than you can load image from another thread.
I think it is enough.

A: according to your code try this
public void bindView(View view, Context context, Cursor cursor) {
 switch (view.getId) {
   case R.id.ImageView01:
    // your code here
   break;
   case R.id.ImageView02:
   // your code here
   break;

  }
}


text:
Q: Dynamic items in Shell flyout, without losing static items? While using the MAUI Shell class (with XAML), I am struggling to find a way to add dynamic flyout items without losing existing static items. I have tried using a Shell.FlyoutContentTemplate, but that seems to replace the entire contents of the flyout with my template, and completely hides the static items that I want to keep. Does anyone know how to do this successfully?
<Shell
    x:Class="Frostgrave_Helper.AppShell"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:Frostgrave_Helper"
    Title="Frostgrave Warbands"
    FlyoutBackground="{AppThemeBinding Light={StaticResource IceBrush}, Dark={StaticResource IceBrushDark}}">

    <Shell.FlyoutHeaderTemplate>
        <DataTemplate>
            <Grid BackgroundColor="#00000000"
                  HeightRequest="200">
                <Image Aspect="AspectFit"
                       Source="frostgrave.png" />
            </Grid>
        </DataTemplate>
    </Shell.FlyoutHeaderTemplate>

    <Shell.FlyoutContentTemplate>
        <DataTemplate>
            <StackLayout>
                <ListView x:Name="MenuItemsListView"
                          SeparatorVisibility="None"
                          HasUnevenRows="true"
                          ItemsSource="{Binding WarbandNames}">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <ViewCell>
                                <StackLayout Padding="15,10"
                                             HorizontalOptions="FillAndExpand">
                                    <Label VerticalOptions="FillAndExpand"
                                           VerticalTextAlignment="Center"
                                           Text="{Binding}"
                                           TextColor="Black"
                                           FontSize="20"/>
                                </StackLayout>
                            </ViewCell>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </StackLayout>
        </DataTemplate>
    </Shell.FlyoutContentTemplate>

    <ShellContent Title="New warband..."
                Icon="plus_solid.png"
                ContentTemplate="{DataTemplate local:views.NewWarbandPage}" />

    <ShellContent Title="About"
                Icon="circle_info_solid.png"
                ContentTemplate="{DataTemplate local:About}" />

    <Shell.FlyoutFooterTemplate>
        <DataTemplate>
            <StackLayout>
                <Label Text="Tetra Software Consultancy"
                       TextColor="Black"
                       HorizontalOptions="Center" />
            </StackLayout>
        </DataTemplate>
    </Shell.FlyoutFooterTemplate>
</Shell>

A: You can add a certain ShellContent in code behind with a button click or something else .
Sample  code
private void Button_Clicked(object sender, EventArgs e)
{
    ShellContent content = new ShellContent();
    content.Title = "test";
    content.FlyoutIcon = "dotnet_bot.svg";
    content.Content = new MainPage();

    AppShell.Current.Items.Add(content);
}


text:
Q: Restricting a generic parameter in the scope of a method Let's say that we have a class Foo<T> which represents some operation that produces a value of type T. I would like to be able to compose two objects of this class in the case that one produces a Function<A, B> and the second one produces an A to get a Foo<B>. I can do that with the following static method:
public static <T, U> Foo<U> compose(Foo<Function<T, U>> fn, Foo<T> x) {
    // the composition is an implementation detail
}

Now I can easily compose a fooAtoB of type Foo<Function<A, B>> with a fooA of type Foo<A> like this:
compose(fooAtoB, fooA)

Unfortunately, in my case it is common for Foo to produce nested functions like Function<A, Function<B, Function<C, D>>> and I'd like to be able to compose these with Foo<A>, Foo<B> and Foo<C> to get a Foo<D>.
I can do that with the following:
compose(compose(compose(fooAtoBtoCtoD, fooA), fooB), fooC);

This works, but there's a lot of nesting and the readability suffers because of that. Ideally, what I'd like to be able to do is something like this:
fooAtoBtoCtoD.compose(fooA).compose(fooB).compose(fooC)

But as far as I can tell, it's impossible to express such a thing, as there's no way to name the return type of compose, because compose has no way of knowing whether or not the T in Foo<T> is actually a Function<U, V>.
It's quite easy to do it the other way:
<U> Foo<U> compose(Function<T, U> fn)

But this is, again, not very nice to use.
fooC.compose(fooB.compose(fooA.compose(fooAtoBtoCtoD)))

The arguments are written from right to left and there's lots of nesting.
This brings me to the question:
Is there a way to restrict Foo's T parameter to a subset of types only in the scope of the compose method so that it can take advantage of that restriction?
Something that would allow me to express the following would be great:
T extends Function<U, V> in the scope of
<U, V> Foo<V> compose(Foo<U> x) {
    // values of type T are convertible to Function<U, V>
    // in the scope of this method
}

Right now I think that nothing like that exists and that the proof of T being a function must come from the outside when calling compose, so something like this:
<U, V> Foo<V> compose(Function<T, Function<U, V>> fn, Foo<U> x) {
    // I can use fn#apply to convert a T to a Function<U, V> here
}

works fine when given the identity function:
fooAtoBtoCtoD.compose(x -> x, fooA).compose(x -> x, fooB).compose(x -> x, fooC)

But it's a bit too long and repeating x -> x all over is not fun.
A solution to that might be to package the function together with Foo. Given the following class:
class FooWithIdentity<T, U> extends Foo<T> implements Function<U, U> {
    @Override
    U apply(U val) {
        return val;
    }

    ...
}

and the following two methods in Foo:
<P extends Foo<U> & Function<T, Function<U, V>>, U, V> Foo<V> compose(P foo)
{
    Function<U, V> fun = foo.apply(value);
    return new Foo<>(fun.apply(foo.value));
}

<U> FooWithIdentity<T, U> wrap() {
    return new FooWithIdentity<>(this);
}

I've achieved the following:
fooAtoBtoCtoD.compose(fooA.wrap()).compose(fooB.wrap()).compose(fooC.wrap())

Which is, in my opinion, the best solution so far.
EDIT: Radiodef's solution gave me an idea for a simpler solution with the same interface:
class Foo<T>
{
    ...
    <U> U through(Function<Foo<T>, U> fn) {
        return fn.apply(this);
    }

    <U> Function<Foo<Function<T, U>>, Foo<U>> composing() {
        return fooFn -> /* compose fooFn and this here */;
    }
}

Essentially, through just takes a function and runs this through it and composing produces a function that does the actual composition, together they can be used like this:
Foo<D> fooD = fooAtoBtoCtoD
    .through(fooA.composing())
    .through(fooB.composing())
    .through(fooC.composing());

A: Another variant would be to make e.g. the following methods:
class Foo<T> {
    ...
    <U> Foo<U> map(Function<T, U> fn) {
        return new Foo<>(fn.apply(this.value));
    }
    static <T, U> Function<Function<T, U>, U> composing(Foo<T> t) {
        return fn -> fn.apply(t.value);
    }
}

That would let you do e.g. this:
Foo<D> fooD =
    fooAtoBtoCtoD.map(composing(fooA))
                 .map(composing(fooB))
                 .map(composing(fooC));

(Here's a working example.)
That's not really any shorter, but it's a little more clear about what it's doing.
As for the hope of something like abc.compose(a).compose(b), not in Java at the moment, unfortunately.
I think it would be possible in principle for the Java compiler to support some kind of instance method-level generics like <A,B> where 'this' must be a Foo<Function<A,B>>, though. It doesn't require anything more than checking the type of the reference at the method call site, so it's not like erasure prevents it.
Usually when Java is missing a generics feature it's because erasure makes it impossible to implement, like generic constructor calls, but I don't think that's the case here. The method body (which requires T be a Function) could erase to casts like ((Function) this.value).apply(a).


text:
Q: Displaying a image in a div I am having problems to display a image in a div element.
In the div is a custom web control (a login control).
   <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" Theme="Styles" %>
<%@ Register src="wucLogin.ascx" tagname="wucLogin" tagprefix="log" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Login</title>
    <link rel="Stylesheet" type="text/css" href="App_Themes/Styles/LoginStyleSheet.css" />
</head>
<body>
    <form id="form1" runat="server">
        <div id="divLogin">

        <log:wucLogin id="WebUserControlLogin" runat="server" />
        </div>
    </form>
</body>
</html>

Everything gets displayed as it should. A basic login control with some basic layout and a blue background.
But when i try to put a picture in the div i cannot get it to display. I tried every possible path for the image so i do not think i have made a error there.
Basicly i want the login control to display, with behind it a picture (centered).
Css for the div element (the map images is directly a map in the root:
#divLogin
{
    background-image: url('../Images/test2.png');
    background-repeat: no-repeat;
    background-position:center;

    position: absolute;
    text-align: center;

    top: 40%;
    left: 52.8%;
    width: 401px;
    height: 123px;
    margin-top: -61,5px;
    margin-left: -250px;
}

Best regards.

A: I dont see an ID of "divLog" on your page .. just "divLogin" .. could that be the issue?

A: change position to relative, and put the login stuff inside the image div. also update the top and left for the relative positioning.
just a thought.


text:
Q: Issue of using field of type array in rails There might be a group of records in a table where only two fields vary record by record, and rest fields remains same. This calls for a normalization by splitting by a table through a foreign key association. But, in Ruby-on-Rails, it would mean the creation of a model. So, is it still possible to lessen use of disk space?
May be, it is, because it would be reasonable that storing multiple values of one column in a record would require the column to be an array of any type. But declaring the field to be :array type results in an error. So, is there a way to work around it?

A: After generating a model, open the model's file. Insert one line for each field.

serialize :field_name

But ensure that the fields for which you are serializing, should be of type

:text

or

:string

If they aren't of such primitive data types, i.e. of another type like

:datetime

then it would return an error.
This step is not complete as a whole. You need to do one complementing step: de-serialize, because in the model-level storage, it is stored as a string starting with "---\n-", which is not suitable for array-type operations.
While reading data from the model, you need to perform the following step:

YAML.load(field_name)

where field_name refers to the field that was serialized.
The above step would return an array, on which you can perform normal array operations.


text:
Q: VBA, MS Access - Set text box to query I have a form, a combobox (dropdown menu) and a textbox.
When a specific value from the combobox is chosen, I want the textbox to query for values in a table.
This is my idea, but it's not working:
Private Sub Combobox1_Click()
If Me.Combobox1.Value = "London" Then

    Dim SQL As String

    SQL = "SELECT tabel_prices.[London]" _
        & "FROM tabel_prices "

    Me.TextBox1.Value = SQL

End If
End Sub


text:
Q: How to create custom query for getting user id in Repository Symfony My tasks is to get the current user products. I have a listCartProductsAction in CartController with following lines of code:
  public function listCartProductsAction()
    {
        $cartProducts = $this->getDoctrine()->getRepository('AppBundle:CartProduct')->findByUser($this->getUser()->getId());

        return $this->render('cart/cart.view.html.twig', array(
            'cartProducts' => $cartProducts
        ));
    }

In the CartRepository im trying to create a query which get the products of current user, but it's definitely not correct:
 public function findByUser($user)
    {
        $query = $this
            ->getEntityManager()
            ->createQuery("SELECT u FROM AppBundle:Cart u WHERE u.IDENTITY = ?1")
            ->setParameter(1, $user->getUser()->getId());
        return $query->getResult();
    }

When i try to display the products in the twig template, i got exception:

Call to a member function getUser() on integer

Any ideas how to prevent this error ?
After var_dump($cartProducts);
`array (size=2)
  0 =>
    object(AppBundle\Entity\Cart)[898]
      private 'id' => int 1
      private 'userId' =>
        object(AppBundle\Entity\User)[765]
          private 'id' => int 8
          private 'email' => string 'rumen@abv.bg' (length=12)
          private 'username' => string 'Rumkata97' (length=9)
          private 'name' => string 'Rumen Panchev' (length=13)
          private 'password' => string '$2y$13$1QVBSg.uPPMdln6N/5/3DOjubxWtpkZYYtWlHEPc2S.JPx24Qz3Ce' (length=60)
          private 'image' => string 'c066099438bc7e258cc0ba21fa9d1b31' (length=32)
          private 'image_form' => null
          private 'products' =>
            object(Doctrine\ORM\PersistentCollection)[789]
              ...
          private 'role' => string 'ROLE_ADMIN' (length=10)
          private 'cart' =>
            object(Doctrine\ORM\PersistentCollection)[815]
              ...
      private 'dateCreated' =>
        object(DateTime)[900]
          public 'date' => string '2017-04-25 17:21:58.000000' (length=26)
          public 'timezone_type' => int 3
          public 'timezone' => string 'Europe/Berlin' (length=13)
      private 'dateUpdated' =>
        object(DateTime)[904]
          public 'date' => string '2017-04-25 18:02:30.000000' (length=26)
          public 'timezone_type' => int 3
          public 'timezone' => string 'Europe/Berlin' (length=13)
  1 =>
    object(AppBundle\Entity\Cart)[899]
      private 'id' => int 3
      private 'userId' =>
        object(AppBundle\Entity\User)[765]
          private 'id' => int 8
          private 'email' => string 'rumen@abv.bg' (length=12)
          private 'username' => string 'Rumkata97' (length=9)
          private 'name' => string 'Rumen Panchev' (length=13)
          private 'password' => string '$2y$13$1QVBSg.uPPMdln6N/5/3DOjubxWtpkZYYtWlHEPc2S.JPx24Qz3Ce' (length=60)
          private 'image' => string 'c066099438bc7e258cc0ba21fa9d1b31' (length=32)
          private 'image_form' => null
          private 'products' =>
            object(Doctrine\ORM\PersistentCollection)[789]
              ...
          private 'role' => string 'ROLE_ADMIN' (length=10)
          private 'cart' =>
            object(Doctrine\ORM\PersistentCollection)[815]
              ...
      private 'dateCreated' =>
        object(DateTime)[901]
          public 'date' => string '2017-04-27 14:28:53.000000' (length=26)
          public 'timezone_type' => int 3
          public 'timezone' => string 'Europe/Berlin' (length=13)
      private 'dateUpdated' =>
        object(DateTime)[902]
          public 'date' => string '2017-04-27 15:06:50.000000' (length=26)
          public 'timezone_type' => int 3
          public 'timezone' => string 'Europe/Berlin' (length=13)`

A: I think the problem is pretty simple: The findByUser function gets the int id of the user (through $this->getUser()->getId()), but still wants to call some functions on it, which of course doesn't work. Instead, the line in the findByUser function should be:
->setParameter(1, $user);


text:
Q: Rescale large numerical factors in rational functions Given a rational function
$$
f(x_1,x_2) = \dfrac{r_1 x_1^2 + r_2 x_2}{r_3 x_1 + r_4 x_2},
$$
with $r_i$ arbitrary real or complex numbers,
is there a built-in function to get Mathemtica to rewrite as
$$
f(x_1,x_2) = \dfrac{x_1^2 + \frac{r_2}{r_1}x_2}{\frac{r_3}{r_1} x_1 + \frac{r_4}{r_1} x_2} ?
$$
I wrote a function that finds $r_{max}$ (the $r_i$ with largest modulus) and rescales all other $r_i$'s by the $r_{max}$:
rescale[x_] :=
Module[
{
out, scale
}
,
out = x;
scale =
Cases[out,z_ /; Head[z] === Complex || Head[z] === Real, Infinity] // Union;
scale = First[SortBy[scale, Abs[#] &]];
out = out /.
{z_Complex :> Simplify[z/scale],
r_Real :> Simplify[r/scale]};
out
];

Is there a built in Mathematica function that does this? If not, in what ways can I improve this function?
Context: I have such rational functions where the $r_i$ all end up having ridiculously large modulus (say $\cal{O}(|r_{max}|) \sim 10^{750}$), and they clean up nicely under such a replacement.


text:
Q: how to nginx configuration updates without having to reload or restart nginx I want Nginx to update configuration file without reloading or restarting Nginx. It seem API or anything (http://nginx.com/products/on-the-fly-reconfiguration/).

A: On Ubuntu or Debian it's as simple as using the reload argument:
service nginx reload

The official way is to send SIGHUP:
kill -HUP $(ps -ef | grep nginx | grep master | awk '{print $2}')

The above command will get the process ID of the nginx master process and send a SIGHUP signal to it.
See the Controlling Nginx documentation for Nginx.
You can also use the Nginx binary:
nginx -s reload


text:
Q: How do I get access to the "last_hidden_state" for code generation models in huggingface? I'm trying to obtain the "last_hidden_state" (as explained here) for code generation models over here. I am unable to figure out how to proceed, other than manually downloading each code-generation-model and checking if its key has that attribute using the following code -
import numpy as np
from datasets import load_dataset
from transformers import AutoTokenizer
from transformers import AutoModel, AutoModelForCausalLM
import torch
from sklearn.linear_model import LogisticRegression

from transformers import AutoTokenizer, AutoModelWithLMHead

tokenizer = AutoTokenizer.from_pretrained("codeparrot/codeparrot")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = AutoModelWithLMHead.from_pretrained("codeparrot/codeparrot").to(device)

inputs = tokenizer("def hello_world():", return_tensors="pt")
inputs = {k:v.to(device) for k,v in inputs.items()}
with torch.no_grad():
    outputs = model(**inputs)
print(outputs.keys())

So far, I tried this strategy on CodeParrot and InCoder with no success. Perhaps there is a better way to access the values of the hidden layers?

A: The hidden_states of output from CodeGenForCausalLM is already the last_hidden_state for the codegen model. See: link
where hidden_states = transformer_outputs[0] is the output of CodeGenModel (link) and the transformer_outputs[0] is the last_hidden_state
        if not return_dict:
            return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)

        return BaseModelOutputWithPast(
            last_hidden_state=hidden_states,
            past_key_values=presents,
            hidden_states=all_hidden_states,
            attentions=all_self_attentions,
        )


text:
Q: How to Delist a dataframe row whose value is a list I want to convert the below data frame into space-separated in python.
Like:
0  ['raj', 'kumar']
1  ['kill', 'bill']

To
0  raj kumar
1  kill bill

A: try using reduce for each row in the dataframe
data=[{'value': ['raj', 'kumar']},
{'value':  ['kill', 'bill']}]
df=pd.DataFrame(data)
print(df)
def concatWords(lst):
    return functools.reduce(lambda x,y: x+" "+y,lst)
df["value"]=df["value"].apply(concatWords)
print(df)

output:
value
0  raj kumar
1  kill bill


text:
Q: MPI_Scatter : Scatter Eigen Matrix I am trying to implement an MPI_Scatter using eigen matrix using following :
// get pointer to samples
double *X = prob.x;
// map the samples into the matrix object
MatrixXd globaldata = Map<MatrixXd>(X, dims, nsmp);
MatrixXd localdata;
int size, rank;

MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);

if (rank == 0) {
    printf("Processor %d has data before Scatter \n", rank);
    cout << globaldata<<endl<<endl;
}

MPI_Scatter(globaldata.data(), 1, MPI_DOUBLE, &localdata, 1, MPI_DOUBLE, 0,
        MPI_COMM_WORLD);

printf("Processor %d has data \n", rank);
cout << localdata << endl;

The output of MatrixXd globaldata is :
        -1         -1         -1         -1
 -0.997455  -0.996032  -0.998472  -0.996154
  -0.94402  -0.912698  -0.966387  -0.915385
 -0.974555  -0.960317  -0.984721  -0.961538
  -0.46056 -0.0753968  -0.676089   0.423077
         1          1          1          1

Then I  try to scatter the eigen Matrix gloaldata using
MPI_Scatter(globaldata.data(), 1, MPI_DOUBLE, &localdata, 1, MPI_DOUBLE, 0,
            MPI_COMM_WORLD);

However i don't think above is correct. How can i scatter the above eigen matrix column by column so that when i run  mpirun -np 4 ./mpitest for example i see each column of eigen matrix mapped to each process or the 2 mapped to each process if np is 2? Is the send_datatype and recv_datatype correct i-e MPI_DOUBLE?

A: In MPI_Scatter, the count (which you have as 1) is the number of elements sent to each process. To distribute the matrix evenly amongst "size" processes then you need to set count to 16/size (for your 4x4 matrix example).
This relies on all the data in the matrix being stored as a single contiguous block of memory - you'll need to check that's the case for MatrixXd types, although I'd guess it would be true.
Again, whether the scatter distributes rows or columns depends on your storage order. For standard C arrays, on 4 processes you would send a separate row to each process, not a  column. However, Eigen seems to default to column-major storage (standard for Fortran but not for C) which would then mean you are sending entire columns.

A: You need to allocate space for the receive buffer. Simply defining a variable as double * doesn't reserve any storage so you will get an error. I think the same is true for your original example - localdata is defined but it looks like no storage space is allocated.
To get the code working, you could try:
double X1[24]; // This is more storage than you need but its safe
...
MPI_Scatter(X, 4,MPI_DOUBLE, X1, 4, MPI_DOUBLE, 0, MPI_COMM_WORLD)

Although the error is occurring in MPI_Scatter, I think the source of the problem is that there's some confusion here between pointers and allocating arrays.


text:
Q: Java regular expression to match specific integer values separated by a dot delimiter Basically I'm trying to implement three regular expressions as specified below -

*

*First regular expression should match at the least the literal string 10.1 or any string like 10.1.0.0 or 10.1.1.0 or 10.2.1.0 or 10.2.1.1 and so on but it should at the least match 10.1 or any higher versions. I tried the following regular expression
\d+\.\d+(\.\d+\.\d+)*
but this matches even lower versions such as 9.1.1.0 or 9.1 and so on.

*Second regular expression should match anything higher than the string literal 10.1 but not 10.1 but it should match any other string like 10.2 or 10.3 or 10.1.0.0 or 10.1.1.0 or 10.2.1.0 or 10.2.1.1 or 10.2 or 10.3 or 11.1.1.0 or 11.1 and so on. Tried the following but did not match the expectation (\\d+)\\.(\\d+)(.*)

*Third regular expression should match anything lower than the string literal 10.1 but not 10.1 but it should match any other string like 10.0 or 9.1 or 9.2 or 9.1.1.0 or 9.1 or 9.1.2.0.
Basically how do I match the literal string like 10.1 followed by any optional numbers separated by a dot and how do I match anything higher or lower than the literal string like in my 1st, 2nd and 3rd points?
I'm still trying to modify my regular expression to match my requirement, any help/guidance will be very helpful.

A: Not really feasible as "4" < "10" and such. Better work on ints.
class Version implements Comparable<Version> {
    final int[] parts;
    Version(String vs) {
        parts = Stream.of(vs.split("\\.")).mapToInt(Integer::parseInt).toArray();
    }

    @Override
    public String toString() {
        return Arrays.stream(parts)
            .map(Integer::toString)
            .collect(Collectors.joining("."));
    }

    @Override
    public int compareTo(Version other) {
        return Arrays.compare(parts, other.parts);
    }
    ...
}

Version version1 = new Version("10.0.1");
Version version2 = new Version("1.2.1");
if (version1.compareTo(version2) <= 0) {
    System.out.printf("%s <= %s%n", version1, version2);
}

There is a coding principle on which this approach is based:

Do not use primitive types immediately for a specific quantity/entity.
Wrap it in a value class.

A: There is another way to convert each "." separated number to a fixed length string. For example, "1.2.3.4" becomes "0001000200030004" if the maximum number of digits for each number is 4. Use "****" if there are no numbers. ("****" is less than "0000") For example, "11.2" becomes "00110002********".
You can compare strings thus converted with String.compare().
An example of sorting by converted numbers is shown below.
static final int NUMBER_SIZE = 4;
static final String UNDEF_NUMBER = "*".repeat(NUMBER_SIZE);
static final Pattern VERSION_PAT = Pattern.compile(
    "(\\d+)\\.(\\d+)(?:\\.(\\d+)(?:\\.(\\d+))?)?");

static String fixed(String s) {
    return s == null ? UNDEF_NUMBER : "0".repeat(NUMBER_SIZE - s.length()) + s;
}

public static String normalize(String version) {
    Matcher m = VERSION_PAT.matcher(version);
    if (!m.matches())
        throw new IllegalArgumentException("version");
    return fixed(m.group(1)) + fixed(m.group(2))
         + fixed(m.group(3)) + fixed(m.group(4));
}

public static void main(String[] args) {
    String[] versions = {
        "10.1", "10.1.0", "10.2", "10.3", "10.1.0.0", "10.1.1.0",
        "10.2.1.0", "10.2.1.1", "10.2.0", "10.3.0", "11.1.1.0",
        "10.0", "9.1", "9.2", "9.1.1.0", "9.1.2.0"
    };
    record Pair(String version, String normalized) {}
    Arrays.stream(versions)
        .map(version -> new Pair(version, normalize(version)))
        .sorted(Comparator.comparing(Pair::normalized))
        .forEach(pair -> System.out.printf("%16s : %s%n", pair.version, pair.normalized));
}

output:
         9.1 : 00090001********
     9.1.1.0 : 0009000100010000
     9.1.2.0 : 0009000100020000
         9.2 : 00090002********
        10.0 : 00100000********
        10.1 : 00100001********
      10.1.0 : 001000010000****
    10.1.0.0 : 0010000100000000
    10.1.1.0 : 0010000100010000
        10.2 : 00100002********
      10.2.0 : 001000020000****
    10.2.1.0 : 0010000200010000
    10.2.1.1 : 0010000200010001
        10.3 : 00100003********
      10.3.0 : 001000030000****
    11.1.1.0 : 0011000100010000


text:
Q: Comparision test for this series? How do I check divergence of this series?
$$\sum_{n=0}^{\infty} \frac{6}{4n-1} - \frac{6}{4n+3}$$
Wolframalpha said it used the comparision test but I don't see what possible smaller sum to use?
It's also a telescoping series but I don't know how that is useful in this case?!

A: $\sum_{n=0}^m(6/(4 n-1)-6/(4 n+3)) = -6/(4 m+3)-6$
where m is finite for the rearranging, but now we let it go $\to \infty$.
What happens?

A: $$\sum_{n=0}^{\infty} \frac{6}{4n-1} - \frac{6}{4n+3}=24\sum_{n=0}^{\infty}\frac{1}{(4n-1)(4n+3)}$$ Now as $4n-1>n$ f0r $n>0$ and $4n+3>n$ so
$$\frac{1}{(4n-1)(4n+3)}\leq \frac{1}{n^2}$$