text:
Q: Is it possible/practical to use a Linux server to authenticate Windows devices? I am from a small primary school and we are currently looking into getting a server purely for authentication. I do not want to push software to the devices or anything like that. I simply want to force the devices to input a username/password before they can use it (to keep track of who is using what for security purposes. We are getting more and more windows tablets in and it is hard for the teachers to keep track of who is using what).
I do not want to spend money so i thought using open source server software would be a better idea. I understand i will need a relatively good piece of hardware to then run this but that shouldn't be a problem to sort out.
I looked around at Apache, ClearOS and Ubuntu Server and they all look great but i can't seem to find any information regarding compatibility of Linux servers with windows.
So: Is it possible/practical to use a Linux server to authenticate Windows devices?
and if so, any recommendations?

A: I just wanted to add this as further support. It is possible(and fundamentally AWESOME) to use samba as a replacement for a windows server domain controller. Glancing at those links it looked(and i could have missed something) that it was focusing on ldap for authenticating linux users, rather than windows users.
Some information can be found(http://xmodulo.com/samba-primary-domain-controller.html)
but basically you will want to install samba Active Directory, and modify the config file

sudo cp /etc/samba/smb.conf
[global]

workgroup = sambadomain    netbios name = sambapdc     server
string = Samba PDC
   domain master = yes
     preferred master = yes
     domain logons = yes
   add machine script = /usr/sbin/useradd -N -g
     machines -c Machine -d /var/lib/samba -s /bin/false %u
      security =user
         encrypt passwords = yes
       wins support = yes
   name resolve order = wins lmhosts hosts bcast
    logon path = \%N\%U\profile
     logon drive = H:
   logon home = \%N\%U

At the end of it you can then manage users with the command line.

#to create user
  sudo smbpasswd -a dan
  #to activate user
   sudo smbpassword -e dan
  #to give user login rights
   sudo net rpc rights grant "SAMBADOMAIN\dan" SeMachineAccountPrivilege SePrintOperatorPrivilege SeAddUsersPrivilege SeDiskOperatorPrivilege SeRemoteShutdownPrivilege
  #to add to domain groups.
  sudo net groupmap add ntgroup="Administrator" unixgroup=root rid=512 type=d

Using this method your windows machines would join the domain as if it were a windows domain server providing authentication.
There are some more steps involved, but there is a wealth of information out there regarding using samba for AD :)

A: Yes, it's perfectly possible! You can set up a Linux Server as an LDAP server, which allows for users to use the same username and password to authenticate on all boxes (including Linux ones).
Some useful links:

*

*Wikipedia page on LDAP

*Ubuntu page on configuring OpenLDAP


text:
Q: Validation loop error I am trying to validate my python script:
def DOBSearch():
    loop = True
    while loop == True:
        try:
            DOBsrch = int(input("Please enter the birth month in a two digit format e.g. 02: "))
            for row in BkRdr:
                DOB = row[6]
                day,month,year = DOB.split("/")
                if DOBsrch == int(month):
                    print("W")
                    surname = row[0]
                    firstname = row[1]
                    print(firstname, " ",surname)
                    addrsBk.close
                    loop = False
                else:
                    print("1 That was an invalid choice please try again.")
        except ValueError:
            print("That was an invalid choice please try again.")

However when I try to test the script I find there is a bug/error as I get the following outputs:
>>> DOBSearch()
Please enter the birth month in a two digit format e.g. 02: 2345
1 That was an invalid choice please try again.
1 That was an invalid choice please try again.
1 That was an invalid choice please try again.
1 That was an invalid choice please try again.
1 That was an invalid choice please try again.
1 That was an invalid choice please try again.
Please enter the birth month in a two digit format e.g. 02: 23456
Please enter the birth month in a two digit format e.g. 02: 4321
Please enter the birth month in a two digit format e.g. 02: 2345
Please enter the birth month in a two digit format e.g. 02: yrsdhctg
That was an invalid choice please try again.
Please enter the birth month in a two digit format e.g. 02: 02
Please enter the birth month in a two digit format e.g. 02:

here is the CSV file:
Jackson,Samantha,2 Heather Row,Basingstoke,RG21 3SD,01256 135434,23/04/1973,sam.jackson@hotmail.com
Vickers,Jonathan,18 Saville Gardens,Reading,RG3 5FH,01196 678254,04/02/1965,the_man@btinternet.com
Morris,Sally,The Old Lodge, Hook,RG23 5RD,01256 728443,19/02/1975,smorris@fgh.co.uk
Cobbly,Harry,345 The High Street,Guildford,GU2 4KJ,01458 288763,30/03/1960,harry.cobbly@somewhere.org.uk
Khan,Jasmine,36 Hever Avenue,Edenbridge,TN34 4FG,01569 276524,28/02/1980,jas.khan@hotmail.com
Vickers,Harriet,45 Sage Gardens,Brighton,BN3 2FG,01675 662554,04/04/1968,harriet.vickers@btinternet.com

A: You aren't distinguishing between what is a valid birth month (i.e. one that makes sense, an integer between 1 and 12) and what is a birth month in BkRdr (presumably, some subset of that). You have too much in the try block, and will tell the user for every row in BkRdr that their input was invalid, when a later row might actually match.
I would split this into at least two functions, with explicit arguments rather than relying on scope:
def input_month():
    """Get a valid birth month from the user."""
    while True:
        try:
            month = int(input("Please enter the birth month in a two digit format e.g. 02: "))
        except ValueError:
            print("Must be a number")
        else:
            if month in range(1, 13):
                return month
            print("Must be in range 1-12")

def DOB_search(BkRdr):
    """Find a valid birth month in BkRdr."""
    while True:
        search_month = input_month()
        for row in BkRdr:
            ...
            if search_month == int(month):
                ...
                return " ".join((firstname, surname))
        print("Not found in BkRdr.")

This separates the two concerns of your code:

*

*Getting a valid birth month input from the user; and

*Trying to match that birth month in BkRdr.

I would also rethink the variable names - what is a BkRdr anyway?

A: I think there are a two errors in your code.
The first is that you're printing your first error message repeatedly. This is because the print line is inside of the for loop that checks against each row from your CSV file. Each row that doesn't match produces the error message.
To fix that, you should probably move the print statement up a level, to be called after the for loop ends.
The second issue is that BkRdr, which you loop on, appears to be an iterator, not a sequence that you can repeatedly iterate. This is why every numerical entry after the first fails silently. The for loop doesn't do anything at all in those cases!
To fix this second issue, you probably need to change other code you haven't shown, so that your CSV file gets read into a list, rather than only an iterator. (Or, alternatively, you could rewind the file, or close and reopen it.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Gitlab: trigger manual action via API I have a GitLab-CI pipeline stage that looks like this:
test:
  stage: test
  script:
    - echo test
  when: manual

I need to trigger this action via a GitLab API request. I've tried these solutions but they do not seem to work.
curl --request POST \
  --form token=<trigger-token> \
  --form ref=<branch-name> \
https://gitlab.example.com/api/v4/projects/1/trigger/pipeline

curl --request POST \
  --header PRIVATE-TOKEN <private-token> \
https://gitlab.example.com/api/v4/projects/1/jobs/1/play

I don't receive any error message. However, if I pipe the curl-request output to jq, I get the following output:
[...]
      "started_at": null,
      "finished_at": null,
      "committed_at": null,
      "duration": null,
      "coverage": null,
      "detailed_status": {
        "icon": "status_manual",
        "text": "blocked",
        "label": "waiting for manual action",
        "group": "manual",
        "tooltip": "manual action"
[...]

These are the admin logs, but even if the Pipeline is authorized, the job is not triggered.
{"severity":"INFO","time":"2020-11-05T15:57:51.989Z","correlation_id":"z7ATZBEHCB2","message":"Pipeline authorized","project_id":148,"user_id":12}

A: The API call you're using is to trigger the step, not to start it manually. If you change your job definition to accept triggers or manual actions, then your current API call would work. We can do this with the rules keyword:
test:
  stage: test
  script:
    - echo test
  when: manual
  rules:
    - if: "$CI_PIPELINE_SOURCE == 'trigger'"
       when: always

What this does is set the default to manual so it can still be started in the UI, but also check the $CI_PIPELINE_SOURCE predefined variable to see if the pipeline was triggered. If so, it will always run.
You can see the docs for the rules keyword here: https://docs.gitlab.com/ee/ci/yaml/#rules and all of the predefined variables here: https://docs.gitlab.com/ee/ci/variables/predefined_variables.html


text:
Q: Local nameserver issues I have an Ubuntu 18.04 server that runs a DHCP server for a wired and wireless network and acts as a gateway to the internet (so PCs on the LAN have to connect to the server to access the internet). From PCs on the wired network, I can enter the server's hostname into a browser's address bar and development versions of websites that the server hosts are accessible. If I try the same thing with a PC that's on the wireless network, the server's hostname isn't resolved correctly so the website isn't displayed. PCs on either the wired or wireless network can access sites that are on the internet without any problems. Using "ping " on PCs on the wired network runs without errors but from PCs on the wireless network it fails to resolve the name. Any ideas why the DNS lookup is not working on the WiFi but working OK on the wired interfaces?
EDIT:
I'm using dnsmasq for dns lookups / dhcp control and netplan using NetworkManager for the network configuration (the wireless is set up to act as an access point for any device).
EDIT - in response to PEdroArthur's comment:
dig when run on server:-

; <<>> DiG 9.11.3-1ubuntu1.5-Ubuntu <<>> thincontroller
  ;; global options: +cmd
  ;; Got answer:
  ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 59068
  ;; flags: qr rd ra; QUERY: 1, ANSWER: 4, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
  ; EDNS: version: 0, flags:; udp: 65494
  ;; QUESTION SECTION:
  ;thincontroller.                        IN      A
;; ANSWER SECTION:
  thincontroller.         0       IN      A       127.0.0.1
  thincontroller.         0       IN      A       127.0.1.1
  thincontroller.         0       IN      A       192.168.1.254
  thincontroller.         0       IN      A       10.42.0.254
;; Query time: 0 msec
  ;; SERVER: 127.0.0.53#53(127.0.0.53)
  ;; WHEN: Sat Mar 09 11:44:50 GMT 2019
  ;; MSG SIZE  rcvd: 107

And on a PC connected wirelessly:-

; <<>> DiG 9.11.3-1ubuntu1.5-Ubuntu <<>> thincontroller
  ;; global options: +cmd
  ;; Got answer:
  ;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 33715
  ;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
  ; EDNS: version: 0, flags:; udp: 65494
  ;; QUESTION SECTION:
  ;thincontroller.           IN  A
;; Query time: 0 msec
  ;; SERVER: 127.0.0.53#53(127.0.0.53)
  ;; WHEN: Sat Mar 09 11:56:07 GMT 2019
  ;; MSG SIZE  rcvd: 43


text:
Q: Cuando un usuario se registre o identifique una vez completada la acción la página debe mostrar la última página que el usuario se encontraba ¿Como puedo lograr eso,  en java en JEE ?
@Override
protected String getSuccessRedirect(final HttpServletRequest request,
final HttpServletResponse response) {
if (httpSessionRequestCache.getRequest(request, response) != null) {
return httpSessionRequestCache.getRequest(request, response)
.getRedirectUrl();
}
    return "/";
}


text:
Q: execute multiple statements if mysql_query fails $query = sprintf("select * from sometable;");
$result = mysql_query($query) or die (mysql_error());

modified to:
$query = sprintf("select * from sometable;");
$result = mysql_query($query) or $DBError=true;

Now I want to execute 2 statements if the query fails, is this possible using the "short above"? e.g. something like this:
$query = sprintf("select * from sometable;");
$result = mysql_query($query) or {$DBError=true; $ErrorCode=0;}

A: You can simply use conditional statement like:
$result = mysql_query($query);
if (!$result) {
 $DBError = true;
 $ErrorCode = 0;
}

By the way. mysql_ extension is deprecated. You should use PDO.


text:
Q: DI using dynamic constructor injection I have a problem using DI with constructor properties. I am building a PDFBuilder based on my IPDFBuilder.
public interface IPDFBuilder
{
    string templatefilepath { get; }
    string templatefilename { get; }
    Dictionary<string, string> dict { get; }
    void CreatePDF();
}

public class PDFBuilder : IPDFBuilder
{
    public string templatefilename { get; private set; }
    public string templatefilepath { get; private set; }
    public Dictionary<string, string> dict { get; private set; }

    public PDFBuilder(string templatefilename, string templatefilepath, Dictionary<string, string> dict)
    {
        this.templatefilename = templatefilename;
        this.templatefilepath = templatefilepath;
        this.dict = dict;
    }

    public void CreatePDF() {
        //Do something
    }
}

This PDFBuilder can and will be used in multiple controllers, for example:
public class KeuringController : Controller
{
    private IPDFBuilder _PDFBuilder;
    public KeuringController(IPDFBuilder pdfBuilder)
    {
        _PDFBuilder = pdfBuilder;
    }
    //Action methods that use `PDFBuilder` below...
}

However, I can't set the properties of PDFBuilder in the startup class (where DI registration is beeing done) because different controllers will use different values for the properties of the PDFBuilder class. 1 simple solution would be to just make the setters of the properties public so in an action method I can  set the values and then call CreatePDF(). However this doesn't feel right. Another simple solution would be to remove the class properties and just pass the 3 properties of PDFBuilder as method properties to the CreatePDF method like this:
public void CreatePDF(string templatefilename, string templatefilepath, Dictionary<string, string> dict) {
        //Do something
    }

But now let's say that my PDFBuilder whould have 10 methods which all need these 3 properties. Then this is not the correct solution right?
What would be the correct solution then? I have encountered this problem multiple times with different classes/interfaces implementations and would like to have some help with designing in these situations.

A: You are injecting runtime data into your component's constructor, which is a bad thing. The solution is to move those runtime values out of the constructor into the CreatePDF method:
public interface IPDFBuilder
{
    void CreatePDF(string templatefilepath, string templatefilename,
        Dictionary<string, string> dict);
}

A: You could subclass (or prototype, depending on your requirements) different kinds of PDFBuilders and inject them into the according classes.
I don't know what DI Framework you're using, but i'm pretty sure theres an option to tell the framework what kind of dependency you want to inject in specific classes.
Edit: Keep in mind: This solution is not applicable for values known at runtime.

A: There is two ways of doing what you want:
1) Create factory for builder.

