text:
Q: Python - Pulling data from a file that matches a parameter I have a file that contains information about users and the amount of times they have logged in. I am trying to pull all users that have a login of >= 250 and save it to another file. I am new at python coding and continue to get a "invalid literal with base 10" error when trying to run this portion of my code. Can anyone help me out and explain why this happens so I can prevent from this from happening in the future? TIA
thanks
def main():
  userInformation = readfile("info")
  suspicious = []
  for i in userInformation :
    if(int(i[2])>=250):
       suspicious.append(i)

Full code below if needed:
#Reading the file function
def readFile(filename):
    file = open(filename,'r')
    lines =  [x.split('\n')[0].split(';') for x in file.readlines()]
    file.close()
    return lines

def writeFile(suspicious):

    file = open('suspicious.txt','w')
    for i in suspicious:

        file.write('{};{};{};{}\n'.format(i[0],i[1],i[2],i[3]))

    file.close()

def main()
   userInformation = readfile("info")
   suspicious = []
   for i in userInformation :
     if(int(i[2])>=250):
       suspicious.append(i)
   writeFile(suspicious)

   print('Suspicious users:')
   for i in suspicious:
      print('{} {}'.format(i[0],i[1]))
main()

Here is some line of my file:
Jodey;Lamins;278
Chris;Taylors;113
David;Mann;442
etc
etc

A: "invalid literal with base 10" occurs when you're trying to parse an integer that's not in base 10. In other words i[2] is not a valid integer (most likely it's a string that you're incorrectly trying to convert to an integer). Also, it would be best to correctly format your main function.

A: Ok, so I took your example file and played with it a little. The issues I faced were mostly spacing issues. So, here's the code you might like -
UsersInfoFileName = '/path/to/usersinfofile.txt'
MaxRetries = 250
usersWithExcessRetries = []

with open(UsersInfoFileName, 'r') as f:
  lines = f.readlines()
  consecutiveLines = (line.strip() for line in lines if line.strip())
  for line in consecutiveLines:
    if (int(line.split(';')[-1]) > MaxRetries):
      usersWithExcessRetries.append(line)

for suspUsers in usersWithExcessRetries:
  print(suspUsers)

Here's what it does -

*

*Reads all lines in the given file

*Filters all lines by excluding lines which may be empty

*Removes surrounding white spaces for the remaining lines

*Reads last semi-colon separated value, and compares it with MaxRetries

*Adds the original line to a list if the value exceeds MaxRetries


text:
Q: Can't instantiate abstract class 'base.CreditCard' I'm facing an awkward problem here, I'm trying to have hierarchy parcelable classes but I'm getting this bizarre error:
java.lang.InstantiationException: Can't instantiate abstract class br.com.dinda.models.credit_cards.base.CreditCard
    at java.lang.reflect.Constructor.newInstance()(Constructor.java:-2)
    at com.google.gson.internal.ConstructorConstructor$3.construct()(ConstructorConstructor.java:104)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read()(ReflectiveTypeAdapterFactory.java:186)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read()(ReflectiveTypeAdapterFactory.java:103)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read()(ReflectiveTypeAdapterFactory.java:196)
    at com.google.gson.Gson.fromJson()(Gson.java:810)
    at com.google.gson.Gson.fromJson()(Gson.java:775)
    at com.google.gson.Gson.fromJson()(Gson.java:724)
    at com.google.gson.Gson.fromJson()(Gson.java:696)
    at com.newrelic.agent.android.instrumentation.GsonInstrumentation.fromJson()(GsonInstrumentation.java:90)
    at br.com.dinda.models.CheckoutData.fromJson()(CheckoutData.java:38)
    at br.com.dinda.repositories.CheckoutRepository.getPersistedCheckout()(CheckoutRepository.java:46)
    at br.com.dinda.repositories.CheckoutRepository.getCheckout()(CheckoutRepository.java:28)
    at br.com.dinda.presenters.CheckoutStep2Presenter.onCreate()(CheckoutStep2Presenter.java:43)
    at br.com.dinda.views.fragments.CheckoutStep2Fragment.onCreateView()(CheckoutStep2Fragment.java:183)
    at android.support.v4.app.Fragment.performCreateView()(Fragment.java:1789)
    at android.support.v4.app.FragmentManagerImpl.moveToState()(FragmentManager.java:955)
    at android.support.v4.app.FragmentManagerImpl.moveToState()(FragmentManager.java:1138)
    at android.support.v4.app.FragmentManagerImpl.moveToState()(FragmentManager.java:1120)
    at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated()(FragmentManager.java:1929)
    at android.support.v4.app.FragmentActivity.onStart()(FragmentActivity.java:547)
    at android.support.v7.app.AppCompatActivity.onStart()(AppCompatActivity.java:-1)
    at br.com.dinda.views.activities.BaseActivity.onStart()(BaseActivity.java:49)
    at android.app.Instrumentation.callActivityOnStart()(Instrumentation.java:1238)
    at android.app.Activity.performStart()(Activity.java:6288)
    at android.app.ActivityThread.performLaunchActivity()(ActivityThread.java:2397)
    at android.app.ActivityThread.handleLaunchActivity()(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900()(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage()(ActivityThread.java:1356)
    at android.os.Handler.dispatchMessage()(Handler.java:102)
    at android.os.Looper.loop()(Looper.java:148)
    at android.app.ActivityThread.main()(ActivityThread.java:5530)
    at java.lang.reflect.Method.invoke()(Method.java:-2)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run()(ZygoteInit.java:733)
    at com.android.internal.os.ZygoteInit.main()(ZygoteInit.java:623)

My code is:
@Parcel(converter = CreditCard.CreditCardConverter.class)
public abstract class CreditCard {

    public static final String CREDIT_CARD_MASK = "**** **** **** ####";
    public static ImmutableList<CreditCard> CREDIT_CARD_OPERATORS;

    static {
        CREDIT_CARD_OPERATORS = ImmutableList.of(
                new EloCreditCard(),
                new VisaCreditCard(),
                new MastercardCreditCard(),
                new HipercardCreditCard()
        );
    }

    @SerializedName("credit_card_id")
    Integer id;

    @SerializedName("credit_card_name")
    String name;

    @SerializedName("credit_card_number")
    String number;

    @SerializedName("credit_card_month")
    Integer month;

    @SerializedName("credit_card_year")
    Integer year;

    @SerializedName("credit_card_operator")
    String operator;

    String securityCode;

    boolean saveCreditCard;

    /**
     * Funcao para retornar o nome da operadora do cartao
     * eg. visa ou mastercard
     * @return nome da operadora
     */
    @NonNull
    public abstract String getCreditCardOperatorName();

    /**
     * Funcao que retorna o regex para verificar a validade da operadora do cartao (nums sao validos para a bandeira especificada)
     * eg. visa = Pattern.compile("^4[0-9]{15}$"),
     * @return @Pattern para a operadora especificada
     */
    public abstract Pattern creditCardRegex();

    /**
     * Funcao que retorna o Regex parcial para identificar a operadora do cartao
     * * eg. visa = Pattern.compile("^4[0-9]*$")
     * @return @Pattern para a verificacao parcial da operadora do cartao
     */
    public abstract Pattern partialCreditCardRegex();

    /**
     * Funcao que retorna o logo da bandeira da operadaora do cartao quando o msm esta selecionado
     * @return Drawable do logo
     */
    @DrawableRes
    public abstract int operatorLogoRes();

    /**
     * Funcao que retorna o logo da bandeira da operadaora do cartao quando o msm <b>nao</b> esta selecionado
     * @return Drawable do logo desmarcado (cinza)
     */
    @DrawableRes
    public abstract int operatorLogoDisabledRes();

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof CreditCard)) return false;

        CreditCard card = (CreditCard) o;

        return getCreditCardOperatorName().equals(card.getCreditCardOperatorName());

    }

    @Override
    public int hashCode() {
        return getCreditCardOperatorName().hashCode();
    }

    public static class CreditCardConverter implements ParcelConverter<CreditCard> {

        @Override
        public void toParcel(CreditCard input, android.os.Parcel parcel) {
            parcel.writeParcelable(Parcels.wrap(input), 0);
        }

        @Override
        public CreditCard fromParcel(android.os.Parcel parcel) {
            return Parcels.unwrap(parcel.readParcelable(CreditCard.class.getClassLoader()));
        }
    }
}

And a child class:
@Parcel
public class HipercardCreditCard extends CreditCard {

    @Override
    public String getCreditCardOperatorName() {
        return "hipercard";
    }

    @Override
    public Pattern creditCardRegex() {
        return Pattern.compile("^606282[0-9]{10}$");
    }

    @Override
    public Pattern partialCreditCardRegex() {
        return Pattern.compile("^(?:6|60|606|6062|60628|606282[0-9]{0,10})$");
    }

    @Override
    public int operatorLogoRes() {
        return R.drawable.ic_credit_card_hipercard_on;
    }

    @Override
    public int operatorLogoDisabledRes() {
        return R.drawable.ic_credit_card_hipercard_off;
    }
}

I took care of annotating them as @Parcel, but I can't seem to find out what's going on.
This issue has happened on version 1.1.5 of Parceler.
Thanks.

