text:
Q: Linq sort with a twist I have the following records

The last 2 are children of record 3 and 4, I would like to be able to sort the records by amount but it should be that the non interest(parents) ones are sorted first then their children should show up after so for example it would be like this
2000
2000
20001
99.84 (child of the above)
50000
249.58 (child of the above)

Basically I would like my sort by amount to disregard the one with "IsInterest" set to true but make them show up after their parent.
I can do this by first taking all the parents into a new collection.. then go through the parent to see if there is any children then insert them after the parent in the new collection but I feel this is not efficient and dirty code so I thought I would ask maybe someone knows black magic.
The sort should also be aware of asc/desc on the amount.
I can post my code of ripping the collection apart and putting it together if it helps but I am trying not to use that code if possible.
My sort method takes a string for "ascending" or "descending" if that helps
Thank you
UPDATE2
I will point out that there is only ever going to be 2 levels, and that the children will ever only have one parent (no grand parents) and that each parent will have a maximum of 1 child
UPDATE code as requested (fields name may differ from the db fields..)
 switch (sortMember.ToUpper())
            {
                case "AMOUNT":
                    {
                        //check to see if any imputed interests exist
                        if (contributions.Any(x => x.IsImputedInterest))
                        {
                            var children = contributions.Where(x => x.IsImputedInterest);
                            var sortedColl = contributions.Where(x => x.IsImputedInterest == false).OrderByWithDirection(x => x.ContributionAmount, sortDirection.ToUpper() == "DESCENDING").ToList();
                            foreach (var child  in children )
                            {
                                //find the parent
                                var parentIndex = sortedColl.FindIndex(x => x.ContributionId == child.ParentContirbutionId);
                                sortedColl.Insert(parentIndex+1, child);

                            }

                        }
                        else
                        {
                            contributions = contributions.OrderByWithDirection(x => x.ContributionAmount, sortDirection.ToUpper() == "DESCENDING");
                        }

                        break;
                    }
            }

.................
 public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, bool descending)
    {
        return descending ? source.OrderByDescending(keySelector)
                          : source.OrderBy(keySelector);
    }

    public static IOrderedQueryable<TSource> OrderByWithDirection<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, bool descending)
    {
        return descending ? source.OrderByDescending(keySelector)
                          : source.OrderBy(keySelector);
    }

A: Here's a single statement Linq solution:
var desc = order == "descending";
var result = list
    //group parents with it's children
    .GroupBy(x => x.ParentId ?? x.Id)
    //move the parent to the first position in each group
    .Select(g => g.OrderBy(x => x.ParentId.HasValue).ThenBy(x => desc ? -x.Amount : x.Amount))
    //sort the groups by parents' amounts
    .OrderBy(g => desc ? -g.First().Amount : g.First().Amount)
    //retrieve the items from each group
    .SelectMany(g => g);

Some performance hints:

*

*You can drop the ThenBy(...) if there's always going to be at most one child or you don't care about children order

*Use an if statement to check the order and have two versions of the statement - the second one using OrderByDescending/ThenByDescending, and drop the ternary operator (desc ? ... : ...) - otherwise it will be evaluated for each item

I'm not giving any guarantees on performance in relation to your current solution - it might as well turn out to be slower.

A: You can use the following generic method (not limited by levels or number of parent/children):
public static class Extensions
{
    public static IEnumerable<T> ThenByHierarchy<T, TKey>(this IOrderedEnumerable<T> source, Func<T, TKey> keySelector, Func<T, TKey> parentKeySelector)
    {
        var itemByKey = source.ToDictionary(keySelector);
        var processSet = new HashSet<T>();
        var stack = new Stack<T>();
        foreach (var item in itemByKey.Values)
        {
            for (var next = item; processSet.Add(next); )
            {
                stack.Push(next);
                if (!itemByKey.TryGetValue(parentKeySelector(next), out next)) break;
            }
            while (stack.Count != 0)
                yield return stack.Pop();
        }
    }
}

Just append it at the end of your OrderBy sequence like this
var result = contributions
    .OrderByWithDirection(x => x.ContributionAmount, sortDirection.ToUpper() == "DESCENDING")
    .ThenByHierarchy(x => x.ContributionId, x => x.ParentContirbutionId);

UPDATE: It turns out that it's not so simple. While the method above provides a correct order for the leaf elements as well for the element to its parent, it does not order correctly the parents. The correct one is as follows (using another reusable method from here How to flatten tree via LINQ?, so if we don't count that it isn't really much bigger than the previous):
public static class Extensions
{
    public static IEnumerable<T> HierarchicalOrder<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector, Func<T, TKey> parentKeySelector, Func<IEnumerable<T>, IOrderedEnumerable<T>> order)
    {
        // Collect parent/child relation info
        var itemById = source.ToDictionary(keySelector);
        var childListById = new Dictionary<TKey, List<T>>();
        var rootList = new List<T>();
        foreach (var item in itemById.Values)
        {
            var parentKey = parentKeySelector(item);
            List<T> childList;
            if (parentKey == null || !itemById.ContainsKey(parentKey))
                childList = rootList;
            else if (!childListById.TryGetValue(parentKey, out childList))
                childListById.Add(parentKey, childList = new List<T>());
            childList.Add(item);
        }
        // Traverse the tree using in-order DFT and applying the sort on each sublist
        return order(rootList).Expand(item =>
        {
            List<T> childList;
            return childListById.TryGetValue(keySelector(item), out childList) ? order(childList) : null;
        });
    }
    public static IEnumerable<T> Expand<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> elementSelector)
    {
        var stack = new Stack<IEnumerator<T>>();
        var e = source.GetEnumerator();
        try
        {
            while (true)
            {
                while (e.MoveNext())
                {
                    var item = e.Current;
                    yield return item;
                    var elements = elementSelector(item);
                    if (elements == null) continue;
                    stack.Push(e);
                    e = elements.GetEnumerator();
                }
                if (stack.Count == 0) break;
                e.Dispose();
                e = stack.Pop();
            }
        }
        finally
        {
            e.Dispose();
            while (stack.Count != 0) stack.Pop().Dispose();
        }
    }
}

and the usage in your case is simple
var result = contributions
    .HierarchicalOrder(x => x.ContributionId, x => x.ParentContirbutionId, c =>
    .OrderByWithDirection(x => x.ContributionAmount, sortDirection.ToUpper() == "DESCENDING"));


text:
Q: When is a row actually inserted into DB? When is a row actually inserted into the database? Is it when "INSERT" statement is finished? or when "COMMIT" statement is finished after "INSERT" statement?

A: If you are running inside a transaction, when the transaction is committed.  Otherwise, immediately.

A: Later than you think. The principles here apply generally.
The whole point of the transaction log is to ensure ACID works in case of a power failure just as the INSERT finishes. The INSERT will be rolled forward or rolled back as part of the recovery phase (in most RDBMS)
So, it's more important that the transaction log entry is acknowledged as stored on the media. Then the INSERT can commit.
The data page containing the changed row will end up on disk eventually (checkpoint etc) but not necessarily at the point of successful commit.
However, the data page is in memory and available for use.
Note, an INSERT could cause a page split, indexes to be updated, triggers to fire etc so what I've said is simplified.
And it doesn't matter one way or the other when the data ends up on disk: as long as I can get the data and it's safe in case of, say, power failure
An oldie but still relevant for SQL Server: SQL Server 2000 I/O Basics
And what I've summarized is Write Ahead Logging

A: Depends on the database/table implementation. It might just be when the transaction log is integrated - until which time the row is only inserted in the transaction log, and in memory.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python Geoip2 maxminddb.reader error in EC2 server Hi I am facing a issue with below code.
PS : Its working fine with my local machine but facing issues in servers.
import geoip2.database

def get_geo_city_from_ip(ip="103.148.20.109"):

    try:
        reader = geoip2.database.Reader('GeoLite2-City.mmdb')
        response = reader.city(ip)
        city=response.city.name
        reader.close()
        return city
    except Exception as e:
        return None
a = get_geo_city_from_ip()
print("City ####",a)

Error
Traceback (most recent call last):
  File "test.py", line 2, in <module>
    import geoip2.database
  File "/var/www/html/geo/test/lib/python3.5/site-packages/geoip2/database.py", line 10, in <module>
    import maxminddb
  File "/var/www/html/geo/test/lib/python3.5/site-packages/maxminddb/__init__.py", line 5, in <module>
    import maxminddb.reader
  File "/var/www/html/geo/test/lib/python3.5/site-packages/maxminddb/reader.py", line 36
    _buffer: Union[bytes, FileBuffer, "mmap.mmap"]
           ^
SyntaxError: invalid syntax

Packages & Version
Python 3.5.2
aiohttp==3.6.2
async-timeout==3.0.1
attrs==20.2.0
certifi==2020.6.20
chardet==3.0.4
geoip2==4.0.2
idna==2.10
idna-ssl==1.1.0
maxminddb==2.0.2
multidict==4.7.6
pkg-resources==0.0.0
requests==2.24.0
simplegeoip2==1.0.2
typing-extensions==3.7.4.3
urllib3==1.25.10
yarl==1.5.1

A: Are you use python 3.7+ in local machine?
Not support annotation var type in python 3.5.
Like error exc info.
 _buffer: Union[bytes, FileBuffer, "mmap.mmap"]

Use python 3.7+ in your ec2 server, all is ok.

A: Its working after I changed the
geoip2==2.9.0
maxminddb==1.4.1


text:
Q: Entity Spaces - Save issues when using SQLServer session state We have been working with Entity Spaces and everything was working great on our local development machines until we started using SqlServer for our Session management.
Our hosting service (ITech) has a server farm so it is imperative that we get this working against SqlServer for the session management.
The issue that we are seeing is on the save of objects that were placed into session and then later retrieved. The rowstate for the objects are getting reset to invalid instead of added etc.
We contacted Entity Spaces for assistance and their advice was to use "their" serialization method to convert the objects into a string and then placing the string into the session. When we attempted this, the primary object was being serialized properly but it did not attempt to serialize any child objects in the object graph. For instance, a loan object with a list of borrowers hanging off of it. The loan itself would be serialized but not the borrowers list.
If I serialized manually to binary and store that into the session, the entire object graph is there but now we are back to the rowstate not being set properly. I decided to work around this by creating my own rowstate property called "Status". I then would set the Status property to the objects rowstate just before I serialized to binary. Then I would flip the rowstate from invalid to whatever Status was set to when I deserialized the object. This all "looked" right in the debugger but, when I told it to save, Entity Spaces did not create the right SQL.  It tried to save without the values of the properties of the entity.
Has anyone else attempted this and if so, did you find a solution?


text:
Q: How do I remove duplicates WITHIN a row using Power Query? I have data that looks like this:

Wire
Point1
Point2
Point3
Point4
Point5
Point6

A
WP1
WP1
WP2

WP2

B
WP3
WP4
WP3

WP4

C
WP5
WP5
WP6
WP7
WP6
WP7

(note the varying lengths of each row, and the duplicates)
I would like to have the end result be:

Wire
Point1
Point2
Point3

A
WP1
WP2

B
WP3
WP4

C
WP5
WP6
WP7

Duplicates removed, and blank spaces removed.
This would be VERY similar to the =UNIQUE() function, but that is not available in power query.