2) Create configurator for builder.

When you create factory, you basically specify how object is created and so can freely set everything you want into different implementations for different builders:
public inteface IPDFBuilderFactory
{
    IPDFBuilder Create();
}

You will need to pass all dependencies - this is a drawback. I personally don't like this method.
Another way, is to create configuration like this:
public interface IPDFConfiguration
{
    string templatefilename {get;}
    string templatefilepath {get;}
    Dictionary<string, string> dict {get;}
}

and pass it as argument to constructor:
public PDFBuilder(IPDFConfiguration configuration)
{
    ...
}

It will give you more flexebility in initialization of your builders if you deside to change them some time. Also you can freely initialize this configuration - constants, configs, databases, etc.
One of drawbacks - your configuration can become very clumsy over time and without refactoring it will be black hole for others, so be carefull.
Choose what fits you the best.


text:
Q: VB ASP.NET. "the conversion overflowed an integer column." I am working in VB ASP.NET.  I am doing a SELECT.  I have a variable in the WHERE clause that usually works, but when I enter 13 or more characters, I get the message "the conversionnvarchar value overflowed an integer column."  Any help will be greatly appreciated!
Here is my statement:
SELECT VACD
FROM VENDOR
WHERE VACD = FORM.VACD

A: If you mix characters and numbers in a comparison you might get an implicit conversion.  I might be wrong since as @Oded said: even 12 digits shouldn't be usable.  Better explanation.

A: Character values are implicitly converted to integers when they are compared to. So this means that your 13 characters will be to large for the Int32 number which ranges from -2,147,483,648 to 2,147,483,647.


text:
Q: What are the initial steps to setup a git repo on GitHub and my private server? (I have seen pull/push from multiple remote locations but my question involves something slightly different, or at least different enough that I can't figure it out.)
I am trying to write a script that will create a (private) repo on GitHub, but I want to also have all of the commit history, etc on another server as a backup in case GitHub ever explodes, gets taken over by space aliens, or is otherwise unavailable. The idea here is that if we wake up some morning and can't use GitHub ever again, I'd like to be able to just point to my server and have it take over as smoothly as possible.
What I Know (or think I know)

*

*I can create the new (private) repo on GitHub very easily. I have that part all figured out using the GitHub API and it seems to work fine. (I thought that would be that hard part, but it was fairly easy.)

*I understand about adding this part:

git remote set-url origin --push --add <a remote>
git remote set-url origin --push --add <another remote>

What I Don't Know
The problem is that I can't seem to figure out how to set up the repo on the non-GitHub server.
I have my user account setup on the remote server, and I can ssh to it using ssh public key encryption. I can run commands on it just fine, and I can even pull from GitHub using my private GitHub account.
However, I can't figure out what the right commands are in order to setup the initial git repository so that it will accept the changes that I want to push to it.
I've tried running git clone and git pull and git init on the server, but they all resulted in errors when I tried to push additional changes.
I finally ran git init --bare which seems to have worked in-as-miuch as no errors are given when I do push, but none of the "non-git" files from the repo are actually present in the folder on the server, it's just the git-specific files:
HEAD
branches/
config
description
hooks/
info/
objects/
refs/

so if GitHub were to disappear, I wouldn't have a copy of the files on my server, which seems to defeat the whole purpose of what I'm trying to do.
I've been all over Google and stackoverflow.com looking for solutions, but I must be missing something fundamental here. I only have a basic knowledge of git (just enough to be dangerous, as the saying goes).
Thanks for your time and attention.
edited to add: Thanks to VonC for the answer below, which clarified what I needed was a bare repo, but with another feature, as he described, to give me access to my files in that repo. I think that's exactly what I needed but didn't know enough to ask for.

A: If you want to see your files (at least for the main branch), add to your bare repo a post-receive script which will (as I did here) checkout the content of that bare repo to a working tree:
cd /path/to/working/tree
git --git-dir=/path/to/bare/repo/.git --work-tree/path/to/working/tree checkout -f

You will see your files there, every time you are pushing to that bare repo.


text:
Q: How to platform exception error flutter 2020 I am trying to get to get a dialog pop to indicate to the user that the email already exists, but I keep getting this error an the dialog pop doesn't show, have gone through similar solution but none seem to work  any help will be appreciated

Exception has occurred.
FirebaseAuthException ([firebase_auth/email-already-in-use] The email address is already in use by another account.)

Below is my authentication code
    void registerToFb() {
firebaseAuth
    .createUserWithEmailAndPassword(
        email: emailController.text, password: passwordController.text)
    .then((result) {
  dbRef.child(result.user.uid).set({
    "email": emailController.text,
    "age": ageController.text,
    "name": nameController.text
  }).then((res) {
    isLoading = false;
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (context) => Home(uid: result.user.uid)),
    );
  });
}).catchError((err) {
  print(err);
  showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("Error"),
          content: Text(err.message),
          actions: [
            FlatButton(
              child: Text("Ok"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            )
          ],
        );
      });
});

}

A: I've not checked the latest docs but I think the error codes have changed. First check by printing what's inside err.message. I read somewhere this changed to err.code!


text:
Q: is there a simple front for sql server? i am in a multi-user environment
i am using access as a front end connecting to sql server database. i am allowing users to edit only one table in sql server.
i dont want to continue using access to edit a sql-server table.
can someone recommend another tool to do this?

A: The Access 2007 runtime and the Access 2010 runtime is free for the download from Microsofts website.   Of course you'd want to purchase Access licenses for power users who want to create their own queries usually for export to Excel.

A: Either Access or Excel are almost certainly the simplest solutions available that meet your requirements, when you consider both the simplicity of the user interface itself and the simplicity of implementing, deploying, and maintaining the solution for the users. Creating even a simple web page isn't nearly so simple – you'll need to setup a web server, configure user security, develop the web page, etc.

A: Use SSMS -- Sql Server Management Studio.
Update
Found a near duplicate @SU: Less daunting front end for SQL Server
Update 2
Try to use Microsoft ASP.NET Dynamic Data. And a tutorial on YouTube, of course.

A: If you pull down a copy of visual studio express you could build a single screen application that allows editing a table with just drag and drop from the server explorer.  No coding needed unless you're looking to add some more advanced logic.
Alternatively you could just use Access to also build a one screen front end - with that as the start up form to your Access DB your users wouldn't even know they're in Access.
Edit:

*

*Assuming you're in a windows domain - put all your users in to a security group and then grant this group access to the SQL Server.  Only grant the group permissions on the specific objects that they need to edit.

*Create a blank Access DB.

*Link your SQL Server table in to the Access DB - e.g. in 2007 the option is in the External Data ribbon > more... > ODBC database.

*Once you have the table linked create a form to edit the data by doing Create > more > Form Wizard.
This allows you to pick the exact columns you want them to edit, pick a layout etc.
From here the options are really only limited by how much effort you want to put in but it's a good start in contrast to direct table access.

A: Sounds like you need to give CRUD access to a table in a SQL Server database.
Suggest making a simple page - use ASP.NET Dynamic Data. Watch this video to get started with ASP.NET Dynamic Data.
Failing that, provision the user with Microsoft Access.

*

*setup a new user in SQL Server, and give it permissions on that table only.

*setup Access to read, update, create and delete that table. Use the credentials of the user in the bullet above. This will ensure they can't mess anything else up.

*Only bring that table into the user's view.

A: I believe it's still in Beta but you might want to also take a look at WebMatrix.


text:
Q: Password Policy Windows API Is there any API to work with Local and/or Global Password Policy (read/write policy settings)?
I found there is a windows command:

net accounts

What API does it use to read the settings? Is it possible to change the settings programmatically under admin permissions?