A: Actually I forgot to add in my serializer the CustomTypeAdapter,
if (json != null) {
            Gson gson = new Gson();
            return gson.fromJson(json, CheckoutData.class);

Should be:
if (json != null) {
            Gson gson = new GsonBuilder().registerTypeAdapter(CreditCard.class, new CreditCardTypeAdapter()).create();
            return gson.fromJson(json, CheckoutData.class);

Sorry to bother and hope it helps someone else !

A: I believe you're running into this problem:

Polymorphism
Note that Parceler does not unwrap inheritance hierarchies, so any
  polymorphic fields will be unwrapped as instances of the base class.
  This is because Parceler opts for performance rather than checking
  .getClass() for every piece of data.

 @Parcel public class Example {
     public Parent p;
     @ParcelConstructor Example(Parent p) { this.p = p; } }

 @Parcel public class Parent {} @Parcel public class Child extends
 Parent {} Example example = new Example(new Child());
 System.out.println("%b", example.p instanceof Child); // true example
 = Parcels.unwrap(Parcels.wrap(example)); System.out.println("%b", example.p instanceof Child); // false

Refer to the Custom
  Serialization section for an example of working with polymorphic
  fields.

So you should be able to use custom serialization to get around this.
https://github.com/johncarl81/parceler#custom-serialization

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android Extend BaseExpandableListAdapter I am trying to extend the BaseExpandableListAdapter, however when once I view the list and I select one of the elements to expand, the order of the list gets reversed.  For example, if I have a list with 4 elements and select the 1st element, the order (from top to bottom) is now 4, 3, 2, 1 with the 4th element (now at the top) expanded.  If I unexpand the 4th element the order reverts to 1, 2, 3, 4 with no expanded elements.
Here is my implementation:
public class SensorExpandableAdapter extends BaseExpandableListAdapter {
    private static final int FILTER_POSITION = 0;
    private static final int FUNCTION_POSITION = 1;
    private static final int NUMBER_OF_CHILDREN = 2;
    ArrayList<SensorType> mParentGroups;
    private Context mContext;
    private LayoutInflater mInflater;

    public SensorExpandableAdapter(ArrayList<SensorType> parentGroup, Context context) {
        mParentGroups = parentGroup;
        mContext = context;
        mInflater = LayoutInflater.from(mContext);
    }
    @Override
    public Object getChild(int groupPosition, int childPosition) {
        // TODO Auto-generated method stub
        if(childPosition == FILTER_POSITION) return "filter";
        else return "function";
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {
        if(convertView == null)
        {
            convertView = (RelativeLayout)mInflater.inflate(R.layout.sensor_row_list_item, parent, false);
            if(childPosition == FILTER_POSITION) {
                ((CheckBox)convertView.findViewById(R.id.chkTextAddFilter)).setText("Add Filter");
            } else {
                ((CheckBox)convertView.findViewById(R.id.chkTextAddFilter)).setText("Add Function");
                ((CheckBox)convertView.findViewById(R.id.chkTextAddFilter)).setEnabled(false);
            }
        }
        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        // TODO Auto-generated method stub
        return NUMBER_OF_CHILDREN;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return mParentGroups.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        // TODO Auto-generated method stub
        return mParentGroups.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        // TODO Auto-generated method stub
        return groupPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
        if(convertView == null)
        {
            convertView = mInflater.inflate(android.R.layout.simple_expandable_list_item_1, parent, false);
            TextView tv = ((TextView)convertView.findViewById(android.R.id.text1));
            tv.setText(mParentGroups.get(groupPosition).toString());
        }
        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        // TODO Auto-generated method stub
        return true;
    }
}

`
I just need to take a simple ArrayList of my own SensorType class.  The children are the same for all classes, just two.
Also, how do I go about making the parent in each group LongClickable?  I have tried in my ExpandableListActivity with this getExpandableListView().setOnLongClickableListener() ... and on the parent TextView set its OnLongClickableListener but neither works.
Any help on either of these is greatly appreciated!

A: public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
        if(convertView == null)
        {

Just comment out "if". This should help.

A: this is my first stackoverflow.com -answer.
I was struggling with this problem today, and I tried the solutions provided in the previous posts.
Commenting out the "if"-clause does fix the problem, but I believe this is not a recommended solution. As described in this ListView video (http://www.youtube.com/watch?v=wDBM6wVEO70), the re-use of convertView is essential when dealing with large datasets.
My solution is very simple and it worked perfectly in my case. I got the idea from the previously mentioned video:
   public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent)     {

        // 1. Step: check if convertView can be re-used or if it should be created.

        if (convertView == null) {

                // create the view or inflate the view from xml here
                // Note: inlating is expensive process, so do it only if needed
                //       (it's needed when convertView can not be re-used)
                //
                // TODO: your code here

        }

        // 2. Step: populate the convertView with correct data.
        // Correct data can be accessed through groupPosition.
        //
        // TODO: your code here

        return convertView;
    }

I believe that this second step was missing from the code provided in the question?
I hope this helps someone with this same problem.

*

*Tuomas

A: Update: This answer comes way too late; but for anyone having the same problem, here is my solution.
I just had the same issue and managed to work it out after reading the chome2phone source code.
The key is indeed in this method:
public View getChildView(int groupPosition, int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {
        if(convertView == null)
        {
            convertView = (RelativeLayout)mInflater.inflate(R.layout.sensor_row_list_item, parent, false);
            if(childPosition == FILTER_POSITION) {
                ((CheckBox)convertView.findViewById(R.id.chkTextAddFilter)).setText("Add Filter");
            } else {
                ((CheckBox)convertView.findViewById(R.id.chkTextAddFilter)).setText("Add Function");
                ((CheckBox)convertView.findViewById(R.id.chkTextAddFilter)).setEnabled(false);
            }
        }
        return convertView;
    }

AS @Dan said, convertView is a cached item and as the documentation says:

convertView: the old view to reuse, if possible.
  You should check that this view is
  non-null and of an appropriate type
  before using. If it is not possible to
  convert this view to display the
  correct data, this method can create a
  new view. It is not guaranteed that
  the convertView will have been
  previously created by
  getChildView(int, int, boolean, View,
  ViewGroup).

In my case, the object passed to getChildView() came probably from a cache in the exact reverse order than created; a Stack probably (LIFO).
There are mainly two solutions; either you will remove

if(convertView == null)

thus recreating the child on every expand/collapse action or on every orientation change, or (way better performance wise) do something this:
public View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent) {
    RelativeLayout mItemView;
    if (null == convertView || !(convertView instanceof RelativeLayout)) {
        mItemView = (RelativeLayout)mInflater.inflate(R.layout.sensor_row_list_item, parent, false);
    }else{
        mItemView = (RelativeLayout) convertView;
    }
    if(childPosition == FILTER_POSITION) {
        ((CheckBox)convertView.findViewById(R.id.chkTextAddFilter)).setText("Add Filter");
    } else {
        ((CheckBox)convertView.findViewById(R.id.chkTextAddFilter)).setText("Add Function");
        ((CheckBox)convertView.findViewById(R.id.chkTextAddFilter)).setEnabled(false);
    }
}
return convertView;

Which means that you will use the object convertView to render the item instead of creating a new one.
I hope this works for you too.

A: I hope this is the answer you are looking for
public class Sample extends ExpandableListActivity {

    ExpandableListAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
          mAdapter = new MyExpandableListAdapter();
          setListAdapter(mAdapter);
          registerForContextMenu(getExpandableListView());
    }

   @Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    // TODO Auto-generated method stub
    super.onCreateContextMenu(menu, v, menuInfo);

      menu.setHeaderTitle("Sample menu");
      menu.add(0, 0, 0, R.string.expandable_list_sample_action);

}

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // TODO Auto-generated method stub

         ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();

         String title = ((TextView) info.targetView).getText().toString();

         int type = ExpandableListView.getPackedPositionType(info.packedPosition);

         if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
             int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
             int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
             Toast.makeText(Sample.this, title + ": Child " + childPos + " clicked in group " + groupPos,
                     Toast.LENGTH_SHORT).show();
             return true;
         } else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
             int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
             Toast.makeText(this, title + ": Group " + groupPos + " clicked", Toast.LENGTH_SHORT).show();
             return true;
         }

         return false;

    }
    /**
     * A simple adapter which maintains an ArrayList of photo resource Ids.
     * Each photo is displayed as an image. This adapter supports clearing the
     * list of photos and adding a new photo.
     *
     */
    public class MyExpandableListAdapter extends BaseExpandableListAdapter {
        // Sample data set.  children[i] contains the children (String[]) for groups[i].
        private String[] groups = { "People Names", "Dog Names", "Cat Names", "Fish Names" };
        private String[][] children = {
                { "Arnold", "Barry", "Chuck", "David" },
                { "Ace", "Bandit", "Cha-Cha", "Deuce" },
                { "Fluffy", "Snuggles" },
                { "Goldy", "Bubbles" }
        };

        public Object getChild(int groupPosition, int childPosition) {
            return children[groupPosition][childPosition];
        }

        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        public int getChildrenCount(int groupPosition) {
            return children[groupPosition].length;
        }

        public TextView getGenericView() {
            // Layout parameters for the ExpandableListView
            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                    ViewGroup.LayoutParams.FILL_PARENT, 64);

            TextView textView = new TextView(Sample.this);
            textView.setLayoutParams(lp);
            // Center the text vertically
            textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
            // Set the text starting position
            textView.setPadding(36, 0, 0, 0);
            return textView;
        }

        public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                View convertView, ViewGroup parent) {
            TextView textView = getGenericView();
            textView.setText(getChild(groupPosition, childPosition).toString());
            return textView;
        }

        public Object getGroup(int groupPosition) {
            return groups[groupPosition];
        }

        public int getGroupCount() {
            return groups.length;
        }

        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
                ViewGroup parent) {
            TextView textView = getGenericView();
            textView.setText(getGroup(groupPosition).toString());
            return textView;
        }

        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public boolean hasStableIds() {
            return true;
        }

    }}


text:
Q: Export formatting of an Excel worksheet to Powershell (or VBA) commands There are several threads here on SO which are concerned with filling and formatting an Excel sheet out of Powershell. The concepts for this are easy, but creating a report in this way can quickly become cumbersome -- particularly when a nice format is desired.
Therefore, I want to get rid of the whole formatting and instead base the report on an existing template, for example looking like

The fields A2, B2 and C2 then shall be filled through a Powershell script.
The straightforward way to accomplish this would be to create the Excel template once and save it somewhere as a file. Then let the script open the template, fill it with data, and save it somewhere else. Although this works, it is not nice as the powershell script is not self-contained: one always needs to handle two files, the script as well as the template.
Therefore, I'm seeking for a way to bundle together the script and the Excel template. My first idea for this is to export the Excel template as a series of formatting commands. (This is similar to the result of a macro, where one obtains VBA code, but a macro is not maintainable: if I want to add one column, I'd need to repeat the whole macro.)
Ideally, with this I would like to have the example sheet exported into Powershell like
$sheet.cells.item(1,1) = 'Name'
$sheet.cells.item(1,1).font.Name = 'Calibri'
$sheet.cells.item(1,1).font.bold = $True
... and so on ...

(As said, Powershell would be optimal, but I could also arrange with VBA, why I tagged it as well.)
Is it possible to create such an export?


text:
Q: How to determine the right syntax for an undocumented API call using Postman, but with a Python example I'd like to use Postman to play around with my own Peloton rider data, exploring their API.
I found a great GitHub example with documented endpoints: https://github.com/geudrik/peloton-api/blob/master/API_DOCS.md
https://api.onepeloton.com/auth/login

or
https://api.onepeloton.com/api/user/<user id>

I'm not a developer - but I've toyed around with self build projects using a Particle and some basic API calls - and have always used Postman as a playground.
The Github example has an authentication approach:
import requests

s = requests.Session()
payload = {'username_or_email':'Your username or email', 'password':'your password'}
s.post('https://api.onepeloton.com/auth/login', json=payload)

But when trying in Postman:
POST: https://api.onepeloton.com/auth/login?username_or_email=my_user&password=my_pass
All I get is 'login failed'
Where if I try:
GET: https://api.onepeloton.com/api/instructor
It works (this is one of a few calls that doesn't require authentication)
This is an undocumented API, so it is trial and error - but I'm guessing someone that is actually a developer may look at what I've done and see the obvious....
I've tried the POST with username / pass as Params as well as using basic Authorization type in Postman.
Thanks!

A: The Python code snippet POSTs the body as JSON but your Postman snippet is supplying the username and password values via query string parameters.
Change your Postman POST operation to a JSON payload and try again.
For anyone playing in Postman - image of it working there


text:
Q: Can I pass a Binding variable as a parameter in a function? (do I need to in this case?) I'm new to Swift / Firebase and need some help with my code.
I have a simple create new account page, and I am using Firebase.
I want to create a user when a button is tapped - change button colour/text to reflect this - then return to HomeView
Now, I want to include all the Auth.auth() in a separate function on a separate swift file - to keep my View code clean.
Currently, I'm setting the isShowingNewAccountView = false to return back to HomeView (via a NavigationLink on HomeView) - isShowingAccountView is a Binding variable from HomeView.
If I put all the Auth.auth() code into a separate function, is it possible to change the value of the isShowingAccountView to 'false' when a user is created from within the function? Is there a more elegant alternative
Button(action: {
    Auth.auth().createUser(withEmail: newUser.userEmail, password: newUser.userPassword) { authDataResult, error in
        if error != nil {
            print("Error detected")
            print(error!.localizedDescription)

            isShowingNewAccountView = true         //Binding variable from HomeView - Keep showing NewAccountView
            newUser.successNewAccountCreated = false
            return
        }
        else
        {
            print("Account Successfully Created")
            isShowingNewAccountView = false        //Binding variable from HomeView - Revert back to HomeView
            newUser.successNewAccountCreated = true
            return
        }
    }
}, label: {
    CustomButton(buttonText: (!newUser.successNewAccountCreated ? "Create New Account" : "New Account Created"), colourVar: newUser.successNewAccountCreated ? .green : (isInputAppropriate() ? .accentColor : .gray)
})

On HomeView I have:
NavigationLink(destination: NewAccountView(isShowingNewAccountView: $isShowingNewAccountView), isActive: $isShowingNewAccountView) {
    //passing isShowingAccountView as a binding $
    EmptyView()
}

Thanks in advance.

A: Maybe this approach may help you:
Three views (just as an example):

*

*ContentView: It shows either Page1 or Page2, depending on the var isShowingNewAccountView.

*Page1: It is the page you use to create a new user, it will be shown when isShowingNewAccountView is false. It calls the function signUp from the AuthenticationViewModel.

*Page2: It is the page that will be opened when a new User has been created and isShowingNewAccountView is true
One ViewModel (also just as an example)
The authentication is handled in the AuthenticationViewModel. It is handling the functions to signUp, signIn and signOut. It also holds isShowingNewAccountView.
Views
import SwiftUI
import FirebaseFirestore
import Firebase
import FirebaseFirestoreSwift

struct Page1: View {

    @EnvironmentObject var authenticationViewModel: AuthenticationViewModel
    @State private var buttonPressed = false
    @State private var email: String = "sebastian@hello.me"
    @State private var password: String = "password"

    var body: some View {
        VStack(){

            Text("Register")
                .font(Font.system(size: 24, weight: .bold))
                .padding()
                .padding(.vertical, 50)

            TextField("E-Mail", text: $email)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()

            SecureField("Password", text: $password)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()

            Button(action: {
                buttonPressed.toggle()
                authenticationViewModel.signUp(email: email, password: password){ success, uid in
                    if success {
                        print("UID: \(uid)")
                    } else {
                        print("Uh-oh")
                    }
                    buttonPressed = false
                }
            }) {
                Text(buttonPressed ? "In Progress" : "Sign Up - Create User")
                    .foregroundColor(buttonPressed ? Color.pink : Color.cyan)
            }
        }
    }
}

struct Page2: View {

    @EnvironmentObject var authenticationViewModel: AuthenticationViewModel
    var body: some View {

        Button(action: {
            authenticationViewModel.isShowingNewAccountView.toggle()
        }) {
            Text("Back to other page")
        }
    }
}

struct ContentView: View {
    @EnvironmentObject var authenticationViewModel: AuthenticationViewModel
    var body: some View {
        if authenticationViewModel.isShowingNewAccountView {
            Page2()
        } else {
            Page1()
        }
    }
}

ViewModel for Authentication
import Foundation
import FirebaseFirestore
import Firebase
import FirebaseFirestoreSwift

class AuthenticationViewModel: ObservableObject {

    let db = Firestore.firestore()

    @Published var isShowingNewAccountView: Bool = false

    // Sign Up
    func signUp(email: String, password: String, completion: @escaping (Bool, String)->Void) {

        Auth.auth().createUser(withEmail: email, password: password) { authResult, error in

            // ERROR AND SUCCESS HANDLING
            if error != nil {
                // ERROR HANDLING
                print(error?.localizedDescription as Any)
                completion(false, "ERROR")
            } else {
                // SUCCESS HANDLING
                self.isShowingNewAccountView = true
                completion(true, authResult?.user.uid ?? "")
            }
        }
    }

    // Sign In
    func signIn(email: String, password: String, completion: @escaping (Bool, String)->Void) {

        Auth.auth().signIn(withEmail: email, password: password) { (authResult, error) in

            // ERROR AND SUCCESS HANDLING
            if error != nil {
                // ERROR HANDLING
                print(error?.localizedDescription as Any)
                completion(false, "ERROR")
            }

            completion(true, authResult?.user.uid ?? "")
        }
    }

    // Sign Out
    func signOut(_ completion: @escaping (Bool) ->Void) {
        try! Auth.auth().signOut()
        completion(true)
    }

    // Create new user
    func createNewUser(name: String, id: String) {
        do {
            let newUser = User(name: name, id: id)
            try db.collection("users").document(newUser.id!).setData(from: newUser) { _ in
                print("User \(name) created")
            }
        } catch let error {
            print("Error writing user to Firestore: \(error)")
        }
    }
}

Alternative with a NavigationLink
In your approach you are using a NavigationLink. That would work as well. In that case the ContentView as well as the Page1 view are slightly different (Page2 stays as it is):
ContentView Update
In the ContentView it is not necessary do make the decision which view will be shown.
struct ContentView: View {
    @EnvironmentObject var authenticationViewModel: AuthenticationViewModel
    var body: some View {
       Page1()
    }
}

Page1 Update
On Page1 we now need the NavigationView and the NavigationLink. As soon as isShowingNewAccountView becomes true, it opens Page2, but for me, the NavigationLink is something you can press, like a button. But anyway:
struct Page1: View {

    @EnvironmentObject var authenticationViewModel: AuthenticationViewModel
    @State private var buttonPressed = false
    @State private var email: String = "sebastian@hello.me"
    @State private var password: String = "password"

    var body: some View {
        NavigationView(){
            VStack(){

                Text("Register")
                    .font(Font.system(size: 24, weight: .bold))
                    .padding()
                    .padding(.vertical, 50)

                TextField("E-Mail", text: $email)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding()

                SecureField("Password", text: $password)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding()

                Button(action: {
                    buttonPressed.toggle()
                    authenticationViewModel.signUp(email: email, password: password){ success, uid in
                        if success {
                            print("UID: \(uid)")
                        } else {
                            print("Uh-oh")
                        }
                        buttonPressed = false
                    }
                }) {
                    Text(buttonPressed ? "In Progress" : "Sign Up - Create User")
                        .foregroundColor(buttonPressed ? Color.pink : Color.cyan)
                }

                NavigationLink(destination: Page2(), isActive: $authenticationViewModel.isShowingNewAccountView){
                                EmptyView()}
            }
        }
    }
}

Please see the gif:


text:
Q: Ignore properties set undefined on GET request in Angular with Typescript I'm trying to request some data from the server. When I change a property's model to undefined this "undefined" string is sent in the query string.
let filterModel = new GroupFilterModel();
filterModel.status = anycondition ? "opened" : undefined;
this.http.get<GroupModel[]>("apiurl", { params: filterModel });

The querystring sent is something like this:
apiurl?status=undefined

I want to avoid sending the status variable. How can I have this behaviour?

A: Use this one liner in ES6:
Object.keys(obj).forEach(key => obj[key] === undefined ? delete obj[key] : '');

As if:
filterModel.status = anycondition ? "opened" : undefined;
const model = Object.keys(filterModel).forEach(key => obj[key] === undefined ? delete obj[key] : '');
this.http.get<GroupModel[]>("apiurl", { params: model });

You can go even further and make it an extension on the object:
Object.prototype.StripUndefined = function StripUndefined() {
  return this.keys(filterModel).forEach(key => obj[key] === undefined ? delete obj[key] : '');
};

A: You can remove properties that have undefined and null values with lodash as follows:
let filterModel = new GroupFilterModel();
filterModel.status = anycondition ? "opened" : undefined;
this.http.get<GroupModel[]>("apiurl", { params: _.pickBy(filterModel) });

For other solutions using vanilla JS see:
Remove blank attributes from an Object in Javascript


text:
Q: assign Json value to a variable using $.each() I am trying to pass the result of this query as a Json string to Jquery so that I can assign the value to a JQuery variable. Actually there will be more than one key:value pair but I am illustrating my problem with a single pair for simplicity. I am able to console.log the index and value however when I try to assign the value to a variable I get an "undefined" message. I have done this successfully elsewhere and am not sure what i am missing here:
$query = (
"SELECT MedCondPrimary, Count(MedCondPrimary) as Count
FROM Comments
WHERE MedCondPrimary='Arthritis'");

$result = mysqli_query($dbc, $query);

WHILE($rows = mysqli_fetch_array($result)) {

$medcond = $rows['MedCondPrimary'];
$array3[$medcond] = $rows['Count'];
};

$json_count=json_encode($array3);
    echo $json_count; // {"Arthritis":"26"}

JQ:
    var tally = ;
    console.log(tally);// Object { Arthritis="26"} should be a string?
$.each(tally, function(index, value) {
  console.log(index+":"+value);     //Arthritis:26
  var arthritis = value.Arthritis;
  console.log(arthritis);          //undefined
    });

A: Your jQuery code should be using each() instead of $.each() here.
$( tally ).each(function( index, obj ) {
  console.log( index + ":" + obj.Arthritis); // Arthritis:26
  var arthritis = obj.Arthritis;
  console.log( arthritis ); // 26
});

each() passes the object while $.each() passes property-value pairs for an object. You're $.each() at the other place must be working because you passed it an array as shown below:
// iterating an array
$.each( [{Arthritis:26}], function( index, obj) {
    console.log( obj.Arthritis ); // 26
});

PHP Edit :
$json_count=json_encode($array3);
echo "[" . $json_count . "]";


text:
Q: SQL insert dot or comma into varchar (accounting, money) I'm currently sitting on a MySQL-table that has column called unitprice (VARCHAR) formatted as follows;
Example
5102938
304948
495845
The data represents money; the last two numbers are always cents.
Result
51029.38
3049.48
4958.45
My goal is to insert a dot on the third-final position so I can use CAST/CONVERT to convert the column from VARCHAR to DECIMAL. Does MySQL have regex support which may allow me to do this? Or any build-in features?

A: Just convert to unsigned and divide by 100:
select cast(unitprice as unsigned) / 100.0

If the values are really big, you might need something bigger than unsigned, but it is a reasonable choice for most currencies and prices.
Of course, if you want it as a decimal, then use that:
select cast(unitprice as decimal(10, 2)) / 100.0

Be sure to put in the precision and scale that are appropriate for your problem.


text:
Q: Why can I no longer access my WordPress admin page? I wanted to migrate my website from one domain to another, so I used WordPress move plugin. While using WordPress move plugin I used change domain option, made the required changes, but after that, I am not able to access my website from old domain or new domain even I cant access admin dashboard.
How can I get at admin panel so I can revert the changes?

A: You have to access your db in order to see the domain name in the wp_options table, the plugin you used might changed that.
You can see your site domain in wp_options under 'siteurl', it tops the table rows.
In order to access your db you need to connect to your hosting panel (cpanel, plesk etc) and open phpMyAdmin.
Then you can achive a full domain change in db ( domain might be found in more tables than just wp_options ) you need to use a
https://interconnectit.com/products/search-and-replace-for-wordpress-databases/
Just upload it to your new hosting and access it via browser.
For example if you upload a folder containing the above script name search_and_replace, you can access it hitting domain.com/search_and_replace
Then just place your old domain in the left input and the new domain in the right one and hit live run.
Just be cautious and be aware that this script is performing db changes so if anything goes wrong you need to have a db backup.
When the script completes execution you need to access your sites wp-admin and resave the permalinks in order for wordpress to create the new .htaccess


text:
Q: Change iframe values in textarea My code:

Choose a color
<input type="color" name="color" id="color">

Change width
<input type="text" name="width" id="width">

<textarea id="iframe_url" name="iframe_url" rows="3">

</textarea>

I use jQuery to access textarea value.

I need to change color hex in iframe src url
I need to change iframe width / height from input

A: You can use replace with regexp to update the string from the textarea.

$('#color').on('change', function() {
  var updatedContent = $('#iframe_url').val().replace(/color=\#{1}\d*\w*/, `color=${$(this).val()}`);

  $('#iframe_url').val(updatedContent);
});

$('#width').on('change', function() {
  var updatedContent = $('#iframe_url').val().replace(/width="\d+"/, `width="${$(this).val()}"`);

  $('#iframe_url').val(updatedContent);
});

  Choose a color
  <input type="color" name="color" id="color">

  Change width
  <input type="number" type="number" min="0" step="1" name="width" id="width">

<textarea id="iframe_url" name="iframe_url" rows="3" readonly>

</textarea>


text:
Q: How to tell rsync not to touch the destination directory permissions? I am using rsync to sync a directory from a machine to another but I encountered the following problem: the destination directory permissions are altered.
rsync -ahv defaults/ root@hostname:~/

The problem is that in this case the permissions and ownership of the defaults forlder will be assigned to the destination folder.
I do want to keep the permissions for the files and subdirectories but not for the source directory itself.
Also, I do not want to remove any existing files from the destination (but to update them if needed), but I think that current settings are already ok regarding this.
How can I do this?

A: If you want to exclude the defaults directory from having its permissions altered, you would have to literally not include it in the command (since you obviously want to maintain the permissions of everything you are copying). You can thus either do this:
rsync -ahv defaults/* root@hostname:~/

Or, in case you have files or directories starting with a dot inside defaults, and assuming you are using bash:
shopt -s dotglob
rsync -ahv defaults/* root@hostname:~/


text:
Q: Why are different currents used for charging batteries with the same voltage output? I'm trying to understand the behavior of batteries a bit more. I've noticed that chargers for given batteries have different current capabilities.  Do batteries need to be charged with a voltage that is near their nominal output?  E.g., a 12V battery should be charged with 12V?  If one charger for a battery has a 1A output and the other has a 2A output, is the higher current charger actually just supplying a higher voltage?
The batteries don't have some kind of semi-conductor-like physics going on which allows them to maintain a constant voltage drop with different current levels, do they?

A: Batteries are usually charged with a bit more voltage than their "full" voltage, but the details vary widely.  Often batteries that are deeply discharged need to be brought up slowly until they are reasonably full.  Most batteries can be charged with simple logic that applies some fixed voltage or some fixed current, whichever is lower, if you're willing to give up some charging time.  Even that doesn't apply universally though, like with NiMH.  If you want the fastest possible charging time, you have to carefully do what the datasheet says to do.
A 2 A charger isn't going to produce a higher voltage than a 1 A charger, but it has more current capability.  That means it is intended to charge a larger battery, all else being equal.
For the best answer, read the datasheet for the particular battery you want to charge and don't assume it applies to any other battery.

A: A battery charger must produce a voltage a little higher than the battery voltage - how much higher depends on the battery chemistry, temperature, and other things.
1 Amp and 2 Amp chargers for a given battery type will produce the same final voltage, but the 2 Amp charger can deliver a higher currrent into a discharged battery.  With both chargers, the actual charging current will decrease as the battery approaches full charge.


text:
Q: Temperature converter in python I went through a couple of converters in python but they entered the int value seperately. If the input is 100C i want the output in F and if its 50F i want it in C. I'm new to python and tried some simple lines but the error says its impossible to concatenate str and int.
a = raw_input(" enter here")
char = "f"
char2 = "c"
for s in a:
    if s in char:
        b=(5*(a-32))/9
        print(b,"c")
        continue
    elif s in char2:
        d = (9*a/5)+32
        print(d,"f")
        continue

A: Since the user will enter a number followed by the unit, you need to only check if the last character of the string to understand which conversion to do.
You can use slicing, here is an example:
>>> a = '45F'
>>> a[-1]
'F'
>>> a[:-1]
'45'

Of course '45' is a string not a number, converting it to a number with int() will allow you do math on it.
Putting all that together, we have something like this:
a = raw_input('Enter here: ')
number = int(a[:-1])
letter = a[-1].lower()
if letter == 'f':
    print('{} in C is {}'.format(a, 5*(number-32)/9))
if letter == 'c':
    print('{} in F is {}'.format(a, 9*(number/5)*32))


text:
Q: Seletor CSS para modificar TAG antes ou depois dentro da div Estou em dúvida ao aplicar alguns estilos no css. Desejo modificar uma tag usando uma div dentro dela:

header {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
    -webkit-flex-wrap: nowrap;
    -ms-flex-wrap: nowrap;
    flex-wrap: nowrap;
    -webkit-box-pack: start;
    -webkit-justify-content: flex-start;
    -ms-flex-pack: start;
    justify-content: flex-start;
    box-sizing: border-box;
    -webkit-flex-shrink: 0;
    -ms-flex-negative: 0;
    flex-shrink: 0;
    width: 100%;
    margin: 0;
    padding: 0;
    border: none;
    min-height: 64px;
    max-height: 1000px;
    white-space: nowrap;
    -webkit-transition-duration: 0.2s;
    -moz-transition-duration: 0.2s;
    -ms-transition-duration: 0.2s;
    -o-transition-duration: 0.2s;
    transition-duration: 0.2s;
    -webkit-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
       -moz-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
        -ms-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
         -o-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
            transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
    -webkit-transition-property: max-height,box-shadow;
       -moz-transition-property: max-height,box-shadow;
        -ms-transition-property: max-height,box-shadow;
         -o-transition-property: max-height,box-shadow;
            transition-property: max-height,box-shadow;
    background-color: #00bcd4;
    color: #ffffff;
    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12);
}

header .drawer-button {
    display: block;
    position: absolute;
    height: 48px;
    width: 48px;
    border: 0;
    -webkit-flex-shrink: 0;
    -ms-flex-negative: 0;
    flex-shrink: 0;
    overflow: hidden;
    text-align: center;
    cursor: pointer;
    font-size: 26px;
    line-height: 50px;
    margin: 10px 12px;
    top: 0;
    left: 0;
    color: #ffffff;
    z-index: 4;
}

header .li-row {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    height: 64px;
    margin: 0;
    padding: 0 15px 0 80px;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -webkit-flex-direction: row;
    -ms-flex-direction: row;
    flex-direction: row;
    -webkit-flex-wrap: nowrap;
    -ms-flex-wrap: nowrap;
    flex-wrap: nowrap;
    -webkit-flex-shrink: 0;
    -ms-flex-negative: 0;
    flex-shrink: 0;
    box-sizing: border-box;
    -webkit-align-self: stretch;
    -ms-flex-item-align: stretch;
    align-self: stretch;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
}

header .li-row > * {
    -webkit-flex-shrink: 0;
    -ms-flex-negative: 0;
    flex-shrink: 0;
}

header .layout-spacer {
    -webkit-box-flex: 1;
    -webkit-flex-grow: 1;
    -ms-flex-positive: 1;
    flex-grow: 1;
}

header .action-drawer {
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-flex-wrap: nowrap;
    -ms-flex-wrap: nowrap;
    flex-wrap: nowrap;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    height: 64px;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -webkit-flex-direction: row;
    -ms-flex-direction: row;
    flex-direction: row;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
}

header .action-drawer > .drawer-button {
    position: inherit;
    margin: inherit;
}

header .layout-spacer > input[type="search"] {
    border: none;
    width: 50%;
    height: 40px;
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 3px;
    margin: 0 auto;
    top: 0;
    bottom: 0;
    color: black;
}

header .layout-spacer > input[type="search"]:focus, input[type="search"]:focus + header.color, header .layout-spacer > input[type="search"]:focus + .color {
    background-color: white;
    -webkit-transition: all 0.5s;
       -moz-transition: all 0.5s;
        -ms-transition: all 0.5s;
         -o-transition: all 0.5s;
            transition: all 0.5s;
}

Title

            <input type="search" class="text-subhead" />

oi

Desejo modificar a cor do  através do <input type="search"> sem utilizar jQuery, somente utilizando css.

A: Como o Felipe Assunção informou, não existe um método que modifique uma propriedade em um parentElement a partir do childElement ainda, isso só estará presente no CSS4... você pode fazer isso tanto com jQuery quanto com javascript puro. Aqui vai um exemplo que montei e que faz exatamente o que você precisa em javascript puro:

var inputSearch = document.querySelector('header input[type=search]');

inputSearch.addEventListener('focus', function() {
  this.parentElement.parentElement.parentElement.classList.toggle('searchfocus');
}, false);

inputSearch.addEventListener('blur', function() {
  this.parentElement.parentElement.parentElement.classList.toggle('searchfocus');
}, false);
@import url('https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css');
@import url('https://fonts.googleapis.com/css?family=Montserrat');
 * {
  margin: 0;
  padding: 0;
  outline: none;
  color: #fff;
  font-family: 'Montserrat', sans-serif;
}
header {
  width: 100%;
  height: 50px;
  background: #2b82ad;
  transition: all 0.2s ease-in-out;
}
header.searchfocus {
  background: #00405d;
}
header,
header > section {
  display: flex;
  align-items: center;
}
header button {
  height: 50px;
  min-width: 50px;
  padding: 10px;
  background: transparent;
  border: none;
  outline: none;
  cursor: pointer;
}
button:hover {
  background: rgba(0, 0, 0, 0.1);
}
button:active {
  background: rgba(0, 0, 0, 0.2);
}
button,
h1 {
  text-shadow: 1px 1px 2px #222;
  user-select: none;
}
button .fa {
  font-size: 150%;
  padding: 5px;
}
header > section {
  flex-grow: 1;
  justify-content: space-between;
}
header > section > h1 {
  padding: 10px;
}
header > section > nav > input[type=search] {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid #77B8D8;
  border-radius: 10px;
  padding: 3px 10px;
  font-size: 90%;
  width: 200px;
  margin: 0 5px;
}
input[type=search]::-webkit-input-placeholder {
  color: rgba(255, 255, 255, 0.5);
}
input[type=search]:-moz-placeholder {
  color: rgba(255, 255, 255, 0.5);
}
input[type=search]::-moz-placeholder {
  color: rgba(255, 255, 255, 0.5);
}
input[type=search]:-ms-input-placeholder {
  color: rgba(255, 255, 255, 0.5);
}
input[type=search]::-ms-input-placeholder {
  color: rgba(255, 255, 255, 0.5);
}
input[type=search]:placeholder-shown {
  color: rgba(255, 255, 255, 0.5);
}

  <button></button>

Hello World

      <input type="search" class="" placeholder="procurar" />
      <button>Sobre</button>
      <button>Contato</button>


text:
Q: Laravel routes behind reverse proxy Ok, so for development purposes, we have a dedicated web server. It's not currently connected directly to the internet, so I've setup an apache reverse proxy on another server, which forwards to the development server.
This way, I can get web access to the server.
The problem is, the routes in Laravel are now being prefixed with the internal server IP address, or the servers computer name.
For example, I go to http://subdomain.test.com but all the routes, generated using the route() helper, are displaying the following url: http://10.47.32.22 and not http://subdomain.test.com.
The reverse proxy is setup as such:
<VirtualHost *:80>
    ServerName igateway.somedomain.com

    ProxyRequests Off
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    ProxyPass / http://10.47.32.22:80/
    ProxyPassReverse / http://10.47.32.22:80/
    <Location />
        Order allow,deny
        Allow from all
    </Location>
</VirtualHost>

I have set the actual domain name in config\app.php.
Question
How can I set the default URL to use in routing? I don't want it using the internal addresses, because that defeats the point of the reverse proxy.
I've tried enclosing all my routes in a Route::group(['domain' ... group, which doesn't work either.

A: Go to app/Http/Middleware/TrustProxies.php and change the protected variable $proxies like this:
protected $proxies = ['127.0.0.1'];

Just this! Be happy!

A: Because laravel route is created not from the config/app itself rather than from the server. My solution is adding the proxy_set_header Host to the nginx's config.
server {
    listen 80;
    server_name my.domain.com;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host  my.domain.com;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://127.0.0.1:8000;
    }
}

i'm using laravel 8 with nginx docker inside a running nginx on the machine, so yeah it's double nginx

A: add this code in App\Providers\AppServiceProvider class
if (Str::contains(Config::get('app.url'), 'https://')) {
    URL::forceScheme('https');
}

A: I ran into the same (or similar problem), when a Laravel 5 application was not aware of being behind an SSL load-balancer.
I have the following design:

*

*client talks to an SSL load balancer over HTTPS

*SSL load balancer talks to a back-end server over HTTP

That, however, causes all the URLs in the HTML code to be generated with http:// schema.
The following is a quick'n'dirty workaround to make this work, including the schema (http vs. https):
Place the following code on top of app/Http/routes.php
In latest version of laravel, use web/routes.php
$proxy_url    = getenv('PROXY_URL');
$proxy_schema = getenv('PROXY_SCHEMA');

if (!empty($proxy_url)) {
   URL::forceRootUrl($proxy_url);
}

if (!empty($proxy_schema)) {
   URL::forceSchema($proxy_schema);
}

then add the following line into .env file:
PROXY_URL = http://igateway.somedomain.com

If you also need to change schema in the generated HTML code from http:// to https://, just add the following line as well:
PROXY_SCHEMA = https

In latest version of laravel forceSchema method name has changed to forceScheme and the code above should look like this:
if (!empty($proxy_schema)) {
    URL::forceScheme($proxy_schema);
}

A: Seems the Laravel have more convinient solution.. Check answer there: How do I configure SSL with Laravel 5 behind a load balancer (ssl_termination)?

A: Ok, so I got it. Hopefully this will help someone in the future.
It seems like Laravel ignores the url property in the config\app.php file for http requests (it does state it's only for artisan), and it instead uses either HTTP_HOST or SERVER_NAME provided by apache to generate the domain for URLs.
To override this default url, go to your routes.php file and use the following method:
URL::forceRootUrl('http://subdomain.newurl.com');

This will then force the URL generator to use the new url instead of the HTTP_HOST or SERVER_NAME value.

A: Following up @TimeLord's solution:
In latest version of laravel the name for forced schema has changed and now it is:
URL::forceScheme()

A: I know this topic is old a.f but I've been solving this issue by replacing the following line in my DatabaseSessionHandler.pdf [@Illuminate/Session]:
    protected function ipAddress()
    {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
//        return $this->container->make('request')->ip();
    }

Of course you need to migrate the sesssion table first and set up the config
(.env Variable SESSION_DRIVER=database)

A: For nginx, you don't need to do anything extra in Laravel. The fix can be done at from nginx config;
server {
    listen 80;
    listen [::]:80 ipv6only=on;

    server_name sub.domain.dev;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host  sub.domain.dev;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://127.0.0.1:8000;
    }
}

A: Figured out a way that much cleaner and only does exactly what the loadbalancer tells it to, add this function to your RouteServiceProvider
protected function enforceProtocol()
{
    if(request()->server->has('HTTP_X_FORWARDED_PROTO')){
        URL::forceScheme(request()->server()['HTTP_X_FORWARDED_PROTO']);
    }
}

and in the boot section, simple call it like so
public function boot()
{
    $this->enforceProtocol();
    //other stuff
}


text:
Q: Axiom of regularity implication How does axiom of regularity ensures that Russell's Paradox doesn't occurs. Given the axiom of regularity states: If A is a non-empty set, then there is at least one element x of A which is either not a set, or is disjoint from A.

A: It doesn't.
You need the other axioms of $\mathsf{ZF}$ to define how to construct sets, and thus to see that the object in Russell's paradox is a proper class.
Note that the domain of discourse is $V$, the class of all sets. Any variable that is used in a first-order formula in the language of set theory refers to elements of $V$, and thus to sets. This means that proper classes and sets can only contain sets.
If $R=\{x\mid x\notin x\}$ is a set, this would lead to a contradiction, since then both $R\in R$ and $R\notin R$ are provable. However, if we make our axioms such that $R$ is a proper class, then $R$ cannot contain itself, since $R$ is not an element in our universe.
It is the axiom (scheme) of unrestricted comprehension of naive set theory that makes it possible to define the set $\{x\mid x\notin x\}$. In $\mathsf{ZF}$ such a thing is not possible, since we're using the weaker axiom (scheme) of separation, that says you can only define subsets of sets with first-order formulas:
Unrestrictied comprehension: $\forall\bar v\,\exists y\forall x(x\in y\leftrightarrow \phi(x,\bar v))$
Separation: $\forall\bar v\forall z\exists y\forall x(x\in y\leftrightarrow (\phi(x,\bar v)\land x\in z))$

The axiom of regularity says that any non-empty set contains an element that is disjoint from it.
Regularity: $\forall x(x\neq\varnothing\to \exists y\in x( y\cap x=\varnothing)$
It makes sure that a set cannot contain itself, since if $x\in x$, then $\{x\}$ does not contain a $y$ such that $y\cap x=\varnothing$. Without it, most of mathematics is still perfectly provable, and Russell's paradox doesn't work since we use the (weak enough) axiom (scheme) of separation.
Using the axiom of regularity, we can prove that $R=V$, since $x\notin x$ is true for any set.


text:
Q: How to modify AWS Cognito JWT Tokens, we are using NodeJS technical question I am using AWS Cognito for user management. I am getting too much information in JWT Token (in payloads). I do not want to pass it on to receiving API Client. So my question is how do I reduce the data or get the data which is only necessary for the user. Sending that much data is the security issue.
I don't find any documentation or console controls to modify the same.
For example I only want:
"exp": 0000000000,
"at":  0000000000,
"username":"exampleUsername"

A: It sounds like you have a client that might be third party, or you trust less. You can setup a separate Cognito UserPool App Client for this application. Then write a Pre Token Generation Lambda to suppress token fields you do not want to expose to this client, and assign it to the correct UserPool App Client.
https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-token-generation.html
You probably already know this, but you cannot edit a token after it is issued without invalidating the token.


text:
Q: attach website username to paypal IPN product_id i have IPN data sending back the correct info, i have the product id and i also have a text box for user's to write in their in-game-name in on my website.
im stuggling to attach the username input with the IPN product_id. what i want it to do is when the user clicks the paypal button, it process's the transaction and if approved the username entered from the website and product_id get placed into a array or something that i can later put into my database
im quite new to php and html please bare with me

A: When you create a PayPal transaction, pass a variable named custom with the values you want to store as part of the transaction.
For old-style HTML integrations that use no API or JS, this is documented here: https://developer.paypal.com/docs/paypal-payments-standard/integration-guide/Appx-websitestandard-htmlvariables/#payment-transaction-variables

IPN is very old and clunky. Crrent PayPal integrations don't use IPN at all, but rather two routes on your server that call the PayPal API -- one for 'Create Order' and one for 'Capture Order', documented here: https://developer.paypal.com/docs/business/checkout/server-side-api-calls/#server-side-api-calls
When you do that capture call you get an immediate response of success/failure and can update your database/system accordingly. Thus there is no need to wait around for PayPal to send you an IPN notification.
Those two routes on your server should return JSON data (and only JSON data) when called. The approval flow to pair with them is https://developer.paypal.com/demo/checkout/#/pattern/server
You can add POST data values to your fetch request.


text:
Q: cannot start neo4j server using plugin I have created a 2 server plugins and packaged the jar file into var/lib/neo4j/plugins one by one. For one jar file I\m able to start server, but with another jar file I get following error:

Okt 26 13:01:05 gaurav-GB-BSi3-6100 neo4j[24787]:         at
  org.neo4j.kernel.impl.proc.ProcedureJarLoader$1.fetchNextOrNull(ProcedureJarLoader.java:146)
  Okt 26 13:01:05 gaurav-GB-BSi3-6100 neo4j[24787]:         at
  org.neo4j.kernel.impl.proc.ProcedureJarLoader$1.fetchNextOrNull(ProcedureJarLoader.java:118)
  Okt 26 13:01:05 gaurav-GB-BSi3-6100 neo4j[24787]:         at
  org.neo4j.collection.PrefetchingRawIterator.peek(PrefetchingRawIterator.java:50)
  Okt 26 13:01:05 gaurav-GB-BSi3-6100 neo4j[24787]:         at
  org.neo4j.collection.PrefetchingRawIterator.hasNext(PrefetchingRawIterator.java:36)
  Okt 26 13:01:05 gaurav-GB-BSi3-6100 neo4j[24787]:         at
  org.neo4j.kernel.impl.proc.ProcedureJarLoader.loadProcedures(ProcedureJarLoader.java:91)
  Okt 26 13:01:05 gaurav-GB-BSi3-6100 neo4j[24787]:         at
  org.neo4j.kernel.impl.proc.ProcedureJarLoader.loadProceduresFromDir(ProcedureJarLoader.java:82)
  Okt 26 13:01:05 gaurav-GB-BSi3-6100 neo4j[24787]:         at
  org.neo4j.kernel.impl.proc.Procedures.start(Procedures.java:275) Okt
  26 13:01:05 gaurav-GB-BSi3-6100 neo4j[24787]:         at
  org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:434)
  Okt 26 13:01:05 gaurav-GB-BSi3-6100 neo4j[24787]:         ... 11 more
  Okt 26 13:01:05 gaurav-GB-BSi3-6100 neo4j[24787]: 2017-10-26
  11:01:05.344+0000 INFO  Neo4j Server shutdown initiated by request

To create the jar file I'm using:
mvn clean package


text:
Q: How to send and listen message via telnet I have a custom TCP server on localhost and I want to test it via window telnet. When a message sent to my TCP server with specified format (e.g GO|CD1502| with special characters) then my server send back to client a response message (e.g OK or ERROR).
Now, I want to test my server via telnet client on window 11. These are steps I've done to sent message

*

*Open telnet

*Open connection: open 127.0.0.1 6565 (my tcp server listening ip and port)

*Using escape character (Ctrl + ]) to back command terminal

*Send message: send GO|CD1502|

*Checking server, message received and sent response message

-> How do I check response message from telnet terminal when stream listening message was escaped?


text:
Q: Domain [ Understanding ] issue when creating a Linux email server Ok, here goes my paradoxical question.
For about 1 year into my hobby-ish career, I used to buy my domains and a hosting package from Reseller Club. I purchased their " shared hosting " plan and with the help of the cPanel I was able to host and manage around 7 websites, emails, domain addons for me and my clients.
Now, this month I bought un-manged VPS hosting plan with root access, from another provider. Running on CentOs 6.5, with Nginx, PHP-FPM installed after some hustles, and Goggling I was able to have my sites working without any problem. The only confusing part so far is the e-mail problem. I have no idea how to solve the logical aspect of the problem.
Though, I was able to set up an email for one account using postfix, dovecot, and installed roundcube/squirrelmail and everything worked just fine.
The problem of creating multiple emails for multiple domain, for example, before I switched to VPS, I had 5 clients that had multiple emails like john@foo.com, nina@bar.net .... There does not seem easy way create such type of email, and integrate the backup. the first problem is how do I create multiple email account, without having one to conflict with the other?  I have understood that, each email account has it's own directory in the /home folder, but this means if someone from site1 creates an email called contact@site1.com and another client from different domain creates an email called contact@differentsite.net then there would be two folders called contact in home directory. This surely is impossible. Also, as of now, to avoid my website's environment getting messed up with my email environment, I have brought a second VPS. with just 512ram for email service only. I am thinking of installing arch linux since it is a lightweight OS. I would love a feedback on this one too.
Thanks.

A: Basically, you need to configure postfix correctly and set it up for dealing with multiple domain names and virtual aliases.
Have a look at /etc/postfix/main.cf, and search for the line virtual_alias_domains. If it isn't there, add it. The line should contain the domain names that will receive mails:
virtual_alias_domains = site1.com, differentsite.net

Then, add a line to point to the file which will contain your alias mappings:
virtual_alias_maps = hash:/etc/postfix/virtualmaps

Next, make the file (touch /etc/postfix/virtualmaps) and edit it with your text editor. Syntax is pretty straight forward:
contact@site1.com            john
contact@differentsite.net    nina

Save the file, do postmap /etc/postfix/virtualmaps and you should be ready to go.


text:
Q: How many different/unique $4$-letter arrangements are there of the letters in the word Mississauga? How many different/unique $4$-letter arrangements are there of the letters in the word Mississauga?
I'm thinking we need permutations? I already tried finding each letter and still don't get it... any help?
So far I've broken it off to:-
$M=1$
$I=2$
$S=4$
$A=2$
$U=1$
$G=1$
However, I don't really know what to do next.

A: M=1
I=2
S=4
A=2
U=1
G=1
Case 1: All 4 letters are same
There is only one arrangement for this.
Case 2: 3 letters are similar
The three letters must be S. The remaining letter can be chosen in ${5 \choose 1}$
 ways and these can be arranged in $\frac {4!}{3!}$ ways.  This makes a total of 20 arrangements.
Case 3: 2 pairs are similar
The two repeating letters can be chosen in ${3 \choose 2}$ ways and can be arranged in $\frac {4!}{{2!}{2!}}$. This equals 18 arrangements.
Case 4: 2 are similar
The repeating letters can be chosen in ${3 \choose 1}$  ways and the remaining two in ${5 \choose 2}$ ways. These can be arranged in $\frac {4!}{2!}$ ways. This equals 360 arrangements.
Case 5: All 4 are different
The 4 letters can be chosen in ${6 \choose 4}$ ways and can be arranged in $4!$ ways. This equals 360 ways.
Hence the total number of arrangements is $1+20+18+360+360=759$.

A: Here's a hint as to one way to do it. Break it up into mutually-distinct cases:

*

*All four letters are different.

*One letter appears twice; two letters appear once.

*Two letters appear twice.

*One letter appears three times; one letter appears once.

*One letter appears four times.

Can you take it from here?

A: The word Mississauga has the following multiplicity: $M(1\times), I(2 \times ), S(4\times), A(2 \times), G(1\times), U( 1 \times)$
You want a word with $4$ letters, so lets take for example $(M,I,S,A,G,U)$.
For a $4$-letter word you have a lot of combinations. Now you just have to write them down.
I'm going to do a few and let you do the rest.
For example if you have a $4$ letter word with one $M$ , one $I$, one $A$ and one $U$. You have $(1,1,0,1,0,1)$. For this you have $\frac{11!}{1!1!1!1!}$
If you take one $M$, two $I$ and one $S$  , you have $(1,2,1,0,0,0)$. For this you have $\frac{11!}{1!2!1!}$
You have to write all of combinations possible of $(M,I,S,A,G,U)$ with the sum value of $4$, where $M,I,S,A,G,U$ can vary up to their multiplicity respectively. In the end you sum up everything and get your result. However the word Missisauga has alot of combinations, so it might take some time.

A: Considering  letters in the order $M,I,S,A,G,U,$ the approach given by MathScientist  can be encapsulated in the formula
Coefficient of $x^4$ in $4!(1+x)(1+x+\frac{x^2}{2!})(1+x+\frac{x^2}2 + \frac{x^3}{3!} +\frac{x^4}{4!})(1+x+\frac{x^2}{2!})(1+x)(1+x)$
which, of course, can be condensed and ordered systematically  to
Coefficient of $x^4$ in $4!(1+x)^3(1+x + \frac{x^2}{2!})^2  (1+x+\frac{x^2}{2!} + \frac{x^3}{3!} + \frac {x^4}{4!})$


text:
Q: Enable and require SSL for certain actions in an MVC3 application I am busy setting up a protocol between my payments service provider and my site.  They use Immediate Payment Notification (IPN), where they contact a URL in my site when the payment is processed, sending me confirmation data.  I would like to secure this URL, and one or two others, using SSL.  The majority of actions don't require this, as no sensitive data is passed during normal operations, only payments, logins, and uploads.

A: Should be able to just add the [RequireHttps] annotation to the action:
[RequireHttps]
public ActionResult processOverSSL ()
{

}

As long as IIS is configured for SSL with a certificate, it should just redirect to https.


text:
Q: SPQuery cause me an error: "One or more field types are not installed properly the problem is a CAML query of SPQuery that throw an error: One or more field types are not installed properly
any help please:
it work perfect in U2U CAML
 source code is:
   sb.Append("<Where>");
    sb.Append("<Or>");
                            sb.Append("<And>");
                                sb.Append("<Eq><FieldRef Name='" +
  ConstVariables.valide_les_destinataires_encodé + "' /><Value
  Type='Boolean'>0</Value></Eq>");
                                sb.Append("<Eq><FieldRef Name='" +
  ConstVariables.envoyer_vers_directeur_encodé + "' /><Value
  Type='Boolean'>1</Value></Eq>");
                            sb.Append("</And>");

                            sb.Append("<Or>");
                                sb.Append("<And>");
                                    sb.Append("<And>");
                                        sb.Append("<Eq><FieldRef Name='" +
  ConstVariables.valide_les_destinataires_encodé + "' /><Value
  Type='Boolean'>1</Value></Eq>");
                                        sb.Append("<Eq><FieldRef Name='" +
   ConstVariables.envoyer_vers_directeur_encodé + "' /><Value
  Type='Boolean'>1</Value></Eq>");
                                    sb.Append("</And>");
                                    sb.Append("<And>");
                                        sb.Append("<Eq><FieldRef Name='" +
  ConstVariables.reponse_destinataires_encodé + "' /><Value Type='Boolean'>1</Value>
  </Eq>");
                                        sb.Append("<Eq><FieldRef Name='" +
   ConstVariables.fiche_distribution_prepare_encodé + "' /><Value
  Type='Boolean'>1</Value>
  </Eq>");
                                    sb.Append("</And>");
                                sb.Append("</And>");
                                sb.Append("<Eq><FieldRef Name='" +
  ConstVariables.valid_par_directeur_ca_encodé + "' /><Value
  Type='Boolean'>0</Value></Eq>");
                             sb.Append("</Or>");
                        sb.Append("</Or>");

                        sb.Append("</Where>");

   SPView vv = list.Views["Tous les documents"];
            SPQuery squery = new SPQuery();
            squery.Query = sb.ToString();

            vv.Query = squery.Query;
            vv.Update();

            list.Update();
            list.ParentWeb.Update();

   //the CAML query above is equivalent to this after i intercept it in debugging:

 <Where>
<Or>
    <And>
        <Eq><FieldRef Name='Valid_x00e9__x0020_les_x0020_destinataires'
   /><Value Type='Boolean'>0</Value></Eq>
        <Eq><FieldRef Name='Envoyer_x0020_vers_x0020_Directeur' /><Value
  Type='Boolean'>1</Value></Eq>
    </And>
    <Or>
        <And>
          <And>
               <Eq><FieldRef
  Name='Valid_x00e9__x0020_les_x0020_destinataires' /><Value
  Type='Boolean'>1</Value></Eq>
               <Eq><FieldRef Name='Envoyer_x0020_vers_x0020_Directeur'
 /><Value Type='Boolean'>1</Value></Eq>
          </And>
          <And>
               <Eq><FieldRef Name='R_x00e9_ponse_x0020_Destinataire'
   /><Value Type='Boolean'>1</Value></Eq>
               <Eq><FieldRef
  Name='Fiche_x0020_distribution_x0020_pr_x00e9_par_x00e9_e' /><Value
  Type='Boolean'>1</Value></Eq>
          </And>
        </And>
        <Eq><FieldRef Name='Valid_x00e9__x0020_par_x0020_directeur' />
   <Value Type='Boolean'>0</Value></Eq>
    </Or>
</Or>

  </Where>

A: Check that your CAML list query is not referencing inexistent fields in the primary content type and in the list itself. Remove  the fields or recreate them again.


text:
Q: Is javax.ejb still in used today? I am working on a project to build a stateless ejb calculator component and my very first error is that the javax.ejb package does not exist (even after I looked for and included the jar).
The thing is all solutions I am seeing online are old.....like from 2006, with the latest ones being 2013-2015. Which kinda makes it seem like an obsolete thing, and there's probably a better way of doing it. If so please advice me. I'm using the latest version of Apache Netbeans and JDK 15. Currently started the project with Java EE7(recommended in the tutorial I'm following) and GlassFish server.
Also I'm not sure if it all stems from the import error but when I try to add business logic, "Insert code " does not give me an "Add Business Method" option.

A: After much trial and error, finally adding the whole Java EE 7 API library worked. No more
javax.ejb package does not exist error and that has fixed the no Add Business Method issue
Would still appreciate help better methods of doing this (if they exist)


text:
Q: How to does rounding off binary number works? I am currently learning floating points and my question is:
if I have a number like 0.01 and I want to round it off then I have 0.1
but if I have a number , 0.000000001, does that mean I have 0.1 as well or 0.0?


text:
Q: How to convert Eclipse template file to IntelliJ template file How can I convert Eclipse template file to IntelliJ template file. I do not want to add plugin to use the Eclipse file. I want to convert it.

A: Though not strictly respecting your question (no plugin), the built-in plugin Eclipse integration of IDEA 13 can import Eclipse templates quite accurately:
http://blog.jetbrains.com/idea/2014/01/intellij-idea-13-importing-code-formatter-settings-from-eclipse/
As stated in that post, the result cannot be 100% accurate as IDEA does not support all of the template options present in Eclipse (and the opposite might be true too).


text:
Q: Groupby on condition and calculate sum of subgroups Here is my data:
import numpy as np
import pandas as pd
z = pd.DataFrame({'a':[1,1,1,2,2,3,3],'b':[3,4,5,6,7,8,9], 'c':[10,11,12,13,14,15,16]})
z

    a   b   c
0   1   3   10
1   1   4   11
2   1   5   12
3   2   6   13
4   2   7   14
5   3   8   15
6   3   9   16

Question:
How can I do calculation on different element of each subgroup? For example, for each group, I want to extract any element in column 'c' which its corresponding element in column 'b' is between 4 and 9, and sum them all.
Here is the code I wrote: (It runs but I cannot get the correct result)
gbz = z.groupby('a')
# For displaying the groups:
gbz.apply(lambda x: print(x))

list = []

def f(x):
    list_new = []
    for row in range(0,len(x)):
        if (x.iloc[row,0] > 4 and x.iloc[row,0] < 9):
            list_new.append(x.iloc[row,1])
    list.append(sum(list_new))

results = gbz.apply(f)

The output result should be something like this:
    a   c
0   1   12
1   2   27
2   3   15

A: It might just be easiest to change the order of operations, and filter against your criteria first - it does not change after the groupby.
z.query('4 < b < 9').groupby('a', as_index=False).c.sum()

which yields
   a   c
0  1  12
1  2  27
2  3  15

A: Use
In [2379]: z[z.b.between(4, 9, inclusive=False)].groupby('a', as_index=False).c.sum()
Out[2379]:
   a   c
0  1  12
1  2  27
2  3  15

Or
In [2384]: z[(4 < z.b) & (z.b < 9)].groupby('a', as_index=False).c.sum()
Out[2384]:
   a   c
0  1  12
1  2  27
2  3  15

A: You could also groupby first.
z = z.groupby('a').apply(lambda x: x.loc[x['b']\
           .between(4, 9, inclusive=False), 'c'].sum()).reset_index(name='c')
z

   a   c
0  1  12
1  2  27
2  3  15

A: Or you can use
z.groupby('a').apply(lambda x : sum(x.loc[(x['b']>4)&(x['b']<9),'c']))\
             .reset_index(name='c')
Out[775]:
   a   c
0  1  12
1  2  27
2  3  15


text:
Q: solr dataimport handler jndi websphere I am trying to use jndiName attribute in db-data-config.xml. This works great in tomcat. However having issues in websphere.
Following exception is thrown
"Make sure that a J2EE application does not execute JNDI operations on "java:" names within static code blocks or in threads created by that J2EE application.  Such code does not necessarily run on the thread of a server application request and therefore is not supported by JNDI operations on "java:" names. [Root exception is javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:"."
It seems like websphere has issues accessing jndi resource from Static code. Has anyone experienced this ?
 DataImporter  E org.apache.solr.common.SolrException log Full Import failed:org.apache.solr.handler.dataimport.DataImportHandlerException: Unable to execute query: <REMOVE SQL from here>
    at org.apache.solr.handler.dataimport.DataImportHandlerException.wrapAndThrow(DataImportHandlerException.java:72)
    at org.apache.solr.handler.dataimport.JdbcDataSource$ResultSetIterator.<init>(JdbcDataSource.java:253)
    at org.apache.solr.handler.dataimport.JdbcDataSource.getData(JdbcDataSource.java:210)
    at org.apache.solr.handler.dataimport.JdbcDataSource.getData(JdbcDataSource.java:39)
    at org.apache.solr.handler.dataimport.SqlEntityProcessor.initQuery(SqlEntityProcessor.java:59)
    at org.apache.solr.handler.dataimport.SqlEntityProcessor.nextRow(SqlEntityProcessor.java:73)
    at org.apache.solr.handler.dataimport.EntityProcessorWrapper.nextRow(EntityProcessorWrapper.java:238)
    at org.apache.solr.handler.dataimport.DocBuilder.buildDocument(DocBuilder.java:596)
    at org.apache.solr.handler.dataimport.DocBuilder.doFullDump(DocBuilder.java:268)
    at org.apache.solr.handler.dataimport.DocBuilder.execute(DocBuilder.java:187)
    at org.apache.solr.handler.dataimport.DataImporter.doFullImport(DataImporter.java:359)
    at org.apache.solr.handler.dataimport.DataImporter.runCmd(DataImporter.java:427)
    at org.apache.solr.handler.dataimport.DataImporter$1.run(DataImporter.java:408)
Caused by: javax.naming.ConfigurationException: A JNDI operation on a "java:" name cannot be completed because the server runtime is not able to associate the operation's thread with any J2EE application component.  This condition can occur when the JNDI client using the "java:" name is not executed on the thread of a server application request.  Make sure that a J2EE application does not execute JNDI operations on "java:" names within static code blocks or in threads created by that J2EE application.  Such code does not necessarily run on the thread of a server application request and therefore is not supported by JNDI operations on "java:" names. [Root exception is javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:".]
    at com.ibm.ws.naming.java.javaURLContextImpl.throwConfigurationExceptionWithDefaultJavaNS(javaURLContextImpl.java:428)
    at com.ibm.ws.naming.java.javaURLContextImpl.lookup(javaURLContextImpl.java:399)
    at com.ibm.ws.naming.java.javaURLContextRoot.lookup(javaURLContextRoot.java:214)
    at com.ibm.ws.naming.java.javaURLContextRoot.lookup(javaURLContextRoot.java:154)
    at javax.naming.InitialContext.lookup(InitialContext.java:436)
    at org.apache.solr.handler.dataimport.JdbcDataSource$1.call(JdbcDataSource.java:140)
    at org.apache.solr.handler.dataimport.JdbcDataSource$1.call(JdbcDataSource.java:128)
    at org.apache.solr.handler.dataimport.JdbcDataSource.getConnection(JdbcDataSource.java:363)
    at org.apache.solr.handler.dataimport.JdbcDataSource.access$200(JdbcDataSource.java:39)
    at org.apache.solr.handler.dataimport.JdbcDataSource$ResultSetIterator.<init>(JdbcDataSource.java:240)
    ... 11 more
Caused by: javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:".
    at com.ibm.ws.naming.ipbase.NameSpace.getParentCtxInternal(NameSpace.java:1837)
    at com.ibm.ws.naming.ipbase.NameSpace.lookupInternal(NameSpace.java:1166)
    at com.ibm.ws.naming.ipbase.NameSpace.lookup(NameSpace.java:1095)
    at com.ibm.ws.naming.urlbase.UrlContextImpl.lookup(UrlContextImpl.java:1233)
    at com.ibm.ws.naming.java.javaURLContextImpl.lookup(javaURLContextImpl.java:395)
    ... 19 more

A: Solr is using unmanaged threads here and is doing a JNDI lookup in the java: namespace in one of these threads. That is not supported in WebSphere because WebSphere identifies the java: namespace based on the thread performing the lookup. Tomcat does this based on the thread context class loader, which explains the difference in behavior. Note that unmanaged threads are not allowed by the J2EE specs, so that WebSphere's behavior is actually standards compliant.


text:
Q: Fancy Box and Booking Calendar - JQuery conflict in Wordpress I updated the Booking Calendar plugin on my WP site. It wasn't working due to an error with a script, and I fixed it using this solution: http://wpbookingcalendar.com/faq/loading-jquery-twice/
Problem is, editing out that line makes FancyBox not work anymore. I have updated FancyBox and JQuery Files, but still have the same problem: I have to choose between the Booking Calendar or the FancyBox to work, editing in or out that call to Jquery.
This is how the header of the page looks now. Is there anyway I can make both things work at the same time?
Thanks!
    <?php if ( is_page('Booking Calendar Name') ) { ?><?php wp_head(); ?><?php } ?>

<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />
<!-- <script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery-1.8.3.min.js"></script> -->

<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery.flow.1.2.min.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery.form.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/init_form.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/init.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/easySlider1.5.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/dropdowns.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/fancybox/jquery.mousewheel-3.0.6.pack.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/fancybox/jquery.fancybox.js"></script>
<link rel="stylesheet" type="text/css" href="<?php bloginfo('template_directory'); ?>/fancybox/jquery.fancybox.css" media="screen" />

A: Without being able to view the source code on your site, it's hard to tell but what @JFK points out makes me think that there is no jQuery on your site unless you're on the page that utilizes the Calendar plugin. In either case, I would try de-registering the script and loading the one you want via your functions.php like this:
wp_deregister_script('jquery');
    if(!is_admin()) {
    wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js');
    wp_enqueue_script('jquery');
}

You can remove the jQuery that is in your header since it will be loaded here instead.


text:
Q: Can I use Microsoft Office 2010: Primary Interop Assemblies to convert word,excel to PDF Can I use Microsoft Office 2010: Primary Interop Assemblies to convert word, excel to PDF? How easy is it? Any C# example?

A: You can't use the interop assemblies without having office installed as well. Once office is installed it works, but to make it reliable and scalable a lot of work is required, but it is not impossible.

A: Yes, you can use Document.SaveAs to save as a PDF.
It is un-supported and tricky to do this in a non-interactive (or server side) manner.


text:
Q: C++ how to check if each row and column of 3x3 matrix contains only different numbers In my Hitori game, the player removes numbers from the gameboard.
The game is won if all rows and columns have only different numbers.
In line 43, I would need to make some check function so that the board is checked after every removal, but I dont know how to do that. Should I perhaps make several for-loops?
#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std; using Board = std::vector<vector<int>>;
const unsigned char EMPTY = ' ';

void initBoard(Board& board) {

string input = "1 1 3 1 2 2 2 2 3";

istringstream is { input };

    for (auto& row : board)
    {
        for(auto& column : row)
        {
        is >> column;
        }
    }
}

void printBoard(const Board& board) {

    for(unsigned int row = 0; row < 3; ++row)
    {
       cout << "| " << row + 1 << " | ";
        for(unsigned int column = 0; column < 3; ++column)
        {
            if(board.at(row).at(column) == 0)
            {
                cout << EMPTY << " ";
            }
            else
            {
                cout << board.at(row).at(column) << " ";
            }
        }
       cout << "|" << endl;
    }
    // CHECK IF EACH ROW AND COLUMN CONTAIN THE SAME NUMBER SEVERAL TIMES
    // IF NOT -> THE GAME HAS BEEN WON

}

void updateBoard(Board& board) {

    int x, y;

    while (true) {
        cout << "Enter coordinates (x, y): ";
        cin >> x;
        cin >> y;

            board.at(y-1).at(x-1) = 0;
            printBoard(board);
}
}

int main()
{
    Board board(3, vector<int>(3)); // board is vector with 3 rows and 3 columns
    initBoard(board);
    printBoard(board);
    updateBoard(board);
}

A: You need something that can be used to count how often a value occurs in a row or column. Because your values are nonnegative integers, you can use them as the indices of an array or vector, as suggested by Pete Becker. Another way is to use them as the keys of an associative container like std::unordered_map.
My preference would be to put these checks in separate function(s) that you call from within the game loop, so that it can terminate when a win is detected. Here is an example function that checks the columns of the board, returning true if each has unique values:
#include <algorithm>
#include <unordered_map>

using RepCount = std::unordered_map<int, int>;

bool allUnique(RepCount const& reps)
{
    return std::ranges::all_of(reps, [](auto& pair) {
        auto [value, count] = pair;
        return value == 0 || value == EMPTY || count == 1;
    });
}

bool checkColumns(Board const& board)
{
    for (unsigned col = 0; col < 3; ++col) {
        RepCount reps;
        for (auto& row : board)
            ++reps[row[col]];
        if (!allUnique(reps))
            return false;
    }
    return true;
}

You can invert this loop to perform the same check for each row.


text:
Q: How do I get a specific Youtube Stream ID in Android Studio using the YoutubeAPI? How would one go about getting a current Youtube Live Stream video ID for youTubePlayer.LoadVideo to run correctly?
 youTubePlayer.loadVideo("8XiqrERZo_8");

I want to be able to to receive a Youtubers Live Stream ID without having to hard code in the current video ID every time. If another way is easier to implement I'm happy to any suggestions!
Here is what I have currently in my MainActivity file:
public class MainActivity extends YouTubeBaseActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    YouTubePlayerView youTubePlayerView;
    YouTubePlayer.OnInitializedListener onInitializedListener;

    String KEY = "{GOOGLE_API_KEY}";

    youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubePlayer);

    onInitializedListener = new YouTubePlayer.OnInitializedListener() {
    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
        youTubePlayer.loadVideo("8XiqrERZo_8");
    }

    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {

    }
    };

     youTubePlayerView.initialize(KEY,onInitializedListener);

}
}

And in my xml class all I'm using is:
    <com.google.android.youtube.player.YouTubePlayerView
         android:id="@+id/youtubePlayer"
         android:layout_width="match_parent"
         android:layout_height="match_parent">

    </com.google.android.youtube.player.YouTubePlayerView>


text:
Q: Active Directory RSAT not showing under Windows features I have Windows 10 Pro installed as a virtual Machine in Esxi box , I wanted to configure AD in the same machine to authenticate user logins from other machines.
After installing 'RSAT Active Directory Domain Services and Lightweight Directory Service Tools ' , I am unable to get its display under Windows features as I want to turn ON that particular Windows feature.enter image description here


text:
Q: Why doesn't cornerRadius.width/2 give me a perfect circle? Im trying to create a circle from a squared view using this code:
self.situationerCircle.layer.cornerRadius = self.situationerCircle.frame.size.width/2.0
situationerCircle.clipsToBounds = true

But I still don't get a perfect round circle. I'm pretty certain it has something to do with my constraints as I did a test circle using these constraints:

with this code:
testc.layer.cornerRadius = self.testc.frame.size.width/2
testc.clipsToBounds = true

This works perfectly. The constraints for the bad circle however look like this:

The reason is because I want to make it grow in size in proportion to its container while keeping the same 1:1 ratio. But the result is a semi circle, that have subtle but visible edges. Any ideas how to solve this?

A: If you trying to execute this codes in viewDidLoad() it might be happen. viewDidAppear() will work but if you are try inside the cell there is a method called awakeFromNib() where you define your objects. Add it and replace your codes there. And i agree with Larme answer you can call layoutIfNeeded() to refresh view and force perfect circle i think.


text:
Q: numpy.loadtxt does not read file with complex numbers I am trying to read a file with complex numbers in the form :
data.dat

1.5795219122457646E-11-3.852906516379872E-15i   -3.5949335665378405E-12-1.626143709108086E-15i
-6.720365121161621E-15-5.377186331212649E-17i   -3.736251476362349E-15-3.0190920417856674E-17i

I use the following code to read the file :
import numpy as np

c_complex = np.loadtxt('data.dat', delimiter='\t', dtype=np.complex128)

But it gives me the following error :
TypeError: complex() argument must be a string or a number, not 'bytes'

What could I do to solve this problem ?
Thank you very much for your help

A: This seems to have been a bug in older versions of numpy (Issue). Either update your numpy to the latest version of their github repository or use the function numpy.genfromtxt().
c.complex = np.genfromtxt('data.dat', delimiter='\t', dtype=np.complex128)


text:
Q: Highlight entire text inside text field with single click I want to be able to just click inside a text field, so that it highlights all the text inside it (and possibly also copies it). Although, I'm satisfied with just getting it highlighted if that's possible with HTML only. Many people are using NoScript and such nowadays, so I'm trying to stay away from JavaScript etc.
TinyPic is one example which uses this little 'feature'.
Thanks for your help.

A: I'm pretty sure you need to use some javascript; no matter how trivial it might be.
For example; this does what you're asking:
<input type="text" value="Click Me to Select Text" onclick="this.select()">

A: in the head section add this script:
    <script language="JavaScript">
    function highlight(field) {
    field.focus();
    field.select();}</script>

And then for each field that you want to select all the text in when clicked, add this:
onClick='highlight(this);

I hope it works, try it by the way


text:
Q: Display Rows that Have a 0 count I'm trying to accumulate a Year to Date total of the number of incident events in a SQL Server shipping system, for display in a graph.
What I have at the moment:
SELECT EventType.Name AS [Incident Name], COUNT(Event.ID) AS [Occurrence]
FROM  Event
INNER JOIN
        PortEvent ON Event.PortEventID = PortEvent.ID
INNER JOIN
        EventType ON PortEvent.EventID = Event.ID

WHERE Event.IsIncident = 1 and Event.Date BETWEEN (Start of Year & Now)
GROUP BY Event.Name

What this returns;
Incident Name       Occurrence

Incident 1              1
Incident 3              4
Incident 4              7

What I want:
Incident Name       Occurrence

Incident 1              1
Incident 2              0
Incident 3              4
Incident 4              7
Incident 5              0

Is there a way to do this simply? I have seen a few examples on SO, but only for adjacent tables.
Thanks

A: You have problem in you EventType ON PortEvent.EventID = Event.ID condition.The query below must solve your issue.
SELECT ET.Name AS [Incident Name], COUNT(E.ID) AS [Occurrence]
FROM EventType ET
  LEFT JOIN PortEvent PE
    ON ET.ID = PE.EventID
  LEFT JOIN Event E
    ON PE.EventID = E.ID
      AND E.IsIncident = 1
      AND E.Date BETWEEN ([Start of Year] AND Now)
GROUP BY ET.Name

UPDATE
If you want to include in result incidents only you can try this:
    ON PE.EventID = E.ID
      AND E.Date BETWEEN ([Start of Year] AND Now)
   WHERE E.IsIncident = 1
GROUP BY ET.Name

A: Simply using left joins is insufficient. You need to re-order your query so all event types are in the left-most recordset (that's how I visualize it anyway). Additionally, you need to get rid of the where clause and add it to the event table's join because, if not, it might as well be an inner join.
SELECT
    EventType.Name AS [Incident Name], COUNT(Event.ID) AS [Occurrence]
FROM  EventType
LEFT JOIN PortEvent ON Event.PortEventID = PortEvent.ID
LEFT JOIN Event ON PortEvent.EventID = Event.ID and Event.IsIncident = 1 and Event.Date BETWEEN (Start of Year & Now)
GROUP BY Event.Name

A: (CASE WHEN COUNT(Event.ID) = 0 THEN 0 ELSE COUNT(Event.ID) END) AS [Occurrence]

A: Change the INNER JOIN of the EventType to a Left Join. This will return the Event and zero or more of the EventType
SELECT EventType.Name AS [Incident Name], COUNT(Event.ID) AS [Occurrence]
FROM  Event
LEFT JOIN
        PortEvent ON Event.PortEventID = PortEvent.ID
LEFT JOIN
        EventType ON PortEvent.EventID = Event.ID

WHERE Event.IsIncident = 1 and Event.Date BETWEEN (Start of Year & Now)
GROUP BY Event.Name