text:
Q: Speeding Up Python This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:

*

*Firstly: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?

*Secondly:  When writing a program from scratch in python, what are some good ways to greatly improve performance?
For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization.  What would you do to speed it up in this case short of rewriting it in something like C?

A: Cython and pyrex can be used to generate c code using a python-like syntax. Psyco is also fantastic for appropriate projects (sometimes you'll not notice much speed boost, sometimes it'll be as much as 50x as fast).
I still reckon the best way is to profile your code (cProfile, etc.) and then just code the bottlenecks as c functions for python.

A: I'm surprised no one mentioned ShedSkin: http://code.google.com/p/shedskin/, it automagically converts your python program to C++ and in some benchmarks yields better improvements than psyco in speed.
Plus anecdotal stories on the simplicity: http://pyinsci.blogspot.com/2006/12/trying-out-latest-release-of-shedskin.html
There are limitations though, please see: http://tinyurl.com/shedskin-limitations

A: I hope you've read: http://wiki.python.org/moin/PythonSpeed/PerformanceTips
Resuming what's already there are usualy 3 principles:

*

*write code that gets transformed in better bytecode, like, use locals, avoid unnecessary lookups/calls, use idiomatic constructs (if there's natural syntax for what you want, use it - usually faster. eg: don't do: "for key in some_dict.keys()", do "for key in some_dict")

*whatever is written in C is considerably faster, abuse whatever C functions/modules you have available

*when in doubt, import timeit, profile

A: Regarding "Secondly: When writing a program from scratch in python, what are some good ways to greatly improve performance?"
Remember the Jackson rules of optimization:

*

*Rule 1: Don't do it.

*Rule 2 (for experts only): Don't do it yet.

And the Knuth rule:

*

*"Premature optimization is the root of all evil."

The more useful rules are in the General Rules for Optimization.

*

*Don't optimize as you go.  First get it right.  Then get it fast.  Optimizing a wrong program is still wrong.

*Remember the 80/20 rule.

*Always run "before" and "after" benchmarks.  Otherwise, you won't know if you've found the 80%.

*Use the right algorithms and data structures.  This rule should be first.  Nothing matters as much as algorithm and data structure.
Bottom Line
You can't prevent or avoid the "optimize this program" effort.  It's part of the job.  You have to plan for it and do it carefully, just like the design, code and test activities.

A: This won't necessarily speed up any of your code, but is critical knowledge when programming in Python if you want to avoid slowing your code down.  The "Global Interpreter Lock" (GIL), has the potential to drastically reduce the speed of your multi-threaded program if its behavior is not understood (yes, this bit me ... I had a nice 4 processor machine that wouldn't use more than 1.2 processors at a time).  There's an introductory article with some links to get you started at SmoothSpan.

A: Run your app through the Python profiler.
Find a serious bottleneck.
Rewrite that bottleneck in C.
Repeat.

A: People have given some good advice, but you have to be aware that when high performance is needed, the python model is: punt to c.  Efforts like psyco may in the future help a bit, but python just isn't a fast language, and it isn't designed to be.  Very few languages have the ability to do the dynamic stuff really well and still generate very fast code; at least for the forseeable future (and some of the design works against fast compilation) that will be the case.
So, if you really find yourself in this bind, your best bet will be to isolate the parts of your system that are unacceptable slow in (good) python, and design around the idea that you'll rewrite those bits in C.  Sorry.  Good design can help make this less painful.  Prototype it in python first though, then you've easily got a sanity check on your c, as well.
This works well enough for things like numpy, after all.  I can't emphasize enough how much good design will help you though.  If you just iteratively poke at your python bits and replace the slowest ones with C, you may end up with a big mess.  Think about exactly where the C bits are needed, and how they can be minimized and encapsulated sensibly.

A: It's often possible to achieve near-C speeds (close enough for any project using Python in the first place!) by replacing explicit algorithms written out longhand in Python with an implicit algorithm using a built-in Python call.  This works because most Python built-ins are written in C anyway. Well, in CPython of course ;-) https://www.python.org/doc/essays/list2str/

A: Just a note on using psyco: In some cases it can actually produce slower run-times. Especially when trying to use psyco with code that was written in C. I can't remember the the article I read this, but the  map() and reduce() functions were mentioned specifically. Luckily you can tell psyco not to handle specified functions and/or modules.

A: This is the procedure that I try to follow:

*

* import psyco; psyco.full()

* If it's not fast enough, run the code through a profiler, see where the bottlenecks are. (DISABLE psyco for this step!)

* Try to do things such as other people have mentioned to get the code at those bottlenecks as fast as possible.

*
*Stuff like [str(x) for x in l] or [x.strip() for x in l] is much, much slower than map(str, x) or map(str.strip, x).

* After this, if I still need more speed, it's actually really easy to get PyRex up and running. I first copy a section of python code, put it directly in the pyrex code, and see what happens. Then I twiddle with it until it gets faster and faster.

A: Rather than just punting to C, I'd suggest:
Make your code count. Do more with fewer executions of lines:

*

*Change the algorithm to a faster one. It doesn't need to be fancy to be faster in many cases.

*Use python primitives that happens to be written in C. Some things will force an interpreter dispatch where some wont. The latter is preferable

*Beware of code that first constructs a big data structure followed by its consumation. Think the difference between range and xrange. In general it is often worth thinking about memory usage of the program. Using generators can sometimes bring O(n) memory use down to O(1).

*Python is generally non-optimizing. Hoist invariant code out of loops, eliminate common subexpressions where possible in tight loops.

*If something is expensive, then precompute or memoize it. Regular expressions can be compiled for instance.

*Need to crunch numbers? You might want to check numpy out.

*Many python programs are slow because they are bound by disk I/O or database access. Make sure you have something worthwhile to do while you wait on the data to arrive rather than just blocking. A weapon could be something like the Twisted framework.

*Note that many crucial data-processing libraries have C-versions, be it XML, JSON or whatnot. They are often considerably faster than the Python interpreter.

If all of the above fails for profiled and measured code, then begin thinking about the C-rewrite path.

A: The usual suspects -- profile it, find the most expensive line, figure out what it's doing, fix it. If you haven't done much profiling before, there could be some big fat quadratic loops or string duplication hiding behind otherwise innocuous-looking expressions.
In Python, two of the most common causes I've found for non-obvious slowdown are string concatenation and generators. Since Python's strings are immutable, doing something like this:
result = u""
for item in my_list:
    result += unicode (item)

will copy the entire string twice per iteration. This has been well-covered, and the solution is to use "".join:
result = "".join (unicode (item) for item in my_list)

Generators are another culprit. They're very easy to use and can simplify some tasks enormously, but a poorly-applied generator will be much slower than simply appending items to a list and returning the list.
Finally, don't be afraid to rewrite bits in C! Python, as a dynamic high-level language, is simply not capable of matching C's speed. If there's one function that you can't optimize any more in Python, consider extracting it to an extension module.
My favorite technique for this is to maintain both Python and C versions of a module. The Python version is written to be as clear and obvious as possible -- any bugs should be easy to diagnose and fix. Write your tests against this module. Then write the C version, and test it. Its behavior should in all cases equal that of the Python implementation -- if they differ, it should be very easy to figure out which is wrong and correct the problem.

A: The canonical reference to how to improve Python code is here:  PerformanceTips.  I'd recommend against optimizing in C unless you really need to though.  For most applications, you can get the performance you need by following the rules posted in that link.

A: First thing that comes to mind: psyco. It runs only on x86, for the time being.
Then, constant binding. That is, make all global references (and global.attr, global.attr.attr…) be local names inside of functions and methods. This isn't always successful, but in general it works. It can be done by hand, but obviously is tedious.
You said apart from in-code optimization, so I won't delve into this, but keep your mind open for typical mistakes (for i in range(10000000) comes to mind) that people do.

A: If using psyco, I'd recommend psyco.profile() instead of psyco.full(). For a larger project it will be smarter about the functions that got optimized and use a ton less memory.
I would also recommend looking at iterators and generators. If your application is using large data sets this will save you many copies of containers.

A: Besides the (great) psyco and the (nice) shedskin, I'd recommend trying cython a great fork of pyrex.
Or, if you are not in a hurry, I recommend to just wait. Newer python virtual machines are coming, and unladen-swallow will find its way into the mainstream.

A: A couple of ways to speed up Python code were introduced after this question was asked:

*

*Pypy has a JIT-compiler, which makes it a lot faster for CPU-bound code.

*Pypy is written in Rpython, a subset of Python that compiles to native code, leveraging the LLVM tool-chain.

A: For an established project I feel the main performance gain will be from making use of python internal lib as much as possible.
Some tips are here: http://blog.hackerearth.com/faster-python-code

A: There is also Python → 11l → C++ transpiler, which can be downloaded from here.


text:
Q: TypeError: $(...).autocomplete is not a function I am getting the error TypeError: $(...).autocomplete is not a function when using the following code inside a Drupal module.
jQuery(document).ready(function($) {
        $("#search_text").autocomplete({
            source:results,
            minLength:2,
            position: { offset:'-30 0' },
            select: function(event, ui ) {
                    goTo(ui.item.value);
                    return false;
            }
    });
});

jQuery is definitely loaded, and I have tried using a different variable for $ - any ideas what else might be the problem?
(Edit) Drupal specific answer for autocomplete:
drupal_add_library('system', 'ui.autocomplete');

A: you missed jquery ui library.  Use CDN of Jquery UI or if you want it locally then download the file from Jquery Ui
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet">
<script src="YourJquery source path"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

A: Simple solution:
The sequence is really matter while including the auto complete libraries:
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet">
<script src='https://cdn.rawgit.com/pguso/jquery-plugin-circliful/master/js/jquery.circliful.min.js'></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

A: In my exprience I added two Jquery libraries in my file.The versions were jquery 1.11.1 and 2.1.Suddenly I took out 2.1 Jquery from my code. Then ran it and was working for me well. After trying out the first answer. please check out your file like I said above.

A: Just add these to libraries to your project:
<link href="https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet">
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>

Save and reload. You're good to go.

A: Try this code, Let $ be defined
(function ($, Drupal) {

  'use strict';

  Drupal.behaviors.module_name = {
    attach: function (context, settings) {
        jQuery(document).ready(function($) {
      $("#search_text").autocomplete({
          source:results,
          minLength:2,
          position: { offset:'-30 0' },
          select: function(event, ui ) {
                  goTo(ui.item.value);
                  return false;
          }
        });
        });
   }
  };
})(jQuery, Drupal);