A: Use can use the NetUserModalsGet() function in netapi32.lib.
See the example at https://msdn.microsoft.com/en-us/library/aa370656(VS.85).aspx
NetUserModalsGet
struct USER_MODALS_INFO_0
{
    DWORD usrmod0_min_passwd_len;
    DWORD usrmod0_max_passwd_age;
    DWORD usrmod0_min_passwd_age
    DWORD usrmod0_force_logoff;
    DWORD usrmod0_password_hist_len;
}
PUSER_MODALS_INFO_0 = ^USER_MODALS_INFO_0;

PUSER_MODALS_INFO_0 info0;

NET_API_STATUS res = NetUserModalsGet(nil, 0,  out info0);

if (res <> NERR_Success)
   RaiseWin32Error(res);
try
   //Specifies the minimum allowable password length.
   //Valid values for this element are zero through PWLEN.
   Log(info0.usrmod0_min_passwd_len);

   //Specifies, in seconds, the maximum allowable password age.
   //A value of TIMEQ_FOREVER indicates that the password never expires.
   //The minimum valid value for this element is ONE_DAY.
   //The value specified must be greater than or equal to the value for the usrmod0_min_passwd_age member.
   Log(info0.usrmod0_max_passwd_age);

   //Specifies the minimum number of seconds that can elapse between the time
   //a password changes and when it can be changed again.
   //A value of zero indicates that no delay is required between password updates.
   //The value specified must be less than or equal to the value for the usrmod0_max_passwd_age member.
   Log(info0.usrmod0_min_passwd_age);

   //Specifies, in seconds, the amount of time between the end of the valid
   // logon time and the time when the user is forced to log off the network.
   //A value of TIMEQ_FOREVER indicates that the user is never forced to log off.
   //A value of zero indicates that the user will be forced to log off immediately when the valid logon time expires.
   Log(info0.usrmod0_force_logoff);

   //Specifies the length of password hi'+'story maintained.
   //A new password cannot match any of the previous usrmod0_password_hist_len passwords.
   //Valid values for this element are zero through DEF_MAX_PWHIST
   Log(info0.usrmod0_password_hist_len);
finally
   NetApiBufferFree(info0);
end;

A: You should have a look at:
Windows-OS-User-Management
Query-the-New-Windows-Audit-Policies-Programmatica


text:
Q: unable to cover batch class completely Scheduler Class:
global class bankerjob implements Database.batchable<sObject> , Database.Stateful{
private EmailTemplate emailTemp;
global bankerjob(){
    emailTemp = [Select Id From EmailTemplate Where Name = 'Banker'];
}
global Database.QueryLocator start(Database.BatchableContext bc){
    String query = 'Select Id, Lastname, Firstname, Email From Contact WHERE (Id IN (select Banker__c from Lead WHERE RecordType.Name = \'Branch\' ) AND RecordType.Name = \'Branch\')';
    return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext bc, List<Contact> scope){
    try{
    List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
    for(Contact con : scope) {
         if(emailTemp != null && con.Email != null && con.Email != '') {
               Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
               email.setToAddresses(new List<String>{con.Email});
               email.setTargetObjectId(con.Id);
               email.setTemplateId(emailTemp.Id);
               email.setTreatTargetObjectAsRecipient(true);
               emails.add(email);
         }
     }
     Messaging.sendEmail(emails);
     }
     catch(exception ex){}
}
global void finish(Database.BatchableContext bc){}
}

Test Class:
@istest
class bankerjob_Test{
static testmethod void test() {
  Profile p = [select Name from profile where Name = 'System
  Administrator'];
  User u = new User(Alias = 'test1',Country='United
  States',Email='abc@domain.com',EmailEncodingKey='UTF-8',
                       LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id,
                       TimeZoneSidKey='America/Los_Angeles', UserName='abc@test.org');
  insert u;
  system.runas(u){
     List<contact> con1 = new List<Contact>();
          for(Integer i=0 ;i <200;i++){
              Contact con = new Contact();
              con.Lastname = 'testing1'+i;
              con.Email = 'test@email.com';
              con1.add(con);
          }
          insert con1;

          List<Lead> lead1 = new List<Lead>();
          for(Integer j=0 ;j <200;j++){
              Lead l = new Lead();
              l.LastName = 'test';
              l.Status = 'New';
              l.banker__c = con1[0].Id;
              lead1.add(l);
          }
          insert lead1;

          EmailTemplate emailTemp = new EmailTemplate();
          emailTemp.isActive = true;
          emailTemp.Name = 'name';
          emailTemp.DeveloperName = 'test';
          emailTemp.TemplateType = 'text';
          emailTemp.FolderId = UserInfo.getUserId();
          insert emailTemp;

          System.Test.startTest();
          bankerjob obj = new bankerjob();
          DataBase.executeBatch(obj);
          System.Test.stopTest();
  }
  }
  }

Unable to cover the global void execute method.
Please let me know what am I missing here, any suggestion helps! thanks.

A: You need to fulfill the query conditions. That means you need to create lead records and specify those contacts as Banker__c values for those leads, and set the correct record type for all of the leads and contacts you create. Once you create records that meet the criteria, your execute method will run.


text:
Q: how to inject by keys pair value using lodash in node js My jsob object look like this
{"LAB_123":{"abc":"bde"},"LAB_345":{"abc":"efg"}}

Second json object is
{"LAB_123":{"xyz":"dfe"},"LAB_345":{"PQR":"ABC"}}

I need to join those two object to create one json array which should look like this
{"LAB_123":{"abc":"bde","xyz":"dfe"},"LAB_345":{"abc":"efg","PQR":"ABC"}}

I can add keys values using looping through the json array but is there any method using lodash which will make this code look easier.

A: You can use lodash's _.merge(), which recursively merges the object. Since merge mutates the 1st object (the 1st param), use an empty object to avoid mutating the original objects:

const a = {"LAB_123":{"abc":"bde"},"LAB_345":{"abc":"efg"}};

const b = {"LAB_123":{"xyz":"dfe"},"LAB_345":{"PQR":"ABC"}};

const result = _.merge({}, a, b);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

If you want an array of objects, you can split the result of the 1st example using _.toPairs() to key/value pairs, and map them to objects:

const a = {"LAB_123":{"abc":"bde"},"LAB_345":{"abc":"efg"}};

const b = {"LAB_123":{"xyz":"dfe"},"LAB_345":{"PQR":"ABC"}};

const result = _({})
  .merge(a, b)
  .toPairs()
  .map(([key, value]) => ({ [key]: value }))
  .value();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


text:
Q: Why is NSURLSession don't use my configured NSURLCache? iOS7 brings NSURLSession, with the help of NSURLSessionConfigure, we can customize URLCache, so i tried it, but with no luck, it seems my URLCache is not used at all.
- (void)testURLCache
{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
    NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:1024 * 100 diskCapacity:1024 * 100 diskPath:@"test.urlcache"];

    NSLog(@"usage:%lu", (unsigned long)[cache currentDiskUsage]);

    config.URLCache = cache;

    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    for (int i = 0; i < 40; i++) {
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js?%d", i]]];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            if (error) {
                NSLog(@"error:%@", error);
            } else {
                NSLog(@"done:%d", i);
            }
        }];
        [task resume];
        [NSThread sleepForTimeInterval:0.5];
    }
    NSLog(@"usage:%lu", (unsigned long)[cache currentDiskUsage]);
}

something i observed:
1) a test.urlcache folder is created under Caches folder, and with 3 files Cache.db, Cache.db-shm, Cache.db-wal, the size of Cache.db is 4KB, no records in it.
2) every time run the code, the first output of usage is always 0, after for loop ended, usage becomes 4096, the next time usage becomes 0 again.

A: Seems like there are two potential issues:

*

*Your cache is too small. Historically, it wouldn't cache if the item being cached exceeded 10% of the total cache size.

*You're checking the disk usage 0.5 seconds after the last request. That might be too soon for the cache to be written to persistent storage.
Below I use a bigger cache and wait 10 seconds before final check of disk usage, and the cache works fine. I also use GCD to queue the serial tasks to eliminate the arbitrary 0.5 second delay, which is both safer, and makes it more obvious when it's retrieving data over network and when it's using the cache.
- (void)testURLCache
{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;

    // this is too small and won't cache
    // NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:100 * 1024 diskCapacity:100 * 1024 diskPath:@"small.urlcache"];

    // use bigger cache
    NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:10 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:@"big.urlcache"];

    config.URLCache = cache;

    // I'm going to add tasks to serial queue so that (a) I don't block main queue;
    // and (b) I don't need arbitrary delay, but I can just signal when it's done.

    dispatch_queue_t queue = dispatch_queue_create("com.domain.app.datatasks", 0);

    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    for (int i = 0; i < 40; i++) {
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

        dispatch_async(queue, ^{
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js?%d", i]]];
            NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

                if (error) {
                    NSLog(@"error:%@", error);
                } else {
                    NSLog(@"done:%d", i);
                }

                dispatch_semaphore_signal(semaphore);                   // signal dispatched block that request is done
            }];
            [task resume];

            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);  // wait until task is complete
        });
    }

    // when the queued tasks finish, then check disk usage both immediately and 10 seconds later

    dispatch_async(queue, ^{

        // check cache size immediately after the data tasks finish

        NSLog(@"usage:%lu", (unsigned long)[cache currentDiskUsage]);

        // check again in 10 seconds

        double delayInSeconds = 10.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            NSLog(@"usage:%lu", (unsigned long)[cache currentDiskUsage]);
        });
    });
}

As an aside, for network tasks like this, I'd generally use operation queue rather than dispatch queue and then wrap my data tasks in concurrent NSOperation subclass. Then I can use  dependencies to dictate the final completion operation, but at the same time both permit concurrency but also dictate the degree of concurrency, but this seemed outside the scope of the original question and I wanted to keep this as simple as possible.

A: This is iOS7 issue. With iOS8.1 it works correctly, I'm not sure about iOS8. Please notice also you can still use iOS7 SDK to compile your app, and it'll work correctly on iOS8.1 devices.
However you may still use global cache, instead of the one assigned to NSURLSessionConfiguration:
NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:1024 * 100 diskCapacity:1024 * 100 diskPath:@"test.urlcache"];
[NSURLCache setSharedURLCache:cache];

BTW, in iOS8 there are 3 not yet documented methods in NSURLCache class (actually it is a NSURLSessionTaskAdditions category of NSURLCache, check NSURLCache.h file):
- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forDataTask:(NSURLSessionDataTask *)dataTask
- (void)getCachedResponseForDataTask:(NSURLSessionDataTask *)dataTask completionHandler:(void (^) (NSCachedURLResponse *cachedResponse))completionHandler
- (void)removeCachedResponseForDataTask:(NSURLSessionDataTask *)dataTask

...however it's not neccessary to touch them is you want to change caching mechanics ;)