A: It's a lot easier to work with columns, so I'd recommend unpivoting the Point columns, removing duplicates, and then putting it into the shape you want.
Here's a full query you can past into your Advanced Editor to look at each step more closely:
let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WclTSUQoPMEQijYAkBIHYsTrRSk5gtjGYNIGzYWpMwGqcwWxTJNIMTJqjsGNjAQ==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Wire = _t, Point1 = _t, Point2 = _t, Point3 = _t, Point4 = _t, Point5 = _t, Point6 = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Wire", type text}, {"Point1", type text}, {"Point2", type text}, {"Point3", type text}, {"Point4", type text}, {"Point5", type text}, {"Point6", type text}}),
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"Wire"}, "Attribute", "Value"),
    #"Filtered Rows" = Table.SelectRows(#"Unpivoted Other Columns", each ([Value] <> "")),
    #"Removed Duplicates" = Table.Distinct(#"Filtered Rows", {"Wire", "Value"}),
    #"Grouped Rows" = Table.Group(#"Removed Duplicates", {"Wire"}, {{"Point", each Text.Combine([Value],","), type text}}),
    #"Split Column by Delimiter" = Table.SplitColumn(#"Grouped Rows", "Point", Splitter.SplitTextByDelimiter(",", QuoteStyle.Csv), {"Point1", "Point2", "Point3"})
in
    #"Split Column by Delimiter"

A: *

*Unpivot

*Group by Wire

*

*Aggregate into sorted List of Unique Points

*Calculate Max number of items in all the Lists to use in the later Column Splitter

*Extract the List of points into semicolon separated string

*Split into new columns

M Code
let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source, List.Transform(Table.ColumnNames(Source), each {_, Text.Type})),

//Unpivot
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"Wire"}, "Attribute", "Value"),
    #"Removed Columns" = Table.RemoveColumns(#"Unpivoted Other Columns",{"Attribute"}),

//Group by Wire
//Aggregate by sorted, unique list of Points for each Wire
    #"Grouped Rows" = Table.Group(#"Removed Columns", {"Wire"}, {
        {"Point", each List.Sort(List.Distinct([Value]))}}),

//Calculate the Max unique Points for any Wire (for subsequent splitting
maxPoints = List.Max(List.Transform(#"Grouped Rows"[Point], each List.Count(_))),

//Extract the List values into a semicolon separated list
    #"Extracted Values" = Table.TransformColumns(#"Grouped Rows",
        {"Point", each Text.Combine(List.Transform(_, Text.From), ";"), type text}),

//Then split into new columns using the semicolon delimiter
    #"Split Column by Delimiter" = Table.SplitColumn(#"Extracted Values", "Point",
        Splitter.SplitTextByDelimiter(";", QuoteStyle.Csv),maxPoints)

in
    #"Split Column by Delimiter"


text:
Q: Cakephp Ajax Login is loggin in even with wrong data I have a simple html form to login outside my cake structure, I send the login data via jquery to my login function:
public function login() {
        if ($this->request->is('ajax')) {

            $this->request->data['Appuser']['password'] = Security::hash($this->request->data['password']);
            $this->request->data['Appuser']['name'] = $this->request->data['name'];

            if ($this->Auth->login()) {
                return $this->redirect($this->Auth->redirectUrl(array('action' => 'returnUserData')));
            }else{
                $this->response->body(json_encode('Login failed!'));
            }
        }elseif($this->request->is('post')){
            if ($this->Auth->login()) {
                return $this->redirect($this->Auth->redirectUrl());
            }else{
                $this->Session->setFlash(__('Invalid username or password, try again'));
            }
        }
    }

The very strange thing is:

*

*the login via post from /view/users/login.ctp form works perfectly!

*When I try to login from "outside" via ajax, I am always logged in even with wrong access details and get the data from function 'returnUserData'
$('#login').click(function() {
          $.ajax({
              type: "POST",
              url: '/api/login',
              data: {
                  name:     $("#username").val(),
                  password: $("#password").val()
              },
              success: function(data)
              {
                  alert(data);
              }
          });

      });

When I set a debug(); after  if ($this->request->is('ajax')) I can see it, so the script seems to go into the right if section. But I don't get it, why the $this->Auth->login always return true...?


text:
Q: grails 5 web-plugin profile throwing missing ServletWebServerFactory bean question first for those in a hurry:
Should I define a separate ServletWebServerFactory bean for the plugin? Or do I want it to ignore looking for it since it seems to work just fine with the root app's servlet factory
Further details:
Exception in thread "main" org.springframework.context.ApplicationContextException:
Unable to start web server; nested exception is
org.springframework.context.ApplicationContextException: Unable to start
ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.

at grails.boot.GrailsApp.run(GrailsApp.groovy:99)

I have a multi-project grails app. Root app loads a plugin with the profile "web-plugin"
grails:
    profile: web-plugin

I generated the plugin scaffolding using the default grails command line (
grails create-plugin), so most settings are default for grails 5.
When I run the main app, it builds and starts the plugin first. When it hits the plugin's generated Application.main method, it blows up
 @PluginSource
 class Application extends GrailsAutoConfiguration {
   static void main(String[] args) {
      //blows up here saying there is no ServletWebServerFactory bean
      GrailsApp.run(Application, args)
   }
 }

Then, the root app- which has the ServletWebServerFactory Bean defined - starts fine. From the running root app I can access and run the plugin endpoints even though it encountered the exception..
How should I address the error? To repeat the question: Should I define a separate ServletWebServerFactory bean for the plugin? Or do I want it to ignore looking for it since it seems to work just fine with the root app's servlet factory?

A:
To repeat the question: Should I define a separate
ServletWebServerFactory bean for the plugin?

No.
If your dependencies are configured correctly I don't expect you will have the problem if you run the main method in the app (as distinct from the plugin).


text:
Q: Flutter - prevent tap/click events from being passed through view hierarchy I'm looking for the best way to stop tap/click events from being propagated up the view hierarchy. Suppose we have a simple scenario with a TextField decorated with a an 'X' clear text button.
When I click the "X" button the click event is propagated up to TextField's onPressed().
final _textEditingController = TextEditingController(text: "");

@override
Widget build(BuildContext context) {
  return TextFormField(
    controller: _textEditingController,
    onTap: onEditTextTapped,
    decoration: InputDecoration(
      suffixIcon: IconButton(
        onPressed: onClearTextClick,
        icon: Icon(
          Icons.clear,
          size: 20.0,
        ),
      ),
    ),
    style: TextStyle(fontWeight: FontWeight.normal, fontSize: 18),
  );
}

void onEditTextTapped() {
  print('TextField tapped');
}

void onClearTextClick() {
  print('clear text clicked');
}

The result is:
flutter: clear text clicked
flutter: TextField tapped

I need something similar to Android's android:clickable="true" or Flutter's AbsorbPointer that would trap all click events and stop them from being passed through to the view beneath BUT only when I click 'clear text' button. Click event from TextFormField should still trigger onEditTextTapped()
Flutter (Channel stable, v1.9.1+hotfix.2, on Mac OS X 10.14.5 18F132)

A: Use pointer_interceptor widget, especially if you target Web with complex layouts involving maps, Stack, drawers, Positionned widgets, etc. So in your case it would be something like:
import 'package:pointer_interceptor/pointer_interceptor.dart';
...
return TextFormField(
    controller: _textEditingController,
    onTap: onEditTextTapped,
    decoration: InputDecoration(
      suffixIcon: PointerInterceptor(
        child: IconButton(
          onPressed: onClearTextClick,
          icon: Icon(
            Icons.clear,
            size: 20.0,
          ),
        ),
      ),
    ),
    style: TextStyle(fontWeight: FontWeight.normal, fontSize: 18),
  );

A: use Stack as an option :D
  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.centerRight,
      children: <Widget>[
        TextFormField(
          controller: _textEditingController,
          onTap: onEditTextTapped,
          decoration: InputDecoration(
            suffixIcon: IconButton(
              onPressed: onClearTextClick,
              icon: Icon(Icons.clear, size: 20.0),
            ),
          ),
          style: TextStyle(fontWeight: FontWeight.normal, fontSize: 18),
        ),
        IconButton(
          onPressed: onClearTextClick,
          icon: Icon(Icons.clear, size: 20.0),
        ),
      ],
    );
  }


text:
Q: Openlayers setStyle method applied to a feature doesn't visually change the style? I'm using the select interaction with OpenLayers:
My goal is to simply change the UI display on the map through the feature rather than a layer. Here is what I'm attempting now:
selectClick.getFeatures()
selectClick.getFeatures().item(0)
selectClick.getFeatures().item(0).setStyle(
                new Style({
                    stroke: new Stroke({
                        color: '#7e0101',
                    }),
                    fill: new Fill({
                        color: 'rgba(36, 37, 42, .25)',
                    }),
                }),
            );

By logging selectClick.getFeatures().item(0).getStyle() before and after the change I'm able to see that the style for the feature has been modified. However this doesn't result in a visual update. Any suggestions? Do I have to make the change on the layer instead?


