text:
Q: How can i lazyload a table while the user have the ability to search data in it? So i have a huge amount of data to load in a table , maybe thousands of rows and i am fetching the data from an API.
Now i have the obvious problem that the DOM will take so much time to render.
I googled about lazy-loading and i'am thinking it may be a solution but i'am not sure because the user can search the data (front-end search), so i'am afraid that would not be possible if the data is not even rendered in the DOM.
I am asking for a javascript solution even if i have to use a library or so.
Thank you!

A: You've got a couple of options here:

*

*Do the search on the back-end if possible

*Load the data into a Javascript array only, then just render a small section of it at a time, and search the array.

It seems unlikely you'll need a library, searching the contents of an array of data should be straightforward.
Edit
Okay, if putting search functionality on the back-end is impossible it's still fairly easy to store and search thousands of rows of a table in-browser. The below working example generates 10000 rows of random data and shows up to 15 of them that match the user's search. Adding pagination should not be challenging. In the final loop, page one is values of j < 15. So for page 2 print rows where 15 ≤ j < 30, for page 3 print when 30 ≤ j < 45, etc.
The important thing for memory consumption is to not store all your data in the DOM and just hide the rows the user shouldn't see. In this example there are only ever 15
 elements in the DOM, all the data is stored in an array and only the user's current view is rendered.

const data = [];
const table = document.querySelector('table');
const input = document.querySelector('input');

function printRow(row) {
  // in reality you have to escape data for HTML, this is just a quick demo
  table.insertAdjacentHTML('beforeend', `<tr><td>${row.id}</td><td>${row.r}</td><td>${row.s}</td>`);
}

// Generate dummy data
for (let i = 0; i < 10000; i++) {
  data.push({'id': i,
    'r': Math.random().toString(36),
    's': Math.random().toString(36)});
}

// Display first page of data
for (let i = 0; i < 15; i++) {
  printRow(data[i]);
}

input.addEventListener('input', e => {
  table.innerHTML = '';
  for (let i = 0, j = 0; i < data.length & j < 15; i++) {
    if (data[i].r.indexOf(input.value) >= 0 || data[i].s.indexOf(input.value) >= 0) {
      printRow(data[i]);
      j++;
    }
  }
});
<input>


text:
Q: input() problem jupyter notebook and other website I'm working on a website called NOWCODER, similar to the Leetcode but a Chinese version.
One of the question is asking for user to input some text(multiple lines) and determine whether the texts that enter are qualified as an appropriate password.
What bothers me is the input()
so I write my code on Jupyter notebook (python 3) as:
# 1st Code

s = [] # get all the input text
while True:
    try:
        lines = input()
        if lines:
            s.append(lines)
        else:
            break

the code works fine in jupyter nootbook but when i copied it to the nowcoder website it doesn't work, it said "no input and output data"
so i modified the code to the following:
# 2nd Code

s = []
while True:
    try:
        s.append(input())
    except:
        break

and it works
The problem is now I tried to execute the 2nd Code in the Jupyter notebook, the while loop never ends and keeps asking for input. I don't know how to fix it or where is the problem.
Also i try re.stdin.readline() and it doenst work on jupyter nootbook, so I want to know if there is some way to make it executable on both the NOWCODER website as well as on the Jupyter notebook

A: The second code is fine, you just need to send an end-of-file signal (EOF), which you can do on Unix/Linux with Ctrl+D and on Windows with Ctrl+Z. Python receives this as an EOFError, which your except clause will catch and break the loop. However, a bare except is bad practice. You should at least change it to except Exception.
That said, you could simplify massively by using fileinput.input to take input.
import fileinput
s = [s.rstrip('\n') for s in fileinput.input()]

redpajama_set_name: RedPajamaStackExchange


text:
Q: how can i concat first_name and last_name two different database fields to assign to drop down list in cakephp using 'list' in find statement $swimmer = $this->Swimmer->find('list', array(
    'conditions' => array('Swimmer.group' => $this->data['Swimmer']['group_id']),
    'order' => array('Swimmer.first_name ASC'),
    'fields' => 'Swimmer.first_name'
));

A: First of all, setup a virtual field in your Swimmer model as suggested by Ann Pham. eg:
var $virtualFields = array(
    'name' => "CONCAT(Swimmer.first_name, ' ', Swimmer.last_name)"
);

Then, fetch the data for your dropdown list like so: (assuming Swimmers controller)
$this->Swimmer->find('list', array('fields' => array('Swimmer.id', 'Swimmer.name')));

You could also try doing this in your SwimmerModel:  var $displayName = 'Swimmer.name'; (not 100% sure if this would work). If it does work, you won't need the 'fields' array in the find.

A: An another approach is to concat the field on the fly in the fields list.
Ex:
$swimmer = $this->Swimmer->find('list',
array(
    'conditions' => array(
        'Swimmer.group' => $this->data['Swimmer']['group_id']),
    'order' => array(
        'Swimmer.first_name ASC'
    ),
    'fields' => 'CONCAT(Swimmer.first_name, " ", Swimmer.first_name) AS full_name'
));

A: http://book.cakephp.org/view/1588/virtualFields


text:
Q: Передача данных в переменную PHP после выполнения JS скрипта Есть скрипт который ищет инфу на своей же странице по классу, и заменяет содержимое.
Например:
тест

Скрипт ищет класс test и заменяет слово тест на какое то рандомное. Какое - неизвестно, слово подставляется только после загрузки страницы. Вот как после загрузки страницы передать новое слово в переменную php? Сам пхп код находится в другом месте, ему можно дать ссылку на страницу где это слово меняется и выводится. Пробовал через XMLHttpRequest, но не очень понимаю принцип работы, как должен выглядеть PHP файл.
Через simple_html_dom он естественно хавает только первоначальное слово.
Какие еще есть варианты?


text:
Q: How to add a  within a  At the moment I have:
<form>
    <fieldset>
        <legend>Personal Info</legend>

                Info

    </fieldset>
</form>

But the legend title 'Personal Info' appears above the line and NOT in the middle of the line.
Can someone please tell me what I am doing wrong?
I get this instead:
__________Personal Info__________

A: Apply a style to your legend tag e.g.
<legend style="position:absolute; left:50%;">Personal Info</legend>

A: Got it! :) I just had to adjust the height on the  maybe due to me using twitter bootstrap there was some conflict with the bootstrap css styles for the  property.


text:
Q: Angular ng-repeat not show empty object attributes I am trying to loop through using the data below in angular ng-repeat
{

    "qid": "173995X306X4091",
    "gid": null,
    "comments": "Milestone1: Here is the milestone1details",
    "owner": "Me",
    "targetdate": "28-10-2016"

},
{

    "qid": "173995X306X4101",
    "gid": null,
    "comments": "",
    "owner": "",
    "targetdate": ""
}

HTML:

            Milestone
            Milestone Owner
            Milestone Target date

            {{milestone.comments  }}
            {{milestone.owner  }}
            {{milestone.targetdate  }}

I don't want the empty attributes to show :
like the below for second object

            Milestone
            Milestone Owner
            Milestone Target date

How can I do this?
Thanks

A: Just add a condition in the tr as following:

Alternatively, you can also use ng-show instead of ng-if. Both will not display the row the only difference is that ng-if will remove that empty row from the DOM while the ng-show will hide that row using a CSS class.
Edit: Also, I suggest you moving your ng-repeat condition to the tr itself (if you do not have specific requirement). See a working example below:

var app = angular.module("sa", []);