text:
Q: Slowly moving an object to a new position in Unity C# I have a car object in my scene. I would like to simulate a basic driving animation by moving it to a new position slowly... I have used the code below but I think I'm using Lerp wrong? It just jumps forward a bit and stops?
void PlayIntro() {
    GameObject Car = carObject;
    Vector3 oldCarPos = new Vector3(Car.transform.position.x, Car.transform.position.y, Car.transform.position.z);
    GameObject posFinder = GameObject.Find("newCarPos");

    Vector3 newCarPos = new Vector3(posFinder.transform.position.x, posFinder.transform.position.y, posFinder.transform.position.z);

    carObject.transform.position = Vector3.Lerp (oldCarPos, newCarPos, Time.deltaTime * 2.0f);
}

A: There's two problems with your code:

*

*Vector3.Lerp returns a single value. Since your function will only be called once, you're just setting the position to whatever Lerp returns. You will want to change the position every frame instead. To do this, use coroutines.

*Time.DeltaTime returns the time that has passed since the last frame, which will generally be a very small number. You will want to pass in a number ranging from 0.0 to 1.0 depending the progress of the movement.
Your code will then look like this:
IEnumerator MoveFunction()
{
    float timeSinceStarted = 0f;
    while (true)
    {
        timeSinceStarted += Time.DeltaTime;
        obj.transform.position = Vector3.Lerp(obj.transform.position, newPosition, timeSinceStarted);

        // If the object has arrived, stop the coroutine
        if (obj.transform.position == newPosition)
        {
            yield break;
        }

        // Otherwise, continue next frame
        yield return null;
    }
}

A: A simple solution is immediately after the Lerp function actually set the object's position to the desired position
here's what it should look like
carObject.transform.position = Vector3.Lerp (oldCarPos, newCarPos, Time.deltaTime * 2.0f);
carObject.transform.position = newCarPos;


text:
Q: Failed image loading in Stencil Theme I have a background image that fails to load in a BigCommerce Stencil theme only once the theme is deployed.
I am loading the image via CSS:
background-image: url(/assets/img/backgrounds/background_flag@700x394@72ppi.jpg);
The final URL outputted:
http://cdn3.bigcommerce.com/assets/img/backgrounds/background_flag@700x394@72ppi.jpg (not found)
What am I missing?


text:
Q: Create VectorDrawable from String (path)? Is there a way to get SVG path string from the API and create VectorDrawable dynamically?
I have been trying to do this for hours without success. Even more, all (!) examples on the Internet explain creating VectorDrawable from XML resources.
In my case, XML resource file is pointless as I am trying to fetch SVG path from the Internet API.

A: Inflating a drawable from a XML file instead of from resources is actually impossible, because the drawable will try to cast the XmlPullParser to XmlResourceParser which is only implemented by private class XmlBlock.Parser. Even that parser is only used for parsing binary XML files. I tried every possible way of doing this without reflection, it's impossible.
So I found documentation on binary XML files and learned how they were made, helped with some compiled binary XML vector drawable files I had. The documentation dates back to 2011 and is still valid, I guess it will most likely remain this way, so future compatibility isn't an issue.
A previous version was tested for more than a thousand paths, without problem. The new version posted here should work just as well. (Previous versions are available in the answer history) Compared with loading a drawable directly from resources, I found that there's an average of 14 microseconds or so of extra loading, not noticeable.
Here's the code:
public class VectorDrawableCreator {

    private static final byte[][] BIN_XML_STRINGS = {
            "width".getBytes(),
            "height".getBytes(),
            "viewportWidth".getBytes(),
            "viewportHeight".getBytes(),
            "fillColor".getBytes(),
            "pathData".getBytes(),
            "path".getBytes(),
            "vector".getBytes(),
            "http://schemas.android.com/apk/res/android".getBytes()
    };

    private static final int[] BIN_XML_ATTRS = {
            android.R.attr.height,
            android.R.attr.width,
            android.R.attr.viewportWidth,
            android.R.attr.viewportHeight,
            android.R.attr.fillColor,
            android.R.attr.pathData
    };

    private static final short CHUNK_TYPE_XML = 0x0003;
    private static final short CHUNK_TYPE_STR_POOL = 0x0001;
    private static final short CHUNK_TYPE_START_TAG = 0x0102;
    private static final short CHUNK_TYPE_END_TAG = 0x0103;
    private static final short CHUNK_TYPE_RES_MAP = 0x0180;

    private static final short VALUE_TYPE_DIMENSION = 0x0500;
    private static final short VALUE_TYPE_STRING = 0x0300;
    private static final short VALUE_TYPE_COLOR = 0x1D00;
    private static final short VALUE_TYPE_FLOAT = 0x0400;

    /**
     * Create a vector drawable from a list of paths and colors
     * @param width drawable width
     * @param height drawable height
     * @param viewportWidth vector image width
     * @param viewportHeight vector image height
     * @param paths list of path data and colors
     * @return the vector drawable or null it couldn't be created.
     */
    public static Drawable getVectorDrawable(@NonNull Context context,
                                             int width, int height,
                                             float viewportWidth, float viewportHeight,
                                             List<PathData> paths) {
        byte[] binXml = createBinaryDrawableXml(width, height, viewportWidth, viewportHeight, paths);

        try {
            // Get the binary XML parser (XmlBlock.Parser) and use it to create the drawable
            // This is the equivalent of what AssetManager#getXml() does
            @SuppressLint("PrivateApi")
            Class<?> xmlBlock = Class.forName("android.content.res.XmlBlock");
            Constructor xmlBlockConstr = xmlBlock.getConstructor(byte[].class);
            Method xmlParserNew = xmlBlock.getDeclaredMethod("newParser");
            xmlBlockConstr.setAccessible(true);
            xmlParserNew.setAccessible(true);
            XmlPullParser parser = (XmlPullParser) xmlParserNew.invoke(
                    xmlBlockConstr.newInstance((Object) binXml));

            if (Build.VERSION.SDK_INT >= 24) {
                return Drawable.createFromXml(context.getResources(), parser);
            } else {
                // Before API 24, vector drawables aren't rendered correctly without compat lib
                final AttributeSet attrs = Xml.asAttributeSet(parser);
                int type = parser.next();
                while (type != XmlPullParser.START_TAG) {
                    type = parser.next();
                }
                return VectorDrawableCompat.createFromXmlInner(context.getResources(), parser, attrs, null);
            }

        } catch (Exception e) {
            Log.e(VectorDrawableCreator.class.getSimpleName(), "Vector creation failed", e);
        }
        return null;
    }

    private static byte[] createBinaryDrawableXml(int width, int height,
                                                  float viewportWidth, float viewportHeight,
                                                  List<PathData> paths) {
        List<byte[]> stringPool = new ArrayList<>(Arrays.asList(BIN_XML_STRINGS));
        for (PathData path : paths) {
            stringPool.add(path.data);
        }

        ByteBuffer bb = ByteBuffer.allocate(8192);  // Capacity might have to be greater.
        bb.order(ByteOrder.LITTLE_ENDIAN);

        int posBefore;

        // ==== XML chunk ====
        // https://justanapplication.wordpress.com/2011/09/22/android-internals-binary-xml-part-two-the-xml-chunk/
        bb.putShort(CHUNK_TYPE_XML);  // Type
        bb.putShort((short) 8);  // Header size
        int xmlSizePos = bb.position();
        bb.position(bb.position() + 4);

        // ==== String pool chunk ====
        // https://justanapplication.wordpress.com/2011/09/15/android-internals-resources-part-four-the-stringpool-chunk/
        int spStartPos = bb.position();
        bb.putShort(CHUNK_TYPE_STR_POOL);  // Type
        bb.putShort((short) 28);  // Header size
        int spSizePos = bb.position();
        bb.position(bb.position() + 4);
        bb.putInt(stringPool.size());  // String count
        bb.putInt(0);  // Style count
        bb.putInt(1 << 8);  // Flags set: encoding is UTF-8
        int spStringsStartPos = bb.position();
        bb.position(bb.position() + 4);
        bb.putInt(0);  // Styles start

        // String offsets
        int offset = 0;
        for (byte[] str : stringPool) {
            bb.putInt(offset);
            offset += str.length + (str.length > 127 ? 5 : 3);
        }

        posBefore = bb.position();
        bb.putInt(spStringsStartPos, bb.position() - spStartPos);
        bb.position(posBefore);

        // String pool
        for (byte[] str : stringPool) {
            if (str.length > 127) {
                byte high = (byte) ((str.length & 0xFF00 | 0x8000) >>> 8);
                byte low = (byte) (str.length & 0xFF);
                bb.put(high);
                bb.put(low);
                bb.put(high);
                bb.put(low);
            } else {
                byte len = (byte) str.length;
                bb.put(len);
                bb.put(len);
            }
            bb.put(str);
            bb.put((byte) 0);
        }

        if (bb.position() % 4 != 0) {
            // Padding to align on 32-bit
            bb.put(new byte[4 - (bb.position() % 4)]);
        }

        // Write string pool chunk size
        posBefore = bb.position();
        bb.putInt(spSizePos, bb.position() - spStartPos);
        bb.position(posBefore);

        // ==== Resource map chunk ====
        // https://justanapplication.wordpress.com/2011/09/23/android-internals-binary-xml-part-four-the-xml-resource-map-chunk/
        bb.putShort(CHUNK_TYPE_RES_MAP);  // Type
        bb.putShort((short) 8);  // Header size
        bb.putInt(8 + BIN_XML_ATTRS.length * 4);  // Chunk size
        for (int attr : BIN_XML_ATTRS) {
            bb.putInt(attr);
        }

        // ==== Vector start tag ====
        int vstStartPos = bb.position();
        int vstSizePos = putStartTag(bb, 7, 4);

        // Attributes
        // android:width="24dp", value type: dimension (dp)
        putAttribute(bb, 0, -1, VALUE_TYPE_DIMENSION, (width << 8) + 1);

        // android:height="24dp", value type: dimension (dp)
        putAttribute(bb, 1, -1, VALUE_TYPE_DIMENSION, (height << 8) + 1);

        // android:viewportWidth="24", value type: float
        putAttribute(bb, 2, -1, VALUE_TYPE_FLOAT, Float.floatToRawIntBits(viewportWidth));

        // android:viewportHeight="24", value type: float
        putAttribute(bb, 3, -1, VALUE_TYPE_FLOAT, Float.floatToRawIntBits(viewportHeight));

        // Write vector start tag chunk size
        posBefore = bb.position();
        bb.putInt(vstSizePos, bb.position() - vstStartPos);
        bb.position(posBefore);

        for (int i = 0; i < paths.size(); i++) {
            // ==== Path start tag ====
            int pstStartPos = bb.position();
            int pstSizePos = putStartTag(bb, 6, 2);

            // android:fillColor="#aarrggbb", value type: #rgb.
            putAttribute(bb, 4, -1, VALUE_TYPE_COLOR, paths.get(i).color);

            // android:pathData="...", value type: string
            putAttribute(bb, 5, 9 + i, VALUE_TYPE_STRING, 9 + i);

            // Write path start tag chunk size
            posBefore = bb.position();
            bb.putInt(pstSizePos, bb.position() - pstStartPos);
            bb.position(posBefore);

            // ==== Path end tag ====
            putEndTag(bb, 6);
        }

        // ==== Vector end tag ====
        putEndTag(bb, 7);

        // Write XML chunk size
        posBefore = bb.position();
        bb.putInt(xmlSizePos, bb.position());
        bb.position(posBefore);

        // Return binary XML byte array
        byte[] binXml = new byte[bb.position()];
        bb.rewind();
        bb.get(binXml);

        return binXml;
    }