A: In my case, I include an extra jquery library from TAMPERMONKEY script! Disable the script and it works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to extract data from a value text I was inherited a query and part of the query is to remove characters to get certain characters.
So here is the string "Added Keyword (Group) 'ABC-ABC-ABC-ABC' to 'Incoming Fax  - 4/3/2017 1:57:21 PM - From: [Fax Name or #s], To: [2140000000]"
Here is my query:
SUBSTRING(column1,CHARINDEX('to ''',column1)+19,LEN(LTRIM(RTRIM(column1)))-CHARINDEX('''',(column1))-19) as Received

The end result is I just want the Date and Time which is the 4/3/2017 1:57:21 PM
I'm using SSMS 2014

A: you can change +4 or -4 as you need. now you will have your desire output
SUBSTRING(INSTR(column1,'Fax',1)+4,(INSTR(column1,'Form:',1)-INSTR(column1,'Fax',1)-4))

A: Try to make use of below code:
    DECLARE @String NVARCHAR(MAX) ='Added Keyword (Group) ''ABC-ABC-ABC-ABC'' to ''Incoming Fax  - 4/3/2017 1:57:21 PM - From: [Fax Name or #s], To: [2140000000]'
    SELECT SUBSTRING(@String,PATINDEX('%[0-9]%',@String),20)as Received
    --SELECT SUBSTRING(@String,PATINDEX('%[0-9]%',column1),20)as Received


text:
Q: How to solve a network error with a WMS? There is an error with a WebMapService I am using. The error message is depicted in the following image:

The properties of the file are shown in the image below.

Does anyone know how to fix this corrupted file? I am using QGIS version 3.4

A: This is the ArcGIS FeatureServer address you need:
https://data.ogauthority.co.uk/arcgis/rest/services/OGA_Public_WGS84/OGA_Infrastructure_WGS84/FeatureServer/
Preview of the data that are present in this FeatureServer connection:

Preview of the data/extent:


text:
Q: deploy data from sql 2016 backup to azure database I've got backup data from a SQL 2016 server that i want to move/restore onto an azure database.  I'm not seeing an in-house option to do this anywhere, so it looked like the best option was to restore locally, build schema/data scripts for the data, and then run the script on the azure database.
Only problem is that the script that i get back is around 4GB large.  it won't load in sql management studio or azure's own 'query editor' page, and if i deploy via sqlcmd it crashes halfway w/out an easy way to figure out where it crashed at and how to resume from that point.
Are there good methods out there to do this?  I plan on needing to do this several times, so i'd like to get my methods down.  Thank you!

A: You need a live DB to export to Azure, which would require you to restore it locally. Once that is done, you can create a .BACPAC file on Azure storage and restore it, or set up transactional replication, and there are a few other methods as well.
The .BACPAC migration process looks to be the simplest, even if it isn't that simple. Honestly, this page explains it better than I can. Bruno Terklay is at least a minor demigod over at Microsoft, and this is really well written. All credit to him, not me.


text:
Q: Breaking the span's text by ", " I have a  which contains a list of skills separated by a comma and a space. Now with jQuery or with CSS (if possible) I would like to get only the skills without the ", ".
So if I have the skills like: Photographer, Designer
I need to separate those skills and store each skill in an JavaScript array.

A: Given this markup
Skill1, Skill2, Skill3

You could use the split() method
$('#skills').text().split(', ');  // ["Skill1", "Skill2", "Skill3"]

A: use the Javascript function split
var str = $("span").text();
var results = str.split(", ");

http://www.w3schools.com/jsref/jsref_split.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

A: If you need to remove spaces as well then
"Photographer, Designer, Wedding Planners".split(',').map(function(){return arguments[0].replace(/^(\s)*/g, '')});

or else you can simply use
"Photographer, Designer".split(',');

A: Use split :
http://www.w3schools.com/jsref/jsref_split.asp
var skill = "Photgrapher, Designer";
var skillArray = skill.split(", ");
console.log(skillArray); // output ["Photographer", "Designer"]

A: user javascript split function it will return a array
Code like this :
Photographer, Designer

var str = $("span").text();
var results = str.split(", ");

you can use this as results[0] , results[1]
I Hope it will help.


text:
Q: Methods unindentified error in java I wrote a small program consisting of two classes. I am trying to call the methods from the second class but I get an error.
The error is:

Exception in thread "main" java.lang.Error: Unresolved compilation
  problems: The method getSum(int[]) is undefined for the type
  UserInteraction The method getAverage(int[]) is undefined for the type
  UserInteraction at UserInteraction.main(UserInteraction.java:66)

Here's the code of the first class:
import java.util.Scanner;

public class UserInteraction {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int choice = 0;
        String[] subjects = new String[10];
        int grades[] = new int[10];
        double sum = 0.0;
        Grades method = new Grades();

    do
    {
        System.out.println("1. Enter a course name and a grade");
        System.out.println("2. Display all grades");
        System.out.println("3. Calculate the average grade");
        System.out.println("4. Exit program");

        choice = scan.nextInt();

        if ( choice == 1 )
        {
            Scanner scansubjects = new Scanner(System.in);
            Scanner scangrades = new Scanner(System.in);

            System.out.println("Enter 10 subjects and their corresponding grades:");
            System.out.println();

            int i = 0;

            for( i = 0; i < 10; i++ )
            {
                System.out.println("Subject:");

                String temp = scansubjects.nextLine();
                subjects[i] = temp.toLowerCase();

                System.out.println("Grade:");

                grades[i] = scangrades.nextInt();

                if( i == ( subjects.length - 1 ) )
                {
                    System.out.println("Thank you!");
                    System.out.println();
                }
            }
        }

        if ( choice == 2 )
        {
            System.out.println("Subjects" + "\tGrades");
            System.out.println("---------------------");

            for(int p = 0; p < subjects.length; p++)
            {

                System.out.println(subjects[p] + "\t" + "\t" + grades[p]);
            }
        }

        if ( choice == 3 )
        {
              System.out.println("Total of grades: " + getSum(grades));
              System.out.println("Count of grades: " + grades.length);
              System.out.println("Average of grades: " + getAverage(grades));
              System.out.println();
        }

    } while ( choice != 4);

    }

 }

And the second class is:
public class Grades {

    public static double getAverage(int[] array)
    {
        int sum = 0;
        for(int i : array) sum += i;
        return ( ( double ) sum )/array.length;
}

    public static double getSum(int[] array)
    {
        int sum = 0;
        for (int i : array)
        {
         sum += i;
        }
        return sum;
    }

    }

A: You don't need this, because it only has static methods:
Grades method = new Grades(); // <-- delete this line

To call static methods they must be preceded with their class name like this:
System.out.println("Total of grades: " + Grades.getSum(grades));
System.out.println("Count of grades: " + grades.length);
System.out.println("Average of grades: " + Grades.getAverage(grades));

A: Your code doesn't compile. Don't try to execute non-compiling code. Fix all the compilation errors before executing the code. They're visible in the "Problems" view of your Eclipse IDE.

A: You need to call Grades.getSum and Grades.getAverage to get the right result. Also, don't forget to import the Grade class, using the command import Grades; in the beginning of the UserInteraction class.


text:
Q: Accessing UserManager outside AccountController I am trying to set the value of a column in aspnetuser table from a different controller (not accountcontroller). I have been trying to access UserManager but I can't figure our how to do it.
So far I have tried the following in the controller I want to use it in:
    ApplicationUser u = UserManager.FindById(User.Identity.GetUserId());
    u.IsRegComplete = true;
    UserManager.Update(u);

This would not compile (I think because UserManager has not been instantiated the controller)
I also tried to create a public method in the AccountController to accept the value I want to change the value to and do it there but I can't figure out how to call it.
public void setIsRegComplete(Boolean setValue)
{
    ApplicationUser u = UserManager.FindById(User.Identity.GetUserId());
    u.IsRegComplete = setValue;
    UserManager.Update(u);

    return;
}

How do you access and edit user data outside of the Account Controller?
UPDATE:
I tried to instantiate the UserManager in the other controller like so:
    var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
    ApplicationUser u = userManager.FindById(User.Identity.GetUserId());

I the project complied (got a little excited) but when I ran the code I get the following error:
Additional information: The entity type ApplicationUser is not part of the model for the current context.

UPDATE 2:
I have moved the function to the IdentityModel (don't ask I am clutching at straws here) like so:
   public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
        public Boolean IsRegComplete { get; set; }

        public void SetIsRegComplete(string userId, Boolean valueToSet)
        {

            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());
            ApplicationUser u = new ApplicationUser();
            u = userManager.FindById(userId);

            u.IsRegComplete = valueToSet;
            return;
        }
    }

However I am still getting the following:
The entity type ApplicationUser is not part of the model for the current context.

There is also the following class in IdentitiesModels.cs:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

What am I doing wrong here? It feels like I am completely barking up the wrong tree. All I am trying to do is update a column in aspnetuser table from the action of a different controller (i.e not the AccountsController).

A: If you have to get UserManager's instance in another Controller just add its parameter in Controller's constructor like this
public class MyController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;

    public MyController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;;
    }
}

But I have to get UserManager in a class that is not controller !
Any help would be appreciated.
UPDATE
I am considering you are using asp.net core

A: If you're using the default project template, the UserManager gets created the following way:
In the Startup.Auth.cs file, there's a line like this:
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

that makes OWIN pipeline instantiate an instance of ApplicationUserManager each time a request arrives at the server. You can get that instance from OWIN pipeline using the following code inside a controller:
Request.GetOwinContext().GetUserManager<ApplicationUserManager>()

If you look carefully at your AccountController class, you'll see the following pieces of code that makes access to the ApplicationUserManager possible:
    private ApplicationUserManager _userManager;

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

Please note, that in case you need to instantiate the ApplicationUserManager class, you need to use the ApplicationUserManager.Create static method so that you have the appropriate settings and configuration applied to it.

A: I ran into this same problem and modified my code to pass a reference to the UserManager class from the Controller to the Model:
//snippet from Controller
public async Task<JsonResult> UpdateUser(ApplicationUser applicationUser)
{
    return Json(await UserIdentityDataAccess.UpdateUser(UserManager, applicationUser));
}

//snippet from Data Model
public static async Task<IdentityResult> UpdateUser(ApplicationUserManager userManager, ApplicationUser applicationUser)
{
    applicationUser.UserName = applicationUser.Email;
    var result = await userManager.UpdateAsync(applicationUser);

    return result;
}

A: FOR MVC 5

The steps to access usermanger or createUser outside Account controller is easy. Follow the below steps

*

*Create a controller, consider SuperAdminController

*Decorate the SuperAdminController same as the AccountController as below,
private readonly IAdminOrganizationService _organizationService;
private readonly ICommonService _commonService;
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;

public SuperAdminController()
{
}

public SuperAdminController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
{
    UserManager = userManager;
    SignInManager = signInManager;
}

public SuperAdminController(IAdminOrganizationService organizationService, ICommonService commonService)
{
    if (organizationService == null)
        throw new ArgumentNullException("organizationService");

    if (commonService == null)
        throw new ArgumentNullException("commonService");

    _organizationService = organizationService;
    _commonService = commonService;
}

public ApplicationSignInManager SignInManager
{
    get
    {
        return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
    }
    private set
    {
        _signInManager = value;
    }
}

public ApplicationUserManager UserManager
{
    get
    {
        return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
    }
    private set
    {
        _userManager = value;
    }
}

*Create User in Action method
[HttpPost]
public async Task<ActionResult> AddNewOrganizationAdminUser(UserViewModel userViewModel)
{
    if (!ModelState.IsValid)
    {
        return View(userViewModel);
    }

    var user = new ApplicationUser { UserName = userViewModel.Email, Email = userViewModel.Email };
    var result = await UserManager.CreateAsync(user, userViewModel.Password);
    if (result.Succeeded)
    {
        var model = Mapper.Map<UserViewModel, tblUser>(userViewModel);

        var success = _organizationService.AddNewOrganizationAdminUser(model);

        return RedirectToAction("OrganizationAdminUsers", "SuperAdmin");

    }
    AddErrors(result);
    return View(userViewModel);
}

A: If you need access to the UserManager outside of a controller you can use the following:
var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext());
var applicationManager = new ApplicationUserManager(userStore);


text:
Q: Specifying Column Expiration with TTL in cassandra when i insert value with TTL column expiration it gives me some unexpected output
public static void setTTL()
    {
        try
        {
            Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
            Connection con = DriverManager.getConnection("jdbc:cassandra://192.168.1.32/temp");
            String qry = "INSERT INTO userscql3(user_name,password)VALUES('yogesh','temp@123') USING TTL 5";
            Statement smt = con.createStatement();
            smt.executeUpdate(qry);
            System.out.println(" TTL has been set");
        }
        catch(Exception e)
        {
            System.out.println(" : " + e.getMessage());
            e.printStackTrace();
        }
    }

After tracing it what i got
Caused by: UnavailableException()
    at org.apache.cassandra.thrift.Cassandra$execute_cql_query_result.read(Cassandra.java:33485)
    at org.apache.thrift.TServiceClient.receiveBase(TServiceClient.java:78)
    at org.apache.cassandra.thrift.Cassandra$Client.recv_execute_cql_query(Cassandra.java:1402)
    at org.apache.cassandra.thrift.Cassandra$Client.execute_cql_query(Cassandra.java:1388)
    at org.apache.cassandra.cql.jdbc.CassandraConnection.execute(CassandraConnection.java:392)
    at org.apache.cassandra.cql.jdbc.CassandraConnection.execute(CassandraConnection.java:416)
    at org.apache.cassandra.cql.jdbc.CassandraStatement.doExecute(CassandraStatement.java:161)
    ... 3 more

A: Without backtrace it's difficult to response. But you seem to use Cassandra in an another server than the local host. Did you have configured the listen address of Cassandra? By default it listens only on localhost.
EDIT
In cassandra.yaml You have to change the listen_address and rpc_address. Just for the test case you can use: 0.0.0.0
If you check for the UnavailableException in the Cassandra API You can read:

UnavailableException
      Not all the replicas required could be created and/or read.

May be you are using a consistency ALL and one of your nodes is down or something like that.


text:
Q: how to generate an camera app in cordova using Visual studio 15 I am just starting to use cordova in Visual studio 15 in my windows 8 system. I want a basic app which has a button "Take Photo" and it should do so when I run my app in any device, whether andriod, ios or windows phone and finaly store the image in some location. I was reading the cordova docs about it and got fully confused. I also want to know whether the look and feel of the app will change when I  install the apps into various devices.
Please help!

A: You'll want to use the cordova-plugin-camera plugin (as mentioned in the comments) to take a picture. When you use that plugin you can also specify a DestinationType of FILE_URI or NATIVE_URI and it will save the picture to disk.
As for your question about look and feel: Cordova itself doesn't do anything to provide you a user interface that adapts its UI, but you can use a framework like OnsenUI or Ionic to do this.
To experiment with Ionic, and the Camera plugin, try a tutorial I wrote awhile back, which walks you through both of these.


text:
Q: How can I prove that $\lim_{n \to \infty} a_n = 21$ using the $\epsilon - N$ definition? The exercise goes like this...
Let $(a_n) \subset \mathbb{R}$ given by $a_1=\sqrt{21}$ and $a_{n+1}=\sqrt{21a_n}$
a) Find the value of $L=\lim_{n \to \infty} a_n$
b) Prove that $L=\lim_{n \to \infty} a_n$
I managed to prove that the sequence is monotonic increasing and bounded above by $21$ by induction so i can assume that $(a_n)$ converges and show that $L=21$ using a little bit of algebra. But for b) I'm asked to prove the fact using the $\epsilon - N$ definition of limit
I'm used to struggle a lot proving limits for non-recursive sequences using the formal definition of limit, so in this case I don't really know how to proceed.
Any suggestions?

A: Try to show that $a_{n}=21^{1-\frac{1}{2^{n}}}$. What is the limit thereof?

A: You proved that the limit $L$ exists, now only observe that the limit must satisfy
$$L=\sqrt{21 L}$$
because of course $\lim_{n\rightarrow\infty} a_n = \lim_{n\rightarrow\infty}a_{n+1} = \sqrt{21\lim_{n\rightarrow\infty}a_n}$ by the continuity of the square root and multiplication.

A: $$a_n=\sqrt{21\sqrt{21\sqrt{21\sqrt{21\sqrt{21...}}}}}$$
$$\implies \dfrac{ (a_n)^2}{21}=a_n$$
$$\implies a_n=21$$
Or more straightforward,
$$\sqrt{21\sqrt{21\sqrt{21\sqrt{21\sqrt{21...}}}}}=21^\frac{1}{2}\times 21^\frac{1}{4}\times 21^\frac{1}{8} \cdots=21^{\frac{1}{2}+\frac{1}{4}+\frac{1}{8}+\cdots}=21^{\frac{\frac{1}{2}}{1-\frac{1}{2}}}=21.$$


text:
Q: Microsoft Code Analysis. Does Option Infer exist as a rule? I recently ran into an bug caused by the accidental reuse of a variable in a For Each loop in my VB.NET project.
Dim iterator As Integer = 0
For Each iterator In {1, 2, 3}
Next
Console.WriteLine(iterator)

This code will output '3'
I should have used a different variable name for the For Each loop. The loop was modifying the variable which was used for other purposes elsewhere.
I can prevent this behaviour by turning Option Infer off. However this introduces a lot (3000 ish) errors in a moderate sized project I'm working on.
What I would prefer, is a code analysis rule that flags up the use of For Each without a type declaration.
I've had a quick look through the Code Analysis rules provided with Visual Studio 2017, but can't see a rule. I fear I may have to create a custom rule.
Can anyone clarify that a rule does not exist before I start getting my hands dirty with custom rules?


text:
Q: Converting Chinese UTF8 to readable string I'm trying to convert Chinese characters in a XML file to readable Chinese string using javascript, but I'm not sure how to. I have checked other SO posts, and tried the following
unescape(encodeURIComponent('丘'))

but still can't get it to work, and wondering if someone could help?
<utf8>丘</utf8>

A: Neither unescape nor encodeURIComponent (which deal with percent-encoding) will help you with a XML character entity. You just want to parse the XML file! Accessing the DOM then will yield the expected string.


text:
Q: How do I loop pulling in all the folders in a directory, run the same code on them and get summary output files? I have a directory with a folder for each individual patient on a study, but multiple files within each folder for that patient. I want to run the same code in R for each folder and create a summary file.
so for example:
setwd("~/pt1")

##pull in files
T1<-read.csv('T1.csv')
T2<-read.csv('T2.csv')
T3<-read.csv('T3.csv')
T4<-read.csv('T4.csv')

## lots of code here ##

--> outputsummaryfile

Repeat for 80 more folders(patients).
I know how to create a function and pull in and run multiple files, but I'm stuck on how to pull in multiple folders and run a function on multiple files within that folder.
Any help?

A: The following is an quick way for limited files.
all_files_list<-list.files('path to folder',full.names = TRUE,recursive=TRUE,include.dirs=TRUE) # this will now be a list of all files with full paths.

main_df<- data.frame() # your main dataframe
for(file in all_files_list){ # loops the file listing
  tmp_df <- read_tsv(file) #reads each file
  #process tmp_df
  main_df<- bind_rows(tmp_df) # merge to main dataframe provided same set of columns
}

Note that since all_files_list is a list and if it will contain large number of files, you can user purrr package to streamline it.
Update1:
Another option is to use purrr package and read all files into a list of dataframes as follows:
list_of_dataframes<-purrr::map(all_files_list,read_csv,id="filename") #ID column will have the filenames.

Then you could loop your all_files_list and process each dataframe as per your needs.

A: I suggest you read about purrr::map. This video also shows its use (https://www.youtube.com/watch?v=bzUmK0Y07ck&t=1598s) and there is an example about reading multiple files.

A: You can list directories with list.dirs, then loop the dir's
dirs <- list.dirs(path = "[...]", recursive = FALSE)
for (i in 1:length(dirs)) {
  files <- list.files(path = "[...]")
  do.the.magic.on(files[i])
}


text:
Q: No color fill in cell in different file I have a Macro with this code it runs fine it the file I saved it in, but when i try to run it on another excel file the code still runs but in the ChangeColor method, it doesn't fill the cells. It runs step by step fine it just doesn't fill the color. Here is my code.
Sub ChangeColor()

'---------------------------ChangeColor-------------------------

Dim rCell As Range
Worksheets("MSS Open Purchase Orders").Select
With Sheet1
    For Each rCell In .Range("N4", .Cells(.Rows.Count, 14).End(xlUp)).Cells
        If rCell.Value <= Date Then
            rCell.Interior.Color = vbRed
             ElseIf rCell.Value <= Date + 7 Then
            rCell.Interior.Color = RGB(255, 102, 0)
        ElseIf rCell.Value <= Date + 30 Then
            rCell.Interior.Color = vbYellow

        Else
            rCell.Interior.Color = vbGreen
        End If
    Next rCell
End With

'------------------------------I-------------------------------

 Worksheets("I").Select
With Sheet2
    For Each rCell In .Range("N2", .Cells(.Rows.Count, 14).End(xlUp)).Cells
        If rCell.Value <= Date Then
            rCell.Interior.Color = vbRed
            ElseIf rCell.Value <= Date + 7 Then
            rCell.Interior.Color = RGB(255, 102, 0)
        ElseIf rCell.Value <= Date + 30 Then
            rCell.Interior.Color = vbYellow

        Else
            rCell.Interior.Color = vbGreen
        End If
    Next rCell
 End With

 '------------------------------O-------------------------------
   Worksheets("O").Select
With Sheet3
    For Each rCell In .Range("N2", .Cells(.Rows.Count, 14).End(xlUp)).Cells
        If rCell.Value <= Date Then
            rCell.Interior.Color = vbRed
            ElseIf rCell.Value <= Date + 7 Then
            rCell.Interior.Color = RGB(255, 102, 0)
        ElseIf rCell.Value <= Date + 30 Then
            rCell.Interior.Color = vbYellow

        Else
            rCell.Interior.Color = vbGreen
        End If
    Next rCell
 End With

   '------------------------------E-------------------------------
   Worksheets("E").Select
With Sheet4
    For Each rCell In .Range("N2", .Cells(.Rows.Count, 14).End(xlUp)).Cells
        If rCell.Value <= Date Then
            rCell.Interior.Color = vbRed
             ElseIf rCell.Value <= Date + 7 Then
            rCell.Interior.Color = RGB(255, 102, 0)
        ElseIf rCell.Value <= Date + 30 Then
            rCell.Interior.Color = vbYellow

        Else
            rCell.Interior.Color = vbGreen
        End If
    Next rCell
 End With

  '------------------------------C-------------------------------
    Worksheets("C").Select
With Sheet5
    For Each rCell In .Range("N2", .Cells(.Rows.Count, 14).End(xlUp)).Cells
        If rCell.Value <= Date Then
            rCell.Interior.Color = vbRed
             ElseIf rCell.Value <= Date + 7 Then
            rCell.Interior.Color = RGB(255, 102, 0)
        ElseIf rCell.Value <= Date + 30 Then
            rCell.Interior.Color = vbYellow

        Else
            rCell.Interior.Color = vbGreen
        End If
    Next rCell
 End With

'------------------------------------Sort---------------------------------------

 ActiveWorkbook.Worksheets("MSS Open Purchase Orders").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("MSS Open Purchase Orders").Sort.SortFields.Add Key _
    :=Range("N4"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
With ActiveWorkbook.Worksheets("MSS Open Purchase Orders").Sort
    .SetRange Range("N4:N58")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
 End With

End Sub

Any help is appreciated just started using vba in excel

A: There are a number of ways to do this, but if the workbook you want your code to work on is the active workbook, you can reference it as in this example
ActiveWorkbook.Worksheets("MSS Open Purchase Orders").Select

To @Zeno point, you can probably dispense with the
With Sheet1 and End With

etc. and remove the .s.

A: I see two main issues with your code

*

*You have repeated the code many number of times. You could use a common sub and keep on calling that.

*You should avoid the use of  .Select/.Activate/Selection/Activecell/Activesheet/Activeworkbook You may want to see THIS
Here is how your code can be optimized. This is just an example. Please amend it to suit your needs.
UNTESTED
Sub ChangeColor()
    Dim wb As Workbook, ws As Worksheet

    '~~> Here change it to the relevant workbook
    Set wb = ThisWorkbook

    '~~> Here set the worksheets you want to work with
    Set ws = wb.Worksheets("MSS Open Purchase Orders")

    '~~> Do the coloring
    ColorCells ws

    '~~> Again set the worksheets you want to work with
    Set ws = wb.Worksheets("I")

    '~~> Do the coloring
    ColorCells ws

    '~~> Again set the worksheets you want to work with
    Set ws = wb.Worksheets("O")

    '~~> Do the coloring
    ColorCells ws

    '
    '~~> And So On
    '
End Sub

'~~> Common Sub to color the sheets
Sub ColorCells(sHt As Worksheet)
    Dim rCell As Range

    With sHt
        For Each rCell In .Range("N2", .Cells(.Rows.Count, 14).End(xlUp)).Cells
            If rCell.Value <= Date Then
                rCell.Interior.Color = vbRed
            ElseIf rCell.Value <= Date + 7 Then
                rCell.Interior.Color = RGB(255, 102, 0)
            ElseIf rCell.Value <= Date + 30 Then
                rCell.Interior.Color = vbYellow
            Else
                rCell.Interior.Color = vbGreen
            End If
        Next rCell
    End With
End Sub


text:
Q: One to One relationship in MySQL I'm trying to make a one to one relationship in a MySQL DB. I'm using the InnoDB engine and the basic table looks like this:
CREATE TABLE `foo` (
  `fooID` INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` TEXT NOT NULL
)

CREATE TABLE `bar` (
  `barName` VARCHAR(100) NOT NULL,
  `fooID` INT(11) NOT NULL PRIMARY KEY,
  CONSTRAINT `contact` FOREIGN KEY (`fooID`) REFERENCES `foo`(`fooID`)
)

Now once I have set up these I alter the foo table so that the fooID also becomes a foreign key to the fooID in bar.
The only issue I am facing with this is that there will be a integrity issue when I try to insert into either.
I would like some help, thanks.

A: A true one-to-one relationship in a relational database is best done by adding a column; If the data in these two tables is always required for every record, then the table should be defined as foo (fooID, name, barname).

A: You can deffered the checking of constraint to the end of transaction. However I haven't find anything for MySQL (it is not the most advanced database). For PostgreSQL (for other the syntax varies):
ALTER TABLE foo ADD FOREIGN KEY (fooID) REFERENCES bar DEFERRABLE;

Which means that constraint will be checked at the end of transaction.
If you have to use MySQL use Chris Shaffer answer.

A: I found a "hacky" solution to this, the variable foreign_key_checks can be used.
If one alters the fooID in foo to have a foreign key constraint in bar, one can then insert that as such
SET foreign_key_checks = 0;
INSERT...;
INSERT...;
SET foreign_key_checks = 1;

As I said "hacky" and I would probably not to this on a production system.


text:
Q: jquery - expand google map when scroll down So, i have split page:
one side - sections with texts and locations
other side - google map with pins referring to the sections
I add script that expand the map height when you scroll down, but it's not so intuitive.
Is there any better code than can open expand the map while user scroll down?
This is my current code:
// change map size when scroll down
$(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= 450) {
        $("#map-warp").addClass("change-map-canvas");   // removed the . from class
        $("#map-warp").css("margin-top", "40px"); ;     // change margin from top for close infoWindow button
    } else {
        $("#map-warp").removeClass("change-map-canvas");  // removed the . from class
        $("#map-warp").css("margin-top", "10px"); ;
    }
});

A: bind window scroll , whene scroll to end  trigger  if = true
$(window).scroll(function() {
              //scroll in the end
             if (document.documentElement.scrollHeight = document.documentElement.scrollTop + document.documentElement.offsetHeight)) {
               //dosomething
               }

        });


text:
Q: redirecionar todas ar requisições para a index.php e pegar o valor passado pela URL Preciso redirecionar todas as requisição para a index.php para que possa inserir no body o arquivo .php correspondente a url.
Exemplo quando acesso o www.dominio.com.br/esqueceu-senha carrego no index a pagina esqueceu-senha.php.
No index tem as tags <!doctype html>     , todos css,  e tambem todos os js. No da tag body carrego os arquivos .php. Simliar a uma spa.
criei o arquivo htacess conforme abaixo
 RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [QSA]

<!doctype html>
<html lang="pt-BR">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Plus-Sese-Br</title>

    <!-- Bootstrap core CSS -->
    <link href="http://localhost/app/css/bootstrap.min.css" rel="stylesheet">
    <link href="http://localhost/app/vendor/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<body>

<?php
$url = (isset($_GET['url'])) ? $_GET['url']:'login.php';
$url = array_filter(explode('/',$url));
$file = $url[0].'.php';
if(is_file($file)){
    include_once $file;
}else{
    include_once 'login.php';
}

?>

<script type="text/javascript" src="http://localhost/plus-outbound/js/jquery-3.5.1.min.js"></script><script type="text/javascript" src="http://localhost/plus-outbound/js/bootstrap.min.js"></script>
</body>

</html>

se o arquivo passado na url não existir é redireionado para login . Se o arquivo na url não existir esta funcionando. O problema esta quando existe a url / arquivo  não esta carregando entre a tag body como o exemplo. Estou usando url absulta em tudo mas quando a url passada existe carrega o arquivo somente este arquivo sem body css e js.


text:
Q: Flutter: How to set line height property of text to ThemeData How can I set the line-height globally inside ThemeData?
theme: ThemeData(
       brightness: Brightness.light,
       accentColor: myAccentColor,
       primaryColor: myPrimaryColor,
       fontFamily: 'Ubuntu',
       buttonTheme: ThemeData.light().buttonTheme.copyWith(
            buttonColor: myPrimaryColor,
            textTheme: ButtonTextTheme.primary,
            shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(5)),
       ),
       scaffoldBackgroundColor: myBackgroundWhite,
       cardColor: myBackgroundWhite,
       textSelectionColor: myGreyTextColor,
       cursorColor: myAccentColor,
       cupertinoOverrideTheme: CupertinoThemeData(
          primaryColor: myAccentColor,
       ),
       errorColor: myErrorColorRed,
)

A: We cant set the line-height (property name: height) directly from ThemeData.
The best practice for handling text style is by using material type system guidelines. See the section "Material Text Scale: Modernizing Flutter Text Theming" from here.
So then on global ThemeData, you can use
theme: ThemeData(
          brightness: Brightness.light,
          accentColor: flujoAccentColor,
          primaryColor: flujoPrimaryColor,
          fontFamily: 'FiraSans',
          textTheme: TextTheme(
              headline5: TextStyle(
                fontSize: 24.0,
                fontWeight: FontWeight.w700,
                fontStyle: FontStyle.normal,
              ),
              bodyText1: TextStyle(
                fontSize: 16.0,
                fontStyle: FontStyle.normal,
                letterSpacing: 0.5,
              ),
              bodyText2: TextStyle(
                fontSize: 14.0,
                fontStyle: FontStyle.normal,
                letterSpacing: 0.25,
                height: 1.5,
              ),
              subtitle1: TextStyle(
                fontSize: 16.0,
                fontStyle: FontStyle.normal,
                letterSpacing: 0.15,
              ),
              subtitle2: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w400,
                fontStyle: FontStyle.normal,
              ),
              caption: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w400,
                fontStyle: FontStyle.normal,
              ),
              overline: TextStyle(
                fontSize: 10,
                fontWeight: FontWeight.w400,
                letterSpacing: 0.25,
                height: 1.5,
                fontStyle: FontStyle.normal,
              )),

Like this and on a Text widget, apply it like:
Text(
    "Hello world!",
     style: Theme.of(context).textTheme.bodyText1.copyWith(color: Colors.teal,),
);


text:
Q: Point Solar Radiation Computation using ArcPy? I want to use ArcGIS Point Solar Radiation tool to compute the solar radiation for more than 1000 data points.  The table for the shapefile point data looks like this:

Hour represent the time of start and ending time of collection.  The julian column is the julian day.
I believe ArcGIS provides the code below to work for one row only:

  # Import system modules
import arcpy
from arcpy import env
from arcpy.sa import *

# Set environment settings
env.workspace = "C:/sapyexamples/data"

# Set local variables
inRaster = "elevation"
inPntFC = "observers.shp"
outFeatures = "c:/sapyexamples/output/outglobal1.shp"
latitude = 35.75
skySize = 200
timeConfig = TimeWithinDay(183, 16, 16)
dayInterval = 14
hourInterval = 0.5
zFactor = 0.3048
calcDirections = 32
zenithDivisions = 8
azimuthDivisions = 8
diffuseProp = 0.3
transmittivity = 0.5
outDirectRad = "C:/sapyexamples/output/outdirectrad1.shp"
outDiffuseRad = "C:/sapyexamples/output/outdiffuserad1.shp"
outDirectDur = "C:/sapyexamples/output/outduration1.shp"

# Execute PointsSolarRadiation...
PointsSolarRadiation(inRaster, inPntFC, outFeatures, "", latitude, skySize,
                     timeConfig, dayInterval, hourInterval, "INTERVAL",
                     zFactor, "FROM_DEM", calcDirections, zenithDivisions,
                     azimuthDivisions,"STANDARD_OVERCAST_SKY", diffuseProp,
                     transmittivity, outDirectRad, outDiffuseRad, outDirectDur)

How could I edit the code so that it would calculate the solar radiation per row (or per point sample)?
I want to keep most of the values constant, except for:
timeConfig = TimeWithinDay(183, 16, 16)

That means that in every run, it will only change the 'Julian' day and the 'hour' and keep the rest of the values the same. For example: (183, 16, 16) should be (269, 18, 18) when the code runs to calculate the third row.
In the end, once all the rows are calculated, a new column would be added for the solar radiation of each row.
I am new to coding.


text:
Q: Getting 404 not found when calling Asp.Net Core MVC action from Jquery I am trying to call index (with Post decorated) in Home controller and post below data (in json format), but its giving me 404 not found.
HomeController.cs
[HttpGet]
public IActionResult Index()
{
    return View();
}

[HttpPost]
public async Task<IActionResult> Index(LoginModel model)
{
    //login check code
}

client.js
loginUser: function (url, object) {
        var data = JSON.stringify(object);
        $.post(url, data, function (res) {
            if (!res.Message) {
                window.location.href = "/Dashboard/Dashboard";
            }
        });
    }

$('#login_id').click(function(){
    var loginModel=new Object();
    loginModel.Username= "username";
    loginModel.Password = "password";

    loginUser("Home/Index", loginModel)
});

In above JS code, there is no hit to Index action when $.Post gets execute. Tried with Postman as well as ARC client both.

Thanks

A: just change this line

loginUser("Home/Index", loginModel)
to this
loginUser("/Home/Index", loginModel)

A: $('#login_id').click(function(){
    var loginModel=new Object();
    loginModel.Username= "username";
    loginModel.Password = "password";

    loginUser("Home/Index", loginModel)
});


text:
Q: How to pass a key to a service app through Azure application's gateway? I have configured an application gateway in the Azure portal and I have added a function app in the backend pool. The authorization level on one of the function in the function app is set to "function", now I want to pass the function key of this function using application gateway instead of passing it through URL.
for example- http://20.0.0.1/api/HttpExample?code=XV2Js97D/Zy5aw6th2hr7iLzFbBiuZ4RfdKuT8nA==
Where, 20.0.0.1 is application gateway public IP and
/api/HttpExample?code=XV2Js97D/Zy5aw6th2hr7iLzFbBiuZ4RfdKuT8nA== is function URL
Is there any way to make this happen?

A: Please find the below two ways used to pass a key to function app from API and get the output without key in the URL.
Method 1:
Passing the Key to the service App in the form of Headers.
Steps:

*

*Azure Portal > API Management Service > Your API > Your Service App >
Select Get HttpTrigger > Click on Test Pane

*There you can copy the key -value or you can also copy from the
subscriptions pane in your API Service.

*Pass these values to the header section in the developer portal of
your API, as shown below:

Then the output will be:

Method 2:

*

*Go to Azure Portal > API Management Services > Your API > APIs pane

*Select your service app ( I selected Function App)

*Click on Settings > uncheck the box option 'Subscription required' on Subscription Menu and click on Save.

Note: Make Sure you have removed the key in the headers section.
Now run your API in developer portal, it should show 200 response code as below:

*

*Unchecking the subscription key in the settings menu should not be
done on production side. It can be used for Dev and Testing Purposes.

Passing the key to a service app in the form of header is one of the best way, instead in the URL.


text:
Q: What's the idiomatic way of mapping Doctrine SQL Query Builder (DBAL) to types? I am facing a challenge while working on type-mapping for a query constructed via Doctrine SQL Query Builder (from DBAL, not ORM) using MySQL 8.
The executed query returns the following three columns from the database:

*

*user_id (bigint column in table)

*start_at (datetime column in table)

*ends_at (datetime column in table)

But by my current implementation like below (simplified for example), no values are mapped to their PHP counterparts.
        $queryBuilder = $this->entityManager->getConnection()->createQueryBuilder();

        $result = $queryBuilder
            ->select([
                'st.user_id',
                'st.starts_at',
                'st.ends_at',
            ])
            ->from('some_table', 'st')
            ->execute()
            ->fetchAll();

The result returned by the fetchAll() method gives me back an array<string, string>, effectively leaving me with string values for user_id instead of int and string for start_at/ends_at instead of native PHP DateTime(Immutable) objects.
Of course I can do the type mapping/casting myself by iterating over/mapping the result fetched from the database, but I wonder if there is another way to do it in Doctrine (maybe by registering som kind of ResultSetMapping or similar for SQL Query Builder).
If this is indeed possible, what's the idiomatic way?
Thanks.

A: Did you map the data / columns for the object you are trying to fetch? While using doctrine in symfony projects(and I guess pure PHP projects too and its explained here you are pointing to the entity class in from() method, so for example if your mapped object is Acme\Model\SomeObject you need to pass the object namespace and name to the from() method ->from('Acme\Model\SomeObject', 'alias') then it should automatically populate the object with values (if there are setters or if properties are public)


text:
Q: Run python parallel processes I have more than 20 independent scripts that I need to execute I don't know exactly how many processes I can execute in parallel as good practice:
import os
import glob
from multiprocessing import Pool

processos = (
    'p1.py',
    'p2.py',
    'p3.py',
    'p4.py',
    'p5.py',
    'p6.py',
    'p7.py',
    'p8.py',
    'p9.py',
    'p10.py',
    'p11.py',
    'p12.py',
    'p13.py',
    'p14.py',
    'p15.py',
    'p16.py',
    'p17.py',
    'p18.py',
    'p19.py',
    'p20.py',
    'p21.py',
    'p22.py',
    'p23.py',
    'p24.py'
)
def roda_processo(processo):
    os.system('python {}'.format(processo))

pool = Pool(processes=24)
pool.map(roda_processo, processos)

Would you like to know the most effective way to run these scripts.
Detail: These processes will run with schedules.

A: Why not use shell?
seq 1 24 | xargs -L1 -I{} -P`nproc` python p{}.py
 -P maxprocs
         Parallel mode: run at most maxprocs invocations of utility at
         once.

 nproc
          print the number of processing units available

A: Using GNU Parallel you can do:
parallel python ::: p*.py

It will spawn one process per CPU thread.
If your processes only use 30% CPU power (e.g. maybe it is waiting for the network the rest of the time) it makes sense to spawn 3 times as many:
parallel -j300% python ::: p*.py


text:
Q: Kafka js quick example errors I have this very simple code which is supposed just to transmit a simple message from producer to consumer using Kafka in local host which come from the official GitHub
const { Kafka } = require('kafkajs')

const kafka = new Kafka({
  clientId: 'my-app',
  brokers: ['kafka1:9092', 'kafka2:9092']
})

const producer = kafka.producer()
const consumer = kafka.consumer({ groupId: 'test-group' })

const run = async () => {
  // Producing
  await producer.connect()
  await producer.send({
    topic: 'test-topic',
    messages: [
      { value: 'Hello KafkaJS user!' },
    ],
  })

  // Consuming
  await consumer.connect()
  await consumer.subscribe({ topic: 'test-topic', fromBeginning: true })

  await consumer.run({
    eachMessage: async ({ topic, partition, message }) => {
      console.log({
        partition,
        offset: message.offset,
        value: message.value.toString(),
      })
    },
  })
}

run().catch(console.error)

When I execute this code using node index.js (which is this file) I get many of these two errors :
{"level":"ERROR","timestamp":"2021-03-29T12:01:00.633Z","logger":"kafkajs","message":"[Connection] Connection error: getaddrinfo ENOTFOUND kafka1","broker":"kafka1:9092","clientId":"my-app","stack":"Error: getaddrinfo ENOTFOUND kafka1\n    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26)"}

{"level":"ERROR","timestamp":"2021-03-29T12:01:00.635Z","logger":"kafkajs","message":"[BrokerPool] Failed to connect to seed broker, trying another broker from the list: Connection error: getaddrinfo ENOTFOUND kafka1","retryCount":0,"retryTime":323}

So it looks like the first lines defining the broker on local port 9092 are not working I guess? But I don't know how to correct this. Could you help me please?

A: Thanks to OneCricketeer I've found that I havn't properly launch a local kafka server so the first lines could not work.
Many thanks to him !


text:
Q: Error with validate() in AbstractFormValidator Wicket I tried to add some validations to DateTextField as follows:
      IFormValidator validator = new AbstractFormValidator() {
        public FormComponent<?>[] getDependentFormComponents() {
            return new FormComponent[] { dateTextField };
        }

        public void validate(Form<?> form) {
            Date date = (Date) dateTextField.getConvertedInput();

            if(date == null){
                error(getDependentFormComponents()[0],"Date of Collection is empty.");
            }
            else{
                if (date.before(getTodayDate(Boolean.TRUE))){
                    error(getDependentFormComponents()[0],"The range of the Date of Collection is invalid.");
                }
            }
        }
    };

    form.add(validator);

The validations are working absolutely fine but the output of error message appeared as below:
  Could not locate error message for component: CreatePrintingJob$3@form:dateOfCollection and error: [ValidationError message=[null], keys=[Date of Collection is empty., CreatePrintingJob$4], variables=[[label0=dateOfCollection],[name0=dateOfCollection],[input0=]]]. Tried keys: dateOfCollection.Date of Collection is empty., Date of Collection is empty., dateOfCollection.CreatePrintingJob$4, CreatePrintingJob$4.

Why could not the error message be located?

A: It is because you are supposed to give a property key allowing Wicket to find the correct error message in the property bundle of your component/page/application.


text:
Q: how to add Angular $http event listeners I'm currently uploading a file in an angular directive with...
var fd = new FormData();
fd.append("uploadedFile", scope.uploadedFile);

var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListenter("load", uploadComplete, false);
xhr.addEventListenter("error", uploadFailed, false);
xhr.addEventListenter("abort", uploadCanceled, false);
xhr.open("POST", scope.postUrl);
scope.uploadInProgress = true;
xhr.send(fd);

function uploadProgress(e){
  scope.$apply(function(){
    if(e.lengthComputable){
      scope.progress = Math.round(e.loaded * 100 / e.total);
    } else {
      scope.progress = 'unable to compute';
    }
  });
 }

 ...

Can this snippet be refactored using $http provider?  i can't figure out how to keep my event listeners.

A: Short answer: soon you will be able to, but not yet exactly as you have requested.
There are a few options being discussed to build in the functionality - exposing the base xhr object, or allowing callbacks to be set for the methods.
See https://github.com/angular/angular.js/issues/1934 specifically - progress events won't work for the moment.
In the meantime, I would recommend creating an object manually and using $apply to update your scope, just as you have.
See this question for more details on how to use a service to set up at least start and stop events you can catch - but no luck on the progress.
AngularJS: need to fire event every time an ajax call is started

A: For now you can use angular-file-upload directive which is simple/lightweight and supports file drop and upload progress.
It uses a shim to be loaded before the angular to be able to access XHR private object in angular and attach upload event listener to it.
<div ng-controller="MyCtrl">
  <input type="file" ng-file-select="onFileSelect($files)" multiple>
</div>

JS:
//inject angular file upload directive.
angular.module('myApp', ['angularFileUpload']);

var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
  $scope.onFileSelect = function($files) {
    for (var i = 0; i < $files.length; i++) {
      var $file = $files[i];
      $upload.upload({
        url: 'my/upload/url',
        file: $file,
        progress: function(evt){
           $scope.progress = parseInt(100.0 * evt.loaded / evt.total);
        }
      }).then(function(data, status, headers, config) {
        // file is uploaded successfully
        console.log(data);
      });
    }
  }
}];


text:
Q: how to rebalance mongodb after adding a shard How do I rebalance mongodb data after adding a new shard
I do not think it does it automatically?
I could not find anything, it's there support for this?
Also the key for my shards is unique
Thanks,

A: When you add a new shard, MongoDB should automatically start re-balancing data according to your shard key.
However, it will not start re-balancing until there is a certain amount of data. So if you don't have few gigs of data, you probably won't see any re-balancing.
If you have lots of data and you add a shard and it never starts migrating data, then it's time to go to the google group and start asking questions. As it stands, lots of people are using auto-sharding and it is definitely re-balancing automatically.
I'm not saying you haven't found a bug, just that you'll need a lot more data to back that up.


text:
Q: Multiple user stream to one StockTwits widget Is it possible to aggregate multiple user stream into a StockTwits widget or is it limited to one ?

A: It's just limited to one username or symbol. Here's the widget documentation.


text:
Q: AJAX PHP variable to populate form field jquery Trying to find a solution any help or pointers to get me in the right direction would be appreciated.
Scenario: I have a HTML form that I use to modify a mysql database with PHP. I want when the page loads it has a field on this form that pulls from the database which is easy enough with
<input type="text" name="inputTag" value="<?php echo $people['Service Tag']; ?>"     onblur="this.value=this.value.toUpperCase()" />

That would be to easy.
I have a separate php page say... test.php that scrapes text off of a page and stores in a variable. With something similar to this
<?php
$file_string = file_get_contents('http://blahblah.com/');
preg_match("/<title>Product Support for (.+)\| HP/i", $file_string, $matches);
$print = "$matches[1]";
?>

I need something that will allow me to populate the form field with the php variable $print from the test.php and put that into the value of the inputTag field only if the field is clicked
Basically I dont want it to run the file_get_contents everytime my page loads because it is slow and not always needed. But I want the form field to display what is currently stored in the database onload but allow you to click that form field which triggers the screen scrape php file and echos the $print variable from that php file in the text field of the form so that I can then submit the form after im finished filling it out.
I am kind of a noob when it comes to this stuff but can get around some... Best I could figure out is that I need to make a AJAX call with something like this.

Load the initial page as usually which pulls the current info from the database.
Then maybe add some javascript with a onclick event that clears the field and populates it with the variable from the ajax call?
Is this even possible or am I living in a dreamland? sorry if this is confusing I can try to clarify if needed.
thanks!
UPDATE*
    Update Field

this is what I finally used to to get it to work thanks

A: <input type="text" id="serviceTag" name="inputTag" value="<?php echo $people['Service Tag']; ?>"/>
Update Field

In your php file, you should output/echo out just that string/value that you want to be inserted into the input field


text:
Q: If $f: \mathbb R^n \to \mathbb R^n$ satisfies $\|f(x - y)\| = \|f(x) - f(y)\|$, is $f$ additive? Question
Main question:

Let $\| \cdot \|$ be a norm on a finite-dimensional real vector space $V$. If $f : V \to V$ is a function satisfying
  $$
\| f(x-y)\| = \|f(x) - f(y)\|
$$
  for all $x, y \in V$, does it follow that $f$ is additive? I.e., does it follow that $f(x + y) = f(x) + f(y)$ for all $x, y$?

Follow-up:

Does the answer change depending on the choice of $\| \cdot \|$? In particular, what if $\| \cdot \|$ is an inner product norm?

Background
Last week, user C.F.G. asked a very similar question, to which the answer was "no for trivial reasons": they asked whether the function $f$ was necessarily linear, but clearly all additive functions satisfy the condition, and there are non-linear additive functions. User Charlie Cunningham pointed out in the comments that the question is actually interesting if you remove the trivial reasons. Because the question had been answered, I tried to get an answer to the non-trivial question myself. The original question included the requirement that the vector space be finite-dimensional; I removed this requirement because it erroneously struck me as an irrelevant restriction (I thought you could just take the subspace containing $x, y, f(x), f(y)$ to get a finite-dimensional $V$). (The functional relation in those questions has a different form, but this is equivalent the formulation above, as pointed out by user Omnomnomnom in comments.)
However, we then got a negative answer to my question -- an example of a non-additive $f$ satisfying the condition -- where the infinite-dimensionality of $V$ was crucial. This has left us with the tantalizing option that the finite-dimensionality of $V$ was crucial to the resolution of the question. I did not want to ask yet another very similar question here, but I also did not want to edit my question, as it had gotten a correct answer that did not deserve to be made irrelevant. Maybe third time's the charm?

A: The claim does not hold. The classical counterexample mentioned in the linked answer by GEdgar works.
Let $V=\mathbb R^2$ supplied with the max-norm. Define $f$ by
$$
f(x) = (x_1, |x_1|).
$$
Then
$$
\|f(x-y)\| = |x_1-y_1|
$$
and
$$
\|f(x) - f(y)\| = \max (|x_1-y_1|, \ \big||x_1|-|y_1|\big|) = |x_1-y_1|,
$$
so the condition is satisfied but $f$ is not additive.


text:
Q: How to select the left audio channel with ffmpeg and downmix to mono? I have an old "stereo" movie as a mp4 file.
The sound is only in the left channel, the right channel is silent.
I'd like to use ffmpeg to copy the video stream :
ffmpeg -hide_banner -i video.mp4 -c:v copy ...

and convert the audio to mono by selecting only the left channel :
-map_channel 0.1.0 -map_channel -1

But that didn't change anything :-(
What is the correct ffmpeg command line for that ?
Is it also possible to do that whithout re-encoding ?

A: There are at least two methods to select the left audio channel and output as mono.
Using -map_channel
Assuming the input only contains audio:
ffmpeg -i input -map_channel 0.0.0 output

*

*The first number is the input file id: you only have one input so that will be 0. The second number is the stream specifier: if the audio is the second stream, such is often the case in a typical video file, then you would use 1 instead. The third number is the channel number: in a stereo input the first channel is usually the Front Left, and the second is usually the Front Right.

*If you want the right channel instead use -map_channel 0.0.1.

*If the input contains video, then the audio will likely (but not always) be listed as the second stream, so you would need to use 0.1.0 instead.
Using pan audio filter
ffmpeg -i input -af "pan=mono|c0=FL" output

*

*Alternatively, you could use pan=mono|c0=c0.

*If you want the right channel instead use pan=mono|c0=FR (or pan=mono|c0=c1).

Also see

*

*pan audio filter documentation

*FFmpeg Wiki: Audio Channel Manipulation

A: @LordNeckbeard : Found the reason why my resulting file had only audio on the left channel like my source file.
It was because I used :
-map_channel 0.1.0 -map_channel -1
which muted the second audio channel, instead of just using :
-map_channel 0.1.0
Thanks for your help :)


text:
Q: Why do batches behave different in Production than in a Sandbox Recently I observed serious and undocumented differences in the runtime behaviour of Sandbox vs. Production orgs, e.g.:

*

*Batches (same code, same data) run faster in the Sandbox

*Same Batch in Sandbox sometimes takes 1h and sometimes 6h.

*Batches abort only in Production due to SOQL running to long

This is really problematic as one cannot rely on code to work in a Sandbox to also work in Production.
Salesforce Support seems not to be able or willing to explain that behavior.So I want to ask you for your experiences with that.

A: One reason is in Production you may have huge data so the SOQL may give read time out error as you might not have indexed your fields .
Second reason is batch process is async in nature and it will be executed only when resources at salesforce servers are free.

A: I'm not sure if it will be the case for you, but in our Sandbox quite often there is considerably less activity. For example, the scheduled jobs may be switched off, the only users are a handful of developers, inbound web services aren't being hit because all that is pointed at Production.
In that case there is a lot less demand for resources in the Sandbox and so the performance may be better.


text:
Q: Jail only a specific user with vsftpd I'm using both Redhat and CentOS. When I do followings:
 # vi /etc/vsftpd/vsftpd.conf
 chroot_local_user=YES
 # service vsftpd restart

Then all users are jailed in their home directory.
How can I jail a specific user only?

A: You have 2 options:
chroot_local_user=YES
chroot_list_enable=YES
chroot_list_file=/etc/vsftpd/nonchroot.list

Where file /etc/vsftpd/nonchroot.list should contail the users you don't want to chroot.
OR
chroot_list_enable=YES
chroot_list_file=/etc/vsftpd/chroot.list

Where the file /etc/vsftpd/chroot.list should contain the users you want to be chrooted to their home. By default all other users should have access to the / (root).


text:
Q: Open physical file on the server using ASP.NET I want to open a physical file on the server on HyperLink click.
<asp:HyperLink ID="HyButton1" Target="_blank" NavigateUrl='<%#Eval("FullPath") %>' runat="server" Text="Open File" ></asp:HyperLink>

"FullPath" is like "E:\PINCDOCS\Mydoc.pdf"
Currently in Chrome i'm getting the error.

Not allowed to load local resource:

Can this be done or any other alternative solution?

A: The physical file should be located within an IIS Web Site, Virtual Directory or Web Application.  So you'd need to create a virtual directory to E:\PINCDOCS.  See here for instructions: http://support.microsoft.com/kb/172138
Then in your code behind you can use code like: http://geekswithblogs.net/AlsLog/archive/2006/08/03/87032.aspx to get a Url for the physical file.

A: //SOURCE
<asp:HyperLink ID="HyButton1" Target="_blank" NavigateUrl='<%#ful_path(Eval("")) %>' runat="server" Text="Open File" ></asp:HyperLink>//ful_path is c# function name

//C#:
protected string ful_path(object ob)
{
    string img = @Request.PhysicalApplicationPath/image/...;
    return img;
}

A: When you set the NavigateUrl to FullPath, Chrome will see the link local to the user machine who is accessing the site and not the server itself.
So, you always need to make the URL for any hyberlink to be in the form of //someURL or http://someurl
In your case, you have to remove the NavigateUrl and add a OnClick handler, and inside the handler, you will read the file using the FileStream and write the file contents to the response stream then flush it
example of the click handler:
context.Response.Buffer = false;
context.Response.ContentType = "the file mime type, ex: application/pdf";
string path = "the full path, ex:E:\PINCDOCS";

FileInfo file = new FileInfo(path);
int len = (int)file.Length, bytes;
context.Response.AppendHeader("content-length", len.ToString());
byte[] buffer = new byte[1024];
Stream outStream = context.Response.OutputStream;
using(Stream stream = File.OpenRead(path)) {
    while (len > 0 && (bytes =
        stream.Read(buffer, 0, buffer.Length)) > 0)
    {
        outStream.Write(buffer, 0, bytes);
        len -= bytes;
    }
}


text:
Q: Why does a ddply command take so long after the progress bar gets to 100? I have a data file with 10000 lines. The file contains blocks of 100 lines with a different factor in the first column, and I use ddply to process them. For example like this:
result.df = ddply(data.df, "V1", calc_stuff, .progress = "text")
message("done!")

It takes about one minute for the ddply progress bar to get to 100%. However then R does "something" for another 5-7 minutes before the next line in the script is processed (the message is printed in this example).
What is R doing in that time? Collecting the results in "result.df"? Can I speed that up somehow? I have many of these files to process.

A: ddply takes the following approach:

*

*Split up dataset.

*Apply function to each component of the split

*Combine the components into one big result data set

The progressbar probably deals with step 2, and states how far along it is in processing each of the chunks. Step 3. is what takes time in your case, and is not included in the progressbar.
To speed up your analysis, I would stop using plyr and start using dplyr. This is orders of magnitude faster than plyr, and the successor to plyr. See the tutorial I wrote for some more information.
Your code example would boil down to something like:
results.df = data.df %>% group_by(V1) %>% calc_stuff()


text:
Q: How to prevent spring boot from logging both into specified file and catalina.out I'm working in a spring-boot project (version 1.5.1) and using logback. My application.properties has the following log settings:
logging.level.=info
logging.level.org.acme.myapp=info
logging.file=${catalina.home}/logs/AppLogFile.log

When the application logs something this is written to the specified AppLogFile.log and also to catalina.out:
==> AppLogFile.log <==
2017-04-13 13:37:33.102 DEBUG 4646 --- [http-nio-8080-exec-25] c.l.c.c.controller.IndexPage             : isAllowedToSeeContent: Homebase: MOCKBASE

==> catalina.out <==
2017-04-13 13:37:33.102 DEBUG 4646 --- [io-8080-exec-25] c.l.c.c.controller.IndexPage             : isAllowedToSeeContent: Homebase: MOCKBASE

==> AppLogFile.log <==
2017-04-13 13:37:33.108 DEBUG 4646 --- [http-nio-8080-exec-25] c.l.c.c.controller.MedlistService        : MedlistService::isControlDay 2017-04-13, true

==> catalina.out <==
2017-04-13 13:37:33.108 DEBUG 4646 --- [io-8080-exec-25] c.l.c.c.controller.MedlistService        : MedlistService::isControlDay 2017-04-13, true

This seems to be additivity Problem. Is it really necessary to provide logback.xml like mentioned in here: howto-configure-logback-for-logging?
Or is there a more direct way?

Update:
Even if I follow the recommendation from the howto and add a logback-spring.xml to my classpath:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <include resource="org/springframework/boot/logging/logback/defaults.xml" />
  <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}" />
  <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
  <root>
    <appender-ref ref="FILE" />
  </root>
</configuration>

I get the following errors (en masse):
17:50:01.267 [localhost-startStop-1] DEBUG org.springframework.jndi.JndiPropertySource - JNDI lookup for name [LOGGING_patternLevel] threw NamingException with message: Name [LOGGING_patternLevel] is not bound in this Context. Unable to find [LOGGING_patternLevel].. Returning null.
17:50:01.267 [localhost-startStop-1] DEBUG org.springframework.jndi.JndiTemplate - Looking up JNDI object with name [java:comp/env/LOGGING_patternlevel]

Setting logging.pattern.console= to an empty string, seems to do the trick - BUT is this really the right solution?

A: Does your tomcat's conf/logging.properties contain the following line?
.handlers = 1catalina.org.apache.juli.AsyncFileHandler, java.util.logging.ConsoleHandler

This is part of the default package. Remove the ConsoleHandler entry from it.

A: As the target tomcat is NOT under my control and my application is not the only one on the server, I've decided to disable the console logging by setting the logging.pattern.console= to an empty string.

The answer from Olaf Kock, I'm sure, is also valid, see the Considerations for production usage paragraph - but I have to admit I failed to get it working - Therefor I could not test it :(


text:
Q: Integrate Spring Boot Actuator with New Relic I am trying to integrate New Relic with Spring Boot actuator. Most of the tutorials and response in StackOverflow itself suggest to use New Relic Java Agent but as per Spring Boot documentation installing Java Agent is not mandatory (unless I misunderstood something) also checked this. So, here is my application.properties currently.
management.metrics.export.newrelic.enabled = true
management.metrics.export.newrelic.api-key = <API_KEY>
management.metrics.export.newrelic.account-id = <ACCOUNT_ID>
logging.level.io.micrometer.newrelic=TRACE
management.metrics.export.newrelic.step=30s

and in the log I am seeing
2021-01-11 12:05:18.315 DEBUG 44635 --- [trics-publisher] i.m.n.NewRelicInsightsApiClientProvider  : successfully sent 73 metrics to New Relic.

Based on this logs it looks like it is sending logs. But I have no idea where to see this logs. Ideally I would like to pass app name as well so that I can differentiate metric by app name and preferably by env as well later. Any suggestions?

A: To add "app name" and "env" to your metrics, you just need to configure the MeterFilter with the common tags:
@Configuration
public class MetricsConfig {

    @Bean
    public MeterFilter commonTagsMeterFilter(@Value("...") appName, @Value("...") env) {
        return MeterFilter.commonTags(Tag.of("app name", appName), Tag.of("env", env);
    }
}

Setting the following property you should be able to see what metrics are being sent to NewRelic:
logging.level.io.micrometer.newrelic=TRACE


text:
Q: AttributeError, ImportError on scipy.misc image functions (e.x imread, imresize, imsave, imshow etc.) I have came across two kinds of errors when trying to import or directly use any of the image functions included in the scipy.misc module. Here are two error examples with the imread() function:
>>> from scipy.misc import imread

ImportError: cannot import name 'imread' from 'scipy.misc'

and
>>> import scipy.misc
>>> scipy.misc.imread

AttributeError: module 'scipy.misc' has no attribute 'imread'

What am I doing wrong?

A: You are not doing anything wrong. This is due to the removal of the image functions from the scipy.misc module since SciPy Version 1.2.0. I don't know why did they deem those functions deprecated and removed them, but if you want to use them, you can rollback to a previous SciPy version by uninstalling the current one and installing a previous one:
pip uninstall scipy
pip install scipy==1.1.0

Make sure you have Pillow installed too:
pip install Pillow

If you don't want to use an old version of SciPy, then you will need to change your code. According to the official docs of each deprecated function, here is what SciPy suggests:

*

*fromimage(im) -> np.asarray(im)

*imfilter() -> Use Pillow filtering functionality directly.

*imread() -> imageio.imread()

*imsave() -> imageio.imwrite()

*imresize() -> numpy.array(Image.fromarray(arr).resize())

*imrotate -> skimage.transform.rotate()

*imshow() -> matplotlib.pyplot.imshow()

*toimage() -> Image.fromarray()
It assumes to install the below libraries:
pip install numpy Pillow scikit-image imageio matplotlib

and import them:
import numpy as np, Pillow, skimage, imageio, matplotlib

In addition, I quote two sources I found, mentioning the deprecation of the scipy.misc image I/O functionality:
From scipy.github.io:

The following functions in scipy.misc are deprecated: bytescale, fromimage, imfilter, imread, imresize, imrotate, imsave, imshow and toimage. Most of those functions have unexpected behavior (like rescaling and type casting image data without the user asking for that). Other functions simply have better alternatives.

From imageio.readthedocs.io (especially for imread):

Transitioning from Scipy's imread
Scipy is deprecating their image I/O functionality.
This document is intended to help people coming from Scipy to adapt to
  Imageio's imread function. We recommend reading the user api and
  checkout some examples to get a feel of imageio.
Imageio makes use of variety of plugins to support reading images (and
  volumes/movies) from many different formats. Fortunately, Pillow is
  the main plugin for common images, which is the same library as used
  by Scipy's imread. Note that Imageio automatically selects a plugin
  based on the image to read (unless a format is explicitly specified),
  but uses Pillow where possible.
In short terms: For images previously read by Scipy's imread, imageio
  should generally use Pillow as well, and imageio provides the same
  functionality as Scipy in these cases. But keep in mind:

*

*Instead of mode, use the pilmode keyword argument.

*Instead of flatten, use the as_gray keyword argument.

*The documentation for the above arguments is not on imread, but on the docs of the individual formats, e.g. PNG.

*Imageio's functions all return numpy arrays, albeit as a subclass (so that meta data can be attached).


text:
Q: ItemsControl with databound ItemsSource and two-way binding of elements (replacable items) I have an ObservableCollection of objects (e.g. Persons with First/Last Name) which I would like to display in an ItemsControl. Each Item is displayed in a custom "editor" control, which allows editing of the object's properties.
This part is working fine and fairly standard.
<ItemsControl ItemsSource="{Binding Persons}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <custom:PersonEditor Person="{Binding}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

However, the custom editor control also has the ability to replace the entire object is has received (rather than just editing a person's name, replace it with a new person object).
What I am looking for is a way to push this change back into the ObservableCollection. As it is now, changing the Person object within the editor does not replace the item in the list, which would be the desired outcome.
Any help would be appreciated.

A: If you don't have access to the custom control itself what you could try would be using a setter on a property to clear the ObservableCollection and re-add the items instead of outright replacing it.
For example:
private ObservableCollection<MyModel> _dataSource;

public ObservableCollection<MyModel> DataSource
{
    get
    {
        return _dataSource;
    }

    set
    {
        _dataSource.Clear();

        foreach(var item in value)
        {
            _dataSource.Add(item);
        }
    }
}

This would prevent the item itself from getting replaced which causes issues with ItemSources since they apparently only bind to the items property once.


text:
Q: Error 10822 when trying to create simple falling edge with signal out I am having the below error code when attempting to compile.
Error (10822): HDL error at CLEARBLK.vhd(17): couldn't implement registers for assignments on this clock edge
LIBRARY IEEE;
    USE IEEE.STD_LOGIC_1164.ALL;
    USE IEEE.NUMERIC_STD.ALL;

    ENTITY CLEARBLK IS
        PORT
        ( CMB       : IN STD_LOGIC;
          CLR       : OUT STD_LOGIC
        );
    END CLEARBLK;

    ARCHITECTURE CLRBLK OF CLEARBLK IS
          BEGIN
            PROCESS(CMB)
            BEGIN
              IF (FALLING_EDGE(CMB)) THEN
                  CLR <= '1';
              ELSE
                  CLR <= '0';
                    END IF;
              END PROCESS;
    END CLRBLK;

A: Your issue is that you have not written a register.
In synthesis, your sensitivity list will be ignored, and depending on toolchains, you have written something that will either

*

*Infers a double-edged flip-flop, which is not present in your device.

*Infers something that would make CLR '1' for 1 delta cycle, so less than 0 time. This can't exist.

Your main issue is that you don't have a time reference, which would determine what the minimum size of your "blip" is. The correct way to handle this is to introduce a clock and make a simple 1 FF delay line:
ENTITY CLEARBLK IS
    PORT
    ( CLK       : IN  STD_LOGIC;
      CMB       : IN STD_LOGIC;
      CLR       : OUT STD_LOGIC
    );
END CLEARBLK;

ARCHITECTURE CLRBLK OF CLEARBLK IS
      BEGIN
        PROCESS(CLK)
          VARIABLE CMB_D : STD_LOGIC;
        BEGIN
          IF (RISING_EDGE(CLK)) THEN
              CLR <= '0';
              IF CMB_D = '0' and CMB = '1' THEN
                CLR <= '1';
              END IF;
              CMB_D := CMB;
          END IF;
        END PROCESS;
END CLRBLK;


text:
Q: How to route traffic in AWS ALB based on two conditions I am migrating services from Kubernetes to AWS ECS. For routing I use AWS Application Load Balancer (ALB).
The ALB has a listener on port 80 and my services are aggregated in target groups.
To route traffic between the services I use ALB listener rules.
For the routing I need to have two conditions to be met: a host-header and a path-pattern.
So I would to have something like following:

I tried to add multiple conditions to a rule (in Terrafom), however it is only possible to either have a host-header or a path-pattern:

Only one of host_header, http_header, http_request_method, path_pattern, query_string or source_ip can be set in a condition block

It is also not possible to add host_header together with path_pattern in the AWS Console.
How to route traffic in AWS ALB based on two conditions - host-header + path-pattern?
One possible option would be to use one ALB per host, but that would be way too expensive when the number of hosts / subdomains increases.
How it is done in Kubernetes
Simultaneous host-header and a path-pattern routing is possible in the nginx ingress router in Kubernetes. For example having these two ingress ressources:
Resource 1
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: web-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
spec:
  rules:
    - host: domain-one.com
      http:
        paths:
          - path: /web
            backend:
              serviceName: web-service
              servicePort: 8080
          - path: /media/files
            backend:
              serviceName: web-service
              servicePort: 8080

    - host: another-domain.com
      http:
        paths:
          - path: /web
            backend:
              serviceName: web-service
              servicePort: 8080
          - path: /media/files
            backend:
              serviceName: web-service
              servicePort: 8080

Resource 2
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: api-ingress
  annotations:
    kubernetes.io/ingress.class: "nginx"
spec:
  rules:
    - host: www.domain-one.com
      http:
        paths:
          - path: /api
            backend:
              serviceName: api-service
              servicePort: 8181

For Kubernetes it is possible to define besides the path parameter also an optional host parameter.
So in the end both the host and path must match the content of an incoming request before the loadbalancer directs traffic to the corresponding backend:

So, how to achieve the same on AWS ALB?
Thank you.

A: The ALB listener rule can contain multiple conditions, but one condition can contain only one of the described blocks.
The conditions of a single rule are processed with an AND, so all conditions must met in order to be routed to the target group.
So it is needed to create multiple rules for multiple hosts, as answered here:
https://stackoverflow.com/a/46304567/1820806
Edit: I will verify this solution and will update the post.
Edit 2: This solution works.

A: I was migrating from k8s also to ECS.
As you mentioned you need to have multiple conditions.
This is how I do it in terraform.
resource "aws_lb_listener_rule" "backend_api_routing" {
  depends_on = [aws_alb_target_group.main8080]

  listener_arn = var.https_aws_alb_listener_arn
  priority     = var.backend_api_routing_priority

  action {
    type             = "forward"
    target_group_arn = aws_alb_target_group.main8080.arn
  }

  condition {
    host_header {
      values = ["domain-one.com"]
    }
  }

  condition {
    path_pattern {
      values = ["/web/*", "/media/files/*"]
    }
  }
}

Also, I suggest you that you check terragrunt, it allows you to re use terraform modules.


text:
Q: Are data transformations on non-normal data necessary for an exploratory factor analysis when using the principal axis factoring extraction method? I am developing a questionnaire to measure four factors which constitute spirituality, and I would like to ask the following question:
Are data transformations on non-normal data necessary for an exploratory factor analysis when using the principal axis factoring extraction method?
I finished screening my data yesterday, and I found that 3 out of 20 questions are positively skewed while 1 out of 20 is negatively skewed (Question 6 = 4.88, Question 9 = 7.22, Question 12 = 11.11, Question 16 = -6.26). I also found that 1 of the questions (out of 20) is leptokurtic (Question 12 = 12.21).
I chose the principal axis factoring extraction method because I read that it is used on "severely non-normal data" while maximum-likelihood is used on normal data, but:

*

*How would I know if my data is "severely" non-normal?

*If my data is "severely non-normal", does this mean that I can leave the data as it is now (not transform it) and analyze it using the principal axis factoring extraction method? Or do I need to transform the data before proceeding with the EFA?

*If I do need to transform the data, what transformations would I use for positively skewed, negatively skewed, and leptokurtic items?

A: Factor analysis is essentially a (constrained) linear regression model. In this model, each analyzed variable is the dependent variable, common factors are the IVs, and the implied unique factor serve as the error term. (The constant term is set to zero due to centering or standardizing which are implied in computation of covariances or correlations.) So, exactly like in linear regression, there could exist "strong" assumption of normality - IVs (common factors) are multivariate normal and errors (unique factor) are normal, which automatically leads to that the DV is normal; and "weak" assumption of normality - errors (unique factor) are normal only, therefore the DV needs not to be normal. Both in regression and FA we usually admit "weak" assumption because it is more realistic.
Among classic FA extraction methods only the maximum likelihood method, because it departs from the characteristics of population, states that the analyzed variables be multivariate normal. Methods like principal axes or minimal residuals do not require this "strong" assumption (albeit you can make it anyway).
Please remember that even if your variables are normal separately, it doesn't necessarily guarantee that your data are multivariate normal.
Let us accept "weak" assumption of normality. What is the potential threat coming from strongly skewed data, like your, then? It is outliers. If the distribution of a variable is strongly asymmetric the longer tail becomes extra influential in computing correlations or covariances, and simultaneously it provokes apprehension about whether it still measures the same psychological construct (the factor) as the shorter tail does. It might be cautious to compare whether correlation matrices built on the lower half and the upper half of the rating scale are similar or not. If they are similar enough, you may conclude that both tails measure the same thing and do not transform your variables. Otherwise you should consider transforming or some other action to neutralize the effect of "outlier" long tail.
Transformations are plenty. For example, raising to a power>1 or exponentiation are used for left-skewed data, and power<1 or logarithm - for right-skewed. My own experience says that so called optimal transformation via Categorical PCA performed prior FA is almost always beneficial, for it usually leads to more clear, interpretable factors in FA; under the assumption that the number of factors is known, it transforms your data nonlinearly so as to maximize the overall variance accounted by that number of factors.

A: I just post what I learned from Yong and Pearce (2013).

To perform a factor analysis, there has to be univariate
  and multivariate normality within the data (Child, 2006)

Yong, A. G., & Pearce, S. (2013). A beginner's guide to factor analysis: Focusing on exploratory factor analysis. Tutorials in quantitative methods for psychology, 9(2), 79-94. DOI:10.20982/tqmp.09.2.p079