app.controller("FooController", function($scope) {

  $scope.milestones = [{

    "qid": "173995X306X4091",
    "gid": null,
    "comments": "Milestone1: Here is the milestone1details",
    "owner": "Me",
    "targetdate": "28-10-2016"

  }, {

    "qid": "173995X306X4101",
    "gid": null,
    "comments": "",
    "owner": "",
    "targetdate": ""
  }];
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

        Milestone
        Milestone Owner
        Milestone Target date

        {{milestone.comments }}
        {{milestone.owner }}
        {{milestone.targetdate }}

Like @Ved commented/answered, if there are space between quotes, you can also modify your query like this:

There will not be any error if any of the value is undefined/null.

A: You can have a look at the following plunkr
https://plnkr.co/edit/BplBjwxISICLVV3nQzD9?p=preview

        {{milestone.comments }}
        {{milestone.owner }}
        {{milestone.targetdate }}

A: Use ng-if. This should be sufficient:

A: I more addition as the above answer will fail if any filed have empty space between like quotes " "
{

    "qid": "173995X306X4101",
    "gid": null,
    "comments": "",
    "owner": " ",
    "targetdate": " "
}

so better to use trim().

        {{milestone.comments }}
        {{milestone.owner }}
        {{milestone.targetdate }}

A: Using ng-show:

            Milestone
            Milestone Owner
            Milestone Target date

            {{milestone.comments  }}
            {{milestone.owner  }}
            {{milestone.targetdate  }}

You can also use a default value:
{{milestone.owner || "No Owner"}}


text:
Q: Apache Flume (twitter) I am a beginner so kindly bear with me. I need to download twitter logs and would like to use Flume. However, I am not familiar with Java. Can Python be use with the Flume Agent ? Any links that I could refer to will be very helpful.
thanks!

A: As far as I know, you don't need to code anything but properly configure Flume with already developed stuff ;)
Please, refer to this link. I followed it some time ago in order to capture certain twits into my HDFS. If any question with the details, I can help you based on my own experience with such a link.


text:
Q: jQuery - Initially click button twice to increase/decrease div height I've seen a number of similar posts but still can't pin-point the issue in my simple code. I'm sure it's a simple solution/reason it's doing this..
The idea is for the div to increase in height too 100% of the content, or decrease in height back to the original 150px, based on toggling from button click (variable $status_on_button). Initial height as you can see in the jQuery is set to 150px.
I have to click the button twice INITIALLY to fire the first condition. Thereafter it works as it's supposed to. If it's at all relevant, the jQuery code is entered into a wordpress plugin which has worked well in the past. My code as follows:
HTML:
<div id="aboutus_container" style="overflow:hidden;">
  <!--some html elements/paragraphs here-->
</div>

<button class="btn btn-default" id="aboutus_readmore_button">Read more...</button>

jQuery:
jQuery(document).ready(function($) {

  // initialise toggle variable to zero and 'aboutus_container' div height
  $status_on_button = 0;
  $('#aboutus_container').css('height', '150px');

  //button click
  $('#aboutus_readmore_button').click(function(){
    if ($status_on_button==0) {
      $('#aboutus_container').animate({height:'150px'}, 500);
      $status_on_button = 1; //toggle button status
    } else {
      $('#aboutus_container').animate({height:'100%'}, 500);
      $status_on_button = 0; //toggle button status
    }
  });

});

This is probably going to be an "aha" moment with the answer and probably staring me in the face. Thank you.

A: Ahhh, it just dawned on me. I have to swop the height 100% line and the height 150px line. It must do the 100% height first or it's setting the initial height a second time on first click, which shows no change in div.. eureka. Typing this post helped. I'll leave it here for others that may find it useful.
Here is the corrected jQuery code:
jQuery(document).ready(function($) {

  // initialise toggle variable to zero and 'aboutus_container' div height
  $status_on_button = 0;
  $('#aboutus_container').css('height', '150px');

  //button click
  $('#aboutus_readmore_button').click(function(){
    if ($status_on_button==0) {
      $('#aboutus_container').animate({height:'100%'}, 500);
      $status_on_button = 1; //toggle button status
    } else {
      $('#aboutus_container').animate({height:'150px'}, 500);
      $status_on_button = 0; //toggle button status
    }
  });

});

For clarification, these two lines were swopped:
$('#aboutus_container').animate({height:'100%'}, 500);

$('#aboutus_container').animate({height:'150px'}, 500);

A: I'm not a jQuery expert (not by a long-shot!) but it looks like you set your variable to '0' and then set the height to 150px and then within the function you're checking if the status variable == 0 (which it is on the first iteration!) and so you're setting it to 150px AGAIN on the first click.  Looks like just a logic problem!
Again, I'm no jQuery expert, but I might do it a bit differently - first get the current height of the aboutus_container when you trigger the function with the button click.  For example (pseudocode, because I don't know the jQuery syntax off the top of my head):
if(#aboutus_container(height) == 150px) {
     [make it 100%]
}
else {
     [make it 150px]
}


text:
Q: How do you change the Excel StatusBar message using Office.js? I am trying to figure out how to change the status message in excel using the office.js Excel Add-in.  I wouldnt think this would be too hard but cant seem to find it.

A: This cannot be done programmatically with Office.js. One potential alternative is to pop a toast on your add-in itself. We have a helper function you can use and looks like:

async function run() {
    await Excel.run(async (context) => {

        OfficeHelpers.UI.notify("Whatever text you need");

        await context.sync();
    });
}

Please also upvote/create a new request in our https://officespdev.uservoice.com/


text:
Q: How do I implement autocomplete in C# and SQL Server and is it worth it? So here's an example of what I'm trying to do. Lets assume I'm making a soccer game submitting program and I have a few fields that I'm supposed to fill, 2 of which I want autocomplete on. One textBox for the Home Team and one textBox for the Away Team.
Here is an simplified example of what the database table would look like:
-----------------------------
|  home_team  |  away_team  |
-----------------------------
|  Chelsea FC |   Arsenal   |
|  Liverpool  |  Norwich FC |
|  Man. City  |   Everton   |
|  Tottenham  | Stoke City  |

I want the program to load suggestions or results checking every team in the table when I type something in any of the two textBoxes. This is to make typing the correct team names easier and faster based on former submissions.
How would this be done?
Also, if I do this, would it be too much of a strain on the database and getting worse with every next submission? Because it seems as though it would have to check the whole of the "home_team" and "away_team" columns with every letter I type into one of the textBoxes.
This is with Windows Forms.

A: You'll definitly want to get all of your Data and Fields when the Form is loaded. Executing a request everytime you type a letter is a bad idea.
Once you have all of your fields, simply put them in a list and there are AutoComplete propreties to your Textbox.
Set the Auto Complete Mode and the Auto Complete Source and you're done!
Check this example out, it's very simple!
Auto Complete TextBox in C#


text:
Q: error 404 after removing public/index.html I just wantet to test a simple rails app on my new VPS-Server with Ubuntu 12.04, Apache and PhusionPassenger.
Everything works fine with the default index.html file in the public directory.
But if I remove this file and try to render files from the view-directory I get and 404 Error.
On my local machine everything works...
I thought, maybe it has something to do with the asset pipeline, so i tried "rake assets:precompile" but it didn't help.
Edit: I have set the correct root path, with action and method.

A: Maybe you have not set root_path in your app. You can set it like this :root => "controller_name#action_name".

A: I found the solution for my problem:
Logfiles showed "application.css isn't precompiled".
instead of: rake assets:precompile I used bundle exec rake assets:precompile and now it works fine!

A: The index.html file is the default substitute for your root url.
So when you removed it, then there is no route that handles the root url (/).
To set the root URL (/), any of these routes will do:
root :to => 'controller#action'
root => 'controller#action'
get '/' => 'controller#action'


text:
Q: How can I set up a local mail server and forward external email to another? I would like to set up an email server, using Redhat 7.6, let's call it mail.domain.tld. The box is realm-joined to that domain. I want to create email addresses for domain users, for example fred@mail.domain.tld, (note that I do want the mail hostname to be there, because fred@domain.tld is already in use by the domain).
I want this server to handle all email for domain users, and forward any emails that are bound for other domains (Gmail for example) to a separate email server, let's call it big-mail.domain.tld. This separate server already exists and is configured.
I wish the emails themselves to be stored on mail.domain.tld, and users can access them remotely from other boxes with Thunderbird via imap and smtp.
Is such an arrangement even possible? Is it possible using Postfix and Dovecot? I have been trying to follow many tutorials, but I am unfamiliar with the exact terminology to look for, and my use case seems to be somewhat unusual. This is the way I want it to work, because big-mail.domain.tld is not under my control, nor is the Active Directory domain controller itself.
EDIT: I forgot to say, I want the users to be able to authenticate with the mail server using their domain credentials.

A: Your question is too broad to answer in our Q&A format!
The steps that are needed are roughly:

*

*Configure the server to support Active Directory authentication / integration. That is already a topic in itself with several options on how to achieve that: https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/windows_integration_guide/index

*Once that works configure Postfix to accept incoming mail for your domain and to allow authenticated users to relay (send) email using your postfix server. See http://www.postfix.org/SASL_README.html
Configure postfix to use a relayhost to not send outgoing messages directly over the internet to their recipients, but to hand them over to next hop (smarthost, mail relay, outgoing SMTP server) for subsequent delivery.

*Install dovecot so that users can login using IMAP and/or POP3. Since your system is already integrated with AD by now, you probably don't need to create virtual users you can probably suffice by using "pam" authentication.
Don't forget to get an TLS certificate and secure your services with that, you don't want your users to send passwords to your services in clear-text!


text:
Q: how to implement animation on shake effect in iphone? I have implemented one simple application for iphone.now i want to implement some animation.
Example:i have selected one photo from the photo library.Then i want to animate selected portion from the photo using shake effect.
I have seen lots of application in apple store.But i dont know how to implement this functionality.

A: Maybe you are referring to the "wobble" effect? See how to create iphone's wobbling icon effect?


text:
Q: How to store video in my created directory using download manager in android version 10 or 10+ I have write android:requestLegacyExternalStorage="true" in manifest  tag.
Also i have added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

both permission in manifest file.
Also .java code for download is
 public void download(int position)
    {
        Toast.makeText(mContext, "Downloading start..", Toast.LENGTH_SHORT).show();
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(videoItems.get(position).VideoUrl));
        request.setDescription("Downloading..");
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);
        request.setTitle(videoItems.get(position).VideoName);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        {
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        }
        request.setDestinationInExternalPublicDir("/bgm bingo" ,videoItems.get(position).VideoName+".mp4");
        manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        id = manager.enqueue(request);
        mContext.registerReceiver(onDownloadComplete,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

Still i not able to store my video in my created app folder.
This code perfect run android version 9 or less but when android version is 10 or 10+ then this code will not work. so how to solve it. please give me solution.


text:
Q: Test if directory exists based on filename I'm aware of the PHP file_exists function, & is_dir.
I saw about a month ago, a process where you can test BOTH in one search. But I can't find it now.

$file = "/directory/dir2/dir3/filename";

Is there a command based on the filename only - to test if the DIRECTORY exists? (without using 2-3 lines of code)
If the directory does not exist - mkdir (recursive). But if the directory does exist, there's no need to use MKDIR.
I can't find it in the mkdir information
Ps: I do know the mkdir recursive function.

A: Not sure there's a good way of doing this in a particularly short block of code - but you'd struggle to get a more resilient solution than Phazei's recursive directory creation on:
Create a folder if it doesn't already exist

A: if (!is_dir(foldername with path)) {
  mkdir();

}


text:
Q: Working UDP Receive program suddenly fails with: The underlying connection was closed: An unexpected error occurred on a send For months and months my UDP Receive app has worked flawlessly. It receives a message on a specified port and sends out another message to a .php application that updates a database. It no longer can send the message to the web program.
It was working fine up until today.
The command that fails is:
var stream = client.OpenRead(url);

Was there a .NET or Windows 10 upgrade that would cause this to fail?
I checked the url parameter and the web program is working just fine.
How do I fix this?


text:
Q: Within IAM, can I restrict a group of users to access/launch/terminate only certain EC2 AMIs or instances? What the title says.
Within the master AWS account, I have several personal accounts, i.e. AWS Identity and Access Management (IAM) users. I would like to assign certain IAM users to groups and prevent them from terminating certain Amazon EC2 instances, de-registering certain Amazon Machine Images (AMIs), etc.
I don't mind if they're playing with their own stuff, but I don't want them to touch my stuff.
Is that possible?

A: Update
AWS has just announced Resource-Level Permissions for Amazon EC2 and Amazon RDS to address this long standing shortcoming of IAM support within EC2 and RDS (in comparison to other AWS services, see my original answer below for details/background):

Today we are making IAM even more powerful with the introduction of resource-level permissions for Amazon EC2 and Amazon RDS. [...]
On the EC2 side, you can now construct and use IAM policies to control
  access to EC2 instances, EBS volumes, images, and Elastic IP
  addresses. [...]
Here are just a few of things that you can do:

*

*Allow users to act on a limited set of resources within a larger, multi-user EC2 environment.

*Set different permissions for "development" and "test" resources.

*Control which users can terminate which instances.

*Require additional security measures, such as MFA authentication, when acting on certain resources.

This solves a plethora of security complications and enables quite a few new use cases as well.
Furthermore, EC2 policy statements can include reference to tags on EC2 resources, which allows to use the same tagging model and schema for permissions and for billing reports. Finally, there's an expanded set of condition tags [...] including ec2:Region, ec2:Owner, and ec2:InstanceType, see Condition Keys for Amazon EC2 for details.
Solution
Here's a variation of Example 3: Allow users to stop and start only particular instances for the use case at hand, which allows users to start and stop [and terminate] only the instances that have the tag "department=dev":
{
   "Version": "2012-10-17",
   "Statement": [{
      "Effect": "Allow",
      "Action": [
        "ec2:StopInstances",
        "ec2:StartInstances",
        "ec2:TeminateInstances"
      ],
      "Resource": "arn:aws:ec2:us-east-1:123456789012:instance/*",
      "Condition": {
        "StringEquals": {
          "ec2:ResourceTag/department": "dev"
        }
      }
    }
   ]
}

Caveat
Support for resource-level permissions is restricted to the following set of actions on the indicated resources still, which excludes parts of the use case (e.g. de-registering AMIs) - the confidence in the foundation for this complex and far-reaching feature  is apparently high enough though to announce that they plan to add support for additional APIs throughout the rest of 2013 (AWS doesn't usually publish any roadmaps):

*

*Instances - Reboot, Start, Stop, Terminate.

*EBS Volumes - Attach, Delete, Detach.

Original Answer
I'm afraid this isn't possible the way you'd like to do it (and many others for that matter, including myself).
Problem
You want to restrict access to a particular service's resources rather than its actions - while AWS Identity and Access Management (IAM) supports both in principle, not every AWS product/service offers restrictions based on resources yet; unfortunately Amazon EC2 is one of these and even featured as an example for this very difference, see Integrating with Other AWS Products:

The following table summarizes whether you can grant IAM permissions
  that control access to a service's actions, resources, or both. For
  example, you can use IAM to control which Amazon EC2 actions users
  have access to, but you can't use IAM to control users' access to
  AMIs, volumes, instances, etc. [emphasis mine]

(Partial) Workaround
Depending on the needs of the other accounts, you might still be able to at least limit their ability to perform those actions considered destructive - you can explore the available actions via the AWS Policy Generator, for example:

*

*ec2:DeregisterImage - obvious effect, when denied for a user/group

*ec2:ModifyInstanceAttribute - this would help via Enabling Termination Protection for an Instance, when denied for a user/group:

By default, you can terminate any instances you launch. If you want to
  prevent accidental termination of the instance, you can enable
  termination protection for the instance.

That is, once you've enabled termination protection, anyone without permission to use ec2:ModifyInstanceAttribute cannot terminate these instances at all.
Obviously the respectively restricted accounts won't be able to facilitate those calls for their own resources anymore.
Furthermore this won't prevent them from running a fancy Cluster Compute Eight Extra Large Instance or so, incurring respective costs in turn ;)
Alternative Approach
Depending on your setup/environment you might want to look into Consolidated Billing instead, which essentially provides a way to gather one or many AWS accounts under another one, which is paying for the resources used by the others.
While this is primarily an accounting feature, it can be used to separate areas of concern as well - for example, it's quite common to facilitate separate development and production accounts to achieve respectively independent operation, not the least regarding IAM rights and the like.
The introductory blog post New AWS Feature: Consolidated Billing provides a good overview, and here is the relevant topic from the AWS Consolidated Billing Guide regarding your apparent use case:

The paying account is billed for all costs of the linked accounts.
  However, each linked account is completely independent in every other
  way (signing up for services, accessing resources, using AWS Premium
  Support, etc.). The paying account owner cannot access data belonging
  to the linked account owners (e.g., their files in Amazon S3). Each
  account owner uses their own AWS credentials to access their resources
  (e.g., their own AWS Secret Access Key). [emphasis mine]

Obviously this functionality is targeted at larger customers, but depending on your scenario you might be able to come up with a solution to separate your AWS accounts and resources as needed still.


text:
Q: Google maps to Open Street map I have a directory test site in which I've added Google maps and I have some poi into map....But the problem is that my api key as free shows the map without restrictions just one time. After that google map shows a message that is only for development use...Is there any way without pay to have Google map free use for many page visitors? Or the only solution is to use alternative maps like open Street and so on? What alternative is easier in coding to change Google maps? If you have an descriptive example, will help me....

A: You can create your own mapserver and do updates and everything around it by your own. Please provide some more informations.
Please be aware that the Open Streetmap Database is free, the Open Street map API Server is not. There are some limitation for using that Service in your application.
Also there are several other Providers on the Market that might be interresting for you.
https://www.mapbox.com/


text:
Q: How to Achieve Expressive Dynamic Array Sorting in Swift As a discipline to just learn the Swift way of doing things I try avoid as much typecasting to NSWhatevers as possible, however, there are times like these where doing so is quite frustrating.
I have a table view controller with sortable headers for columns of data. The data I use is an array of objects. I want to sort the array by the field names in those objects. If the user taps the same column header button again, the sort order is reversed which means I have to keep track of the current sort direction for each field/column.
In Objective-C/NSArray APIs, it was pretty simple to do this dynamically. You just use an NSSortDescriptor with sortedArrayUsingDescriptors on NSArray passing it the field/column name and the sort order and you got back what you need.
In Swift however, you cannot pass the field name dynamically as a string. Instead you have to specify explicitly which field you want to use which means you either have to setup a verbose switch or if/else construct or you have to define a dictionary that takes your sort field as the key and a closure as the value. The closure then is what gets passed to your sort function. I set this up in a playground just to see what I could figure out going with the dictionary/closure lookup route. Here's what I came up with using some dummy objects:
class Order {
    var orderNumber:String
    var invoiceNumber:String
    var orderDate:NSDate

    init(orderNumber:String, invoiceNumber:String, orderDate:NSDate) {
        self.orderNumber = orderNumber
        self.invoiceNumber = invoiceNumber
        self.orderDate = orderDate
    }
}

I instantiate a few of them in an array like this:
var orders = [Order(orderNumber: "123456", invoiceNumber: "2342342", orderDate: NSDate()),
    Order(orderNumber: "332422", invoiceNumber: "848484", orderDate: NSDate()),
    Order(orderNumber: "423425", invoiceNumber: "488244", orderDate: NSDate())]

Then I create my lookup dictionary that provides the closure I want to sort with:
var sorters = [
    "orderNumber" :
        [true : { (o1: Order, o2: Order) -> Bool in return o1.orderNumber < o2.orderNumber },
        false : { (o1: Order, o2: Order) -> Bool in return o1.orderNumber > o2.orderNumber }],
    "invoiceNumber" :
        [true : { (o1: Order, o2: Order) -> Bool in return o1.invoiceNumber < o2.invoiceNumber },
            false : { (o1: Order, o2: Order) -> Bool in return o1.invoiceNumber > o2.invoiceNumber }],
    "orderDate" :
        [true : { (o1: Order, o2: Order) -> Bool in return o1.orderDate < o2.orderDate },
            false : { (o1: Order, o2: Order) -> Bool in return o1.orderDate > o2.orderDate }]
]

You're probably wondering what gives with the true and false keys. This is to determine whether it should be sorted ascending (true) or descending (false). You can see how this plays out when I go to actually run the sort:
var currentSortField = "invoiceNumber"
var ascending = false

orders.sort(sorters[currentSortField]![ascending]!)

Note: I had to also overload the greater than and less than operators for NSDate to get the comparison to work in the "orderDate" field:
func >(lhs:NSDate, rhs:NSDate) -> Bool {
    return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
}

func <(lhs:NSDate, rhs:NSDate) -> Bool {
    return lhs.compare(rhs) == NSComparisonResult.OrderedDescending
}

The background on this question I realize is a bit long, however, I am just a bit befuddled that Swift doesn't appear to have a more elegant solution for solving this problem and wanted to provide the complete solution I've come up with to date. Remember, the NSWhatever equivalent in this case is a one liner:
var sorted = (orders as NSArray).sortedArrayUsingDescriptors([NSSortDescriptor(key: currentSortField, ascending: ascending)])

So here's the question. Is there a more succinct, expressive, and idiomatic way to do this in Swift without resorting to Foundation APIs?
If you want to try out the playground I created to test this, you can get it here: https://www.dropbox.com/s/8m53bprzui50muq/Sorting.playground.zip?dl=0
UPDATE After a discussion with Matt in the comments, I went ahead and implemented a sorting closure that compromises by using valueForKey: after making my Order object inherit from NSObject. It is a compromise, but it keeps me from completely abandoning the Swift sort function altogether and yet I don't have to type a boat ton of code. It goes like this:
var currentSortField = "invoiceNumber"
var ascending = false

var sorter = { (o1: Order, o2: Order) -> Bool in
    if ascending {
        return (o1.valueForKey(currentSortField) as String) < (o2.valueForKey(currentSortField) as String)

    } else {
        return (o1.valueForKey(currentSortField) as String) > (o2.valueForKey(currentSortField) as String)

    }
}

orders.sort(sorter)

It's no one-liner, but it's an interesting compromise.
UPDATE TO THE UPDATE
That's actually not going to work unless all of the vars are strings--which they are not. This dies on o1.valueForKey(currentSortField) as String when the field in question is an NSDate and not a String.

A: It isn't clear to me what kind of answer would satisfy you. Personally I think your solution is a good one. A more simple-minded version, for those having trouble following what you're doing, would be something like this:
struct Thing {
    var first:String
    var last:String
}
var arr = [Thing]()
arr.append(Thing(first:"Al", last:"Zork"))
arr.append(Thing(first:"Zelda", last:"Aardvark"))

var howToSort: ((Thing, Thing) -> Bool)

func sorter(thing1:Thing, thing2:Thing) -> Bool {
    return thing1.first < thing2.first
}
howToSort = sorter
let arr2 = sorted(arr, howToSort)

func sorter2(thing1:Thing, thing2:Thing) -> Bool {
    return thing1.last < thing2.last
}
howToSort = sorter2
let arr3 = sorted(arr, howToSort)

The point is simply that things like sorter and sorter2 are things that can be stored and retrieved. And that's what saving the sort criteria depends on.
Now, it's also true that sorter and sorter2 can't be formed dynamically, the way an NSSortDescriptor can, or applied dynamically and type-agnostically, the way KVC is doing when you sort using a sort descriptor. But Swift, as I said in my comment, is a language that deliberately lacks eval ("don't be eval!"), introspection, dynamic message formation (no performSelector), and type-agnosticism. You can generalize your solution somewhat using a generic, I suppose, but the real issue seems to me to be that you're now addicted to the "power" of those things and you want to go cold-turkey on them without actually giving them up. My job, as I see it, is to talk you off the ledge.
Of course, my real response to your question is: Hey, Objective-C and NSSortDescriptor are not going away, so what's the big deal?

A: Try this solution. It works and the shortest way
var array = [6,3,2,1,5,4]

Sort (ascending) its elements
array = array.sort { $0 < $1 }
print(array)
result is  [1, 2, 3, 4, 5, 6]


text:
Q: How to create an external list of javascript files At the bottom of several of my website, I have a list of javascript/css reference files, such as
<link rel="stylesheet" href="http://domain.co.uk/general.css" />
<script src="http://domain.co.uk/jquery-3.2.1.min.js"></script>
<script src="http://domain.co.uk/jquery-ui.min.js"></script>
<script src="http://domain.co.uk/helpers.js"></script>

They all point to another website I have. This works as I only need to update the content of the files and since they all point to the same file location updates are easy.
The problem I have is, if I want to add a new file (javascript or css) then I have to add a new <script... or <link... to every website which has this list.
What I'd love to do is move that list into an external file, and reference it there.
EG
Website1
<link rel="stylesheets" href="http://domain.co.uk/myCssFiles.css" />
<script src = "http://domain.co.uk/javascriptFiles.js"> </script>

Website2
<link rel="stylesheets" href="http://domain.co.uk/myCssFiles.css" />
<script src = "http://domain.co.uk/javascriptFiles.js"> </script>

And as such, the content of myCssFiles.cs could be
<link rel="stylesheet" href="http://domain.co.uk/general.css" />
<link rel="stylesheet" href="http://domain.co.uk/general2.css" />
<link rel="stylesheet" href="http://domain.co.uk/general3.css" />

and likewise for the javascript.
How can I achieve this?
Please note, I control these websites and CORS isn't an issue.

A: Hope this helps,
You can have common.js to include all your js file
common.js
var scripts = {
"http://domain.co.uk/jquery-3.2.1.min.js",
"http://domain.co.uk/jquery-ui.min.js"
}

scripts.forEach(function(data) {
    var x = document.createElement('script');
    x.src = data;
    document.getElementsByTagName("body")[0].appendChild(x);
});

You can have a single common.js file and add links as u needed to the scripts array. You just have to include the common.js in your websites.


text:
Q: Query For All Constraints in a SQL Database Diagram Is there a way to show constraints in a SQL Server db diagram?
Like for example, in a card number, it shows there is a CHECK constraint etc..

A: In SSMS, if you expand the tree of tables for your database, then expand the Columns folder, the icon next to a column will be a silver/gray key if it's part of a foreign key relationship, but unfortunately it won't show you the column to which column it's mapped.
You could also create a new diagram in SSMS by right-clicking the "Database Diagrams" folder underneath your database in the tree and choosing "New Database Diagram." You will get lines between the tables where foreign keys exists.
You could also use third-party tools to reverse engineer a diagram from your DB schema, like Microsoft Visio or Sparx Enterprise Architect.
I'm not sure SSMS Express supports these things, so you might be out of luck with anything fancy/visual.


text:
Q: SPARQL getting an intersecting set I following data:
:A :hasCity City1
:A :hasCity City2
:A :hasCity City3
:A :hasCity City4

:K :hasCity City1
:K :hasCity City2

......
I'm trying to find all subjects that have cities 1 and 2 so I wrote the query:
select ?s
{
   ?s :hasCity ?city.
   FILTER (?city =:City1 && ?city=:City2)
}

But, I don't get back any results.
if I just do:
select ?s
{
   ?s :hasCity ?city.
   FILTER (?city =:City1)
}

I get back A,K,Q,M and if I just do:
select ?s
{
   ?s :hasCity ?city.
   FILTER (?city =:City2)
}

I get back A,K,L
so when I use the  && operator, I should get back A&K, right? Am I missing something?

A: What you need to do is ask for all subjects that share the same set of objects, using a triple pattern on the same property. You'd end up with a very simple query:
SELECT ?s {?s :hasCity :City1, :City2}

With :hasSubject, if you want to keep the one-line query, you just ask for the inverse of the property:
SELECT ?s { ?s ^:hasSubject :City1, :City2}

When using = , you need to ensure you compare apples with apples. For example ?a = ?b, or str(?a) = str(<b>).


text:
Q: How to Learn Noncommutative Geometry This is a more direct, and precise question of a previous one that I have deleted.
Obligatory Information/Background
I am currently a first-year undergraduate studying at a frequented Mathematical Institute in the United States. I am well versed in "basic" mathematics, I.e linear algebra, groups, etc…, and I have recently been reading ahead, in the form of Yau's "Lectures on Differential Geometry" and certain Mathematical Physics papers, and I decided that I want to do research in Noncommutative Geometry due to the appeal of the work/questions Connes is engaging with this very field. I also wish to "truly" read and understand the work by Yau and other differential Geometers due to their importance in Mathematical Physics. This leads me to my next problem and first question for you all.
Where does one begin?
So far, I believe I should read through the "Rudin Trifecta" which is a coined name for Rudin's Mathematical Analysis, Real (Measures) Analysis, and Functional Analysis book. This is in order to approach Noncommutative Geometry, which largely draws ideas from measure theory.
While doing so, I wish to learn more about Algebraic Topology due to its intrinsic link to Electromagnetism and other theories such as TQFT. Considering I already know a fair bit of Abstract Algebra, I'd hope after finishing some topology I am capable of approaching Peter May's 2-Volume Concise Algebraic Topology course.
Now, I also wish to learn Differential Geometry due to its prolific nature in math phys (Calabi-Yau, Einstein, Kahler).
As you can see I want to learn a lot, but I have limited time, so is this really a good route for myself as someone interested in Math Phys on the Geometric side of things? You can likely guess my interests based on the things I have said thus far. If someone can point out some flaws in my plan, or point me in a direction far more efficient than my naive route, that would be largely appreciated.


text:
Q: using awk to do exact match in a file i'm just wondering how can we use awk to do exact matches.
for eg
$ cal 09 09 2009
   September 2009
Su Mo Tu We Th Fr Sa
   1  2  3  4  5
6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

$ cal 09 09 2009 | awk '{day="9"; col=index($0,day); print col }'
17
0
0
11
20
0
8
0

As you can see the above command outputs the index number of all the lines that contain the string/number "9", is there a way to make awk output index number in only the 4th line of cal output above.???  may be an even more elegant solution?
I'm using awk to get the day name using the cal command. here's the whole line of code:
     $ dayOfWeek=$(cal $day $month $year | awk '{day='$day'; split("Sunday Monday Tuesday Wednesday Thursday Friday Saturday", array); column=index($o,day); dow=int((column+2)/3); print array[dow]}')

The problem with the above code is that if multiple matches are found then i get multiple results, whereas i want it to output only one result.
Thanks!

A: Limit the call to index() to only those lines which have your "day" surrounded by spaces:
awk -v day=$day 'BEGIN{split("Sunday Monday Tuesday Wednesday Thursday Friday Saturday", array)} $0 ~ "\\<"day"\\>"{for(i=1;i<=NF;i++)if($i == day){print array[i]}}'

Proof of Concept
$ cal 02 1956
    February 1956
Su Mo Tu We Th Fr Sa
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29

$ day=18; cal 02 1956 | awk -v day=$day 'BEGIN{split("Sunday Monday Tuesday Wednesday Thursday Friday Saturday", array)} $0 ~ "\\<"day"\\>"{for(i=1;i<=NF;i++)if($i == day){print array[i]}}'
Saturday

Update
If all you are looking for is to get the day of the week from a certain date, you should really be using the date command like so:
$ day=9;month=9;year=2009;
$ dayOfWeek=$(date +%A -d "$day/$month/$year")
$ echo $dayOfWeek
Wednesday

A: you wrote

cal 09 09 2009

I'm not aware of a version of cal that accepts day of month as an input,
only
 cal ${mon} (optional) ${year} (optional)

But, that doesn't affect your main issue.
you wrote

is there a way to make awk output index number in only the 4th line of cal output above.?

NR (Num Rec) is your friend
and there are numerous ways to use it.
cal 09 09 2009 | awk 'NR==4{day="9"; col=index($0,day); print col }'

OR
cal 09 09 2009 | awk '{day="9"; if (NR==4) {col=index($0,day); print col } }'

ALSO
In awk, if  you have variable assignments that should be used throughout your whole program, then it is better to use the BEGIN section so that the assignment is only performed once. Not a big deal in you example, but why set bad habits ;-)?
HENCE
cal 09 2009 | awk 'BEGIN{day="9"}; NR==4 {col=index($0,day); print col }'

FINALLY
It is not completely clear what problem you are trying to solve. Are you sure you always want to grab line 4? If not, then how do you propose to solve that?
Problems stated as " 1. I am trying to do X. 2. Here is my input. 3. Here is my output. 4. Here is the code that generated that output" are much easier to respond to.
It looks like you're trying to do date calculations. You can be much more robust and general solutions by using the gnu date command. I have seen numerous useful discussions of this tagged as bash, shell, (date?).
I hope this helps.

A: This is so much easier to do in a language that has time functionality built-in.  Tcl is great for that, but many other languages are too:
$ echo 'puts [clock format [clock scan 9/9/2009] -format %a]' | tclsh
Wed

A: If you want awk to only output for line 4, restrict the rule to line 4:

$ awk 'NR == 4 { ... }'


text:
Q: Road blocked by stone arc? In Tropico 4, Mission 5 there is a stone arc that leads to two mines (gold and iron).
Unfortunately I am unable to get there, because said arc seems to prevent any roads from being built underneath it!

Is this a bug? (I sure hope so)
Is there any alternative way to get to the ressource fields?

A: I noticed this too when I played that mission.  I believe it to be a bug.
My workaround was to build 2 roads and have a small gap under the arch.  Not ideal, and I'm not sure either road was ever actually used, but it worked.

A: I never even noticed the arch on that level, or if I did I must have assumed that I couldn't build under it. I think you'll find that there's another (much longer) route you can take, to the east of your starting town, then bearing south past the central volcano, and finally swinging round to the west to get to the mines. It was quite convenient for some of the deposits that turned up later, however.


text:
Q: Dart version is 2.2.0 but I get an error requiring version >=2.2.0 I have the latest version of Flutter and I'm trying to run the official Flutter gallery app. When I do dart --version I get
Dart VM version: 2.2.0 (Tue Feb 26 15:04:32 2019 +0100) on "macos_x64"

However, when I try to get the packages:
[flutter_gallery] flutter packages get
Running "flutter packages get" in flutter_gallery...
The current Dart SDK version is 2.1.2-dev.0.0.flutter-0a7dcf17eb.

Because flutter_gallery requires SDK version >=2.2.0 <3.0.0, version solving failed.
pub get failed (1)
exit code 1

What's interesting is when I run flutter upgrade it lists an older version of Dart (Tools).
Upgrading Flutter from /Users/leejohnson/dev/flutter...
From https://github.com/flutter/flutter
   a1bee54fd..59ce7d6bf  dev        -> origin/dev
   55a2ee588..f8f2b043e  master     -> origin/master
 * [new tag]             v1.3.13    -> v1.3.13
Already up to date.

Upgrading engine...
Already up-to-date.

Flutter 1.2.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 8661d8aecd (5 weeks ago) • 2019-02-14 19:19:53 -0800
Engine • revision 3757390fa4
Tools • Dart 2.1.2 (build 2.1.2-dev.0.0 0a7dcf17eb)

If I understand this error correctly, Flutter is not using the latest version of Dart yet the official Flutter example app requires it. How do I fix this?

A: The output of dart --version is completely irrelevant for Flutter. What you need to check is flutter doctor -v or flutter --version. In your case it shows Tools • Dart 2.1.2 (build 2.1.2-dev.0.0 0a7dcf17eb)
You probably need to switch to another channel until the next stable channel update
flutter channel dev

or
flutter channel master

A: Flutter has its own dart-sdk in flutter/bin/cache/. So when you do dart --version , its probably another dart sdk in your system.

A: For anyone else stuck (The other channels were broken), what I found was switching to stable then switching versions within stable fixed it for me. You can do this by doing the following:
flutter versions
flutter versions 1.5.5 (Or some other version)


text:
Q: using the ui library while iterating over a table in coronaSDK In CoronaSDK, I'm trying to make a certain code that creates a lot of buttons and plays sounds for each of those buttons more "efficient" by first creating a table of strings and then creating the buttons and handlers by iterating over the table.  I'm using the common "ui.lua" file to create buttons.  However, I get (at least) two errors. The first is that the newButton fcn says it's expecting a table value for "default."  Here's the code:
--create the array.  Note that these names will be used for all the objects that refer to these things, so you must have a consistent naming convention
local instruments  = {"snare","piano1", "piano2","guitar1","guitar2","softPiano"}
--set constants to be able to set the x value of the buttons
local h = display.contentWidth/6-25;
local multiplier = 1
--loop through each item in the array to: (a) load the sound, (b) create a btn press event, and (c) create the button
for k,v in pairs(instruments) do
    --first, we use the value to make some reference strings
    img = "images/"..v.."_btn.png"
    sound = "media/"..v..".wav"

    --now create the event listener
    local playThis = function (event)
        audio.play(sound)
    end
    --now create the button
    local thisInstrument = ui.newButton{
        default = img,
        onPress = playThis
    }
    thisInstrument.x = h*multiplier
    thisInstrument.y = display.contentHeight * .8
    multiplier = multiplier + 1
end

When I change the value of default to a straight up string, the buttons are at least created and displayed as expected across the screen.
 local thisInstrument = ui.newButton{
            default = "images/snareDrum_btn.png",
            onPress = playThis
        }

Of course, the sound still doesn't play when I click a button.  So, two questions: First, why won't a simple reference to default = img work?  Second, how do I get the listener to work for each new button?

A: Ok, so I found the answer.  I made a couple of stupid rookie mistakes.  The reason the local variable wasn't working had nothing to do with my code.  It was actually because I had misnamed a couple of the image files (doh!).
Second, the button listener wasn't working because (drumroll...) I had forgotten to load the audio files ahead of time (double doh!).  I ended up deciding to place the playThis function outside the loop so that it wasn't being recreated unnecessarily.  Instead, I set a "sound" property on the created buttons and used the event argument to figure out which button was pushed and play the corresponding sound.
Here's the final code (I've modularized it to make it more re-usable). Hopefully, this'll be a lesson for others in checking your entire environment before banging your head about your code.
--init globals
_H = display.contentHeight;
_W = display.contentWidth;