    private static int putStartTag(ByteBuffer bb, int name, int attributeCount) {
        // https://justanapplication.wordpress.com/2011/09/25/android-internals-binary-xml-part-six-the-xml-start-element-chunk/
        bb.putShort(CHUNK_TYPE_START_TAG);
        bb.putShort((short) 16);  // Header size
        int sizePos = bb.position();
        bb.putInt(0); // Size, to be set later
        bb.putInt(0);  // Line number: None
        bb.putInt(-1);  // Comment: None

        bb.putInt(-1);  // Namespace: None
        bb.putInt(name);
        bb.putShort((short) 0x14);  // Attributes start offset
        bb.putShort((short) 0x14);  // Attributes size
        bb.putShort((short) attributeCount);  // Attribute count
        bb.putShort((short) 0);  // ID attr: none
        bb.putShort((short) 0);  // Class attr: none
        bb.putShort((short) 0);  // Style attr: none

        return sizePos;
    }

    private static void putEndTag(ByteBuffer bb, int name) {
        // https://justanapplication.wordpress.com/2011/09/26/android-internals-binary-xml-part-seven-the-xml-end-element-chunk/
        bb.putShort(CHUNK_TYPE_END_TAG);
        bb.putShort((short) 16);  // Header size
        bb.putInt(24);  // Chunk size
        bb.putInt(0);  // Line number: none
        bb.putInt(-1);  // Comment: none
        bb.putInt(-1);  // Namespace: none
        bb.putInt(name);  // Name: vector
    }

    private static void putAttribute(ByteBuffer bb, int name,
                                     int rawValue, short valueType, int valueData) {
        // https://justanapplication.wordpress.com/2011/09/19/android-internals-resources-part-eight-resource-entries-and-values/#struct_Res_value
        bb.putInt(8);  // Namespace index in string pool (always the android namespace)
        bb.putInt(name);
        bb.putInt(rawValue);
        bb.putShort((short) 0x08);  // Value size
        bb.putShort(valueType);
        bb.putInt(valueData);
    }

    public static class PathData {

        public byte[] data;
        public int color;

        public PathData(byte[] data, int color) {
            this.data = data;
            this.color = color;
        }

        public PathData(String data, int color) {
            this(data.getBytes(StandardCharsets.UTF_8), color);
        }

    }

}

A call to getVectorDrawable returns a VectorDrawable from a list of paths. The drawable can contain multiple paths with different colors. There are also parameters for the drawable and viewport size.
Here's an example:
List<PathData> pathList = Arrays.asList(new PathData("M128.09 5.02a110.08 110.08 0 0 0-110 110h220a109.89 109.89 0 0 0-110-110z", Color.parseColor("#7cb342")),
                    new PathData("M128.09 115.02h-110a110.08 110.08 0 0 0 110 110 110.08 110.08 0 0 0 110-110z", Color.parseColor("#8bc34a")),
                    new PathData("M207.4 115.2v-.18h-5.1l-61.43-61.43h-25.48v20.6h-6.5a11.57 11.57 0 0 0-11.53 11.53v26.09h.11c-.11.9.5 2 1.7 3.32.12.08.12.08.12.2l3.96 4-46.11 79.91c5.33 4.5 11.04 8.4 17 11.8a109.81 109.81 0 0 0 108.04 0 110.04 110.04 0 0 0 51.52-64.65c.38-1.28.68-2.57 1.1-3.78z", Color.parseColor("#30000000")),
                    new PathData("M216.28 230.24a6.27 6.27 0 0 0-.9-2.8l-31.99-55.57-10.58-18.48-19.85-34.21-15.08 15.12 18.6 32.28 10.2 17.73 30.92 53.37a5.6 5.6 0 0 0 1.97 2.12l15.42 10.5c.6.39 1.29.39 1.9.08.6-.37.9-.98.9-1.7z", Color.parseColor("#e1e1e1")),
                    new PathData("M186.98 115.02a58.9 58.9 0 0 1-30.5 51.6 58.4 58.4 0 0 1-56.7 0l18.6-32.28-15.13-15.12-62.48 108.22c-.5.9-.8 1.78-.9 2.8l-1.4 18.6c-.12.71.3 1.28.9 1.7.6.37 1.29.3 1.9-.12l15.41-10.4a7.87 7.87 0 0 0 1.97-2.07l30.92-53.53a78.74 78.74 0 0 0 77.23 0 76.65 76.65 0 0 0 16.6-12.4 79.3 79.3 0 0 0 24.07-56.89z", Color.parseColor("#f1f1f1")),
                    new PathData("M147.3 74.12h-6.43v-20.6h-25.48v20.6h-6.5a11.57 11.57 0 0 0-11.53 11.5v26.07h.11c-.11 1.02.5 2.12 1.82 3.4l23.05 23.14a8.3 8.3 0 0 0 5.75 2.38v-.07l.07.07c2.12 0 4.2-.75 5.71-2.38l23.1-23.1c1.32-1.32 1.81-2.53 1.81-3.4h.12V85.7a11.68 11.68 0 0 0-11.6-11.6zm-19.14 40.9h-.07a15.4 15.4 0 0 1 0-30.8v-.2l.07.2a15.46 15.46 0 0 1 15.31 15.38 15.46 15.46 0 0 1-15.3 15.42z", Color.parseColor("#646464")));

A: @Andre.Anzi To extend the class to support strokeColor and strokeWidth, you can try to arrange the attributes in an alphabetical order.


text:
Q: Custom Facebook Pages not viewable (blank page) for some users I've followed this tutorial to create a custom page on some facebook pages; now the problem is that some people can't see anything: they can see only a blank page inside facebook
The pages are:
https://www.facebook.com/AmbassadorRicevimenti (clicking on Home tab some people can't see my html page)
https://www.facebook.com/pages/Le-torte-di-Antonietta/173602889364785 (clicking on Home tab some people can't see my html page)
For these pages I've got both https and http urls; I've even tried to put only "hello word" in these pages, but nothing, some people can't see anything.
Obviously sandbox mode is off, so everyone can see the page.
I've seen that this blank page happens both with facebook logged users, and with not logged users (so people that tries to see the page without logging on facebook, but using a direct link); many other people (logged and not) can see the page without problems.

A: For me it looks like the Secure Page Tab URLs for your Tab Application are working fine, but your Page Tab URLs are not.  For both of the Facebook pages you shared, I can see your App content if I'm browsing over https but not for http.  On both pages I see the error message "Loggati su Facebook per vedere questa pagina. Grazie mille," when viewing the Tab over http. (This translates to "Log into Facebook" in Italian, but I am logged in.)
Are your sure the http URL is working properly?
Do you have any App settings or features in your http URL that would break the page when it is viewed over http instead of https?

A: Sounds like it could be related to your server sending the HTTP Header X-Frame-Options, that when set to DENY forbids browsers to iframe the served document.
There is an option ALLOW facebook.com (or other domain), but according to MDN is not well supported yet.
Some browsers ignoring this setting would explain the behaviour you see.


text:
Q: navbar background isnt trasnparent but instead the color of the backgrounds completely So when coding my website i have an issue where when i tried to make the background transparent but it shows like a solid bar instead, could it possibly be embedded into my other code?
.navbar {
position: fixed;
top: 0;
right: 5%;
z-index: 1;
display: flex;
background: transparent;}

the issue

A: I recommend use opacity to make transparent background!
Just go through this link on W3schools you will understand the concept of transparency and opacity.


text:
Q: Django REST framework on primary key I am currently trying to display multiple models with a primary key to find that specific data but I am encountering the following error: selected() got an unexpected keyword argument 'pk'
Here is the code:
views.py
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .serializers import DeviceSerializers, DeviceDetailSerializers
@api_view(['GET'])
def selected(request,pk):
    devices = Device.objects.all(pk=pk)
    devicedetail = DeviceDetail.objects.all(DD2DKEY=pk)
    devserializer = DeviceSerializers(devices, many = True)
    devdserializer = DeviceDetailSerializers(devicedetail, many = True)
    results = devserializer.data + devdserializer.data
    return Response(results)

serializers.py
from rest_framework import serializers
from .models import Device, DeviceDetail

class DeviceSerializers(serializers.ModelSerializer):
    class Meta:
        model=Device
        fields = '__all__'

class DeviceDetailSerializers(serializers.ModelSerializer):
    class Meta:
        model = DeviceDetail
        fields = '__all__'

models.py
class Device(models.Model):
    hostname = models.CharField(max_length=50, unique = True)
    ipaddr = models.GenericIPAddressField(protocol='ipv4', unique=True, verbose_name='mangement IP') ##Use for mgt_id_addr
    date_added = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.hostname

class DeviceDetail(models.Model):

    SUBNET_CHOICES = (
    ('16','16'),
    ('17', '17'),
    ('18','18'),
    ('19','19'),
    ('20','20'),
    ('21', '21'),
    ('22', '22'),
    ('23', '23'),
    ('24', '24'),
    ('25', '25'),
    ('26', '26'),
    ('27', '27'),
    ('28', '28'),
    ('29', '29'),
    ('30', '30'),
    )

    DEV_MODS =(
        ('Catalyst 9606R', 'Catalyst 9606R'),
        ('C9300L-48T-4X', 'C9300L-48T-4X')
    )

    mgt_interface = models.CharField(max_length=50)
    subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES)
    ssh_id = models.CharField(max_length=50)
    ssh_pwd = models.CharField(max_length=50)
    enable_secret = models.CharField(max_length=50)
    dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement
    DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables

    def __str__(self):
        return self.hostname

urls.py (In app)
from django.urls import path
from .views import DeviceListView
from . import views
from .views import devicelist
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [

    path('selecteddevice/<int:pk>', views.selected),
]

Is passing a primary key not allowed for the Django Rest framework? I coded the views with the knowledge of coding for the views for the HTML pages but it does not seem to work. For the URL, i typed 127.0.0.1/selecteddevice/179 for example. My database has the record of 179
Traceback in my powershell:
Traceback (most recent call last):
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\P1338475\.virtualenvs\django_swing-t91g66f4\lib\site-packages\rest_framework\decorators.py", line 50, in handler
    return func(*args, **kwargs)
TypeError: selected() got an unexpected keyword argument 'pk'

A: Not an expert but You can try this:
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .serializers import DeviceSerializers, DeviceDetailSerializers
@api_view(['GET'])
def selected(request,pk=None):
    if pk != None:
        devices = Device.objects.filter(id=pk)
        print(devices)
        devicedetail = DeviceDetail.objects.filter(DD2DKEY=pk)

        devserializer = DeviceSerializers(devices, many=True)
        devdserializer = DeviceDetailSerializers(devicedetail, many=True)
        results = {
            "dev":devserializer.data,
            "devd" : devdserializer.data,
        }
        # results = devserializer.data + devdserializer.data
        return Response(results)