text:
Q: How do you build a gadget + mobile app that work together through bluetooth? The company I work at is looking to create a gadget. Something like rollerskates. We want to build a mobile app that comes with it where you can use to see your location and where you've travelled.
How does something like this work? Is there a bluetooth chip that we need to buy and insert into the machine? Is there anything like this? I see companies like Rocketskate (https://www.kickstarter.com/projects/petertreadway/acton-r-rocketskates-worlds-first-smart-wearable-m) doing this.
Any help would be really appreciated thank you.

A: I would start with a Low energy BT eval board from Nordic Semiconductor.  If you buy the eval board,  you can use one of their template apps for iOS or Android to send the data to the mobile device.
If you are going to get fancy, you'll need to write some code for the BT radio node embedded processor side , send the data over the BT profile to the phone, and display/process it.
They have everything you need in one place and it's the easiest to get started.
Good luck.


text:
Q: Best way to point out the mistakes in an answer / post Consider the flow of events:

*

*User A asks a question

*User B answers it

*I downvote the answer with a comment explaining the downvote

Now that they understand who downvoted their answer, they just go to one of my answers / questions and downvote it. To avoid this, I have the following options:
Downvote without an explanation -
The answerer wouldn't come to know who downvoted their post and also wouldn't be able to know what's wrong with the answer. If nobody points out the mistake, it'll remain as it is. I'm not sure if this is a good thing. If answers contain incorrect information, it should be corrected (or deleted).
Ignore the downvote and move on - This is the easiest solution. One downvote is not an end of the world. I could simply ignore the (revenge-)downvote(s) I receive from the explanation and move on to the next question / answer.
I've already read similar posts on Meta and I understand that serial downvotes will be taken care of -- and that I can e-mail Stack Overflow team if the downvotes follow some sort of pattern.
What's the best way to handle this issue? Should I just stop explaining the reason, just downvote the post and move along? Or maybe I should leave a very polite comment explaining what's wrong with their answer. If so, how?

A: Don't mention that you downvoted, just post a comment pointing out why the answer is wrong without mentioning downvotes at all. Of course the user can guess that it might have been you that downvoted, but you don't have to remind them. Don't attack the user or the answer as a whole (e.g. "this answer is terrible"), just point out the specific problem in a comment.
If the user starts to respond agressively, just flag the comments if appropriate and walk away, don't engage in a discussion under such circumstances and you'll avoid unnecessary trouble.
If a user retaliates with downvotes, let the automatic reversal script deal with it. This catches most revenge voting, and if a user is evading it you can flag for moderator attention and they'll deal with it. You might have to live with a very small amount of downvotes, it is almost impossible to prove bad intentions with only one or two votes, but you are pretty safe from any serious retaliation with downvotes.
In short, try to comment in a way that is unlikely to be perceived as an attack, and don't be afraid of retaliation by unreasonable users, there are ways to deal with them.


text:
Q: HTML2PDF - table align css I am using html2pdf plugin with my php script and I encounter an issue to align my table. I did a test with a simple HTML page, and my css works, but as soon as I put it with HTML2PDF, it doesn't work. Does anybody know a trick to perform it ?
Here my code:
I declared my css content like that:

and into my php script, I did:

    <?php
    echo "
Average
";

    $fields_numAvgAmp = mysqli_num_fields($resultMoyLecAmp);
    //Get column names
    $fieldsMoyLecAmp = mysqli_query($conn,'SHOW columns FROM '.$tablename.'AmpliconValues');
    //Columns_to exclude
    $columns_to_exclude= array('Amplicon');
    echo "
";
    ...
    ?>


text:
Q: What's the best practice for renaming a table and adding attributes to the same table? From a best practice point of view which is better:

*

*Create a migration that changes the name of a table and adds attributes to that table in a single migration.

OR

*

*Create a migration for the table change and another one for the change of attributes.

A: Step 1: Create a new migration
$ bin/rails generate migration RenameOldTable_to_NewTable

Step 2: Inside the migration file, add this code.
class RenameOldTableToNewTable < ActiveRecord::Migration[5.0]
  def change
    rename_table :old_table_name, :new_table_name
  end
end

Step 3: Run the migration
$ bundle exec rake db:migrate

This is a very simple way to rename a table using migration. All the attributes will remain same as old table.


text:
Q: Why RSA is said to be faster than ElGamal Encryption? For RSA, every block of plaintext needs to be exponentiated by the private key: p^e (mod n)
For ElGamal, every block of plaintext is multiplied by the secret key s*m (mod n)
So I thought ElGamal would be faster than RSA for encryption.  However most online articles say RSA is faster than ElGamal, why is that?


text:
Q: Adding conditional statement to Array.from() I have the following code,
AllDays= Array.from(moment.range(startDate, endDate).by('day')).map(day => day.format('YYYY-MM-DD'));

I would like to add a conditional to it so if a given day in the range start - end is chosen it is NOT included in the generated array.
So say the range is 1st-4th, I would like to specify if its the 3rd do not include it in the array.
I can do this by looping over the array AFTERWARDS and removing the dates but was wondering if there was a way to do it from within ?

A: Just slice the elements from 0 to length - 1:

this['moment-range'].extendMoment(moment);

let startDate = '2022-04-01';
let endDate = '2022-04-04';

let allDays = Array.from(moment.range(startDate, endDate).by('day')).map(day => day.format('YYYY-MM-DD')).slice(0,-1);

console.log(allDays /* except the last */);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/4.0.2/moment-range.js"></script>

A: const datesToRemove = new Set(ArrayOfDatesToRemove);
AllDays = AllDays.filter(date => !datesToRemove.has(date));

I was able to solve this using filter


text:
Q: inside div element find out mouse position? i done one concept of  program is find out mouse coordinate position inside div element ... its perfectly working in IE browser only but i cant get answer in mozilla firefox... what is the reason??????????
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<title>Cursor position status display</title>

A: Your function may be working perfectly fine, your problem is probably the window.status part: https://developer.mozilla.org/en/DOM/window.status

This property does not work in default configuration of Firefox and some other browsers: setting window.status has no effect on the text displayed in the status bar.

Maybe try outputing the coordinates into some other element in the page, or better yet, if you have something like Firebug, you can output use the console.


text:
Q: Text wrap in matrix context Before I use the matrix facility. I can wrap text inside a box simply by specifying the align=left property then \\
However, in the matrix context, this seems not working. I want the graph like this

However the following code compiles fail on This is \\ node D under matrix
\documentclass[border=5mm, convert]{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes, positioning, matrix}
\usepackage{lmodern}
\usepackage{underscore}

\begin{document}
\begin{tikzpicture}[auto]
    \tikzset{myrect/.style={rectangle, rounded corners, align=left, minimum width=3cm, minimum height=1cm, draw=black}}

    \node [myrect] (a) {This is node A};
    \node [myrect, below = of a] (b) {This is \\ node B};

    \matrix (matrix1) [below = of b, nodes = {myrect}, matrix of nodes, row sep=1cm] {
        This is node C \\
        {This is \\ node D} \\
    };
\end{tikzpicture}
\end{document}

The line wrapping under matrix only works when I am adding things like text width = 3cm, but this seems redundant to align=left.
Can anyone help me out?

A: \matrix (matrix1) [below = of b, nodes = {myrect}, matrix of nodes, row sep=1cm] {
    This is node C \\
    \shortstack{This is \\ node D}\\};


text:
Q: How to make a sub menu from a parent menu Fiddle: https://jsfiddle.net/n3tzbn4o/2/
Sample Css:
/* Reset */
.menu, .menu2,
.menu ul, .menu2 ul,
.menu li, .menu2 li,
.menu a, .menu2 a,
ul, li {
    margin: 0;
    padding: 0;
    border: none;
    outline: none;
}

For the parent menu menu 3 sub menu 2015, how come the sub submenu is inheriting from the menu class and not the menu2 class? Also, how come the hover doesn't change color for the second item inside the menu2 class ul.
Please help me resolve the issue

A:
For the parent menu menu 3 sub menu 2015, how come the sub submenu is inheriting from the menu class and not the menu2 class?

Actually, the sub submenu is inheriting from the .menu2 class.

Also, how come the hover doesn't change color for the second item inside the menu2 class `ul.

Because you have a syntax error in your li tags.

Correct the tags from <l1> ... </l1> to <li> ... </li>, and the link will work.


text:
Q: Angular 8 - PDF generation using jsPdf Im using jsPdf to generate a PDF document which captures my html screen contents. I can see my downloaded PDF file in the download folder.
Can we change the path where the PDF is getting downloaded? Instead of having the default c:/downloads can we change the path?

A: Answer to your question is NO. It is not possible to change default download folder from Angular/Javascript or any other framework/language for that matter. It is forbidden due to user's security. That decision is always handled by the browser.
You could however define a Content-Disposition header that tells the browser if the file is supposed to be displayed inline or if it an attachment that can be downloaded and saved locally.


text:
Q: Significance of the [Net.SecurityProtocolType] enumeration constants? Why does the SecurityProtocolType enum have the following constants:

Enum Value
Enumeration Constant

Ssl3
48

Tls
192

Tls11
768

Tls12
3072

Tls13
12288

I notice that each integer is 4 times the previous one, but would integer values of 1, 2, 4, 8, 16 not suffice to allow for bitwise operations?

*I have omitted the 'SystemDefault' value (0) because presumably this is mutually exclusive from the others?


text:
Q: Functional calculus for $C^{*}$-algebras I am new to $C^{*}$-algebras and, although I know there are a lot of references in which the functional calculus is proved, I was trying to prove it myself with my own reasoning and words. I have already proved Gelfand Isomorphism Theorem, so it can be used in the proof.
So, let $\mathcal{A}$ be a $C^{*}$-algebra with unit and $a\in \mathcal{A}$ be normal. I want to prove that $C^{*}(a) \cong C(\sigma(a))$, where $C^{*}(a)$ is the unital abelian $C^{*}$-algebra generated by $a$, $\sigma(a)$ is the spectrum of $a$ relative to $\mathcal{A}$ and $\sigma_{C^{*}(a)}(a)$ is the spectrum of $a$ relative to $C^{*}(a)$, which is the same as $\sigma(a)$.
Attempt of Proof: By Gelfand Isomorphism Theorem, I know that $C^{*}(a) \cong C(\widehat{C^{*}(a)})$. The mapping $\hat{a}: \widehat{C^{*}(a)}\to \mathbb{C}$ is injective because every character on $C^{*}(a)$ is completely determined by its values on the generating element $a$. Moreover:
$$\operatorname{Im}(\hat{a}) = \{\hat{a}(\varphi): \varphi \in \widehat{C^{*}(a)}\} = \{\varphi(a): \varphi \in \widehat{C^{*}(a)}\} = \sigma_{C^{*}(a)}(a) = \sigma(a) $$
and it follows that $\hat{a}: \widehat{C^{*}(a)} \to \sigma(a)$ is a homomorphism, so $\widehat{C^{*}(a)} \cong \sigma(a)$. Therefore, if $\hat{b} \in C(\widehat{C^{*}(a)})$ then $b\circ \hat{a}^{*} \in C(\sigma(a))$ is an algebra $*$-isomorphism. Thus, $C^{*}(a) \cong C(\sigma(a))$ is an algebra $*$-isomorphism and, in particular, $a \mapsto \hat{a}\circ \hat{a}^{*} = \operatorname{Id}$ is the identity map from $\sigma(a)$ to $\mathbb{C}$.
Is my proof correct?

A: Your argument is correct, but some clarifications are needed.
You argued that $\hat a$ is bijective.  You want to conclude that it is a homeomorphism (you have a typo in there). This requires you to show that it is bicontinuous, which in turn makes look at the topologies involved. The crucial point is to consider the weak$^*$-topology on $\widehat{C^*(a)}$, which makes it compact. The continuity of $\hat a$ now follows from the definition of the weak$^*$-topology, and the continuity of $(\hat a)^{-1}$ follows from the compactness of $\widehat{C^*(a)}$.


text:
Q: Buffered output for fs.readfile() in Nodejs why below code is giving buffered output even though "utf-8" is the default encoding?
    fs.readFile('includes/India2011.csv',function (err, data) {
    if (err) throw err;
    console.log(data);
    });

A: From the documentation:

If no encoding is specified, then the raw buffer is returned.

You have to specify utf-8 encoding like this:
fs.readFile('includes/India2011.csv', 'utf-8', function (err, data) {
    if (err) throw err;
    console.log(data);
});

documentation


text:
Q: I have question about an example code in Microsoft Docs "FREETEXT (Transact SQL)" I want to use Freetext statement for search a phrase in SQL Server 2016 not separated words base on this sample code in Microsoft Docs.(https://learn.microsoft.com/en-us/sql/t-sql/queries/freetext-transact-sql?view=sql-server-2017)
USE AdventureWorks2012;
GO

DECLARE @SearchWord NVARCHAR(30);
SET @SearchWord = N'high-performance';

SELECT Description
FROM Production.ProductDescription
WHERE FREETEXT(Description, @SearchWord);
GO

Is it a definition for using "-" in freetext?
Looks there is no difference between "high performance" and "high-performance" in results.


text:
Q: Execute function multiple times without using a loop I have a simple table with IDs:
ObjectId
----------
100
101
102

I'd would like to execute a function fn_GetStuff(Id) multiple times like this:
fn_GetStuff(100)
fn_GetStuff(101)
fn_GetStuff(102)

Is it possible to do this without using a loop?
I tried this it doesn't work:
SELECT *
FROM myTable
INNER JOIN fn_GetStuff(myTable.ObjectId)

A: OP is using a in-line table valued function it looks like so they would need a CROSS APPLY...
Select  *
From    myTable mt
Cross   Apply schema.fn_GetStuff(mt.ObjectID) f

A: Assuming your function is a scalar-valued function, you can just do:
select fn_GetStuff(Objectid)
from myTable

If your function is table valued, then you would need to use cross apply.

A: You don't need to join because there isn't another table. You should be okay to do this:
SELECT fn_GetSTuff(t.ObjectId)
FROM myTable t


text:
Q: Testing Web Services Consumer Here are some tools that I have found to test web services consumers:
http://www.soapui.org/
https://wsunit.dev.java.net/
Are there any others? I would prefer testing frameworks that are written in Java or Python.

A: I have used soapui by a maven plugin. It can create junit-linke reports to be run and analysed like unit tests. This can be easily integrated in continious build, also with the free distribution of soapui.

A: I've  used Web Service Studio.

Web Service Studio is a tool to invoke web methods interactively. The
  user can provide a WSDL endpoint. On clicking button Get the tool
  fetches the WSDL, generates .NET proxy from the WSDL and displays the
  list of methods available. The user can choose any method and provide
  the required input parameters. On clicking Invoke the SOAP request is
  sent to the server and the response is parsed to display the return
  value.
This tool is meant for web service implementers to test their web
  services without having to write the client code. This could also be
  used to access other web services whose WSDL endpoint is known.

Also the Web Services Explorer in Eclipse which comes as part of the Web Tools Platform.

Through UDDI and WSIL, other applications can discover WSDL documents
  and bind with them to execute transactions or perform other business
  processes. The Web Services Explorer allows you to explore, import,
  and test WSDL documents.

A: The Grinder is right up your ally with both Java and Python, that handles most web services, (SOAP/REST/CORBA/RMI/JMS/EJB) etc.
http://grinder.sourceforge.net/

A: You really need to be more specific: What is it that you want to test in your WS-consumer? That it calls the right WS? This looks a bit pointless - WS are a perfect place for mocking whatever may be called - without anything being called.
In order to test the consumer you'd otherwise be writing a Webservice that mocks the original, right? I'd suppose that the communication protocol that goes through the wire is not the clients domain - e.g. it's generated. So the only thing a WS-consumer's client sees is the interface. And there's nothing to test in an interface.
It might be that I completely misunderstood your question - please clarify if I did. I'll revise the answer then.


text:
Q: If a step fails in a test case but test cases passes , extent report shows whole test case as failed even though final status of test case is passed I am using DataProvider for my test cases, and with one of the data a step fails in test case but test case passes, testNG shows the test case as passed but extent report show it as failed. Extent Report screenshot

A: To provide the reportStep("Sample Test", "pass"); in each testcase.
eg:
@test
public void verifylogin(){
reportStep("UserName entered successfully", "pass");
}

@test
public void verifylogin(){
reportStep("Email entered successfully", "pass");
}

So that you got the output like this


text:
Q: Diffable 3D Modeling Format I would like to create a 3D model using software development-like collaboration.  Ideally, I'd like to store a 3D model as a diffable file/files in git.  Is there a format/tool that can do this?
Right now, the closest solution I have come up with is to use Python scripting in Blender.  For obvious reasons, this makes it more difficult to actually create the model though.
TIA.

A: If you use a text-based format such as Wavefront .OBJ, git will show you diffs, but they're unlikely to be helpful.  However, if you know the kind of output you want, you can use a filter to customize diff output for particular file types.  This section of Pro Git on binary diffs gives an example of using .gitattributes to define a command which should be used to generate the text which is used for diffing two files.  You could similarly write a script that summarized properties of your 3D model file, so that the output of git diff for them is more helpful.

A: It seems that the best solution today is to rely on a procedural description of the model's creation.  Not ideal.


text:
Q: Convert object for writing to firebase? (Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray) I have an array like this: var myArray = [(String, Int)]()
I would like to write this to Firebase, but get the error: "Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray"
When I do this: ("\(myArray)") when updating childValues, it goes through, but it also writes all the ""´s, ()´s and \´s
I have a webpage that reads from Firebase, and I would like to make it look nicer by removing the extra characters.
Is it possible to convert my array or something to make Firebase accept it?

A: Your array is an array of tuples and a tuple is not one of the supported types.
You could map the tuple to a real array
let realArray = myArray.map{[$0.0, $0.1]}

Please consider this note from the documentation:

Tuples are useful for temporary groups of related values. They're not suited to the creation of complex data structures. If your data structure is likely to persist beyond a temporary scope, model it as a class or structure, rather than as a tuple.


text:
Q: Table Join Across Main Query and Subquery My database contains the following tables:
TABLE SALESCOUNT
-----------------------------------
| id | startWeek  | repID | sales |
-----------------------------------
| 1  | FY13M01W01 | 0001  |   4   |
| 2  | FY13M01W01 | 0002  |   8   |
| 3  | FY13M01W02 | 0001  |   5   |
| 4  | FY13M01W02 | 0002  |   9   |
...

TABLE SALES
----------------------------------------------------
| id | salesRepID | salesDate  | division  | team  |
----------------------------------------------------
| 1  |   0001     | 2013-01-01 |   divA    | teamA |
| 2  |   0002     | 2013-01-01 |   divC    | teamA |
| 3  |   0001     | 2013-01-01 |   divD    | teamD |
| 4  |   0002     | 2013-01-08 |   divB    | teamC |
...

TABLE DEPT
-------------------------------
| id | repID | region | dept  |
-------------------------------
| 1  | 0001  |   01   |   A   |
| 2  | 0002  |   02   |   B   |
| 3  | 0001  |   C    |   A   |
| 4  | 0002  |   02   |   B   |
...

TABLE GEO
-----------------------------------
| id | geo   | regionA | regionB  |
-----------------------------------
| 1  | geoA  |   01    |     A    |
| 2  | geoA  |   02    |     B    |
| 3  | geoB  |   03    |     C    |
| 4  | geoB  |   04    |     D    |
...

TABLE FISCALWEEK
--------------------------------
| id | salesDate  | startWeek  |
--------------------------------
| 1  | 2013-01-01 | FY13M01W01 |
| 2  | 2013-01-08 | FY13M01W02 |
...

The following query returns the desired results:
SELECT y.startWeek, SUM(y.sales), dept.dept, geo.geo
FROM salesCount as y,
(
    SELECT DISTINCT a.salesRepID
    FROM sales AS a
    WHERE (a.team IN ("teamA", "teamB", "teamC)
        AND a.saleDate BETWEEN "2013-01-01" AND "2013-06-30"
        AND a.division IN ("divA", "divB", "divC")
) as x
INNER JOIN dept
    ON x.salesRepID = dept.repID
INNER JOIN geo
    ON dept.region = geo.regionA OR dept.region = geo.regionB
WHERE x.salesRepID = y.repID
    AND y.startWeek BETWEEN "FY13M01W01" AND "FY13M06W04"
GROUP BY y.startWeek, geo.geo, dept.dept
ORDER BY y.startWeek ASC, geo.geo ASC, dept.dept ASC

My goal is to utilize the FISCALWEEK table to generate the 2 date pairs (1 in the WHERE clause of the subquery and 1 in the WHERE clause of the main query). I would like to be able to enter the date pair as (xxxx-xx-xx) in a single place and use that to populate both areas with the date in the required format. Unfortunately, I am not able to alter the data or tables.
I have been searching for quite a while and can't seem to find an answer that I am able to transfer to my situation. I have tried numerous permutations with this being the only one I can come up with that gives me the desired results. Please let me know if you have any questions or need any additional information. Any help is greatly appreciated. Thank you.

A: This is just off the top of my head, maybe you could start by extracting the saleDate into the outer query:
SELECT y.startWeek, SUM(y.sales), dept.dept, geo.geo
FROM salesCount as y,
(
    SELECT DISTINCT a.salesRepID, a.saleDate
    FROM sales AS a
    WHERE (a.team IN ("teamA", "teamB", "teamC)
        AND a.division IN ("divA", "divB", "divC")
) as x
INNER JOIN dept
    ON x.salesRepID = dept.repID
INNER JOIN geo
    ON dept.region = geo.regionA OR dept.region = geo.regionB
WHERE x.salesRepID = y.repID
    AND y.startWeek BETWEEN "FY13M01W01" AND "FY13M06W04"
    AND x.saleDate BETWEEN "2013-01-01" AND "2013-06-30"
GROUP BY y.startWeek, geo.geo, dept.dept
ORDER BY y.startWeek ASC, geo.geo ASC, dept.dept ASC

Then from there you can look at joining the FISCALWEEK table, something like:
SELECT y.startWeek, SUM(y.sales), dept.dept, geo.geo
FROM salesCount as y,
(
    SELECT DISTINCT a.salesRepID, a.saleDate
    FROM sales AS a
    WHERE (a.team IN ("teamA", "teamB", "teamC)
        AND a.division IN ("divA", "divB", "divC")
) as x
INNER JOIN dept
    ON x.salesRepID = dept.repID
INNER JOIN geo
    ON dept.region = geo.regionA OR dept.region = geo.regionB
INNER JOIN fiscalweek
    ON y.startWeek = fiscalweek.startWeek
WHERE x.salesRepID = y.repID
    AND y.startWeek BETWEEN "FY13M01W01" AND "FY13M06W04"
    AND x.saleDate = fiscalweek.salesDate
GROUP BY y.startWeek, geo.geo, dept.dept
ORDER BY y.startWeek ASC, geo.geo ASC, dept.dept ASC

Not sure if this will work but hopefully gives you some ideas


text:
Q: Normal basis theorem Let $K$ be a finite Galois extension of, say, $\mathbb{Q}$. Then is known(and called normal basis theorem) that if i view $K$ as a representation of $Gal(K/\mathbb{Q})$ over $\mathbb{Q}$ it is isomorphic to the regular representation $\mathbb{Q}[Gal(K/\mathbb{Q})]$.
My question is the following:
Does anybody know a proof where one is able to directly compute  the trace of each non identical element in $Gal(K/\mathbb{Q})$ , proving that is 0(of course this is equivalent to the thesis)?
One brute force attempt could be to do the calculations with primitive basis(powers of a primitive element), but the calculations seems to me quite wild.
Another little tought that i had was to write the induced map $K \otimes_{\mathbb{Q}} K$, $\phi \otimes \phi$ and using that commutes with the multiplication map, and hoping to get some infos about the square of the trace of $\phi$.


text:
Q: Complex usage of "nor" and explanation I'm positive this is an acceptable usage of "nor," but I can't find a rule that explains the usage. Please help!

He was too tired to walk to the next open crossing. Nor to start an argument.

A: The sentences in your example are pieces of a longer logical line of thought in which putting "Nor" at the beginning of the second sentence makes perfectly good sense, but only if you provide enough clues about the line of thought to carry the reader or listener with you. Here's how you might express the full line of thought:

He was too tired to walk to the next open crossing. Or to put the same idea in negative form, he didn't have the energy to walk to the next open crossing. Nor did he have the energy to start an argument.

As the expanded form of the wording makes clear, this line of thought has three distinct steps: (1) describing the person as being too tired to do something; (2) transforming the affirmative first statement into a negative equivalent, by describing the person as not having enough energy to do something; (3) adding, in parallel to the negative second statement, a third statement, also negative, but with the negative sense of the statement emerging from the opening word nor.
As you can see, if you restate the first sentence as the (negative) second sentence before proceeding to the third sentence, the first statement ceases to be necessary to conveying the basic sense of the original two sentences which is, expressed affirmatively,

*

*He was too tired to walk to the next open crossing.

*He was also too tired to start an argument.

or, expressed negatively,

*

*He didn't have the energy to walk to the next open crossing.

*He also didn't have the energy to start an argument. [Or alternatively: Nor did he have the energy to start an argument.]

Presented with these two forms of the new (and trimmer) logical progression of the original ideas, we can shorten the wording further by removing some of the repetitious wording from the second parallel phrase in each case. We can boil the affirmative wording down to

He was too tired to walk to the next open crossing. Or to start an argument.

And we can boil the negative wording down to either

He didn't have the energy to walk to the next open crossing. Or to start an argument.

or

He didn't have the energy to walk to the next open crossing. Nor to start an argument.

Since the phrase "He was too tired" is understood to be the base for the parallel phrases "to walk to the next open crossing" and "to start an argument" in the affirmatively expressed pair, replacing the second occurrence of "He was too tired" with "or" is easy for the reader or listener to recognize and interpret correctly.
Likewise, a straightforward version of the negatively expressed pair would have "He didn't have the energy" as the base and "to walk to the next open crossing" and "to start an argument" as parallel phrases, with "or" again replacing the second iteration of "He didn't have the energy." But starting the second sentence with "Nor" effectively inverts the form of the second idea, from "He didn't have the energy  to start an argument" to "Nor did he have the energy to start an argument." The sentence still has a negative form, but the negation flows from "nor did he" rather than from "he didn't."
That's why both

He didn't have the energy to walk to the next open crossing. Or to start an argument.

and

He didn't have the energy to walk to the next open crossing. Nor to start an argument.

make immediate logical sense. In the first instance, the reader/hearer is asked to apply the "He didn't have the energy" base to the second parallel phrase. And in the second instance, the reader/hearer is asked to apply the inverted form of the base phrase—namely, "Nor did he have the energy"—to the second parallel phrase. Either way, the reader/listener is in little danger of being left behind as the writer/speaker moves on to the next point in the narrative.


text:
Q: Saving Blocks of cropped image Resulted from blockproc in Matlab I've been trying to crop and save the blocks (subimages) from the original image using blockproc and imcrop functions, but I couldn't. I'm only able to see the figures of the blocks. Is there any way to save these blocks to the specified folder? Thanks.
clear all
close all
clc
a = imread('3.jpg');
folderPath='C:\Program Files\Folder';
blockSize = [70,70];
d = blockproc(a,blockSize,@(bs) imcrop(bs.data));
%blockproc(a, blockSize, @(bs)imcrop(bs.data),'BorderSize', [1 1 ]);

%i=1;
fileName = [folderPath num2str(i) '.jpg'];
imwrite(d, fileName, 'jpg');

A: My assumption from the information you have in the question, "you want to bring up every 70x70 block of your image and then crop out a smaller part in this 70x70 block using IMCROP and save that smaller region to a file". (If that is not your intention, please do update the question).
You could do this by using this function (air code, hope you get the idea)
In cropAndSaveBlock.m:
function cropAndSaveBlock(bs)
   subBlockRegion = imcrop(bs.data);
   % Use location of the block to come up with a unique name
   fileName = [strrep(num2str(bs.location),' ','_') '.jpg'];
   imwrite(sbBlockRegion, fileName);
end

And then call it using:
blockproc(a,blockSize,@cropAndSaveBlock);


text:
Q: Combining expand with other operators in rxjs Let's say I have a set of rewriting rules that I want my Observable to implement:
A => B B
B => C

That is, whenever there's an A on the observable, output two Bs. Whenever there's a B (even when it comes from an A), output a C. This
 seems like natural use case for expand, and it's pretty easy to implement. As expected, each A turns into ABCBC.
But what if I want to combine the expansion with another operator? Let's say my rules are:
A => B repeated N times, where N is the number of "A"s so far.
B => C, but only if the number of "B"s so far is divisible by 10.

Grouping values by whether they're As or Bs sounds like a job for groupBy, and counting the number of outputs for each sounds like scan, but how do I combine those operators with expand?

A: Two years late and not strictly an answer to your question, but another approach that yields the same result and might be easier to build upon.
Building streams recursively:
This approach builds out your stream recursively. Kind of the same idea you may use to build a nieve parser.
function recursiveOperator(){
  return s => s.pipe(
    mergeMap(val => concat(
      of(val),
      streamFor(val)
    ))
  )
}

function streamFor(x){
  let stream;
  if (x == 'A') {
    stream = from(['B','B']);
  }else if (x == 'B') {
    stream = of('C');
  }else{
    stream = EMPTY;
  }
  return stream.pipe(
    recursiveOperator()
  )
}

zip(
  timer(0, 4000),
  from(['A','B','A'])
).pipe(
  map(([x,y]) => y),
  recursiveOperator()
).subscribe(console.log);

output:
abcbc // Then wait 4 seconds
bc  // Then wait 4 seconds
abcbc

Using a Subject:
I'm pretty sure that as-is, this introduces a race condition. They're resolved consistently since JS is single-threaded and the event loop is predictable, but you're having two streams each pushing values to the same subject and I haven't yet built in anything that ensures no unwanted interleaving.
With some tweaking, however, this can be much more performant for large inputs.
const valueSubject = new Subject<string>();
valueSubject.subscribe(console.log);

zip(
  timer(0, 4000),
  from(['A', 'B', 'A'])
).pipe(
  map(([x,y]) => y)
).subscribe(val => valueSubject.next(val));

valueSubject.pipe(
  tap(val => {
    if (val == 'A') {
      valueSubject.next('B');
      valueSubject.next('B');
    }else if (val == 'B') {
      valueSubject.next('C');
    }
  })
).subscribe();

output:
abcbc // Then wait 4 seconds
bc  // Then wait 4 seconds
abcbc


text:
Q: Why does Piwik insert the script tag before all others? I noticed that the Piwik tracking code inserts the script tag before the first script tag in the <head>:
var d=document,
    g=d.createElement('script'),
    s=d.getElementsByTagName('script')[0];
...
s.parentNode.insertBefore(g,s);

Is there a reason for this? Can I just insert it at the end of <head> or even in the body?

A: Yes, you could insert it wherever you want. When a script does something like this, it's considered a nice thing. It's going to put it in the same location as the first script on your page, which is presumably where the page author wanted his scripts to be placed. If the first script is in the <head> or <body> that's where it'll put it.
There's no real reason, and also, no real benefit to the script itself either. The very fact that it's loading an external resource means that it's execution will be after the page has finished loading and executing the scripts that were hardcoded in the page (due to JS's single-threaded nature and the fact that loading a script like this will cause it to behave in an async fashion).
Basically you can have it load wherever you want, but presumably it's not going to benefit you, page loading speed, or the script itself.


text:
Q: Take the derivative of the parameter in an integral. Consider two smooth functions $f(x)$, $g(x)$ defined on $\mathbb{R}^n$, and $g$ has compact support. Easily, we have
$$
\int_{\mathbb{R}^n}f(ax)g(x)dx=\int_{\mathbb{R}^n}a^{-d}f(x)g(a^{-1}x)dx,
$$
where $a>0$. Now take the derivative with respect to $a$, we get
$$
\begin{aligned}
&\ \frac{d}{da}(\text{LHS})\\&=\int_{\mathbb{R}^n}\sum_i x^i\frac{\partial{f}}{\partial{x^i}}(ax)g(x)dx\\&=\sum_i \int_{\mathbb{R}^n} a^{-1} x^i g(x) dx^1dx^2\cdots d_{x^i}(f(ax))\cdots dx^n\\
&=-\sum_i \int_{\mathbb{R}^n} a^{-1} f(ax)dx^1\cdots d_{x^i}(x^ig(x))\cdots dx^n\\&=-\sum_i \int_{\mathbb{R}^n} a^{-1}f(ax)[g(x)+x^i\frac{\partial{g}}{\partial{x^i}}(x)]dx\\&=-\sum_i\int_{\mathbb{R}^n}a^{-d-1}f(x)g(a^{-1}x)+a^{-d-2}f(x)x^i\frac{\partial{g}}{\partial{x^i}}(a^{-1}x)dx,
\end{aligned}
$$
however,
$$
\begin{aligned}
&\ \frac{d}{da}(\text{RHS})\\
&=\sum_i \int_{\mathbb{R}^n}-d a^{-d-1}f(x)g(a^{-1}x)-a^{-d-2}f(x) x^i\frac{\partial{g}}{\partial{x^i}}(a^{-1}x)dx.
\end{aligned}
$$
Since the equality hold for arbitrary $a>0$, it should keep right after taking derivative with respect to $a$. Would you tell me where is the problem here?


text:
Q: Need assistance understanding __block Storage Type __block NSString *x = @"123"; //  x lives in block storage
void (^printXAndY)(NSString*) = ^(NSString *y) {
    x = [x stringByAppendingString:y];
    printf("%@ %@\n", x, y);
};
printXAndY(@"456");

Apple docs says:

The __block Storage Type You can specify that an imported variable be
  mutable—that is, read-write— by applying the __block storage type
  modifier.

If the x is mutable, isn't this x = [x stringByAppendingString:y]; wrong? and can cause memory leaks?

A: First, you are confusing two completely unrelated things: 1) the variable being assignable (i.e. non-const), and 2) if the variable is of object pointer type, the object it points to being "mutable".
Non-__block local variables are const inside a block, which means you can't do x = something. Making the variable __block allows you to do x = something inside the block (regardless of the type of x). When x is a pointer variable, assignment to it makes it point to something else.
So-called "mutating" a "mutable" object just means you can call a method on it that somehow changes the "contents" of the object. It does not involve assigning to any pointers that may point to this object.

As to your second question, memory leaks, no, there shouldn't be any memory leaks. First of all, if you're using ARC, it's obvious that there are no leaks. Even if you are using MRC, there are no leaks. In fact, if this is MRC, none of the object pointers in this code has been retained by your function (they are not the result of retain, alloc, new, copy, etc.), so there cannot possibly be a leak.


text:
Q: Selecting data from two tables with sql query I have 2 tables
Course ( ID Date Description Duration Meatier_ID Promotion_ID).
second table
Ensign( E_Id Meatier_Id Promotion_Id)
infarct i have an id based on that id i have to Select data from Ensign where id=Eng_Id then i need to select data from Course where Meatier_Id and Promotion_Id in table Course are equal to Meatier_Id and Promotion_Id to data selected in earlier query
can i do it using one S q l query thanks
Br
Sara

A: Your question is bit vague, But I gave it a try
--These two variables take the place for your 'Earlier Query' values
DECLARE @Meatier_ID INT = 100,
        @Promotion_Id INT = 15

--The query
SELECT *
FROM Course AS C
INNER JOIN Ensign AS E ON C.ID = E.E_Id
WHERE C.Meatier_ID = @Meatier_ID
AND C.Promotion_Id = @Promotion_Id

A: Join the two tables together on Meater_ID and Promotion_ID. Then select those rows where Eng_Id is the id you are working with.
SELECT *
FROM Course c
INNER JOIN Ensign e
   ON e.Meatier_ID = c.Meatier_ID
  AND e.Promotion_ID = c.Promotion_ID
WHERE e.Eng_Id = <id value here>

EDIT:
The above should work for SQL Server. For derby, try:
SELECT *
FROM Course
INNER JOIN Ensign
  ON Ensign.Meatier_ID = Course.Meatier_ID
 AND Ensign.Promotion_ID = Course.Promotion_ID
WHERE Ensign.Eng_Id = <id value here>

A: select e.E_Id, e.Meatier_Id, e.Promotion_Id, c.ID, c.Date, c.Description, c.Duration from Ensign as e inner join course as c where  e.Meatier_Id=c.Meatier_Id and e.Promotion_Id=c.Promotion_Id and e.E_Id=@Eng_Id


text:
Q: Equivalent to Run Method(VBA) in OpenOffice Calc I have been trying to convert a VBA for Excel code to OpenOffice Calc (basic) and now Im having trouble accessing an external program (and it´s database) to generate an output which I will use later in my code. In other words, I give an input, call the program and later I want an output file.
In VBA:
Prog = Worksheets("Settings").Cells(2, 2) & IPRODB & " -i " & DateiAll_in
Wait = True
Set sh = CreateObject("WScript.Shell")
RetVal = sh.Run(Prog, 0, Wait)

Worksheets("Settings").Cells(2, 2) is the program's path and IPRODB is the database's path, "-i" seems to be a command to the program and DateiAll_in is the Input file (.csv) I created before in the code.
The OpenOffice basic offers the function Shell(Pathname, Windowstyle, Param, bSync) to open external programs but It would not be the same since in the "run method" in VBA I am running a macro containing the program, its´s Database and Input File. (expression.Run(MacroName, varg1,varg2, (...))
Is there any alternative to the Shell function or can I use it in the same way as I used the "run method" in VBA?

A: From the OpenOffice.org forums (didn't test it myself):
Dim oSvc as object
oSvc = createUnoService("com.sun.star.system.SystemShellExecute")

Rem Launch notepad
oSvc.execute(ConvertToUrl("C:\windows\notepad.exe"), "", 0)

A: I used the Shell function. In the first argument of the function I added all the equivalents of "Worksheets("Settings").Cells(2, 2) & IPRODB & " -i " & DateiAll_in". I substituted Worksheets("Settings").Cells(2, 2)  for the direct path of the program only because it was easier. So it worked with this code below:
Shell("C:\Program Files\*******\*****\*****.exe & IPRODB & "-i" & DateiAll_in",1,,True)


text:
Q: SUMIF with a difference I am trying to accomplish something which in my mind seems easy but I can't write it down as a formula.
Essentially, I want to do a SUMIF however I'm rather stuck.
I have a table which I would like to lookup a value along 1 row, and where it is present I want to sum a range, this range is adjacent to the cell in the row,
For example, if the value is present in A1, SUM A5:A15, if the same value is also present in B1, SUM B5:B15 and add the two together, and so on - How do I accomplish this in one pass? I want to look along a row with over 70 values, of which there are 12 possible variables,
it may not possible, but I have a hunch it's relatively straight forward ^_^

A: you can use this array formula - entered with Ctrl+Shift+Enter:
=SUM(IF(A1:D1="my value"; A2:D15))

(use , it instead of ; if that is your list separator in the region and language advanced settings)


text:
Q: Convergence of Bernoulli distribution using Central Limit Theorem while I was studying the Central Limit theorem, this problem showed up:
If $0<p = 1-q < 1$ and $x > 0$, then
$$
\sum_{k \in K} \binom{n}{k}p^kq^{n-k} \to 2 \int_{0}^{x} \frac{1}{\sqrt{2\pi}}e^{\frac{-1}{2}u^2} du,
$$
where $K := \left\{k: np - x\sqrt{npq} \leq k \leq np+x\sqrt{npq}\right\}$.
The book sugests to apply the theorem to a sequence of random variables with the Bernoulli distribuition. Can somebody help me with this? Doesn't look hard, but I cant understand even the first steps.
Thanks in advance!!

A: Let $(X_i)$ be an i.i.d sequence where $X_n$ takes the value $1$ with probability $p$ and  the value $0$ with probability $q$. Let $S_n=X_1+X_2+\cdots+X_n$. Note that $EX_n=p$ and $EX_n^{2}=p$ so the variance of $X_n $ is $p-p^{2}=pq$. By CLT $P(-x \leq \frac {S_n-np} {\sqrt {npq}} \leq x) \to \int_{-x}^{x} \frac  1{\sqrt {2\pi}} e^{-x^{2}/2} dx=2\int_{0}^{x} \frac  1{\sqrt {2\pi}} e^{-x^{2}/2} dx$. Now just re-write the event on the left.


text:
Q: Regular Expression WildCard matching split with java split method I know there's similar questions like this asked before, but i want to do a custom operation and i don't know how to go about it.
I want to split a string of data with a regular expression like, but this time like i know the starting character and the ending character like:
String myString="Google is a great search engine<as:...s>";

The <as: and s> is the beginning and closing characters
the ... is dynamic which i cant predict its value
I want to be able to split the string from the beginning <as: to the end s>
with the dynamic string in it.
Like:
myString.split("<as:/*s>");

Something like that. I also want to get all the occurrence of the <as:..s> in the string.
i know this can be done with regex, but I've never done it before. I need a simple and neat way to do this.
Thanks in advance

A: Rather than using a .split(), I would just extract using Pattern and Matcher. This approach finds everything between <as: and s> and extracts it to a capture group. Group 1 then has the text you would like.
public static void main(String[] args)
{
    final String myString="Google is a great search engine<as:Some stuff heres>";

    Pattern pat = Pattern.compile("^[^<]+<as:(.*)s>$");

    Matcher m = pat.matcher(myString);
    if (m.matches()) {
        System.out.println(m.group(1));
    }
}

Output:

Some stuff here

If you need the text at the beginning, you can put it in a capture group as well.
Edit: If there are more than one <as...s> in the input, then the following will gather all of them.
Edit 2: increased the logic. Added checks for emptiness.
public static List<String> multiEntry(final String myString)
{
    String[] parts = myString.split("<as:");

    List<String> col = new ArrayList<>();
    if (! parts[0].trim().isEmpty()) {
        col.add(parts[0]);
    }

    Pattern pat = Pattern.compile("^(.*?)s>(.*)?");
    for (int i = 1; i < parts.length; ++i) {
        Matcher m = pat.matcher(parts[i]);
        if (m.matches()) {
            for (int j = 1; j <= m.groupCount(); ++j) {
                String s = m.group(j).trim();
                if (! s.isEmpty()) {
                    col.add(s);
                }
            }
        }
    }

    return col;
}

Output:

[Google is a great search engine, Some stuff heress, Here is Facebook, More Stuff, Something else at the end]

Edit 3: This approach uses find and looping to do the parsing. It uses optional capture groups as well.
public static void looping()
{
    final String myString="Google is a great search engine"
            + "<as:Some stuff heresss>Here is Facebook<as:More Stuffs>"
            + "Something else at the end" +
            "<as:Stuffs>" +
            "<as:Yet More Stuffs>";

    Pattern pat = Pattern.compile("([^<]+)?(<as:(.*?)s>)?");

    Matcher m = pat.matcher(myString);
    List<String> col = new ArrayList<>();

    while (m.find()) {
        String prefix = m.group(1);
        String contents = m.group(3);

        if (prefix != null) { col.add(prefix); }
        if (contents != null) { col.add(contents); }
    }

    System.out.println(col);
}

Output:

[Google is a great search engine, Some stuff heress, Here is Facebook, More Stuff, Something else at the end, Stuff, Yet More Stuff]

Additional Edit: wrote some quick test cases (with super hacked helper class) to help validate. These all pass (updated) multiEntry:
public static void main(String[] args)
{
    Input[] inputs = {
            new Input("Google is a great search engine<as:Some stuff heres>", 2),
            new Input("Google is a great search engine"
                    + "<as:Some stuff heresss>Here is Facebook<as:More Stuffs>"
                    + "Something else at the end" +
                    "<as:Stuffs>" +
                    "<as:Yet More Stuffs>" +
                    "ending", 8),
            new Input("Google is a great search engine"
                            + "<as:Some stuff heresss>Here is Facebook<as:More Stuffs>"
                            + "Something else at the end" +
                            "<as:Stuffs>" +
                            "<as:Yet More Stuffs>", 7),
            new Input("No as here", 1),
            new Input("Here is angle < input", 1),
            new Input("Angle < plus <as:Stuff in as:s><as:Other stuff in as:s>", 3),
            new Input("Angle < plus <as:Stuff in as:s><as:Other stuff in as:s>blah", 4),
            new Input("<as:To start with anglass>Some ending", 2),
    };

    List<String> res;
    for (Input inp : inputs) {
        res = multiEntry(inp.inp);
        if (res.size() != inp.cnt) {
            System.err.println("FAIL: " + res.size()
            + " did not match exp of " + inp.cnt
            + " on " + inp.inp);
            System.err.println(res);
            continue;
        }
        System.out.println(res);
    }
}


text:
Q: Is it possible to view who edited a lightning page layout Say i go to a ticket, click the gear, hit edit page and....completely nuke it. Is it possible to see who has edited it? I can't seem to find any admin area to view that information, and obviously it doesn't exist under "lightning pages".
Can i pull it from the metadata somehow?

A: Click on setup -- > search lightning app builder.You can see who last modified by against the lightning page. I hope this is what you were looking for.


text:
Q: Qt - How to connect the comboBox to the database I'm attempting to query the database and put the result in a combobox.

*

*db was initally declared public, but lastError() returned "driver not loaded" in the openConnection() function which checked if(!db.open()). The function returned true for win7, but false for win8 and XP.

*Not sure why this happened. Some forum comments suggest "declaring variable in header as a global leaves it up to the compiler when the object is created....db object is instantiated at the wrong time".

*the connection call from mainwindow was QsqlDatabase db = dbConnector::getInstance()->db;

*then db is used in the line for the combobox: QSqlQuery* qry=new QSqlQuery(db);
Instead of declaring db public:

*

*I created comboBoxInit(), because I don't think db can be accessed by mainwindow. (db is declared private)

*The current code returns "ui is not declared in this scope"

How do you connect the comboBox to the db in this example?

mainwindow.cpp
#include "dbConnector.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    dbConnector *dbc = dbConnector::getInstance();

    if(!dbc->openConnection()) {
        ui->statusBar->showMessage("Failed to open the database");
    } else {
        ui->statusBar->showMessage("Connected");
    }

    dbConnector::getInstance()->comboBoxInit();

    //QSqlQueryModel * modal=new QSqlQueryModel();
    //QSqlQuery* qry=new QSqlQuery(db);
    //qry->prepare("select name from table");
    //qry->exec();

    modal->setQuery(*qry);
    ui->comboBox->setModel(modal);
    ui->comboBox_2->setModel(modal);

}

dbConnector.h
class dbConnector
{
    private:
      static dbConnector * _instance;
      dbConnector();
      QSqlDatabase db;

    public:
      static dbConnector * getInstance();

      bool openConnection();
      bool closeConnection();
      bool comboBoxInit();
      ~dbConnector();
};

dbConnector.cpp
dbConnector::dbConnector()
{
   if (!QSqlDatabase::isDriverAvailable(driver))
   {
       //QMessageBox::critical(this,tr("error::"),qry.lastError().text());
       QMessageBox::critical(0,connectError,driverExist);
       exit(1);
   }
   db = QSqlDatabase::addDatabase(driver);
   db.setDatabaseName(fileName);
   openConnection();
}

bool dbManager::comboBoxInit()
{
    QSqlQueryModel * modal=new QSqlQueryModel();
    QSqlQuery* qry=new QSqlQuery(db);
    qry->prepare("select name from table");
    qry->exec();

    modal->setQuery(*qry);
    //qDebug() << modal;

    return true;
    ui->comboBox->setModel(modal);
    ui->comboBox_2->setModel(modal);
}


text:
Q: Realm subquery sorted by Date I have the following model:
class User: Object {
   dynamic var name = ""
   let events = List<Event>()
}

class Event : Object {
   dynamic var description = ""
   let dates = List<Date>()
}

class Date : Object {
    dynamic var date = "" //string
}

Is there any good way to query/filter for the (one) event with closes date to current date? If not possible, how should the modell be modified, i saw that subqueries are only available with @count i.e. realm.objects(Company.self).filter("employees.@count > 5")

A: It's a shame that date isn't an NSDate property since you could easily just sort by descending order, and then use LinkingObjects to look up the Event in which that Date object belongs:
class Event : Object {
   dynamic var description = ""
   let dates = List<Date>()
}

class Date : Object {
    dynamic var date = NSDate()
    let events = LinkingObjects(fromType: Event.self, property: "dates")
}

let realm = try! Realm()
let latestDate = realm.objects(Date.self).sorted("date", ascending: false).first
let latestEvent = latestDate.events.first

Unfortunately, as date is a string, that might not work. You could try and used sorted() on date, but it will be sorting alphabetically, and not chronologically, so you may not get the latest date.
If that's the case, you'll need to manually implement a loop through each Date object, parse it and perform the sorting yourself.


text:
Q: What are the possibitlities to effectively parse YAML file in Scala? How to use it in scala? I want to make a configuration file for my certain variables, so that I don't have to change in code each time.
I want to do it by making a YAML file. I am working with scala.
What are the effective ways to use these variables by reading from yaml into my application.
So far, I have looked in snakeyaml library but it contains java functions and parses yaml in a string by which I can't go into nested key value pair of yaml file without splitting the string.
How can I use these by staying in scala and what are the better ways to parse as i would need to get the nested values often. How can I use it in my application?
eg
if this is my yaml file
---
accountName: Ymail Account
username: johndoe
password: secret
mailbox: INBOX
imapServerUrl: imap.mail.yahoo.com
protocol: imaps
minutesBetweenChecks: 1
usersOfInterest: [barney, betty, wilma]
...

I want to get each index of userOfInterst individually as needed.
so far I have done like this
  @BeanProperty var accountName = ""
  @BeanProperty var username = ""
  @BeanProperty var password = ""
  @BeanProperty var mailbox = ""
  @BeanProperty var imapServerUrl = ""
  @BeanProperty var protocol = ""
  @BeanProperty var minutesBetweenChecks = 0
  @BeanProperty var usersOfInterest = new java.util.ArrayList[String]
  override def toString: String = s"acct: $accountName, user: $username, url: $imapServerUrl, uot: $usersOfInterest," +
    s"mbc: $minutesBetweenChecks"

but it just prints all as string which isnt helpful. What are the other options and how to get it dynamically?


text:
Q: Startup logic on splash screen loops forever I am using a splash screen to determine which route to send the user depending on their logged-in state.
My service checks the user state on firebase like so:
 Stream<User?> isUserLoggedIn() {
    var user = _firebaseAuth.authStateChanges();

    return user;
  }

My model calls the service and determines the user route based on the response:
  User? handleStartUpLogic() {
    print('Run only once and stop magically printing text!');
    _authenticationServices.isUserLoggedIn().listen((User? user) {
      if (user == null) {
        print('User is signed out!');
        goToSignIn();
      } else {
        print('User is signed in!');
        goToMarket();
      }
    });
  }

...and in my View I set on model ready:
 return ViewModelBuilder<SplashModel>.reactive(
        onModelReady: (model) => model.handleStartUpLogic(),
        createNewModelOnInsert: false,
        builder: (context, model, child) => Scaffold(
              backgroundColor: fontColor,
              body: Center(child: Image.asset('assets/fable_Icon.png')),
            ),

When I run this code I get this unending looP:
I/flutter (12991): Run only once and stop magically printing text!
I/flutter (12991): Run only once and stop magically printing text!
I/chatty  (12991): uid=10080(u0_a80) 1.ui identical 10 lines
I/flutter (12991): Run only once and stop magically printing text!
I/flutter (12991): Run only once and stop magically printing text!
I/flutter (12991): Run only once and stop magically printing text!
I/flutter (12991): Run only once and stop magically printing text!
I/chatty  (12991): uid=10080(u0_a80) 1.ui identical 32 lines
I/flutter (12991): Run only once and stop magically printing text!
I/zygote  (12991): Do partial code cache collection, code=60KB, data=43KB
I/zygote  (12991): After code cache collection, code=57KB, data=42KB
I/zygote  (12991): Increasing code cache capacity to 256KB
I/flutter (12991): Run only once and stop magically printing text!
I/flutter (12991): Run only once and stop magically printing text!
I/chatty  (12991): uid=10080(u0_a80) 1.ui identical 156 lines
I/flutter (12991): Run only once and stop magically printing text!
I/flutter (12991): Run only once and stop magically printing text!
I/chatty  (12991): uid=10080(u0_a80) 1.ui identical 15 lines
I/flutter (12991): Run only once and stop magically printing text!
I/flutter (12991): Run only once and stop magically printing text!
I/flutter (12991): Run only once and stop magically printing text!
I/chatty  (12991): uid=10080(u0_a80) 1.ui identical 54 lines
I/flutter (12991): Run only once and stop magically printing text!
I/flutter (12991): Run only once and stop magically printing text!
I/chatty  (12991): uid=10080(u0_a80) 1.ui identical 21 lines
I/flutter (12991): Run only once and stop magically printing text!
I/flutter (12991): Run only once and stop magically printing text!

Will greatly appreciate the help

A: Anything in the build method can be built multiple times, like when you update state. Potentially by getting the model, you are updating the state, which fires the function, which updates the state. You should put it inside an initState().


text:
Q: How Do I Send a Broadcast Request to a Node.JS server On My LAN? I have a Raspberry Pi hooked up to a RGB LED strip. On the Pi, is a Node.JS server that hosts a webpage, and that webpage lets me pick a color for the LED strip. All that works.
The problem is, I want to be able to dynamically find the IP address (I don't want to do static IPs. I want to give these out to some family, and I want them to "just work" once I join them to the wifi).
What I would like to do is to have a phone app that can find the Raspberry Pi on the network. I was thinking about this, and I remembered reading about broadcast IP addresses for the LAN. I've never used them before, but seems to be what I need. The app would start up, send a specially crafted message on broadcast that says "Where's the Raspberry Pi?" and the Pi would answer "Here I am! I'm at X address!"
I've never tried to use a broadcast IP address before, so I decided to try a proof of concept. I started up a Node.JS server on my Pi that looks like this:
var http = require('http');

var port = 8081;

var server = http.createServer(function(request, response) {
    response.writeHead(200);
    response.end("Pong");
});
server.listen(port, function() {
    console.log((new Date()) + ' Server is listening on port ' + port);
});

Then from my PC, curl 192.168.1.XXX:8081 (the known IP address) and boom. Expected response.
But curl 192.168.1.255:8081 gets me a 502 error.
From what I'm reading online, that should be the broadcast address. Is my router likely to be blocking this? Am I just doing something fundamentally wrong?
Thanks in advance. :)

A: You're doing something fundamentally wrong :)
You can not send a broadcast message using TCP/HTTP (see Can I use broadcast or multicast for TCP?) but you could send an UDP datagram (see Send Broadcast datagram) instead. It should work if your router doesn't filter that kind of traffic.
Many operating systems come with a tool called arp-scan. You could rely on ARP (Address Resolution Protocol) and use this tool to list the IP-MAC associations on your network. You could simply use the IP that belongs to a Raspberry Pi.


text:
Q: Pandas sliding window over a dataframe column I am new to pandas. I am using pandas to read a CSV file of timestamped records, into a dataframe. The data has the following columns:

timestamp  COLUMN_A COLUMN_B COLUMN_C

After reading the data into the dataframe, I want to be able to run a windowing function on COLUMN_C; The function should return the timestamped values of the column.
I have written something that works for iterables:
import collections
import itertools

def sliding_window_iter(iterable, size):
    """Iterate through iterable using a sliding window of several elements.

    Creates an iterable where each element is a tuple of `size`
    consecutive elements from `iterable`, advancing by 1 element each
    time. For example:

    >>> list(sliding_window_iter([1, 2, 3, 4], 2))
    [(1, 2), (2, 3), (3, 4)]
    """
    iterable = iter(iterable)
    window = collections.deque(
        itertools.islice(iterable, size-1),
        maxlen=size
    )
    for item in iterable:
        window.append(item)
        yield tuple(window)

How do I modify this to work on the column of a dataframe?

A: It's simpler to successively slice through the dataframe. Since you want overlapping windows [(1, 2), (2, 3), (3, 4), ...], you could write it like this:
def sliding_window_iter(series, size):
    """series is a column of a dataframe"""
    for start_row in range(len(series) - size + 1):
        yield series[start_row:start_row + size]

Usage:
df = pd.DataFrame({'A': list(range(100, 501, 100)),
                   'B': list(range(-20, -15)),
                   'C': [0, 1, 2, None, 4]},
                  index=pd.date_range('2021-01-01', periods=5))

list(sliding_window_iter(df['C'], 2))

Output:
[2021-01-01    0.0
 2021-01-02    1.0
 Freq: D, Name: C, dtype: float64,
 2021-01-02    1.0
 2021-01-03    2.0
 Freq: D, Name: C, dtype: float64,
 2021-01-03    2.0
 2021-01-04    NaN
 Freq: D, Name: C, dtype: float64,
 2021-01-04    NaN
 2021-01-05    4.0
 Freq: D, Name: C, dtype: float64]

Also works if you pass in multiple columns:
list(sliding_window_iter(df.loc[:, ['A', 'C']], 2))

#output:
[              A    C
 2021-01-01  100  0.0
 2021-01-02  200  1.0,
               A    C
 2021-01-02  200  1.0
 2021-01-03  300  2.0,
               A    C
 2021-01-03  300  2.0
 2021-01-04  400  NaN,
               A    C
 2021-01-04  400  NaN
 2021-01-05  500  4.0]


text:
Q: How to segment characters from image of handwritten words I am trying trying to find the bounding box for individual characters in the image of a word .  input
a = img[:,:,0]
b = img[:,:,1]
c = img[:,:,2]

s = a + b + c

h = s.sum(axis = 0)

min_peakind = signal.find_peaks_cwt(inv_data, np.arange(1,10))

I tried to find the boundaries along horizontal axis by finding the the local maximum of summation along vertical axis(0 black pixel and 255 white pixel)  output i able to get is .  ouput
is there a better way to segment?


text:
Q: Elegant way to count number of elements in each column of a matrix that are greater than those in every other column? I currently have a solution that works. I'm wondering if there is a more elegant approach?
First the setup:
set.seed(315)
mat <- matrix(sample(1:5, 20, replace = TRUE), nrow = 4, ncol = 5)
> mat
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    4    1    3    3
[2,]    5    3    5    1    4
[3,]    4    1    1    4    3
[4,]    3    3    1    1    1

From this matrix, I want to create an 5x5 output matrix, where the entry in i,j is the number of elements in column j that were greater than column i of the input matrix.
edit: Originally I described a solution where the entry i,j of the output solution is the number of elements in column i are greater than column j, but provided the opposite relationship in the output. I changed the description to match the output, and any differences in the answers provided are probably a result of that.
This solution gives the desired output:
mat.pm <- apply(mat, MARGIN = 2,
                function(x) {
                  return(apply(mat, MARGIN = 2, function(y) {
                    return(sum(x > y))
                  }))
                })

> mat.pm
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    0    0    0
[2,]    2    0    1    1    2
[3,]    3    2    0    2    2
[4,]    2    3    1    0    1
[5,]    3    2    1    1    0

Is there possibly a better way that doesn't involve double-nested apply functions?
edit: here is some benchmarking for the various approaches:
library(microbenchmark)

set.seed(315)
bm_data <- matrix(sample(1:5, 6000, replace = TRUE), nrow = 200, ncol = 30)

op <- microbenchmark(
  APPLY1 = apply(bm_data, MARGIN = 2,
                function(x) {
                  return(apply(bm_data, MARGIN = 2, function(y) {
                    return(sum(x > y))
                  }))
                }),
  APPLY2 = apply(bm_data, 2 , function(x) colSums( x > bm_data)),
  SWEEP = apply(bm_data,2,function(x) colSums(sweep(bm_data,1,x,"-")<0)),
  VECTORIZE = {
    n <- 1:ncol(bm_data);
    ind <- expand.grid(n, n)
    out <- colSums(bm_data[,c(ind[,2])] > bm_data[,c(ind[,1])])
  },
  SAPPLY = sapply(seq(ncol(bm_data)), function(i) colSums(bm_data[, i] > bm_data)),
  times = 100L
)

> summary(op)
       expr      min        lq    median        uq       max neval
1    APPLY1 9742.091 10519.757 10923.896 11876.614 13006.850   100
2    APPLY2 1012.097  1080.926  1148.111  1247.965  3338.314   100
3     SWEEP 7020.979  7667.972  8580.420  8943.674 33601.336   100
4 VECTORIZE 3036.700  3266.815  3516.449  4476.769 28638.246   100
5    SAPPLY  978.812  1021.754  1078.461  1150.782  3303.798   100

@Ricardo's SAPPLY and @Simon's APPLY2 strategies are both nice, one line solutions that perform much faster that my APPLY1 approach. In terms of elegance, @Simon's update with APPLY2 hits the mark - simple, readable and fast.
One takeaway I learned through discussion here is how much faster apply functions rip through a matrix compared to a data.frame. Convert, then compute if possible.
@Simon's expand.grid is the most creative - I had not even thought to approach the problem in that way. Nice.

A: Edit:
See below for details but you can do this in a single apply loop:
apply( mat , 2 , function(x) colSums( x > mat )

apply is fast here, because is optimised to work on matrices. A lot of the time spent using apply is usually in the conversion of a data.frame to a matrix which is not needed here.

Original:
It's possible to do this entirely vectorised because > has an method for matrices and data.frames. Therefore you can get the indices of columns to compare using expand.grid(), use this to subset the matrix, do the logical comparison and then use colSums to get the result and matrix to wrap it back up to the correct size. All this in 4 lines (really it could be 2):
n <- 1:ncol(mat)
ind <- expand.grid(n,n)
out <- colSums( mat[,c(ind[,1])] > mat[,c(ind[,2])] )

matrix( out , ncol(mat) , byrow = TRUE )
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    0    1    0    0    0
#[2,]    2    0    1    1    2
#[3,]    3    2    0    2    2
#[4,]    2    3    1    0    1
#[5,]    3    2    1    1    0

Update:
apply seems even faster, and combining apply with @Ricardo's comparison of the whole matrix leads us to a single, fastest (?) apply solution which is approximately 4 times quicker than the OP:
#  Single apply loop
f1 <- function(mat) apply( mat , 2 , function(x) colSums( x > mat ) )

#  OP double apply loop
f2 <- function(mat) {apply(mat, MARGIN = 2,
                function(x) {
                  return(apply(mat, MARGIN = 2, function(y) {
                    return(sum(x > y))
                  }))})}

require(microbenchmark)
microbenchmark( f1(mat) , f2(mat) )

#Unit: microseconds
#    expr     min       lq   median       uq      max neval
# f1(mat)  95.190  97.6405 102.7145 111.4635  159.584   100
# f2(mat) 361.862 370.7860 398.7830 418.3810 1336.506   100

A: I think the results you have are transposed:
## This gives you what you show as output
sapply(seq(ncol(mat)), function(i) colSums(mat[, i] > mat))

## This gives you what you _describe_ in the question
t(sapply(seq(ncol(mat)), function(i) colSums(mat[, i] > mat)))

     [,1] [,2] [,3] [,4] [,5]
[1,]    0    2    3    2    3
[2,]    1    0    2    3    2
[3,]    0    1    0    1    1
[4,]    0    1    2    0    1
[5,]    0    2    2    1    0

A: Here's a way using only 1 apply, but replacing the other with sweep, so not sure it counts:
apply(mat,2,function(x) colSums(sweep(mat,1,x,"-")<0))
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    0    0    0
[2,]    2    0    1    1    2
[3,]    3    2    0    2    2
[4,]    2    3    1    0    1
[5,]    3    2    1    1    0

A: Benchmarking:
 bigmat<-matrix(sample(0:5,200,rep=T),nr=10)
    gridfoo <- function(mat) {
    n <- 1:ncol(mat)
    ind <- expand.grid(n,n)
    out <- colSums( mat[,c(ind[,1])] > mat[,c(ind[,2])] )
    }

    appfoo<- function(mat) apply(mat,2,function(x) colSums(sweep(mat,1,x,"-")<0))

    app2foo<- function(mat) t(sapply(seq(ncol(mat)), function(i) colSums(mat[, i] > mat)))

 microbenchmark(gridfoo(bigmat),appfoo(bigmat),app2foo(bigmat),times=10)
Unit: microseconds
            expr      min       lq    median       uq      max neval
 gridfoo(bigmat)  363.909  369.895  381.4410  413.086  522.557    10
  appfoo(bigmat) 1208.892 1231.129 1238.1850 1252.083 1521.913    10
 app2foo(bigmat)  298.482  310.883  317.0835  323.284  762.454    10

But...(notice difference in time unit)
Rgames> bigmat<-matrix(sample(0:5,20000,rep=T),nr=100)
Rgames> microbenchmark(gridfoo(bigmat),appfoo(bigmat),app2foo(bigmat),times=10)
Unit: milliseconds
            expr       min        lq   median        uq       max neval
 gridfoo(bigmat) 106.15115 112.98458 149.5746 183.87987 249.35418    10
  appfoo(bigmat) 127.44553 127.92874 132.5372 136.42562 199.12123    10
 app2foo(bigmat)  14.64483  14.99676  18.6089  20.51824  20.91122    10

A: This works, but it might not scale well because of the heavy merge step.
library(reshape2)
matmelted <- melt(mat)
matmeltedcross<- merge(matmelted,matmelted,by = 'Var1', allow.cartesian = TRUE)
matmeltedcross$count <- matmeltedcross$value.x > matmeltedcross$value.y
mat.pm <- with(
  matmeltedcross[matmeltedcross$count == TRUE,],
  table(Var2.y,Var2.x)
)

Output -
> mat.pm
      Var2.x
Var2.y 1 2 3 4 5
     1 0 1 0 0 0
     2 2 0 1 1 2
     3 3 2 0 2 2
     4 2 3 1 0 1
     5 3 2 1 1 0


text:
Q: How to set my state from vuex to it's "original" form? Is it possible to set the state from my store to its original "form"?
In my application I have modal and when it's closed I want to get rid of all the changes that the user has made.
This is my state:
const state = {
    calendarOptions: [
        { startDate: moment().format("YYYY-MM-DD"), endDate: moment().add(365, 'days').format("YYYY-MM-DD")}
    ],
    startDate: moment().format("YYYY-MM-DD"),
    endDate: moment().add(7, 'days').format("YYYY-MM-DD"),
    dirtyRangeUpdate: true,
    availableChannels: {},
    availableRooms: {},
    availableRates: {},
    weekDays: [],
    rangeContext: '',
    selectedRooms: [],
    selectedRatePlans: [],
    selectedChannel: [],
    revenueRatePreference: '',
    showOnlyPreselected: true,
    rangeUpdateDataCollection: null,
    rangeUpdateSubmitData: null
}

How is it possible to achieve it? Thanks in advance.


text:
Q: Google Identity Platform pricing - Monthly Active User I'm trying to pin pricing on a use case for Identity Platform and would appreciate if anyone can confirm how the pricing works.
The pricing documentation states:

Any account that has signed in within a given month is considered an active user. Inactive users are stored at no cost.

My reading of this is that I could create a user account programmatically (e.g. in a cloud function) and I would not be charged for that account, until and unless someone actually signs in to that account. (As opposed to the user being counted as active for the month in which the account is created, login or no.) Does anyone know if that reading is correct?

A: You should get verification from the Google itself if yor understanding of the charges is correct; open up a ticket with Google Cloud Billing here: https://cloud.google.com/support/billing
However - documentation clearly describes how do you define an active user here.
Alternatively you can experiment yourself - create a test account and don't login for over a month and then check the billing.

A: According to this identity platform pricing model document:
Identity Platform charges per Monthly Active User (MAU) for most sign-in methods.
That is, any account that has signed in within a given month is considered an active user. Inactive users are stored at no cost.
Phone and multi-factor authentication users are charged per successful verification.


text:
Q: Падает метод если запускать его из теста JUnit Написал метод который создает архив, если запускать из Main'a то все работает. Пытаюсь протестировать с помощью junit - падает ошибка java.io.FileNotFoundException: src\main\resources\zipped2.zip (Системе не удается найти указанный путь)
В чем может быть проблема?
Main:
public class Main {
    public static void main(String[] args) throws IOException {
        Zipper zipper = new Zipper();
        String packageSource = "src/main/resources/packageToZip";
        File file = new File(packageSource);
        FileOutputStream pathForZip = new FileOutputStream("src/main/resources/zipped.zip");
        ZipOutputStream zipOut = new ZipOutputStream(pathForZip);
        zipper.zip(file, file.getName(), zipOut);
        zipOut.close();
        String zipFile = "src/main/resources/zipped.zip";
        String outDirectory = "src\\main\\resources\\outDirectory";
        zipper.unZipIt(zipFile, outDirectory);
    }
}

Zipper:
public void zip(File file, String filename, ZipOutputStream zipOut) throws IOException {
        if (file.isDirectory()) {
            if (filename.endsWith(File.separator)) {
                zipOut.putNextEntry(new ZipEntry(filename));
                zipOut.closeEntry();
            } else {
                zipOut.putNextEntry(new ZipEntry(filename + File.separator));
                zipOut.closeEntry();
            }
            File[] filesList = file.listFiles();
            for (File foreachFile : filesList) {
                zip(foreachFile, filename + File.separator + foreachFile.getName(), zipOut);
            }
            return;
        }
        try (FileInputStream fileInput = new FileInputStream(file)) {
            ZipEntry zipEntry = new ZipEntry(filename);
            zipOut.putNextEntry(zipEntry);
            byte[] buffer = new byte[fileInput.available()];
            int length;
            while ((length = fileInput.read(buffer)) >= 0) {
                zipOut.write(buffer, 0, length);
            }
        }
    }

Test
public class ZipperTest {

    @Test
    public void zip() throws IOException {
        Zipper zipper = new Zipper();
        String packageSource = "src/main/resources/packageToZip";
        File file = new File(packageSource);
        FileOutputStream pathForZip = new FileOutputStream("src/main/resources/zipped2.zip");
        ZipOutputStream zipOut = new ZipOutputStream(pathForZip);
        zipper.zip(file, file.getName(), zipOut);
        zipOut.close();
    }
}

A: При запуске теста - другой текущий директорий. Задавайте/вычисляйте абсолютный путь.


text:
Q: Question about exact differential equation When we are asked to solve the 1st order ODE of the form,
$M(x,y)+N(x,y)y'=0$
and given that it is exact, then there exists a function $\phi(x,y)=C$ s.t $\phi_x=M $ and $\phi_y=N$
But did we actually solve the ODE?Did we actually find a function y=y(x) explicitly or implicitly?
If the ODE is not exact, then we have to multiply an integrating factor $\mu(x,y)$ to make it exact, and again obtain a function $\chi(x,y)=C$
But this time the total differential of $\chi$ is not equal to the original ODE, did we actually 'solve' the ODE?

A: Yes, to both questions.
Obviously, you find implicit solutions.