--test to see if I can more efficiently write code to do a repeated action by placing items inside an array and looping through the array
--import the ui file to create buttons
local ui = require("ui")

--create the array.  Note that these names will be used for all the objects that refer to these things, so you must have a consistent naming convention
local instruments  = {"snare","piano1", "piano2","guitar1","guitar2"}
--set constants to be able to set the x value of the buttons

local function doThis (event)
    audio.play(event.target.property)
end

--loop through each item in the array to: (a) load the sound, (b) create a btn press event, and (c) create the button (the event must be created before the listener, else it has nothing to listen for)
local function makeBtns(btnList,btnImg,property,groupXPos,groupYPos)
    --first, let's place all the buttons inside a button group, so we can move them together
    local thisBtnGroup = display.newGroup();
    for index,value in ipairs(btnList) do
        --first, we use the value to make some reference strings
        local img = "images/base_btn.png"
        property = audio.loadSound("sounds/"..value..".wav")
        --now create the button
        local thisBtn = ui.newButton{
            default = img,
            onPress = doThis,
            text = value,
            size = 10
        }
        thisBtnGroup:insert(thisBtn)
        thisBtn.x = (index -1) * thisBtn.width
        thisBtn.property = property
    end
    thisBtnGroup.x = groupXPos; thisBtnGroup.y = groupYPos
    return thisBtnGroup