text:
Q: Assistance with Lua functions As noted before, I'm relatively new to lua, but again, I learn quick.  The last time I got help here, it helped me immensely, and I was able to write a better script.  Now I've come to another question that I think will make my life a bit easier.  I have no clue what I'm doing with functions, but I'm hoping there is a way to do what I want to do here.  Below, you'll see an example of code I have to do to strip down some unneeded elements.  Yeah, I realize it's not efficient in the least, so if anyone else has a better idea of how to make it much more efficient, I'm all ears.  What I would like to do is create a function with it so that I can strip down whatever variable with a simple call of it (like stripdown(winds)).  I appreciate any help that is offered, and any lessons given.  Thanks!
winds = string.gsub(winds,"%b<>","")
winds = string.gsub(winds,"%c"," ")
winds = string.gsub(winds,"  "," ")
winds = string.gsub(winds,"  "," ")
winds = string.gsub(winds,"^%s*(.-)%s*$", "%1)")
winds = string.gsub(winds," ","")
winds = string.gsub(winds,"/ ", "(")

Josh

A: This should be slightly better:
function stripdown(str)
    return (str:gsub("%b<>","")
               :gsub("[%c ]+"," ")
               :gsub("^%s*(.-)%s*$", "%1)")
               :gsub(" ","")
               :gsub("/ ", "("))
end

Reduced 3 of the patterns down to one;
The brackets around the return expression reduce the output to only the first return value from gsub.

A: For a function like this, I'm a huge fan of object syntax:
function stripdown(winds)
    winds = winds:gsub("%b<>","")
                 :gsub("%c"," ")
                 :gsub("  "," ")
                 :gsub("  "," ")
                 :gsub("^%s*(.-)%s*$", "%1)")
                 :gsub(" ","")
                 :gsub("/ ", "(")
    return winds
end

This version is no more or less efficient than the other, but there's a lot less syntactic noise and I find it easier to see what's going on.
There's a technical reason for not simply returning the big expression, and that's because gsub returns two results.
Assigning it to winds "adjusts" away the (unwanted) second result, and the function returns only the string.

A: Turning it into a function is the easy part.
function stripdown(winds)
    winds = string.gsub(winds,"%b<>","")
    winds = string.gsub(winds,"%c"," ")
    winds = string.gsub(winds,"  "," ")
    winds = string.gsub(winds,"  "," ")
    winds = string.gsub(winds,"^%s*(.-)%s*$", "%1)")
    winds = string.gsub(winds," ","")
    winds = string.gsub(winds,"/ ", "(")
    return winds
end

This function as written does produce and abandon a lot of intermediate string results, which can be a relatively expensive operation. It is almost certainly worth careful study of the documentation for string.gsub() and its pattern language. It should be possible to do at least some of what you've specified in fewer operations.


text:
Q: Unknown provider: $scopeProvider <- $scope I am trying to make a small test work that validates wether the controller is defined.
The error I am receiving is:
myApp.orders module Order controller should .... FAILED
    Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- OrdersCtrl

Reading similar errors it has something to do with the dependencies, but I don't know what's wrong.
Controller:
'use strict';

angular.module('myApp.orders', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/orders', {
    templateUrl: 'orders/orders.template.html',
    controller: 'OrdersCtrl'
  });
}])

.controller('OrdersCtrl', function($scope, $location) {
  $scope.changeView = function(view){
    $location.path(view); // path not hash
  }
});

Test:
'use strict';

describe('myApp.orders module', function() {

  beforeEach(module('myApp.orders'));

  describe('Order controller', function(){

    it('should ....', inject(function($controller) {
      //spec body
      var OrdersCtrl = $controller('OrdersCtrl');
      expect(OrdersCtrl).toBeDefined();
    }));

  });
});

A: This is because you are not passing the $scope variabl einside the controller when you are creating it in test. And the controller tries to define $scope.changeView, but it finds $scope as undefined.
You need to pass a $scope variable to the controller in your test.
var $rootScope, $scope, $controller;

beforeEach(function() {
    module('myApp.orders');

    inject(function (_$rootScope_, _$controller_) {
        $rootScope = _$rootScope_;
        $scope = _$rootScope_.$new();
        $controller = _$controller_;
    });
});

and in your test,
var OrdersCtrl = $controller('OrdersCtrl', { $scope: $scope });

