text:
Q: merge duplicate file path in children - tree node I am using the following json to build a tree structure.. if you notice, there are 2 children with identical file path borides and titanium, I need to merge them so that duplicate folders are not created.
my output folder structure would be
SRD 13
    - borides
        - titanium
            - srd13_B-102.json
            - srd13_B-103.json

with the following json, borides and titanium are getting repeated
Input json
parentObj =

[{
"data": {
    "resTitle": "-JANAF Thermochemical Tables - SRD 13"
},
"children": [{
    "data": {
        "filePath": "borides"
    },
    "children": [{
        "data": {
            "filePath": "titanium"
        },
        "children": [{
            "data": {
                "filePath": "srd13_B-102.json"
            },
            "children": []
        }]
    }]
}, {
    "data": {
        "filePath": "borides"
    },
    "children": [{
        "data": {
            "filePath": "titanium"
        },
        "children": [{
            "data": {
                "filePath": "srd13_B-103.json"
            },
            "children": []
        }]
    }]
}]
}]

Output json would be
[{
"data": {
    "resTitle": "-JANAF Thermochemical Tables - SRD 13"
},
"children": [{
    "data": {
        "filePath": "borides"
    },
    "children": [{
        "data": {
            "filePath": "titanium"
        },
        "children": [{
                "data": {
                    "filePath": "srd13_B-102.json"
                }
            },
            {
                "data": {
                    "filePath": "srd13_B-103.json"
                }
            }
        ]
    }]
}]
}]

I am using the following script to merge the nodes but it only looks for identical filepath in first level, but in this case there are identical file paths in second level too..
const tmp ={}
ParentObj.children.forEach((o) => {
    const path = o.data.filePath;
    if (tmp[path]) {
        tmp[path].children = tmp[path].children || [];
        tmp[path].children.push(...o.children)
    } else {
        tmp[path] = o;
    }
});
ParentObj.children = Object.values(tmp);

I appreciate any help.

A: You need some recursion to achieve this. I used Array.prototype.reduce() and recursive function merge to merge duplicate children nodes:

const merge = (data) => {
  return data.reduce((result, current) => {
      let dup = result.find(d => d.data.filePath === current.data.filePath);
      if (!dup) {
          result.push(current.children && current.children.length > 0 ? {
              data: current.data,
              children: merge(current.children)
          } : {data: current.data});
      } else if (current.children && current.children.length > 0) {
          dup.children = merge(dup.children.concat(current.children));
      }
      return result;
  }, []);
};

let parentObj =
[
   {
      "data":{
         "resTitle":"-JANAF Thermochemical Tables - SRD 13"
      },
      "children":[
         {
            "data":{
               "filePath":"borides"
            },
            "children":[
               {
                  "data":{
                     "filePath":"titanium"
                  },
                  "children":[
                     {
                        "data":{
                           "filePath":"srd13_B-102.json"
                        },
                        "children":[

                        ]
                     }
                  ]
               }
            ]
         },
         {
            "data":{
               "filePath":"borides"
            },
            "children":[
               {
                  "data":{
                     "filePath":"titanium"
                  },
                  "children":[
                     {
                        "data":{
                           "filePath":"srd13_B-103.json"
                        },
                        "children":[

                        ]
                     }
                  ]
               }
            ]
         }
      ]
   }
];

console.log(JSON.stringify(merge(parentObj), null, '  '));


text:
Q: adding show.rjs causes error on show.haml page I have a controller that I want to be able to respond to html or to js requests.
Currently, I have a HAML page that shows information about a document. Simply by adding a show.rjs file to the views/documents folder, I start getting errors.
Here is what renders:
try { } catch (e) { alert('RJS error:\n\n' + e.toString()); alert(''); throw e }

Here is my controller:
def show
    @document = Document.find(params[:id])
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @document }
      format.js
    end
end

here is show.rjs:
logger.debug "what the heck!"

Anyone have any idea why this might not be working?

A: Rename it show.js.erb
Change your content to <% logger.debug "what the heck!"%>
I think the latest is enough though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Xcode accidentally removed reference to a file I accidentally removed the reference to a .h file in xcode.
The file is actually a nuisance and needs to be deleted. I tried finding the physical location of the file and deleting through finder but it caused the build to fail. I have now restored it back to the physical location.
I need to undo the "remove reference" so I can then delete the file through XCode properly.
Thanks for the help

A: No worries.The file exist.
You need to add it again .
First click ⌥⌘A and after add the missing file.


text:
Q: How to prevent concurrent login for a web application using express-session I am creating a web application which will be used by App's Administrators and for security reasons we don't want to allow multiple active logins from a single user at any point of time.
I am storing session data in the web browser's cookie and want backend to have active user's information who are currently logged in to the application so that on successful login request I can find out if this particular user already has an active session. If that is possible then I can block the login for that user.
One way to do that is storing IsLoggedIn in the Database with LastLoginTime and on each login, I can use this two flags to identify if an active session exists.
Open to other better solutions if any

A: I think a more robust solution than checking last login times would be to generate and store an id for each new login and then include a middleware to make sure the session's id for each user matches what you expect. That way every time the user logs in on another device the previous one will be invalidated and only one session will be valid at a time. You may even just be able to use express-session's req.session.id.


text:
Q: Let $f : \mathbb R → \mathbb R$ be defined by $f(x) = |x|$. Prove or disprove:

Let $f : \mathbb R → \mathbb R$ be defined by $f(x) = |x|$. Then $f$ is $T_u − T_u$ continuous.

where $T_u$ is usual topology

A: Of course you are right, yet your answer is not complete though. It's an easy fact that a set in $\mathbb{R}$ is open if and only if it's the union of open intervals. So for any open set $U$, we have $$U=\cup_{\lambda \in \Lambda}V_{\lambda}.$$ where each $V_{\lambda}$ is an open interval. Thus,$$f^{-1}(U)=f^{-1}(\cup_{\lambda \in \Lambda}V_{\lambda})=\cup_{\lambda \in \Lambda}f^{-1}(V_{\lambda}).$$ As you have shown,each $f^{-1}(V_{\lambda})$ is open in $\mathbb{R}$. Hence, $f^{-1}(U)=\cup_{\lambda \in \Lambda}f^{-1}(V_{\lambda})$ is open in $\mathbb{R}$ for it's union of open sets, which implies $f$ is $T_{u}−T_{u}$ continuous.

A: $\left|\,|x| - |y|\,\right| \le |x-y|$ by the reverse triangle inequality. So $f$ is Lipschitz, we can take $\delta = \epsilon$ uniformly on $\mathbb{R}$. This gives us that $f$ is even uniformly continuous.
As for continuity via open sets: you indeed only have to check (by a simple lemma) $f^{-1}[O]$ is open for $O$ in a (sub)base for the topology, like open intervals, or open segments. But you either have to know / quote such a lemma, or prove it yourself (which is not hard).


text:
Q: jQuery selectors -> all TD within a specific table I am still learning jQuery and the selector bit is incredibly useful, but I still don't understand it perfectly well.
I have a table with id=table1, and I want to select all td's in this table.
(really I want to wrap the text within each td with a div with overflow:hidden so I can force the cell heights to be uniform.)
What's the appropriate syntax for the jQuery (javaScript?) selector?
Any links to awesome selector tutorials are also welcome.