end

local myBand = makeBtns(instruments,"images/base_btn.png","sound",_W/3,_H-50)


text:
Q: BigQuery Cross Join Failing I'm trying to pull user activity by date. I am trying to built a table of every day since a user account was created, using cross join and a where clause. In my case, cross join cannot be avoided. The calendar table is just a list of all dates for last 365 days (365 rows). The user table has ~1b rows.
Here is the query that fails with insufficient resources:
SELECT
  u.user_id as user_id,
  date(u.created) as signup_date,
  cal.date as date,
from (select date(dt) as date from [dw.calendar] where date(dt) <
CURRENT_DATE() ) cal
  cross join each dw.user u
where
  date(u.created) <= cal.date

Based on https://cloud.google.com/bigquery/query-reference, cross joins do not even support the "each" clause. How do I perform the above operation to successfully create a table?

A: You do not need to fill "empty" days to just calculate daily count and perform window function to get the aggregated sum, so you don't even need calendar table for this. To make this happen you need to use RANGE vs. ROWS in your window. See example below (for BigQuery Standard SQL)
#standardSQL
SELECT
  user_id, created, daily_count,
  SUM(daily_count) OVER(
    PARTITION BY user_id ORDER BY created_unix_date DESC
    RANGE BETWEEN CURRENT ROW AND 6 FOLLOWING
  ) weekly_avg