A: Restructure your unit test slightly. We have a pattern where the controller is defined in the beforeEach() so it's ready for the test. You also need to import the controller you're testing:
import ControllerToTest from 'path/to/your/real/controller';
describe('myApp.orders module',() => {
  let vm;
  beforeEach(() => {
    inject(($controller, $rootScope) => {
      vm = $controller(ControllerToTest,
        {
          $scope: $rootScope.$new()
        };
    });
  });

  describe('Order Controller', () => {
    it('should do something', () => {
      expect(vm).toBeDefined();
    });
  });
});

A: Chaneg your controller like this
   .controller('OrdersCtrl',['$scope', '$location', function($scope, $location) {
       $scope.changeView = function(view){
        $location.path(view); // path not hash
      }
    }]);


text:
Q: Dplyr join on maximum matching value, if no exact match is possible I'm trying to join two tables in dplyr. Sometimes it's possible to match exact on the column year, but in some cases the matching year is not available.
In that case, i would like to join on the maximum year
Left <- tibble(id = c(1,2,3),
           year = c(2010,2010,2012))

Right <- tibble(id = c(1,1,2,3,3),
            year = c(2010,2011,2010,2010,2011),
            new = c(T,T,T,T,T))

Joined <- left_join(Left, Right, by = c("id", "year"))

# A tibble: 3 x 3
     id  year   new
  <dbl> <dbl> <lgl>
1     1  2010  TRUE
2     2  2010  TRUE
3     3  2012    NA

As you can see, id 3 is not matched, I tried the package fuzzyjoin, but i'm unable to fuzzy-join on one column, and exact-join on another:
Fuzzy_joined <- fuzzyjoin::difference_left_join(Left, Right, by = c("id", "year"))
Fuzzy_joined
# A tibble: 9 x 5
   id.x year.x  id.y year.y   new
  <dbl>  <dbl> <dbl>  <dbl> <lgl>
1     1   2010     1   2010  TRUE
2     1   2010     1   2011  TRUE
3     1   2010     2   2010  TRUE
4     2   2010     1   2010  TRUE
5     2   2010     1   2011  TRUE
6     2   2010     2   2010  TRUE
7     2   2010     3   2010  TRUE
8     2   2010     3   2011  TRUE
9     3   2012     3   2011  TRUE

What is the most efficient way to join non-matching cases on the smallest distance of a the year variable, and an exact match of the id variable, using dplyr syntax?

A: I would use a left join on id and year and then filter to get the best match for year
left_join(Left, Right, by = "id", suffix  = c("", "_r")) %>%
  mutate(delta = year - year_r) %>%
  filter(delta >= 0) %>%
  group_by(id, year) %>%
  slice(which.min(delta)) %>%
  select(-delta)

# A tibble: 3 x 4
# Groups:   id, year [3]
     id  year year_r   new
  <dbl> <dbl>  <dbl> <lgl>
1     1  2010   2010  TRUE
2     2  2010   2010  TRUE
3     3  2012   2011  TRUE

There might be more efficient solutions, but this will work well with moderate-sized data sets.


text:
Q: 404 Redirect is not working In my htaccess file my ErrorDocument 404 statement is not redirecting to index.php. Instead, i'm getting a regular 404 error. This is a regular apache installation.
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    #Removes access to the system folder by users.
    #Additionally this will allow you to create a System.php controller,
    #previously this would not have been possible.
    #'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file,
    #such as an image or css document, if this isn't true it sends the
    #request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    # Submitted by: ElliotHaughin

    ErrorDocument 404 /index.php
</IfModule>

A: Need more information here. Are getting CodeIgniter's 404 or Apache's 404?
If you're getting CodeIgniter's 404, it's working as expected.

A: I got it sorted. I went with a custom error handling router in Code Igniter and skipped the .htaccess file. I didn't have direct access to the clients server so I made the changes on my own and gave them a standard .htaccess file for CI. It just made my life simpler to go that route.


text:
Q: Getting CWWKF0044E incompatible feature error using Open Liberty with Maven, but I didn't configure incompatible features When using Open Liberty version 22.0.0.5 and liberty-maven-plugin version 3.3 with a server config (server.xml) configuring just a single feature:
    <featureManager>
        <feature>batch-2.0</feature>
    </featureManager>

and running "dev mode" (via mvn liberty:dev), I get this error as dev mode starts the server:

[INFO] [ERROR   ] CWWKF0044E: The
io.openliberty.connectionManager1.0.internal.ee-6.0 and batch-2.0
features cannot be loaded at the same time. The
io.openliberty.connectionManager1.0.internal.ee-6.0 feature of Java EE
6 is incompatible with the batch-2.0 feature of Jakarta EE 9. The
batch-2.0 and batch-2.0 configured features include an incompatible
combination of features. Your configuration is not supported. Update
the configuration to use features that support either the Java EE or
Jakarta EE programming models, but not both.
[INFO] [WARNING ] CWWKF0046W: The configuration includes an
incompatible combination of features. As a result, the feature manager
did not install any features.

A: SOLUTION
This is a bug. To resolve, update liberty-maven-plugin to the latest version (or at least to version 3.4, where this was fixed).
The bug is described here from the runtime angle, as it was an issue with the way the liberty-maven-plugin queries the Open Liberty runtime for feature versions.


text:
Q: Pandas apply, rolling, groupby with multiple input & multiple output columns I've been struggling the past week trying to use apply to use functions over an entire pandas dataframe, including rolling windows, groupby, and especially multiple input columns and multiple output columns. I found a large amount of questions on SO about this topic and many old & outdated answers. So I started to create a notebook for every possible combination of x inputs & outputs, rolling, rolling & groupby combined and I focused on performance as well. Since I'm not the only one struggling with these questions I thought I'd provide my solutions here with working examples, hoping it helps any existing/future pandas-users.

A: Important notes

*

*The combination of apply & rolling in pandas has a very strong output requirement. You have to return one single value. You can not return a pd.Series, not a list, not an array, not secretly an array within an array, but just one value, e.g. one integer. This requirement makes it hard to get a working solution when trying to return multiple outputs for multiple columns. I don't understand why it has this requirement for 'apply & rolling', because without rolling 'apply' doesn't have this requirement. Must be due to some internal pandas functions.

*The combination of 'apply & rolling' combined with multiple input columns simply does not work! Imagine a dataframe with 2 columns, 6 rows and you want to apply a custom function with a rolling window of 2. Your function should get an input array with 2x2 values - 2 values of each column for 2 rows. But it seems pandas can't handle rolling and multiple input columns at the same time. I tried to use the axis parameter to get it working but:

*

*Axis = 0, will call your function per column. In the dataframe described above, it will call your function 10 times (not 12 because rolling=2) and since it's per column, it only provides the 2 rolling values of that column…

*Axis = 1, will call your function per row. This is what you probably want, but pandas will not provide a 2x2 input. It actually completely ignores the rolling and only provides one row with values of 2 columns...

*When using 'apply' with multiple input columns, you can provide a parameter called raw (boolean). It's False by default, which means the input will be a pd.Series and thus includes indexes next to the values. If you don't need the indexes you can set raw to True to get a Numpy array, which often achieves a much better performance.

*When combining 'rolling & groupby', it returns a multi-indexes series which can't easily serve as an input for a new column. The easiest solution is to append a reset_index(drop=True) as answered & commented here (Python - rolling functions for GroupBy object).

*You might ask me, when would you ever want to use a rolling, groupby custom function with multiple outputs!? Answer: I recently had to do a Fourier transform with sliding windows (rolling) over a dataset of 5 million records (speed/performance is important) with different batches within the dataset (groupby). And I needed to save both the power & phase of the Fourier transform in different columns (multiple outputs). Most people probably only need some of the basic examples below, but I believe that especially in the Machine Learning/Data-science sectors the more complex examples can be useful.

*Please let me know if you have even better, clearer or faster ways to perform any of the solutions below. I'll update my answer and we can all benefit!

Code examples
Let's create a dataframe first that will be used in all the examples below, including a group-column for the groupby examples.
For the rolling window and multiple input/output columns I just use 2 in all code examples below, but obviously this could be any number > 1.
df = pd.DataFrame(np.random.randint(0,5,size=(6, 2)), columns=list('ab'))
df['group'] = [0, 0, 0, 1, 1, 1]
df = df[['group', 'a', 'b']]

It will look like this:
group   a   b
0   0   2   2
1   0   4   1
2   0   0   4
3   1   0   2
4   1   3   2
5   1   3   0

Input 1 column, output 1 column
Basic
def func_i1_o1(x):
    return x+1

df['c'] = df['b'].apply(func_i1_o1)

Rolling
def func_i1_o1_rolling(x):
    return (x[0] + x[1])

df['d'] = df['c'].rolling(2).apply(func_i1_o1_rolling, raw=True)

Roling & Groupby
Add the reset_index solution (see notes above) to the rolling function.
df['e'] = df.groupby('group')['c'].rolling(2).apply(func_i1_o1_rolling, raw=True).reset_index(drop=True)

Input 2 columns, output 1 column
Basic
def func_i2_o1(x):
    return np.sum(x)

df['f'] = df[['b', 'c']].apply(func_i2_o1, axis=1, raw=True)

Rolling
As explained in point 2 in the notes above, there isn't a 'normal' solution for 2 inputs. The workaround below uses the 'raw=False' to ensure the input is a pd.Series, which means we also get the indexes next to the values. This enables us to get values from other columns at the correct indexes to be used.
def func_i2_o1_rolling(x):
    values_b = x
    values_c = df.loc[x.index, 'c'].to_numpy()
    return np.sum(values_b) + np.sum(values_c)

df['g'] = df['b'].rolling(2).apply(func_i2_o1_rolling, raw=False)

Rolling & Groupby
Add the reset_index solution (see notes above) to the rolling function.
df['h'] = df.groupby('group')['b'].rolling(2).apply(func_i2_o1_rolling, raw=False).reset_index(drop=True)

Input 1 column, output 2 columns
Basic
You could use a 'normal' solution by returning pd.Series:
def func_i1_o2(x):
    return pd.Series((x+1, x+2))

df[['i', 'j']] = df['b'].apply(func_i1_o2)

Or you could use the zip/tuple combination which is about 8 times faster!
def func_i1_o2_fast(x):
    return x+1, x+2

df['k'], df['l'] = zip(*df['b'].apply(func_i1_o2_fast))

Rolling
As explained in point 1 in the notes above, we need a workaround if we want to return more than 1 value when using rolling & apply combined. I found 2 working solutions.
1
def func_i1_o2_rolling_solution1(x):
    output_1 = np.max(x)
    output_2 = np.min(x)
    # Last index is where to place the final values: x.index[-1]
    df.at[x.index[-1], ['m', 'n']] = output_1, output_2
    return 0

df['m'], df['n'] = (np.nan, np.nan)
df['b'].rolling(2).apply(func_i1_o2_rolling_solution1, raw=False)

Pros: Everything is done within 1 function.
Cons: You have to create the columns first and it is slower since it doesn't use the raw input.
2
rolling_w = 2
nan_prefix = (rolling_w - 1) * [np.nan]
output_list_1 = nan_prefix.copy()
output_list_2 = nan_prefix.copy()

def func_i1_o2_rolling_solution2(x):
    output_list_1.append(np.max(x))
    output_list_2.append(np.min(x))
    return 0

df['b'].rolling(rolling_w).apply(func_i1_o2_rolling_solution2, raw=True)
df['o'] = output_list_1
df['p'] = output_list_2

Pros: It uses the raw input which makes it about twice as fast. And since it doesn't use indexes to set the output values the code looks a bit more clear (to me at least).
Cons: You have to create the nan-prefix yourself and it takes a bit more lines of code.

Rolling & Groupby
Normally, I would use the faster 2nd solution above. However, since we're combining groups and rolling this means you'd have to manually set NaN's/zeros (depending on the number of groups) at the right indexes somewhere in the middle of the dataset. To me it seems that when combining rolling, groupby and multiple output columns, the first solution is easier and solves the automatic NaNs/grouping automatically. Once again, I use the reset_index solution at the end.
def func_i1_o2_rolling_groupby(x):
    output_1 = np.max(x)
    output_2 = np.min(x)
    # Last index is where to place the final values: x.index[-1]
    df.at[x.index[-1], ['q', 'r']] = output_1, output_2
    return 0

df['q'], df['r'] = (np.nan, np.nan)
df.groupby('group')['b'].rolling(2).apply(func_i1_o2_rolling_groupby, raw=False).reset_index(drop=True)

Input 2 columns, output 2 columns
Basic
I suggest using the same 'fast' way as for i1_o2 with the only difference that you get 2 input values to use.
def func_i2_o2(x):
    return np.mean(x), np.median(x)

df['s'], df['t'] = zip(*df[['b', 'c']].apply(func_i2_o2, axis=1))

Rolling
As I use a workaround for applying rolling with multiple inputs and I use another workaround for rolling with multiple outputs, you can guess I need to combine them for this one.
1. Get values from other columns using indexes (see func_i2_o1_rolling)
2. Set the final multiple outputs on the correct index (see func_i1_o2_rolling_solution1)
def func_i2_o2_rolling(x):
    values_b = x.to_numpy()
    values_c = df.loc[x.index, 'c'].to_numpy()
    output_1 = np.min([np.sum(values_b), np.sum(values_c)])
    output_2 = np.max([np.sum(values_b), np.sum(values_c)])
    # Last index is where to place the final values: x.index[-1]
    df.at[x.index[-1], ['u', 'v']] = output_1, output_2
    return 0

df['u'], df['v'] = (np.nan, np.nan)
df['b'].rolling(2).apply(func_i2_o2_rolling, raw=False)

Rolling & Groupby
Add the reset_index solution (see notes above) to the rolling function.
def func_i2_o2_rolling_groupby(x):
    values_b = x.to_numpy()
    values_c = df.loc[x.index, 'c'].to_numpy()
    output_1 = np.min([np.sum(values_b), np.sum(values_c)])
    output_2 = np.max([np.sum(values_b), np.sum(values_c)])
    # Last index is where to place the final values: x.index[-1]
    df.at[x.index[-1], ['w', 'x']] = output_1, output_2
    return 0

df['w'], df['x'] = (np.nan, np.nan)
df.groupby('group')['b'].rolling(2).apply(func_i2_o2_rolling_groupby, raw=False).reset_index(drop=True)


text:
Q: Why does this element move horizontally (only in IE) during CSS animation? EDIT: Happens on IE10, Win 7
I'm using transform to place the element horizontally and during animation, since I'm updating the vertical using transform, I also set horizontal to the same value as before but it moves!
Why is it changing horizontal despite the same value?
https://jsfiddle.net/kr0qz5b2/2/
HTML:

JavaScript:
document.querySelector( "img" ).onclick = function(event) {
  event.target.className = "test";
}

CSS:
html, body
{
  height: 100%;
}
.p
{
  position: relative;
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
  display: block;
  z-index: 2;
}
.c
{
  position: absolute;
  left: 0;
    top: 0%;
    height: 20%;
    width: 50%;
    text-align: center;
    display: block;
}

.c img
{
      position: absolute;
      top: 35%;
      left: 50%;
      -webkit-transform: translate(-50%,0em) perspective(1px);
      -ms-transform: translate(-50%,0em) perspective(1px);
      transform: translate(-50%,0em) perspective(1px);
      height: 40%;
      margin-left: auto;
      margin-right: auto;
      display: block;
}

@keyframes test
{
  0%, 50%, 100%
  {
    transform: translate(-50%,0em);
    -webkit-transform: translate(-50%,0em);
    -moz-transform: translate(-50%,0em);
  }

  25%
  {
    transform: translate(-50%,-.5em);
    -webkit-transform: translate(-50%,-.5em);
    -moz-transform: translate(-50%,-.5em);
  }

  75%
  {
    transform: translate(-50%,.5em);
    -webkit-transform: translate(-50%,.5em);
    -moz-transform: translate(-50%,.5em);
  }
}

.c img.test
{
  -webkit-animation-name: test;
  -moz-animation-name: test;
  animation-name: test;
  -webkit-animation-duration: 400ms;
  -moz-animation-duration: 400ms;
  animation-duration: 400ms;
  -webkit-animation-iteration-count: 3;
  -moz-animation-iteration-count: 3;
  animation-iteration-count: 3;
  -webkit-animation-timing-function: linear;
  -moz-animation-timing-function: linear;
  animation-timing-function: linear;
  -webkit-animation-fill-mode: none;
  -moz-animation-fill-mode: none;
  animation-fill-mode: none;
}

A: Remove the unused perspective transform on .c img to fix the animation.
-webkit-transform: translate(-50%,0em) perspective($perspective);
-ms-transform: translate(-50%,0em) perspective($perspective);
transform: translate(-50%,0em) perspective($perspective);

Becomes:
-webkit-transform: translate(-50%,0em);
-ms-transform: translate(-50%,0em);
transform: translate(-50%,0em);

A: As pointed out by @JonUleis, it appears there's a bug in IE 10 (on Win 7) where an animation with multiple iterations has a split-second unsetting of the element's styles between the iterations. This can cause blips and odd movements.
The only solution is to do 1 iteration and use the percentages to simulate multiple iterations. This does mean you cannot do it infinitely
https://jsfiddle.net/kr0qz5b2/17/
@keyframes test
{
  0%, 22%, 44%, 66%, 88%
  {
    transform: translate(-50%,0em);
    -webkit-transform: translate(-50%,0em);
    -moz-transform: translate(-50%,0em);
  }

  11%, 55%
  {
    transform: translate(-50%,-.5em);
    -webkit-transform: translate(-50%,-.5em);
    -moz-transform: translate(-50%,-.5em);
  }

  33%, 77%
  {
    transform: translate(-50%,.5em);
    -webkit-transform: translate(-50%,.5em);
    -moz-transform: translate(-50%,.5em);
  }
}

.c img.test
{
  -webkit-transform: translate(-50%,0em);
  -ms-transform: translate(-50%,0em);
  transform: translate(-50%,0em);
  -webkit-animation-name: test;
  -moz-animation-name: test;
  animation-name: test;
  -webkit-animation-duration: 1000ms;
  -moz-animation-duration: 1000ms;
  animation-duration: 1000ms;
  -webkit-animation-iteration-count: 1;
  -moz-animation-iteration-count: 1;
  animation-iteration-count: 1;
  -webkit-animation-timing-function: linear;
  -moz-animation-timing-function: linear;
  animation-timing-function: linear;
  -webkit-animation-fill-mode: forwards;
  -moz-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}


text:
Q: Get UITabBarController on presented ViewController/NavigationController I am presenting a Navigation Controller from a TabbarController
let planSettingsVC = PlanSettingsViewController.instantiateFromStoryboard()
let planInfoNavCon = UINavigationController(rootViewController: planSettingsVC)

if let myTabBarVC = self.tabBarController as? MyPlanTabBarController {
        myTabBarVC.present(planInfoNavCon, animated: true, completion: nil)
}

PlanInfoNavCon gets presented and now I want to access the TabBarController that presented it.
Found in Library:

open var tabBarController: UITabBarController? { get } // If the view controller has a tab bar controller as its ancestor, return it. Returns nil otherwise.

So I tried the following on PlanSettingsViewController

*

*print(self.tabBarController) Prints nil

*print(self.presentingViewController.tabBarController) Prints nil

*print(self.navigationController?.presentingViewController?.tabBarController) Prints nil

*print(self.navigationController.tabBarController) Prints nil

*self.navigationController?.presentingViewController as? MyPlanTabBarController Results in nil
I am able to access TabBarController on ViewController of TabBar by self.tabBarController but
How do I access the TabBarController which presented this?
P.S.
po self.navigationController returns <UINavigationController> and po self.navigationController?.presentingViewController returns <UIViewController>

A: This code:
if let myTabBarVC = self.tabBarController as? MyPlanTabBarController {
        myTabBarVC.present(planInfoNavCon, animated: true, completion: nil)
}

says: "Present planInfoNavCon from self.tabBarController"
Curious... it seems each VC in the NavController considers itself presented by the controller that presented the NavController... so...
You still don't need the extra .tabBarController part, but you also don't need to get a reference to the Nav Controller.
This code, in the current VC in PlanSettingsViewController, should get the proper reference to the tabBarController:
var thePresenter = self.presentingViewController as? MyPlanTabBarController

So, to get a reference to the tabBarController from planInfoNavCon, you want to get its presenter:
var thePresenter = self.navigationController?.presentingViewController

You don't want the extra .tabBarController part (may need other ? unwrapping - I'm not actually running this code).