A: The following should do the trick
$('#table1 td').wrapInner('

');

and add a css rule in your stylesheet
.no-overflow{
      overflow:hidden;
      /*and whatever other css properties here*/
 }

For completeness here is the documentation about

*

*wrapInner()

*all selectors

*the Descendant Selector jQuery('ancestor descendant') that we used in this situation

A: This will select all the cells:
$("#table1 td")

jQuery uses CSS3 selectors, read about them here:
http://api.jquery.com/category/selectors/

A: $("#table1").find("td");

A: $("#table1 td").each(function() {
  var text = $(this).html();
  var div = $("

");
  div.html(text);
  $(this).html(div);
});


text:
Q: http paranoia/concern I am currently creating a personal "local" website. I do not plan on port fowarding to make it accessible to those outside my network. Will that be good enough for security, what about people on the same local network as I am, how can I block any other pcs from accessing my website, or password protect it?
I feel that http is not needed for this type of setup due to it being a local website, but I have connection to many APIs: Google Maps API, Facebook API, etc. Can my site be compromised without having http?
-Thanks, this community's support has always been fantastic!

A: Bind your webserver to 127.0.0.1, then you will only be able to access the site locally.


text:
Q: How to inject specific JSON data into an HTML element? Big Picture: Building a website to organize dinosaurs based on time-period - I've learned how to store JSON data files. It is accessing and injecting this data that I am having trouble with.

*

*I'm using a pop-up script that fires when an item on one of the lists is clicked that pops-up to display data about the selected Dino (src: http://dev.vast.com/jquery-popup-overlay/)

looks like this:

*

*From this image you can see there are a few fields that need to be filled from a list of JSON data - from here I have a few questions:

*

*If there are, say, 100 dinosaurs - what is the most efficient way to store this data? Should I have a separate JSON txt file for each dinosaur's traits?

*How can I link each list items such that when they are clicked - they load the proper data - without writing very redundant code?

*

*for example the pop up script fires when the "name_open" class is         added to the HTML element that is clicked - could I do something similar to inject my JSON data?
stored JSON data is such:
[
{
    "name": "T-REX" ,
    "period": "85-65 million years",
    "location": "Montana, USA",
    "discovered": "1902"
}
]

within the pop-up  the code is as follows:

 T-REX

Name:

Period:

Location(s):

Discovered in:

*

*I have ID'd every item into which I would want to inject code.

So, once again - how can I inject my data, and what is an efficient way on storing a vast amount of data?

*

*i understand that this question is broad, but I would really appreciate some directional advice such as would AJAX be completely necessary to inject this data? Or is there anyway to store multiple dinosaur's data in one JSON text file - I'd assume having to use REGEXPs to sort through the data. The biggest obstacle is how to tie each list item to a specific data point in the JSON array without writing an abundant amount of redundant code.

if it's any use I copy-pasted most of the page data into this fiddle, however can't get the pop-up script to function within it: https://jsfiddle.net/evanbananas/ssgeLpox/1/

A: You can use jQuery.getJSON() method!
For ex.:
$.getJSON( "stored/test.json", function( data ) {
  $.forEach(data, function(d, i) {
     $('#name').html(d.name);
     $('#period').html(d.period);
     $('#location').html(d.location);
     $('#discovered').html(d.discovered);
  });
});

A: You could also use AngularJS. It is really simple to work with JSON data and put each value into any html elements.


text:
Q: "Unsubscribe" from messages about limits If I reach limits for my Salesforce edition I'm receiving message like "Hourly limit exceeded for processing workflow time trigger". Is there any way I can stop receiving these messages, like unsubscribe or uncheck some option?

A: Salesforce limits the number of time triggers an organization can execute per hour as follows:

*

*Enterprise Edition =500

*Developer Edition =50

*Unlimited Edition =1,000

Refer this link
https://developer.salesforce.com/forums/?id=906F00000008m1cIAA


text:
Q: font shorthand line-height not inheriting on child elements I have this declaration
body {font: normal .625em/1.2em Arial, sans-serif;}

I would normally expect that any paragraph tags etc would inherit the line-height and adapt it to there specific size. For example
p {font-size: 2.0em}

should have a line-height of 24px assuming a base 16px browser font size * .625 = 10px * 2.0em = 20px 1.2em line height on 20px is 24.
Odd thing it appears to be rendering as just 1em
If i change the body declaration to
body {font: normal .625em/1.2 Arial, sans-serif;}

omitting the em unit it renders correctly. So I guess my problem is solved but I have never seen this before and am very confused as to why this is. Does anyone know the reason for it? Sorry I cant point to a site I am building locally.

A: Eric Meyer wrote on the topic of "unitless line-height" several years ago:  http://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/
Basically, if you include the unit, then the line-height is based off of the ancestor element's font-size and not the current element's font-size.

A: When a property is inherited, the inherited value is the "computed value". This means that if you declare a value of 1.2em for body, then the body font size is multiplied by 1.2 and the result is the value that will be inherited by any child of body that does not have the property set on them. No matter what their own font sizes are.
For line-height, there is a special rule regarding the use of pure (unitless) numbers: "The used value of the property is this number multiplied by the element's font size. […] The computed value is the same as the specified value." This means that when you specify the value as 1.2, then you get the same line height for body (the "used value") as you get by using 1.2em, but the inherited value ("computed value") is the pure number 1.2. And this means that it will get multiplied by each element's own font size.
The morale is that line-height should normally be set using a pure number. Moreover, it is generally best to set it for all elements, avoiding all inheritance for it, e.g. * { line-height: 1.3; }. (By the way, 1.3 is generally better than 1.2 for Arial. StackOverflow uses a value corresponding to 1.3, with Arial as the primary font, and the line height is hardly excessive here. But this depends on factors like line length of course.)


text: Q: Getting a list of locales of a xcode project from a run script pahse Is there a way of loading the list of locales added to a xcode project in a run script phase ? I need to create the proj folders automatedly.


text:
Q: How expensive is it to have a list field with thousands of elements on a realm object? Let's say that we have a group object with a field called contacts on it. Contacts is a list that holds references to contact objects and can in theory have up to 20 000 objects in it.
My question(s):
If I query group object, am I taking a performance hit because there's a huge list field on it? If not, am I taking a performance hit when I access that field?
If this design is not good, would it be better to instead have a groups field on contact object, since there is probably a lot less groups than there is contacts?
Thanks in advance!

A: Non-code questions are challenging as we don't know the entire use case but let me address this at a high level.
Generally speaking, Realm Results which are Collections are lazily-evaluated results of a query operation. A realm List is also an example of a Collection.
This lazy evaluation enables code to be written that is elegant, high performance code even when the data sets are gigantic and with complex queries.
You can generally work with Collections like a regular JavaScript array but they don't actually hold matching Realm objects in memory. Instead they reference the matched objects stored in the Realm file.
The end result is that large datasets have very small memory footprints which in most cases avoids the need for paginating the query as the Realm objects are only loaded when used. Pagination can then be handled in memory on the device by just displaying smaller number of elements from the query, appropriate for your UI

e.g. if the query returns 10,000 results, optionally use pagination to
display 10 at a time via an index [0...9] and then [10...19] for
example. That technique preserves the query results but also protects
memory as only those 10 elements are loaded but you still have access to
the entire query results

So, as long as you keep your Realm objects as a Collection type - then no, the memory impact is minimal. However, and this is the important bit, as soon as high level functions are run against those collections or they are mapped to an array, ALL of the data is loaded.
Best practice is to keep Realm objects 'Realmy' by leveraging Collections (Results, Lists etc).
If your Contacts is a List collection then you should be good to go.


text:
Q: How can I capture the content wrapped in a pair of custom Blade directives? I am trying to write a custom Blade directive which can modify the content and return it, something like this:

    @uppercase
    This is a line of text.
    @enduppercase

which would render in the HTML as following:

    THIS IS A LINE OF TEXT.

What I do NOT wish to know is how to do the following:
@uppercase('This is a line of text')

How can I capture all the content within the start and end directives, process and then return them to the view?
Note: There is a similar sounding question here, with a comment linking to another question that purportedly has the answer, but it doesn't really answer the question I have described here.

A: I found the answer shortly after posting this question.
Add the following to your AppServiceProvider::boot() method:
\Blade::directive('uppercase', function () {
    return '<?php ob_start(); ?>';
});

\Blade::directive('enduppercase', function () {
    return '<?php echo strtoupper(ob_get_clean()); ?>';
});

I referred to this code for the idea: https://github.com/RobinRadic/blade-extensions/blob/master/src/Directives/EndspacelessDirective.php


text:
Q: multiple values insert to mysql using last used id for multiple files i'm making a car info form in the admin panel. I want to add 6 images which would have the same id as the car info
form
  car info selectors (x12)
  file input (x6)
/form

2 separate tables (cars and images)
how do i give all the file inputs the same id as the car info?
i'm new to programming, but in my mind i have to use max(id) from the car table, add +1 and give it to all the input files carID when inserting them to the database. Is there and easier way to do this? or is my logic faulty?

A: If you are using mysqli in php then use the mysqli_insert_id function
http://www.php.net//manual/en/mysqli.insert-id.php
This gives you the id of the last record inserted.
You should never just use the max id. Entirely possible another record has been inserted by another user / process between your insert and you following inserts of dependent records.


text:
Q: Django-Taggit validate newly added tags before save This is how my models look like. I was not able to do the validation by overriding the save method of either of the models.
class NotificationListTag(TaggedItemBase):
    content_object = models.ForeignKey('Mailer')

class Mailer(models.Model):

    from_email = models.CharField(max_length=255)
    to_emails = TaggableManager(
        through=NotificationListTag,
        blank=True,
        verbose_name='To Emails',
        help_text='Space separated email ID'
    )

How do I validate each of the newly added tags before it gets saved. Did I miss something out.

A: I ended up creating a custom API for the tagging autocomplete suggestions, that only suggests valid names.
You can override the the tagit.js call wagtail makes by default, to pass your custom autocomplete URL to it. In this way, you don't have to do validation after the user has entered a value.


text:
Q: Accessing Cload Firestore Database using a locally running Firebase Function Emulator I use the Firebase Emulator Suite to run and debug my Cload Functions locally, as described in this guide: https://firebase.google.com/docs/functions/local-emulator
I got a Cload Firestore Database ready-to-go with some data in it.
I try to fetch data from Cload Firestore through my locally emulated cload functions.
My approach so far was following the "Writing the Cloud Function Code" section in https://cloud.google.com/community/tutorials/cloud-functions-firestore
My functions/src/index.ts file looks like this:
import * as functions from 'firebase-functions';

const Firestore = require('@google-cloud/firestore');
const cors = require('cors')({origin: true});
const admin = require('firebase-admin');

admin.initializeApp();

const PROJECTID = 'XYZ';
const firestore = new Firestore({
  projectId: PROJECTID
});

const logger = function(object: any){
    console.log(JSON.stringify(object));
}

export const create_order = functions.https.onRequest((request, response) => {
    cors(request, response, () => {
        // var test_doc_id = "82GKB2P6xee9lftOidDj";
        const trucks = firestore.collection("trucks").get();
        logger(trucks);
        response.send(JSON.stringify(firestore));
    });
});

I expected the value of "trucks" to be an array of all trucks coming from firestore, but there is no result "{}" coming back.
Can someone give me hints, guides and suggestions how to do this in a correct way ?
Best regards, and thanks for your help

A: firestore.collection("trucks").get() returns a Promise.
If you want to log out the data, you could write an asynchronous method:
cors(request, response, async () => {
  const trucks = await firestore.collection('trucks').get();
  logger(trucks);
  // ...
});

A: I think you can control which DB functions are listening to with GOOGLE_APPLICATION_CREDENTIALS environment variable. Running without will listen to local, while running with your production firebaseAdminSdkServiceAccount.json will listen to changes on production DB.
On windows you would start it from terminal like this:
SET GOOGLE_APPLICATION_CREDENTIALS=/config/firebaseAdminSdkServiceAccount.json
firebase emulators:start

Then for listening for firestore document changes you reference:
const functions = require('firebase-functions');
functions.firestore.document('/mydoc/{mydocId}').onWrite(...)

EDIT: To make sure I'm right I did some googling, and came up with this explaination:

When using emulators:start we want to keep people inside the local
  emulation environment unless they specifically ask to be broken out.
  Right now, you can ask to contact production by manually restoring the
  GOOGLE_APPLICATION_CREDENTIAL files when running in the emulator.

https://github.com/firebase/firebase-tools/issues/1412#issuecomment-504561828


text:
Q: Coefficient of Maass cusp forms are bounded Let $$\phi(z)=\sum_{\gamma\in U_2(\mathbb{Z})\backslash SL(2,\mathbb{Z})} \,\,\,\,\,\sum_{m_1=1}^{\infty}\,\,\sum_{m_2\neq 0}a(m,n)W_{\text{Jacquet}}\left(\begin{pmatrix} |m_1m_2| &  & \\
 & m_1 & \\
 & & 1 \end{pmatrix}\begin{pmatrix}\gamma & \\ & 1\end{pmatrix}z\,,\, \nu,\,\psi_{1,\frac{m_2}{|m_2|}} \right)$$ be a Maass cusp form of type $\nu=(\nu_1,\nu_2)$ for $SL(3,\mathbb{Z})$. Show that $a(m,n)=O(1).$
Note that$$a(m,n)W_{\text{Jacquet}}\left(\begin{pmatrix} |m_1m_2|y_1y_2 &  & \\
 & m_1y_1 & \\
 & & 1 \end{pmatrix}\,,\, \nu,\,\psi_{1,\frac{m_2}{|m_2|}} \right)\\=\int_0^1\int_0^1\int_0^1\phi(z)e^{-2\pi i[m_1x_1+m+2x_2]}\,dx_1dx_2dx_3$$ If we knew that $\phi$ is bounded, then the claim would follow by choosing $y_1=c_1|m_1|^{-1}, y_2=c_2|m_2|^{-1}$ , but we only know that $\phi(z)$ is square integrable in the Seigel domain.


text:
Q: Vue.js slider with local image doesn't work Hi i find this image slider for Vue.js on "digitalocean.com" but works only with image uploaded on (imgbb, pixabay, etc). i try to set with local image (on assets) but doesn't work, some one can help me?
i already tried with ../assets/castelgandolfo.jpg or ./assets/castelgandolfo.jpg
sorry for my english!
This is the code:

export default {
  name: "Slider",
  data() {
    return {
      images: [
        "https://i.ibb.co/6NJ7p6w/Castelgandolfo.jpg",
        "https://i.ibb.co/QJN06cG/Grottaferrata.jpg",
        "https://i.ibb.co/R3pHtGx/Ariccia.jpg",
      ],
      timer: null,
      currentIndex: 0
    };
  },

  mounted: function() {
    this.startSlide();
  },

  methods: {
    startSlide: function() {
      this.timer = setInterval(this.next, 10000);
    },

    next: function() {
      this.currentIndex += 1;
    },
    prev: function() {
      this.currentIndex -= 1;
    }
  },

  computed: {
    currentImg: function() {
      return this.images[Math.abs(this.currentIndex) % this.images.length];
    }
  }
};

A: You can refer images directly using '@'
Example:
<img src="@/assets/images/home.png"/>


text:
Q: Is there any way to invert the caret? When programming in Visual Studio, the caret (i.e. the vertical line that shows where text will be inserted) is either a vertical line (when in insert mode) or a block (when in overwrite mode).
Is there anyway to make it the other way around?
I just like the block caret...reminds me of the 380Z that I first started programming on...

A: $Host.UI.RawUI.CursorSize = 100
The value is a percentage size.  Default value is 25.

A: To my knowledge, this is not possible. The vertical line in the VS editor sits between two characters, showing where the new character will be inserted. In insert mode, the block shows which character will be replaced. Nearly every development text editor I've used (many versions of Visual Studio, Delphi, VBA editor in Excel, etc) uses this convention. Swapping the modes just wouldn't make much sense.


text:
Q: Android system wide nofiles(descriptors) limit Is there any way to set system wide nofiles(descriptors) limit - like editing /etc/security/limits.conffile in linux?
I have root access to system - so access rights is not problem

A: I have not found any solution to do this system wide, but found terminal command prlimit ${PID}  7  SOFT HARD where PID is Process ID of your app. SOFT and HARD are soft and hard limits.
But be careful - there are some software in android which will not work if you have too much opened FD. I personnally met such kind of errors (for chromium web view):
Abort message: 'FORTIFY: FD_SET: file descriptor >= FD_SETSIZE'
But decreasing limit works good for me allowing to meet "Too many open files" much quicker =)


text:
Q: BigQuery Automation using PUB/SUB trigger? During bigquery automation i am deploying this https://github.com/firebase/functions-cron sample code. What changes i need to make in this. And not getting what is url, description. How to set url?

A: I have tried a BigQuery Automation using http trigger, hope it could be helpful. Here is what I did:

*

*Create a Cloud Function that runs BigQuery query.

*

*Keep the HTTP trigger url for step2.  https://[your_project_ID].cloudfunctions.net/[your_cloud_funtion_name]

*Create an App Engine App.

*

*Since we cannot specify a Google Cloud Endpoint in the url field of a cron job, I created a handler to send the request to HTTP trigger url

*Create cron.yaml that calls this handler every x minutes.

*Deploy the application to App Engine.
$ gcloud app deploy app.yaml \cron.yaml

If you need more details, please post a comment and I will be happy to help.


text:
Q: How to config GenericObjectPoolConfig? Currently, I am using apache commons pool2. But I couldn't find any document related to how to config GenericObjectPoolConfig properly. Like maxIdle, maxActive, minEvictableIdleTimeMillis and so on. Does anybody have some general rules?

A: Please refer to the official documentation as below
I like the configurable parameters documented in pool 1.x :
https://commons.apache.org/proper/commons-pool/api-1.6/org/apache/commons/pool/impl/GenericObjectPool.html
However, in pool2 documentation can be read from the method level documentation :
https://commons.apache.org/proper/commons-pool/apidocs/org/apache/commons/pool2/impl/GenericObjectPool.html
For the later part of the question regarding the 'general rules', the pool (BaseObjectPoolConfig) comes with the defaults configured, so you can test and then fine tunes specific parameters based on your app behavior.
Hope this clarifies, else you can ask specific questions.


text:
Q: Keras Sequence of sequences Let's say I have an Input to the model as sequence of items: [3,2,1,4,5,6]. Then I can make Keras Input Layer shape=(SEQUENCE_LEN, ) and then add Embedding Layer. But I have an Input of sequences of sequences of pairs. For example : [[(3, 1),(2,3),(1,5)], [(4, 1),(5,2)], [(6, 5),(7, 1),(8, 5)]]
I have pre-trained embeddings for first items in each pair and I want to have trainable Embedding Layer for second items in pairs. The second item in each pair roughly speaking means the amount of a first item in some context. Which first layers do you suggest to use to convert this problem to usual sequence classification? I suspect that I would need more than just a combination of Embedding and Input Layer
UPD: Even if I just concat these sequences into one, how do I cope with second value in each pair? What is the best way to use information about "amount" of items?


text:
Q: Does monotonicity imply surjectivity? There is an exercise in "An introduction to Category Theory" by Harold Simmons says:
Consider any pair of $\mathcal{Pos}$-arrows $f: S \rightarrow T$ and $g: T \rightarrow S$.
Show that when both $id_S \le g \circ f$ and $f \circ g \le id_T$,
if $f \dashv g$ then
$$f \circ g \circ f = f \quad g \circ f \circ g = g $$
There is a solution to this exercise ([here](http://www.cambridge.org/us/download_file/150877/, exercise 1.3.6(b) on page 12)), which I don't understand:
To prove $f \circ g \circ f = f$, we know that $\forall a \in S, id_s(a) \le (g \circ f)(a)$ and because $f$ is a monotonic function($\mathcal{Pos}$-arrow),
we know that $f(a) \le (f \circ g \circ f)(a)$, so far so good.
On the other hand, it states that for each $b \in T$, we have
$$ (f \circ g)(b) \le b $$
and hence
$$ (f \circ g \circ f)(a) \le f(a) $$
as a particular case.
But here how can we go from $b$ to $f(a)$? It might look obvious but for $f$ we only know that it is monotonic, to make sure $\forall b \in T, \exists a \in S, f(a) = b$ we need $f$ to be surjective. However this concern isn't seen in the proof.
So even if it doesn't sound good to me, I guess monotonicity implies surjectivity?
EDIT:
I think in general if there is a poset $S$, $\forall a,b \in S$, if $a \le b$,
then it is fine to "add any monotone to the left side" (i.e $f(a) \le f(b), (g \circ f)(a) \le (g \circ f)(b),(h \circ g \circ f)(a) \le (h \circ g \circ f)(b), \ldots $, sorry I don't know the formal terminology for this) But I doubt the same holds when you are "adding monotone to the right side".

A: No, monocity doesn't imply surjectivity, but we don't even need surjectivity.
By hypothesis, we know that for all $b\in T$ we have $(f\circ g)(b)\le b$. In particular, for any $a\in S$, it also holds for the element $f(a)\in T$ written in place of $b$.
By the way, the conditions on the pair $f,g$ (to satisfy $id_S \le g\circ f$ and $f\circ g\le id_T$) make the definition of $f$ being left adjoint to $g$, i.e. $f\dashv g$ (also called a 'Galois connection' between $S$ and $T^{op}$).


text:
Q: Combine few grok into one I have the log entry and the grok pattern as below.
Log:
2017-04-11 18:31:41,938 | INFO | 195 | Process | Bundle Name | logStr: GUID: dl99X/WeN77E2SmyjH9uS1Fy+EDvFQ5R_939bae | ReferenceID: 20170411183141500676 | InstanceID: 70411183141906430422429270016 | ChannelID: EXAMPLE | System: EXAMPLE | ServiceName: EXAMPLE | InvocationPoint: inbound

2017-04-11 18:31:42,743 | INFO | 193 | API | Bundle Name | Outbound Message | RESPONSE=[GUID=[dl99X/WeN77E2SmyjH9uS1Fy+EDvFQ5R_939bae], InstanceID=[70411183141906430422429270016], logStr=[GUID: dl99X/WeN77E2SmyjH9uS1Fy+EDvFQ5R_939bae | ReferenceID: 20170411183141500676 | InstanceID: 70411183141906430422429270016 | ChannelID: EXAMPLE | System: EXAMPLE | ServiceName: EXAMPLE | InvocationPoint: inbound

Grok pattern:
grok {
#grok general pattern
match => {
"message" => "%{TIMESTAMP_ISO8601:logdate}%{SPACE}\|%{SPACE}%{LOGLEVEL:level}%{SPACE}\|%{SPACE}%{DATA:thread}%{SPACE}\|%{SPACE}%{DATA:serviceName}%{SPACE}\|%{SPACE}%{DATA:bundle}%{SPACE}\|%{SPACE}%{GREEDYDATA:logdetails}"
}
}
#Grok to get GUID
grok {
match => {
"logdetails" => "(?<=GUID:).%{DATA:guid}(?=\s)"
}
}
#Grok to get ChannelID
grok {
match => {
"logdetails" => "(?<=ChannelID:).%{DATA:channelID}(?=\s)"
}
}
#Grok to get ReferenceID
grok {
match => {
"logdetails" => "(?<=ReferenceID:).%{DATA:referenceID}(?=\s)"
}
}

I have few separate grok to just get the GUID, ChannelID and ReferenceID.
Is there any way to combine the groks into one?
Thank you in advance!

A: It's best to know the types of logs you're dealing with, but what I'll do when there are too many types to worry about (but they remain in the same format):

*

*Determine the base format

*Treat everything after base as the "msg" or payload.

*Parse the payload with the fields you are looking for.

Each of your messages have the base format of timestamp | loglevel | thread:
LINE %{BASE}\s?\|\s?%{GREEDYDATA:msg}

# Patterns
BASE %{CUSTTIME:timestamp}\s?\|\s?%{WORD:loglevel}\s?\|\s?%{NONNEGINT:thread}
CUSTTIME %{YEAR}-%{MONTHNUM}-%{MONTHDAY} %{HOUR}:%{MINUTE}:%{SECOND},%{MILLI}
MILLI (?:([1-9][0-9]{0,2}|0))

Then you can just add the patterns for the fields you're looking for in the same pattern file, since all of the values are very similar to key=value, but instead with colons:
COMMAVALUE (\s?(.*?(?=\s\w+:|$))\s?)

# Fields
GUID GUID:%{COMMAVALUE:guid}
CHANNELID ChannelID:%{COMMAVALUE:channel_id}
REFERENCEID ReferenceID:%{COMMAVALUE:reference_id}

So you can use two adjacent grok filters to do this, one to extract the msg payload, and another to extract the fields from said msg.
filter {
    grok {
        patterns_dir   => "/etc/logstash/patterns"
        match => { "message" => "%{LINE}" }
    }
    grok {
        patterns_dir => "/etc/logstash/patterns"
        break_on_match => false
        match => [
            "msg", "%{GUID}",
            "msg", "%{CHANNELID}",
            "msg", "%{REFERENCEID}"
        ]
    }
}

output {
    stdout { codec => "rubydebug" }
}


text:
Q: Declaring a variable without specifying its data type in C++ Why is it necessary  to specify the datatype of a variable? What if my program requires the user to enter data that could belong to any one of two non intersecting data types? Shouldn't the option of declaring a variable without specifying a variable be provided so as to account for a situation. Why can't we let the computer decide the data type on the basis of user input? If the compiler has enough capability to identify a type error, I'm sure it can easily specify a data type on the basis of the input.

A: Compilers don't deal with input, so that's no option.
There's boost::variant<T,U> which is a type can hold either T or U values, but you still have to specify to the compiler all possible options, and you have to make clear what you put in.
User input always starts out as a string. Parsing turns that into types, but the result depends on the actual parsing. If you're parsing float values, 0 is a perfectly fine float value.


text:
Q: Understanding "like" vs equal in T-SQL to rewrite where condition My original statement is
where charindex(';' + tableA.Col1 + ';' , ';' + Table.col2 + ';') > 0

I want to rewrite this. First I use in a join condition
on (';' + Table.col2 + ';') like  ('%;' + tableA.Col1 + ';%')

This gives the same result. But then I think why concatenate the semicolons
on Table.col2 like  ('%' + tableA.Col1 + '%')

Which also gives the same result. But since I concatenate ; on both sides I thought maybe they were after equal on both sides:
on Table.col2 = tableA.Col1

But this does not give the same result. Is there a way to use the equality sign instead of like? It does not make sense can anyone explain? Why has the first statement concatenation of ; of both sides?


text:
Q: ASP.NET Core with React.JS How to open separate Browser for the Backend? I've created an "ASP.NET core with React.Js" project :

And when I'm running it, it waits a while then redirects me to the front-end page which makes me not able to have the back-end browser(I need it to play with SwaggerUI and other stuff):

The question is:
how can I make both browsers open? I mean a browser for the front-end "http://localhost:46432" and one for the back-end as well "https://localhost:7211".
And thank you in advance.

A: Download NuGet dependecy:

Swashbuckle.AspNetCore

Adding the following lines to Program.cs:
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
...
app.UseSwagger();
app.UseSwaggerUI();

then from the browser call the backend URL+swagger: https://localhost:7211/swagger


text:
Q: Entity Framework - Migrations update-database Throwing strange error I have been using EF - Code First for a while on a project, with everything working ok.
I recently got a new computer, installed Visual Studio and SQL Server. I then opened up the visual studio solution and tried to recreate my database using the update-database command.
I am getting this error. Any ideas of how to fix it?
PM> update-database -verbose
Using StartUp project 'AsoRock.Data'.
Using NuGet project 'AsoRock.Data'.
System.Xml.XmlException: 'true' is an unexpected token. The expected token is '"' or '''. Line 17, position 190.
   at System.Xml.XmlTextReaderImpl.Throw(Exception e)
   at System.Xml.XmlTextReaderImpl.Throw(String res, String[] args)
   at System.Xml.XmlTextReaderImpl.ThrowUnexpec;tedToken(String expectedToken1, String expectedToken2)
   at System.Xml.XmlTextReaderImpl.ParseAttributes()
   at System.Xml.XmlTextReaderImpl.ParseElement()
   at System.Xml.XmlTextReaderImpl.ParseElementContent()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r)
   at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r, LoadOptions o)
   at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
   at System.Xml.Linq.XDocument.Load(String uri, LoadOptions options)
   at System.Data.Entity.Migrations.Utilities.ConfigurationFileUpdater.Update(String configurationFile)
   at System.Data.Entity.Migrations.Design.ToolingFacade..ctor(String migrationsAssemblyName, String contextAssemblyName, String configurationTypeName, String workingDirectory, String configurationFilePath, String dataDirectory, DbConnectionInfo connectionStringInfo)
   at System.Data.Entity.Migrations.MigrationsDomainCommand.GetFacade(String configurationTypeName, Boolean useContextWorkingDirectory)
   at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
'true' is an unexpected token. The expected token is '"' or '''. Line 17, position 190.

A: I fixed it! Check your web-config file if you come across this problem. It was a typo in the file.


text:
Q: Удаление элемента из односвязного списка путём смещения Есть struct следующего вида:
type ListNode struct {
    Val  int
    Next *ListNode
}

В него записаны следующие данные:
0xc000104220&{1 0xc000104230}
0xc000104230&{2 0xc000104240}
0xc000104240&{3 0xc000104250}
0xc000104250&{3 <nil>}

DeleteDuplicates сравнивает между собой все элементы массива по полю Val и если находит похожие должен сдвинуть цепочку на месте дубликата.
func (ln *ListNode) DeleteDuplicates() {

LOOP:
    for e1 := ln; e1 != nil; e1 = e1.Next {
        for e2 := e1.Next; e2 != nil; e2 = e2.Next {
            if e1.Val == e2.Val {
                e1 = e1.Next //Должен перезаписывать ln
                goto LOOP
            }
        }
    }
}

В моём представлении e1 должен затереться ссылкой e1.Next, и всё это должно отражается на ln, так как e1 содержит ссылку на элемент ln, но вместо этого просто меняется значение e1. Скорее всего, я неправильно использую переменные со ссылкой, так как если написать в грубую ln.Next = ln.Next.Next это сработает.
Код на goplay если нужно: https://goplay.space/#CYWdOSI3DLM


text:
Q: --add-modules only on compilation I'm building my project with maven and java-9. I've added in my pom.xml file:
<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>${maven-compiler-plugin.version}</version>
    <configuration>
        <source>${java.version}</source>
        <target>${java.version}</target>
        <compilerArgs>
            <arg>--add-modules</arg>
            <arg>java.xml.bind</arg>
        </compilerArgs>
    </configuration>
</plugin>

But still, to run the application I have to run it like this:
java -jar --add-modules java.xml.bind my-app.jar

Is there a way to build the application, to run from the command line without --add-modules java.xml.bind to java command line arguments?

A: I made this answer a while ago where I answered this as an additional info to exposing non java.se packages in Java-9 using Maven.
The added part specifically focusses on using the standalone version of the
java.xml.* APIs. To adapt to which you can probably start consuming the dependency on jaxb-api:2.3.0 which can be loaded as a module and can be executed from the classpath as well. The change you need to make is to add the following to your dependencies list:
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

This way you ensure migrating to standalone APIs for the module as well as moving away from a deprecated piece of code.


text:
Q: Selecting Random Rows in relation to Random Rows So I've been trying for a few days now and looking all over but I can't seem to find a solution for this situation. Maybe I'm over-thinking it, so I guess this is two questions in one:

*

*Am I even going the right direction?

*Why isn't this working as expected?

Situation:
I have a website where users can sign up, creating a "User". After registration, they can then create multiple profiles or "Characters".
I need a way to select a particular number of random users (in this case 12) and then select one of their characters at random.
Current Data Structure:
Users Table - {UserID}
Characters Table - {CharacterID, DisplayName, UserID}
Problem:
Usually I do this kind of stuff via code, but I wanted to approach this in a purely SQL method primarily because I didn't want to hit the code once for the random list of users and then 12 more times for each random character per user.
Eventually I came to the conclusion that this wasn't something that could be done with a single one-line query (if I'm wrong please correct me, I may just not be seeing the trees in the forest here). So I decided to select the 12 random users, loop through them and on each one select a random character for each user.
This seems to work and from what I can tell, it's not horrendous in terms of performance. However... I'm running into a small problem with the returned data. It only returns 12 rows sometimes. Other times it jumps down to 11 rows or 10 rows and I can't for the life of me figure out why it's doing this. Would anyone be able to shed light on this?
Code:
Declare @UserTable TABLE(UserID int)
Insert Into @UserTable Select Top 12 UserID From Users Where ((ABS(CAST( (BINARY_CHECKSUM(*) * RAND()) as int)) % 100) < 10)

Declare @OutputTable TABLE(CharacterID int, CharacterDisplayName nvarchar(MAX), UserID int)

Declare @CurrentUserID int
Select @CurrentUserID = min(UserID) From @UserTable
While @CurrentUserID is not null
Begin
    Insert Into @OutputTable Select Top 1 CharacterID, CharacterDisplayName, UserID FROM CharactersForListing Where UserID = @CurrentUserID Order By NewID()
    Select @CurrentUserID = min(UserID) from @UserTable Where UserID > @CurrentUserID
End

Select * From @OutputTable

A: How about something like this? The main query gets 12 random Users. The correlated cross apply gets 1 randomly selected Character for that User.
select top 12
    u.UserID
    , c.CharacterID
from Users u
cross apply
(
    select top 1 CharacterID
    from Characters ch
    where ch.UserID = u.UserID
    order by newid()
) c
order by NEWID()

A: Where ((ABS(CAST( (BINARY_CHECKSUM(*) * RAND()) as int)) % 100) < 10) is approximately giving you 10% of the table. If you table Users is really small, top 12 * does not guarantee to give you 12 rows.
If you table is small enough, you can change your Insert into query to
Insert Into @UserTable Select Top 12 UserID From Users ORDER BY NEWID()


text:
Q: How to do web testing for ASP.NET MVC views? In ASP.NET WebForms, I've used Selenium to record and run my web and UI tests in a number of projects.
I know we can unit test Controllers and Models in ASP.NET MVC very easily.
What about Views?
Would you also test Views? If not how to make sure the Views, which are rendered by Controller Actions, contain the expected logics and behaviour?
I'd guess the same Web Testing Tools used in WebForms, such as WatiN and Selenium, could also be used here, not sure?
If so, what would be the difference between WebTesting in WebForms and WebTesting in MVC?

A:
What about Views?

Erm, Selenium and WatiN.
Really, what makes you think that ASP.NET MVC views are any different than classic ASP.NET WebForms as far as integration tests are concerned? I mean they all spit HTML at the end of the day. That's what browsers and stuff like Selenium understand. Who spit this HTML is not that much important. What you care about in an integration test is that when a user lambda clicks on a button alpha after entering beta in the gamma text field hi got this Welcome User Phi on the resulting HTML page, don't you? You really don't care about things like ASP.NET MVC or even less about things like ASP.NET MVC Views.
By the way you could use Selenium and WatiN with PHP. Or with Java Servlets if you are a fan of them. Doesn't really matter the server side technology you are using. What matters in an integration test is the scenarios that you have defined previously.

If so, what would be the difference between WebTesting in WebForms and WebTesting in MVC?

None.

A: I think there are differences between ASP.NET MVC and WebForms when it comes to browser driven integration tests, in that the different Server-side aspects of these frameworks lead to different testing approaches.
Take a framework that assists with this, such as Seleno. It uses Selenium under the bonnet but abstracts all browser interaction into C# Page Objects, which you can then use very fluently in C# tests.
There are lots of extensions and conventions which assist with many common browser automation operations, such as clicking on buttons or extracting data from tables.
But why do I bring this up as an answer to this question? Seleno is particularly handy for .NET MVC as the Page Objects can be generic, typed to the ViewModel for a particular View (or Partial View) which creates a strongly typed association when writing a corresponding Page Object for that View.
It is the ViewModel aspect of MVC which opens up this sort of approach; I think it would be trickier to do this with WebForms.


text:
Q: Is there a way to hide/stop some output generated by debug Looking for help to understand why I have the additional output from the debug line below:
- name: Check kernel diff
  become: true
  shell: "sdiff {{ item }}/pre-kernel.out {{ item }}/post-kernel.out | grep '|' | awk -F'|' '{print $2}' | xargs"
  register: "kernel"
  with_items: "{{work_dir}}"
- debug:
    msg: "The system is now running Kernel Version {{ item.stdout }}"
  when: "{{ item.changed == true }}"
  with_items: "{{ kernel.results}}"

The output from msg is correct, but how can I stop/hide all the detail that appears before it:
TASK [patching : debug] ************************
[WARNING]: conditional statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: {{ item.changed == true }}
ok: [test02] => (item={'stderr_lines': [], 'ansible_loop_var': u'item', u'end': u'2020-05-26 16:23:37.068718', u'stderr': u'', u'stdout': u'4.14.35-1902.302.2.el7uek.x86_64', u'changed': True, 'failed': False, u'delta': u'0:00:00.008894', u'cmd': u"sdiff /var/tmp/patching_2020-05-26/pre-kernel.out /var/tmp/patching_2020-05-26/post-kernel.out | grep '|' | awk -F'|' '{print $2}' | xargs", 'item': u'/var/tmp/patching_2020-05-26', u'rc': 0, u'invocation': {u'module_args': {u'warn': True, u'executable': None, u'_uses_shell': True, u'strip_empty_ends': True, u'_raw_params': u"sdiff /var/tmp/patching_2020-05-26/pre-kernel.out /var/tmp/patching_2020-05-26/post-kernel.out | grep '|' | awk -F'|' '{print $2}' | xargs", u'removes': None, u'argv': None, u'creates': None, u'chdir': None, u'stdin_add_newline': True, u'stdin': None}}, 'stdout_lines': [u'4.14.35-1902.302.2.el7uek.x86_64'], u'start': u'2020-05-26 16:23:37.059824'}) => {
    "msg": "The system is now running Kernel Version 4.14.35-1902.302.2.el7uek.x86_64"
}

So it looks more like just:
TASK [patching : debug] ************************
ok: [test02] => {
    "msg": "The system is now running Kernel Version 4.14.35-1902.302.2.el7uek.x86_64"
}

var_file.yml for reference:
---
work_dir:
  - /var/tmp/patching_{{ansible_date_time.date}}

I've been using this as guidance.

A: TL;DR;
Based on your exact example, this should be, your debug task:
- debug:
    msg: "The system is now running Kernel Version {{ item.stdout }}"
  loop: "{{ kernel.results }}"
  when: item.changed
  loop_control:
    label: 'kernel'

Which will output
TASK [debug] *******************************************************************
ok: [local] => (item=kernel) => {
    "msg": "The system is now running Kernel Version 4.14.35-1902.302.2.el7uek.x86_64"
}

You can't reduce it totally, as you want but you can indeed make loops less annoyingly verbose by defining a label in the loop_control attribute.
In this label you can select one of the attributes of your dictionary to be displayed when Ansible loops over it rather than the full dictionary.
- debug:
    msg: "The system is now running Kernel Version {{ item.stdout }}"
  loop:
    - some: foo
      dict: foo
      with: foo
      an: foo
      annoyingly: foo
      long: foo
      list: foo
      of: foo
      attributes: foo
      name: bar
      stdout: bar
  loop_control:
    label: "{{ item.name }}"

This will give a recap looking like this
TASK [debug] *******************************************************************
ok: [local] => (item=bar) => {
    "msg": "The system is now running Kernel Version bar"
}

Versus the cluttered one without loop_control:
TASK [debug] *******************************************************************
ok: [local] => (item={'some': 'foo', 'dict': 'foo', 'with': 'foo', 'an': 'foo', 'annoyingly': 'foo', 'long': 'foo', 'list': 'foo', 'of': 'foo', 'attributes': 'foo', 'name': 'bar', 'stdout': 'bar'}) => {
    "msg": "The system is now running Kernel Version bar"
}

Also, in order to fix your warning, you just need to remove the Jinja curly bracers, as when always assume you are going to pass a Jinja expression.
And testing that something == true is an uneeded extra verbosity too, when: something-that-evaluates-to-true is enough.
So you should use
  when: item.changed

Instead of your actual
  when: "{{ item.changed == true }}"

PS: since Ansible 2.5 loop should be preferred rather than with_items.

A: without "loop_control" ansible code
    - name: 'Print message if CPU utilization become abnormal'
  debug:
    msg:
       - -------------------------------------------------------
       - CPU Utilization = ( 100 - idle time ) = "{{ item.stdout  }}"% is idle
       - -------------------------------------------------------
  #loop:
  with_items:
    - "{{ incidentcpuworknote_cpu }}"
    - "{{ incidentcpuworknote_cpu1 }}"
    - "{{ incidentcpuworknote_cpu2 }}"
  when: item.stdout| int <= 10

Below is the ansible execution result before using the loop_control
TASK [Print message if CPU utilization become abnormal] ******************************************************************************************
ok: [ansiblenode] => (item={u'stderr_lines': [], u'cmd': u"mpstat -u 1 3|tail -1| awk '{print $NF}'\n", u'end': u'2021-04-03 03:37:38.417169', u'stdout': u'0.00', u'changed': True, u'failed': False, u'delta': u'0:00:03.259453', u'stderr': u'', u'rc': 0, u'stdout_lines': [u'0.00'], u'start': u'2021-04-03 03:37:35.157716'}) =>
  msg:
  - '-------------------------------------------------------'
  - CPU Utilization = ( 100 - idle time ) = "0.00"% is idle
  - '-------------------------------------------------------

with "loop_control" ansible code
Note: "loop_control" helped to avoid ansible debug messages while executing the loop
- name: 'Print message if CPU utilization become abnormal'
  debug:
    msg:
       - -------------------------------------------------------
       - CPU Utilization = ( 100 - idle time ) = "{{ item.stdout  }}"% is idle
       - -------------------------------------------------------
  #loop:
  with_items:
    - "{{ incidentcpuworknote_cpu }}"
    - "{{ incidentcpuworknote_cpu1 }}"
    - "{{ incidentcpuworknote_cpu2 }}"
  when: item.stdout| int <= 10
  loop_control:
    label: "{{ item.stdout }}"

Below is the ansible execution result after using the loop_control
TASK [Print message if CPU utilization become abnormal] *****************************************************
ok: [ansiblenode] => (item=0.00) =>
  msg:
  - '-------------------------------------------------------'
  - CPU Utilization = ( 100 - idle time ) = "0.00"% is idle
  - '-------------------------------------------------------'


text:
Q: How can I access an existing AWS database via .PEM file in R? To make a long story short, a former developer have setup a database(MongoDB) at Amazon Web Services(AWS), through EC2. Now to the problem, all I have got thus far is the information in the previous sentence as well as a .PEM file, and I would like to access the database through R, is that possible?
Sorry that I don't have more information at the moment, but I just have no idea where to start.

A: If you have the PEM file you can follow the directions to access the instance here. Now this assumes the instance has a public ip address that is internet reachable with port 22 open.
 If it does not you'll need a vpn setup to reach the private instances.
If you do not have the PEM file you'll need to re-create instance by snapshotting it and creating a new instances based off of that snapshot, with a PEM key you do have access to. Here is the AWS documentation on that process


text:
Q: Могут ли несколько человек выгружать свои проекты на Github? Мое учебное задание - чтобы каждый студент группы свои работы загружал в один репозиторий.
Мне нужно реализовать репозиторий github в который несколько человек будут загружать свои проекты. Нужно чтобы была одна ветка, в которую люди загружают проекты.
Я пытался это реализовать, я загрузил один файл в репозиторий в ветку master, потом дал доступ другому человеку к репозиторию и он в эту же ветку загрузил свой проект, но при этом мой файл удалился.
Во время выгрузки файла, появилась такая ошибка:

Можно ли это сделать как нибудь, чтобы все файлы других людей оставались нетронутыми?

A: *

*Ваше учебное задание, видимо, предполагало формулировку "научиться совместно работать с проектами в git". Или - "научиться совместно работать с проектами в github". Для начала - обратите внимание, что это не одно и то же.

*В гитхаб можно без ограничений совместно работать с публичными проектами, и с некотрыми ограничениями по числу участников - с приватными проектами. При этом у каждого участника должен быть свой экаунт на гитхабе.

*В ошибке, которую Вы привели, есть волшебные слова "forced update", которые на русский перводятся как "перезаписать всё, что было в репозитории, к чёртовой матери, и гори оно всё огнём!". Применять такую бескомпромиссную политику следует осмотрительно и только если она действительно нужна.

*В комментариях Вам правильно написали, что при совместной работе лучше не делать коммиты, а присылать пул - реквесты. Вообще, по гиту и гитхабу есть множество хороших учебных пособий, начиная от Pro GIT, и заканчивая видео на ютьюбе, котрые Вы найдёте  без моей помощи.

*Если быть очень кратким, то план должен быть такой: как создавать репозиторий? как клонировать его к себе? как добавлять файлы для коммита? как коммитить? как пушить? Что такое ветки и как устроена схема работы с несколькими верками проекта? как создавать пулл-реквестыи принимать их? Если с этим немного поразбираться, потратив на каждый из этих вопросов хотя бы по 15 мин - всё станет гораздо понятнее.
ТОгда, если вопросы еще будут, Вы можете дополнить Ваш вопрос, отредактировав его.


text:
Q: Reactive UI Merging Observables to a ObservableAsPropertyHelper I am trying to merge several Observables on a couple of ReactiveLists to create an ObservableAsPropertyHelper.
public class Model : ReactiveObject {
    ReactiveList<int> IngredientsEntities;
    // ...
    public int CostOfIngredients(...) { ... }
}

public class ViewModel : ReactiveObject {

    public Model Promotion;

    private ReactiveList<int> ingredientsQuantities;
    private ObservableAsPropertyHelper<int> cost;

    public Dictionary<..., ...> Ingredients;

    public int Cost {
        get { return cost.Value; }
    }

    public ViewModel() {
        // ...

        var ingredientsObservables = new[]
        {
            ingredientsQuantities.ItemChanged.Select(_ => Unit.Default),
            ingredientsQuantities.ShouldReset.Select(_ => Unit.Default),
            Promotion.IngredientsEntities.ItemChanged.Select(_ => Unit.Default),
            Promotion.IngredientsEntities.ShouldReset.Select(_ => Unit.Default),
        };
        Observable.Merge(ingredientsObservables)
            .Select(_ => promotion.CostOfIngredients(Ingredients))
            .ToProperty(this, x => x.Cost, out cost);

        Observable.Merge(ingredientsObservables)
            .Subscribe(_ =>
            {
                this.Log().Info("Ingredients change detected");
            });

    }
}

The log message fires, but the CostOfIngredients never gets called, and cost remains null. Am I doing something wrong here?
EDIT:
I modified ViewModel and this now works:
public class ViewModel : ReactiveObject {
    private int cost;
    public int Cost {
        get { return cost; }
        set { this.RaiseAndSetIfChanged(ref cost, value); }
    }

    // ...

   public ViewModel() {
        // ...
        var ingredientsObservables = new[]
            {
                ingredientsQuantities.ItemChanged.Select(_ => Unit.Default),
                ingredientsQuantities.ShouldReset.Select(_ => Unit.Default),
                Promotion.IngredientsEntities.ItemChanged.Select(_ => Unit.Default),
                Promotion.IngredientsEntities.ShouldReset.Select(_ => Unit.Default),
            };
            Observable.Merge(ingredientsObservables)
                .Subscribe(_ => Cost = promotion.CostOfIngredients(Ingredients));

   }
}

My understanding is that Select(_ => Unit.Default) creates an Observable for Unit.Default that never changes, thus never invoking any further Selects.

A: I think your problem is your use of ItemChanged - this only fires if you have item tracking enabled, and only when an item in your collection changes (i.e. myList[3].SomeProperty = "bar";). You probably want Changed, which will cover everything.


text:
Q: Deploy ContentType with DocumentTemplate First of all I created a few test columns...
Secondly I created a new content type (derived from Document).
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <ContentType ID="0x0101000F16F9EDC2D547C48480B02B918168DD" Name="MyDocContentType1" Group="Custom Content Types" Description="My Document Content Type 1" Inherits="TRUE" Version="0">
    <FieldRefs>
      <FieldRef ID="{d17ecdc8-991a-4efc-a758-bbb522dd2f62}" DisplayName="My Test Column 1" Required="FALSE" Name="MyTestColumn1" />
      <FieldRef ID="{8e9ef300-b566-4939-8b3c-760e13afb6d5}" DisplayName="My Test Column 2" Required="FALSE" Name="MyTestColumn2" />
    </FieldRefs>
    <DocumentTemplate TargetName="~site/_cts/MyDocContentType1/MyDocumentTemplate1.dotx" />
  </ContentType>
</Elements>

Next I created a module deploying my word 2013 template file (.dotx) to /_cts//MyCustomTemplate1.dotx
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="DocumentTemplates" RootWebOnly="TRUE" Url="_cts/MyDocContentType1">
    <File Path="DocumentTemplates\MyDocumentTemplate1.dotx" Url="MyDocumentTemplate1.dotx" Type="Ghostable" />
  </Module>
</Elements>

Adding the content type to a library enables the document template...
E.g. when I create a new item of "MyDocContentType1" it opens up Word 2013.
However the document template is not correctly bound to the server - the document information panel doesn't appear and I cannot add any quick parts refering to sharepoint content type columns.
It does work when I assign the document template via the SharePoint Web UI.
Any ideas?
Edit: The word template (.dotx) is already aware of the SharePoint columns. In a previous step I assigned the DocumentTemplate manually (to design the word template). Now that the .dotx template is feature complete I want to deploy it as part of a SharePoint solution (for example to a newly created site collection).
Edit: Of course it works using a programmatic approach assigning the DocumentTemplate property via feature event receiver. That's not the solution I am looking for. Declarative only.
To me it looks like a bug. If I go to the content type, edit/update the document template (updating - not uploading a new one!) and create a new document from that content type it starts to work... ?!

A: I am going to assume that you created your *.dotx file directly in word and added it to Visual Studio.
The reason why it doesn't work is that the dotx file needs to have references to the SharePoint fields encoded in the Word file itself.
I would suggest to:

*

*Deploy your content type without any document template

*Add the content type to a document library

*Edit the newly created list content type (inside the document library) and upload a blank empty *.dotx template: now SharePoint will create a copy of your dotx file, add all the content type columns, and save the new dotx file in the Forms/ folder in your document library ; After this, you have a blank dotx file with the correct associations - test it by adding a new document in your document library with your content type and check the information panel

*Open the document library in SharePoint Manager (or with SharePoint Designer, or navigate to the Forms/ folder) and download the SharePoint-generated dotx file

*Customize this dotx file to your needs

*Delete the document library and retract your wsp package

*add the final dotx to your solution and your content type just like you did before


text:
Q: how do i make a loop to display the next 3 even number? hello all i'm trying to make javascript to display an evens numbers by using a form with start number and number of evens to display. user will enter starting number and enter the number of even to display.
say start at 7 number of evens is 3 should display 8 10 12.  just need some direction. thanks
my code:

<title>evens</title>

Enter Number

           <form name="number" class="form-inline">

            Starting Number
            <input type="text" id="starting" class="form-control">

               numbers of evens
               <input type="text" id="step" class="form-control">

           <button type="button" onclick="evenDisplay()" class="btn" >submit</button>

Enter Number

       <form name="number" class="form-inline">

        Starting Number
        <input type="text" id="starting" class="form-control">

           numbers of evens
           <input type="text" id="step" class="form-control">

       <button type="button" onclick="evenDisplay()" class="btn" >submit</button>
</form>

A: You had several bugs in your code. I think i fixed it:
function evenDisplay() {

    var starting = parseInt(document.getElementById("starting").value);
    var step = parseInt(document.getElementById("step").value);
    var evens = [];

    for (i = starting+(starting%2), j=0;  j <step; i+=2, j++) {
        evens.push(i);
    }
    console.log(evens);
}

window.onload = function(){
  document.getElementById("btn").onclick = evenDisplay;
}

CodePen
You need to add id="btn" to your button for this to work.
Btw definind event handlers in HTML is highly discouraged.

A:

function evenDisplay() {

    var starting = parseInt(document.getElementById("starting").value);
    var step = parseInt(document.getElementById("step").value);
    if(!isNaN(starting)&&!isNaN(step)){
    var evens = [];
    var x=(step*2)+starting;
    for (i = starting+1;  i <=x; i++) { /* this loop would show as much as evens number as long value of i<= set to  and doesn't care if the user enter the number of evens */
        i % 2 || evens.push(i);
    }
   console.log(evens);
}

else{console.log("Nan");}
}

Enter Number

           <form name="number" class="form-inline">

            Starting Number
            <input type="text" id="starting" class="form-control">

               numbers of evens
               <input type="text" id="step" class="form-control">

           <button type="button" onclick="javascript:evenDisplay();" class="btn" >submit</button>

Here I use the equation =(step*2)+starting to loop with in the required range also I check if isNaN for the input values


text:
Q: Setting max x and y values for Swift I was trying to put a random number generator in my code today and I was going to use the maximum x and y values for it.
Here is a snippet of my code:
var rand_x = CGFloat(arc4random_uniform(maxXValue))
var rand_y = CGFloat(arc4random_uniform(maxYValue))

But I continue to get the error message:
Use of unresolved identifier 'maxXValue'
Use of unresolved identifier 'maxYValue'
Any tips to fix this problem? Thanks!

A: If you don't specify what are your maxXValue and maxYValue it won't work, these values don't exist by default.
Define them as follows :
let maxXValue: UInt32 = 200
let maxYValue: UInt32 = 200

Obviously these values are examples and you have to choose them yourself.


text:
Q: how to autostart php-fpm on mac i wanna install the nginx and php on my mac(Yosemite10.10.5).but the php-fpm can't autostart when i restart the mac.
step1,install nginx by brew
===>success, i can visit the http://localhost/index.html
step2,set the nginx service autostart as follow
sudo chown root:wheel/usr/local/opt/nginx/bin/nginx
sudo chmod u+s/usr/local/opt/nginx/bin/nginx
mkdir -p ~/Library/LaunchAgents
cp /usr/local/opt/nginx/homebrew.mxcl.nginx.plist ~/Library/LaunchAgents/

step3,test the autostart func,see the pic.
===>success
step4,install php5.4 by brew
===>success
step4,set the php54 autostart as follow
sudo chown root:wheel /usr/local/opt/php54/sbin/php-fpm
sudo chmod u+s /usr/local/opt/php54/sbin/php-fpm
cp /usr/local/opt/php54/homebrew.mxcl.php54.plist ~/Library/LaunchAgets

step5,test the autostart funcs
===>failed,and nothing happened.see the pic.
step6,i guess that's the permission problem,so i typed as follow and success.
sudo launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.php54.plist

so, i did the step4 as nginx to avoid the permission problem, but the result is failed. any help will be appreciate.
pic


text:
Q: Samba vs. NFS: Performance I've got a choice of setting up Samba or NFS on my Linux based NAS ( nslu2 running OpenDebian ).

*

*Does anyone have performance related stories comparing the two options ? Are there tuneup tricks that improve transfer speeds for one or the other ?

*What options do I have in terms of toolkits/test suites to gather performance metrics on my setup ?

The nslu2 isn't the most powerful NAS ( 266Mhz ARM processor, 32 MB RAM ) so the overhead of running the Samba or NFS daemon is a factor too. Also, I'm looking at this purely from a performance standpoint, i.e. security issues surrounding NFS aren't my concern.

A: The main benefit I can think of to use SAMBA is that is supports SMB file shares to windows boxes.  If you want to connect to this with only a another unix box, then NFS will likely perform better.

A: NFS isn't great but Samba will definitely be slower, the only advantage is to allow Windows clients. Unless Windows machines are an issue go with NFS.

A: I don't have the numbers anymore, but NFS trounced Samba in performance when I did my big head to head comparison/benchmarking series.  And on high speed and/or high latency links, using NFS over TCP outperformed NFS over UDP.  Apparently at some point windowing becomes more important than simple packets.

A: Go with NFS - if you are using Vista or 7 Clients install Services for Unix and you'll be able to access NFS exports via Windows machines using microsofts NFS clients.

A: Hello fellow NSLU2 user. I would definitely go for NFS, unless there were some compelling reasons (namely Windows machines). NFS is more light-weight and faster.
As for the NSLU2 side, you will find that tweaking the NFS options and choosing the right filesystem for the shared disk are important. I have chosen ext3 but then switched to ext2 as it seemed to consume less of the precious resources. When using wireless don't expect extraordinary performance and don't use too big block size, otherwise go for huge blocks.
In either case there are some parameters to tweak. Do some benchmarks on your own and decide which options are the best (TCP/UDP, rsize, wsize, etc) for example for NFS here is some old comparison:
NSLU2 NFS
Last but not least - it would be nice to see your results - to learn from them ;)


text:
Q: Polyglossia difference between "\text{...}" and "\begin{} ... \end{}" Beside the syntax, are there any other differences and use cases
when one should use \text<lang>{...} vs \begin{<lang>} ... \end{<lang>} to
select another language, i.e., insert snippets of text written in
another language?
The documentation only stipulates longer pieces
of text in favor for the environment syntax.
PS. It was my original understanding that the environment syntax
started a new line before inserting the text, but a quick test proved
me wrong.

A: They're not the same. With \text<language>{text} you're doing \foreignlanguage{<language>}{text}, whereas \begin{<language>} is the same as \begin{otherlanguage}{<language>}
The environment form also changes the tags, which is not the case with the command form, as seen in the following example; dates are changed by both forms.
\documentclass{article}
\usepackage{polyglossia}
\setmainlanguage{english}
\setotherlanguage{italian}

\begin{document}

Nothing: \chaptername\ \today

\texttt{\string\textitalian}: \textitalian{\chaptername\ \today}

Environment:

\begin{italian}
\chaptername\ \today
\end{italian}

\end{document}

In the .aux file you'll find
\select@language {english}
\select@language {italian}
\select@language {english}

(among other things); the first is written at the start, the second is caused by \begin{italian} and the third by \end{italian}. Usage of \textitalian won't make such an annotation.


text:
Q: What is the least ordinal than cannot be embedded in $\mathbb{R}^\mathbb{R}$? Let $\mathbb{R}^\mathbb{R}$ be the set of functions $\mathbb{R}\to\mathbb{R}$ patially ordered by eventual domination. Obviously, every ordinal below $\omega_1$ can be embedded in $\mathbb{R}^\mathbb{R}$ using only constant functions.
What is the least ordinal than cannot be embedded in $\mathbb{R}^\mathbb{R}$?

A: One can define an eventually increasing sequence $\{f_\alpha:\alpha<\omega_1\}$ by transfinite recursion on $\alpha$. By inserting sequences in the intervals $(f_\alpha(x),f_{\alpha+1}(x))$ we can see that $\omega_1$-sums (and of course, $\omega$-sums) do not lead out of the representable ordinals. This gives that all ordinals $<\omega_2$ are representable and this is clearly sharp if CH holds, by Will's above answer.
If CH fails, larger ordinals can be represented, if, e.g. Martin's Axiom holds.

A: Let me get things started with some simple observations.
Note that given any countable sequence of functions $f_n$, we can
by diagonalization construct a function eventually dominating all
of them, $f(x)=\max_{n\leq x}f_n(x)$. It follows that we may by
transfinite recursion construct an embedding of $\omega_1$ into
your order: at successor stages, add one to the previous function;
at limit stages, use the diagonalization just described.
So actually, since $\mathbb{R}$ is order-isomorphic to bounded
intervals of itself, we can therefore also embed $\omega_1$ into
the order many times, on top of one another. So this gives
strictly larger ordinals mapping in.
More generally, the bounding number $\mathfrak{b}$ is the size
of the smallest unbounded family of functions, and any family of
size less than $\mathfrak{b}$ will be bounded above. Thus, the
recursive construction actually shows that we can find an
embedding of $\mathfrak{b}$ into $\mathbb{N}^{\mathbb{N}}$ under
eventual domination. Thus, we also get strictly larger ordinals
than $\mathfrak{b}$ embedding in, by using the bounded-interval trick again.
There are diverse independence results concerning the exact
value of $\mathfrak{b}$. Under CH, it is the same as the
continuum, of course, but when CH fails, it can be far larger than
$\omega_1$.
Using Péter's idea, once we have a map from $\mathfrak{b}$ into the order, then we may conclude that the class of ordinals that map into the order is closed under sums of length $\mathfrak{b}$. Thus, any ordinal up to $\mathfrak{b}^+$ is is order-embeddable into $\mathbb{R}^\mathbb{R}$ under eventual domination. So $\mathfrak{b}^+$ is a lower bound for your desired ordinal.
I guess the same idea shows that whenever an ordinal $\kappa$ embeds in, then the class of ordinals will be closed under sums of length $\kappa$, and so all ordinals up to $\kappa^+$ will also map in. Thus, the smallest ordinal not embedding in must be a cardinal, and furthermore, it must be a regular cardinal for the same reason.
Update.  It is relatively consistent that the answer is $\mathfrak{c}^+$, even when the continuum $\mathfrak{c}$ is very large, and much larger than $\mathfrak{b}$. The reason is that by forcing, we can undertake a very long forcing iteration of length $\kappa$ to add a dominating real at each stage, and thereby get a model with continuum $\kappa$, such that $\kappa$ embeds into the order (and so the smallest ordinal not embedding into the order is $\kappa^+$). Now, the point is that with further ccc forcing, we can make $\mathfrak{b}$ small or whatever we like, but meanwhile, we still have our old functions showing that $\kappa$ maps into the order.


text:
Q: I used uDraper plugins in source edition UE5,tips build through you IDE I used Draper in Source Edition UE5(release version UE4.24 and UE5.0.3 works correctly ), operated 1,2, and 3 according to ReadMe in the installation path, and also replaced BuildId. However, when I opened the project tips :  build through you IDE
I get an error when I don't follow the README:
enter image description here
ReadMe Info:
uDraper plugin is distributed in a binary form (without source code).
There where some undocumented but well known ways to achieve this without breaking the build of C++ projects in UE4.
But in UE5 it seems not to be the case anymore (there are plenty of complaints about this issue on the Internet).
At this point we can suggest a somwhat hacky way to make your C++ projects work properly in the presence of uDraper plugin:

*

*Copy UnrealBuildTool.DraperHook.* files into [UE5 Root]\Engine\Binaries\DotNET\UnrealBuildTool

*Replace "UnrealBuildTool.exe" with "UnrealBuildTool.DraperHook.dll" in [UE5 Root]\Engine\Build\BatchFiles\Build.bat

*replace "UnrealBuildTool.exe" with "UnrealBuildTool.DraperHook.exe" in [UE5 Root]\Engine\Config\BaseEngine.ini ("UnrealBuildTool" value under "PlatformPaths" section)

It's still a work in progress so we hope to find a better solution in the future.
Regarding custom Engine builds we expect that the binary distribution of the uDraper plugin should be compatible as long as ABI didn't change.
Just replace "BuildId" in Draper\Binaries\Win64\UnrealEditor.modules to your "CompatibleChangelist" from [UE5 Root]\Engine\Build\Build.version
step 1:
enter image description here
step 2:   The original file says "UnrealBuildTool.dll" not "UnrealBuildTool.exe"
enter image description here
step 3:
enter image description here
The above modification is still the error of FIG. 1
step 4:
enter image description here
open project
enter image description here
I opened the project with VS and compiled it successfully, and opened it again with the same erro.Previously, the plug-in was placed in the project path to open the project promptFailed to generate Projiect files,

A: We try to keep uDraper plugin up to date with official UE releases and do not attempt to support custom builds from GitHub.
The instructions you're referring to might be helpful but we do not guarantee that it will work with any GitHub version.
You can try to find an earlier UE version on GitHub to better match an officially released version and try it out.


text:
Q: Tcp and receiving order I'm preparing an exam and I stumbled upon kind of interesting question. Basically what happens when for whatever reason the receiver receives the packets in reverse order?
For example I have a window of size 2 and I send packet 2 and 3 but 3 arrives faster than 2.
I'm not quite sure about the answer so I'll ask here.
Does the receiver sends a duplicate ack upon arrival of 3 and then ack2 upon arrival of 2?
And then, what happens to the transmission window?


text:
Q: 'Circular dependency dropped` with ASM files when building with make The problem is that when I build my project, make gives annoying messages about circular dependencies with ASM files. What's strange, the message isn't shown for C files compiled in the very same way. Here is the Makefile:
# VV4OS Makefile. Here are the main targets:
# I.   all (can be called without specifying the target) - builds everything
# II.  install - copies the kernel to a disk image.
# III. clean - removes the files that are created by this build system
# and thus can be recovered.
# You can set up the build system by changing the build constants.

# Here come build constants.
# If you can't build VV4OS consider changing them.

# Used tools.

MAKE=make

MOUNT=mount
UMOUNT=umount

SUDO=sudo

# I don't know if there are systems where RM, CP or MKDIR command isn't standard.
# I've added them just in case.

RM=rm
RMFLAGS=-f

CP=cp
CPFLAGS=

MKDIR=mkdir
MKDIRFLAGS=-p

# Compilers (and the linker) and their flags.

ASM=nasm
ASMFLAGS=-felf32

CC=/home/alexander/opt/cross/bin/i686-elf-gcc
CFLAGS=-Wall -Wextra -Werror -ffreestanding -std=c11 -c -Iinclude

LINKER=/home/alexander/opt/cross/bin/i686-elf-gcc
LFLAGS=-ffreestanding -nostdlib -lgcc -T linker.ld

# Files.

SOURCES=$(wildcard *.c) $(wildcard */*.c) $(wildcard */*/*.c) \
    $(wildcard *.asm) $(wildcard */*.asm) $(wildcard */*/*.asm)

OBJECTS=$(SOURCES:=.o)

KERNEL=kernel.elf

DISK_IMG=disk.img
IMG_OFFSET=1048576 # Where the partition starts in bytes (NOT in sectors)
IMG_MNTDIR=/mnt/

# Destination paths.

KERNEL_DEST_PATH=/sys/vv4os/
KERNEL_DEST_NAME=kernel.elf

# These targets are executed whenever they called even if there are ready files with their names.

.PHONY: all install clean

# Here comes the build system code.
# Do not modify it unless your IQ level is higher than 110.

# Build everything (currently only the kernel).
# You can simply call make if you want to do it.

all:
    $(MAKE) $(KERNEL)

# Installs the kernel to a disk image.

install: $(KERNEL) $(DISK_IMG)
    $(MOUNT) -o loop,offset=$(IMG_OFFSET) $(DISK_IMG) $(IMG_MNTDIR)
    $(MKDIR) $(MKDIRFLAGS) $(IMG_MNTDIR)/$(KERNEL_DEST_PATH)
    $(CP) $(KERNEL) $(IMG_MNTDIR)/$(KERNEL_DEST_PATH)/$(KERNEL_DEST_NAME)
    $(UMOUNT) $(IMG_MNTDIR)

# Only builds the kernel.

$(KERNEL): $(OBJECTS)
    $(LINKER) $(LFLAGS) -o $@ $^

# Assemblies assembly files with assembler.

%.asm.o: %.asm
    $(ASM) $(ASMFLAGS) $< -o $@

# Compiles C files with compiler.

%.c.o: %.c
    $(CC) $(CFLAGS) $< -o $@

# Removes all the files that are created by make (and thus can be recovered).

clean:
    $(RM) $(RMFLAGS) $(OBJECTS) $(KERNEL)

And here is the build log:
$ make
make kernel.elf
make[1]: Entering directory '/home/alexander/Documents/vv4os'
/home/alexander/opt/cross/bin/i686-elf-gcc -Wall -Wextra -Werror -ffreestanding -std=c11 -c -Iinclude io/term.c -o io/term.c.o
/home/alexander/opt/cross/bin/i686-elf-gcc -Wall -Wextra -Werror -ffreestanding -std=c11 -c -Iinclude io/keyboard.c -o io/keyboard.c.o
/home/alexander/opt/cross/bin/i686-elf-gcc -Wall -Wextra -Werror -ffreestanding -std=c11 -c -Iinclude hdd/hdd.c -o hdd/hdd.c.o
/home/alexander/opt/cross/bin/i686-elf-gcc -Wall -Wextra -Werror -ffreestanding -std=c11 -c -Iinclude hdd/mbr.c -o hdd/mbr.c.o
/home/alexander/opt/cross/bin/i686-elf-gcc -Wall -Wextra -Werror -ffreestanding -std=c11 -c -Iinclude libc/stdlib.c -o libc/stdlib.c.o
/home/alexander/opt/cross/bin/i686-elf-gcc -Wall -Wextra -Werror -ffreestanding -std=c11 -c -Iinclude libc/string.c -o libc/string.c.o
/home/alexander/opt/cross/bin/i686-elf-gcc -Wall -Wextra -Werror -ffreestanding -std=c11 -c -Iinclude libc/stdio.c -o libc/stdio.c.o
/home/alexander/opt/cross/bin/i686-elf-gcc -Wall -Wextra -Werror -ffreestanding -std=c11 -c -Iinclude isr/isr.c -o isr/isr.c.o
/home/alexander/opt/cross/bin/i686-elf-gcc -Wall -Wextra -Werror -ffreestanding -std=c11 -c -Iinclude isr/descriptor_tables.c -o isr/descriptor_tables.c.o
/home/alexander/opt/cross/bin/i686-elf-gcc -Wall -Wextra -Werror -ffreestanding -std=c11 -c -Iinclude isr/timer.c -o isr/timer.c.o
/home/alexander/opt/cross/bin/i686-elf-gcc -Wall -Wextra -Werror -ffreestanding -std=c11 -c -Iinclude general/system.c -o general/system.c.o
/home/alexander/opt/cross/bin/i686-elf-gcc -Wall -Wextra -Werror -ffreestanding -std=c11 -c -Iinclude general/kernel.c -o general/kernel.c.o
make[1]: Circular boot/boot.asm <- boot/boot.asm.o dependency dropped.
nasm -felf32 boot/boot.asm -o boot/boot.asm.o
make[1]: Circular isr/interrupts.asm <- isr/interrupts.asm.o dependency dropped.
nasm -felf32 isr/interrupts.asm -o isr/interrupts.asm.o
/home/alexander/opt/cross/bin/i686-elf-gcc -ffreestanding -nostdlib -lgcc -T linker.ld -o kernel.elf io/term.c.o io/keyboard.c.o hdd/hdd.c.o hdd/mbr.c.o libc/stdlib.c.o libc/string.c.o libc/stdio.c.o isr/isr.c.o isr/descriptor_tables.c.o isr/timer.c.o general/system.c.o general/kernel.c.o boot/boot.asm.o isr/interrupts.asm.o
make[1]: Leaving directory '/home/alexander/Documents/vv4os'

What could be the problem?
UPD:
It always gives such a message when a target like
file.asm.o: file.asm
    nasm file.asm -o file.asm.o

is executed where file.asm is any assembly file (it works with an empty one).

A: The problem is that your .asm files match the builtin %: %.o rule. This rule lets you type make foo to create an executable named foo from foo.o similar to how you can use the same command to build an executable from a file named foo.c. To prevent it from matching this rule you need create an implicit rule that matches .asm files:
%.asm:

You don't need this for your .c files because there's already a builtin %.c: rule.


text:
Q: fancybox - navigating back and forward I'm using fancybox's ajax method to open content that itself contains a link that opens another modal in it's place. This all works fine.
My question is how can I add a "Back" functionality so that when a Back link is clicked in the currently open modal it opens the previously open modal. In this case the first modal opened?
Code so far:
$("a.trans").fancybox({
    ajax : {
        type            : "POST",
        data            : 'mydata=test'
    },
    'padding'           : 0,
    'overlayColor'      : '#333',
    'overlayOpacity'    : 0.2
});

$("a#additional_trans").fancybox({
    ajax : {
        type            : "POST",
        data            : 'mydata=test'
    },
    'padding'           : 0,
    'overlayColor'      : '#333',
    'autoDimensions'    : false,
    'titleShow'         : true,
    'titlePosition'     : 'outside',
    'title'             : 'Transact Online',
    'width'             : '633',
    'height'            : 'auto',
    'overlayOpacity'    : 0.2
});

$("#modal_back_btn").live('click', function() {
  // Not sure what to put here if indeed this is the correct place
  // It needs to open $("a.trans").fancybox()
});

A: You should be able to accomplish this by
$.fancybox.prev();

However, you could also do a
$.fancybox.close();
$("a.trans").fancybox();

inside of your click handler.


text:
Q: Decomposition of positive semi-definite matrices I know that any positive semi-definite matrix $A$ can be written as $A = B^T B$. My question is that if we know that $A = B^TB = C^TC$, then is there any relation with $B$ and $C$? I know that it is possible that $B \neq C$ for example:
\begin{equation}
\begin{bmatrix}
1 &0 \\0 &1
\end{bmatrix}\begin{bmatrix}
1 &0 \\0 &1
\end{bmatrix} = \begin{bmatrix}
-1 &0 \\0 &-1
\end{bmatrix}\begin{bmatrix}
-1 &0 \\0 &-1
\end{bmatrix}.
\end{equation}
Thanks,

A: If $A=B^TB$ take any orthogonal matrix $P$ such that $P^TP=PP^T=I$ then if $C=PB$ one has
$$C^TC=B^TP^TPB=B^TB=A$$
Now assume we have two matrices such that $A=B^TB=C^TC$. If A is definite positive $B$ and $C$ are invertible and we have $B=\left(B^{-1}\right)^TC^TC$. Write $P=\left(B^{-1}\right)^TC^T$ and compute
$$PP^T=\left(B^{-1}\right)^TC^TCB^{-1}$$
If $B$ and $C$ are not invertible use density property of invertible matrices to get to the same result.

A: Let $B,C$ be $m\times n$ matrices. If $B^*B=C^*C$ $(=A)$ then the SVD of $B$ and $C$ are related as
$$
B=U_1\Sigma V^*,\qquad C=U_2\Sigma V^*
$$
that is, they share the matrices $V$ (with the columns being the normalized eigenvectors of $A$) and $\Sigma$ (with $\Sigma^*\Sigma$ being the diagonal form of $A$). It gives immediately that
$$
C=U_2\Sigma V^*=U_2U_1^*U_1\Sigma V^*=U_2U_1^*B=WB
$$
where $W$ is unitary.
P.S. It is straightforward to generalize the relation to the case when $C$ has more rows than $B$, but $W$ will be a rectangular matrix with $W^*W=I$.


text:
Q: Creating Associative Array in PHP I have a multidimensional array.
$shop = array(
              array("appn1", "pub1" ,"pub2" , "pub3"),
              array("appn2", "pub1"),
              array("appn3", "pub1" ,"pub2")
            );

The first item in each array is application number and the rest in each array are the publication numbers. I get the first item(application number) and the last item of each array(latest publication number) like this
 $index = count(array_keys($shop));
    for($i=0;$i<$index;$i++){

        $appln_nr = $shop[$i][0];
        echo $appln_nr;

        $publn_nr_index = count(array_keys($shop[$i]))-1;
        $publn_nr = $shop[$i][$publn_nr_index];
        echo $publn_nr;
   }

Now I have application number and publication number for each inner array.
I want to create an associative array from the application numbers and publication numbers.
where the key should be the application number and its value is the publication number.
Thanks
EDIT
What I am getting from $shop array
 Array
 (
  [0] => Array
    (
        [0] => appn1
        [1] => pub1
        [2] => pub2
        [3] => pub3
    )

  [1] => Array
    (
        [0] => appn2
        [1] => pub1
    )

  [2] => Array
    (
        [0] => appn3
        [1] => pub1
        [2] => pub2
    )
)

And this is what I need in my associative array
Array(
    "appn1" => "pub3"
    "appn2" => "pub1"
    "appn3" => "pub2"
)

A: Finally i understood what you wanted, after your edit XD:
$shop = array(
    array("appn1", "pub1" ,"pub2" , "pub3"),
    array("appn2", "pub1"),
    array("appn3", "pub1" ,"pub2")
);
$shopNew = array();

foreach($shop as $value){
    $shopNew[$value[0]] = end($value);
}

// now if you want you can replace $shop and unset $shopNew
$shop = $shopNew;
unset($shopNew);

print_r($shop);

the output is this:
Array (
  [appn1] => pub3
  [appn2] => pub1
  [appn3] => pub2
)

A: You can easily convert your array into a new format by using the first element as key (see reset) and the last element (see end) as value:
foreach($shop as $fl) {
    $v[reset($fl)] = end($fl);
}

Result is in $v then.
If you want to transform the array you need to delete each element as well:
foreach($shop as $v => $fl) {
    $shop[reset($fl)] = end($fl);
    unset($shop[$v]);
}

Result is in $shop then. Unset takes care of removing from the array.
Output in both cases is:
array(3) {
  'appn1' =>
  string(4) "pub3"
  'appn2' =>
  string(4) "pub1"
  'appn3' =>
  string(4) "pub2"
}

A: You can try
$shop = array(
        array("appn1","pub1","pub2","pub3"),
        array("appn2","pub1"),
        array("appn3","pub1","pub2")
        );

$final = array();
array_map(function ($var) use(&$final) {$final[reset($var)] = end($var);}, $shop);
var_dump($final);

Output
array
  'appn1' => string 'pub3' (length=4)
  'appn2' => string 'pub1' (length=4)
  'appn3' => string 'pub2' (length=4)

A: try this:
 foreach($shop as $k => $v) {
     $new_arr[$v[0]] = end($v);
 }

It should give you this result,
$new_arr = array(
      "appn1" => "pub3",
      "appn2" => "pub1",
      "appn3" => "pub2"-
);

A: You can also create like this,
$arrField = [];
$arrField['id'] = '0001';
$arrField["first_name"] ='Demo Test';
print_r($arrField);

print_r($arrField) display output like this.
Array ( [id] => 0001 [first_name] => Demo Test )


text:
Q: Multiple API Gateway instances, one lambda function I am trying to build a system where multiple APIs gateway instances should execute the same lambda function.
My problem is that I would like to change only the lambda configuration in function of the API gateway used.
Let's take the name of a database as an example that should change if the lambda is being triggered from one API or the other.
Example:
API Gateways:
https://my-first-api-gateway.execute-api.eu-west-1.amazonaws.com
https://my-second-api-gateway.execute-api.eu-west-1.amazonaws.com

I then have one lambda function being called by the two APIs: say_hello.
This function has to retrieve a quote from a database. If the function has been called from my-first-api-gateway the lambda function has to use my_first_database and if the function has been called from my-second-api-gateway, it has to use my_second_database.
The only solution I came with is to deploy as many lambda functions as I have API Gateways. And then use environment variables to store my database name.
I don't like my solution because when I update a single line of code I'll have to redeploy all of my lambda functions.. (if I have 300 different databases to use, that would mean to update 300 lambda functions at once..)
Thank you for your ideas on this subject!

A: If you use a Lambda-Proxy integration you should be fine.
Full details of the event can be found here, however critically the headers Host, origin and Referer all point the the API Gateway uri:
"headers": {
  "Host": "j3ap25j034.execute-api.eu-west-2.amazonaws.com",
  "origin": "https://j3ap25j034.execute-api.eu-west-2.amazonaws.com",
  "Referer": "https://j3ap25j034.execute-api.eu-west-2.amazonaws.com/dev/"
}

Therefore it should be fairly trivial for you to branch/look-up your database behaviour from this information.


text:
Q: Html.TextBoxFor set value I use <input type="file" id="fileId" name="fileId"/> and
        <% = Html.TextBoxFor (x => x.FileName, new {@ class = "className", maxlength = 255, id = "fileName"})%> in my mvc project. I want to save in a text box the file name selected in the INPUT element. How can I do this?

A: You need to use javascript to achieve this. Here's an example with jquery:
$(function() {
    $('#fileId').change(function() {
        // When the user selects a file, read the selected filename
        // and set it to the textbox
        var filename = $(this).val();
        $('#fileName').val(filename);
    });
});


text:
Q: Trouble adding Images into a Gui using tkinter OK so i am trying to make a program that displays an image when pressing a button, and i am having trouble getting the images into the program
this is my full code:
# Nicolas Bart
import tkinter as tk
from PIL import Image, ImageTk

from tkinter import *

window = tk.Tk()
window.title('Bad Meme Generator')
window.geometry('500x500')
window.configure(bg='saddle brown')

meme_label = tk.Label(window, text='PRESS BUTTON FOR BAD MEMES:',
fg='blue4', bg='brown4', font=('comicsans', '20'))
meme_label.grid(pady=25, padx=25, column=0, row=0)

def button_command():
    meme_window = tk.Tk()
    meme_window.title('I Warned You')
    meme_window.grid()

image = Image.open('pexels-photo-247932.jpg')
photo = ImageTk.PhotoImage(image)

label = tk.Label(meme_window, image=photo)
label.image = photo
label.place(x = 0, y = 0)

button = tk.Button(window, text='Dont Do It!', command=button_command,
padx=100, pady=75, font=('comicsans', '20'),
               bg='brown4', fg='blue4')
button.grid(column=0, row=1)

warning_label = tk.Label(window, text="Really shit tier memes incoming:",
bg='brown4', fg='blue4',
                         font=('comicsans', '20'))
warning_label.grid(pady=75)

window.mainloop()

every time i run this program, when i press the button to open the image, it gives the error "AttributeError: type object 'Image' has no attribute 'open'"
the specific part of the program that is giving the error is:
def button_command():
    meme_window = tk.Tk()
    meme_window.title('I Warned You')
    meme_window.grid()

    image = Image.open('pexels-photo-247932.jpg')
    photo = ImageTk.PhotoImage(image)

    label = tk.Label(meme_window, image=photo)
    label.image = photo
    label.place(x = 0, y = 0)

any help would be appreciated. Thank you :)

A: This is a good example of why you shouldn't do from tkinter import *. Tkinter has an Image class, so by doing this import after importing Image from PIL you overwrite the PIL class with the tkinter class.
Since you're already importing tkinter the preferred way (import tkinter as tk), you don't need to import tkinter a second time. You need to remove the statement from tkinter import *.
You also make the mistake of creating more than one instance of Tk. I don't know if it contributes to the problem or not, but it's not something you should be doing. If you need additional windows then you should create instances of Toplevel.


text:
Q: Firebase security rule not working on CollectionGroup I have this security rule code
  match /{path=**}/favorited/{userUID} {
  allow create, update, read: if request.auth.uid == userUID;
}

And this is the error message I got

W/Firestore( 6236): (21.3.0) [Firestore]: Listen for Query( collectionGroup=favorited where userUID == abcdefghijklmnopqrstuvwxyz and favorite == true order by -updatedAt, -name) failed: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}

The Query I used is
  Firestore.instance.collectionGroup('favorited')
    .where('userUID', isEqualTo: user.uid)
    .where('favorite', isEqualTo: true)
    .orderBy('updatedAt', descending: true).snapshots()

I can't figure out which part of security rule for collectionGroup went wrong.
Query code worked fine when there was no security rule.
What am I missing here?

A: Your Query:
Firestore.instance.collectionGroup('favorited')
    .where('userUID', isEqualTo: user.uid)
    .where('favorite', isEqualTo: true)
    .orderBy('updatedAt', descending: true).snapshots()

...is looking for any documents (unknown Id's) that have a field {userUID: value} where the value equals user.uid, but your security rule:
match /{path=**}/favorited/{userUID} {
  allow create, update, read: if request.auth.uid == userUID;

is specifically looking for document(s) with the Id of request.auth.uid.
Remembering that Security Rules are not filters, have you created your documents such that each document with Id {value} also has a field {userUID: value} ?
The query has to do the filtering; the Security Rule ensures that only Queries whose results ALL pass the rule will succeed. If the query can result in a whose Id is NOT the same as the field {userUID: value} it will be rejected.