FROM `dw.user`, UNNEST([UNIX_DATE(created)]) AS created_unix_date
ORDER BY user_id, created DESC

i am not sure about exact schema /types of your table so might need to adjust above respectively, but meantime you can test/play with below dummy data
#standardSQL
WITH `dw.user` AS (
  SELECT
    day AS created,
    CAST(1 + 10 * RAND() AS INT64)  AS user_id,
    CAST(100 * RAND() AS INT64) AS daily_count
  FROM UNNEST(GENERATE_DATE_ARRAY('2017-01-01', '2017-04-26')) AS day
)
SELECT
  user_id, created, daily_count,
  SUM(daily_count) OVER(
    PARTITION BY user_id ORDER BY created_unix_date DESC
    RANGE BETWEEN CURRENT ROW AND 6 FOLLOWING
  ) weekly_avg
FROM `dw.user`, UNNEST([UNIX_DATE(created)]) AS created_unix_date
ORDER BY user_id, created DESC


text:
Q: TS ES6 - Building Library - Export Issues I have built a server library package that I am want to use for all my programs by importing as the "Base/Core" server program.  To use it as an API, I am doing this in the index.ts.
import { MainServer } from './server-app'; //Want for Type

export class Server {
    private static _serverConfig = null;
    private static _mainDB = null;
    private static _supportDB = null;
    private static _mainServer: MainServer = null;  //Heres type
    private static _client = '';

    constructor(serverConfig, client: string) {
        Server._serverConfig = serverConfig;
        Server._client = client;
    }

    public static async connectAndRun() {
        //Connect then Server._mainDB = db;
        ....
    }

    public static getClientName() {
        return this._client;
    }

    public static getMainServer() {
        return Server._mainServer;
    }

    public static getMainDB() {
        return Server._mainDB;
    }

    public static getSupportDB() {
        return Server._supportDB;
    }
}

export * from './server-app'; //Need for the API to have access to all variables needed

I am getting errors when import { MainServer } from './server-app'; as well as export * from './server-app'; because inside server-app.ts, I am doing more exports such as this:
export * from './collections/app-version.collection';
Inside that file, I have such:
import { Server } from '../index';
import { AppVersionModel } from '../models/app-version.model';

let schema: any = {
    _id: {
        type: String,
        optional: true
    },
    ...
};

export const AppVersions: Model<ServerModel> = Server.getMainDB().model('app-versions', Schema);

So its trying to use Server.getMainDB() which the server is undefined because it's importing in index.ts before my Server is finished it's construction as well as before my DB is connected and defined.
I understand why index.ts needs all the exports, but I do not understand how to export everything without having dependency/import/export issues.

A: Fixed this by generating a index.d.ts typings file with all the export declare functions/constants needed.


text:
Q: Page numbering in Footer is lost while converting to PDF with Docx4j Im Building a API to convert XHtml Files in Word files (.docx) and in PDF, using the Docx4j Libary.
At this Moment the Application works almost well with a few little (i think) formatting issues.
I add CTSimpleFields to my Word document using this code snippet:
 CTSimpleField currentPageNumber = factory.createCTSimpleField();
 currentPageNumber.setInstr(" PAGE \\* Arabic  \\* MERGEFORMAT ");
 CTSimpleField totalPageCount = factory.createCTSimpleField();
 totalPageCount.setInstr("NUMPAGES  \\* Arabic  \\* MERGEFORMAT");

This works well if the document is saved as docx
wordZipFile.save(getOutputStream());

Word Output
But when i try to convert the WordMLPackage to PDF using this snippet:
FieldUpdater updater = new FieldUpdater(this.wordZipFile);
updater.update(true);
Docx4J.toPDF(this.wordZipFile,this.getOutputStream());

The page numbering is missing in the output PDF file.
PDF Output
Has somebody an idea how to workaround for this problem?


text:
Q: Function returns returns either int or list of ints. Assinging the first to a variable Suppose we have
def f_1():
    return (3, 4)

def f_2():
    return 2

The functions are given. It is not code that I can modify.
We know they return either an integer or a sequence of them.
I would like to assign the return to a variable, where the variable should take only the first of the integers if the return is a sequence of them.
Is there a build-in syntactic device in Python that allows me to do this?
for function in [f_1, f_2]:
    ...
    x = function()[0] # Works for f_1, breaks for f_2
    y = function()    # Works for f_2, assigns (3, 4) for f_1 while
                      #   we really would like only the 3 to be the
                      #   assigned value