text:
Q: How do I make it so that it will only accept a String from the first textField? My code is for an applet that expands a binomial. I haven't finished it, but it'll only accept an exponent between 1 and 10, inclusive. I got it to 7, but like I said, I haven't finished. My problem is this: in the first textField, it'll accept a number and a variable (like 4a, or something). And the code I wrote can't take into account that number (it's supposed to only accept a variable). So...How do I get it so that the first textField can't allow there to be an int? THANKS!
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.Action;

public class BinomialExpander extends JApplet implements ActionListener
{
  JLabel welcome;
  JLabel directions;
  JLabel example;

  JLabel instructions;
  JLabel startOfBinomial;
  JLabel plusSign;
  JLabel forExponent;
  JLabel endOfBinomial;

  JTextField firstVar;
  JTextField txtSecond;
  JTextField exp;

  JLabel lblExpanded;
  JLabel outputExpanded;
  FlowLayout layout;

  JButton compute;

  private int[] pascal1 = {1,1};
  private int[] pascal2 = {1,2,1};
  private int[] pascal3 = {1,3,3,1};
  private int[] pascal4 = {1,4,6,4,1};
  private int[] pascal5 = {1,5,10,10,5,1};
  private int[] pascal6 = {1,6,15,20,15,6,1};
  private int[] pascal7 = {1,7,21,35,35,21,7,1};
  private int[] pascal8 = {1,8,28,56,70,56,28,8,1};
  private int[] pascal9 = {1,9,36,84,126,84,36,9,1};
  private int[] pascal10 = {1,10,45,120,210,120,45,10,1};

  private String a;
  private int y;
  private int expo;
  private String x;

  public void init()
  {
      Container c = getContentPane();
      c.setBackground(Color.pink);

      layout = new FlowLayout();
      layout.setAlignment(FlowLayout.LEFT);
      c.setLayout(layout);
      setSize(500,175);

      welcome = new JLabel("Welcome to the Binomial Expander Applet!");
      welcome.setFont(new Font("Copperplate Gothic Bold", Font.PLAIN, 16));
      directions = new JLabel("Enter binomial ONLY in the form: (VARIABLE + NUMBER)^EXPONENT");
      directions.setFont(new Font("Times New Roman", Font.PLAIN, 14));
      example = new JLabel("EXAMPLE: (x + 2)^2.");
      instructions = new JLabel("Enter the variable of your binomial:");
      startOfBinomial = new JLabel(" (");
      firstVar = new JTextField(4);
      plusSign = new JLabel(" + ");
      txtSecond = new JTextField(4);
      endOfBinomial = new JLabel(")");
      forExponent = new JLabel("^");
      forExponent.setFont(new Font("Times New Roman", Font.PLAIN, 10));
      exp = new JTextField(2);
      compute = new JButton("Compute!");
      compute.addActionListener(this);
      lblExpanded = new JLabel("Your expanded binomial is: ");
      outputExpanded = new JLabel("");
      c.add(welcome);
      c.add(directions);
      c.add(example);
      c.add(instructions);
      c.add(startOfBinomial);
      c.add(firstVar);
      c.add(plusSign);
      c.add(txtSecond);
      c.add(endOfBinomial);
      c.add(forExponent);
      c.add(exp);
      c.add(compute);
      c.add(lblExpanded);
      c.add(outputExpanded);
  }
  public void actionPerformed(ActionEvent event)
  {
      a = firstVar.getText();
      y = Integer.parseInt(txtSecond.getText());
      expo = Integer.parseInt(exp.getText());

      outputExpanded.setText(expand());
  }
  public String expand()
  {
     if (expo < 1 || expo > 10)
     {
        x = "ERROR: Exponent value must be between 1 and 10, inclusive.";
        return x;
     }
     else if (expo == 1)
     {
        x = a + "+" + y;
        return x;
     }
     else if (expo == 2)
     {
        x = a + "^" + expo + " + " + (pascal2[1] * y) + a + " + " + (pascal2[2] * Math.pow(y, expo));
        return x;
     }
     else if (expo == 3)
     {
        x = a + "^" + expo + " + " + (pascal3[1] * y) + a + "^" + (expo-1) + (pascal3[2] * Math.pow(y, expo-1)) + a + " + " + (Math.pow(y, expo));
        return x;
     }
     else if (expo == 4)
     {
        x = a + "^" + expo + " + " + (pascal4[1] * y) + a + "^" + (expo-1) + " + " + (pascal4[2] * Math.pow(y, expo-2)) + a + " ^ " + (expo-2) + " + " + (pascal4[3] *
        Math.pow(y, expo-1)) + a + "+" + (Math.pow(y,expo));
        return x;
     }
     else if (expo == 5)
     {
        x = a + "^" + expo + " + " + (pascal5[1] * y) + a + "^" + (expo-1) + " + " + (pascal5[2] * Math.pow(y,expo-3)) + a + "^" + (expo-2) + " + " + (pascal5[3] *
        Math.pow(y, expo-2)) + a + "^" + (expo-3) + " + " + (pascal5[4] * Math.pow(y, expo-1)) + a + " + " + (Math.pow(y, expo));
        return x;
     }
     else if (expo == 6)
     {
        x = a + "^" + expo + " + " + (pascal6[1] * y) + a + "^" + (expo-1) + " + " + (pascal6[2] * Math.pow(y, expo-4)) + a + "^" + (expo-2) + " + " + (pascal6[3] *
        Math.pow(y, expo-3)) + a + "^" + (expo-3) + " + " + (pascal6[4] * Math.pow(y, expo-2)) + a + "^" + (expo-4) + " + " + (pascal6[5] * Math.pow(y, expo-1)) +
        a + " + " + (Math.pow(y,expo));
        return x;
     }
     else if (expo == 7)
     {
        x = a + "^" + expo + " + " + (pascal7[1] * y) + a + "^" + (expo-1) + " + " + (pascal7[2] * Math.pow(y, expo-5)) + a + "^" + (expo-2) + " + " + (pascal7[3]
        * Math.pow(y, expo-4)) + a + "^" + (expo-3) + " + " + (pascal7[4] * Math.pow(y, expo-3)) + a + "^" + (expo-4) + " + " + (pascal7[5] * Math.pow(y, expo-2))
        + a + "^" + (expo-5) + (pascal7[6] * Math.pow(y, expo-1)) + a + " + " + (Math.pow(y, expo));
        return x;
     }
     return x;
  }
  }

A: assuming a is your string that you want to remove the numbers from try this
a = a.replaceAll("[0-9]*$", "");

that will take out all numbers.

A: I would recommend using String's match() function to see if the value in a is a valid answer (I don't know what is valid for you). and then if it's not valid you can use a JDialog to show an error message rather than computing the binomial.
It would looks something like this:
  public void actionPerformed(ActionEvent event)
  {
      a = firstVar.getText();
      y = Integer.parseInt(txtSecond.getText());
      expo = Integer.parseInt(exp.getText());

      if(a.matches(/*Some REGEX*/)) {
          outputExpanded.setText(expand());
      }
      else {
          //Use the JDialog
      }
  }

Here are the pages:
String
JDialog

A: The answers above are enough for your question. Let me be a little nosy and point out that your code could be a lot improved (and shortened) by using loops instead of hard coded instructions.
I quickly prepared the following code:
public static float coefficient(int n, int k) {
        int sup = 1;
        int inf = 1;
        for (int i = (n-k)+1; i <= n; i++) {
            sup *= i;
        }
        for (int i = 2; i <= k; i++) {
            inf *= i;
        }
        return (sup / inf);
    }
public static String Binomials(int limit, int y, String variable) {
    StringBuilder result = new StringBuilder("");
    for (int i = 0; i <= limit; i++) {
        if (i>0) {
            result.append("+"+variable );
            if (i>1) {
                result.append("^" + i );
            }
            result.append("*");
        }
        result.append(  Math.pow(y, limit-i) * coefficient(limit, i));
    }
    return (result.toString());
}

It is not thoroughly tested and not improved for efficiency, but it seems to work just fine. Hence, I believe it may serve as a foundation for you to create a generic version of your method.