Note: Assume that we don't know which of the functions return the sequence and which return just a number.

A:
Is there a build-in syntactic device

No. The usual practice is to ask for forgivness:
x = function()
try:
    x = x[0]
except TypeError:
    pass

A: I wouldnt go for try-except statement. To me it's an overkill.
More likely I would try to do something like:
result = function()
# this can be changed to abc.Sequence for more general approach
if isinstance(result, (list, tuple)):
    result = result[0]

A: Going in the other direction, wrap f_2 in another function to ensure that the function called in the body of the loop always returns a sequence.
for function in [f_1, lambda : (f_2(),)]:
    x = function()[0]

The additional overhead of another function call may make this approach undesirable.


text:
Q: OLOO Pattern clarification I'm still studying but lately changed the field I want to work in to web development. So programming is nothing new to me but I never really looked twice at javascript.
I'm trying to learn fast but I got confused about the different inheritance patterns used in javascript. I looked up on the classical prototype chain where the .prototype reference is set by the programmer (I think this is commonly refered to as prototype pattern).
Then I was reading lots of blogs and articles about OLOO and its advantages regarding simplicity.
So I tried coding a little sample myself and while researching for a good approach I came up with a snipped of code that I can't really put into any of those two categories.
I made a fiddle if one wants to have a look:
http://jsfiddle.net/HB7LU/19377/
For anyone else, this is basically my code:
function Parent() {
    return {
        array: [],

        add: function(element) {
            this.array.push(element + this.array.length.toString());
        },

        getAll: function() {
            return this.array;
        },
    };
};

function Child() {
    return Object.assign(Parent(), {

        removeAllButOne: function() {
            this.array.splice(1);
        }
    });
};

foo = Parent();
foo.add('foo');

bar = Child();
bar.add('bar');

foo.add('foo');
bar.add('bar');
bar.removeAllButOne();

Hopefully someone can clarify what it is I did here and what drawbacks I'll face using this method. I know it can't be OLOO because OLOO relies on a simple Object.create(...);
to create new objects.
EDIT: Link to fiddle was broken, sorry

A: What you are doing is somewhat like a mixin pattern.  You're creating a new Parent object, then partially merging it into the Child object which is kind of the idea behind a mixin.
Here are some references on mixins:
A Fresh Look at Javascript Mixins
The Mixin Pattern
JavaScript Mixins: Beyond Simple Object ExtensionPosted
Here are some disadvantages of what you're doing:

*

*You create a Parent instance, copy from it, then throw it away.

*Any methods on Parent.prototype would not be inherited

*instanceof Parent will not be supported

*instanceof Child will not be supported

Object.assign() only copies enumerable, own properties so it does not copy the entire state of a Parent object, thus it can only be used in this circumstance when you explicitly know the parent object doesn't have any of the things that will not be copied.


text:
Q: Storybook type wrong when using children as an arg I'm trying to use TS and storybook children in args, https://storybook.js.org/docs/react/writing-stories/stories-for-multiple-components#using-children-as-an-arg
I have a Button.stories.tsx:
import { ComponentStory, ComponentMeta } from "@storybook/react"

import { Button } from "./Button"

export default {
    title: "Example/Button",
    component: Button,
    argTypes: {
        backgroundColor: { control: "color" },
    },
} as ComponentMeta<typeof Button>

const Template: ComponentStory<typeof Button> = (args) => <Button {...args} />

export const Primary = Template.bind({})
Primary.args = {
    primary: true,
    label: "Button",
}

and ButtonGroup.stories.tsx:
import { ComponentStory, ComponentMeta } from "@storybook/react"

import { ButtonGroup } from "./ButtonGroup"

import { Primary } from "../Button/Button.stories"

export default {
    title: "Example/ButtonGroup",
    component: ButtonGroup,
    argTypes: {},
}

const Template: ComponentStory<typeof ButtonGroup> = (args) => <ButtonGroup {...args} />

export const PrimaryButtonGroup = Template.bind({})
PrimaryButtonGroup.args = {
    children: (
        <>
            <Primary {...Primary.args} />
            <Primary {...Primary.args} />
        </>
    ),
}

There is a type error on the <Primary {...Primary.args} /> on PrimaryButtonGroup.args. The problem is the args is optional, so the primary and label from Primary.args could be undefined. So it cannot match the label type string.
How can I fix this issue?


text:
Q: Datastage-What is the escape character for # in execute command activity? What is the escape character for # in execute command activity? Well i was trying to replace one string in file with "#",but datastage treating # as job parameter and expecting the value to be assigned in datastage parameters.For that we need escape character for "#". I tried using \ and / as escape characters but none of them solved my problem. Thank You.

A: Just wanted to add that the actual answer to this question is:
    \043
The expression mentioned previously (!/^\043/) is related to the first link @Damienknight posted.

A: Use awk to replace the # sign, and you can use the octal character code for # in the regular expression:
!/^\043/

There is a thread in DSXchange that discusses this.
Here is a guide on escape sequences in AWK expressions.
A table with ascii codes, including a column for octal values.


text:
Q: PIP Install request RuntimeError: maximum recursion depth exceeded in python 2.7 I am new to python and facing below issue.
When I am trying to install request module by using command PIP install request, I got the error
RuntimeError: maximum recursion depth exceeded

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in
C:\users\sandeep_kumar39\appdata\local\temp\pip-build-gzzphx\setupfiles\

Python version is 2.7.12
and I already upgrade the distribution package by using command pip install --upgrade distribute
and upgraded the pip version too by using command pip install --upgrade pip
Complete output of error:
C:\Python27\Scripts>pip install request
Collecting request
  Using cached request-0.0.12.tar.gz
Collecting get (from request)
  Using cached get-0.0.20.tar.gz
Collecting post (from request)
  Using cached post-0.0.12.tar.gz
Collecting setupfiles (from request)
  Using cached setupfiles-0.0.16.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "c:\users\sandeep_kumar39\appdata\local\temp\pip-build-3gsgdg\setupfiles\setup.py", line 4, in <module>
        from setupfiles import setup
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
            File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 18, in <module>
        import setupfiles # nopep8
      File "setupfiles.py", line 11, in <module>
        dirname = os.path.abspath(os.path.dirname(__file__))
      File "c:\python27\lib\ntpath.py", line 215, in dirname
        return split(p)[0]
      File "c:\python27\lib\ntpath.py", line 180, in split
        d, p = splitdrive(p)
    RuntimeError: maximum recursion depth exceeded

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in c:\users\sandeep_kumar39\appdata\local\temp\pip-build-3gsgdg\setupfiles\

A: This appears to be due to a bug in recent versions of setupfiles, upon which request depends.  You can work around this by first installing version 0.0.14 of setupfiles with pip install setupfiles==0.0.14 before trying to install request.


text:
Q: How to render context when we open template from S3buckets? I'm trying to render context in template. But I'm unable to do that. I'm opening my template from bucket and reading. Now how to render context.
    render_param.update({'name': email.split("@")[0],'email': email})
    # html_message = loader.render_to_string(obj.html_template.url, request_data)
    html_message = default_storage.open(obj.html_template.name, 'r')
    html_message= f"""
    {html_message.read()}
    """
    message = EmailMultiAlternatives(subject, html_message, email_host.email, [email])

    message.attach_alternative(html_message, 'text/html')
    messages.append(message)


text:
Q: A better definition of "median"? Referring to the definition in Wikipedia, paraphrased:

Formally, a median of a population is any value such that at most half
of the population is less than the proposed median and at most half is
greater than the proposed median. As seen above, medians may not be
unique. If each set contains less than half the population, then some
of the population is exactly equal to the unique median.
If the data set has an odd number of observations, the middle one is
selected. For example, the following list of seven numbers,
If the data set has an even number of observations, there is no
distinct middle value and the median is usually defined to be the
arithmetic mean of the two middle values

But  as all you statisticians know, this can lead to misdirection.  Consider the following dataset ( R code)
foo <- rnorm(1000)
bar <- rnorm(1001,50)
median(c(foo,bar))
[1] 46.86411

But the graph shows how bad a choice that is:
hist(c(foo,bar), breaks=100)

Clearly we'd be better off picking the arithmetic mean of the max of the low peak and the min of the high peak.  Is this just a case of "look at the data before deciding which statistical parameters matter"?  Is there a reason the strict definition of 'median' fails to produce a useful value here?


text:
Q: Using rails logger in rake tasks, rails 5 I'm building a ruby on rails app, using rails 5, and I have a number of rake tasks from which I'd like to log information. However, when I attempt to access the logger, I get an error: undefined local variable or method `logger'
I have my rake tasks in lib/tasks, and I've declared a logger in both production.rb and developement.rb
Here's an example task:
namespace :some_namespace do
    desc "a description"
    task :scrape_info do
        include Scraper
        startTime = Time.now
        Rails.logger.tagged("Scraper") { Rails.logger.info "Beginning scrape: #{startTime} " }
        Scraper.scrape_info
        endTime = Time.now
        Rails.logger.tagged("Scraper") { Rails.logger.info "Finished scrape: #{endTime} " }
    end
end

And an excerpt from development.rb where I have the logger defined:
 config.logger = Logger.new(STDOUT)
 config.log_level = :info
 config.logger = ActiveSupport::TaggedLogging.new(logger)

Any idea how to incorporate the logger into rake tasks? I understand that I could simply use a puts statement to print to stdout, but eventually I'd like to have daily log files, and I would like my rake tasks to be included in those files
ANSWER:
Simply add the environment tag given in the answer from @Joel_Blum. Also, in development.rb, the line
config.logger = ActiveSupport::TaggedLogging.new(logger)

needs to be:
config.logger = ActiveSupport::TaggedLogging.new(config.logger)

A: Try adding the environment, this will have the effect of loading your rails app.
 task :scrape_info => :environment do
  ...
 end


text:
Q: PHP simpleXMLelment xpath returns unexpected results I have executed the following code on the the sample XML at the bottom of the question and I am getting unexpected results.
$xml = simplexml_load_string($xml_string);
$addresses = $xml->response->addressinformation;
var_dump($addresses->xpath('//record'));

I would expect this to return only the two record nodes that are children of the current addresses node.  But, it actually returns all 5 of the record nodes of the original $xml element.  Everything I have read says that the // notation is relative to the current node.  I realize that there are other ways to get to just the two records I've referenced in the questions. $addresses->xpath('records/record'); is just one example.  But, the strange behavior is part of a larger problem I'm having and I just need to understand why it is behaving this way. Everything I've read would lead me to believe otherwise.  Can anyone help me understand?
Sample XML
$xml_string = '
<?xml version="1.0" encoding="utf-8"?>
<root>
    <response>
        <addressinformation>
            <records>
                <record id="1">
                    <fullname>JOHN E DOE</fullname>
                    <firstname>JOHN</firstname>
                    <middlename>E</middlename>
                    <lastname>DOE</lastname>
                    <fulldob>01/01/1970</fulldob>
                </record>
                <record id="2">
                    <fullname>JOHN E DOE</fullname>
                    <firstname>JOHN</firstname>
                </record>
            </records>
        </addressinformation>
        <otherinformation>
            <records>
                <record id="3">
                    <fullname>JOHN DOE</fullname>
                    <firstname>JOHN</firstname>
                    <lastname>DOE</lastname>
                    <fulldob>01/01/1970</fulldob>
                </record>
                <record id="4">
                    <fullname>JOHN EDWARD DOE</fullname>
                    <firstname>JOHN</firstname>
                    <middlename>EDWARD</middlename>
                    <lastname>DOE</lastname>
                    <fulldob>19700000</fulldob>
                </record>
                <record id="5">
                    <fullname>JOHN EDWARD DOE</fullname>
                    <firstname>JOHN</firstname>
                    <middlename>EDWARD</middlename>
                    <lastname>DOE</lastname>
                    <fulldob>19830000</fulldob>
                </record>
            </records>
        </otherinformation>
    </response>
</root>
';

A: According to https://www.w3.org/TR/1999/REC-xpath-19991116/:

//para selects all the para descendants of the document root and thus selects all para elements in the same document as the context node

and

.//para selects the para element descendants of the context node

Note the dot before the latter one. This also works in your case:
var_dump($addresses->xpath('.//record'));

properly only shows the two nodes you are expecting.
The thing is - apparently - that even all the objects are just of type SimpleXMLElement, the first one that you are creating by calling simplexml_load_string() is for some reason considered the document root. When you "destruct" your document into nodes and subnodes this all makes sense to me.
However I would agree that this is at least some behaviour that is not documented in the PHP docs, so I recommend you suggest an edit there.


text:
Q: Breeze does not work with predictate in aspnetcore project I am building an ASP.NET Core project, which uses breezejs and typescript. The mysterious thing is that when I load data without a predicate, all the things work fine, but when a predicate is added to filter the data, there is an error:'500 Internal Server Error' . I tried to debug in the controller, when browser make the request, it can get to the controller.
But, in the js side, the request has no return, which means the js code cannot go through the breakpoint.
executeQuery(query) {
    return this.manager
        .executeQuery(query.using(breeze.FetchStrategy.FromServer || this.fetchStrategy))
        .then(function (data) {
            return data.results;//my breakpoint
        });
}

The contorller:
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Jumpstart.Web.Data;
using Microsoft.AspNetCore.Authorization;
using Jumpstart.Model;
using Breeze.AspNetCore;
using Newtonsoft.Json.Linq;
using Breeze.Persistence;

namespace Jumpstart.Web.Controllers
{
[Produces("application/json")]
[Route("breeze/[controller]/[action]")]
[BreezeQueryFilter]
public class JumpstartController : Controller
{
    private readonly IUnitOfWork _uitOfWork;

    public JumpstartController(IUnitOfWork uitOfWork)
    {
        _uitOfWork = uitOfWork;
    }

    /// <summary>
    /// Get public tenants
    /// </summary>
    /// <returns>IQueryable tenants</returns>
    [HttpGet]
    [AllowAnonymous]
    public IQueryable<Tenant> Tenants()
    {
        return _uitOfWork.TenantRepository.All();

    }

The request :
Request URL:http://localhost:50481/breeze/Jumpstart/tenants?$filter=Id%20eq%20guid%2709ae9363-240a-46d7-b5a6-30529e7dee63%27&
Request Method:GET
Status Code:500 Internal Server Error

A: Found the reason. The breeze.core(server end) only permit json format predicate, but the default in breeze front end is not.
the solution is :
  breeze.config.initializeAdapterInstance("uriBuilder", "json");


text:
Q: Дублирование value c input c form в такую же form Необходимо копировать value из input name=[id] и name=[ssid] в form id ="addEntForm" в такую же form id ="addEntForm" только в div id="div2"
Пытался попытка увенчалась провалом

var x = $('#addEntForm input[name="id"]').val()
$('#div2 input[name="id"]').val(x);

var x = $('#addEntForm input[name="ssid"]').val()
$('#div2 input[name="ssid"]').val(x);
<form method="post" id="addEntForm" style="margin:0px" name="addform" enctype="multipart/form-data" onsubmit="openery();return false;">

    <input name="id" value=""> // вставить сюда
    <input name="a" value="14">
    <input name="ssid" value=""> // вставить сюда
    <input id="numi" value="1">

</form>

<form method="post" id="addEntForm" style="margin:0px" name="addform" enctype="multipart/form-data" onsubmit="openery();return false;">

    kjhkjh

  <input name="id" value="55"> \\берем отсюда
  <input name="a" value="14">
  <input name="ssid" value="W4sdENxN"> \\берем отсюда
  <input id="numi" value="1">
</form>

A: ID не может совпадать с любым другим ID в одном пространстве DOM. Ошибки, обычно, браузеры не кидают, но поведение будет разным и уж точно неверным (или случайно верным, на уровне 'пальцем в небо').

function $(s){return document.querySelector(s);} // Syntactic sugar

document.addEventListener('DOMContentLoaded', e => { // After loading the page, copy the value
  $('#to input[name="ssid"]').value = $('#from input[name="ssid"]').value; // Copy the 'ssid' value
  $('#to input[name="id"]').value = $('#from input[name="id"]').value; // Copy the 'id' value
});
<form method="post" id="to" style="margin:0px" name="addform" enctype="multipart/form-data" onsubmit="openery();return false;">

    <input name="id" value="">
    <input name="a" value="14">
    <input name="ssid" value="">
    <input id="numi" value="1">

</form>

<form method="post" id="from" style="margin:0px" name="addform" enctype="multipart/form-data" onsubmit="openery();return false;">

    kjhkjh

  <input name="id" value="55">
  <input name="a" value="14">
  <input name="ssid" value="W4sdENxN">
  <input id="numi" value="1">
</form>


text:
Q: Moving Sprite in direction it is rotated (unity) I'am making a space shooter in Unity. The problem is that I can't get the sprite to move in the direction it is rotated. How can I do it?
Code:
using UnityEngine;

public class PlayerControl : MonoBehaviour
{
  public float speed = 13f;
  public Animator animator;
  public Rigidbody2D rigidBody2D;
  public float rotation = 0.0f;

void Start()
{
    rigidBody2D = GetComponent<Rigidbody2D>();
}

void Update()
{
     if(Input.GetKey(KeyCode.W)){
        Vector2 pos = rigidBody2D.velocity;
        pos.y += speed * Time.deltaTime;
        rigidBody2D.velocity = pos;
    }

    if(Input.GetKey(KeyCode.A)){
        rigidBody2D.SetRotation(rotation);
        rotation += 2.0f;
    }
      if(Input.GetKey(KeyCode.D)){
        rigidBody2D.SetRotation(rotation);
        rotation -= 2.0f;
    }
}

}

A: You can get the facing(or forward) direction by multiplying the orientation by whatever axis you use for rotating your game object.
Below are three examples:
// Top down example: the spaceship rotate in it's Y axis
// first, let's get its facing direction
Vector3 forwardDirection = spaceshipObject.transform.rotation * Vector3.up;

// then we can move the spaceship forward
// either with normal Transform
Vector3 moveDirection = forwardDirection * speed * Time.deltaTime;
spaceshipObject.transform.position += moveDirection;
// if you dont want to do the maths, you can directly use Unity's builtin transform.forward to move your ship, it does the same as line 3
Vector3 moveDirection = spaceshipObject.transform.forward;
spaceshipObject.transform.Translate(moveDirection * speed * Time.deltaTime);
// Or if you fancy using Rigibodies
rigidbody.velocity = forwardDirection * speed * Time.deltaTime;


text:
Q: How to get and maintain the oauth2 token using spring-security-oauth2-client when using authorization code grant in angular How can I get the token to the front end angular application after successful redirection to the index.html page happens like
1. I have used
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
in my pom.xml
2. then I have added required properties in my application.properties file
3. I built the angular files and placed them under resources/static folder

Now the redirection to auth-server and callback to application happens successfully but how to get the oauth2 token and store in the angular application which will be useful for further calls

A: If you have an Angular app, then it is the client. It should use angular-auth-oidc-client or alike to:

*

*login users

*handle redirects to and from authorization-server

*exchange authorization-code for access-token

*access-token refreshing

*add authorization-header with access-token to requests sent to configured secured routes

Spring REST API applications are resource-servers. It should depend on spring-boot-starter-oauth2-resource-server, not spring-boot-starter-oauth2-client. Refer to spring boot doc or have a look at those tutorials for more details on configuring Spring resource-servers.


text:
Q: Выбор лимитированного количества строк с группировкой Есть таблица A (id, name) и B (id, name, a_id). Как выбрать из таблицы B набор строк состоящий из последних максимум 100 строк каждого a_id.
Например: A с 3 строками id = 1,2,3 и B с 150 строками где a_id = 1, 50 строками где a_id = 2, 100 строками где a_id = 3 тогда нужно вернуть набор состоящий с 100 строк где a_id = 3, 50 строк где a_id = 2 и 100 последних строк где a_id = 1 (последние строки имею ввиду сортируя по id - DESC LIMIT)

A: Как вариант можно использовать оконную функцию для получения порядкового номера ассоциированной записи, чтоб потом отфильтровать:
select * from (
    select a.*, b.*, row_number() over(partition by a_id order by b.id desc) bnum
    from a
        inner join b on a.id = b.a_id
) as r
where r.bnum <= 100;

Второй способ это использовать LATERAL объединение:
select a.*, b.*
from a
   inner join lateral (
     select *
     from b
     where b.a_id = a.id
     order by id desc
     limit 100
) as b on true;


text:
Q: How to assert that a text ends with digits in protractor I would like to assert in Protractor that a link text is composed by the following way: text-1 (where text is a variable, and the number can be composed by any digits).
I tried the following:
browser.wait(
        ExpectedConditions.visibilityOf(
        element(by.xpath(`//a[@class = 'collapsed' and starts-with(text(), '${text}') and ends-with(text(), '-(/d+)')]`))),
 5000)

and
browser.wait(
        ExpectedConditions.visibilityOf(
        element(by.xpath(`//a[@class = 'collapsed' and starts-with(text(), '${text}') and ends-with(text(), '/^-(/d+)$/')]`))),
        5000)

Unfortunately, none of the above xpaths worked.
How can I fix this?

A: If you change the way to declare the variable and your second predicate you can go with :
//a[@class='collapsed'][starts-with(text(),'" + text_variable + "')][number(replace(.,'^.*-(\d+)$','$1'))*0=0]

where [number(replace(.,'^.*-(\d+)$','$1'))*0=0] test for the presence of a number at the end of a string.
Example. If you have :

foofighters-200
foofighters
boofighters-200
boofighters-200abc

The following XPath :
//a[@class='collapsed'][starts-with(text(),'foo')][number(replace(.,'^.*-(\d+)$','$1'))*0=0]

will output 1 element :
foofighters-200

So in Protractor you could have :
var text = "foo";
browser.wait(ExpectedConditions.visibilityOf(element(by.xpath("//a[@class='collapsed'][starts-with(text(),'" + text + "')][number(replace(.,'^.*-(\d+)$','$1'))*0=0]"))), 5000);
...

A: You can use regexp for this:
await browser.wait(async () => {
    return new RegExp('^.*(\d+)').test(await $('a.collapsed').getText());
}, 20000, 'Expected link text to contain number at the end');

Tune this regex here if needed:
https://regex101.com/r/9d9yaJ/1


text:
Q: Training a Neuronal Network which recognize music chord and intervals In school we have to listen to intervals and chords and determine their name. I'm really into neuronal network. Thats why I want to create a neuronal network with Python which listen to the audio and give me the name as an output. I've learned once that for music I need a LSTM. Should I need for this purpose also a LSTM and how/where should I start? Can anybody teach me how to achieve my goal?

A: first of all you need to exactly define the task you like to solve: Do you like to classify a whole piece of music/track or do you like to classify segments of the piece/track? This will influence which architecture you need to use to solve your task. I will briefly present an approach for each of those tasks.

*

*Classifying a track: Recordings of music are time series, for each of your recordings you need to have a label. Your first intuition of using LSTMs (or RNNs in general) is a good one. Just use your recording transformed into a vector as input-sequence for your LSTM-network and let it put out probabilities for each class. As already indicated by a comment, working in frequency-space can be beneficial. However just using the Fourier-Transformation of the whole track will most likely lose important information since the temporal frequency information is lost. Rather use Short-time Fourier-Transormation (STFT) or Mel-frequency cepstrum coefficients (MFCC, here is a python-library to calculate them: libROSA). Very oversimplified, those methods will transform your time series into some kind of 'image', an two-dimensional frequncy-spectrum, and for image classification task Convolutional Neural Networks (CNNs) are the way to go.

*Classifying segments: If you like to classify segments of your track you need to have a labels for each time-frame in your song. Lets say your song is 3 minutes long and you have a sampling frequency of 60 Hz, your vector representation of the song will have 3*60*60 = 10800 time-frames, thus for each of the entries you need to provide a class label (chord or whatever). Again you can use LSTMs, use your vector as input-sequence and let your network produce an output sequence of the same length of your song and compare it to the class labels. You also could use the previously mentioned STFT- or MFC-coefficients as inputs and take advantage of the frequency information, now you will have a spectrum for each time-frame as input.

I hope these broad ideas will bring you one step closer to solve your task. For implementation details I like to point you to the keras documentation and to countless tutorials on the internet.
Disclaimer:
My knowledge of music theory is rather limited, so please take my answer with a grain of salt and feel free to correct me or ask for clarification. Have fun


text:
Q: How to save massive data on dynamodb? I'm trying to save massive phone registers to a dynamodb working on docker (local), but everytime that i'm trying to save i get an error
Error: connect ECONNREFUSED 127.0.0.1:8000 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16)
Here is my code that im trying to call every record that i need to save, working on nest
async saveData(saveItem: listUser) {
        const tableName: string = this.userTableName;
        const input = <BatchWriteCommandInput>{};
        input.RequestItems = {};
        input.RequestItems[tableName] = [
            { PutRequest: { Item: saveItem } },
        ];

        const output = await this.dynamoClient.getDocumentClient().send(new BatchWriteCommand(input));

        return output.$metadata.httpStatusCode;
    }

EDIT
It appears executing the save funtion mutiple times, it works with the first 40 or 50 entries and then shows up this error.
It's the conection error shows up when tryin to save mutiple times

A: Error: connect ECONNREFUSED 127.0.0.1:8000 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) states you are trying to connect to localhost on port 8000. If you are using DynamoDB local, ensure the service is running on port 8000 locally.


text:
Q: Is it possible to have more than one screen in Parallels? I use Parallels 10 on Yosemite. My hardware has one screen or two screens, depending on if I use the laptop and/or an external screen in combination. However, Parallels only recognises one screen:

(Here in the Windows 7 Display settings.)
Is it possible for Parallels to use two screens, such that each screen is on one OSX space?
Much like I swipe between spaces in OSX, where one space has Parallels fullscreen, I would like to be able to swipe further and get to a second Parallels screen even when I have only one monitor attached to the host machine - effectively, as far as Windows in the hosted VM is concerned, a second monitor, but one accessible through OSX's Spaces. Is this possible, and if so, how?
This seems to be possible for VMWare Workstation and possibly VirtualBox, but I can't find anything for Parallels (for that matter, I don't know if the Workstation monitor capability is in VMWare Fusion, either.)


text:
Q: Appending rows to numpy array using less memory I have the following problem. I need to change the shape of one Numpy array to match the shape of another Numpy array by adding rows and columns.
Let's say this is the array that needs to be changed:
change_array = np.random.rand(150, 120)

And this is the reference array:
reference_array = np.random.rand(200, 170)

To match the shapes I'm adding rows and columns containing zeros, using the following function:
def match_arrays(change_array, reference_array):

    cols = np.zeros((change_array.shape[0], (reference_array.shape[1] - change_array.shape[1])), dtype=np.int8)
    change_array = np.append(change_array, cols, axis=1)
    rows = np.zeros(((reference_array.shape[0] - change_array.shape[0]), reference_array.shape[1]), dtype=np.int8)
    change_array = np.append(change_array, rows, axis=0)
    return change_array

Which perfectly works and changes the shape of change_array to the shape of reference_array. However, using this method, the array needs to be copied twice in memory. I understand how Numpy needs to make a copy of the array in memory in order to have space to append the rows and columns.
As my arrays can get very large I am looking for another, more memory efficient method, that can achieve the same result. Thanks!

A: Here are a couple ways.  In the code examples, I'll use the following arrays:
In [190]: a
Out[190]:
array([[12, 11, 15],
       [16, 15, 10],
       [16, 12, 13],
       [11, 19, 10],
       [12, 12, 11]])

In [191]: b
Out[191]:
array([[70, 82, 83, 93, 97, 55],
       [50, 86, 53, 75, 75, 69],
       [60, 50, 76, 52, 72, 88],
       [72, 79, 66, 93, 58, 58],
       [57, 92, 71, 97, 91, 50],
       [60, 77, 67, 91, 91, 63],
       [60, 90, 91, 50, 86, 71]])

Use numpy.pad:
In [192]: np.pad(a, [(0, b.shape[0] - a.shape[0]), (0, b.shape[1] - a.shape[1])], 'constant')
Out[192]:
array([[12, 11, 15,  0,  0,  0],
       [16, 15, 10,  0,  0,  0],
       [16, 12, 13,  0,  0,  0],
       [11, 19, 10,  0,  0,  0],
       [12, 12, 11,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0]])

Or, use a more efficient version of your function, in which the result is preallocated as an array of zeros with the same shape as reference_array, and then the values in change_array are copied into the result:
In [193]: def match_arrays(change_array, reference_array):
     ...:     result = np.zeros(reference_array.shape, dtype=change_array.dtype)
     ...:     nrows, ncols = change_array.shape
     ...:     result[:nrows, :ncols] = change_array
     ...:     return result
     ...:

In [194]: match_arrays(a, b)
Out[194]:
array([[12, 11, 15,  0,  0,  0],
       [16, 15, 10,  0,  0,  0],
       [16, 12, 13,  0,  0,  0],
       [11, 19, 10,  0,  0,  0],
       [12, 12, 11,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0]])


text:
Q: Meteor/Fibers - How to use Meteor.call callback? I have this code, where I call a Meteor method from the client and expect a result in the callback. the results object is a well formed object that I can stringify and print from the server's console.
When I run this code, with a valid results and no error, the callback is not called on the client. However, if I substitute fut.return(results) with fut.return(JSON.parse(JSON.stringify(results))), the callback is called and I get "a string" in the client. Any idea why I can return a string but no object?
Server code (in Meteor.Methods()):
getUserEvents : function(userId,start,end) {
        var fut = new Future();
        getUserEventsPrivate(userId,start,end,function(err,results){
            if(err){
                fut.throw(new Meteor.Error( 500, 'Oops, something wrong happened'));
            }else{
                fut.return(results); // works when fut.return(JSON.parse(JSON.stringify(results)));
            }
        });
        return fut.wait();
    }

Client:
Meteor.call('getUserEvents',Meteor.user()._id, startStr, endStr,function(err,results){
    console.log(results);
});

EDIT
here is the Json I'm trying to pass as 'results':
[
  {
    "title": "ResponsiveMTL #1",
    "start": "2015-10-13T21:30:00.000Z",
    "end": "2015-10-14T00:30:00.000Z"
  },
  {
    "title": "Meteor Global Distributed Hackathon",
    "start": "2015-10-10T15:00:00.000Z",
    "end": "2015-10-11T15:00:00.000Z"
  },
  {
    "title": "retenues a la source",
    "start": "2015-10-08T19:25:00.275Z",
    "end": "2015-10-08T19:25:00.275Z"
  },
  {
    "title": "Salsa",
    "start": "2015-09-19T22:00:00.000Z",
    "end": "2015-09-19T23:00:00.000Z"
  },
  {
    "title": "Salsa",
    "start": "2015-10-09T22:00:00.000Z",
    "end": "2015-10-09T23:00:00.000Z"
  }
]

A: It is entirely possible to return an object this way.
Your object is probably not EJSON-serializable out of the box, although it is hard to tell without actually looking at a sample of it.
If, for example, your objects contain circular references, EJSON will silently fail and your callback won't be called. It is unlikely that this is the case, as you are able to get JSON to serialize it.
You can try to find the offending properties and modify them, but it might be a good idea to register it as a custom type with EJSON.
http://docs.meteor.com/#/full/ejson_add_type
Anyway, it would be interesting to see your actual objects and be able to tell more.
What version of Meteor are you using?